-
Notifications
You must be signed in to change notification settings - Fork 3
/
warming_level.py
346 lines (282 loc) · 10.4 KB
/
warming_level.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
from .datalist import concat_xarray_with_metadata, select_by_metadata
def calc_year_of_warming_level(anomalies, warming_level, n_years=20):
"""calculate the period when a certain global warming level is reached
Parameters
----------
anomalies : xr.DataArray
Global mean temperature anomalies.
warming_level : float
Global warming level
n_years : int, default: 20
Length of period over which global warming level must be reached. Currently
restricted to even number of years.
Returns
-------
beg: int
Start year of the period. None if warming level is not exceeded.
end: int
End year of the period. None if warming level is not exceeded.
central_year: int
central year of the period. None if warming level is not exceeded.
"""
# calculate the start and end year of period of first exceedance
if not isinstance(n_years, int) or n_years < 1:
raise ValueError(f"n_years must be a positive integer, got {n_years}")
if n_years % 2 != 0: # odd
beg_offset = end_offset = (n_years - 1) // 2
else: # even
beg_offset = n_years // 2
end_offset = n_years // 2 - 1
anomalies = anomalies.rolling(year=n_years, center=True).mean()
# find years warmer than 'warming_level'
sel = anomalies - warming_level > 0.0
# if no warmer year is found, return
if not sel.any():
return None, None, None
# find index of central year
idx = sel.argmax().values
central_year = anomalies.isel(year=idx).year.values
beg = int(central_year - beg_offset)
end = int(central_year + end_offset)
return beg, end, central_year
def at_warming_level(
tas_list,
index_list,
warming_level,
reduce="mean",
select_by=("model", "exp", "ens"),
skipna=None,
as_datalist=False,
n_years=20,
**kwargs,
):
"""compute value of index at one warming level
Parameters
----------
tas_list : DataList
List of (ds, metadata) pairs containing annual mean global mean temperature data
index_list : DataList
List of (ds, metadata) pairs containing annual data of the index.
warming_level : float
warming level at which to assess the index
reduce : str or None, default: "mean"
How to compute the average over the warming level period. If None the individual
years are returned.
select_by : list of str, optional
Conditions to align tas_list and index_list.
skipna : bool, default: None
If True, skip missing values (as marked by NaN).
as_datalist : bool, default: False
If True returns data as DataList else as xr.DataArray.
n_years : int, default: 20
Length of period over which global warming level must be reached. Currently
restricted to even number of years.
**kwargs : dict
Additional keyword arguments passed on to the average function.
Returns
-------
out : xr.DataArray or DataList
Data at the given warming level. Output type depends on ``as_datalist``.
"""
out = list()
# loop through all global mean temperatures
for tas, meta in tas_list:
attributes = {key: meta[key] for key in select_by}
# try to find the index
index = select_by_metadata(index_list, **attributes)
# make sure only one dataset is found in index_list
if len(index) > 1:
raise ValueError("Found more than one dataset:\n", meta)
# an index was found for this tas dataset
if index:
# determine year when the warming was first reached
beg, end, center = calc_year_of_warming_level(
tas.tas, warming_level, n_years=n_years
)
if beg:
ds_idx = index[0][0]
meta_idx = index[0][1]
# get the Dataarray
da_idx = ds_idx[meta_idx["varn"]]
idx = da_idx.sel(year=slice(beg, end))
if reduce is not None:
# calculate mean
idx = getattr(idx, reduce)("year", skipna=skipna, **kwargs)
else:
# drop year to enable concatenating
idx = idx.drop_vars("year")
out.append([idx, meta_idx])
if not out:
return []
if as_datalist:
return out
return concat_xarray_with_metadata(out)
def at_warming_levels_list(
tas_list,
index_list,
warming_levels,
reduce="mean",
select_by=("model", "exp", "ens"),
factor=None,
skipna=None,
as_datalist=False,
n_years=20,
):
"""compute value of index at several warming levels, returned in a list
Parameters
----------
tas_list : DataList
List of (ds, metadata) pairs containing annual mean global mean temperature data
index_list : DataList
List of (ds, metadata) pairs containing annual data of the index.
warming_levels : iterable of float
warming levels at which to assess the index
reduce : str or None, default: "mean"
How to compute the average over the warming level period. If None the individual
years are returned.
select_by : list of str, optional
Conditions to align tas_list and index_list.
factor : float, default: None
If givem multiplies the data in index_list with this factor.
skipna : bool, default: None
If True, skip missing values (as marked by NaN).
as_datalist, bool, default : False
If True returns data as DataList else as xr.DataArray.
n_years : int, default: 20
Length of period over which global warming level must be reached. Currently
restricted to even number of years.
Returns
-------
out : list of xr.DataArray or list DataList
Data at the given warming levels. Output type depends on ``as_datalist``.
"""
out = list()
for warming_level in warming_levels:
res = at_warming_level(
tas_list,
index_list,
warming_level,
reduce=reduce,
select_by=select_by,
skipna=skipna,
as_datalist=as_datalist,
n_years=n_years,
)
if factor is not None:
if as_datalist:
raise ValueError("Cannot set `factor` and `as_datalist`")
res *= factor
out.append(res)
return out
def at_warming_levels_dict(
tas_list,
index_list,
warming_levels,
reduce="mean",
select_by=("model", "exp", "ens"),
factor=None,
skipna=None,
as_datalist=False,
n_years=20,
**kwargs,
):
"""compute value of index at several warming levels, returned in a dict
Parameters
----------
tas_list : DataList
List of (ds, metadata) pairs containing annual mean global mean temperature data
index_list : DataList
List of (ds, metadata) pairs containing annual data of the index.
warming_levels : iterable of float
warming levels at which to assess the index
reduce : str or None, default: "mean"
How to compute the average over the warming level period. If None the individual
years are returned.
select_by : list of str, optional
Conditions to align tas_list and index_list.
factor : float, default: None
If givem multiplies the data in index_list with this factor.
skipna : bool, default: None
If True, skip missing values (as marked by NaN).
as_datalist : bool, default: False
If True returns data as DataList else as xr.DataArray.
n_years : int, default: 20
Length of period over which global warming level must be reached. Currently
restricted to even number of years.
**kwargs : dict
Additional keyword arguments passed on to the average function.
Returns
-------
out : dict of xr.DataArray or dict of DataList
Data at the given warming levels. The given warming_levels are the dict's keys.
Output type depends on ``as_datalist``.
"""
out = dict()
for warming_level in warming_levels:
res = at_warming_level(
tas_list,
index_list,
warming_level,
reduce=reduce,
select_by=select_by,
skipna=skipna,
as_datalist=as_datalist,
n_years=n_years,
**kwargs,
)
if factor is not None:
if as_datalist:
raise ValueError("That does not work")
res *= factor
out[str(warming_level)] = res
return out
# def calc_anomaly_wrt_warming_level(
# tas_list,
# index_list,
# warming_level,
# how="absolute",
# skipna=None,
# select_by=("model", "exp", "ens"),
# ):
# """calc anomaly of dataset w.r.t. a warming level
# Parameters
# ----------
# tas_list : DataList
# DataList of global mean temperatures.
# index_list : DataList
# DataList of the index to calculate the anomaly for.
# warming_level : float
# Global warming level (GWL) to compute the anomaly for.
# skipna : bool, default: None
# If invalid values should be skipped.
# how : "absolute" | "relative" | "norm" | "no_anom"
# Method to calculate the anomaly. Default "absolute". Prepend "no_check_" to
# avoid the time bounds check.
# select_by : list of str, optional
# Conditions to align tas_list and index_list.
# """
# out = list()
# # loop through all global mean temperatures
# for tas, metadata in tas_list:
# attributes = {key: metadata[key] for key in select_by}
# # try to find the index
# index = select_by_metadata(index_list, **attributes)
# # make sure only one dataset is found in index_list
# if len(index) > 1:
# raise ValueError("Found more than one dataset:\n", metadata)
# # an index was found for this tas dataset
# if index:
# # determine year when the warming was first reached
# beg, end, __ = calc_year_of_warming_level(tas.tas, warming_level)
# if beg:
# index = calc_anomaly(
# index,
# beg,
# end,
# how=how,
# skipna=skipna,
# metadata=metadata,
# at_least_until=None,
# )
# out.append([index, metadata])
# return out