From 9aba24a81f1d7fc89efd6815e1058e38002641e3 Mon Sep 17 00:00:00 2001 From: Patrick Schmitt Date: Fri, 4 Dec 2026 14:33:24 +0100 Subject: [PATCH] Add tutorial on the daily mass balance model and its mass balance profiles --- _toc.yml | 1 + book/massbalance.md | 1 + notebooks/tutorials/daily_mb_profiles.ipynb | 908 ++++++++++++++++++++ notebooks/welcome.ipynb | 1 + 4 files changed, 911 insertions(+) create mode 100644 notebooks/tutorials/daily_mb_profiles.ipynb diff --git a/_toc.yml b/_toc.yml index ef1f24dc..da32a793 100644 --- a/_toc.yml +++ b/_toc.yml @@ -24,6 +24,7 @@ chapters: - file: book/massbalance sections: - file: notebooks/tutorials/massbalance_calibration + - file: notebooks/tutorials/daily_mb_profiles - file: notebooks/tutorials/plot_mass_balance - file: notebooks/tutorials/massbalance_global_params - file: notebooks/tutorials/massbalance_perturbation diff --git a/book/massbalance.md b/book/massbalance.md index d856ef32..5ddbdfa0 100644 --- a/book/massbalance.md +++ b/book/massbalance.md @@ -2,5 +2,6 @@ - [](../notebooks/tutorials/plot_mass_balance.ipynb) - [](../notebooks/tutorials/massbalance_calibration.ipynb) +- [](../notebooks/tutorials/daily_mb_profiles.ipynb) - [](../notebooks/tutorials/massbalance_global_params.ipynb) - [](../notebooks/tutorials/massbalance_perturbation.ipynb) diff --git a/notebooks/tutorials/daily_mb_profiles.ipynb b/notebooks/tutorials/daily_mb_profiles.ipynb new file mode 100644 index 00000000..e84a0930 --- /dev/null +++ b/notebooks/tutorials/daily_mb_profiles.ipynb @@ -0,0 +1,908 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "id": "14ef170a", + "metadata": {}, + "source": [ + "# The daily mass balance model and its mass balance profiles\n", + "\n", + "OGGM's `DailyTIModel` is a temperature index model which computes the mass balance from daily temperature and precipitation. Most applications only need monthly or annual values of it: the calibration, and the dynamical runs, which update the mass balance once per year or month. Going through all the days at each call makes the daily model much slower than the monthly one.\n", + "\n", + "This tutorial presents two tools which remove most of this cost:\n", + "\n", + "- **mass balance profiles**: the daily climate is preprocessed once into monthly and annual \"profiles\", from which the model interpolates. The results are the same as with the computation from all the days.\n", + "- **the series cache**: with the profiles, the model remembers the interpolated climate of its last calls. Useful when you evaluate the same glacier and period many times.\n", + "\n", + "In this tutorial you will learn:\n", + "\n", + "- how to compute the mass balance profiles and use them in the `DailyTIModel`,\n", + "- what the profiles are, and why they do not change the results,\n", + "- how much faster the model becomes,\n", + "- how the series cache works, how to write your own calibration so that it gains from it, and how to control the memory it uses.\n", + "\n", + "We assume that you know the basics of the OGGM mass balance models and their calibration, e.g. from the [mass balance calibration tutorial](massbalance_calibration.ipynb)." + ] + }, + { + "cell_type": "markdown", + "id": "4c6f6bf8", + "metadata": {}, + "source": [ + "## Set-up" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "917866bb", + "metadata": {}, + "outputs": [], + "source": [ + "import time\n", + "from functools import partial\n", + "\n", + "import numpy as np\n", + "import pandas as pd\n", + "import xarray as xr\n", + "import matplotlib.pyplot as plt\n", + "\n", + "from oggm import cfg, utils, workflow, tasks, DEFAULT_BASE_URL\n", + "from oggm.core.massbalance import DailyTIModel, MonthlyTIModel, mb_calibration_to_rmsd" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9065eb23", + "metadata": {}, + "outputs": [], + "source": [ + "cfg.initialize(logging_level='WARNING')\n", + "cfg.PATHS['working_dir'] = utils.gettempdir('OGGM_daily_mb_profiles', reset=True)\n", + "\n", + "# Hintereisferner, from the preprocessed directories\n", + "gdir = workflow.init_glacier_directories(['RGI60-11.00897'], from_prepro_level=3,\n", + " prepro_base_url=DEFAULT_BASE_URL,\n", + " prepro_border=80)[0]" + ] + }, + { + "cell_type": "markdown", + "id": "1d210f06", + "metadata": {}, + "source": [ + "A small helper to measure run times. Timings differ between machines: look at the ratios, not at the absolute numbers." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "792ed98b", + "metadata": {}, + "outputs": [], + "source": [ + "def best_time(func, repeat=5):\n", + " # Fastest of several runs, in seconds\n", + " out = []\n", + " for _ in range(repeat):\n", + " t0 = time.perf_counter()\n", + " func()\n", + " out.append(time.perf_counter() - t0)\n", + " return min(out)" + ] + }, + { + "cell_type": "markdown", + "id": "dfdf591e", + "metadata": {}, + "source": [ + "## Daily climate data and the mass balance profiles\n", + "\n", + "The preprocessed directories contain monthly climate data. We add the daily data of the same dataset:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c27c64c7", + "metadata": {}, + "outputs": [], + "source": [ + "tasks.process_gswp3_w5e5_data(gdir, daily=True) # writes climate_historical_daily.nc" + ] + }, + { + "cell_type": "markdown", + "id": "6d27eede", + "metadata": {}, + "source": [ + "The daily model uses a melt threshold (`temp_melt`) of 0°C, where the monthly model uses -1°C. It therefore needs its own calibration, which we keep in its own settings file. We also store there that we want to use the mass balance profiles: **they are not used by default**." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f1968550", + "metadata": {}, + "outputs": [], + "source": [ + "gdir.create_new_settings('_daily', parent_filesuffix='',\n", + " data={'use_mb_profiles': True});" + ] + }, + { + "cell_type": "markdown", + "id": "be3cdb3f", + "metadata": {}, + "source": [ + "The profiles are computed by an entity task. **You have to call it yourself**, after the daily climate data is processed and before a model is created:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0ccd9e59", + "metadata": {}, + "outputs": [], + "source": [ + "tasks.process_mb_profiles(gdir, settings_filesuffix='_daily')" + ] + }, + { + "cell_type": "markdown", + "id": "7588315b", + "metadata": {}, + "source": [ + "The task writes the file `mb_profiles_climate_historical_daily.nc` to the glacier directory. Now we can calibrate and create the model, as for any other mass balance model:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db355c58", + "metadata": {}, + "outputs": [], + "source": [ + "tasks.mb_calibration_from_geodetic_mb(gdir, settings_filesuffix='_daily',\n", + " observations_filesuffix='_daily',\n", + " mb_model_class=DailyTIModel,\n", + " overwrite_gdir=True)\n", + "mb_daily = DailyTIModel(gdir, settings_filesuffix='_daily')\n", + "mb_daily" + ] + }, + { + "cell_type": "markdown", + "id": "936a6872", + "metadata": {}, + "source": [ + "`use_mb_profiles: True` tells us that the model uses the profiles. There are three ways to switch them on or off:\n", + "\n", + "- the keyword of the model: `DailyTIModel(gdir, use_mb_profiles=True)`,\n", + "- for one glacier and settings file: `gdir.settings['use_mb_profiles']` (what we did above),\n", + "- for all glaciers: `cfg.PARAMS['use_mb_profiles']` (`False` by default).\n", + "\n", + "The keyword wins over the settings, and the settings over `cfg.PARAMS`.\n", + "\n", + "The model is used like any other OGGM mass balance model. Here is the mass balance of one year, next to the one of the monthly model of the preprocessed directory:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3d7115c4", + "metadata": {}, + "outputs": [], + "source": [ + "heights, widths = gdir.get_inversion_flowline_hw()\n", + "mb_monthly = MonthlyTIModel(gdir)\n", + "\n", + "year = 2003\n", + "fig, ax = plt.subplots(figsize=(5, 4))\n", + "for mod, label in [(mb_daily, 'DailyTIModel'), (mb_monthly, 'MonthlyTIModel')]:\n", + " mb = mod.get_annual_mb(heights, year=year) * mod.sec_in_year(year) * mod.ice_density\n", + " ax.plot(mb, heights, label=label)\n", + "ax.set_xlabel('Annual mass balance (mm w.e.)'); ax.set_ylabel('Altitude (m)')\n", + "ax.set_title(f'Hintereisferner, {year}'); ax.legend();" + ] + }, + { + "cell_type": "markdown", + "id": "33365bc1", + "metadata": {}, + "source": [ + "## What the mass balance profiles are\n", + "\n", + "### One day\n", + "\n", + "For each day, the model computes two quantities at each altitude of the glacier: the temperature above the melt threshold (`tempformelt`, which is multiplied by the melt factor to get the melt), and the solid precipitation (`prcpsol`).\n", + "\n", + "OGGM extrapolates the temperature of the climate file from its reference altitude $z_{ref}$ to the altitude $z$ with a constant lapse rate $\\gamma$ (negative, in K per m), and adds the temperature bias $T_{bias}$:\n", + "\n", + "$$T_d(z) = T_d + \\tau, \\qquad \\tau = T_{bias} + \\gamma\\,(z - z_{ref})$$\n", + "\n", + "$T_d$ is the temperature of day $d$ in the climate file. Everything which depends on where we are on the glacier, and on the temperature bias, is in the single number $\\tau$: *how much warmer or colder than the climate file is it here?* **For a given point of the glacier, $\\tau$ is the same for every day.**\n", + "\n", + "The two daily quantities only depend on the temperature, i.e. on $\\tau$:\n", + "\n", + "$$\\text{tempformelt}_d = \\max(T_d + \\tau - T_{melt},\\ 0)$$\n", + "\n", + "$$\\text{prcpsol}_d = P_d \\cdot \\text{clip}\\!\\left(\\frac{T_{liq} - (T_d + \\tau)}{T_{liq} - T_{solid}},\\ 0,\\ 1\\right)$$\n", + "\n", + "Both are made of straight pieces: `tempformelt` has one kink, where the temperature crosses the melt threshold, and `prcpsol` has two, at the two thresholds between snow and rain. Let's compute them for the days of June 2003, from the climate file:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9926588a", + "metadata": {}, + "outputs": [], + "source": [ + "with xr.open_dataset(gdir.get_filepath('climate_historical', filesuffix='_daily')) as ds:\n", + " ref_hgt = ds.ref_hgt\n", + " ds = ds.sel(time='2003-06').load()\n", + "temp_d, prcp_d = ds.temp.values, ds.prcp.values\n", + "\n", + "t_melt = mb_daily.temp_melt\n", + "t_solid, t_liq = mb_daily.temp_all_solid, mb_daily.temp_all_liq\n", + "\n", + "# temperature offsets tau, for the whole range of the glacier and more\n", + "tau = np.linspace(-14, 2, 500)\n", + "# one row per day, one column per offset\n", + "tempformelt_d = np.clip(temp_d[:, None] + tau - t_melt, 0, None)\n", + "prcpsol_d = prcp_d[:, None] * np.clip((t_liq - (temp_d[:, None] + tau)) / (t_liq - t_solid), 0, 1)\n", + "\n", + "# from the temperature offset to the altitude and back (without temperature bias)\n", + "grad = gdir.settings['temp_default_gradient']\n", + "\n", + "def tau_to_altitude(tau):\n", + " return ref_hgt + tau / grad\n", + "\n", + "def altitude_to_tau(z):\n", + " return grad * (z - ref_hgt)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2967d15c", + "metadata": {}, + "outputs": [], + "source": [ + "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 3.5))\n", + "for day in [5, 12, 20]:\n", + " ax1.plot(tau, tempformelt_d[day], label=f'{day + 1} June 2003')\n", + " ax2.plot(tau, prcpsol_d[day])\n", + "ax1.set_title('Temperature above the melt threshold of single days'); ax1.set_ylabel('K')\n", + "ax2.set_title('Solid precipitation of single days'); ax2.set_ylabel('mm w.e.')\n", + "for ax in (ax1, ax2):\n", + " ax.set_xlabel(r'Temperature offset $\\tau$ (K)')\n", + " # a second axis below the first one, with the altitude which belongs to each offset\n", + " below = ax.secondary_xaxis(-0.3, functions=(tau_to_altitude, altitude_to_tau))\n", + " below.set_xlabel('Altitude (m), for temp_bias = 0')\n", + "ax1.legend();" + ] + }, + { + "cell_type": "markdown", + "id": "c8ee47a2", + "metadata": {}, + "source": [ + "The second axis below each plot shows the altitude which belongs to each temperature offset, here without a temperature bias: a colder offset is a higher point of the glacier, so **the altitude increases to the left**. We come back to this below." + ] + }, + { + "cell_type": "markdown", + "id": "a324e9a5", + "metadata": {}, + "source": [ + "### One month\n", + "\n", + "The value of a month is the sum over its days. A sum of functions made of straight pieces is again made of straight pieces, and **it can only bend where one of the days bends**. So if we know the sum at these points (the *nodes*), a linear interpolation between them gives the sum everywhere else. This is exact, not an approximation.\n", + "\n", + "This is what the mass balance profiles are: for each month and each year of the climate file, the nodes of the two sums. The model has them as `mb_daily.profiles`. We compare the nodes of June 2003 with the sum over the days computed above:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dafbce9e", + "metadata": {}, + "outputs": [], + "source": [ + "prof = mb_daily.profiles\n", + "i = prof.monthly.index(prof.month_key(2003, 6)) # the index of the month\n", + "x_melt, y_melt = prof.monthly.melt[i] # the nodes of tempformelt\n", + "x_sol, y_sol = prof.monthly.sol[i] # the nodes of prcpsol\n", + "\n", + "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 3.5))\n", + "ax1.plot(tau, tempformelt_d.sum(axis=0), label='sum over the days')\n", + "ax1.plot(x_melt, y_melt, '.', label=f'the {len(x_melt)} nodes of the profile')\n", + "ax2.plot(tau, prcpsol_d.sum(axis=0))\n", + "ax2.plot(x_sol, y_sol, '.', label=f'the {len(x_sol)} nodes of the profile')\n", + "ax1.set_title('Temperature above the melt threshold, June 2003'); ax1.set_ylabel('K day')\n", + "ax2.set_title('Solid precipitation, June 2003'); ax2.set_ylabel('mm w.e.')\n", + "for ax in (ax1, ax2):\n", + " ax.set_xlabel(r'Temperature offset $\\tau$ (K)')\n", + " ax.set_xlim(tau[0], tau[-1])\n", + " ax.legend()\n", + "ax1.set_ylim(-10, tempformelt_d.sum(axis=0).max());" + ] + }, + { + "cell_type": "markdown", + "id": "433da58c", + "metadata": {}, + "source": [ + "How to read the two curves:\n", + "\n", + "- *Melt curve:* zero for cold offsets (left), then rising. There is one node per day, at $\\tau = T_{melt} - T_d$. Right of the last node, every day of the month melts and the curve continues as a straight line.\n", + "- *Snow curve:* the total precipitation of the month for cold offsets (all of it falls as snow), decreasing to zero for warm offsets (all rain). There are two nodes per day with precipitation, at $\\tau = T_{solid} - T_d$ and $\\tau = T_{liq} - T_d$.\n", + "\n", + "The interpolation between the nodes gives the same as the sum over the days:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "de3ee41a", + "metadata": {}, + "outputs": [], + "source": [ + "print('largest difference, tempformelt:',\n", + " np.abs(prof.monthly.melt.interp(i, tau) - tempformelt_d.sum(axis=0)).max())\n", + "print('largest difference, prcpsol: ',\n", + " np.abs(prof.monthly.sol.interp(i, tau) - prcpsol_d.sum(axis=0)).max())" + ] + }, + { + "cell_type": "markdown", + "id": "3fac6c35", + "metadata": {}, + "source": [ + "### From the temperature offset to the altitude\n", + "\n", + "The temperature offset is the altitude axis with another scale and direction: a point 100 m higher is $100 \\cdot |\\gamma| = 0.65$ K colder with the default lapse rate, so its $\\tau$ is 0.65 smaller. High altitudes are on the left (cold), low altitudes on the right (warm). The altitude which belongs to an offset is\n", + "\n", + "$$z = z_{ref} + \\frac{\\tau - T_{bias}}{\\gamma}$$\n", + "\n", + "We plot the same curves against the altitude, for two values of the temperature bias. The curves themselves do not change: a temperature bias only moves them along the altitude axis, by $-T_{bias} / \\gamma$ (a bias of +1 K moves everything about 154 m up)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e457e1fe", + "metadata": {}, + "outputs": [], + "source": [ + "fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11, 4), sharey=True)\n", + "for temp_bias in [0, 2]:\n", + " z = ref_hgt + (tau - temp_bias) / grad\n", + " ax1.plot(prof.monthly.melt.interp(i, tau), z, label=f'temp_bias = {temp_bias} K')\n", + " ax2.plot(prof.monthly.sol.interp(i, tau), z)\n", + "for ax in (ax1, ax2):\n", + " ax.axhspan(heights.min(), heights.max(), color='lightgrey', label='Hintereisferner')\n", + "ax1.set_xlabel('Temperature above the melt threshold, June 2003 (K day)')\n", + "ax2.set_xlabel('Solid precipitation, June 2003 (mm w.e.)')\n", + "ax1.set_ylabel('Altitude (m)'); ax1.set_ylim(1500, 4500); ax1.legend();" + ] + }, + { + "cell_type": "markdown", + "id": "74514513", + "metadata": {}, + "source": [ + "### What this means for the parameters\n", + "\n", + "To get the mass balance of a month, the model computes $\\tau$ for each altitude, looks up the two curves, and combines them:\n", + "\n", + "$$\\text{MB} = P_f \\cdot \\text{prcpsol}(\\tau) - d_f \\cdot \\text{tempformelt}(\\tau)$$\n", + "\n", + "with the precipitation factor $P_f$ (`prcp_fac`) and the melt factor $d_f$ (`melt_f`). The three calibration parameters therefore do not change the profiles:\n", + "\n", + "- the temperature bias is a part of $\\tau$,\n", + "- the precipitation factor and the melt factor are applied after the look-up.\n", + "\n", + "**The profiles only depend on the daily climate file and on the three temperature thresholds** (`temp_melt`, `temp_all_solid` and `temp_all_liq`). They do not depend on the glacier geometry, the lapse rate or the calibration, and stay valid during a calibration or a dynamical run. If you change the climate file or one of the thresholds, the model raises an error which tells you to run `process_mb_profiles` again." + ] + }, + { + "cell_type": "markdown", + "id": "3cbc9729", + "metadata": {}, + "source": [ + "## The results do not change\n", + "\n", + "We create a second model which computes everything from all the days, as the `DailyTIModel` does by default, and compare the two:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "0e553848", + "metadata": {}, + "outputs": [], + "source": [ + "mb_days = DailyTIModel(gdir, settings_filesuffix='_daily', use_mb_profiles=False)\n", + "\n", + "years = np.arange(2000, 2020)\n", + "# the 240 months of 2000 to 2019\n", + "months = utils.float_years_timeseries(2000, 2019, include_last_year=True)\n", + "\n", + "rng = np.random.default_rng(0)\n", + "calibrated = mb_daily.melt_f, mb_daily.prcp_fac, mb_daily.temp_bias\n", + "diff_annual, diff_monthly = [], []\n", + "for _ in range(5):\n", + " # some random parameters, the same for both models\n", + " for mod in (mb_daily, mb_days):\n", + " mod.melt_f, mod.prcp_fac, mod.temp_bias = calibrated\n", + " params = rng.uniform(3, 12), rng.uniform(1, 4), rng.uniform(-2, 2)\n", + " for mod in (mb_daily, mb_days):\n", + " mod.melt_f, mod.prcp_fac, mod.temp_bias = params\n", + " diff_annual.append(mb_daily.get_specific_mb(heights, widths, year=years) -\n", + " mb_days.get_specific_mb(heights, widths, year=years))\n", + " diff_monthly.append(\n", + " mb_daily.get_specific_mb(heights, widths, year=months, time_resolution='monthly') -\n", + " mb_days.get_specific_mb(heights, widths, year=months, time_resolution='monthly'))\n", + "\n", + "# back to the calibrated parameters\n", + "for mod in (mb_daily, mb_days):\n", + " mod.melt_f, mod.prcp_fac, mod.temp_bias = calibrated\n", + "\n", + "print(f'Largest difference of the annual specific MB: {np.abs(diff_annual).max():.1e} mm w.e.')\n", + "print(f'Largest difference of the monthly specific MB: {np.abs(diff_monthly).max():.1e} mm w.e.')" + ] + }, + { + "cell_type": "markdown", + "id": "6bbc2833", + "metadata": {}, + "source": [ + "The differences are round-off errors: the same numbers are added in another order.\n", + "\n", + "## How much faster is it?\n", + "\n", + "### The mass balance\n", + "\n", + "We time the specific mass balance of 20 years, at annual and at monthly resolution. For a fair comparison we switch off the series cache of the model with profiles (it is the topic of the next section)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "5098e471", + "metadata": {}, + "outputs": [], + "source": [ + "mb_nocache = DailyTIModel(gdir, settings_filesuffix='_daily', mb_series_cache_size=0)\n", + "\n", + "models = {'DailyTIModel, all days': mb_days,\n", + " 'DailyTIModel, profiles': mb_nocache,\n", + " 'MonthlyTIModel': mb_monthly}\n", + "df = pd.DataFrame(index=list(models), columns=['annual (ms)', 'monthly (ms)'], dtype=float)\n", + "for name, mod in models.items():\n", + " df.loc[name, 'annual (ms)'] = 1e3 * best_time(\n", + " lambda: mod.get_specific_mb(heights, widths, year=years))\n", + " df.loc[name, 'monthly (ms)'] = 1e3 * best_time(\n", + " lambda: mod.get_specific_mb(heights, widths, year=months, time_resolution='monthly'))\n", + "df.round(2)" + ] + }, + { + "cell_type": "markdown", + "id": "8f78c80c", + "metadata": {}, + "source": [ + "With the profiles, annual values of the daily model cost about the same as those of the monthly model. Monthly values are still somewhat slower than with the monthly model, but much faster than the computation from all the days.\n", + "\n", + "### A calibration\n", + "\n", + "The calibration tasks create their own model. They use the profiles if the settings say so, as our `_daily` settings do. To time a calibration without profiles, we give the task a model class with another default.\n", + "\n", + "The calibration on the geodetic mass balance from above only needs a few evaluations of annual values, and is fast in both cases. As a more demanding example we take `mb_calibration_to_rmsd`, which fits the melt factor and the precipitation factor to the annual mass balance measured on Hintereisferner. It evaluates the monthly mass balance of all hydrological years with observations, several hundred times:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "32ff3a59", + "metadata": {}, + "outputs": [], + "source": [ + "ref_mb = gdir.get_ref_mb_data()['ANNUAL_BALANCE']\n", + "\n", + "def calibrate(mb_model_class):\n", + " t0 = time.perf_counter()\n", + " out = mb_calibration_to_rmsd(\n", + " gdir, settings_filesuffix='_daily', ref_df=ref_mb,\n", + " calibrate_params=('melt_f', 'prcp_fac'), mb_model_class=mb_model_class,\n", + " write_to_gdir=False, optimisation_kwargs={'seed': 42})\n", + " return time.perf_counter() - t0, out\n", + "\n", + "t_prof, out_prof = calibrate(DailyTIModel)\n", + "t_days, out_days = calibrate(partial(DailyTIModel, use_mb_profiles=False))\n", + "print(f'Calibration with profiles: {t_prof:.2f} s, from all days: {t_days:.2f} s')\n", + "for name, out in [('with profiles:', out_prof), ('from all days:', out_days)]:\n", + " print(f'{name} melt_f = {out[\"melt_f\"]:.4f}, prcp_fac = {out[\"prcp_fac\"]:.4f}, '\n", + " f'RMSD = {out[\"rmsd\"]:.2f} mm w.e.')" + ] + }, + { + "cell_type": "markdown", + "id": "17de1f53", + "metadata": {}, + "source": [ + "### A dynamical run\n", + "\n", + "A run with the dynamical model asks for one mass balance profile per year. This is a small part of its run time, with or without profiles, so do not expect a large gain here. We do the run with both models, mainly to compare the results:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7b9b174e", + "metadata": {}, + "outputs": [], + "source": [ + "tasks.init_present_time_glacier(gdir)\n", + "\n", + "def run(mb_model_class, output_filesuffix):\n", + " tasks.run_from_climate_data(gdir, settings_filesuffix='_daily',\n", + " climate_input_filesuffix='_daily',\n", + " mb_model_class=mb_model_class, ye=2020,\n", + " output_filesuffix=output_filesuffix)\n", + "\n", + "t_prof = best_time(lambda: run(DailyTIModel, '_profiles'), repeat=3)\n", + "t_days = best_time(lambda: run(partial(DailyTIModel, use_mb_profiles=False), '_days'),\n", + " repeat=3)\n", + "print(f'Run with profiles: {t_prof:.2f} s, from all days: {t_days:.2f} s')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "95a7a7e7", + "metadata": {}, + "outputs": [], + "source": [ + "with xr.open_dataset(gdir.get_filepath('model_diagnostics', filesuffix='_profiles')) as ds:\n", + " vol_prof = ds.volume_m3.load()\n", + "with xr.open_dataset(gdir.get_filepath('model_diagnostics', filesuffix='_days')) as ds:\n", + " vol_days = ds.volume_m3.load()\n", + "\n", + "(vol_prof * 1e-9).plot(label='with profiles')\n", + "(vol_days * 1e-9).plot(linestyle='--', label='from all days')\n", + "plt.ylabel('Volume (km$^3$)'); plt.legend()\n", + "print(f'Largest relative difference of the volume: {float(np.abs(vol_prof / vol_days - 1).max()):.1e}')" + ] + }, + { + "cell_type": "markdown", + "id": "3f326463", + "metadata": {}, + "source": [ + "The two runs take about the same time, and they agree, but not always to the last digit. The dynamical model amplifies the round-off differences of the mass balance: a difference in the 14th digit of the mass balance can change which time step the solver takes, and the volumes then differ by a tiny amount. This is the numerical noise of the dynamical model, which is also there when the same run is repeated on another computer.\n", + "\n", + "## When is the daily climate file still read?\n", + "\n", + "With the profiles, the model does not read the daily climate file when it is created. It reads it when it is needed for the first time:\n", + "\n", + "- for daily values (`get_daily_mb`, `get_daily_climate`), e.g. for daily hydrological output,\n", + "- when the temperature bias or the precipitation factor are given as 12 monthly values: the profiles need single values, and the mass balance is then computed from all the days." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "114b2a59", + "metadata": {}, + "outputs": [], + "source": [ + "# a daily value: the model reads the daily climate file now\n", + "mb_daily.get_daily_mb(heights[:3], year=utils.date_to_floatyear(2003, 7, 15))" + ] + }, + { + "cell_type": "markdown", + "id": "f32daa38", + "metadata": {}, + "source": [ + "## Many evaluations: the series cache\n", + "\n", + "Some routines evaluate the model hundreds or thousands of times on the same glacier geometry and period, for example `mb_calibration_to_rmsd`, a parameter grid, or a Bayesian sampler.\n", + "\n", + "The mass balance of a series of time steps is\n", + "\n", + "$$\\text{MB} = P_f \\cdot \\text{prcpsol}(\\tau) - d_f \\cdot \\text{tempformelt}(\\tau)$$\n", + "\n", + "The two interpolated fields depend on the altitudes, the time steps and the temperature bias, but not on the melt factor and the precipitation factor. When only these two change, repeating the interpolation is wasted time.\n", + "\n", + "**How the cache works.** A `DailyTIModel` with profiles remembers the two fields of the last series it computed (with `get_annual_mb_series`, `get_monthly_mb_series`, or `get_specific_mb` for several time steps). Each is stored together with what it was computed for: the altitudes, the time steps and the temperature bias. When the same combination is asked again, the stored fields are used and only the two multiplications are done. Another temperature bias or another geometry creates a new entry. You never have to reset anything, and the results never depend on the cache.\n", + "\n", + "It is on **whenever the profiles are used**. The number of remembered series is `mb_series_cache_size` (32 by default): a keyword of the `DailyTIModel`, or a parameter in `gdir.settings` or `cfg.PARAMS`. Zero switches the cache off, as in the model `mb_nocache` from above. Let's compare the two with a small parameter grid, at monthly resolution:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ed1a0360", + "metadata": {}, + "outputs": [], + "source": [ + "def search(mod):\n", + " for melt_f in np.linspace(3, 12, 20):\n", + " for prcp_fac in np.linspace(1, 4, 20):\n", + " mod.melt_f, mod.prcp_fac = melt_f, prcp_fac\n", + " mod.get_specific_mb(heights, widths, year=months, time_resolution='monthly')\n", + "\n", + "print(f'400 evaluations without cache: {best_time(lambda: search(mb_nocache), 3):.3f} s, '\n", + " f'with cache: {best_time(lambda: search(mb_daily), 3):.3f} s')\n", + "mb_daily.melt_f, mb_daily.prcp_fac, _ = calibrated" + ] + }, + { + "cell_type": "markdown", + "id": "c2041c51", + "metadata": {}, + "source": [ + "### Your own calibration: keep `temp_bias` in the outermost loop\n", + "\n", + "This is the one rule to remember when you write your own calibration or sampling routine. Every new `temp_bias` needs a new interpolation; `melt_f` and `prcp_fac` do not. So change `temp_bias` as rarely as possible.\n", + "\n", + "The order of the loops matters as soon as there are more values of `temp_bias` than remembered series. With `temp_bias` in the innermost loop, each of its values comes back only after all the others, when it is already forgotten:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1d6a1d06", + "metadata": {}, + "outputs": [], + "source": [ + "temp_biases = np.linspace(-2, 2, 40) # more than the 32 remembered series\n", + "melt_fs, prcp_facs = np.linspace(3, 12, 5), np.linspace(1, 4, 5)\n", + "\n", + "def evaluate(mod, temp_bias, melt_f, prcp_fac):\n", + " mod.temp_bias, mod.melt_f, mod.prcp_fac = temp_bias, melt_f, prcp_fac\n", + " mod.get_specific_mb(heights, widths, year=months, time_resolution='monthly')\n", + "\n", + "def temp_bias_outside(mod):\n", + " # good: the interpolation is done once per temp_bias\n", + " for temp_bias in temp_biases:\n", + " for melt_f in melt_fs:\n", + " for prcp_fac in prcp_facs:\n", + " evaluate(mod, temp_bias, melt_f, prcp_fac)\n", + "\n", + "def temp_bias_inside(mod):\n", + " # bad: a new temp_bias at each evaluation\n", + " for melt_f in melt_fs:\n", + " for prcp_fac in prcp_facs:\n", + " for temp_bias in temp_biases:\n", + " evaluate(mod, temp_bias, melt_f, prcp_fac)\n", + "\n", + "print(f'temp_bias in the outermost loop: {best_time(lambda: temp_bias_outside(mb_daily), 3):.3f} s')\n", + "print(f'temp_bias in the innermost loop: {best_time(lambda: temp_bias_inside(mb_daily), 3):.3f} s')\n", + "mb_daily.melt_f, mb_daily.prcp_fac, mb_daily.temp_bias = calibrated" + ] + }, + { + "cell_type": "markdown", + "id": "2f78d806", + "metadata": {}, + "source": [ + "The same holds for optimisers. An optimiser which changes all three parameters together (as `mb_calibration_to_rmsd` does when `temp_bias` is calibrated) proposes a new `temp_bias` at almost every step, and gains nothing from the cache. A nested search does: an outer search on `temp_bias`, and for each of its values an inner fit of `melt_f` and `prcp_fac`.\n", + "\n", + "Here is such a nested search. As observations we take the annual mass balance which was measured on Hintereisferner. To keep the example short we compare it with the modelled mass balance of the calendar years (the measurements are for hydrological years; a real calibration should use those, as `mb_calibration_to_rmsd` does). The model is evaluated at monthly resolution." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "27b788c5", + "metadata": {}, + "outputs": [], + "source": [ + "from scipy.optimize import minimize\n", + "\n", + "observations = ref_mb.loc[2000:2019].values\n", + "assert len(observations) == len(years)\n", + "# the allowed range of the two parameters, from the settings\n", + "bounds = [(gdir.settings[f'{k}_min'], gdir.settings[f'{k}_max'])\n", + " for k in ('melt_f', 'prcp_fac')]\n", + "\n", + "def nested_search(mod):\n", + " out = []\n", + " for temp_bias in np.linspace(-2, 2, 9): # the outer loop\n", + " mod.temp_bias = temp_bias\n", + "\n", + " def rmsd(x):\n", + " mod.melt_f, mod.prcp_fac = x\n", + " # monthly values, summed to the 20 years\n", + " smb = mod.get_specific_mb(heights, widths, year=months,\n", + " time_resolution='monthly')\n", + " return utils.rmsd(observations, smb.reshape(-1, 12).sum(axis=1))\n", + "\n", + " # the inner fit: only melt_f and prcp_fac change\n", + " res = minimize(rmsd, x0=[5.0, 2.5], method='L-BFGS-B', bounds=bounds)\n", + " out.append((temp_bias, res.x[0], res.x[1], res.fun, res.nfev))\n", + " mod.melt_f, mod.prcp_fac, mod.temp_bias = calibrated\n", + " return pd.DataFrame(out, columns=['temp_bias', 'melt_f', 'prcp_fac', 'rmsd',\n", + " 'evaluations']).set_index('temp_bias')\n", + "\n", + "t_cache = best_time(lambda: nested_search(mb_daily), 3)\n", + "t_nocache = best_time(lambda: nested_search(mb_nocache), 3)\n", + "results = nested_search(mb_daily)\n", + "print(f'{results.evaluations.sum()} evaluations: {t_cache:.2f} s with the cache, '\n", + " f'{t_nocache:.2f} s without')\n", + "results.round(3)" + ] + }, + { + "cell_type": "markdown", + "id": "ab087254", + "metadata": {}, + "source": [ + "Each value of `temp_bias` needs one interpolation, and all the evaluations of the inner fit use it again. The table also shows a well known property of this calibration problem: the parameters compensate each other, and the fit changes much less than the parameters do. Which set to take needs more information than the annual specific mass balance (see the [mass balance calibration tutorial](massbalance_calibration.ipynb)).\n", + "\n", + "**When it helps, and when not.**\n", + "\n", + "- It helps when `melt_f` and `prcp_fac` change and everything else stays the same.\n", + "- It does not help when `temp_bias` changes at every evaluation, in dynamical runs (the geometry changes), or for single calls of `get_annual_mb` and `get_monthly_mb`.\n", + "\n", + "### How much memory it uses: `mb_series_cache_max_mb`\n", + "\n", + "**What one remembered series costs.** One entry holds two arrays (`tempformelt` and `prcpsol`) with one value per time step and altitude, of 8 bytes each:\n", + "\n", + "$$\\text{size} = 2 \\cdot 8 \\cdot n_\\text{time steps} \\cdot n_\\text{altitudes} \\;\\text{bytes}$$\n", + "\n", + "For this glacier and some other typical cases:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "12426542", + "metadata": {}, + "outputs": [], + "source": [ + "def entry_size_mb(n_altitudes, n_time_steps):\n", + " return 2 * 8 * n_altitudes * n_time_steps / 1e6\n", + "\n", + "cases = [('this glacier (elevation bands), 20 years', len(heights), 20),\n", + " ('this glacier (elevation bands), 240 months', len(heights), 240),\n", + " ('centerlines with 300 grid points, 600 months', 300, 600),\n", + " ('2D, 10000 glacier pixels, 20 years', 10000, 20),\n", + " ('2D, 10000 glacier pixels, 240 months', 10000, 240)]\n", + "df = pd.DataFrame(cases, columns=['Geometry and period', 'Altitudes', 'Time steps'])\n", + "df['One entry (MB)'] = entry_size_mb(df['Altitudes'], df['Time steps'])\n", + "df" + ] + }, + { + "cell_type": "markdown", + "id": "76d4cb17", + "metadata": {}, + "source": [ + "**Two limits, whichever is reached first.**\n", + "\n", + "- `mb_series_cache_size` (default 32): the number of remembered series.\n", + "- `mb_series_cache_max_mb` (default 10): the memory, in MB, which **all remembered series of one model together** may use.\n", + "\n", + "When a new series does not fit, the **oldest ones are forgotten first** until it does. A series which **alone** is larger than `mb_series_cache_max_mb` is **not remembered at all**: it is computed again at each call, exactly as with `mb_series_cache_size=0`.\n", + "\n", + "**What this means in practice.**\n", + "\n", + "- Elevation bands: all 32 series fit (see the table), there is nothing to do.\n", + "- Centerlines with many grid points and long monthly series: only a few series fit (three in the example of the table). This is enough as long as the temperature bias does not change. For a search over many temperature biases, a larger limit helps.\n", + "- 2D geometries (`use_2d_mb=True` in the calibration tasks, where every glacier pixel is an altitude): short series (a small glacier, annual values) are remembered, long ones (many pixels and many months) are not. With the default, the cache is in effect **off for large 2D series**, and a model cannot use much memory by accident.\n", + "- The limit is per model. A glacier with several flowlines has one model, and one cache, per flowline (`MultipleFlowlineMassBalance`): the total is at most the number of flowlines times the limit. The same holds when you create several models, e.g. one per process in a parallel run.\n", + "- The results never depend on these two parameters, only the speed and the memory.\n", + "\n", + "**How to change it.** `mb_series_cache_max_mb` has no keyword. Set it in `cfg.PARAMS` (for all glaciers) or in `gdir.settings` (for one glacier and settings file) **before the model is created**: a model reads it once, when it is created. Changing it later does not change existing models.\n", + "\n", + "As an example we use 10000 altitudes, as a 2D geometry would have, and 240 months: 38 MB per series, more than the default limit." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e0322b99", + "metadata": {}, + "outputs": [], + "source": [ + "heights_2d = np.linspace(heights.min(), heights.max(), 10000)\n", + "\n", + "def two_calls(mod):\n", + " # the second call only gains if the first one was remembered\n", + " t = []\n", + " for melt_f in [5., 6.]:\n", + " mod.melt_f = melt_f\n", + " t0 = time.perf_counter()\n", + " mod.get_monthly_mb_series(heights_2d, months)\n", + " t.append(time.perf_counter() - t0)\n", + " return t\n", + "\n", + "# default limit of 10 MB: the series is too large to be remembered\n", + "mod = DailyTIModel(gdir, settings_filesuffix='_daily')\n", + "t = two_calls(mod)\n", + "print(f'limit {cfg.PARAMS[\"mb_series_cache_max_mb\"]:.0f} MB: '\n", + " f'first call {t[0]:.3f} s, second call {t[1]:.3f} s')\n", + "\n", + "# a larger limit, for all models created from now on ...\n", + "cfg.PARAMS['mb_series_cache_max_mb'] = 100\n", + "mod = DailyTIModel(gdir, settings_filesuffix='_daily')\n", + "t = two_calls(mod)\n", + "print(f'limit {cfg.PARAMS[\"mb_series_cache_max_mb\"]:.0f} MB: '\n", + " f'first call {t[0]:.3f} s, second call {t[1]:.3f} s')\n", + "cfg.PARAMS['mb_series_cache_max_mb'] = 10 # back to the default" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "73f07534", + "metadata": {}, + "outputs": [], + "source": [ + "# ... or for one glacier only: a settings file which takes all the rest from '_daily'\n", + "gdir.create_new_settings('_daily_large_cache', parent_filesuffix='_daily',\n", + " data={'mb_series_cache_max_mb': 100})\n", + "mod = DailyTIModel(gdir, settings_filesuffix='_daily_large_cache')\n", + "t = two_calls(mod)\n", + "print(f'first call {t[0]:.3f} s, second call {t[1]:.3f} s')" + ] + }, + { + "cell_type": "markdown", + "id": "016378bf", + "metadata": {}, + "source": [ + "How large should the limit be? At least the size of one entry (the formula above) times the number of series which should be remembered. For a calibration with a fixed temperature bias this is one series per model and time resolution; for a search over several temperature biases, one per value. Very long series (more than about two million values) are computed in pieces, and each piece is an entry of its own." + ] + }, + { + "cell_type": "markdown", + "id": "8fe17443", + "metadata": {}, + "source": [ + "## Good to know\n", + "\n", + "- The profiles are written to the glacier directory as `mb_profiles_.nc`. For other daily climate files (e.g. GCM data), give `filename` and `input_filesuffix` to `process_mb_profiles`, as for the model.\n", + "- They depend on the daily climate file and on the temperature thresholds (`temp_melt`, `temp_all_solid` and `temp_all_liq`). If one of them changes, run the task again; the model raises an error if the profiles do not fit.\n", + "- Annual profiles are for calendar years. For hydrological years, use monthly values.\n", + "- The profiles need single values for `temp_bias` and `prcp_fac`, and the constant temperature gradient of the settings.\n", + "- The profiles are optional: without `use_mb_profiles`, the `DailyTIModel` works as before." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "dba147bf", + "metadata": {}, + "outputs": [], + "source": [ + "import os\n", + "for f in ['climate_historical_daily.nc', 'mb_profiles_climate_historical_daily.nc']:\n", + " print(f'{f}: {os.path.getsize(os.path.join(gdir.dir, f)) / 1e6:.2f} MB')" + ] + }, + { + "cell_type": "markdown", + "id": "25798ec4", + "metadata": {}, + "source": [ + "## What's next?\n", + "\n", + "- look at the [mass balance calibration tutorial](massbalance_calibration.ipynb)\n", + "- return to the [OGGM documentation](https://docs.oggm.org)\n", + "- back to the [table of contents](../welcome.ipynb)" + ] + } + ], + "metadata": {}, + "nbformat": 4, + "nbformat_minor": 5 +} diff --git a/notebooks/welcome.ipynb b/notebooks/welcome.ipynb index 01816c29..826c928d 100644 --- a/notebooks/welcome.ipynb +++ b/notebooks/welcome.ipynb @@ -67,6 +67,7 @@ "\n", "- [Plotting the OGGM surface mass-balance, the ELA and AAR](tutorials/plot_mass_balance.ipynb)\n", "- [A look into the new mass balance calibration in OGGM v1.6](tutorials/massbalance_calibration.ipynb)\n", + "- [The daily mass balance model and its mass balance profiles](tutorials/daily_mb_profiles.ipynb)\n", "- [Global distribution of the mass-balance model parameters](tutorials/massbalance_global_params.ipynb)\n", "- [Mass balance parameter perturbation experiments with OGGM](tutorials/massbalance_perturbation.ipynb)" ]