"""Does a year-specific (climate-driven) annual cycle help GlaMBIE convert hydrological-year balances to calendar years, compared with a fixed mean cycle? For each region, model and calendar year Y the script computes D(Y) = B_calendar(Y) - B_hydrological(Y) from the monthly series. D is the correction needed to move an annual value from the hydrological to the calendar year. A fixed mean cycle implies D = 0 every year, so it is the same as applying no correction. Three analyses: 1. size of D against the interannual variability and the GlaMBIE-1 annual uncertainty 2. agreement between models on D(Y) 3. leave-one-model-out: one model is "truth", its hydrological-year values are converted with another model's D(Y); the error is compared with the error of applying no correction Usage: python plot_cycle_correction.py Output: plots/cycle_correction_*.png and .csv """ import glob import itertools import os import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import numpy as np import pandas as pd from plot_overview import DATA, DATASETS, HERE, OUT, REGIONS, INK, MUTED, style_axis # Effectively independent monthly models: the two OGGM runs are near-identical, and Huss model and # ETHZ extended share their non-summer months exactly, so each pair is represented once. MODELS = ['oggm_fix', 'fujita', 'rounce', 'huss'] YEARS = np.arange(1976, 2025) # Hydrological year paired with calendar year Y, as (first month, year offset of that first month). # North: 1 Oct (Y-1) to 30 Sep (Y). South: 1 Apr (Y) to 31 Mar (Y+1). Low latitudes use calendar years. SOUTH = (17, 18, 19) SKIP = (16,) G1_DIR = os.path.join(HERE, 'glambie1_results', 'glambie_results_20240716') def monthly(rid, key): f = os.path.join(DATA, f'{REGIONS[rid][0]}_{DATASETS[key][0]}.csv') df = pd.read_csv(f, parse_dates=['start_date']) return pd.Series(df.glacier_change_observed.values, index=df.start_date.dt.to_period('M')) def cal_hyd(s, rid): """Calendar-year and paired hydrological-year balance (m w.e.) for each year in YEARS.""" cal, hyd = [], [] for y in YEARS: cal.append(s[pd.period_range(f'{y}-01', f'{y}-12', freq='M')].sum()) start = pd.Period(f'{y}-04', 'M') if rid in SOUTH else pd.Period(f'{y - 1}-10', 'M') hyd.append(s[pd.period_range(start, periods=12, freq='M')].sum()) return pd.Series(cal, index=YEARS), pd.Series(hyd, index=YEARS) def glambie1(rid): """GlaMBIE-1: mean annual uncertainty (m w.e.) and the cal - hyd difference it implies, 2000-2023.""" name = glob.glob(os.path.join(G1_DIR, 'calendar_years', f'{rid}_*.csv'))[0] cal = pd.read_csv(name) hyd = pd.read_csv(os.path.join(G1_DIR, 'hydrological_years', os.path.basename(name))) cal.index = cal.start_dates.round().astype(int) off = 0.25 if rid in SOUTH else -0.25 d = {} for y in cal.index: m = hyd[np.isclose(hyd.start_dates, y + off, atol=0.05)] if len(m) == 1: d[y] = cal.combined_mwe[y] - m.combined_mwe.iloc[0] return cal.combined_mwe_errors.mean(), pd.Series(d, dtype=float) def rms(x): return float(np.sqrt(np.mean(np.asarray(x) ** 2))) def main(): os.makedirs(OUT, exist_ok=True) regions = [r for r in REGIONS if r not in SKIP] D, CAL = {}, {} for rid in regions: res = {k: cal_hyd(monthly(rid, k), rid) for k in MODELS} CAL[rid] = pd.DataFrame({k: v[0] for k, v in res.items()}) D[rid] = pd.DataFrame({k: v[0] - v[1] for k, v in res.items()}) rows = [] g1d = {} for rid in regions: d, cal = D[rid], CAL[rid] g1_err, g1d[rid] = glambie1(rid) r = dict(rid=rid, region=REGIONS[rid][0]) # 1. size r['sd_D'] = d.std().mean() # mean over models of the interannual sd of D r['sd_annual'] = cal.std().mean() # interannual sd of the calendar-year balance r['g1_annual_err'] = g1_err # 2. agreement r['mean_pair_corr'] = np.mean([d[a].corr(d[b]) for a, b in itertools.combinations(MODELS, 2)]) r['signal_to_spread'] = d.mean(axis=1).std() / d.std(axis=1).mean() # 3. leave one out: truth A, correction from B. Error with B's cycle = D_B - D_A; without = D_A. for tag, models in (('all', MODELS), ('nofuj', [m for m in MODELS if m != 'fujita'])): none = np.mean([rms(d[a]) for a in models]) other = np.mean([rms(d[b] - d[a]) for a in models for b in models if a != b]) ens = np.mean([rms(d[[b for b in models if b != a]].mean(axis=1) - d[a]) for a in models]) r[f'rmse_none_{tag}'], r[f'rmse_other_{tag}'], r[f'rmse_ens_{tag}'] = none, other, ens r[f'skill_other_{tag}'] = 1 - other / none r[f'skill_ens_{tag}'] = 1 - ens / none # GlaMBIE-1's own applied difference, where both files exist g = g1d[rid] r['g1_sd_D'] = g.std() if len(g) > 2 else np.nan r['g1_corr_with_models'] = g.corr(d.mean(axis=1).reindex(g.index)) if len(g) > 2 else np.nan rows.append(r) t = pd.DataFrame(rows) t.to_csv(os.path.join(OUT, 'cycle_correction.csv'), index=False) # figure 1: D(Y) per model and region fig, axes = plt.subplots(3, 6, figsize=(19, 9.6)) for ax, rid in zip(axes.ravel(), regions): for k in MODELS: ax.plot(YEARS, D[rid][k], color=DATASETS[k][2], lw=1.2, label=DATASETS[k][1]) g = g1d[rid] if len(g): ax.plot(g.index, g.values, color='#0b0b0b', lw=1.4, ls='--', label='GlaMBIE-1 (calendar minus hydrological result)') style_axis(ax) ax.set_xlim(YEARS[0], YEARS[-1]) ax.set_title(f'{rid} {REGIONS[rid][1]}', fontsize=9.5, color=INK, loc='left') fig.suptitle('Calendar-year minus hydrological-year balance, per model', x=0.012, y=0.992, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.962, 'm w.e. This is the correction needed to move an annual value from the hydrological to the calendar year; ' 'a fixed mean cycle gives zero in every year. North: Oct-Sep, south (17-19): Apr-Mar. Independent y-axis per panel.', fontsize=9.5, color=MUTED, ha='left') h, l = axes[0, 0].get_legend_handles_labels() fig.legend(h, l, loc='lower center', ncol=5, frameon=False, fontsize=9.5) fig.tight_layout(rect=(0, 0.04, 1, 0.955)) fig.savefig(os.path.join(OUT, 'cycle_correction_timeseries.png'), dpi=130, facecolor='white') plt.close(fig) # figure 2: error with and without a year-specific cycle, against the GlaMBIE-1 annual uncertainty fig, axes = plt.subplots(1, 2, figsize=(15, 7), sharey=True) y = np.arange(len(t)) for ax, tag, title in zip(axes, ('all', 'nofuj'), ('All four models', 'Without Fujita (three models)')): ax.hlines(y, t[f'rmse_ens_{tag}'], t[f'rmse_none_{tag}'], color='#c9c8c2', lw=2, zorder=2) ax.plot(t[f'rmse_none_{tag}'], y, 'o', ms=8, color='#52514c', zorder=3, label='No correction / fixed mean cycle') ax.plot(t[f'rmse_other_{tag}'], y, 'o', ms=8, color='#2a78d6', zorder=3, label="One other model's year-specific cycle") ax.plot(t[f'rmse_ens_{tag}'], y, 'D', ms=7, color='#1baf7a', zorder=4, label="Mean of the other models' cycles") ax.plot(t['g1_annual_err'], y, '|', ms=14, mew=2, color='#0b0b0b', zorder=3, label='GlaMBIE-1 mean annual uncertainty') style_axis(ax) ax.lines[-1].remove() # style_axis draws a zero line, which here would sit on the first row ax.set_yticks(y) ax.set_yticklabels([f'{r} {REGIONS[r][1]}' for r in t.rid], fontsize=9.5, color=INK) ax.set_xlim(0, None) ax.set_xlabel('RMSE of the calendar-year balance (m w.e.)', color=MUTED) ax.set_title(title, fontsize=11, color=INK, loc='left') axes[0].invert_yaxis() axes[1].legend(loc='lower right', frameon=False, fontsize=9.5) fig.suptitle('Converting hydrological to calendar years: error with and without a year-specific cycle', x=0.012, y=0.985, ha='left', fontsize=14, color=INK, fontweight='bold') fig.text(0.012, 0.94, 'Leave-one-model-out, 1976-2024: one model is taken as truth and its hydrological-year values are converted ' "using another model's cycle.", fontsize=9.5, color=MUTED, ha='left') fig.tight_layout(rect=(0, 0, 1, 0.93)) fig.savefig(os.path.join(OUT, 'cycle_correction_skill.png'), dpi=140, facecolor='white') plt.close(fig) pd.set_option('display.width', 260, 'display.max_columns', 40) print(t.round(3).to_string(index=False)) print('\nmedian over regions:') print(t.drop(columns=['rid', 'region']).median().round(3).to_string()) # per-model size of D, to see who drives the spread print('\ninterannual sd of D per model (m w.e.):') print(pd.DataFrame({REGIONS[r][0]: D[r].std() for r in regions}).T.round(3).to_string()) if __name__ == '__main__': main()