Example 04#
Example 04 models the Nançon catchment (Ille-et-Vilaine) with MODFLOW 6, from 2000
to 2002 in monthly stress periods. As the recharge swings between wet winters and dry summers,
the cells where the water table reaches the ground spread out and draw back. The example is two
files. project.toml says the model, its figures and its exports, and hmp run plays it in
about a minute and a half. py1_run_and_plot.py plays the same file one step at a time from
Python, looks at what each step built, and tries three values of Sy.
Get the example#
hmp workspace init ~/hydromodpy
hmp example add 04 -w ~/hydromodpy
cd ~/hydromodpy/projects/04_streamflow_intermittence_in_transient
hmp example add downloads the files of the example, about 92 MiB, most of it a regional DEM.
Files are cached by content, so a second workspace costs nothing. hmp example list shows the
examples your version ships and hmp example show 04 lists the files one by one.
hmp example add 00 07 08 installs several examples at once and hmp example add --all
installs every one. Each becomes a project of the workspace, and the regional DEM they share
is downloaded once.
The model file#
hmp run plays the file as one forward simulation, as workflow.mode says. The file
then names the catchment. [site] names it and its gauge, NANCON.
Every series below reads that station: the discharge, and the SIM2 recharge and runoff averaged
over the catchment. [metrics] sets the window the discharge is scored on, 2001 and 2002, so
the year 2000 is spin-up.
11# hmp run plays this file as one forward simulation. A calibration file that 12# names this one as its base_config writes mode = "calibration" in its own 13# [workflow] table. 14[workflow] 15mode = "simulation"
17# The catchment. The gauge is the station of every series below: the discharge, 18# the recharge and the runoff read station NANCON. The recharge and the runoff 19# are the SIM2 means over the catchment. The uri is the Hub'Eau code of the 20# site, a key that survives a move to another workspace. 21[site] 22name = "nancon" 23label = "Le Nançon à Lécousse" 24gauge = "NANCON" 25uri = "hubeau:J0014010"
27# The discharge is scored on 2001 and 2002. The year 2000 is spin-up. 28[metrics] 29window = { start = "2001-01-01", end = "2002-12-31" }
31[simulation] 32name = "nancon_intermittence_mf6" 33description = "Nancon catchment, monthly transient 2000-2002, seasonal seepage intermittence."
35# Thirty-six monthly stress periods, one time step each. 36[simulation.time] 37start_datetime = "2000-01-01" 38end_datetime = "2002-12-31" 39step_value = "1 month"
41[[simulation.process]] 42id = "flow_main" 43kind = "flow" 44solvers = ["modflow6"]
The catchment is cut out of a regional DEM of 75 m, upstream of the outlet, after the depressions of the DEM are breached. The domain is the box around the catchment, 172 by 157 cells, and the aquifer is one layer of 30 m under the ground.
46# The catchment is cut out of a regional 75 m DEM, upstream of the outlet, 47# after the depressions of the DEM are breached. The domain is the box around 48# the catchment widened by 10 % of the square root of its area: 172 x 157 cells. 49[geographic] 50crs_project = "EPSG:2154" 51dem_correc_type = "breach"
53[geographic.catchment] 54kind = "from_outlet_coord" 55x_outlet = 389285.910 56y_outlet = 6816518.749 57snap_dist = "150 m" 58buff_area = "10% of sqrt(area)"
60# One layer, 30 m thick under the ground surface. 61[domain.depth_model] 62kind = "constant_thickness" 63thickness = "30 m"
[data] lists what the run reads, each from a file of the shared data/ folder of the
workspace, named by workspace: and read in the folder of its variable. The discharge, the
recharge and the runoff are chronicles of the station site.gauge names, each read with
the location file of its folder, which gives the place and the unit of the station.
65# The DEM, the mapped streams, the gauge, and the monthly recharge and runoff of 66# station NANCON. The mapped streams are drawn and exported. The model does not 67# read them. Each name is read in the folder of its variable, data/dem/, 68# data/hydrometry/ and so on. A chronicle CSV is read with the location file of 69# its folder, here hydrometry_custom_LOC.csv, recharge_custom_LOC.csv and 70# runoff_custom_LOC.csv, which give the place and the unit of station NANCON. 71[data] 72types = ["dem", "hydrography", "hydrometry", "recharge", "runoff"]
74[[data.dem.sources]] 75source = "file" 76path = "workspace:DEM_armorican_massif.tif"
78[[data.hydrography.sources]] 79source = "file" 80path = "workspace:nancon_stream_network.gpkg"
82# Daily discharge of the gauge, 1982 to 2022. 83[[data.hydrometry.sources]] 84source = "file" 85path = "workspace:hydrometry_custom_NANCON_19820201_20220125_D.csv"
87# Monthly SIM2 recharge and runoff of the catchment, 2000 to 2002, in mm/day. 88[[data.recharge.sources]] 89source = "file" 90path = "workspace:recharge_custom_NANCON_20000101_20021231_M.csv"
92[[data.runoff.sources]] 93source = "file" 94path = "workspace:runoff_custom_NANCON_20000101_20021231_M.csv"
The flow is transient, so the heads move from one month to the next and the aquifer stores water. The aquifer has one K, one Sy and one Ss. Every cell drains at the ground, with a conductance that follows K. The first month is solved in steady state under the recharge of January 2000, so the run starts from a wet winter water table.
96# The heads are solved through the 36 months, with storage. The first month is 97# solved in steady state, and [flow.sinks_sources.recharge] says under which 98# recharge. 99[flow] 100flow_regime = "transient" 101first_period_steady = true # No period adds to the steady state, but the first period is solved in steady state. 102param_list = ["K", "Sy", "Ss"]
104# py1_run_and_plot.py gives Sy three values: 0.001, 0.05 and 0.3. 105[flow.param.K.field] 106kind = "homogeneous" 107unit = "m/s" 108value = 5e-5
110[flow.param.Sy.field] 111kind = "homogeneous" 112unit = "-" 113value = 0.05
115[flow.param.Ss.field] 116kind = "homogeneous" 117unit = "m-1" 118value = 1e-5
120# Every cell drains at the ground surface. The conductance follows K, 121# C = K * cell area / 1 m. 122[flow.bc.drainage] 123enabled = true
125# January 2000 is solved in steady state under the recharge of January, so the 126# run starts from a wet winter water table. 127[flow.sinks_sources.recharge] 128enabled = true 129first_clim = "first"
The last part lists the figures and the files the run writes. A figure is a variable at a time, with the layers drawn over it, or a preset. An export block says what to write and when, and the format follows the data.
131# The figures land in runs/nancon_intermittence_mf6/figures/. Each one that 132# applies and fails stops the run, so a broken figure cannot go unseen. 133[display] 134on_error = "raise"
136[[display.figure]] 137preset = "watershed_id_card"
139[[display.figure]] 140variable = "topography" 141overlays = ["mesh", "outline", "network", "outlet"]
143# October 2002, the driest month of the record: the water-table depth with the 144# seepage cells, then a section from south to north through the outlet. 145[[display.figure]] 146variable = "watertable_depth" 147time = "2002-10-15" 148overlays = ["seepage", "outline"] 149limits = [0.0, 15.0] 150line = [[389175.0, 6815000.0], [389175.0, 6826000.0]]
152[[display.figure]] 153variable = "watertable_elevation" 154type = "section" 155name = "section_south_north" 156time = "2002-10-15" 157line = [[389175.0, 6815000.0], [389175.0, 6826000.0]]
159# The share of the 36 months each cell seeps. 160[[display.figure]] 161variable = "simulated_active_network" 162reduce = "frequency" 163overlays = ["outline", "network"]
165# The discharge against the gauge on a log axis, the seepage share of the 166# catchment beside the discharge, and what enters and leaves each month. 167[[display.figure]] 168preset = "hydrograph" 169scale = "log" 170name = "hydrograph_log"
172[[display.figure]] 173preset = "network_expansion"
175[[display.figure]] 176preset = "water_budget"
181# The catchment and the mapped streams: GeoPackage. 182[[export]] 183variable = ["watershed", "hydrographic_network_reference"]
185# The water-table depth and the seepage cells of October 2002: one GeoTIFF each. 186[[export]] 187variable = ["watertable_depth", "seepage_mask"] 188time = "2002-10-15"
190# Simulated and gauged discharge, month by month: CSV. 191[[export]] 192variable = ["discharge", "discharge_obs"]
194# The water budget of every month: CSV. 195[[export]] 196variable = "budget"
Run the file#
hmp run project.toml
import hydromodpy as hmp
run = hmp.run("project.toml").open()
print(run.name)
A relative path is read from the folder you are in. hmp.run returns the
Run, whose reference page lists what it reads.
The run writes its figures to runs/nancon_intermittence_mf6/figures/ and its exports to
runs/nancon_intermittence_mf6/exports/. The last line gives the name of the run and the NSE
of the discharge at the gauge, about 0.97.
Run an unchanged file a second time and nothing is computed. The command says which run is
already there, and hmp run --force computes it again. Edit the file, even one value, and the
second run is a new one, runs/nancon_intermittence_mf6_v2/, then _v3. A name is never
given out again: hmp ls lists the versions,
hmp diff compares them, and a deleted run goes to the project
trash.
What can go wrong#
Message |
Cause |
What to do |
|---|---|---|
|
The coordinate of the file does not fall on a stream cell of the DEM, so the outlet moves to the cell with the largest flow accumulation in a window of |
Nothing, here. A move close to the limit means the coordinate is far from the stream, so check it. |
|
A very small Sy lets the water table move by metres in a month, and MODFLOW 6 does not converge in one time step. The script meets it with Sy = 0.001. |
Cut each month in several time steps with |
The script, step by step#
py1_run_and_plot.py sits next to the file. It finds the project from its own location, so it
runs from any folder, and it can be stepped through cell by cell (# %%) in Spyder or VS Code.
It plays the model in a lab, which builds the model in memory
one step at a time and writes no run until it is asked to.
After load_data, the forcing of the station is in memory, one value per month. The script
draws it.
state = lab.advance("load_data")
print(state.geographic)
print(state.data)
# The recharge and the runoff over the catchment, one value per month in mm/day. The model takes
# the recharge, and the runoff is added to the drain flow to give the discharge.
forcing = pd.DataFrame(
{
name: getattr(state.data, name).points[0].data.set_index("datetime")["value"]
for name in ("recharge", "runoff")
}
)
print(forcing.describe().round(2).to_string())
fig, ax = plt.subplots(figsize=(7, 3))
ax.plot(forcing.index, forcing["recharge"], color="dodgerblue", lw=2, label="recharge")
ax.plot(forcing.index, forcing["runoff"], color="navy", lw=2, label="runoff")
ax.set_ylabel("mm/day")
ax.legend()
fig.savefig(FIGURES / "recharge_and_runoff.png", dpi=150, bbox_inches="tight")
A run stopped at prepare_solver already stores the ground of every cell, so it draws the mesh
on the relief before anything is solved.
# A run stopped at `prepare_solver` stores the ground of every cell, so it draws the mesh.
state = lab.advance("prepare_solver")
print(state.model)
before = lab.run(until_step="prepare_solver")
print(
before.figure(
"topography",
overlays=["mesh", "outline", "network", "outlet"],
save=FIGURES / "mesh_on_relief.png",
)
)
Then Sy takes three values, and each one is kept as a run with the figures and the files of
project.toml. The value of the file gives the run of project.toml, so it is not solved
twice. With Sy = 0.001 the water table moves by metres in a month, and MODFLOW 6 needs four
time steps per month to converge.
# Sy sets how much water the aquifer stores for a metre of water table. Each run writes the
# figures and the files of project.toml. Sy = 0.05 is the value of the file, so its run is
# the run of project.toml.
SY = {"small": 0.001, "file": 0.05, "large": 0.3}
runs = {}
for label, sy in SY.items():
# With Sy = 0.001 the water table moves by metres in a month, and MODFLOW 6 needs four
# time steps per month to converge. That run takes about three minutes.
steps = 4 if label == "small" else 1
lab.set({"Sy": sy, "simulation.time.substeps_per_period": steps})
runs[label] = lab.run(None if label == "file" else f"nancon_sy_{label}")
lab.close()
Each run gives the months when the catchment seeps the least and the most, and run.figure
draws the seepage cells and the water table of these two months from the sealed run, so
nothing is solved again. A small Sy lets the water table follow each month: the network swells
in winter and nearly dries in summer. A large Sy smooths the year.
# The fields are stored by month. Each month is named by its first day, and the figures take
# the middle of the month. Only the cells of the catchment are counted.
rows = []
for label, run in runs.items():
months = run.periods.edges[:-1]
seeps = run.read("seepage_mask").to_numpy()[:, run.catchment_mask.ravel()] > 0
share = pd.Series(seeps.mean(axis=1) * 100, index=months)
scores = run.metrics.set_index("metric")["value"]
rows.append(
{
"Sy": SY[label],
"least (%)": share.min(),
"in": share.idxmin().strftime("%Y-%m"),
"most (%)": share.max(),
"in ": share.idxmax().strftime("%Y-%m"),
"NSE": scores["nse"],
"NSE log": scores["nse_log"],
}
)
for word, month in (("least", share.idxmin()), ("most", share.idxmax())):
middle = (month + pd.Timedelta(days=14)).strftime("%Y-%m-%d")
print(
run.figure(
"seepage_mask",
time=middle,
overlays=["outline"],
save=FIGURES / f"seepage_sy_{label}_{word}.png",
)
)
print(
run.figure(
"watertable_elevation",
type="section",
time=middle,
line=SECTION,
save=FIGURES / f"section_sy_{label}_{word}.png",
)
)
# A small Sy lets the water table follow each month, so the network swells in winter and
# nearly dries in summer. A large Sy smooths the year.
print(pd.DataFrame(rows).set_index("Sy").round(2).to_string())
The script takes about six minutes, most of it the run with the small Sy. Its figures land in
summary/figures/, beside the runs.
Then#
Calibrate K on a network searches K on the mapped network of another catchment. Work in the lab lists every member of the lab, and Run step by step stops a run after a given step. The reference has one card per key of the file.