"""Annual (calendar-year) mass balance of the model submissions against the GlaMBIE-1 consensus, globally and per region. Usage: python plot_annual_mb.py Output: plots/annual_mb_{mwe,gt}.png and plots/annual_mb.csv """ import glob import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt from matplotlib.lines import Line2D from matplotlib.patches import Patch import numpy as np import pandas as pd from plot_overview import DATA, DATASETS, G1, OUT, REGIONS, INK, MUTED, style_axis # Climate-driven model runs only (WGMS-DUS monthly is downscaled observations, see context.md 6.1) MODELS = ['oggm_fix', 'oggm_spin', 'fujita', 'rounce', 'huss', 'uio'] YEARS = (1976, 2025) def annual(rid, key): """Calendar-year totals (m w.e. and Gt, own reported area) for complete years only.""" f = os.path.join(DATA, f'{REGIONS[rid][0]}_{DATASETS[key][0]}.csv') if not os.path.exists(f): return None df = pd.read_csv(f, parse_dates=['start_date']) area = 0.5 * (df.glacier_area_reference_start + df.glacier_area_reference_end) df = df.assign(year=df.start_date.dt.year, gt=df.glacier_change_observed * area / 1000., area=area) g = df.groupby('year').agg(mwe=('glacier_change_observed', 'sum'), gt=('gt', 'sum'), area=('area', 'mean'), n=('gt', 'size')) g = g[g.n == 12].drop(columns='n') return g.loc[YEARS[0]:YEARS[1]] def glambie1(rid): g = pd.read_csv(glob.glob(os.path.join(G1, f'{rid}_*.csv'))[0]) g.index = g.start_dates.round().astype(int) return g.rename(columns={'combined_mwe': 'mwe', 'combined_mwe_errors': 'mwe_err', 'combined_gt': 'gt', 'combined_gt_errors': 'gt_err'}) def figure_global(gdata, x0=2000): """Global annual balance, Gt and m w.e. side by side, from x0.""" g1 = glambie1(0) fig, axes = plt.subplots(1, 2, figsize=(15, 6.3)) for ax, (unit, ulabel) in zip(axes, (('gt', 'Gt per year'), ('mwe', 'm w.e. per year'))): ax.fill_between(g1.index, g1[unit] - g1[unit + '_err'], g1[unit] + g1[unit + '_err'], color='#0b0b0b', alpha=0.12, lw=0, zorder=2) for k, a in gdata.items(): a = a.loc[x0:] _, lab, c, ls, lw, z = DATASETS[k] ax.plot(a.index, a[unit], color=c, ls=ls, lw=1.6, zorder=z, marker='o', ms=3.5, label=lab) ax.plot(g1.index, g1[unit], color='#0b0b0b', lw=2.4, zorder=9, marker='o', ms=4, label='GlaMBIE-1 consensus (2000-2023)') style_axis(ax) ax.tick_params(labelsize=10) ax.set_xlim(x0 - 0.5, YEARS[1] + 0.5) ax.set_title(ulabel, fontsize=11, color=INK, loc='left') h, l = axes[0].get_legend_handles_labels() h.append(Patch(color='#0b0b0b', alpha=0.12, lw=0)); l.append('GlaMBIE-1 annual uncertainty') fig.legend(h, l, loc='lower center', ncol=4, frameon=False, fontsize=10) fig.suptitle(f'Global annual mass balance, {x0}-{YEARS[1]}: model submissions vs GlaMBIE-1', x=0.012, y=0.985, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.935, "Calendar years. Models with all 19 regions; Gt from each model's own reported area, " 'm w.e. = total Gt over total own area.', fontsize=9.5, color=MUTED, ha='left') fig.tight_layout(rect=(0, 0.1, 1, 0.925)) fig.savefig(os.path.join(OUT, f'annual_mb_global_{x0}-{YEARS[1]}.png'), dpi=140, facecolor='white') plt.close(fig) for k, a in gdata.items(): print(k, 'Gt/yr', {y: f"{a['gt'].get(y, np.nan):.0f}" for y in (2019, 2022, 2023, 2024, 2025)}) print('G1 Gt/yr', {y: f"{g1['gt'].get(y, np.nan):.0f}" for y in (2019, 2022, 2023)}) def main(): data = {rid: {k: annual(rid, k) for k in MODELS} for rid in REGIONS} # global: only models with all 19 regions; Gt summed, m w.e. = total Gt over total own area glob_ = {} for k in MODELS: parts = [data[r][k] for r in REGIONS] if any(p is None for p in parts): continue yrs = sorted(set.intersection(*[set(p.index) for p in parts])) gt = sum(p.loc[yrs, 'gt'] for p in parts) area = sum(p.loc[yrs, 'area'] for p in parts) glob_[k] = pd.DataFrame({'gt': gt, 'mwe': gt / area * 1000., 'area': area}) data[0] = glob_ names = {0: (None, 'Global (models with all 19 regions)'), **REGIONS} rows = [] for (unit, ulabel), (x0, x1, sfx) in [(u, p) for p in ((YEARS[0], YEARS[1], ''), (2000, YEARS[1], '_2000-2025')) for u in (('mwe', 'm w.e. per year'), ('gt', 'Gt per year'))]: fig, axes = plt.subplots(4, 5, figsize=(17, 12.5)) for ax, rid in zip(axes.ravel(), names): g1 = glambie1(rid) ax.fill_between(g1.index, g1[unit] - g1[unit + '_err'], g1[unit] + g1[unit + '_err'], step=None, color='#0b0b0b', alpha=0.12, lw=0, zorder=2) for k, a in data[rid].items(): if a is None: continue _, _, c, ls, lw, z = DATASETS[k] ax.plot(a.index, a[unit], color=c, ls=ls, lw=1.2 if not sfx else 1.5, zorder=z, marker='o' if sfx else None, ms=2.5) ax.plot(g1.index, g1[unit], color='#0b0b0b', lw=2, zorder=9, marker='o', ms=2.5) style_axis(ax) ax.set_xlim(x0 - 0.5 if sfx else x0, x1 + 0.5 if sfx else x1) ax.set_title(f'{rid} {names[rid][1]}' if rid else names[rid][1], fontsize=9.5, color=INK, loc='left', fontweight='bold' if rid == 0 else 'normal') if unit == 'mwe' and not sfx: for k, a in data[rid].items(): if a is None: continue common = a.index.intersection(g1.index) if len(common) < 5: continue rows.append(dict(rid=rid, region=names[rid][0] or 'global', dataset=k, n_years=len(common), corr_g1=a.loc[common, 'mwe'].corr(g1.loc[common, 'mwe']), bias_g1=(a.loc[common, 'mwe'] - g1.loc[common, 'mwe']).mean(), rmse_g1=np.sqrt(((a.loc[common, 'mwe'] - g1.loc[common, 'mwe']) ** 2).mean()), sd_model=a.loc[common, 'mwe'].std(), sd_g1=g1.loc[common, 'mwe'].std(), g1_err_mean=g1.loc[common, 'mwe_err'].mean())) fig.suptitle(f'Annual mass balance: model submissions vs GlaMBIE-1, in {ulabel}', x=0.012, y=0.992, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.968, 'Calendar years, complete years only. ' + ("Gt from each dataset's own reported area. " if unit == 'gt' else 'Global m w.e. = total Gt over total own area. ') + 'GlaMBIE-1 band: its annual uncertainty. Independent y-axis per panel.', fontsize=9.5, color=MUTED, ha='left') h = [Line2D([], [], color='#0b0b0b', lw=2, marker='o', ms=3, label='GlaMBIE-1 consensus (2000-2023)'), Patch(color='#0b0b0b', alpha=0.12, lw=0, label='GlaMBIE-1 annual uncertainty')] h += [Line2D([], [], color=DATASETS[k][2], ls=DATASETS[k][3], lw=1.4, label=DATASETS[k][1]) for k in MODELS] fig.legend(handles=h, loc='lower center', ncol=4, frameon=False, fontsize=9.5) fig.tight_layout(rect=(0, 0.06, 1, 0.962)) fig.savefig(os.path.join(OUT, f'annual_mb_{unit}{sfx}.png'), dpi=130, facecolor='white') plt.close(fig) figure_global(data[0]) t = pd.DataFrame(rows) t.to_csv(os.path.join(OUT, 'annual_mb_vs_glambie1.csv'), index=False) pd.set_option('display.width', 250) print('global:'); print(t[t.rid == 0].round(3).to_string(index=False)) print('\ncorrelation with GlaMBIE-1 (calendar years 2000-2023), per region:') print(t[t.rid > 0].pivot(index=['rid', 'region'], columns='dataset', values='corr_g1').round(2).to_string()) print('\nmedian over regions:'); print(t[t.rid > 0].groupby('dataset')[['corr_g1', 'bias_g1', 'rmse_g1', 'sd_model', 'sd_g1', 'g1_err_mean']].median().round(3).to_string()) if __name__ == '__main__': main()