-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathspatial_plots_multimodel.py
More file actions
2103 lines (1756 loc) · 62.5 KB
/
spatial_plots_multimodel.py
File metadata and controls
2103 lines (1756 loc) · 62.5 KB
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
# -*- coding: utf-8 -*-
"""Multi-model UNSEEN spatial maps using CAFE and DCPP models.
Notes
-----
* Slices obs_ds time period to match models
* requires xarray>=2024.10.0, numpy<=2.1.0 (shapely issue?)
* requires acs_plotting_maps, ia39 storage
"""
import calendar
from cartopy.crs import PlateCarree
from cartopy.mpl.gridliner import LatitudeFormatter, LongitudeFormatter
import cmocean
import functools
import matplotlib.pyplot as plt
from matplotlib.colors import BoundaryNorm, LogNorm
from matplotlib.ticker import AutoMinorLocator
import numpy as np
from pathlib import Path
from scipy.stats import mode, median_abs_deviation
import string
import xarray as xr
import xesmf as xe
from acs_plotting_maps import (
cmap_dict,
tick_dict,
regions_dict,
crop_cmap_center,
) # noqa
from unseen import fileio, time_utils, eva, general_utils
from unseen.stability import statistic_by_lead_confidence_interval
from spatial_plots import (
InfoSet,
func_dict,
soft_record_metric,
resample_subsample,
nonstationary_new_record_probability,
month_cmap,
month_cmap_alt,
new_record_probability_empirical,
) # noqa
plt.rcParams["figure.figsize"] = [14, 10]
plt.rcParams["figure.dpi"] = 300
plt.rcParams["figure.constrained_layout.use"] = True
plt.rcParams["contour.linewidth"] = 0.3
plt.rcParams["hatch.color"] = "k"
plt.rcParams["hatch.linewidth"] = 0.5
plt.rcParams["xtick.major.size"] = 4.5
plt.rcParams["xtick.minor.size"] = 3
plt.rcParams["ytick.major.size"] = 4.5
plt.rcParams["ytick.minor.size"] = 3
# Subplot letter labels
letters = [f"({i})" for i in string.ascii_letters]
# -------------------------------------------------------------------------
# Generic plotting functions
# -------------------------------------------------------------------------
def map_subplot(
fig,
ax,
data,
region="aus_states_territories",
hatching=None,
hatching_color="k",
title=None,
ticks=None,
ticklabels=None,
cmap=plt.cm.viridis,
norm=None,
plot_cbar=False,
cbar_label=None,
extend="neither",
cbar_kwargs=dict(fraction=0.05),
mask_not_australia=True,
xlim=(112.5, 154.3),
ylim=(-44.5, -9.6),
xticks=np.arange(120, 155, 10),
yticks=np.arange(-40, -0, 10),
contour=False,
vcentre=None,
**kwargs,
):
"""Plot 2D data on an Australia map with coastlines.
Parameters
----------
fig : matplotlib figure
ax : matplotlib axes
Axes to plot on
Returns
-------
fig : matplotlib figure
ax :
cs : cartopy.mpl.geocollection.GeoQuadMesh
Example
-------
data = xr.DataArray(
np.random.rand(10, 10),
dims=["lat", "lon"],
coords={"lat": np.linspace(-45, -10, 10), "lon": np.linspace(115, 155, 10)},
)
fig, ax = plt.subplots(1, 1, subplot_kw=dict(projection=PlateCarree()))
fig, ax, cs = map_subplot(fig, ax, data)
"""
if title is not None:
ax.set_title(title, loc="left", fontsize=12)
ax.set_extent([*xlim, *ylim], crs=PlateCarree())
# Stolen from acs_plotting_maps
if ticks is not None:
if ticklabels is not None and not isinstance(ticklabels, (list, np.ndarray)):
# Format tick labels
diff = np.diff(ticks)[0] / 2
ticklabels = np.array(ticks[:-1] + diff)
if (ticklabels.astype(int) == ticklabels).all():
ticklabels = ticklabels.astype(int)
if diff >= 1e-3:
ticklabels = np.around(ticklabels, 3)
if ticklabels is None or (len(ticklabels) == len(ticks) - 1):
# Middle or no ticklabels provided
norm = BoundaryNorm(ticks, cmap.N + 1, extend=extend)
if ticklabels is not None:
middle_ticks = [
(ticks[i + 1] + ticks[i]) / 2 for i in range(len(ticks) - 1)
]
else:
middle_ticks = []
else:
# Use ticks as labels between given ticks
middle_ticks = [
(ticks[i + 1] + ticks[i]) / 2 for i in range(len(ticks) - 1)
]
outside_bound_first = [ticks[0] - (ticks[1] - ticks[0]) / 2]
outside_bound_last = [ticks[-1] + (ticks[-1] - ticks[-2]) / 2]
bounds = outside_bound_first + middle_ticks + outside_bound_last
norm = BoundaryNorm(bounds, cmap.N, extend="neither")
if vcentre is not None:
cmap = crop_cmap_center(cmap, ticks, vcentre, extend=extend)
cmap.set_bad("lightgrey") # Set color for NaN values
if contour:
cs = ax.contourf(
data.lon,
data.lat,
data,
cmap=cmap,
norm=norm,
transform=PlateCarree(),
**kwargs,
)
else:
cs = ax.pcolormesh(data.lon, data.lat, data, cmap=cmap, norm=norm, **kwargs)
if hatching is not None:
if hatching_color != "k":
plt.rcParams["hatch.linewidth"] = 0.7
else:
plt.rcParams["hatch.linewidth"] = 0.6
plt.rcParams["hatch.color"] = hatching_color
ax = add_hatching(ax, hatching)
if mask_not_australia:
ax = plot_region_mask(ax, regions_dict["not_australia"])
if plot_cbar:
fig.colorbar(cs, extend=extend, label=cbar_label, ticks=ticks, **cbar_kwargs)
if region is not None:
ax = plot_region_border(ax, regions_dict[region], ec="k", zorder=5)
# Format axis ticks
if xticks is not None:
ax.set_xticks(xticks)
if yticks is not None:
ax.set_yticks(yticks)
ax.xaxis.set_major_formatter(LongitudeFormatter())
ax.xaxis.set_minor_locator(AutoMinorLocator())
ax.yaxis.set_major_formatter(LatitudeFormatter())
ax.yaxis.set_minor_locator(AutoMinorLocator())
return fig, ax, cs
def add_hatching(ax, hatching, **kwargs):
"""Add hatching to plot where hatching is True."""
ax.contourf(
hatching.lon,
hatching.lat,
hatching,
alpha=0,
hatches=["", "xxxx"],
transform=PlateCarree(),
**kwargs,
)
return ax
def add_shared_colorbar(
fig,
ax,
cs,
orientation="horizontal",
ticks=None,
ticklabels=None,
tick_interval=1,
**kwargs,
):
"""Add a shared colorbar to a figure with multiple subplots.
Parameters
----------
fig : matplotlib figure
ax : matplotlib axes
Axes to which the colorbar will be added (usually the last subplot)
cs : cartopy.mpl.geocollection.GeoQuadMesh
The GeoQuadMesh object to which the colorbar corresponds.
orientation : {"horizontal", "vertical"}, default="horizontal"
Orientation of the colorbar.
ticks : array-like, default=None
Ticks for the colorbar. If None, will use the boundaries of the norm.
ticklabels : array-like, default=None
Labels for the ticks. If None, will use the middle of the ticks.
tick_interval : int, default=1
Interval at which to show tick labels. For example, if 2, will show
every second label.
**kwargs : dict
Additional keyword arguments passed to `fig.colorbar`
Returns
-------
cbar : matplotlib colorbar
The colorbar object added to the figure
"""
# Set default colorbar parameters
if "aspect" not in kwargs:
kwargs["aspect"] = 32
if "pad" not in kwargs and "shrink" not in kwargs:
if orientation == "vertical":
kwargs["pad"] = 0.03
kwargs["shrink"] = 0.75
else:
kwargs["pad"] = 0.02
kwargs["shrink"] = 0.7
norm = kwargs.pop("norm", cs.norm)
if ticks is None and hasattr(norm, "boundaries"):
ticks = norm.boundaries
if "extend" not in kwargs:
kwargs["extend"] = norm.extend
# Format ticks
if ticks is not None:
diff = np.ediff1d(ticks) / 2
if ticklabels is not None and not isinstance(ticklabels, (list, np.ndarray)):
# Format tick labels
ticklabels = np.array(ticks[:-1] + diff)
if (ticklabels.astype(int) == ticklabels).all():
ticklabels = ticklabels.astype(int)
if np.all(diff) >= 1e-3:
ticklabels = np.around(ticklabels, 3)
if ticklabels is None:
middle_ticks = []
else:
middle_ticks = np.array(ticks[:-1]) + diff
if np.all(diff) >= 1e-3: # Round to 3 decimal places
middle_ticks = np.around(middle_ticks, 3)
cbar = fig.colorbar(
cs, ax=ax, orientation=orientation, ticks=ticks, norm=norm, **kwargs
)
if ticklabels is not None:
if len(ticks) != len(ticklabels):
ticks = middle_ticks
if orientation == "vertical":
cbar.ax.set_yticks(ticks, ticklabels)
else:
cbar.ax.set_xticks(ticks, ticklabels)
# cbar.update_ticks()
cbar.ax.minorticks_off()
# Hide colorbar ticks at specific intervals
if tick_interval > 1:
axis = "y" if orientation == "vertical" else "x"
labels = eval(f"cbar.ax.{axis}axis.get_ticklabels()")
for i, label in enumerate(labels):
# Hide labels
if i % tick_interval != 0:
label.set_visible(False)
return cbar
def add_inset_colorbar(fig, ax, cs, label, tick_size=8, label_size=9):
"""Add a small colorbar inside the lower left of a subplot.
Parameters
----------
fig : matplotlib figure
ax : matplotlib axes
cs : cartopy.mpl.geocollection.GeoQuadMesh
label : str
Label for the colorbar
tick_size : int, default=8
Font size of the tick labels
label_size : int, default=9
Font size of the colorbar label
Returns
-------
cbar : matplotlib colorbar
The colorbar object
"""
# Create an inset axes for the colorbar [x0, y0, width, height]
cax = ax.inset_axes([0.04, 0.1, 0.7, 0.05])
cbar = fig.colorbar(cs, cax=cax, orientation="horizontal")
cbar.ax.set_title(label, size=label_size)
cbar.ax.tick_params(labelsize=tick_size)
return cbar
def plot_region_border(ax, region, **kwargs):
"""Plot shapefile region borders."""
ec = kwargs.pop("ec", "k") # Default edge color
lw = kwargs.pop("lw", 0.5) # Default line width
ax.add_geometries(
region.geometry,
linewidth=lw,
ls="-",
facecolor="none",
edgecolor=ec,
crs=PlateCarree(),
**kwargs,
)
return ax
def plot_region_mask(ax, region, **kwargs):
"""Mask data outside of the region."""
facecolor = kwargs.pop("facecolor", "white")
ax.add_geometries(
region,
crs=PlateCarree(),
linewidth=0,
facecolor=facecolor,
**kwargs,
)
return ax
def extra_subplot_formatting(ax):
"""Format subplots with common settings."""
# Increase border width of observations & multi-model subplot
[a.set_linewidth(2) for a in ax[0].spines.values()]
[a.set_edgecolor("midnightblue") for a in ax[0].spines.values()]
[a.set_linewidth(2) for a in ax[1].spines.values()]
# Hide any empty subplots
for a in [a for a in ax if not a.collections]:
a.axis("off")
return ax
def add_aus_state_labels(ax, **kwargs):
"""Add Australian states and territories labels to a map."""
regions = regions_dict["aus_states_territories"]
regions = regions[:-1] # exclude "other territories"
for name, centroid in zip(regions.ABBREV, regions.centroid):
x, y = centroid.x, centroid.y
if name not in ["ACT", "VIC", "TAS"]:
# Add the text label at the centroid location
ax.text(x, y - 0.4, name, ha="center", va="center", **kwargs)
else:
# Annotate name to the right with line pointing to centroid
if name == "ACT":
dx, dy = 4.8, -0.5
elif name == "VIC":
dx, dy = 8.5, -2.6
elif name == "TAS":
dx, dy = 6, -0.7
ax.annotate(
name,
xy=(x, y),
xytext=(x + dx, y + dy),
ha="center",
va="center",
arrowprops=dict(arrowstyle="-", lw=1, shrinkA=0, shrinkB=-2),
**kwargs,
)
return ax
# ----------------------------------------------------------------------------
# Data loading and processing functions
# ----------------------------------------------------------------------------
def get_makefile_vars(
models, metric="txx", obs="AGCD", obs_config_file="AGCD-CSIRO_r05_tasmax_config.mk"
):
"""Create nested dictionary of observation and model variables used in Makefile.
Saves all observation and model local variables defined in the Makefile (converted
to lower case and sorted) for the given metric and observation dataset.
Parameters
----------
metric : str
Metric to plot (used to find project details).
obs : str
Name of the observation dataset
obs_config_file : str
Name of the observation dataset makefile (without path).
Returns
-------
var_dict : dict
Nested dictionary of e.g., {CAFE: {metric_fcst: filename, metric_obs: filename}}
"""
dir = Path("/g/data/xv83/unseen-projects/code/")
obs_details = dir / f"dataset_makefiles/{obs_config_file}"
project_details = dir / f"project-{metric}/{metric}_config.mk"
# Nested dictionary of {model: {key1: value, key2: value}}
var_dict = {}
var_dict[obs] = general_utils.get_model_makefile_dict(
dir, project_details, obs, obs_details, obs_details
)
# Format/eval dictionary values (observation only?)
for key in ["plot_dict", "gev_trend_period"]:
var_dict[obs][key] = eval(var_dict[obs][key])
var_dict[obs]["reference_time_period"] = list(
var_dict[obs]["reference_time_period"].split(" ")
)
for model in models:
# Search for the model makefile
model_details = list((dir / "dataset_makefiles/").rglob(f"{model}*config.mk"))[
0
]
var_dict[model] = general_utils.get_model_makefile_dict(
dir, project_details, model, model_details, obs_details
)
return var_dict
def open_model_dataset(
kws,
bc=None,
alpha=0.05,
time_dim="time",
init_dim="init_date",
lead_dim="lead_time",
ensemble_dim="ensemble",
stability_n_resamples=10000,
):
"""Open, format and combine relevant model data."""
time_coder = xr.coders.CFDatetimeCoder(use_cftime=True)
var = kws["var"]
if bc not in ["", None]:
_bc = f"_{bc}_bc"
else:
_bc = ""
metric_fcst = kws[f"metric_fcst{_bc}"]
similarity_file = str(kws[f"similarity{_bc}_file"])
# gev_params_stationary_file = kws[f"gev_stationary{_bc}"]
gev_params_nonstationary_file = kws[f"gev_nonstationary{_bc}"]
model_ds = fileio.open_dataset(metric_fcst)
# Similarity test (for hatching)
similarity_ds = fileio.open_dataset(similarity_file)
ds_independence = xr.open_dataset(kws["independence_file"], decode_times=time_coder)
dparams_ns = xr.open_dataset(gev_params_nonstationary_file)[var]
# Calculate stability confidence intervals (for median and 1% AEP)
if bc is not None:
da = fileio.open_dataset(kws[f"metric_fcst"])[var]
else:
da = model_ds[var]
ci_median = get_stability_ci(
da, "median", confidence_level=0.99, n_resamples=stability_n_resamples
)
ci_aep = get_stability_ci(
da, "aep", confidence_level=0.99, n_resamples=stability_n_resamples, aep=1
)
min_lead_ds = fileio.open_dataset(
kws["independence_file"],
variables="min_lead",
shapefile=kws["shapefile"],
shape_overlap=kws["shape_overlap"],
spatial_agg=kws["min_lead_shape_spatial_agg"],
)
# Drop dependent lead times
min_lead = min_lead_ds["min_lead"]
model_ds = model_ds.groupby(f"{init_dim}.month").where(
model_ds[lead_dim] >= min_lead
)
model_ds = model_ds.dropna(lead_dim, how="all")
model_ds = model_ds.sel(lat=dparams_ns.lat, lon=dparams_ns.lon)
# Convert event_time from string to cftime
try:
event_times = np.vectorize(time_utils.str_to_cftime)(
model_ds.event_time, model_ds.time.dt.calendar
)
model_ds["event_time"] = (model_ds.event_time.dims, event_times)
except ValueError:
model_ds["event_time"] = model_ds.event_time.astype(
dtype="datetime64[ns]"
).compute()
model_ds_stacked = model_ds.stack(
{"sample": [ensemble_dim, init_dim, lead_dim]}, create_index=False
)
model_ds_stacked = model_ds_stacked.transpose("sample", ...)
model_ds_stacked = model_ds_stacked.dropna("sample", how="all")
model_ds_stacked = model_ds_stacked.chunk(dict(sample=-1))
model_ds_stacked[f"{kws['similarity_test']}_pval"] = similarity_ds[
f"{kws['similarity_test']}_pval"
]
model_ds_stacked["pval_mask"] = (
similarity_ds[f"{kws['similarity_test']}_pval"] <= alpha
)
# model_ds_stacked["dparams"] = dparams
model_ds_stacked["dparams_ns"] = dparams_ns
model_ds_stacked["covariate"] = model_ds_stacked[time_dim].dt.year
for dvar in ds_independence.data_vars:
model_ds_stacked[dvar] = ds_independence[dvar]
model_ds_stacked["min_lead_median"] = min_lead
model_ds_stacked["ci_median"] = ci_median
model_ds_stacked["ci_aep"] = ci_aep
return model_ds_stacked
def open_obs_dataset(var_dict, obs):
"""Open metric observational datasets."""
obs_ds = fileio.open_dataset(var_dict[obs]["metric_obs"])
# gev_file = Path(var_dict[obs]["gev_stationary_obs"])
ns_gev_file = Path(var_dict[obs]["gev_nonstationary_obs"])
# dparams = xr.open_dataset(gev_file)[var_dict[obs]["var"]]
dparams_ns = xr.open_dataset(ns_gev_file)[var_dict[obs]["var"]]
if var_dict[obs]["reference_time_period"] is not None:
obs_ds = time_utils.select_time_period(
obs_ds, var_dict[obs]["reference_time_period"]
)
event_times = np.vectorize(time_utils.str_to_cftime)(
obs_ds.event_time, obs_ds.time.dt.calendar
)
obs_ds["event_time"] = (obs_ds.event_time.dims, event_times)
obs_ds["dparams_ns"] = dparams_ns
if "covariate" in dparams_ns:
obs_ds["covariate"] = dparams_ns.covariate
else:
obs_ds["covariate"] = obs_ds.time.dt.year
return obs_ds
def subset_obs_dataset(obs_ds, ds):
"""Subset observation dataset to the given time period."""
start_year = ds.time.dt.year.min().load().item()
obs_ds = obs_ds.where(obs_ds.time.dt.year >= start_year, drop=True)
obs_ds = obs_ds.dropna("time", how="all")
return obs_ds
def shared_grid_regridder(ds, res=1, method="conservative"):
"""Add dataset-specific regridder to each InfoSet instance in info."""
# Create a 1x1 degree grid over Australia
grid = xr.Dataset(
{
"lat": (
["lat"],
np.arange(-44, -9.5 + res, res),
{"units": "degrees_north"},
),
"lon": (["lon"], np.arange(112, 154 + res, res), {"units": "degrees_east"}),
}
)
regridder = xe.Regridder(ds, grid, method)
return regridder
def multimodel_avg(info, models, da_list, func=np.median, **kwargs):
"""Regrid arrays to common grid and return the multi-model average."""
dr_list = []
for i, m in enumerate(models):
# Regrid each DataArray to the common grid using the model's regridder
dr_list.append(info[m].regridder(da_list[i]))
dr = xr.concat(dr_list, dim="model") # Concat along axis=0
if func is not None:
dr = dr.reduce(func, "model", **kwargs)
return dr
def get_stability_ci(da, method, confidence_level=0.99, n_resamples=1000, aep=1):
"""Get the confidence interval of a statistic for a lead time-sized sample.
Parameters
----------
da : xarray.DataArray
DataArray of the model data.
method : {"median", "aep"}
Method to use for the statistic.
confidence_level : float, default=0.99
Confidence level for the confidence interval.
n_resamples : int, default=1000
Number of resamples to use for the confidence interval.
aep : float, default=1
Annual exceedance probability (for the AEP method).
Returns
-------
ci : xarray.DataArray
Confidence interval of the statistic.
"""
if method == "median":
statistic = np.median
kwargs = {}
elif method == "aep":
# Pass the return period to the statistic function
statistic = eva.empirical_return_level
kwargs = dict(return_period=eva.aep_to_ari(aep))
ci = statistic_by_lead_confidence_interval(
da,
statistic,
sample_size=da.ensemble.size * da.init_date.size,
method="percentile",
n_resamples=n_resamples,
confidence_level=confidence_level,
rng=np.random.default_rng(0),
**kwargs,
)
return ci
def get_gev_mask(info, m, var_dict, test="lrt"):
"""Mask where stationary is better than nonstationary GEV model."""
var = var_dict[m]["var"]
if info[m].is_model():
if info[m].bias_correction not in ["", None]:
_bc = f"_{info[m].bias_correction}_bc"
else:
_bc = ""
gev_params_stationary_file = var_dict[m][f"gev_stationary{_bc}"]
covariate = info[m].ds["covariate"]
else:
gev_params_stationary_file = var_dict[m]["gev_stationary_obs"]
covariate = info[m].obs_ds.time.dt.year
dparams = xr.open_dataset(gev_params_stationary_file)[var]
nll = xr.apply_ufunc(
eva._gev_nllf,
dparams,
info[m].ds[var].sel(lat=dparams.lat, lon=dparams.lon),
input_core_dims=[["dparams"], [info[m].time_dim]],
output_core_dims=[[]],
vectorize=True,
dask="parallelized",
dask_gufunc_kwargs=dict(meta=(np.ndarray(1, float),)),
)
# Negative log-likelihood of stationary and nonstationary models
nll_ns = xr.apply_ufunc(
eva._gev_nllf,
info[m].ds.dparams_ns,
info[m].ds[var],
covariate,
input_core_dims=[["dparams"], [info[m].time_dim], [info[m].time_dim]],
output_core_dims=[[]],
vectorize=True,
dask="parallelized",
dask_gufunc_kwargs=dict(meta=(np.ndarray(1, float),)),
)
# Check if the nonstationary model is preferred over the stationary model
result = xr.apply_ufunc(
eva.check_gev_relative_fit,
info[m].ds[var].sel(lat=dparams.lat, lon=dparams.lon),
nll,
nll_ns.sel(lat=dparams.lat, lon=dparams.lon),
input_core_dims=[[info[m].time_dim], [], []],
output_core_dims=[[]],
vectorize=True,
dask="parallelized",
kwargs=dict(test=test, alpha=0.05, n_params=[3, 5]),
)
# True where stationary model is preferred
result = np.logical_not(result)
# pvalue = eva.check_gev_fit(da, dparams, core_dim=["sample"], test="ks")
return result
# ----------------------------------------------------------------------------
# Plotting functions
# ----------------------------------------------------------------------------
def plot_time_agg(info, var, time_agg, plot_dict):
"""Plot time-aggregated data for each model and observation dataset."""
cbar_kwargs = dict(
cmap=plot_dict["cmap"],
ticks=plot_dict["ticks"],
extend=plot_dict["cbar_extend"],
)
fig, ax = plt.subplots(3, 4, subplot_kw=dict(projection=PlateCarree()))
ax = ax.flatten()
da_list = [] # Store data arrays for the multi-model median
for i, m in enumerate(info.keys()):
da = info[m].ds[var].reduce(func_dict[time_agg], dim=info[m].time_dim)
if m in plot_dict["models"]:
i += 1 # Leave ax[1] for the multi-model median
da_list.append(da)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da,
title=f"{letters[i]} {info[m].title_name}",
hatching=info[m].pval_mask,
**cbar_kwargs,
)
# Multi-model median
i = 1
dm = multimodel_avg(info, plot_dict["models"], da_list)
fig, ax[i], cs = map_subplot(
fig, ax[i], dm, title=f"{letters[i]} Multi-model median", **cbar_kwargs
)
add_shared_colorbar(
fig,
ax,
cs,
label=plot_dict["units_label"],
**cbar_kwargs,
)
ax = extra_subplot_formatting(ax)
outfile = f"{plot_dict['fig_dir']}/{time_agg}_{plot_dict['filestem']}.png"
plt.savefig(outfile, bbox_inches="tight")
plt.show()
plt.close()
def plot_obs_anom(
info,
obs,
var,
time_agg,
metric,
covariate_base,
plot_dict,
):
"""Plot map of soft-record metric (e.g., anomaly) between model and observation."""
fig, ax = plt.subplots(3, 4, subplot_kw=dict(projection=PlateCarree()))
ax = ax.flatten()
# Plot obs time agg (not anomaly)
i = 0
da_obs = info[obs].ds[var].reduce(func_dict[time_agg], dim=info[obs].time_dim)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da_obs,
title=f"{letters[i]} Observed {time_agg} {plot_dict['metric']}",
hatching=info[obs].pval_mask,
cmap=plot_dict["cmap"],
ticks=plot_dict["ticks"],
extend=plot_dict["cbar_extend"],
)
cbar = add_inset_colorbar(fig, ax[i], cs, plot_dict["units_label"])
da_list = [] # Store data arrays for the multi-model median
for i, m in enumerate(plot_dict["models"]):
i += 2 # Leave ax[0-1] for obs & multi-model median
da, kwargs = soft_record_metric(
info[m].ds[var],
info[m].obs_ds[var],
time_agg,
metric,
plot_dict,
time_dim=info[m].time_dim,
dparams_ns=info[m].ds["dparams_ns"],
covariate_base=covariate_base,
)
da_list.append(da)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da,
title=f"{letters[i]} {info[m].title_name}",
hatching=info[m].pval_mask,
cmap=kwargs["cmap"],
ticks=kwargs["ticks"],
extend=kwargs["cbar_extend"],
vcentre=kwargs.get("vcentre", None),
)
# Multi-model median
i = 1
dm = multimodel_avg(info, plot_dict["models"], da_list)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
dm,
title=f"{letters[i]} Multi-model median",
cmap=kwargs["cmap"],
ticks=kwargs["ticks"],
extend=kwargs["cbar_extend"],
vcentre=kwargs.get("vcentre", None),
)
kwargs["cbar_label"] = kwargs["cbar_label"].replace("\n", " ")
add_shared_colorbar(
fig,
ax,
cs,
label=kwargs["cbar_label"],
ticks=kwargs["ticks"],
extend=kwargs["cbar_extend"],
tick_interval=kwargs["tick_interval"],
ticklabels=True,
)
ax = extra_subplot_formatting(ax)
# suptitle = kwargs["title"].replace("\n", " ")
# fig.suptitle(suptitle, fontsize=15)
outfile = f"{plot_dict['fig_dir']}/{time_agg}_{metric}_{plot_dict['filestem']}.png"
plt.savefig(outfile, bbox_inches="tight")
plt.show()
plt.close()
def plot_time_agg_subsampled(
info,
obs,
time_agg,
plot_dict,
resamples=1000,
):
"""Plot map of observation-sized subsample of data (sample median of time-aggregate).
Also plot the anomaly of the subsampled data minus regrided obs data.
"""
n_obs_samples = info[obs].obs_ds[info[obs].var].time.size
print(f"Number of obs samples: {n_obs_samples}")
cbar_kwargs = dict(
cmap=plot_dict["cmap"],
ticks=plot_dict["ticks"],
extend=plot_dict["cbar_extend"],
)
fig, ax = plt.subplots(3, 4, subplot_kw=dict(projection=PlateCarree()))
ax = ax.flatten()
# Plot obs time agg (not subsampled)
i = 0
da_obs = (
info[obs].ds[info[obs].var].reduce(func_dict[time_agg], dim=info[obs].time_dim)
)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da_obs,
title=f"{letters[i]} Observed {time_agg} {plot_dict['metric']}",
**cbar_kwargs,
)
da_list = [] # Store data arrays for the multi-model median & anomaly plot
for i, m in enumerate(plot_dict["models"]):
i += 2 # Leave ax[0-1] for obs and the multi-model median
da = resample_subsample(info[m], info[m].ds, time_agg, n_obs_samples, resamples)
da_list.append(da)
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da,
title=f"{letters[i]} {info[m].title_name}",
hatching=info[m].pval_mask,
**cbar_kwargs,
)
# Multi-model median
i = 1
dm = multimodel_avg(info, plot_dict["models"], da_list)
fig, ax[i], cs = map_subplot(
fig, ax[i], dm, title=f"{letters[i]} Multi-model median", **cbar_kwargs
)
add_shared_colorbar(fig, ax, cs, label=plot_dict["units_label"], **cbar_kwargs)
ax = extra_subplot_formatting(ax)
# suptitle = f"{plot_dict['metric']} {time_agg} in obs-sized subsample (median of {resamples} resamples)"
# fig.suptitle(suptitle, fontsize=15)
outfile = (
f"{plot_dict['fig_dir']}/{time_agg}_subsampled_{plot_dict['filestem']}.png"
)
plt.savefig(outfile, bbox_inches="tight")
plt.show()
plt.close()
# Plot anomaly of subsampled data minus regrided obs data
fig, ax = plt.subplots(3, 4, subplot_kw=dict(projection=PlateCarree()))
ax = ax.flatten()
cbar_kwargs = dict(
cmap=plot_dict["cmap_anom"],
ticks=plot_dict["ticks_anom"],
extend="both",
)
# Plot obs time agg (not subsampled)
i = 0
fig, ax[i], cs = map_subplot(
fig,
ax[i],
da_obs,
title=f"{letters[i]} Observed {time_agg} {plot_dict['metric']}",
hatching=info[obs].pval_mask,
cmap=plot_dict["cmap"],
ticks=plot_dict["ticks"][::2],
extend=plot_dict["cbar_extend"],
)
# Create an inset axes for the colorbar
cbar = add_inset_colorbar(fig, ax[i], cs, plot_dict["units_label"])
da_anom_list = [] # Store data arrays for the multi-model median
for i, m in enumerate(plot_dict["models"]):
da = da_list[i]
i += 2 # Leave ax[0-1] for obs and the multi-model median
da_obs_regrid = general_utils.regrid(da_obs, da)
da = da - da_obs_regrid