-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathtest_processing.py
1214 lines (1011 loc) · 37 KB
/
test_processing.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
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime as dt
import os.path
import re
import numpy as np
import pandas as pd
import pandas.testing as pdt
import pint.errors
import pytest
import scmdata.processing
from scmdata import ScmRun
from scmdata.errors import MissingRequiredColumnError, NonUniqueMetadataError
from scmdata.testing import _check_pandas_less_120
@pytest.fixture(scope="function")
def test_processing_scm_df():
data = np.array(
[
[1, 1.1, 1.2, 1.1],
[1.1, 1.2, 1.3, 1.41],
[1.3, 1.4, 1.5, 1.6],
[1.3, 1.5, 1.6, 1.2],
[1.48, 1.51, 1.72, 1.56],
]
).T
yield ScmRun(
data=data,
columns={
"model": ["a_iam"],
"climate_model": ["a_model"],
"scenario": ["a_scenario"],
"region": ["World"],
"variable": ["Surface Air Temperature Change"],
"unit": ["K"],
"ensemble_member": range(data.shape[1]),
},
index=[2005, 2006, 2007, 2100],
)
@pytest.fixture()
def test_processing_scm_df_multi_climate_model(test_processing_scm_df):
other = test_processing_scm_df + 0.1
other["climate_model"] = "z_model"
return test_processing_scm_df.append(other)
crossing_times_year_conversions = pytest.mark.parametrize(
"return_year,conv_to_year", ((None, True), (True, True), (False, False),)
)
def _get_calculate_crossing_times_call_kwargs(return_year):
call_kwargs = {}
if return_year is not None:
call_kwargs["return_year"] = return_year
return call_kwargs
def _get_expected_crossing_times(exp_vals, conv_to_year):
if conv_to_year:
exp_vals = [v if pd.isnull(v) else v.year for v in exp_vals]
else:
exp_vals = [pd.NaT if pd.isnull(v) else v for v in exp_vals]
return exp_vals
@pytest.mark.parametrize(
"threshold,exp_vals",
(
(
1.0,
[
dt.datetime(2006, 1, 1), # doesn't cross 1.0 until 2006
dt.datetime(2005, 1, 1),
dt.datetime(2005, 1, 1),
dt.datetime(2005, 1, 1),
dt.datetime(2005, 1, 1),
],
),
(
1.5,
[
np.nan, # never crosses
np.nan, # never crosses
dt.datetime(2100, 1, 1), # doesn't cross 1.5 until 2100
dt.datetime(2007, 1, 1), # 2007 is first year to actually exceed 1.5
dt.datetime(2006, 1, 1),
],
),
(2.0, [np.nan, np.nan, np.nan, np.nan, np.nan]),
),
)
@crossing_times_year_conversions
def test_crossing_times(
threshold, exp_vals, return_year, conv_to_year, test_processing_scm_df
):
call_kwargs = _get_calculate_crossing_times_call_kwargs(return_year)
res = scmdata.processing.calculate_crossing_times(
test_processing_scm_df, threshold=threshold, **call_kwargs,
)
exp_vals = _get_expected_crossing_times(exp_vals, conv_to_year)
exp = pd.Series(exp_vals, pd.MultiIndex.from_frame(test_processing_scm_df.meta))
pdt.assert_series_equal(res, exp)
@pytest.mark.parametrize(
"end_year",
(
5000,
pytest.param(
10 ** 3, marks=pytest.mark.xfail(reason="ScmRun fails to initialise #179")
),
pytest.param(
10 ** 4, marks=pytest.mark.xfail(reason="ScmRun fails to initialise #179")
),
),
)
@crossing_times_year_conversions
def test_crossing_times_long_runs(
end_year, return_year, conv_to_year, test_processing_scm_df
):
test_processing_scm_df = test_processing_scm_df.timeseries(time_axis="year").rename(
{2100: end_year}, axis="columns"
)
test_processing_scm_df = scmdata.ScmRun(test_processing_scm_df)
call_kwargs = _get_calculate_crossing_times_call_kwargs(return_year)
res = scmdata.processing.calculate_crossing_times(
test_processing_scm_df, threshold=1.5, **call_kwargs,
)
exp_vals = [
np.nan,
np.nan,
dt.datetime(end_year, 1, 1),
dt.datetime(2007, 1, 1),
dt.datetime(2006, 1, 1),
]
exp_vals = _get_expected_crossing_times(exp_vals, conv_to_year)
exp = pd.Series(exp_vals, pd.MultiIndex.from_frame(test_processing_scm_df.meta))
pdt.assert_series_equal(res, exp)
@crossing_times_year_conversions
def test_crossing_times_multi_climate_model(
return_year, conv_to_year, test_processing_scm_df_multi_climate_model
):
call_kwargs = _get_calculate_crossing_times_call_kwargs(return_year)
threshold = 1.5
exp_vals = [
# a_model
np.nan,
np.nan,
dt.datetime(2100, 1, 1),
dt.datetime(2007, 1, 1),
dt.datetime(2006, 1, 1),
# z_model
np.nan,
dt.datetime(2100, 1, 1),
dt.datetime(2007, 1, 1),
dt.datetime(2006, 1, 1),
dt.datetime(2005, 1, 1),
]
res = scmdata.processing.calculate_crossing_times(
test_processing_scm_df_multi_climate_model, threshold=threshold, **call_kwargs,
)
exp_vals = _get_expected_crossing_times(exp_vals, conv_to_year)
exp = pd.Series(
exp_vals,
pd.MultiIndex.from_frame(test_processing_scm_df_multi_climate_model.meta),
)
pdt.assert_series_equal(res, exp)
def _get_expected_crossing_time_quantiles(
cts, groups, exp_quantiles, interpolation, nan_fill_value, nan_fill_threshold
):
cts = cts.fillna(nan_fill_value)
cts_qs = cts.groupby(groups).quantile(q=exp_quantiles, interpolation=interpolation)
out = cts_qs.where(cts_qs < nan_fill_threshold)
out.index = out.index.set_names("quantile", level=-1)
return out
@pytest.mark.parametrize(
"groups", (["model", "scenario"], ["climate_model", "model", "scenario"])
)
@pytest.mark.parametrize(
"quantiles,exp_quantiles",
(
(None, [0.05, 0.5, 0.95]),
([0.05, 0.17, 0.5, 0.83, 0.95], [0.05, 0.17, 0.5, 0.83, 0.95]),
),
)
@pytest.mark.parametrize(
"interpolation,exp_interpolation",
((None, "linear"), ("linear", "linear"), ("nearest", "nearest"),),
)
def test_crossing_times_quantiles(
groups,
quantiles,
exp_quantiles,
interpolation,
exp_interpolation,
test_processing_scm_df_multi_climate_model,
):
threshold = 1.5
crossing_times = scmdata.processing.calculate_crossing_times(
test_processing_scm_df_multi_climate_model,
threshold=threshold,
# return_year False handled in
# test_crossing_times_quantiles_datetime_error
return_year=True,
)
exp = _get_expected_crossing_time_quantiles(
crossing_times,
groups,
exp_quantiles,
exp_interpolation,
nan_fill_value=10 ** 6,
nan_fill_threshold=10 ** 5,
)
call_kwargs = {"groupby": groups}
if quantiles is not None:
call_kwargs["quantiles"] = quantiles
if interpolation is not None:
call_kwargs["interpolation"] = interpolation
res = scmdata.processing.calculate_crossing_times_quantiles(
crossing_times, **call_kwargs
)
if _check_pandas_less_120():
check_dtype = False
else:
check_dtype = True
pdt.assert_series_equal(res, exp, check_dtype=check_dtype)
def test_crossing_times_quantiles_datetime_error(
test_processing_scm_df_multi_climate_model,
):
crossing_times = scmdata.processing.calculate_crossing_times(
test_processing_scm_df_multi_climate_model, threshold=1.5, return_year=False,
)
with pytest.raises(NotImplementedError):
scmdata.processing.calculate_crossing_times_quantiles(
crossing_times, ["model", "scenario"]
)
@pytest.mark.parametrize(
"nan_fill_value,out_nan_threshold,exp_vals",
(
(None, None, [2025.4, 2027.0, np.nan]),
(None, 10 ** 4, [2025.4, 2027.0, np.nan]),
(10 ** 5, 10 ** 4, [2025.4, 2027.0, np.nan]),
(10 ** 6, 10 ** 5, [2025.4, 2027.0, np.nan]),
(
# fill value less than threshold means calculated quantiles are used
3000,
10 ** 5,
[2025.4, 2027.0, 2805.4],
),
(3000, 2806, [2025.4, 2027.0, 2805.4]),
(3000, 2805, [2025.4, 2027.0, np.nan]),
),
)
def test_crossing_times_quantiles_nan_fill_values(
nan_fill_value, out_nan_threshold, exp_vals
):
data = np.array(
[
[1.3, 1.35, 1.5, 1.52],
[1.37, 1.43, 1.54, 1.58],
[1.48, 1.51, 1.72, 2.02],
[1.55, 1.65, 1.85, 2.1],
[1.42, 1.46, 1.55, 1.62],
]
).T
ensemble = scmdata.ScmRun(
data=data,
index=[2025, 2026, 2027, 2100],
columns={
"model": ["a_iam"],
"climate_model": ["a_model"],
"scenario": ["a_scenario"],
"region": ["World"],
"variable": ["Surface Air Temperature Change"],
"unit": ["K"],
"ensemble_member": range(data.shape[1]),
},
)
call_kwargs = {}
if nan_fill_value is not None:
call_kwargs["nan_fill_value"] = nan_fill_value
if out_nan_threshold is not None:
call_kwargs["out_nan_threshold"] = out_nan_threshold
crossing_times = scmdata.processing.calculate_crossing_times(
ensemble, threshold=1.53, return_year=True,
)
res = scmdata.processing.calculate_crossing_times_quantiles(
crossing_times,
["climate_model", "scenario"],
quantiles=(0.05, 0.5, 0.95),
**call_kwargs,
)
exp = pd.Series(
exp_vals,
pd.MultiIndex.from_product(
[["a_model"], ["a_scenario"], [0.05, 0.5, 0.95]],
names=["climate_model", "scenario", "quantile"],
),
)
if _check_pandas_less_120():
check_dtype = False
else:
check_dtype = True
pdt.assert_series_equal(res, exp, check_dtype=check_dtype)
output_name_options = pytest.mark.parametrize(
"output_name", (None, "test", "test other")
)
def _get_calculate_exceedance_probs_call_kwargs(output_name):
call_kwargs = {}
if output_name is not None:
call_kwargs["output_name"] = output_name
return call_kwargs
def _get_calculate_exeedance_probs_expected_name(output_name, threshold):
if output_name is not None:
return output_name
return "{} exceedance probability".format(threshold)
@pytest.mark.parametrize(
"threshold,exp_vals",
(
(1.0, [0.8, 1.0, 1.0, 1.0]),
(1.5, [0.0, 0.2, 0.4, 0.4]),
(2.0, [0.0, 0.0, 0.0, 0.0]),
),
)
@output_name_options
def test_exceedance_probabilities_over_time(
output_name, threshold, exp_vals, test_processing_scm_df
):
call_kwargs = _get_calculate_exceedance_probs_call_kwargs(output_name)
res = scmdata.processing.calculate_exceedance_probabilities_over_time(
test_processing_scm_df,
process_over_cols="ensemble_member",
threshold=threshold,
**call_kwargs,
)
exp_idx = pd.MultiIndex.from_frame(
test_processing_scm_df.meta.drop(
"ensemble_member", axis="columns"
).drop_duplicates()
)
exp = pd.DataFrame(
np.array(exp_vals)[np.newaxis, :],
index=exp_idx,
columns=test_processing_scm_df.time_points.to_index(),
)
exp.index = exp.index.set_levels(
[_get_calculate_exeedance_probs_expected_name(output_name, threshold)],
level="variable",
).set_levels(["dimensionless"], level="unit",)
pdt.assert_frame_equal(res, exp, check_like=True, check_column_type=False)
def test_exceedance_probabilities_over_time_multiple_res(
test_processing_scm_df_multi_climate_model,
):
start = test_processing_scm_df_multi_climate_model.copy()
threshold = 1.5
exp_vals = np.array([[0, 1, 2, 2], [1, 2, 3, 3]]) / 5
res = scmdata.processing.calculate_exceedance_probabilities_over_time(
start, process_over_cols=["ensemble_member"], threshold=threshold,
)
exp_idx = pd.MultiIndex.from_frame(
start.meta.drop(["ensemble_member"], axis="columns").drop_duplicates()
)
exp = pd.DataFrame(exp_vals, index=exp_idx, columns=start.time_points.to_index())
exp.index = exp.index.set_levels(
[_get_calculate_exeedance_probs_expected_name(None, threshold)],
level="variable",
).set_levels(["dimensionless"], level="unit",)
pdt.assert_frame_equal(res, exp, check_like=True, check_column_type=False)
def test_exceedance_probabilities_over_time_multiple_grouping(
test_processing_scm_df_multi_climate_model,
):
start = test_processing_scm_df_multi_climate_model.copy()
threshold = 1.5
exp_vals = np.array([1, 3, 5, 5]) / 10
res = scmdata.processing.calculate_exceedance_probabilities_over_time(
start,
process_over_cols=["climate_model", "ensemble_member"],
threshold=threshold,
)
exp_idx = pd.MultiIndex.from_frame(
start.meta.drop(
["climate_model", "ensemble_member"], axis="columns"
).drop_duplicates()
)
exp = pd.DataFrame(
exp_vals[np.newaxis, :], index=exp_idx, columns=start.time_points.to_index(),
)
exp.index = exp.index.set_levels(
[_get_calculate_exeedance_probs_expected_name(None, threshold)],
level="variable",
).set_levels(["dimensionless"], level="unit",)
pdt.assert_frame_equal(res, exp, check_like=True, check_column_type=False)
@pytest.mark.parametrize(
"threshold,exp_val", ((1.0, 1.0), (1.5, 0.6), (2.0, 0.0),),
)
@output_name_options
def test_exceedance_probabilities(
output_name, threshold, exp_val, test_processing_scm_df
):
call_kwargs = _get_calculate_exceedance_probs_call_kwargs(output_name)
res = scmdata.processing.calculate_exceedance_probabilities(
test_processing_scm_df,
process_over_cols="ensemble_member",
threshold=threshold,
**call_kwargs,
)
exp_idx = pd.MultiIndex.from_frame(
test_processing_scm_df.meta.drop(
"ensemble_member", axis="columns"
).drop_duplicates()
)
exp = pd.Series(exp_val, index=exp_idx)
exp.name = _get_calculate_exeedance_probs_expected_name(output_name, threshold)
exp.index = exp.index.set_levels(["dimensionless"], level="unit",)
pdt.assert_series_equal(res, exp)
def test_exceedance_probabilities_multiple_res(
test_processing_scm_df_multi_climate_model,
):
start = test_processing_scm_df_multi_climate_model.copy()
threshold = 1.5
exp_vals = [0.6, 0.8]
res = scmdata.processing.calculate_exceedance_probabilities(
start, process_over_cols=["ensemble_member"], threshold=threshold,
)
exp_idx = pd.MultiIndex.from_frame(
start.meta.drop("ensemble_member", axis="columns").drop_duplicates()
)
exp = pd.Series(exp_vals, index=exp_idx)
exp.name = _get_calculate_exeedance_probs_expected_name(None, threshold)
exp.index = exp.index.set_levels(["dimensionless"], level="unit",)
pdt.assert_series_equal(res, exp)
def test_exceedance_probabilities_multiple_grouping(
test_processing_scm_df_multi_climate_model,
):
start = test_processing_scm_df_multi_climate_model.copy()
threshold = 1.5
exp_vals = [0.7]
res = scmdata.processing.calculate_exceedance_probabilities(
start,
process_over_cols=["ensemble_member", "climate_model"],
threshold=threshold,
)
exp_idx = pd.MultiIndex.from_frame(
start.meta.drop(
["ensemble_member", "climate_model"], axis="columns"
).drop_duplicates()
)
exp = pd.Series(exp_vals, index=exp_idx)
exp.name = _get_calculate_exeedance_probs_expected_name(None, threshold)
exp.index = exp.index.set_levels(["dimensionless"], level="unit",)
pdt.assert_series_equal(res, exp)
@pytest.mark.parametrize("col", ["unit", "variable"])
@pytest.mark.parametrize(
"func,kwargs",
(
(scmdata.processing.calculate_exceedance_probabilities, {"threshold": 1.5}),
(
scmdata.processing.calculate_exceedance_probabilities_over_time,
{"threshold": 1.5},
),
),
)
def test_requires_preprocessing(test_processing_scm_df, col, func, kwargs):
test_processing_scm_df[col] = [
str(i) for i in range(test_processing_scm_df.shape[0])
]
error_msg = (
"More than one value for {}. "
"This is unlikely to be what you want.".format(col)
)
with pytest.raises(ValueError, match=error_msg):
func(
test_processing_scm_df,
process_over_cols=["ensemble_member", col],
**kwargs,
)
def _get_calculate_peak_call_kwargs(output_name, variable):
call_kwargs = {}
if output_name is not None:
call_kwargs["output_name"] = output_name
return call_kwargs
@output_name_options
def test_peak(output_name, test_processing_scm_df):
call_kwargs = _get_calculate_peak_call_kwargs(
output_name, test_processing_scm_df.get_unique_meta("variable", True),
)
exp_vals = [1.2, 1.41, 1.6, 1.6, 1.72]
res = scmdata.processing.calculate_peak(test_processing_scm_df, **call_kwargs,)
exp_idx = pd.MultiIndex.from_frame(test_processing_scm_df.meta)
exp = pd.Series(exp_vals, index=exp_idx)
if output_name is not None:
exp.index = exp.index.set_levels([output_name], level="variable")
else:
idx = exp.index.names
exp = exp.reset_index()
exp["variable"] = exp["variable"].apply(lambda x: "Peak {}".format(x))
exp = exp.set_index(idx)[0]
pdt.assert_series_equal(res, exp)
def test_peak_multi_variable(test_processing_scm_df_multi_climate_model):
test_processing_scm_df_multi_climate_model["variable"] = [
str(i) for i in range(test_processing_scm_df_multi_climate_model.shape[0])
]
exp_vals = [1.2, 1.41, 1.6, 1.6, 1.72, 1.3, 1.51, 1.7, 1.7, 1.82]
res = scmdata.processing.calculate_peak(test_processing_scm_df_multi_climate_model,)
exp_idx = pd.MultiIndex.from_frame(test_processing_scm_df_multi_climate_model.meta)
exp = pd.Series(exp_vals, index=exp_idx)
idx = exp.index.names
exp = exp.reset_index()
exp["variable"] = exp["variable"].apply(lambda x: "Peak {}".format(x))
exp = exp.set_index(idx)[0]
pdt.assert_series_equal(res, exp)
def _get_calculate_peak_time_call_kwargs(return_year, output_name):
call_kwargs = {}
if return_year is not None:
call_kwargs["return_year"] = return_year
if output_name is not None:
call_kwargs["output_name"] = output_name
return call_kwargs
@output_name_options
@crossing_times_year_conversions
def test_peak_time(output_name, return_year, conv_to_year, test_processing_scm_df):
call_kwargs = _get_calculate_peak_time_call_kwargs(return_year, output_name)
exp_vals = [
dt.datetime(2007, 1, 1),
dt.datetime(2100, 1, 1),
dt.datetime(2100, 1, 1),
dt.datetime(2007, 1, 1),
dt.datetime(2007, 1, 1),
]
res = scmdata.processing.calculate_peak_time(test_processing_scm_df, **call_kwargs,)
exp_idx = pd.MultiIndex.from_frame(test_processing_scm_df.meta)
if conv_to_year:
exp_vals = [v.year if conv_to_year else v for v in exp_vals]
time_name = "Year"
else:
time_name = "Time"
exp = pd.Series(exp_vals, index=exp_idx)
if output_name is not None:
exp.index = exp.index.set_levels([output_name], level="variable")
else:
idx = exp.index.names
exp = exp.reset_index()
exp["variable"] = exp["variable"].apply(
lambda x: "{} of peak {}".format(time_name, x)
)
exp = exp.set_index(idx)[0]
pdt.assert_series_equal(res, exp)
@crossing_times_year_conversions
def test_peak_time_multi_variable(
return_year, conv_to_year, test_processing_scm_df_multi_climate_model
):
test_processing_scm_df_multi_climate_model["variable"] = [
str(i) for i in range(test_processing_scm_df_multi_climate_model.shape[0])
]
call_kwargs = _get_calculate_peak_time_call_kwargs(return_year, None)
exp_vals = [
dt.datetime(2007, 1, 1),
dt.datetime(2100, 1, 1),
dt.datetime(2100, 1, 1),
dt.datetime(2007, 1, 1),
dt.datetime(2007, 1, 1),
] * 2
res = scmdata.processing.calculate_peak_time(
test_processing_scm_df_multi_climate_model, **call_kwargs
)
if conv_to_year:
exp_vals = [v.year if conv_to_year else v for v in exp_vals]
time_name = "Year"
else:
time_name = "Time"
exp_idx = pd.MultiIndex.from_frame(test_processing_scm_df_multi_climate_model.meta)
exp = pd.Series(exp_vals, index=exp_idx)
idx = exp.index.names
exp = exp.reset_index()
exp["variable"] = exp["variable"].apply(
lambda x: "{} of peak {}".format(time_name, x)
)
exp = exp.set_index(idx)[0]
pdt.assert_series_equal(res, exp)
@pytest.fixture(scope="session")
def sr15_inferred_temperature_quantiles(test_data_path):
# fake the temperature quantiles in preparation for the categorisation tests
# we do this as P33 is not included in the SR1.5 output, yet we need it for
# the categorisation
sr15_output = scmdata.ScmRun(
os.path.join(test_data_path, "sr15", "sr15-output.csv"),
)
sr15_exceedance_probs = sr15_output.filter(variable="*Exceedance*")
out = []
for cm in ["MAGICC", "FAIR"]:
cm_ep = sr15_exceedance_probs.filter(variable="*{}*".format(cm))
cm_median = sr15_output.filter(variable="*{}*MED".format(cm)).timeseries()
for p in [0.67, 0.5, 0.34]:
quantile = 1 - p
cm_q = cm_median.reset_index()
cm_q["variable"] = cm_q["variable"].str.replace(
"MED", "P{}".format(int(np.round(quantile * 100, 0)))
)
cm_q = cm_q.set_index(cm_median.index.names).sort_index()
cm_q.iloc[:, :] = 10
for t in [2.0, 1.5]:
cm_ep_t = cm_ep.filter(variable="*{}*".format(t)).timeseries()
# null values in FaIR should be treated as being small
cm_ep_t_lt = (cm_ep_t <= p) | cm_ep_t.isnull()
cm_ep_t_lt = cm_ep_t_lt.reorder_levels(cm_q.index.names).sort_index()
cm_ep_t_lt.index = cm_q.index
cm_q[cm_ep_t_lt] = t
out.append(scmdata.ScmRun(cm_q))
out = scmdata.run_append(out)
return out
@pytest.fixture(scope="session")
def sr15_temperatures_unmangled_names(sr15_inferred_temperature_quantiles):
out = sr15_inferred_temperature_quantiles.copy()
out["quantile"] = out["variable"].apply(
lambda x: float(x.split("|")[-1].strip("P")) / 100
)
out["variable"] = out["variable"].apply(lambda x: "|".join(x.split("|")[:-1]))
return out
@pytest.mark.parametrize("unit", ("K", "mK"))
def test_categorisation_sr15(unit, sr15_temperatures_unmangled_names):
index = ["model", "scenario"]
exp = (
sr15_temperatures_unmangled_names.meta[index + ["category"]]
.drop_duplicates()
.set_index(index)["category"]
)
inp = (
sr15_temperatures_unmangled_names.drop_meta(["category", "version"])
.filter(variable="*MAGICC*")
.convert_unit(unit)
)
res = scmdata.processing.categorisation_sr15(inp, index=index)
pdt.assert_series_equal(exp, res)
category_counts = res.value_counts()
assert category_counts["Above 2C"] == 189
assert category_counts["Lower 2C"] == 74
assert category_counts["Higher 2C"] == 58
assert category_counts["1.5C low overshoot"] == 44
assert category_counts["1.5C high overshoot"] == 37
assert category_counts["Below 1.5C"] == 9
def test_categorisation_sr15_multimodel(sr15_temperatures_unmangled_names):
index = ["model", "scenario", "climate_model"]
inp = sr15_temperatures_unmangled_names.drop_meta(["category", "version"])
inp["climate_model"] = inp["variable"].apply(lambda x: x.split("|")[-1])
inp["variable"] = inp["variable"].apply(lambda x: "|".join(x.split("|")[:-1]))
res = scmdata.processing.categorisation_sr15(inp, index=index)
exp = pd.concat(
[
scmdata.processing.categorisation_sr15(inp_cm, index=index)
for inp_cm in inp.groupby("climate_model")
]
)
pdt.assert_series_equal(exp.sort_index(), res.sort_index())
category_counts = res.groupby("climate_model").value_counts()
assert category_counts.loc["MAGICC6", "Above 2C"] == 189
assert category_counts.loc["MAGICC6", "Higher 2C"] == 58
assert category_counts.loc["MAGICC6", "Lower 2C"] == 74
assert category_counts.loc["MAGICC6", "1.5C high overshoot"] == 37
assert category_counts.loc["MAGICC6", "1.5C low overshoot"] == 44
assert category_counts.loc["MAGICC6", "Below 1.5C"] == 9
assert category_counts.loc["FAIR", "Above 2C"] == 134
assert category_counts.loc["FAIR", "Higher 2C"] == 14
assert category_counts.loc["FAIR", "Lower 2C"] == 80
assert category_counts.loc["FAIR", "1.5C high overshoot"] == 1
assert category_counts.loc["FAIR", "1.5C low overshoot"] == 22
assert category_counts.loc["FAIR", "Below 1.5C"] == 159
def test_categorisation_sr15_multi_variable(sr15_temperatures_unmangled_names):
inp = sr15_temperatures_unmangled_names.copy()
inp["variable"] = range(inp["variable"].shape[0])
error_msg = (
"More than one value for variable. " "This is unlikely to be what you want."
)
with pytest.raises(ValueError, match=error_msg):
scmdata.processing.categorisation_sr15(inp, index=["model", "scenario"])
def test_categorisation_sr15_bad_unit(sr15_temperatures_unmangled_names):
inp = sr15_temperatures_unmangled_names.filter(variable="*MAGICC*").copy()
inp["unit"] = "GtC"
with pytest.raises(pint.errors.DimensionalityError):
scmdata.processing.categorisation_sr15(inp, index=["model", "scenario"])
def test_categorisation_sr15_no_quantile(sr15_temperatures_unmangled_names):
error_msg = (
"No `quantile` column, calculate quantiles using `.quantiles_over` "
"to calculate the 0.33, 0.5 and 0.66 quantiles before calling "
"this function"
)
with pytest.raises(MissingRequiredColumnError, match=error_msg):
scmdata.processing.categorisation_sr15(
sr15_temperatures_unmangled_names.filter(quantile=0.5).drop_meta(
"quantile"
),
index=["model", "scenario"],
)
def test_categorisation_sr15_missing_quantiles(sr15_temperatures_unmangled_names):
error_msg = re.escape(
"Not all required quantiles are available, we require the "
"0.33, 0.5 and 0.66 quantiles, available quantiles: `[0.5]`"
)
with pytest.raises(ValueError, match=error_msg):
scmdata.processing.categorisation_sr15(
sr15_temperatures_unmangled_names.filter(quantile=0.5),
index=["model", "scenario"],
)
@pytest.mark.xfail(
_check_pandas_less_120(),
reason="pandas<1.2.0 can't handle non-numeric types in pivot",
)
@pytest.mark.parametrize(
"index",
(
["climate_model", "model", "scenario", "region"],
["climate_model", "scenario", "region"],
["climate_model", "model", "scenario", "region", "unit"],
),
)
@pytest.mark.parametrize(
",".join(
[
"exceedance_probabilities_thresholds",
"exp_exceedance_prob_thresholds",
"exceedance_probabilities_output_name",
"exp_exceedance_probabilities_output_name",
"exceedance_probabilities_variable",
"exp_exceedance_probabilities_variable",
"categorisation_variable",
"exp_categorisation_variable",
"categorisation_quantile_cols",
"exp_categorisation_quantile_cols",
]
),
(
(
None,
[1.5, 2.0, 2.5],
None,
"{} exceedance probability",
None,
"Surface Air Temperature Change",
"Surface Temperature",
"Surface Temperature",
"run_id",
"run_id",
),
(
[1.0, 1.5, 2.0, 2.5],
[1.0, 1.5, 2.0, 2.5],
"Exceedance Probability|{:.2f}C",
"Exceedance Probability|{:.2f}C",
"Surface Temperature",
"Surface Temperature",
None,
"Surface Air Temperature Change",
None,
"ensemble_member",
),
),
)
@pytest.mark.parametrize(
",".join(
[
"peak_variable",
"exp_peak_variable",
"peak_quantiles",
"exp_peak_quantiles",
"peak_naming_base",
"exp_peak_naming_base",
"peak_time_naming_base",
"exp_peak_time_naming_base",
"peak_return_year",
"exp_peak_return_year",
]
),
(
(
"Surface Temperature",
"Surface Temperature",
None,
[0.05, 0.17, 0.5, 0.83, 0.95],
None,
"{} peak",
None,
"{} peak year",
None,
True,
),
(
"Surface Temperature",
"Surface Temperature",
None,
[0.05, 0.17, 0.5, 0.83, 0.95],
None,
"{} peak",
"test {}",
"test {}",
None,
True,
),
(
"Surface Temperature",
"Surface Temperature",
None,
[0.05, 0.17, 0.5, 0.83, 0.95],
None,
"{} peak",
None,
"{} peak year",
True,
True,
),
(
None,
"Surface Air Temperature Change",
[0.05, 0.95],
[0.05, 0.95],
"test {}",
"test {}",
"test peak {}",
"test peak {}",
True,
True,
),
(
None,
"Surface Air Temperature Change",
[0.05, 0.95],
[0.05, 0.95],
"test {}",
"test {}",
None,
"{} peak time",
False,
False,
),
(
None,
"Surface Air Temperature Change",
[0.05, 0.95],
[0.05, 0.95],
"test {}",
"test {}",
"test peak {}",
"test peak {}",