Add a config field#
Every TOML knob in HydroModPy is backed by a Pydantic v2 model that forbids extra keys. This page covers a field in an existing section, a new section, and the way to write the field so that the generated parameter reference documents it. The reference is built from the models alone, so the declaration of the field is its documentation.
Files to edit#
A section lives in the package it configures. SECTIONS in
hydromodpy/config/section_loader.py holds one row per section of the root and
names its loader and its model, and HydroModPyConfig in
hydromodpy/config/hydromodpy_config.py holds the field of each section. Open the
model there and add the field to it.
The settings of a flow solver are not a section of the root. A key of [solver]
that is not one of its own fields names a flow solver, and its table is validated by
the options class that the adapter declares, for example
hydromodpy/solver/modflow6/modflow6_config.py. To add a field to such a table,
add it on that class with the same rules. SolverConfig.named_tables hands these
classes to the schema, the template and the parameter pages, so none of them needs a
line for the new field. A field that every flow solver reads belongs to [solver]
itself. If a solver ignores it, the solver leaves it out of supports and a file
that sets it is refused when it is read.
A model inherits from HydroModelBase, which forbids extra keys and validates on
assignment. Each field carries a Profile annotation and a
Field(..., description="...").
The contract of a field#
A quantity uses the unit aliases of hydromodpy/core/units/types.py (Length,
Area, Time, FlowRate, Velocity, HydraulicConductivity, and so on).
Each one has a canonical SI unit. A bare number in the file is read in that unit, and
a string such as "50 m" or "0.36 m/h" is converted.
The profile says who sees the field in the templates, the JSON Schema and the
frontend forms. Use Profile.USER unless the field is irrelevant to a
hydrogeologist.
class Profile(IntEnum):
"""Visibility profile for a configuration field."""
USER = 1 # hydrogeologist: physics, paths, project IO
DEV = 2 # developer: tolerances, backends, cache flags
EXPERT = 3 # MODFLOW/Boussinesq/pint internals
The minimal skeleton of a field reads as follows.
from typing import Annotated
from pydantic import Field
from hydromodpy.core.config_kit.profile import Profile
from hydromodpy.core.units.types import HydraulicConductivity
class FlowConfig(HydroModelBase):
k_aquifer: Annotated[HydraulicConductivity, Profile.USER] = Field(
default=1e-5,
description="Aquifer hydraulic conductivity (canonical: m/s).",
examples=[1e-4, "0.36 m/h"],
)
# not checked: k_aquifer is the example of this page, not a key of the model
[flow]
k_aquifer = "0.36 m/h" # converted to m/s
A field that holds a path carries the marker InputFile(role=..., category=...,
portable=...) of hydromodpy/core/tracking/input_file.py in its Annotated
metadata. The manifest of a run then lists the file with its canonical path and its
SHA-256.
@dataclass(frozen=True)
class InputFile:
"""Pydantic field marker for a user-provided input path.
Attach as an ``Annotated`` metadata entry on any ``Path`` or ``str``
field that points to an on-disk file or directory. The walker discovers these
markers at runtime and produces tracked-file entries. ``role`` is also the
folder of the file under the workspace data folder, so ``workspace:<name>``
reads ``data/<role>/<name>``.
"""
role: str
category: str
portable: bool = True
Validators#
Use @field_validator(mode="before") to normalize and @model_validator(mode="after")
for a rule between fields of one model. Keep them small.
A rule that reads two sections belongs to neither of them. It is one row of
CROSS_RULES in hydromodpy/config/cross_checks.py, a CrossRule named by its
function.
@dataclass(frozen=True)
class CrossRule:
"""One rule that reads several validated sections together.
``reads`` names the root sections the rule reads, so the check of a draft runs
it only once each of them is complete. ``rule(sections, *, sealed)`` reads the
sections as attributes, raises a ``ValueError`` or a typed error on a
refusal, and returns the warnings it gives. ``code`` is the check code of its
refusal. The name of the rule is the name of its function.
"""
rule: Callable[..., Iterable[str] | None]
reads: frozenset[str]
code: str = "cross_rule"
reads_the_time: bool = False
"""True hands the rule, as ``time``, the window and the boundaries the walk builds once."""
@property
def name(self) -> str:
return self.rule.__name__
The check of an incomplete document runs the rule once every section in reads is
complete. A test holds reads equal to what the function reads, so a section
missing from it would let the rule run too early.
Add a new section#
Create the Pydantic model in the package it configures.
Add the field to
HydroModPyConfig, with a default factory orNone, and its row inSECTIONS.from_tomlandcheckwalk that one table.If a launcher dispatches on the section, wire it in
hydromodpy/project/dispatch/workflow.py.Regenerate the committed JSON Schema with
python -m tools.docs.schema_export.tests/unit/docs/test_docs_config_consistency.pyfails while the file indocs/source/_static/differs from what the code exports.
Describe the field#
The parameter reference is generated from the models, so nothing is written on a page. Change the field and the next build shows the change wherever the key appears. The table says what the reference reads from a declaration.
The reader sees |
It comes from |
|---|---|
The path of the key |
The model tree under |
The summary line, and the text of the card |
The first sentence of |
The unit |
A quantity type, else |
The default, or required |
|
The range, the allowed values |
|
What each value does |
|
The value on a required line |
The first item of |
Shown by default, or behind the developer and expert button |
The |
When the key is read |
|
The calibrable badge and its search space |
|
The experimental and deprecated badges |
|
field_metadata lives in hydromodpy/core/config_kit/field_metadata.py. It
refuses an unknown key at import, so a typo fails the tests and not the page.
The first sentence of the description is the summary. It shows on the line of the key, in the tree of the whole file and in the search. Make it say what the key sets, in the words of the person who writes the file. The conditions and the exceptions come after it.
Rules for the values:
A choice between values is a
Literal, and every value is explained invalue_docs. The search finds a key by the name of one of its values.A number has a unit.
A key read only in some cases says so with
VisibleWhen, so the card shows the condition on its own line.A required key with no default has an example in
Field(examples=[...]). Never take it from an example project.
Build the documentation (make -C docs html-strict) to check the page of the
section. The build fails on a cited key that does not exist. The tree of the whole
file, The whole file as a tree, shows the key in context.
Test#
A unit test under
tests/unit/config/for the accept and reject cases: extra keys refused, units parsed, validators raised on bad combinations.An integration test if the field changes the dispatched workflow.
hmp check <toml> validates a candidate file against the model. It lists every
fault at once, and --partial accepts a file that still lacks required keys.
Rename, move or remove a key#
A stable key moves under the rules of Versions and stability. A key moved after 2.0.0 keeps loading until the next major version, and inside the 2 line a key is never removed, so a file written for 2.0.0 loads in every 2.x. In one change:
Add a
[[migration]]row ofdocument = "config"tohydromodpy/schema/changes.toml. Useoldandnewfor a key or a table that moves,key,old_valueandnew_valuefor a value that takes another name, oroldandinsteadfor a key that leaves, which the register refuses after the first release of a major version.sinceis the version that ships the change. Addrulewhen the row cannot say the whole change. It names a function ofRULESinhydromodpy/config/config_migration.py. A load then reads the old name with a warning, andhmp doctor --fix-configrewrites the file and the files it inherits. The same row also covers the dotted paths that name the key, such as theoverridesof a calibration phase,--set,HMP_SET_*and the keys of[sites.bind].List the old key in the
model_refused_keysof the model, so a config built in Python is told what to write. Under[calibration],renamed_to(old, new, meaning)ofhydromodpy/calibration/config_terms.pywrites that sentence.Name the old path in
renamed_fromon the new field, so the changes page lists the rename.Run
python -m tools.surface_snapshot. It refuses a removed stable key that has no such row, and it records the key inremoved_toml_keys.tsv.Write the old and the new name under
Changedin the changelog.
tests/unit/config/test_historical_configs.py reads real files of the published
alphas from tests/unit/config/corpus/, so a rename with no row fails there.
A row stays in the register for good. A row of 2.0.0, whose old key only a pre-release wrote, has a delay that ends at 2.2.0, and from then on a live file is refused with the new name. A row of a later 2.x has no end inside the 2 line. A run sealed under the old name stays readable for the whole major line.
Layer boundaries#
The model lives in the layer of the package it configures. Only config,
workflow, project and cli import config, and schema and results
never read it. The full rules are on Layer graph.
See also#
Package: config for the configuration root.
Package: core for
Profile, units, and tracking helpers.Build a frontend if the field powers a UI widget.
TOML parameters for the generated TOML reference.