sir3stoolkit.mantle package
Submodules
sir3stoolkit.mantle.advanced_operations module
Created on Fri Jan 23 12:11:41 2026
This module implements functions that extend the basic C# operations with more advanced operations to change a SIR 3S model.
@author: Jablonski
- class sir3stoolkit.mantle.advanced_operations.SIR3S_Model_Advanced_Operations[source]
Bases:
SIR3S_ModelThis class implements functions that extend the basic C# operations with more advanced operations to change a SIR 3S model.
- add_element_types_to_tk_list(tks: List[str]) List[Tuple[str, str]][source]
Turns list of tks into list of tuples with element type and tk. Only works for DistrictHeating networks. For other mappings we need an additional mapping. see sir3stoolkit/docs/code snippets/mapping_for_groups.ipynb
- Parameters:
self
tks (List[str]) – List of tks of elements like [‘5428054456958551597’, ‘50736424189751239’]
- Returns:
[(‘KNOT’, ‘5428054456958551597’), (‘ROHR’, ‘50736424189751239’)]
- Return type:
List[Tuple[str, str]]
- add_elements_to_group(group_tk: int, element_tks: List[Tuple[str, str]]) None | int[source]
Adds elements to a group with a list of elements.
- Parameters:
self
group_tk (int) – Tk of the group the elements should be added to.
element_tks (list[tuple[str, str]]) –
Tks of elements that should be added to the group. Eg. [(‘KNOT’, ‘5428054456958551597’),
(‘KNOT’, ‘5099111544186125239’)]
- get_element_type_from_tk(tk: str) str[source]
Return element type for given tk.
- Parameters:
self
tk (int) – Tk of element
- Returns:
element type
- Return type:
str
- get_tks_of_group_elements(group_tk: int) List[Tuple[str, str]][source]
Returns list of tuples with element type and tk of elements that are part of specific group.
- Parameters:
self
group_tk (int) – Tk of group for element tk retrival
- Returns:
List of tuples with element type and tk of elements of group.
- Return type:
Any
- remove_elements_from_group(group_tk: int, element_tks: List[Tuple[str, str]]) None | int[source]
Removes elements from a group with a list of elements.
- Parameters:
self
group_tk (int) – Tk of the group the elements should be removed from.
element_tks (list[tuple[str, str]]) –
Tks of elements that should be removed from the group. Eg. [(‘KNOT’, ‘5428054456958551597’),
(‘KNOT’, ‘5099111544186125239’)]
- set_group_elements(group_tk: int, element_tks: List[Tuple[str, str]]) None | int[source]
Overwrites elements in a group with a new list of elements.
- Parameters:
self
group_tk (int) – Tk of the group the elements should be set for.
element_tks (list[tuple[str, str]]) –
Tks of elements that should be set for the group. Eg. [(‘KNOT’, ‘5428054456958551597’),
(‘KNOT’, ‘5099111544186125239’)]
sir3stoolkit.mantle.alternative_models module
Created on Weg Sep 01 14:04:43 2025
This module implements the generation of SIR 3S models in alternative model formats such as pandapipes or nx-Graphs.
@author: Jablonski
- class sir3stoolkit.mantle.alternative_models.SIR3S_Model_Alternative_Models[source]
Bases:
SIR3S_Model_DataframesThis class is supposed to extend the Dataframes class that extends the general SIR3S_Model class with the possibility of using alternative District Heating models such as pandapipes.
- SIR_3S_to_nx_graph()[source]
Build a directed NetworkX graph from SIR 3S model.
- Returns:
Directed graph with nodes and edges populated from SIR 3S model.
- Return type:
nx.DiGraph
- SIR_3S_to_pandapipes()[source]
Converts the currently open SIR 3S network into a pandapipes network.
This function creates a pandapipes network that mirrors the structure of the SIR 3S network, including junctions (nodes), pipes, and external sources/sinks. Only elements of type Node and Pipe are included; FWVB (district heating consumers) are excluded.
- Returns:
A pandapipes network object containing: - Junctions with model data and result values (pressure, temperature, flow). - Pipes with geometry and physical parameters. - External grids (sources) and sinks based on node type and flow direction.
- Return type:
pandapipes.pandapipesNet
- add_properties_to_graph(G: DiGraph, element_type: str, properties: List[str], timestamp: str | None = None) DiGraph[source]
Enrich nodes and edges in G with additional attributes by joining on ‘tk’.
- Parameters:
G (nx.DiGraph) – The already-built graph where nodes/edges have at least a ‘tk’ attribute.
element_type (str) – The element type to filter by (must match df[element_type_col] and edge attr “element type”).
properties (list of str) – Column names from the dataframe to add as attributes
timestamp (str) – Timestamp used for adding result properties. If None, STAT will be used.
- Returns:
The same graph instance with enriched attributes.
- Return type:
nx.DiGraph
sir3stoolkit.mantle.dataframes module
Created on Fri Aug 29 09:22:31 2025
This module implements interactions between SIR 3S and pandas dataframes. You can obtain pandas dfs with model- or resultdata, insert nodes and pipes via a df, etc.
@author: Jablonski
- class sir3stoolkit.mantle.dataframes.SIR3S_Model_Dataframes[source]
Bases:
SIR3S_ModelThis class is supposed to extend the general SIR3S_Model class with the possibility of using pandas dataframes when working with SIR 3S. Getting dataframes, inserting elements via dataframes, running algorithms on dataframes should be made possible.
- add_interior_points_as_flat_cols(df)[source]
Expand tab-separated vector columns (name contains “VEC”) into *_0..*_N-1 columns. Non-VEC columns remain unchanged.
- Parameters:
df (pd.DataFrame) – Input DataFrame with scalar columns and VEC columns containing tab-separated strings.
- Returns:
DataFrame with new numeric columns for each interior point.
- Return type:
pd.DataFrame
- Description:
This method processes the result DataFrame by expanding tab-separated vector-valued properties (typically from pipes) into properly structured numerical segments. Each vector entry becomes a new column.
- add_interior_points_as_multiindex(df_results)[source]
Expand vector properties from tab-separated strings into multiple interior-point segments along a new MultiIndex column level.
Vector properties are identified by having ‘VEC’ in the last column-level name. Their tab-separated string values are split into float segments representing interior points along the device. Non-vector properties have their interior point index set to -1 and retain their scalar values.
- Parameters:
df_results (pd.DataFrame) – Results DataFrame containing scalar and vector properties.
- Returns:
A DataFrame in which vector properties are expanded along a new MultiIndex level named ‘interior points’, with float values for each interior segment. Non-vector properties are assigned interior point -1.
- Return type:
pd.DataFrame
- Description:
This method processes the result DataFrame by expanding tab-separated vector-valued properties (typically from pipes) into properly structured numerical segments. Each vector entry becomes a sequence of interior point values along a new index level. Scalar properties remain unchanged and are placed under interior point -1 to maintain consistent indexing.
- generate_edge_dataframe() DataFrame[source]
Generates dataframes containing all edges in a SIR 3S model.
- Returns:
dataframes containing all edges in a SIR 3S model
- Return type:
DataFrame
- Description:
edge_types = [ ‘Pipe’, ‘Valve’, ‘SafetyValve’, ‘PressureRegulator’, ‘DifferentialRegulator’, ‘FlapValve’, ‘PhaseSeparation’, ‘FlowControlUnit’, ‘ControlValve’, ‘Pump’, ‘DistrictHeatingConsumer’, ‘DistrictHeatingFeeder’, ‘Compressor’, ‘HeaterCooler’, ‘HeatExchanger’, ‘HeatFeederConsumerStation’, ‘RART_ControlMode’ ] are included.
- generate_element_dataframe(element_type: str, tks: list[str] | None = None) DataFrame | GeoDataFrame[source]
Generates a dataframe containing all instances for a given element type in the open SIR 3S model. All model_data and result values (self.GetResultProperties_from_elementType(onlySelectedVectors=False)) for the static timestamp are included.
Result values are returned as floats unless they are vectorized (relevant only for pipes), in which case they are returned as strings. The tks of end nodes are included (fkKI, fkKK). Geometry information is also included.
- Parameters:
element_type (Enum) – The element type (e.g., self.ObjectTypes.Node, self.ObjectTypes.Pipe).
tks (list[str], optional) – List of tks to include in the dataframe. Default: None.
- Returns:
DataFrame containing one row per element instance, including model_data, end nodes, geometry, and available static result values.
- Return type:
pd.DataFrame
- Description:
Builds a comprehensive DataFrame containing model_data and static result values for all requested elements of the given type. Vectorized pipe results are included as strings, and scalar results as floats. Geometry and end-node tks are always included.
- generate_element_model_data_dataframe(element_type: Enum, tks: List[str] | None = None, properties: List[str] | None = None, geometry: bool | None = False, end_nodes: bool | None = False, element_type_col: bool | None = False) DataFrame | GeoDataFrame[source]
Generate a dataframe with model data (static) properties for all devices of a given element type.
- Parameters:
element_type (Enum) – The element type (e.g., self.ObjectTypes.Node).
tks (list[str], optional) – List of tks of instances of the element type to include. All other tks will be excluded. Use for filtering. Default: None (no filtering)
properties (list[str], optional) – List of model data property names to include. If properties=None ⇒ all available properties are used. If properties=[] ⇒ no properties are used. Default: None.
geometry (bool, optional) – If True, includes geometric information for each element in the dataframe. Adds a ‘geometry’ column containing spatial data (WKT representation, e.g. POINT (x y)). An attempt will be made to transform the Dataframe into a GeoDataFrame. The success depends on whether an SRID is defined in the SIR 3S model. Default: False.
end_nodes (bool, optional) – If True and supported by the element type, includes tks of end nodes as columns (fkKI, fkKK, fkKI2, fkKK2). Default: False.
element_type_col (bool, optional) – If True, adds a column indicating the element type. Useful when merging dataframes later. Default: False.
- Returns:
DataFrame (or GeoDataFrame) with one row per device (tk) and columns for the requested model data properties, geometry and end nodes. Columns: [“tk”, <model_data_props>]
- Return type:
pd.DataFrame | gpd.GeoDataFrame
- Description:
Generates a DataFrame (or GeoDataFrame) containing static model data for all elements of a given type. The core of the sir3stoolkit usually returns values without datatypes, that are then interpreted as strings. This function infers and assigns datatypes based on values, therefore misassignments of data types can happen. Tk retains string data type.
- generate_element_results_dataframe(element_type: Enum, tks: List[str] | None = None, properties: List[str] | None = None, timestamps: List[str] | None = None, place_holder_value: float | None = 99999.0) DataFrame[source]
Generate a dataframe with RESULT (time-dependent) properties for all devices and timestamps.
- Parameters:
element_type (Enum) – The element type (e.g., self.ObjectTypes.Node).
tks (list[str], optional) – List of tks of instances of the element type to include. All other tks will be excluded. Use for filtering. Default: None (no filtering)
properties (list[str], optional) – List of RESULT property names to include. If properties=None ⇒ includes all available result properties (per element, only if values exist). If properties=[] ⇒ no properties are used. Default: None.
timestamps (list[Union[str, int]], optional) –
List of timestamps to include. Can be: - List of timestamp strings
(e.g., [“2025-09-25 00:00:00.000 +02:00”, “2025-09-25 00:05:00.000 +02:00”])
- List of integer indices
(e.g., [0, 7, -1]) where 0 = first timestamp, 7 = eighth timestamp, -1 = last timestamp.
Default: None (includes all available timestamps).
place_holder_value (float, optional) – float values to be used if SIR 3S calculations do not return a result. Default: 99999.0
- Returns:
DataFrame with one row per timestamp and MultiIndex columns: - Level 0: tk (device ID) - Level 1: name (device name) - Level 2: end_nodes (tuple of connected node tks as string) - Level 3: property (result name) Data types: float for scalars, str for vectorized data.
- Return type:
pd.DataFrame
- Description:
Generates a DataFrame containing time-dependent result vectors for all selected devices and timestamps. Supports both timestamp strings and index-based selection. Produces a MultiIndex-column DataFrame grouped by device, name, end-nodes, and property.
- generate_longitudinal_section_dataframes() List[DataFrame][source]
Generates dataframes for longitudinal sections.
- Parameters:
self – Instance of SIR_Model_Dataframes class
- Returns:
List of dataframes of the form [section_1_VL, section_1_RL, section_2_VL, section_2_RL, …, section_lfdnr_VL, section_lfdnr_RL, …]
- Return type:
List[DataFrame|GeoDataFrame]
- generate_longitudinal_section_vector_dataframes() DataFrame[source]
Generates dataframes containing model data and result data of pipes in a longitudinal section of a SIR 3S model. Vectorized result data is split into multiple columns.
- Returns:
List of dataframes of the form [section_1_VL, section_1_RL, section_2_VL, section_2_RL, …, section_lfdnr_VL, section_lfdnr_RL, …]
- Return type:
List[DataFrame|GeoDataFrame]
- generate_pipe_vector_dataframe(tks: List[str] = None) DataFrame[source]
Generates dataframe containing model data and result data of pipes in a SIR 3S model. Vectorized result data is split into multiple columns.
- Parameters:
tk – List of pipe tks to exclusivley include. Other pipes are not included.
- Returns:
Dataframe containing model data and result data of pipes
- Return type:
Dataframe
sir3stoolkit.mantle.mantle module
Created on Thu Okt 7 13:44:32 2025
This module is a collector for all mantle implementations. And provides the SIR3S_Model_Mantle() class that contains the functions from all other classes defined in the mantle.
@author: Jablonski
- class sir3stoolkit.mantle.mantle.SIR3S_Model_Mantle[source]
Bases:
SIR3S_Model_Alternative_Models,SIR3S_Model_Dataframes,SIR3S_Model_Plotting,SIR3S_Model_Advanced_Operations
sir3stoolkit.mantle.plotting module
Created on Thu Okt 7 13:39:13 2025
This module implements general plotting functions for SIR 3S applications. TODO: AGSN, Time Curves, Network Color Diagram
@author: Jablonski
- class sir3stoolkit.mantle.plotting.SIR3S_Model_Plotting[source]
Bases:
SIR3S_Model- plot_node_layer(ax=None, gdf=None, *, size_scaling_col: str | None = None, color_mixing_col: str | None = None, attribute: str | None = None, colors=('darkgreen', 'magenta'), legend_fmt: str | None = None, legend_values: list[float] | None = None, size_vmin: float | None = None, size_vmax: float | None = None, color_vmin: float | None = None, color_vmax: float | None = None, query: str | None = None, marker_style: str = 'o', marker_size_factor: float = 1000.0, zorder: float | None = None)[source]
Plot point nodes with separate size and color scaling.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Axis to plot into. If None, uses current axes (plt.gca()).
gdf (pandas.DataFrame or geopandas.GeoDataFrame) – Input with a ‘geometry’ column of shapely geometries.
size_scaling_col (str, optional) – Column used to scale marker sizes (numeric). If None, uses attribute if provided; otherwise constant size.
color_mixing_col (str, optional) – Column used to color markers (numeric). If None, uses attribute if provided; otherwise a constant color.
attribute (str, optional) – Legacy single column used for both size and color if the specific columns are not provided.
colors (tuple[str, str], optional) – Two colors to build a linear segmented colormap.
legend_fmt (str, optional) – Legend label format, default: f”{color_col} {{:.4f}}”.
legend_values (list[float], optional) – Explicit legend tick values; default: 5 linear steps.
size_vmin (float, optional) – Bounds for size normalization; defaults to data min/max.
size_vmax (float, optional) – Bounds for size normalization; defaults to data min/max.
color_vmin (float, optional) – Bounds for color normalization; defaults to data min/max.
color_vmax (float, optional) – Bounds for color normalization; defaults to data min/max.
query (str, optional) – Pandas query string to filter rows before plotting.
marker_style (str, optional) – Matplotlib marker style, default ‘o’.
marker_size_factor (float, optional) – Factor applied after size normalization, default 1000.0.
zorder (float, optional) – Z-order for drawing.
- Returns:
Legend patches based on the color scaling column; None if constant color.
- Return type:
list[matplotlib.patches.Patch] or None
- plot_pipe_layer(ax=None, gdf=None, *, width_scaling_col: str | None = None, color_mixing_col: str | None = None, attribute: str | None = None, colors=('darkgreen', 'magenta'), legend_fmt: str | None = None, legend_values: list[float] | None = None, width_vmin: float | None = None, width_vmax: float | None = None, color_vmin: float | None = None, color_vmax: float | None = None, query: str | None = None, line_width_factor: float = 10.0, zorder: float | None = None)[source]
Plot line geometries with separate width and color scaling.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Axis to plot into. If None, uses current axes (plt.gca()).
gdf (pandas.DataFrame or geopandas.GeoDataFrame) – Input with a ‘geometry’ column of shapely LineString/MultiLineString.
width_scaling_col (str, optional) – Column used to scale line widths (numeric). If None, uses attribute if provided; otherwise constant width.
color_mixing_col (str, optional) – Column used to color lines (numeric). If None, uses attribute if provided; otherwise a constant color.
attribute (str, optional) – Legacy single column used for both width and color if the specific columns are not provided.
colors (tuple[str, str], optional) – Two colors to build a linear segmented colormap.
legend_fmt (str, optional) – Legend label format, default: f”{color_col} {{:.4f}}”.
legend_values (list[float], optional) – Explicit legend tick values; default: 5 linear steps.
width_vmin (float, optional) – Bounds for width normalization; defaults to data min/max.
width_vmin – Bounds for width normalization; defaults to data min/max.
color_vmin (float, optional) – Bounds for color normalization; defaults to data min/max.
color_vmax (float, optional) – Bounds for color normalization; defaults to data min/max.
query (str, optional) – Pandas query string to filter rows before plotting.
line_width_factor (float, optional) – Factor applied after width normalization, default 10.0.
zorder (float, optional) – Z-order for drawing.
- Returns:
Legend patches based on the color scaling column; None if constant color.
- Return type:
list[matplotlib.patches.Patch] or None
- plot_time_curves(df: DataFrame, start=None, end=None, properties=None, axis_labels=None, ylims=None, tks_per_property=None, y_label_ticks=None, y_grid_ticks=None, x_label_ticks=None, x_grid_ticks=None, figsize=(20, 14), axis_offset=60, linestyles=None, legend=True, legend_fontsize=8, legend_loc='upper left', legend_coords=(0.67, 0.33), legend_in_figure=True, missing='skip', normalize=<method 'upper' of 'str' objects>, aliases=None, title_prefix='', show_title=True, rotate_xticks=0, grid=True, grid_style='--', grid_alpha=0.3, logger=None)[source]
Plot multiple properties using multiple y-axes (all on the left). Optionally restrict which TKs are plotted for each property.
Legend labels are “PROPERTY NAME”.
Tick/grid separation: - Labeled ticks come from major ticks (x_label_ticks, y_label_ticks) - Grid lines come from minor ticks (x_grid_ticks, y_grid_ticks) - Horizontal grid is based on the first y-axis (axis 0)
- Parameters:
df (pandas.DataFrame) – Input DataFrame with MultiIndex columns (from s3s.generate_element_results_dataframe()). Level 0 must represent TK/group; last level must represent property. A column level named “name” is used for legend labels if present.
start (Any) – Start timestamp (inclusive) for slicing and x-axis limits. If None, uses first timestamp in df.
end (Any) – End timestamp (inclusive) for slicing and x-axis limits. If None, uses last timestamp in df.
properties (list[str] | None) – List of property names to plot (matched against the last MultiIndex level). If None, plots all properties found.
axis_labels (list[str] | None) – List of y-axis labels corresponding to properties. If None, uses “property=<name>”.
ylims (list[tuple[float, float] | None] | None) – List of y-limits tuples per property axis, e.g. [(0, 12), (0, 40), (0, 60)]. Use None entries to keep autoscale.
tks_per_property (list[list[str] | set[str] | None] | None) – List of lists/sets of TKs allowed per property. If an entry is None or empty, all TKs are allowed.
y_label_ticks (list[int] | None) – Number of labeled y-ticks per axis (one int per property/axis). If None, leaves default tick behavior.
y_grid_ticks (int | None) – Number of horizontal grid lines (minor y-ticks) based on the first y-axis. If None, no minor y-grid control.
x_label_ticks (int | None) – Number of labeled x-ticks (major ticks). If None, uses AutoDateLocator for major ticks.
x_grid_ticks (int | None) – Number of vertical grid lines (minor x-ticks). If None, no minor x-grid control.
figsize (tuple[int, int]) – Matplotlib figure size.
axis_offset (int) – Outward offset (in points) between stacked left-side y-axes.
linestyles (list[str] | None) – List of linestyles used per property (cycled if shorter than properties). Default cycles [“-“,”–“,”:”,”-.”].
legend (bool) – Whether to draw a legend.
legend_fontsize (int | float) – Legend font size.
legend_loc (str) – Legend location argument passed to matplotlib (e.g. “upper left”).
legend_coords (tuple[float, float]) – Legend anchor coordinates passed as bbox_to_anchor.
legend_in_figure (bool) – If True, uses fig.legend(…) (more robust for multiple twinx axes). If False, uses ax0.legend(…).
missing (str) – Policy if a requested property yields no plotted lines after filtering: “skip”, “warn”, or “error”.
normalize (callable) – Function applied to property strings for robust matching (e.g. str.upper).
aliases (dict[str, str] | None) – Mapping applied after normalization to unify names (e.g. {“PHI”: “PH”}). Keys/values must be normalized form.
title_prefix (str) – Optional text prepended to the timeframe title.
show_title (bool) – If True, sets a title containing the selected timeframe.
rotate_xticks (int | float) – Rotation angle (degrees) for x tick labels.
grid (bool) – Whether to draw grid lines (on base axis).
grid_style (str) – Line style for grid.
grid_alpha (float) – Alpha for grid lines.
logger (Any) – Optional logger with .info/.warning methods. If provided, logs are prefixed with “[time curves]”.
- Returns:
(fig, axes, used_properties) where axes is a list of axes (one per property), and used_properties are normalized properties used.
- Return type:
tuple[matplotlib.figure.Figure, list[matplotlib.axes.Axes], list[str]]