-
Notifications
You must be signed in to change notification settings - Fork 37
/
compute_statistics_dataset.py
361 lines (285 loc) · 10.5 KB
/
compute_statistics_dataset.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
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
import math
from typing import Union
import numpy as np
import xarray as xr
import xcdat as xc
def da_to_ds(
d: Union[xr.Dataset, xr.DataArray], var: str = "variable"
):
if isinstance(d, xr.Dataset):
return d.copy()
elif isinstance(d, xr.DataArray):
return d.to_dataset(name=var).bounds.add_missing_bounds().copy()
else:
raise TypeError(
"Input must be an instance of either xarrary.DataArray or xarrary.Dataset"
)
def annual_mean(dm, do, var="variable"):
"""Computes ANNUAL MEAN"""
if dm is None and do is None: # just want the doc
return {
"Name": "Annual Mean",
"Abstract": "Compute Annual Mean",
"Contact": "[email protected]",
"Comments": "Assumes input are 12 months climatology",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
dm_am = dm.temporal.average(var)
do_am = do.temporal.average(var)
return dm_am, do_am # DataSets
def seasonal_mean(d, season, var="variable"):
"""Computes SEASONAL MEAN"""
if d is None and season is None: # just want the doc
return {
"Name": "Seasonal Mean",
"Abstract": "Compute Seasonal Mean",
"Contact": "[email protected]",
"Comments": "Assumes input are 12 months climatology",
}
mo_wts = [31, 31, 28.25, 31, 30, 31, 30, 31, 31, 30, 31, 30]
if season == "djf":
indx = [11, 0, 1]
if season == "mam":
indx = [2, 3, 4]
if season == "jja":
indx = [5, 6, 7]
if season == "son":
indx = [8, 9, 10]
season_num_days = mo_wts[indx[0]] + mo_wts[indx[1]] + mo_wts[indx[2]]
d_season = (
d.isel(time=indx[0])[var] * mo_wts[indx[0]]
+ d.isel(time=indx[1])[var] * mo_wts[indx[1]]
+ d.isel(time=indx[2])[var] * mo_wts[indx[2]]
) / season_num_days
ds_new = d.isel(time=0).copy(deep=True)
ds_new[var] = d_season
return ds_new
# Metrics calculations
def bias_xy(dm, do, var="variable", weights=None):
"""Computes bias"""
if dm is None and do is None: # just want the doc
return {
"Name": "Bias",
"Abstract": "Compute Full Average of Model - Observation",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
dif = dm[var] - do[var]
if weights is None:
weights = dm.spatial.get_weights(axis=["X", "Y"])
# stat = float(dif.weighted(weights).mean(("lon", "lat")))
stat = mean_xy(dif, weights=weights)
return float(stat)
def bias_xyt(dm, do, var="variable"):
"""Computes bias"""
if dm is None and do is None: # just want the doc
return {
"Name": "Bias",
"Abstract": "Compute Full Average of Model - Observation",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
ds = dm.copy(deep=True)
ds["dif"] = dm[var] - do[var]
stat = (
ds.spatial.average("dif", axis=["X", "Y"]).temporal.average("dif")["dif"].values
)
return float(stat)
def cor_xy(dm, do, var="variable", weights=None):
"""Computes correlation"""
if dm is None and do is None: # just want the doc
return {
"Name": "Spatial Correlation",
"Abstract": "Compute Spatial Correlation",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
if weights is None:
weights = dm.spatial.get_weights(axis=["X", "Y"])
dm_avg = dm.spatial.average(var, axis=["X", "Y"], weights=weights)[var].values
do_avg = do.spatial.average(var, axis=["X", "Y"], weights=weights)[var].values
covariance = (
((dm[var] - dm_avg) * (do[var] - do_avg))
.weighted(weights)
.mean(dim=["lon", "lat"])
.values
)
std_dm = std_xy(dm, var)
std_do = std_xy(do, var)
stat = covariance / (std_dm * std_do)
return float(stat)
def mean_xy(d, var="variable", weights=None):
"""Computes bias"""
if d is None: # just want the doc
return {
"Name": "Mean",
"Abstract": "Area Mean (area weighted)",
"Contact": "[email protected]",
}
d = da_to_ds(d, var)
lat_key = xc.axis.get_dim_keys(d, axis="Y")
lon_key = xc.axis.get_dim_keys(d, axis="X")
if weights is None:
weights = d.spatial.get_weights(axis=["X", "Y"])
stat = d[var].weighted(weights).mean((lat_key, lon_key))
return float(stat)
def meanabs_xy(dm, do, var="variable", weights=None):
"""Computes Mean Absolute Error"""
if dm is None and do is None: # just want the doc
return {
"Name": "Mean Absolute Error",
"Abstract": "Compute Full Average of "
+ "Absolute Difference Between Model And Observation",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
if weights is None:
weights = dm.spatial.get_weights(axis=["X", "Y"])
dif = abs(dm[var] - do[var])
stat = dif.weighted(weights).mean(("lon", "lat"))
return float(stat)
def meanabs_xyt(dm, do, var="variable"):
"""Computes Mean Absolute Error"""
if dm is None and do is None: # just want the doc
return {
"Name": "Mean Absolute Error",
"Abstract": "Compute Full Average of "
+ "Absolute Difference Between Model And Observation",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
ds = dm.copy(deep=True)
ds["absdif"] = abs(dm[var] - do[var])
stat = (
ds.spatial.average("absdif", axis=["X", "Y"])
.temporal.average("absdif")["absdif"]
.values
)
return float(stat)
def rms_0(dm, do, var="variable", weighted=True):
"""Computes rms over first axis -- compare two zonal mean fields"""
if dm is None and do is None: # just want the doc
return {
"Name": "Root Mean Square over First Axis",
"Abstract": "Compute Root Mean Square over the first axis",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
dif_square = (dm[var] - do[var]) ** 2
if weighted:
weights = dm.spatial.get_weights(axis=["Y"])
stat = math.sqrt(dif_square.weighted(weights).mean(("lat")))
else:
stat = math.sqrt(dif_square.mean(("lat")))
return float(stat)
def rms_xy(dm, do, var="variable", weights=None):
"""Computes rms"""
if dm is None and do is None: # just want the doc
return {
"Name": "Spatial Root Mean Square",
"Abstract": "Compute Spatial Root Mean Square",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
dif_square = (dm[var] - do[var]) ** 2
if weights is None:
weights = dm.spatial.get_weights(axis=["X", "Y"])
stat = math.sqrt(mean_xy(dif_square, var=var, weights=weights))
return float(stat)
def rms_xyt(dm, do, var="variable"):
"""Computes rms"""
if dm is None and do is None: # just want the doc
return {
"Name": "Spatio-Temporal Root Mean Square",
"Abstract": "Compute Spatial and Temporal Root Mean Square",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
ds = dm.copy(deep=True)
ds["diff_square"] = (dm[var] - do[var]) ** 2
ds["diff_square_sqrt"] = np.sqrt(
ds.spatial.average("diff_square", axis=["X", "Y"])["diff_square"]
)
stat = ds.temporal.average("diff_square_sqrt")["diff_square_sqrt"].values
return float(stat)
def rmsc_xy(dm, do, var="variable", weights=None, NormalizeByOwnSTDV=False):
"""Computes centered rms"""
if dm is None and do is None: # just want the doc
return {
"Name": "Spatial Root Mean Square",
"Abstract": "Compute Centered Spatial Root Mean Square",
"Contact": "[email protected]",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
if weights is None:
weights = dm.spatial.get_weights(axis=["X", "Y"])
if NormalizeByOwnSTDV:
dm_tmp = dm[var] / std_xy(dm[var], var=var, weights=weights)
do_tmp = do[var] / std_xy(do[var], var=var, weights=weights)
else:
dm_tmp = dm[var].copy()
do_tmp = do[var].copy()
# Remove mean
dm_anomaly = dm_tmp - mean_xy(dm_tmp, var=var, weights=weights)
do_anomaly = do_tmp - mean_xy(do_tmp, var=var, weights=weights)
stat = rms_xy(dm_anomaly, do_anomaly, var=var, weights=weights)
return float(stat)
def std_xy(ds, var="variable", weights=None):
"""Computes std"""
if ds is None: # just want the doc
return {
"Name": "Spatial Standard Deviation",
"Abstract": "Compute Spatial Standard Deviation",
"Contact": "[email protected]",
}
ds = da_to_ds(ds, var)
if weights is None:
weights = ds.spatial.get_weights(axis=["X", "Y"])
lat_key = xc.axis.get_dim_keys(ds, axis="Y")
lon_key = xc.axis.get_dim_keys(ds, axis="X")
average = float(ds[var].weighted(weights).mean((lat_key, lon_key)))
anomaly = (ds[var] - average) ** 2
variance = float(anomaly.weighted(weights).mean((lat_key, lon_key)))
std = math.sqrt(variance)
return float(std)
def std_xyt(d, var="variable"):
"""Computes std"""
if d is None: # just want the doc
return {
"Name": "Spatial-temporal Standard Deviation",
"Abstract": "Compute Space-Time Standard Deviation",
"Contact": "[email protected]",
}
ds = d.copy(deep=True)
ds = da_to_ds(ds, var)
average = d.spatial.average(var, axis=["X", "Y"]).temporal.average(var)[var]
ds["anomaly"] = (d[var] - average) ** 2
variance = (
ds.spatial.average("anomaly").temporal.average("anomaly")["anomaly"].values
)
std = math.sqrt(variance)
return std
def zonal_mean(dm, do, var="variable"):
"""Computes ZONAL MEAN assumes rectilinear/regular grid"""
if dm is None and do is None: # just want the doc
return {
"Name": "Zonal Mean",
"Abstract": "Compute Zonal Mean",
"Contact": "[email protected]",
"Comments": "",
}
dm = da_to_ds(dm, var)
do = da_to_ds(do, var)
dm_zm = dm.spatial.average(var, axis=["X"])
do_zm = do.spatial.average(var, axis=["X"])
return dm_zm, do_zm # DataSets