{ "cells": [ { "cell_type": "code", "execution_count": 1, "id": "bd2d9bd5", "metadata": { "tags": [ "hide-cell" ] }, "outputs": [], "source": [ "# Suppress distracting outputs in these examples\n", "# Note: this cell should be hidden with the tag \"hide-cell\"\n", "import logging\n", "import warnings\n", "\n", "from rich import print\n", "\n", "warnings.filterwarnings(\"ignore\", category=UserWarning)\n", "logger = logging.getLogger(\"esmvalcore\")\n", "logger.setLevel(logging.WARNING)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "106d4a56", "metadata": {}, "source": [ "# Models" ] }, { "cell_type": "code", "execution_count": 2, "id": "e8b58319", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "/opt/conda/envs/ewc26/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n", " from .autonotebook import tqdm as notebook_tqdm\n" ] } ], "source": [ "import ewatercycle.models" ] }, { "attachments": {}, "cell_type": "markdown", "id": "ef669930", "metadata": { "tags": [] }, "source": [ "In eWaterCycle models can be added as plugins. The ewatercycle package itself does not ship with any models.\n", "Depending on who set up your system, some or all of the following models will already be available:\n", "\n", "* [\"leaky bucket\" toy model](https://github.com/eWaterCycle/ewatercycle-leakybucket)\n", "* [wflow](https://github.com/eWaterCycle/ewatercycle-wflow)\n", "* [pcrglobwb](https://github.com/eWaterCycle/ewatercycle-pcrglobwb)\n", "* [marrmot M01](https://github.com/eWaterCycle/ewatercycle-marrmot)\n", "* [marrmot M14](https://github.com/eWaterCycle/ewatercycle-marrmot)\n", "* [lisflood](https://github.com/eWaterCycle/ewatercycle-lisflood)\n", "* [hype](https://github.com/eWaterCycle/ewatercycle-hype)\n", "* [HBV](https://github.com/eWaterCycle/ewatercycle-hbv)\n", "* [SWMM](https://github.com/eWaterCycle/ewatercycle-swmm/)\n", "\n", "The process for adding new models is documented in [Adding models](https://ewatercycle.readthedocs.io/en/latest/adding_models.html)" ] }, { "cell_type": "markdown", "id": "9f9f7e91", "metadata": {}, "source": [ "To show the currently available models do:" ] }, { "cell_type": "code", "execution_count": 3, "id": "7196661d", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
ModelSources[\n", " \"HBV\",\n", " \"HBVLocal\",\n", " \"Hype\",\n", " \"LeakyBucket\",\n", " \"Lisflood\",\n", " \"MarrmotM01\",\n", " \"MarrmotM14\",\n", " \"PCRGlobWB\",\n", " \"SWMM\",\n", " \"Wflow\",\n", " \"WflowJl\",\n", "]\n", "\n" ], "text/plain": [ "\u001b[34mModelSources\u001b[0m\u001b[1;34m[\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"HBV\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"HBVLocal\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"Hype\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"LeakyBucket\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"Lisflood\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"MarrmotM01\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"MarrmotM14\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"PCRGlobWB\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"SWMM\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"Wflow\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[32m \u001b[0m\u001b[32m\"WflowJl\"\u001b[0m\u001b[32m,\u001b[0m\n", "\u001b[1;34m]\u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "print(ewatercycle.models.sources)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "04d51cee", "metadata": {}, "source": [ "## Creating, setting up, and initializing a model instance\n", "\n", "The way models are created, setup, and initialized matches [PyMT](https://pymt.readthedocs.io/en/latest/quickstart.html#run-a-model) as much as possible.\n", "To see the all available methods and properties, see the [API reference for the eWaterCycleModel](#ewatercycle.base.model.eWaterCycleModel){.external}.\n", "\n", "There are three main steps required before running a model:\n", "\n", "- instantiate (create a python object that represents the model)\n", "- setup (create a container with the right model, directories, and configuration files)\n", "- initialize (start the model inside the container)\n", "\n", "To a new user, these steps can be confusing as they seem to be related to \"starting a model\". However, you will see that there are some useful things that we can do in between each of these steps. As a side effect, splitting these steps also makes it easier to run a lot of models in parallel (e.g. for calibration). Experience tells us that you will quickly get used to it. \n", "\n", "When a model instance is created, we have to specify the version and pass in a suitable parameter set and forcing. " ] }, { "cell_type": "code", "execution_count": 4, "id": "53d63a85", "metadata": {}, "outputs": [], "source": [ "import ewatercycle.forcing\n", "import ewatercycle.models\n", "import ewatercycle.parameter_sets\n", "\n", "parameter_set = ewatercycle.parameter_sets.available_parameter_sets(\n", " target_model=\"wflow\"\n", ")[\"wflow_rhine_sbm_nc\"]\n", "forcing = ewatercycle.forcing.sources[\"WflowForcing\"](\n", " directory=str(parameter_set.directory),\n", " start_time=\"1991-01-01T00:00:00Z\",\n", " end_time=\"1991-12-31T00:00:00Z\",\n", " shape=None,\n", " # Additional information about the external forcing data needed for the model configuration\n", " netcdfinput=\"inmaps.nc\",\n", " Precipitation=\"/P\",\n", " EvapoTranspiration=\"/PET\",\n", " Temperature=\"/TEMP\",\n", ")" ] }, { "cell_type": "code", "execution_count": 5, "id": "68325e78", "metadata": {}, "outputs": [ { "name": "stderr", "output_type": "stream", "text": [ "WARNING:ewatercycle_wflow.model:Config file from parameter set is missing API section, adding section\n", "WARNING:ewatercycle_wflow.model:Config file from parameter set is missing RiverRunoff option in API section, added it with value '2, m/s option'\n" ] } ], "source": [ "model_instance = ewatercycle.models.Wflow(\n", " version=\"2020.1.3\", parameter_set=parameter_set, forcing=forcing\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "5392967b", "metadata": {}, "source": [ "In some specific cases the parameter set (e.g. for marrmot) or the forcing (e.g. when it is already included in the parameter set) is not needed.\n", "\n", "Most models have a variety of parameters that can be set. An opiniated subset of these parameters is exposed through the eWaterCycle API. We focus on those settings that are relevant from a scientific point of view and prefer to hide technical settings. These parameters and their default values can be inspected as follows:" ] }, { "cell_type": "code", "execution_count": 6, "id": "45b31a03", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "dict_items([('start_time', '1991-01-01T00:00:00Z'), ('end_time', '1991-12-31T00:00:00Z')])" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "model_instance.parameters" ] }, { "attachments": {}, "cell_type": "markdown", "id": "283d23db", "metadata": {}, "source": [ "The start date and end date are automatically set based on the forcing data. \n", "\n", "Alternative values for each of these parameters can be passed on to the setup function:" ] }, { "cell_type": "code", "execution_count": 7, "id": "d0d20ed8", "metadata": {}, "outputs": [], "source": [ "cfg_file, cfg_dir = model_instance.setup(\n", " end_time=\"1991-12-15T00:00:00Z\",\n", " # use `cfg_dir=\"/path/to/output_dir\"` to specify the output directory\n", ")" ] }, { "attachments": {}, "cell_type": "markdown", "id": "55358151", "metadata": {}, "source": [ "The `setup` function does the following:\n", "\n", "- Create a config directory which serves as the current working directory for the mode instance\n", "- Creates a configuration file in this directory based on the settings\n", "- Starts a container with the requested model version and access to the forcing and parameter sets.\n", "- Input is mounted read-only, the working directory is mounted read-write (if a model cannot cope with inputs outside the working directory, the input will be copied).\n", "- Setup will complain about incompatible model version, parameter_set, and forcing.\n", "\n", "After `setup` but before `initialize` everything is good-to-go, but nothing has been done yet. This is\n", "an opportunity to inspect the generated configuration file, and make any changes manually that could not be\n", "done through the setup method. \n", "\n", "To modify the config file: print the path, open it in an editor, and save:" ] }, { "cell_type": "code", "execution_count": 8, "id": "c1103c60-acfd-4d85-a963-1dfda63dff05", "metadata": {}, "outputs": [ { "data": { "text/html": [ "
/home/mmelotto/ewatercycle/docs/user_guide/wflow_20260915_140424/wflow_ewatercycle.ini\n", "\n" ], "text/plain": [ "\u001b[35m/home/mmelotto/ewatercycle/docs/user_guide/wflow_20260915_140424/\u001b[0m\u001b[95mwflow_ewatercycle.ini\u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "print(cfg_file)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "17fce55e", "metadata": {}, "source": [ "Once you're happy with the setup, it is time to initialize the model. You'll have to pass in the config file, even if you've not made any changes:" ] }, { "cell_type": "code", "execution_count": 9, "id": "37029f39", "metadata": {}, "outputs": [], "source": [ "model_instance.initialize(cfg_file) # for some models, this step can take some time" ] }, { "cell_type": "markdown", "id": "d94ad9b6", "metadata": {}, "source": [ "Note that if anything goes wrong on the model side during initialization or at any other point in time you can inspect the model's logs. For example, if some input file is missing or corrupt.\n", "In this case you would do:\n", "\n", "```py\n", "print(model_instance.logs)\n", "```" ] }, { "attachments": {}, "cell_type": "markdown", "id": "57092c12", "metadata": {}, "source": [ "## Running (and interacting with) a model\n", "\n", "A model instance can be controlled by calling functions for running a single timestep (`update`), setting variables, and getting variables. Besides the rather lowlevel BMI functions like `get_value` and `set_value`, we also added convenience functions such as `get_value_as_xarray`, `get_value_at_coords`, `time_as_datetime`, and `time_as_isostr`. These make it even more pleasant to interact with the model.\n", "\n", "For example, to run our model instance from start to finish, fetching the value of variable `discharge` at the location of a grdc station:" ] }, { "cell_type": "code", "execution_count": 10, "id": "e04303a6", "metadata": {}, "outputs": [], "source": [ "grdc_latitude = 51.756918\n", "grdc_longitude = 6.395395" ] }, { "cell_type": "code", "execution_count": 11, "id": "9af1524b", "metadata": {}, "outputs": [], "source": [ "output = []\n", "timestamps = []\n", "while model_instance.time < model_instance.end_time:\n", " model_instance.update()\n", "\n", " discharge = model_instance.get_value_at_coords(\n", " \"RiverRunoff\", lon=[grdc_longitude], lat=[grdc_latitude]\n", " )[0]\n", " output.append(discharge)\n", " timestamps.append(model_instance.time_as_datetime)\n", "\n", " # Here you could do whatever you like, e.g. update soil moisture values before doing the next timestep." ] }, { "attachments": {}, "cell_type": "markdown", "id": "c6f9d8a4", "metadata": {}, "source": [ "We can also get the entire model field at a single time step. To simply plot it:" ] }, { "cell_type": "code", "execution_count": 12, "id": "16ad7cc7", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "
| \n", " | id | \n", "GRDC | \n", "
|---|---|---|
| time | \n", "\n", " | \n", " |
| 1991-01-01 | \n", "6335020 | \n", "4510.0 | \n", "
| 1991-01-02 | \n", "6335020 | \n", "4850.0 | \n", "
| 1991-01-03 | \n", "6335020 | \n", "5190.0 | \n", "
| 1991-01-04 | \n", "6335020 | \n", "5500.0 | \n", "
| 1991-01-05 | \n", "6335020 | \n", "6020.0 | \n", "
{\n", " 'title': 'MEAN DAILY DISCHARGE (Q)',\n", " 'Conventions': 'CF-1.7',\n", " 'references': 'grdc.bafg.de',\n", " 'institution': 'GRDC',\n", " 'history': 'Converted from 6335020_Q_Day.Cmd.txt of 2019-03-27 to netcdf by eWaterCycle Python package',\n", " 'missing_value': '-999.000'\n", "}\n", "\n" ], "text/plain": [ "\u001b[1m{\u001b[0m\n", " \u001b[32m'title'\u001b[0m: \u001b[32m'MEAN DAILY DISCHARGE \u001b[0m\u001b[32m(\u001b[0m\u001b[32mQ\u001b[0m\u001b[32m)\u001b[0m\u001b[32m'\u001b[0m,\n", " \u001b[32m'Conventions'\u001b[0m: \u001b[32m'CF-1.7'\u001b[0m,\n", " \u001b[32m'references'\u001b[0m: \u001b[32m'grdc.bafg.de'\u001b[0m,\n", " \u001b[32m'institution'\u001b[0m: \u001b[32m'GRDC'\u001b[0m,\n", " \u001b[32m'history'\u001b[0m: \u001b[32m'Converted from 6335020_Q_Day.Cmd.txt of 2019-03-27 to netcdf by eWaterCycle Python package'\u001b[0m,\n", " \u001b[32m'missing_value'\u001b[0m: \u001b[32m'-999.000'\u001b[0m\n", "\u001b[1m}\u001b[0m\n" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "print(observations.attrs)" ] }, { "attachments": {}, "cell_type": "markdown", "id": "3ca0a60a", "metadata": {}, "source": [ "# Analysis\n", "\n", "To easily analyse model output, eWaterCycle also includes an `analysis` module." ] }, { "cell_type": "code", "execution_count": 21, "id": "4a251261", "metadata": {}, "outputs": [], "source": [ "import pandas as pd\n", "\n", "import ewatercycle.analysis" ] }, { "attachments": {}, "cell_type": "markdown", "id": "2583f279", "metadata": {}, "source": [ "For example, we will plot a hydrograph of the model run and GRDC observations. To this end, we combine the two timeseries in a single dataframe" ] }, { "cell_type": "code", "execution_count": 22, "id": "a0d0309b", "metadata": {}, "outputs": [], "source": [ "model_discharge = pd.Series(output, index=pd.DatetimeIndex(timestamps), name=\"wflow\")\n", "\n", "combined_discharge = (\n", " observations[\"GRDC\"].to_dataframe()[[\"GRDC\"]].join(model_discharge, how=\"inner\")\n", ")" ] }, { "cell_type": "code", "execution_count": 23, "id": "96923a0d", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "(