"""Overview plots of the GlaMBIE-2 submissions: cumulative mass change per region and globally, for the full period and against the GlaMBIE-1 consensus (2000-2023). Usage: python plot_overview.py Output: plots/*.png next to this script. """ import glob import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd HERE = os.path.dirname(os.path.abspath(__file__)) DATA = os.path.join(HERE, 'glambie2_submitted_data') G1 = os.path.join(HERE, 'glambie1_results', 'glambie_results_20240716', 'calendar_years') OUT = os.path.join(HERE, 'plots') REGIONS = {1: ('ala', 'Alaska'), 2: ('wna', 'W Canada & US'), 3: ('acn', 'Arctic Canada N'), 4: ('acs', 'Arctic Canada S'), 5: ('grl', 'Greenland periph.'), 6: ('isl', 'Iceland'), 7: ('sjm', 'Svalbard'), 8: ('sca', 'Scandinavia'), 9: ('rua', 'Russian Arctic'), 10: ('asn', 'North Asia'), 11: ('ceu', 'Central Europe'), 12: ('cau', 'Caucasus & Mid. East'), 13: ('asc', 'Central Asia'), 14: ('asw', 'South Asia W'), 15: ('ase', 'South Asia E'), 16: ('trp', 'Low latitudes'), 17: ('san', 'Southern Andes'), 18: ('nzl', 'New Zealand'), 19: ('ant', 'Antarctic & subant.')} # key: (file suffix, legend label, color, linestyle, linewidth, zorder) # Climate-driven models get a hue; observation-based series are neutral; the two OGGM runs share a hue. DATASETS = { 'dus_comb': ('combined_wgms-dus_combined', 'WGMS-DUS combined (obs, annual)', '#52514c', '-', 1.8, 5), 'ethz': ('combined_ethz_extended', 'ETHZ extended (obs + GloGEM)', '#8f8e86', '--', 1.6, 5), 'dus_mon': ('model_wgms-dus_monthly', 'WGMS-DUS monthly (downscaled obs)', '#e87ba4', '-', 0.8, 4), 'oggm_fix': ('model_oggm_v17a_fixedgeom', 'OGGM v17a fixed geometry', '#2a78d6', '-', 1.6, 7), 'oggm_spin': ('model_oggm_v17a_spinupgeom', 'OGGM v17a spinup geometry', '#2a78d6', '--', 1.6, 7), 'fujita': ('model_fujita_et_al.', 'Fujita et al. (GLIMB)', '#eb6834', '-', 1.4, 6), 'rounce': ('model_rounce_et_al', 'Rounce et al. (PyGEM)', '#1baf7a', '-', 1.4, 6), 'huss': ('model_huss_model', 'Huss model (GloGEM)', '#eda100', '-', 1.4, 6), 'uio': ('model_uiocryogrid_rgi7', 'UiO CryoGrid (CARRA, 1991+)', '#6250d6', '-', 1.4, 6), } G1_STYLE = dict(color='#0b0b0b', lw=2.2, zorder=9) INK, MUTED, GRID = '#0b0b0b', '#6f6e68', '#e4e3df' def load_cumulative(rid, key): """Cumulative change at each row's end_date (plus a zero at the first start_date), in m w.e. and Gt. Gt uses each dataset's own reported area for that row (mean of start and end reference area). """ 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', 'end_date']) area = 0.5 * (df.glacier_area_reference_start + df.glacier_area_reference_end) idx = pd.DatetimeIndex([df.start_date.iloc[0]]).append(pd.DatetimeIndex(df.end_date)) out = pd.DataFrame({'mwe': np.r_[0, df.glacier_change_observed.cumsum()], 'gt': np.r_[0, (df.glacier_change_observed * area / 1000.).cumsum()]}, index=idx) return out def load_glambie1(rid): """GlaMBIE-1 calendar-year consensus as cumulative series from 2000-01-01 (rid 0 = global).""" f = glob.glob(os.path.join(G1, f'{rid}_*.csv'))[0] g = pd.read_csv(f) idx = pd.to_datetime([f'{int(round(y))}-01-01' for y in np.r_[g.start_dates.iloc[0], g.end_dates]]) out = pd.DataFrame(index=idx) for u, c in (('mwe', 'combined_mwe'), ('gt', 'combined_gt')): out[u] = np.r_[0, g[c].cumsum()] # Annual errors summed in quadrature: assumes independent years, so a lower bound on the # true cumulative uncertainty. out[u + '_err'] = np.r_[0, np.sqrt((g[c + '_errors'] ** 2).cumsum())] return out def at(s, date): """Value of a cumulative series at `date`, linearly interpolated; NaN outside its range.""" date = pd.Timestamp(date) if date < s.index[0] or date > s.index[-1]: return np.nan return np.interp(date.value, s.index.asi8, s.values) def anchored(series, t0): """Shift every series to zero at t0. A series that starts after t0 is instead tied to the median of the others at its own first date, so it is not drawn as if it started from zero.""" out, late = {}, [] for k, s in series.items(): v = at(s, t0) if np.isnan(v): late.append(k) else: out[k] = s[s.index >= pd.Timestamp(t0) - pd.Timedelta(days=366)] - v for k in late: s = series[k] ref = np.nanmedian([at(o, s.index[0]) for o in out.values()]) if out else 0. out[k] = s - s.iloc[0] + (0. if np.isnan(ref) else ref) return out, late def global_sum(per_region, key, grid): """Sum of the regional cumulative Gt series on a common monthly grid; only for 19-region datasets.""" parts = [per_region[r].get(key) for r in REGIONS] if any(p is None for p in parts): return None vals = np.sum([[at(p['gt'], d) for d in grid] for p in parts], axis=0) s = pd.Series(vals, index=grid).dropna() return s def draw(ax, series, late, t0, t1, g1=None, unit='gt'): if g1 is not None: ax.fill_between(g1.index, g1[unit] - g1[unit + '_err'], g1[unit] + g1[unit + '_err'], color='#0b0b0b', alpha=0.13, lw=0, zorder=2) for k, s in series.items(): _, _, c, ls, lw, z = DATASETS[k] s = s[(s.index >= t0) & (s.index <= t1)] ax.plot(s.index, s.values, color=c, ls=ls, lw=lw, zorder=z, solid_capstyle='round') if k in late: # mark where a late-starting series was tied to the others ax.plot(s.index[:1], s.values[:1], 'o', ms=4, mfc='white', mec=c, mew=1.2, zorder=z + 1) if g1 is not None: ax.plot(g1.index, g1[unit], **G1_STYLE) ax.axhline(0, color=MUTED, lw=0.6, zorder=1) ax.set_xlim(pd.Timestamp(t0), pd.Timestamp(t1)) ax.grid(True, color=GRID, lw=0.6) ax.set_axisbelow(True) for sp in ('top', 'right'): ax.spines[sp].set_visible(False) for sp in ('left', 'bottom'): ax.spines[sp].set_color(GRID) ax.tick_params(colors=MUTED, labelsize=8, length=0) def legend_handles(keys, with_g1): from matplotlib.lines import Line2D from matplotlib.patches import Patch h = [] if with_g1: h.append(Line2D([], [], label='GlaMBIE-1 consensus (calendar years)', **{k: v for k, v in G1_STYLE.items() if k != 'zorder'})) h.append(Patch(color='#0b0b0b', alpha=0.13, lw=0, label='GlaMBIE-1 uncertainty (annual errors in quadrature)')) for k in keys: _, lab, c, ls, lw, _ = DATASETS[k] h.append(Line2D([], [], color=c, ls=ls, lw=max(lw, 1.4), label=lab)) h.append(Line2D([], [], marker='o', ls='', ms=4, mfc='white', mec=MUTED, mew=1.2, label='late start: tied to the median of the others')) return h def figure_grid(per_region, glob_series, t0, t1, unit, with_g1, title, fname): fig, axes = plt.subplots(4, 5, figsize=(17, 12.5)) axes = axes.ravel() ulabel = 'Gt' if unit == 'gt' else 'm w.e.' # first panel: global (Gt only; a global m w.e. would need a common area definition) ax = axes[0] if unit == 'gt': ser, late = anchored(glob_series, t0) draw(ax, ser, late, t0, t1, load_glambie1(0).loc[:t1] if with_g1 else None, unit) ax.set_title('Global (datasets with all 19 regions)', fontsize=9.5, color=INK, loc='left', fontweight='bold') else: ax.axis('off') for i, rid in enumerate(REGIONS, start=1): ax = axes[i] ser, late = anchored({k: v[unit] for k, v in per_region[rid].items() if v is not None}, t0) draw(ax, ser, late, t0, t1, load_glambie1(rid).loc[:t1] if with_g1 else None, unit) ax.set_title(f'{rid} {REGIONS[rid][1]}', fontsize=9.5, color=INK, loc='left') for ax in axes: ax.xaxis.set_major_locator(matplotlib.dates.YearLocator(10 if not with_g1 else 5)) ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y')) fig.suptitle(title, x=0.012, y=0.992, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.968, f'Cumulative mass change in {ulabel}, zero at {pd.Timestamp(t0):%d %b %Y}. ' + ('Gt from each dataset\'s own reported area. ' if unit == 'gt' else '') + 'Independent y-axis per panel.', fontsize=9.5, color=MUTED, ha='left') fig.legend(handles=legend_handles(DATASETS, with_g1), loc='lower center', ncol=4, frameon=False, fontsize=9) fig.tight_layout(rect=(0, 0.06, 1, 0.962)) fig.savefig(os.path.join(OUT, fname), dpi=130, facecolor='white') plt.close(fig) def figure_global(glob_series, t0, t1, with_g1, title, fname): fig, ax = plt.subplots(figsize=(11, 6.6)) ser, late = anchored(glob_series, t0) g1 = load_glambie1(0).loc[:t1] if with_g1 else None draw(ax, ser, late, t0, t1, g1) ax.tick_params(labelsize=10) ax.set_ylabel('Cumulative mass change (Gt)', color=MUTED) fig.suptitle(title, x=0.012, y=0.985, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.935, f'Sum of 19 regions, zero at {pd.Timestamp(t0):%d %b %Y}. Gt from each dataset\'s own reported area. ' 'Only datasets covering all 19 regions.', fontsize=9.5, color=MUTED, ha='left') ax.legend(handles=legend_handles(glob_series, with_g1)[:-1], loc='lower left', frameon=False, fontsize=9.5) fig.tight_layout(rect=(0, 0, 1, 0.925)) fig.savefig(os.path.join(OUT, fname), dpi=140, facecolor='white') plt.close(fig) return ser, g1 CYCLE_YEARS = (2000, 2024) MONTHS = 'JFMAMJJASOND' def load_cycle(rid, key): """Mean annual cycle over CYCLE_YEARS: 12 monthly means in m w.e. and Gt, plus the mean area. Only complete calendar years inside the window are used, so a dataset with a shorter record is averaged over fewer years. Returns None for annual datasets and missing regions. """ 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', 'end_date']) if (df.end_date - df.start_date).dt.days.median() > 40: return None df['year'], df['month'] = df.start_date.dt.year, df.start_date.dt.month df = df[(df.year >= CYCLE_YEARS[0]) & (df.year <= CYCLE_YEARS[1])] df = df[df.groupby('year').month.transform('size') == 12] if df.empty: return None area = 0.5 * (df.glacier_area_reference_start + df.glacier_area_reference_end) df = df.assign(mwe=df.glacier_change_observed, gt=df.glacier_change_observed * area / 1000., area=area) out = df.groupby('month')[['mwe', 'gt', 'area']].mean() out.attrs['years'] = (int(df.year.min()), int(df.year.max()), df.year.nunique()) return out def global_cycle(cycles, key): """Global mean cycle for a 19-region dataset: Gt summed, m w.e. as total Gt over total own area.""" parts = [cycles[r].get(key) for r in REGIONS] if any(p is None for p in parts): return None gt = sum(p['gt'] for p in parts) area = sum(p['area'] for p in parts) return pd.DataFrame({'mwe': gt / area * 1000., 'gt': gt, 'area': area}) def style_axis(ax): ax.axhline(0, color=MUTED, lw=0.6, zorder=1) ax.grid(True, color=GRID, lw=0.6) ax.set_axisbelow(True) for sp in ('top', 'right'): ax.spines[sp].set_visible(False) for sp in ('left', 'bottom'): ax.spines[sp].set_color(GRID) ax.tick_params(colors=MUTED, labelsize=8, length=0) def draw_cycle(ax, cyc, kind): """kind 'mwe': monthly mean balance at month centres. kind 'gt': cumulative Gt through the mean year.""" for k, c in cyc.items(): if c is None: continue _, _, col, ls, lw, z = DATASETS[k] if kind == 'mwe': ax.plot(np.arange(12) + 0.5, c.mwe.values, color=col, ls=ls, lw=lw, zorder=z, marker='o', ms=2.5) else: ax.plot(np.arange(13), np.r_[0, c['gt'].cumsum().values], color=col, ls=ls, lw=lw, zorder=z) style_axis(ax) ax.set_xlim(0, 12) ax.set_xticks(np.arange(13)) ax.set_xticklabels([]) ax.set_xticks(np.arange(12) + 0.5, minor=True) ax.set_xticklabels(list(MONTHS), minor=True, fontsize=8, color=MUTED) ax.tick_params(which='minor', length=0) def cycle_handles(keys): from matplotlib.lines import Line2D return [Line2D([], [], color=DATASETS[k][2], ls=DATASETS[k][3], lw=max(DATASETS[k][4], 1.4), label=DATASETS[k][1]) for k in keys] def figure_cycle_grid(cycles, glob_cyc, kind, fname): fig, axes = plt.subplots(4, 5, figsize=(17, 12.5)) axes = axes.ravel() draw_cycle(axes[0], glob_cyc, kind) axes[0].set_title('Global (datasets with all 19 regions)', fontsize=9.5, color=INK, loc='left', fontweight='bold') for i, rid in enumerate(REGIONS, start=1): draw_cycle(axes[i], cycles[rid], kind) axes[i].set_title(f'{rid} {REGIONS[rid][1]}', fontsize=9.5, color=INK, loc='left') y0, y1 = CYCLE_YEARS title = ('Mean annual cycle: monthly specific mass balance' if kind == 'mwe' else 'Mean annual cycle: cumulative mass change through the year') sub = (f'Mean of each calendar month over {y0}-{y1}, m w.e. per month. ' if kind == 'mwe' else f'Mean monthly change over {y0}-{y1} accumulated from 1 January, Gt (each dataset\'s own reported area). ') fig.suptitle(f'GlaMBIE-2 submissions. {title}', x=0.012, y=0.992, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.968, sub + 'Shorter records use the complete years they have. Independent y-axis per panel.', fontsize=9.5, color=MUTED, ha='left') keys = [k for k in DATASETS if any(cycles[r].get(k) is not None for r in REGIONS)] fig.legend(handles=cycle_handles(keys), loc='lower center', ncol=4, frameon=False, fontsize=9) fig.tight_layout(rect=(0, 0.05, 1, 0.962)) fig.savefig(os.path.join(OUT, fname), dpi=130, facecolor='white') plt.close(fig) def figure_cycle_global(glob_cyc, fname): fig, axes = plt.subplots(1, 2, figsize=(14, 6)) draw_cycle(axes[0], glob_cyc, 'mwe') draw_cycle(axes[1], glob_cyc, 'gt') axes[0].set_title('Monthly specific mass balance (m w.e. per month)', fontsize=11, color=INK, loc='left') axes[1].set_title('Cumulative mass change from 1 January (Gt)', fontsize=11, color=INK, loc='left') for ax in axes: ax.tick_params(labelsize=10) ax.tick_params(which='minor', labelsize=10) y0, y1 = CYCLE_YEARS fig.suptitle(f'GlaMBIE-2 submissions. Global mean annual cycle, {y0}-{y1}', x=0.012, y=0.985, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.93, 'Sum of 19 regions; m w.e. is total Gt over each dataset\'s own total area. ' 'Only monthly datasets covering all 19 regions.', fontsize=9.5, color=MUTED, ha='left') axes[0].legend(handles=cycle_handles(glob_cyc), loc='lower left', frameon=False, fontsize=9.5) fig.tight_layout(rect=(0, 0, 1, 0.92)) fig.savefig(os.path.join(OUT, fname), dpi=140, facecolor='white') plt.close(fig) def main(): os.makedirs(OUT, exist_ok=True) per_region = {rid: {k: load_cumulative(rid, k) for k in DATASETS} for rid in REGIONS} grid = pd.date_range('1974-04-01', '2026-10-01', freq='MS') glob_series = {k: s for k in DATASETS if (s := global_sum(per_region, k, grid)) is not None} full = ('1976-01-01', '2026-01-01') g1w = ('2000-01-01', '2026-01-01') figure_grid(per_region, glob_series, *full, 'gt', False, 'GlaMBIE-2 submissions: cumulative mass change 1976-2025', 'cum_gt_regions_1976-2025.png') figure_grid(per_region, glob_series, *full, 'mwe', False, 'GlaMBIE-2 submissions: cumulative specific mass change 1976-2025', 'cum_mwe_regions_1976-2025.png') figure_grid(per_region, glob_series, *g1w, 'gt', True, 'GlaMBIE-2 submissions vs GlaMBIE-1 consensus, 2000 onwards', 'cum_gt_regions_vs_glambie1.png') figure_grid(per_region, glob_series, *g1w, 'mwe', True, 'GlaMBIE-2 submissions vs GlaMBIE-1 consensus, 2000 onwards (specific)', 'cum_mwe_regions_vs_glambie1.png') ser, _ = figure_global(glob_series, *full, False, 'GlaMBIE-2 submissions: global cumulative mass change 1976-2025', 'cum_gt_global_1976-2025.png') ser00, g1 = figure_global(glob_series, *g1w, True, 'GlaMBIE-2 submissions vs GlaMBIE-1 consensus: global, 2000 onwards', 'cum_gt_global_vs_glambie1.png') # numbers behind the global figures rows = [] for k in glob_series: rows.append(dict(dataset=DATASETS[k][1], last_date=ser[k].index[-1].date(), gt_1976_to_2000=round(at(ser[k], '2000-01-01')), gt_1976_to_2025=round(at(ser[k], '2025-01-01')), gt_2000_to_2024=round(at(ser00[k], '2024-01-01')))) rows.append(dict(dataset='GlaMBIE-1 consensus', last_date=g1.index[-1].date(), gt_2000_to_2024=f"{g1['gt'].iloc[-1]:.0f} +- {g1['gt_err'].iloc[-1]:.0f}")) t = pd.DataFrame(rows) t.to_csv(os.path.join(OUT, 'global_cumulative_gt.csv'), index=False) print(t.to_string(index=False)) # mean annual cycle cycles = {rid: {k: load_cycle(rid, k) for k in DATASETS} for rid in REGIONS} glob_cyc = {k: c for k in DATASETS if (c := global_cycle(cycles, k)) is not None} figure_cycle_grid(cycles, glob_cyc, 'mwe', 'annual_cycle_mwe_regions.png') figure_cycle_grid(cycles, glob_cyc, 'gt', 'annual_cycle_gt_cumulative_regions.png') figure_cycle_global(glob_cyc, 'annual_cycle_global.png') cyc_tab = pd.DataFrame({DATASETS[k][1]: dict(winter_max_gt=c['gt'].cumsum().max(), annual_gt=c['gt'].sum(), amplitude_gt=c['gt'].cumsum().max() - min(0, c['gt'].cumsum().min()), annual_mwe=c.mwe.sum(), min_month=MONTHS[c.mwe.values.argmin()] + str(c.mwe.values.argmin() + 1)) for k, c in glob_cyc.items()}).T print(cyc_tab.to_string()) short = [(REGIONS[r][0], k, c.attrs['years']) for r in REGIONS for k, c in cycles[r].items() if c is not None and c.attrs['years'][2] < CYCLE_YEARS[1] - CYCLE_YEARS[0] + 1] print('shorter records:', short) if __name__ == '__main__': main()