-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplot_metrics.py
More file actions
2168 lines (1974 loc) · 67.7 KB
/
plot_metrics.py
File metadata and controls
2168 lines (1974 loc) · 67.7 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
# Standard library
import argparse
import json
import os
import re
from datetime import datetime, timedelta
# Third-party
import cartopy.crs as ccrs
import cartopy.feature as cfeature
import matplotlib.pyplot as plt
import numpy as np
import xarray as xr
from matplotlib.ticker import FuncFormatter, MultipleLocator
# First-party
from neural_lam import constants
def read_npy_to_xarray(file_path, sea_mask, init=False):
"""Reads forecast file and reconstructs the full grid using a sea mask."""
# Get start date from filename
filename = os.path.basename(file_path)
date_str = filename.split(".")[0]
start_date = datetime.strptime(date_str[-8:], "%Y%m%d")
if init:
start_date -= timedelta(days=2)
# Load forecast
data = np.load(file_path) # (time, n_grid, n_features)
n_time, _, _ = data.shape
# Full horizontal grid dimensions
n_lat, n_lon = constants.GRID_SHAPE
# Get the indices (row, col) belonging to the sea
surface_mask = sea_mask.isel(depth=0).values
lat_idx, lon_idx = np.where(surface_mask == 1)
data_vars = {}
feature_idx = 0
# Loop over the parameters
for param_name, param_short, has_depth, unit, colormap, diverging in zip(
constants.PARAM_NAMES,
constants.PARAM_NAMES_SHORT,
constants.LEVELS,
constants.PARAM_UNITS,
constants.PARAM_COLORMAPS,
constants.DIVERGING,
):
if has_depth:
n_depths = len(constants.DEPTHS)
# Extract forecast data for this variable (n_time, n_grid, n_depths)
var_forecast = data[:, :, feature_idx : feature_idx + n_depths]
feature_idx += n_depths
# Initialize a full array (time, lat, lon, depth)
var_array = np.full(
(n_time, n_lat, n_lon, n_depths), np.nan, dtype=data.dtype
)
# Assign forecast data only where sea_mask is water at that depth
for d in range(n_depths):
mask_d = sea_mask.isel(depth=d).values # (n_lat, n_lon)
valid_indices = np.where(mask_d[lat_idx, lon_idx] == 1)[0]
if valid_indices.size > 0:
var_array[
:, lat_idx[valid_indices], lon_idx[valid_indices], d
] = var_forecast[:, valid_indices, d]
# Add variable to the dataset
data_vars[param_short] = (
("time", "latitude", "longitude", "depth"),
var_array,
)
else:
# Non-depth variable (n_time, n_grid)
var_forecast = data[:, :, feature_idx]
feature_idx += 1
# Create a full grid (time, lat, lon) and fill with forecast values
var_array = np.full(
(n_time, n_lat, n_lon), np.nan, dtype=data.dtype
)
var_array[:, lat_idx, lon_idx] = var_forecast
data_vars[param_short] = (
("time", "latitude", "longitude"),
var_array,
)
# Create coordinates
time_coords = [start_date + timedelta(days=i) for i in range(n_time)]
coords = {
"time": time_coords,
"latitude": sea_mask.latitude,
"longitude": sea_mask.longitude,
"depth": sea_mask.depth,
}
ds = xr.Dataset(data_vars, coords=coords)
# Add metadata attributes for each variable
for param_short, param_name, unit, colormap, diverging in zip(
constants.PARAM_NAMES_SHORT,
constants.PARAM_NAMES,
constants.PARAM_UNITS,
constants.PARAM_COLORMAPS,
constants.DIVERGING,
):
ds[param_short].attrs = {
"description": param_name,
"unit": unit,
"colormap": colormap,
"diverging": diverging,
}
return ds
def plot_forecast(
ds, analysis_ds, param, lead_indices, depth_index=2, model="seacast", fs=18
):
"""
Plot a stack of forecast fields and bias to analysis.
"""
unit = ds[param].attrs.get("unit", "")
cmap = ds[param].attrs.get("colormap", "viridis")
diverging = ds[param].attrs.get("diverging", False)
lons = ds["longitude"].values
lats = ds["latitude"].values
extent = [lons.min(), lons.max(), lats.min(), lats.max()]
fc_vals = []
diff_vals = []
for idx in lead_indices:
fc = ds[param].isel(time=idx)
if "depth" in fc.dims:
fc = fc.isel(depth=depth_index)
fc_vals.append(fc.values)
ana = analysis_ds[param].sel(time=ds.time[idx])
if "depth" in ana.dims:
ana = ana.isel(depth=depth_index)
diff = fc - ana
diff_vals.append(diff.values)
fc_all = np.stack(fc_vals)
diff_all = np.stack(diff_vals)
if diverging:
fc_abs_max = np.nanmax(np.abs(fc_all))
fc_vmin, fc_vmax = -fc_abs_max, fc_abs_max
else:
fc_vmin, fc_vmax = np.nanmin(fc_all), np.nanmax(fc_all)
diff_abs_max = np.nanmax(np.abs(diff_all))
diff_vmin, diff_vmax = -diff_abs_max, diff_abs_max
n_rows = len(lead_indices)
fig, axes = plt.subplots(
nrows=n_rows,
ncols=2,
figsize=(18, 3.1 * n_rows),
constrained_layout=True,
sharex=True,
sharey=True,
subplot_kw={"projection": ccrs.PlateCarree()},
)
if n_rows == 1:
axes = axes[np.newaxis, :]
for row, idx in enumerate(lead_indices):
# Forecast panel left
fc_data = ds[param].isel(time=idx)
if "depth" in fc_data.dims:
fc_data = fc_data.isel(depth=depth_index)
ax_fc = axes[row, 0]
im_fc = ax_fc.imshow(
fc_data,
origin="lower",
cmap=cmap,
extent=extent,
vmin=fc_vmin,
vmax=fc_vmax,
)
ax_fc.set_ylabel(
f"{idx+1}d", fontsize=fs, rotation=0, labelpad=7, ha="right"
)
if row == 0:
ax_fc.set_title("SeaCast", fontsize=fs)
ax_fc.coastlines(resolution="10m", linewidth=1)
ax_fc.add_feature(cfeature.LAND, facecolor="whitesmoke")
cbar_fc = fig.colorbar(
im_fc,
ax=ax_fc,
orientation="vertical",
shrink=0.8,
aspect=22,
pad=0.02,
)
cbar_fc.ax.set_ylabel(unit, fontsize=fs - 4)
cbar_fc.ax.tick_params(labelsize=fs - 4)
# Bias panel right
ana_data = analysis_ds[param].sel(time=ds.time[idx])
if "depth" in ana_data.dims:
ana_data = ana_data.isel(depth=depth_index)
diff_data = fc_data - ana_data
ax_diff = axes[row, 1]
im_diff = ax_diff.imshow(
diff_data,
origin="lower",
cmap="RdBu_r",
extent=extent,
vmin=diff_vmin,
vmax=diff_vmax,
)
if row == 0:
ax_diff.set_title("Bias", fontsize=fs)
ax_diff.coastlines(resolution="10m", linewidth=1)
ax_diff.add_feature(cfeature.LAND, facecolor="whitesmoke")
cbar_diff = fig.colorbar(
im_diff,
ax=ax_diff,
orientation="vertical",
shrink=0.8,
aspect=22,
pad=0.02,
)
cbar_diff.ax.set_ylabel(unit)
cbar_diff.ax.set_ylabel(unit, fontsize=fs - 4)
cbar_diff.ax.tick_params(labelsize=fs - 4)
for ax in axes.ravel():
ax.set_xticks([])
ax.set_yticks([])
save_dir = os.path.join("figures", "metrics", "forecast")
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, f"{model}_{param}.png")
fig.savefig(save_path, bbox_inches="tight")
fig.savefig(
os.path.join("figures", "results", f"{model}_{param}.pdf"),
bbox_inches="tight",
)
plt.close(fig)
def plot_forecast_vertical(
ds,
analysis_ds,
param,
lead_indices,
direction="zonal",
suffix="forecast",
fs=14,
):
"""
Plot average over zonal or meridional direction.
"""
unit = ds[param].attrs.get("unit", "")
cmap = ds[param].attrs.get("colormap", "viridis")
cmap.set_bad(color="lightgray")
cmap_bias = plt.get_cmap("RdBu_r").copy()
cmap_bias.set_bad("lightgray")
diverging = ds[param].attrs.get("diverging", False)
if direction == "zonal":
horiz_dim = "longitude"
x_coord_name = "latitude"
xlabel = "Latitude (°)"
fig_width = 9
locator = MultipleLocator(3)
elif direction == "meridional":
horiz_dim = "latitude"
x_coord_name = "longitude"
xlabel = "Longitude (°)"
fig_width = 19
locator = MultipleLocator(5)
else:
raise ValueError("direction must be 'zonal' or 'meridional'")
x_coord = ds[x_coord_name].values
depth_vals = ds["depth"].values
n_depths = len(depth_vals)
y_positions = np.arange(n_depths)
yticklabels = [str(int(d)) for d in depth_vals]
# Precompute forecast and bias sections for each lead time
fc_sections = []
bias_sections = []
for idx in lead_indices:
fc = ds[param].isel(time=idx)
ana = analysis_ds[param].sel(time=ds.time[idx])
# Average horizontally
fc_sec = fc.mean(dim=horiz_dim, skipna=True)
ana_sec = ana.mean(dim=horiz_dim, skipna=True)
# Ensure depth is the first dimension
if "depth" in fc_sec.dims and x_coord_name in fc_sec.dims:
fc_sec = fc_sec.transpose("depth", x_coord_name)
ana_sec = ana_sec.transpose("depth", x_coord_name)
fc_sections.append(fc_sec.values) # (n_depths, len(x_coord))
bias_sections.append(fc_sec.values - ana_sec.values)
# Determine global color limits
fc_all = np.concatenate([s.flatten() for s in fc_sections])
bias_all = np.concatenate([s.flatten() for s in bias_sections])
if diverging:
fc_abs_max = np.nanmax(np.abs(fc_all))
fc_vmin, fc_vmax = -fc_abs_max, fc_abs_max
else:
fc_vmin, fc_vmax = np.nanmin(fc_all), np.nanmax(fc_all)
bias_abs_max = np.nanmax(np.abs(bias_all))
bias_vmin, bias_vmax = -bias_abs_max, bias_abs_max
n_rows = len(lead_indices)
n_cols = 2
fig, axes = plt.subplots(
nrows=n_rows,
ncols=n_cols,
figsize=(fig_width, 4 * n_rows),
constrained_layout=True,
sharex=True,
sharey=True,
)
extent = [x_coord.min(), x_coord.max(), n_depths - 1, 0]
for i, idx in enumerate(lead_indices):
ax_fc = axes[i, 0]
im_fc = ax_fc.imshow(
fc_sections[i],
origin="upper",
cmap=cmap,
vmin=fc_vmin,
vmax=fc_vmax,
extent=extent,
)
ax_fc.set_title(
f"Forecasted {constants.PLOT_NAMES_MAP[param]}, day {idx+1}",
fontsize=fs,
)
ax_fc.set_ylabel("Depth (m)", fontsize=fs)
ax_fc.xaxis.set_major_locator(locator)
if i == n_rows - 1:
ax_fc.set_xlabel(xlabel, fontsize=fs)
else:
ax_fc.set_xticklabels([])
ax_fc.set_yticks(y_positions)
ax_fc.set_yticklabels(yticklabels)
cbar_fc = fig.colorbar(
im_fc,
ax=ax_fc,
orientation="vertical",
shrink=0.855,
aspect=25,
pad=0.02,
)
cbar_fc.ax.set_ylabel(unit)
# Bias panel
ax_bias = axes[i, 1]
im_bias = ax_bias.imshow(
bias_sections[i],
origin="upper",
cmap=cmap_bias,
vmin=bias_vmin,
vmax=bias_vmax,
extent=extent,
)
ax_bias.set_title(
f"Bias of {constants.PLOT_NAMES_MAP[param]}, day {idx+1}",
fontsize=fs,
)
ax_bias.xaxis.set_major_locator(locator)
if i == n_rows - 1:
ax_bias.set_xlabel(xlabel, fontsize=fs)
else:
ax_bias.set_xticklabels([])
ax_bias.set_yticks(y_positions)
ax_bias.set_yticklabels(yticklabels)
cbar_bias = fig.colorbar(
im_bias,
ax=ax_bias,
orientation="vertical",
shrink=0.855,
aspect=25,
pad=0.02,
)
cbar_bias.ax.set_ylabel(unit)
formatter = FuncFormatter(lambda x, pos: f"{x:.0f}")
for ax in axes[-1, :]:
ax.xaxis.set_major_formatter(formatter)
save_dir = os.path.join("figures", "metrics", "forecast_vertical")
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, f"{param}_{direction}_{suffix}.png")
fig.savefig(save_path, bbox_inches="tight")
plt.close(fig)
def plot_group_bias(var, model, sea_mask, dataset="mediterranean"):
"""
Plot group bias for a given variable.
"""
bias_path = os.path.join(
"data", dataset, "metrics", model, "group_bias.npy"
)
data = np.load(bias_path, allow_pickle=True).item()
if var == "zos":
bias = data[var]
else:
bias = data[var] # (4, n_grid)
unit = constants.PARAM_UNITS[constants.PARAM_NAMES_SHORT.index(var)]
sea_surface_mask = sea_mask.isel(depth=0) # (lat, lon)
n_time, _ = bias.shape
# Reconstruct full grid
full_grid_bias = np.full((n_time, *sea_surface_mask.shape), np.nan)
for t in range(n_time):
full_grid_bias[t][sea_surface_mask == 1] = bias[t]
lon = sea_mask.longitude.values
lat = sea_mask.latitude.values
lon2d, lat2d = np.meshgrid(lon, lat)
extent = constants.GRID_LIMITS
fig, axes = plt.subplots(
2,
2,
figsize=(16, 6),
subplot_kw={"projection": ccrs.PlateCarree()},
constrained_layout=True,
sharex=True,
sharey=True,
)
axes = axes.flatten()
vabs = np.nanmax(np.abs(full_grid_bias))
if var == "so":
vabs = np.percentile(
np.abs(full_grid_bias[~np.isnan(full_grid_bias)]), 99.7
)
lead_days = [1, 5, 10, 15]
for i, ax in enumerate(axes):
pcm = ax.pcolormesh(
lon2d,
lat2d,
full_grid_bias[i],
cmap="RdBu_r",
vmin=-vabs,
vmax=vabs,
shading="auto",
)
ax.set_title(f"{var} t={lead_days[i]}")
ax.set_extent(extent, crs=ccrs.PlateCarree())
ax.coastlines(resolution="10m", linewidth=0.5)
ax.set_xticks(
np.linspace(extent[0], extent[1], 5), crs=ccrs.PlateCarree()
)
ax.set_yticks(
np.linspace(extent[2], extent[3], 5), crs=ccrs.PlateCarree()
)
ax.xaxis.set_major_locator(MultipleLocator(5))
ax.yaxis.set_major_locator(MultipleLocator(3))
ax.tick_params(labelsize=8)
if i % 2 == 0:
ax.set_ylabel("Latitude (°)", fontsize=9)
if i // 2 == 1:
ax.set_xlabel("Longitude (°)", fontsize=9)
# Shared colorbar
if var == "so":
extend = "both"
else:
extend = "neither"
cbar = fig.colorbar(
pcm,
ax=axes,
orientation="vertical",
shrink=0.6,
extend=extend,
pad=0.02,
)
cbar.set_label(f"Bias ({unit})", fontsize=10)
save_dir = os.path.join("figures", "metrics", "group_bias")
os.makedirs(save_dir, exist_ok=True)
save_path = os.path.join(save_dir, f"{model}_{var}.png")
plt.savefig(save_path, dpi=150)
plt.close(fig)
def load_metric_std_steps(json_path, n_steps=15, metric="rmse"):
"""
Loads a JSON file and returns
- metric_matrix (n_steps, d_features)
- ci_data, dict with ci_lower and ci_upper, each (n_steps, d_features)
"""
with open(json_path, "r", encoding="utf-8") as f:
data = json.load(f)
param_names = constants.EXP_PARAM_NAMES_SHORT
n_features = len(param_names)
metric_matrix = np.empty((n_steps, n_features))
ci_lower_matrix = np.empty((n_steps, n_features))
ci_upper_matrix = np.empty((n_steps, n_features))
metric_matrix[:] = np.nan
ci_lower_matrix[:] = np.nan
ci_upper_matrix[:] = np.nan
for step in range(n_steps):
step_key = str(step)
if step_key in data:
cycle_data = data[step_key]
for j, param in enumerate(param_names):
if param in cycle_data:
metric_matrix[step, j] = cycle_data[param][metric]
ci_lower_matrix[step, j] = cycle_data[param]["ci_lower"]
ci_upper_matrix[step, j] = cycle_data[param]["ci_upper"]
else:
metric_matrix[step, j] = np.nan
ci_lower_matrix[step, j] = np.nan
ci_upper_matrix[step, j] = np.nan
else:
metric_matrix[step, :] = np.nan
ci_lower_matrix[step, :] = np.nan
ci_upper_matrix[step, :] = np.nan
ci_data = {"ci_lower": ci_lower_matrix, "ci_upper": ci_upper_matrix}
return metric_matrix, ci_data
def plot_metric_by_depth(
variable,
output_dir,
metric_std_all,
model_labels,
metric="rmse",
n_steps=15,
depths=None,
fs=12,
fill_between=False,
color_map=None,
legend_ncol=None,
):
"""
Create one figure for a given variable with a grid of subplots.
Each subplot shows the chosen metric vs. lead time at a depth level.
"""
os.makedirs(output_dir, exist_ok=True)
param_names = constants.EXP_PARAM_NAMES_SHORT
var_indices = []
depths_list = []
for i, pname in enumerate(param_names):
if pname.startswith(variable + "_"):
d_val = int(pname.split("_")[1])
var_indices.append(i)
depths_list.append(d_val)
unit = constants.PARAM_UNITS[constants.PARAM_NAMES_SHORT.index(variable)]
# Sort by depth (ascending)
sorted_pairs = sorted(zip(depths_list, var_indices), key=lambda x: x[0])
sorted_depths, sorted_var_indices = zip(*sorted_pairs)
# Use only every other depth
sorted_depths = sorted_depths[::2]
sorted_var_indices = sorted_var_indices[::2]
if depths is None:
depths = list(sorted_depths)
n_subplots = len(sorted_depths)
ncols = 3
nrows = int(np.ceil(n_subplots / ncols))
fig, axes = plt.subplots(
nrows=nrows,
ncols=ncols,
figsize=(ncols * 3, nrows * 2.6),
sharex=True,
constrained_layout=True,
)
fig.set_constrained_layout_pads(hspace=0.1)
axes = axes.flatten()
x = np.arange(1, n_steps + 1)
# One subplot per depth
for i in range(n_subplots):
ax = axes[i]
row_index = i // ncols
col_index = i % ncols
for model, (metric_matrix, ci_data) in metric_std_all.items():
ax.axvline(x=10, color="lightgray", ls="--", zorder=0)
# Get metric values for all lead times at this depth
y = metric_matrix[:, sorted_var_indices[i]]
if fill_between:
ci_lower = ci_data["ci_lower"][:, sorted_var_indices[i]]
ci_upper = ci_data["ci_upper"][:, sorted_var_indices[i]]
(line,) = ax.plot(
x,
y,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
ax.fill_between(
x, ci_lower, ci_upper, color=line.get_color(), alpha=0.3
)
else:
ax.plot(
x,
y,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
ax.set_xticks(np.arange(1, n_steps + 1), minor=True)
major_ticks = range(1, 16, 2)
ax.set_xticks(major_ticks, minor=False)
ax.set_xticklabels(major_ticks)
ax.tick_params(axis="both", which="major", labelsize=fs)
letter = chr(97 + i)
var_name = constants.PLOT_NAMES_MAP[variable]
ax.set_title(
f"{letter}) {var_name}, {sorted_depths[i]}m",
fontsize=fs,
)
if row_index == nrows - 1:
ax.set_xlabel("Lead time (days)", fontsize=fs)
if col_index == 0:
if metric == "rmse":
ax.set_ylabel(f"{metric.upper()} ({unit})", fontsize=fs)
else:
ax.set_ylabel(metric.upper(), fontsize=fs)
# Create a common legend
handles, labels = axes[0].get_legend_handles_labels()
if legend_ncol is None:
legend_ncol = len(metric_std_all)
fig.legend(
handles,
labels,
loc="upper center",
bbox_to_anchor=(0.52, -0.02),
ncol=legend_ncol,
fontsize=fs,
frameon=False,
)
save_path = os.path.join(output_dir, f"{variable}_{metric}.png")
fig.savefig(save_path, bbox_inches="tight")
pdf_name = f"{variable}_{metric}_{output_dir.split('_')[-1]}.pdf"
fig.savefig(
os.path.join("figures", "results", pdf_name), bbox_inches="tight"
)
plt.close(fig)
def plot_metric_single(
variable,
metric_std_all,
model_labels,
metric="rmse",
n_steps=15,
fs=12,
output_dir="zos_metric_plots",
fill_between=False,
color_map=None,
legend_ncol=None,
):
"""
Plot the chosen metric vs. lead time.
"""
os.makedirs(output_dir, exist_ok=True)
param_names = constants.EXP_PARAM_NAMES_SHORT
var_idx = param_names.index(variable)
unit = constants.EXP_PARAM_UNITS[var_idx]
x = np.arange(1, n_steps + 1)
plt.figure(figsize=(6, 5))
plt.axvline(x=10, color="lightgray", ls="--", zorder=0)
for model, (metric_matrix, ci_data) in metric_std_all.items():
y = metric_matrix[:, var_idx]
if fill_between:
ci_lower = ci_data["ci_lower"][:, var_idx]
ci_upper = ci_data["ci_upper"][:, var_idx]
(line,) = plt.plot(
x,
y,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
plt.fill_between(
x, ci_lower, ci_upper, color=line.get_color(), alpha=0.3
)
else:
plt.plot(
x,
y,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
plt.xlabel("Lead time (days)", fontsize=fs)
if metric == "rmse":
plt.ylabel(f"{metric.upper()} ({unit})", fontsize=fs)
else:
plt.ylabel(metric.upper(), fontsize=fs)
ax = plt.gca()
ax.set_xticks(np.arange(1, n_steps + 1), minor=True)
major_ticks = range(1, 16, 2)
ax.set_xticks(major_ticks, minor=False)
ax.set_xticklabels(major_ticks)
ax.tick_params(axis="both", which="major", labelsize=fs)
handles, labels = ax.get_legend_handles_labels()
if legend_ncol is None:
legend_ncol = len(metric_std_all)
plt.legend(
handles,
labels,
loc="upper center",
bbox_to_anchor=(0.52, -0.15),
ncol=legend_ncol,
fontsize=fs,
frameon=False,
)
save_path = os.path.join(output_dir, f"{variable}_{metric}.png")
plt.savefig(save_path, bbox_inches="tight")
plt.close()
def plot_avg_group_metric(
agg_group_metrics_dict,
metric="rmse",
n_steps=15,
fs=12,
output_dir="avg_group_metric",
fill_between=True,
model_labels=None,
color_map=None,
legend_ncol=None,
):
"""
Plot aggregated average group metrics vs. lead time.
"""
os.makedirs(output_dir, exist_ok=True)
fig, axes = plt.subplots(
2, 2, figsize=(2 * 3.2, 2 * 2.8), constrained_layout=True
)
fig.set_constrained_layout_pads(hspace=0.1)
axes = axes.flatten()
x = np.arange(1, n_steps + 1)
groups = ["uo", "vo", "so", "thetao"]
# Loop over the four groups
for i, group in enumerate(groups):
ax = axes[i]
ax.axvline(x=10, color="lightgray", ls="--", zorder=0)
unit = constants.PARAM_UNITS[constants.PARAM_NAMES_SHORT.index(group)]
for model, group_data in agg_group_metrics_dict.items():
y = np.array(group_data[group][metric])
ci_lower = np.array(group_data[group]["ci_lower"])
ci_upper = np.array(group_data[group]["ci_upper"])
steps = np.arange(1, len(y) + 1)
(line,) = ax.plot(
steps,
y,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model) if model_labels else model,
color=color_map[model],
)
if fill_between:
ax.fill_between(
steps, ci_lower, ci_upper, color=line.get_color(), alpha=0.3
)
ax.set_title(
f"{chr(97+i)}) {constants.PLOT_NAMES_MAP[group]}", fontsize=fs
)
ax.set_xticks(x, minor=True)
major_ticks = range(1, 16, 2)
ax.set_xticks(major_ticks, minor=False)
ax.set_xticklabels(major_ticks)
ax.set_xlabel("Lead time (days)", fontsize=fs)
ax.tick_params(axis="both", which="major", labelsize=fs)
if metric == "rmse":
ax.set_ylabel(f"{metric.upper()} ({unit})", fontsize=fs)
else:
ax.set_ylabel(metric.upper(), fontsize=fs)
ax.tick_params(labelsize=fs)
# Create a common legend across all subplots.
handles, labels = ax.get_legend_handles_labels()
if legend_ncol is None:
legend_ncol = len(agg_group_metrics_dict)
fig.legend(
handles,
labels,
loc="upper center",
bbox_to_anchor=(0.52, -0.05),
ncol=legend_ncol,
fontsize=fs,
frameon=False,
)
save_path = os.path.join(output_dir, f"{metric}.png")
fig.savefig(save_path, bbox_inches="tight")
save_path = os.path.join("figures", "results", f"{metric}_avg.pdf")
fig.savefig(save_path, bbox_inches="tight")
plt.close(fig)
def plot_norm_rmse_diff_by_depth(
variable,
baseline_json,
model_jsons,
baseline_label,
model_labels,
output_dir,
n_steps=15,
fs=12,
fill_between=False,
color_map=None,
legend_ncol=None,
):
"""
Plot normalized RMSE diff computed as
(model_rmse - baseline_rmse) / baseline_rmse.
"""
os.makedirs(output_dir, exist_ok=True)
# Extract indices and depth values for the chosen variable
param_names = constants.EXP_PARAM_NAMES_SHORT
var_indices = []
depths_list = []
for i, pname in enumerate(param_names):
if pname.startswith(variable + "_"):
d_val = int(pname.split("_")[1])
var_indices.append(i)
depths_list.append(d_val)
# Sort by depth (ascending)
sorted_pairs = sorted(zip(depths_list, var_indices), key=lambda x: x[0])
sorted_depths, sorted_var_indices = zip(*sorted_pairs)
# Use only every other depth
sorted_depths = sorted_depths[::2]
sorted_var_indices = sorted_var_indices[::2]
n_subplots = len(sorted_depths)
ncols = 3
nrows = int(np.ceil(n_subplots / ncols))
# Create the figure grid
fig, axes = plt.subplots(
nrows=nrows,
ncols=ncols,
figsize=(ncols * 3, nrows * 2.7),
sharex=True,
sharey=True,
constrained_layout=True,
)
fig.set_constrained_layout_pads(hspace=0.1)
axes = axes.flatten()
x = np.arange(1, n_steps + 1)
# Load baseline metrics for the variable
baseline_metric, baseline_ci = load_metric_std_steps(
baseline_json, n_steps=n_steps, metric="rmse"
)
# Loop over each depth
for i in range(n_subplots):
ax = axes[i]
ax.axvline(x=10, color="lightgray", ls="--", zorder=0)
# Extract the baseline values for this depth
baseline_vals = baseline_metric[:, sorted_var_indices[i]]
if fill_between:
baseline_ci_lower = baseline_ci["ci_lower"][
:, sorted_var_indices[i]
]
baseline_ci_upper = baseline_ci["ci_upper"][
:, sorted_var_indices[i]
]
# For each model, compute the normalized difference
for model, json_path in model_jsons.items():
model_metric, model_ci = load_metric_std_steps(
json_path, n_steps=n_steps, metric="rmse"
)
model_vals = model_metric[:, sorted_var_indices[i]]
# Compute normalized difference
norm_diff = (model_vals - baseline_vals) / baseline_vals
if fill_between:
model_ci_lower = model_ci["ci_lower"][:, sorted_var_indices[i]]
model_ci_upper = model_ci["ci_upper"][:, sorted_var_indices[i]]
# Compute normalized CI bounds conservatively
norm_diff_lower = (
model_ci_lower - baseline_ci_upper
) / baseline_vals
norm_diff_upper = (
model_ci_upper - baseline_ci_lower
) / baseline_vals
(line,) = ax.plot(
x,
100 * norm_diff,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
ax.fill_between(
x,
100 * norm_diff_lower,
100 * norm_diff_upper,
color=line.get_color(),
alpha=0.3,
)
else:
ax.plot(
x,
100 * norm_diff,
linewidth=2,
linestyle="-",
label=model_labels.get(model, model),
color=color_map[model],
)
# Plot the baseline horizontal line
ax.plot(
x,
np.zeros_like(x),
linestyle="-",
linewidth=2,
label=model_labels[baseline_label],
color=color_map[baseline_label],
zorder=0,
)
ax.set_xticks(np.arange(1, n_steps + 1), minor=True)
major_ticks = range(1, 16, 2)
ax.set_xticks(major_ticks, minor=False)
ax.set_xticklabels(major_ticks)
ax.tick_params(axis="both", which="major", labelsize=fs)
letter = chr(97 + i)
var_name = constants.PLOT_NAMES_MAP[variable]
ax.set_title(
f"{letter}) {var_name}, {sorted_depths[i]}m",
fontsize=fs,
)
if (i // ncols) == nrows - 1:
ax.set_xlabel("Lead time (days)", fontsize=fs)
if (i % ncols) == 0:
ax.set_ylabel("Norm. RMSE diff. (%)", fontsize=fs)
handles, labels = axes[0].get_legend_handles_labels()
if legend_ncol is None:
legend_ncol = len(model_jsons) + 1
fig.legend(
handles,
labels,
loc="upper center",
bbox_to_anchor=(0.52, -0.02),
ncol=legend_ncol,
fontsize=fs,
frameon=False,
)
handles, labels = axes[0].get_legend_handles_labels()