DIMR xml files¶
The input to the Deltares Integrated Model Runner (DIMR) is a single XML file, represented by the classes below.
Model¶
Component (BaseModel, ABC)
pydantic-model
¶
Specification of a BMI-compliant model component instance that will be executed by DIMR.
Attributes:
Name | Type | Description |
---|---|---|
library |
str |
The library name of the compoment. |
name |
str |
The component name. |
workingDir |
Path |
The working directory. |
inputFile |
Path |
The name of the input file. |
process |
Optional[int] |
Number of subprocesses in the component. |
setting |
Optional[List[hydrolib.core.io.dimr.models.KeyValuePair]] |
A list of variables that are provided to the BMI model before initialization. |
parameter |
Optional[List[hydrolib.core.io.dimr.models.KeyValuePair]] |
A list of variables that are provided to the BMI model after initialization. |
mpiCommunicator |
Optional[str] |
The MPI communicator value. |
model |
Optional[hydrolib.core.basemodel.FileModel] |
The model represented by this component. |
dict(self, *args, **kwargs)
¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Source code in hydrolib/core/io/dimr/models.py
def dict(self, *args, **kwargs):
# Exclude the FileModel from any DIMR serialization.
kwargs["exclude"] = {"model"}
return super().dict(*args, **kwargs)
is_intermediate_link(self) -> bool
¶
Generic attribute for models that have children fields that could contain files.
Source code in hydrolib/core/io/dimr/models.py
def is_intermediate_link(self) -> bool:
return True
ComponentOrCouplerRef (BaseModel)
pydantic-model
¶
Reference to a BMI-compliant model component instance.
Attributes:
Name | Type | Description |
---|---|---|
name |
str |
Name of the reference to a BMI-compliant model component instance. |
ControlModel (BaseModel)
pydantic-model
¶
Overrides to make sure that the control elements in the DIMR are parsed and serialized correctly.
dict(self, *args, **kwargs)
¶
Add control element prefixes for serialized data.
Source code in hydrolib/core/io/dimr/models.py
def dict(self, *args, **kwargs):
"""Add control element prefixes for serialized data."""
return {
str(self._type): super().dict(*args, **kwargs),
}
validate(v)
classmethod
¶
Remove control element prefixes from parsed data.
Source code in hydrolib/core/io/dimr/models.py
@classmethod
def validate(cls, v):
"""Remove control element prefixes from parsed data."""
# should be replaced by discriminated unions once merged
# https://github.com/samuelcolvin/pydantic/pull/2336
if isinstance(v, dict) and len(v.keys()) == 1:
key = list(v.keys())[0]
v = v[key]
return super().validate(v)
CoupledItem (BaseModel)
pydantic-model
¶
Specification of an item that has to be exchanged.
Attributes:
Name | Type | Description |
---|---|---|
sourceName |
str |
Name of the item at the source component. |
targetName |
str |
Name of the item at the target component. |
is_intermediate_link(self) -> bool
¶
Generic attribute for models that have children fields that could contain files.
Source code in hydrolib/core/io/dimr/models.py
def is_intermediate_link(self) -> bool:
# TODO set to True once we replace Paths with FileModels
return False
Coupler (BaseModel)
pydantic-model
¶
Specification of the coupling actions to be performed between two BMI-compliant model components.
Attributes:
Name | Type | Description |
---|---|---|
name |
str |
The name of the coupler. |
sourceComponent |
str |
The component that provides the data to has to be exchanged. |
targetComponent |
str |
The component that consumes the data to has to be exchanged. |
item |
List[hydrolib.core.io.dimr.models.CoupledItem] |
A list of items that have to be exchanged. |
logger |
Optional[hydrolib.core.io.dimr.models.Logger] |
Logger for logging the values that get exchanged. |
is_intermediate_link(self) -> bool
¶
Generic attribute for models that have children fields that could contain files.
Source code in hydrolib/core/io/dimr/models.py
def is_intermediate_link(self) -> bool:
# TODO set to True once we replace Paths with FileModels
return False
DIMR (FileModel)
pydantic-model
¶
DIMR model representation.
Attributes:
Name | Type | Description |
---|---|---|
documentation |
Documentation |
File metadata. |
control |
List[Union[Start, Parallel]] |
The |
component |
List[Union[RRComponent, FMComponent, Component]] |
List of
|
coupler |
Optional[List[Coupler]] |
optional list of |
waitFile |
Optional[str] |
Optional waitfile name for debugging. |
global_settings |
Optional[GlobalSettings] |
Optional global DIMR settings. |
dict(self, *args, **kwargs)
¶
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
Source code in hydrolib/core/io/dimr/models.py
def dict(self, *args, **kwargs):
kwargs["exclude_none"] = True
kwargs["exclude"] = {"filepath"}
return super().dict(*args, **kwargs)
Documentation (BaseModel)
pydantic-model
¶
Information on the present DIMR configuration file.
Attributes:
Name | Type | Description |
---|---|---|
fileVersion |
str |
The DIMR file version. |
createdBy |
str |
Creators of the DIMR file. |
creationDate |
datetime |
The creation date of the DIMR file. |
FMComponent (Component)
pydantic-model
¶
Component to include the D-Flow FM program in a DIMR control flow.
GlobalSettings (BaseModel)
pydantic-model
¶
Global settings for the DIMR configuration.
Attributes:
Name | Type | Description |
---|---|---|
logger_ncFormat |
int |
NetCDF format type for logging. |
KeyValuePair (BaseModel)
pydantic-model
¶
Key value pair to specify settings and parameters.
Attributes:
Name | Type | Description |
---|---|---|
key |
str |
The key. |
value |
str |
The value. |
Logger (BaseModel)
pydantic-model
¶
Used to log values to the specified file in workingdir for each timestep
Attributes:
Name | Type | Description |
---|---|---|
workingDir |
Path |
Directory where the log file is written. |
outputFile |
Path |
Name of the log file. |
Parallel (ControlModel)
pydantic-model
¶
Specification of a parallel control flow: one main component and a group of related components and couplers. Step wise execution order according to order in parallel control flow.
Attributes:
Name | Type | Description |
---|---|---|
startGroup |
StartGroup |
Group of components and couplers to be executed. |
start |
ComponentOrCouplerRef |
Main component to be executed step wise (provides start time, end time and time step). |
RRComponent (Component)
pydantic-model
¶
Component to include the RainfallRunoff program in a DIMR control flow.
Start (ControlModel)
pydantic-model
¶
Specification of a serial control flow: one main component.
Attributes:
Name | Type | Description |
---|---|---|
name |
str |
Name of the reference to a BMI-compliant model component instance |
StartGroup (BaseModel)
pydantic-model
¶
Specification of model components and couplers to be executed with a certain frequency.
Attributes:
Name | Type | Description |
---|---|---|
time |
str |
Time frame specification for the present group: start time, stop time and frequency. Expressed in terms of the time frame of the main component. |
start |
List[hydrolib.core.io.dimr.models.ComponentOrCouplerRef] |
Ordered list of components to be executed. |
coupler |
List[hydrolib.core.io.dimr.models.ComponentOrCouplerRef] |
Oredered list of couplers to be executed. |
Parser¶
DIMRParser
¶
A parser for DIMR xml files.
parse(path: Path) -> dict
staticmethod
¶
Parses a DIMR file to a dictionary.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
path |
Path |
Path to the DIMR configuration file. |
required |
Source code in hydrolib/core/io/dimr/parser.py
@staticmethod
def parse(path: Path) -> dict:
"""Parses a DIMR file to a dictionary.
Args:
path (Path): Path to the DIMR configuration file.
"""
if not path.is_file():
warn(f"File: `{path}` not found, skipped parsing.")
return {}
parser = etree.XMLParser(
remove_comments=True, resolve_entities=False, no_network=True
)
root = etree.parse(str(path), parser=parser).getroot()
return DIMRParser._node_to_dictionary(root, True)
Serializer¶
DIMRSerializer
¶
A serializer for DIMR files.
serialize(path: Path, data: dict)
staticmethod
¶
Serializes the DIMR data to the file at the specified path.
Attributes:
Name | Type | Description |
---|---|---|
path |
Path |
The path to the destination file. |
data |
Dict |
The data to be serialized. |
Source code in hydrolib/core/io/dimr/serializer.py
@staticmethod
def serialize(path: Path, data: dict):
"""
Serializes the DIMR data to the file at the specified path.
Attributes:
path (Path): The path to the destination file.
data (Dict): The data to be serialized.
"""
path.parent.mkdir(parents=True, exist_ok=True)
xmlns = "http://schemas.deltares.nl/dimr"
xsi = "http://www.w3.org/2001/XMLSchema-instance"
schema_location = "http://content.oss.deltares.nl/schemas/dimr-1.3.xsd"
attrib = {e.QName(xsi, "schemaLocation"): f"{xmlns} {schema_location}"}
namespaces = {None: xmlns, "xsi": xsi}
root = e.Element(
"dimrConfig",
attrib=attrib,
nsmap=namespaces,
)
DIMRSerializer._build_tree(root, data)
to_string = minidom.parseString(e.tostring(root))
xml = to_string.toprettyxml(indent=" ", encoding="utf-8")
with path.open("wb") as f:
f.write(xml)