Tip

For an interactive online version click here: Binder badge

HydroMT-SFINCS | Example 06

Example: making an animation

Create an animation of water levels and depths from SFINCS output.

The example used in this notebook is based on a regular SFINCS model, i.e. no subgrid tables are used. In the absence of the subgrid tables, SFINCS computes the water depth by simply substracting the bed levels from the water levels. The (maximum) water depth h(max) is stored in the NetCDF output (sfincs_map.nc).

For models without subgrid tables, maximum water depth is available directly from the SFINCS output; see Example 05A. For subgrid models, first downscale maximum water levels using a high-resolution elevation dataset, as shown in Example 05B. Apply the same per-timestep downscaling approach when making animations of subgrid results.

The workflow is organized into these steps:

  1. Read the model results.

  2. Plot instantaneous water depths on the model grid.

  3. Inspect water depth at a gauge location.

  4. Prepare and create an animation.

Import dependencies

[1]:
import geopandas as gpd
import xarray as xr

from hydromt_sfincs import SfincsModel, plots

We use the cartopy package to plot maps. This packages provides a simple interface to plot geographic data and add background satellite imagery.

Step 1: Read model results#

The model results in sfincs_map.nc are saved as in a staggered grid format, see SGRID convention. Here we show how to retrieve the face values and translate the dimensions from node indices (m, n) to (x, y) coordinates in order to plot the results on a map.

[2]:
# `sfincs_root` is the (relative) path to sfincs root.
sfincs_root = "sfincs_compound"
mod = SfincsModel(sfincs_root, mode="r")
[3]:
# we can simply read the model results (sfincs_map.nc and sfincs_his.nc) using the output.read method
mod.output.read()

Step 2: Plot instantaneous water depths over time#

When we are working with a model without subgrid, the output does contain (instantanuous) water depths. However, for subgrid models, we first have to create downscaled water depths using the modeled water levels and the high-resolution bed levels see notebook on downscaling water depths. To speed-up the creation of the animation, we only plot every …. th timestep of the results. In addition, in the absence of modeled water depths (so for subgrid models), we approximate the water depth using the water levels and (coarse) bed levels from the model. Replace that with your downscaled water depths!

[4]:
time_step = 4

# h from sfincs_map contains the water depths for each cell face. If not present, we approximate it from the surface and bed elevations.
if "h" not in mod.output.data:
    mod.output.data["h"] = mod.output.data["zs"] - mod.output.data["zb"]

# select only positive water depths
h = mod.output.data["h"].where(mod.output.data["h"] > 0)
h.attrs.update(long_name="water depth", unit="m")

# here we plot the water level every time_step-th hour
plots.plot_map_timesteps(h, time_step=time_step, vmax=4)
[4]:
(<Figure size 1500x2000 with 16 Axes>,
 array([[<Axes: title={'center': 'time = 2010-02-05T00:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-05T04:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-05T08:00:00.000000000'}, xlabel='x', ylabel='y'>],
        [<Axes: title={'center': 'time = 2010-02-05T12:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-05T16:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-05T20:00:00.000000000'}, xlabel='x', ylabel='y'>],
        [<Axes: title={'center': 'time = 2010-02-06T00:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-06T04:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-06T08:00:00.000000000'}, xlabel='x', ylabel='y'>],
        [<Axes: title={'center': 'time = 2010-02-06T12:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-06T16:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: title={'center': 'time = 2010-02-06T20:00:00.000000000'}, xlabel='x', ylabel='y'>],
        [<Axes: title={'center': 'time = 2010-02-07T00:00:00.000000000'}, xlabel='x', ylabel='y'>,
         <Axes: >, <Axes: >]], dtype=object))
../_images/_examples_6_make_results_animation_10_1.png

Step 3: Inspect water depth at a gauge#

Another way to look at the water depths over time, are the timeseries that were created by the model at pre-defined observation stations.

[5]:
# point_h contains the water depths at the sfincs.obs gauge locations
# see mod.plot_basemaps (or next figure) for the location of the observation points
# plot the water level at the specified gauge

station_id = 1

# Approximate water depth at the observation points (when not available for subgrid model)
if "point_h" not in mod.output.data:
    mod.output.data["point_h"] = mod.output.data["zs"] - mod.output.data["zb"]

h_point = mod.output.data["point_h"].rename({"stations": "station_id"})
h_point["station_id"] = h_point["station_id"].astype(int)

_ = h_point.sel({"station_id": station_id}).plot.line(
    x="time",
)
/tmp/ipykernel_6485/2989586721.py:11: UserWarning: rename 'stations' to 'station_id' does not create an index anymore. Try using swap_dims instead or use set_index after rename to create an indexed coordinate.
  h_point = mod.output.data["point_h"].rename({"stations": "station_id"})
../_images/_examples_6_make_results_animation_12_1.png

Step 4: Create animation#

An animation is also simple to make with matplotlib.animation method. Here we add the surface water level in blue colors next to the overland flood depth with viridis colormap. To make the water depth plots/animations more informative, we can again mask out permanent water or small water depths.

[6]:
# filter the water depth data to only include values above a minimum threshold
hmin = 0.05
da_h = mod.output.data["h"].copy()
da_h = da_h.where(da_h > hmin)
da_h.attrs.update(long_name="flood depth", unit="m")

Configure and render the animation#

Create an animation of the water depths over time. The configurations of the animation are specified in the cell below, change accordingly

[7]:
# Configuration of the animation

step = 1  # `step = 1` means one frame every `<step>` dtout.
interval = 250  # interval between frames in milliseconds
vmin = 0  # minimum value for the color scale
vmax = 3  # maximum value for the color scale
cmap = "viridis"  # colormap for the animation
alpha = 1.0  # transparency for the animation
save = False  # whether to save the animation as a video file
return_html = True  # whether to return an HTML animation for inline display

⚠️ Note: FFmpeg required

The inline preview is a compressed HTML5 video and requires the FFmpeg executable. Saving an MP4 (save = True) also requires FFmpeg. With Conda, install it using conda install -c conda-forge ffmpeg. If you only need a non-MP4 file, set return_html = False to skip the inline preview.

[8]:
plots.make_animation(
    data=da_h,
    bmap="sat",
    figsize=(11, 7),
    zoomlevel=12,
    step=step,
    interval=interval,
    vmin=vmin,
    vmax=vmax,
    cmap=cmap,
    alpha=alpha,
    title="SFINCS water depth",
    cbar_kwargs={"shrink": 0.6, "anchor": (0, 0)},
    save_path=mod.root.path / "figs" / "sfincs_h.mp4" if save else None,
    return_html=return_html,
)
[8]:

💡 NOTE: Animating subgrid resultsFor a subgrid animation, downscale the water level (zs) for each timestep separately using the high-resolution elevation data, then assemble the resulting high-resolution depth maps along the time dimension and animate that series. Do not pass the full time series to downscale_floodmap in one call: it reduces non-spatial dimensions to their maximum, which produces an event-maximum map rather than timestep-by-timestep depths.