"""Figures and metrics for the flowline_dx / binsize study. Run after run_config.py for all configs: .cluster_env/run.sh python claude/flowline_dx/analyse.py """ from pathlib import Path import numpy as np import pandas as pd import xarray as xr import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt # noqa: E402 from oggm import cfg, utils # noqa: E402 from oggm import GlacierDirectory # noqa: E402 HERE = Path(__file__).resolve().parent OUT = HERE / 'output' FIGS = HERE / 'figs' FIGS.mkdir(exist_ok=True) GLACIERS = {'RGI60-11.00897': 'Hintereisferner (8.0 km²)', 'RGI60-11.00787': 'Kesselwandferner (4.0 km²)', 'RGI60-11.00289': 'Goldbergkees (0.64 km²)', 'RGI60-11.00892': 'Plattalva (0.42 km²)'} DXS = [1, 2, 4] BINS = [10, 30, 50] C3 = ['#2a78d6', '#eb6834', '#1baf7a'] # validated categorical order INK2 = '#52514e' plt.rcParams.update({'axes.spines.top': False, 'axes.spines.right': False, 'axes.grid': True, 'grid.color': '#e6e5e0', 'grid.linewidth': 0.6, 'axes.edgecolor': INK2, 'font.size': 9, 'lines.linewidth': 1.5, 'legend.frameon': False}) def name(dx, b): return f'dx{dx}_b{b}' def load(kind, dx, b): with xr.open_dataset(OUT / f'run_{kind}_{name(dx, b)}.nc') as ds: return ds.load() def model_fl(rid, dx, b): gd = GlacierDirectory(rid, base_dir=str(HERE / 'work' / name(dx, b) / 'per_glacier')) return gd.read_store('model_flowlines')[-1] # --- Step-y-ness metrics ----------------------------------------------------- def step_metrics(a, a0): """a: annual area series (m2). Returns metrics in % of initial area.""" a = np.asarray(a, dtype=float) da = np.diff(a) smooth = pd.Series(a).rolling(11, center=True, min_periods=11).mean() resid = (pd.Series(a) - smooth).dropna() # only look at the period where the glacier still exists alive = a[:-1] > 0 da = da[alive] return dict( # high-frequency roughness of the area series (11-yr running mean) hf_std=100 * resid.std() / a0, # largest single-year area loss max_loss=100 * -da.min() / a0, # fraction of total area loss done in years with a loss > 3x median # loss (a measure of how concentrated loss is in "events") frac_in_events=(-da[da < -3 * np.median(-da[da < 0])].sum() / -da[da < 0].sum()) if (da < 0).any() else np.nan, # number of years with zero area change while the glacier shrinks n_flat=int((np.abs(da) < 1e-3 * a0 / 100).sum()), ) def main(): cfg.initialize(logging_level='CRITICAL') # --- Metrics table -------------------------------------------------------- rows = [] for kind in ['const', 'random', 'random_m1']: for dx in DXS: for b in BINS: ds = load(kind, dx, b) for rid, gname in GLACIERS.items(): d = ds.sel(rgi_id=rid) for avar in ['area', 'area_min_h']: a = d[avar].values m = step_metrics(a, a[0]) m.update(kind=kind, glacier=gname.split(' (')[0], dx=dx, bin=b, var=avar) rows.append(m) met = pd.DataFrame(rows) met.to_csv(OUT / 'step_metrics.csv', index=False) # --- Fig 1: geometry ------------------------------------------------------ fig, axes = plt.subplots(2, 4, figsize=(13, 6), constrained_layout=True) for j, rid in enumerate(['RGI60-11.00897', 'RGI60-11.00289']): for col, (var, lab) in enumerate([('surface_h', 'Surface elevation (m)'), ('widths_m', 'Width (m)')]): # left: binsize at dx=1 ; right: dx at bin=30 for k, (lst, fixed) in enumerate([(BINS, 'dx'), (DXS, 'bin')]): ax = axes[j, 2 * k + col] for i, v in enumerate(lst): dx, b = (1, v) if fixed == 'dx' else (v, 30) fl = model_fl(rid, dx, b) x = fl.dis_on_line * fl.map_dx y = getattr(fl, var) sel = fl.thick > 0 lbl = f'bin {b} m' if fixed == 'dx' else \ f'dx={dx} ({fl.dx_meter:.0f} m)' ax.plot(x[sel], y[sel], color=C3[i], label=lbl, drawstyle='steps-mid' if var == 'widths_m' else 'default') ttl = 'binsize varies, dx=1' if fixed == 'dx' \ else 'dx varies, bin=30 m' ax.set_title(f'{GLACIERS[rid].split(" (")[0]}: {ttl}', fontsize=9) ax.set_ylabel(lab) if j == 1: ax.set_xlabel('Distance along flowline (m)') if col == 0: ax.legend(fontsize=8) fig.suptitle('Model flowlines at t=0 (glacier part only)') fig.savefig(FIGS / 'fig1_geometry.png', dpi=130) plt.close(fig) # --- Fig 2/3: time series ------------------------------------------------- for kind, title in [('const', 'Constant climate 2000-2019'), ('random', 'Random climate 2000-2019 (seed 1)'), ('random_m1', 'Random climate 2000-2019 -1 K (seed 1)')]: for var, ylab, fac in [('area', 'Area (% of initial)', None), ('area_min_h', 'Area h>2m (% of initial)', None), ('volume', 'Volume (% of initial)', None), ('length', 'Length (m)', 1)]: fig, axes = plt.subplots(2, 4, figsize=(14, 6), constrained_layout=True, sharex=True) for j, rid in enumerate(GLACIERS): for row, (lst, fixed) in enumerate([(DXS, 'bin'), (BINS, 'dx')]): ax = axes[row, j] for i, v in enumerate(lst): dx, b = (v, 30) if fixed == 'bin' else (1, v) d = load(kind, dx, b).sel(rgi_id=rid)[var] y = d.values if fac else 100 * d.values / d.values[0] lbl = f'dx={dx}' if fixed == 'bin' else f'bin {b} m' ax.plot(d.time, y, color=C3[i], label=lbl, lw=1.2, drawstyle='steps-post') if row == 0: ax.set_title(GLACIERS[rid], fontsize=9) if j == 0: ax.set_ylabel(ylab) ax.legend(title='bin=30 m' if fixed == 'bin' else 'dx=1', fontsize=8, title_fontsize=8) if row == 1: ax.set_xlabel('Simulation year') if (rid in ['RGI60-11.00289', 'RGI60-11.00892'] and kind != 'random_m1'): ax.set_xlim(None, 120) fig.suptitle(f'{title}: {var} — top: dx varies (bin 30 m); ' f'bottom: binsize varies (dx=1)') fig.savefig(FIGS / f'fig_ts_{kind}_{var}.png', dpi=130) plt.close(fig) # --- Fig 4: zoom on HEF area, constant climate, all dx -------------------- fig, axes = plt.subplots(1, 3, figsize=(16, 3.8), constrained_layout=True) rid = 'RGI60-11.00897' for ax, kind in zip(axes, ['const', 'random', 'random_m1']): for i, dx in enumerate(DXS): d = load(kind, dx, 30).sel(rgi_id=rid).area_min_h * 1e-6 ax.plot(d.time, d, color=C3[i], lw=1.2, drawstyle='steps-post', label=f'dx={dx} ({dx * 50} m)') ax.set_xlim(0, 300 if kind == 'random_m1' else 150) ax.set_title(f'Hintereisferner area_min_h, {kind} climate, bin 30 m', fontsize=9) ax.set_ylabel('Area (km²)') ax.set_xlabel('Simulation year') ax.legend(fontsize=8) fig.savefig(FIGS / 'fig4_hef_area_zoom.png', dpi=130) plt.close(fig) # --- Fig 5: metric heatmaps ----------------------------------------------- for metric, lab in [('hf_std', 'High-freq. area roughness (% of A0)'), ('max_loss', 'Largest 1-yr area loss (% of A0)')]: fig, axes = plt.subplots(3, 4, figsize=(13, 8.2), constrained_layout=True) for r, kind in enumerate(['const', 'random', 'random_m1']): for j, gname in enumerate(GLACIERS.values()): g = gname.split(' (')[0] sub = met[(met.kind == kind) & (met.glacier == g) & (met['var'] == 'area_min_h')] tab = sub.pivot(index='dx', columns='bin', values=metric) ax = axes[r, j] ax.grid(False) im = ax.imshow(tab.values, cmap='Blues', origin='lower', vmin=0) for (ii, jj), val in np.ndenumerate(tab.values): vmax = np.nanmax(tab.values) ax.text(jj, ii, f'{val:.2f}', ha='center', va='center', fontsize=8, color='white' if val > 0.6 * vmax else '#0b0b0b') ax.set_xticks(range(len(BINS)), [f'{b} m' for b in BINS]) ax.set_yticks(range(len(DXS)), [f'dx={d}' for d in DXS]) ax.set_title(f'{g} ({kind})', fontsize=9) if r == 2: ax.set_xlabel('elevation_band_flowline_binsize') fig.suptitle(lab + ', area_min_h') fig.savefig(FIGS / f'fig5_heatmap_{metric}.png', dpi=130) plt.close(fig) pd.set_option('display.width', 200) for kind in ['const', 'random', 'random_m1']: print(kind) for metric in ['hf_std', 'max_loss', 'frac_in_events', 'n_flat']: print(met[met.kind == kind].pivot_table( index=['var', 'glacier', 'dx'], columns='bin', values=metric).round(3).add_prefix(f'{metric}_b')) if __name__ == '__main__': main()