Functions
Welcome to the Functions page! Here, we will delve into the details of each function, its purpose, parameters and returns. Links to the description of returned objects on the Classes and Objects page will be provided.
Note
Currently, not all functions that are included in PT3S are documented. These will be added in the future.
Read SIR 3S Model and Results
- dxAndMxHelperFcts.readDxAndMx(dbFile, preventPklDump=False, forceSir3sRead=False, maxRecords=None, mxsVecsResults2MxDf=None, mxsVecsResults2MxDfVecAggs=None, crs=None, logPathOutputFct=<function relpath>, SirCalcExePath=None)[source]
Reads SIR 3S model and SIR 3S results and returns a dxWithMx object - also called m object.
Use maxRecords=0 to read only the model. Use maxRecords=1 to read only STAT (the steady state result). Use maxRecords=-1 to (re-)calculate the model by SirCalc.
- Parameters:
dbFile (str) – Path to SIR 3S’ database file (‘modell.db3’ or ‘modell.mdb’). The database is read into a Dx object. The corresponding results are read into an Mx object if available.
preventPklDump (bool, optional, default=False) – Determines whether to prevent dumping objects read to pickle. If True, existing pickles are deleted, SIR 3S’ sources are read and no pickles are written. If False 3 pickles are written or overwritten if older than SIR 3S’ sources.
forceSir3sRead (bool, optional, default=False) – Determines whether to force reading from SIR 3S’ sources even if newer pickles exists. By default pickles are read if newer than SIR 3S’ sources.
maxRecords (int, optional, default=None) – Use maxRecords=0 to read only the model. Use maxRecords=1 to read only STAT (the steady state result). Maximum number of MX-Results to read. If None, all results are read. Use maxRecords=-1 to (re-)calculate the model by SirCalc (by the newest SirCalc available below
C:\3S).mxsVecsResults2MxDf (list, optional, default=None) – List of regular expressions for SIR 3S’ Vector-Results to be included in mx.df. Note that integrating Vector-Results in mx.df can significantly increase memory usage. Example 1:
['ROHR~\*~\*~\*~PHR', 'ROHR~\*~\*~\*~FS', 'ROHR~\*~\*~\*~DSI', 'ROHR~\*~\*~\*~DSK']Example 2:['KNOT~\*~\*~\*~VOLD','ROHR~\*~\*~\*~VOLDA']mxsVecsResults2MxDfVecAggs (list, optional, default=None) – List of timesteps indices for SIR 3S’ Vector-Results to be included in mx.dfVecAggs. Note that integrating all timesteps in mx.dfVecAggs will increase memory usage up to MXS-Size. Example: [3, 42, 666, -1] (-1: last timestep). 3: 3rd timestep. 42: 42th timestep. 666: 666th timestep.
crs (str, optional, default=None) – (=coordinate reference system) Determines crs used in geopandas-Dfs (Possible value:’EPSG:25832’). If None, crs will be read from SIR 3S’ database file.
logPathOutputFct (func, optional, default=os.path.relpath) – func logPathOutputFct(fileName) is used for logoutput of filenames unless explicitly stated otherwise in the logoutput
SirCalcExePath (str, optional, default=None) – SirCalcExePath can be used to specify the path to the SirCalc.exe that is used for calculations if maxRecords<0
- Returns:
An object containing the SIR 3S model and SIR 3S results - also called m object.
- Return type:
dxWithMx
Returns m Object.
Usage Tutorial
Enter the name of the .db3 file you want to read
>>> dbFilename="Example1"
Enter the path to the dir, where this .db3 file is located. In this case the Example data included in PT3S is used.
>>> rootdir=os.path.join(os.path.dirname(os.path.abspath(dxAndMxHelperFcts.__file__)), 'Examples')
Concatenate the rootdir with the dbFilename
>>> dbFile=os.path.join(rootdir, dbFilename + '.db3')
dbFile can now be used as a parameter for readDxAndMx()
>>> dbFile
'C:\\Users\\jablonski\\3S\\PT3S\\Examples\\Example1.db3'
Create a dxWithMx object using readDxAndMx().
>>> m=dxAndMxHelperFcts.readDxAndMx(dbFile=dbFile)
Refer to the Examples page. The Examples 1-X use this function.
Read SIR 3S Results only
- dxAndMxHelperFcts.readMx(wDirMx, logPathOutputFct=<function relpath>)[source]
Reads SIR 3S results and returns a Mx object.
- Parameters:
wDirMx (str) – Path to Mx-Directory. The results are read into a Mx object via the Mx files.
logPathOutputFct (func, optional, default=os.path.relpath) – func logPathOutputFct(fileName) is used for logoutput of filenames unless explicitly stated otherwise in the logoutput. Defaults to os.path.relpath.
- Returns:
Mx object with two attributes: - mx.df: pandas-Df (‘time curve data’) from from SIR 3S’ MXS file(s) - mx.dfVecAggs: pandas-Df (‘vector data’) from SIR 3S’ MXS file(s)
- Return type:
Mx object
Returns Mx object.
Refer to Example 2: Time Curves. It uses this function.
Methods
Methods regarding m Object
switchV3DfColsToMultiindex
- dxAndMxHelperFcts.dxWithMx.switchV3DfColsToMultiindex(self)
Switches V3-Df cols to Multiindex-Cols. switchV3DfColsToMultiindex(): switch cols in V3_ROHR, V3_FWVB, V3_KNOT, V3_VBEL to Multiindex
Methods regarding Dx object
update
- Dx.Dx.update(self, dfUpd, updInverseValue=None)
Updates dbFile (SQLite only)
- Parameters:
dfUpd (df) – df with update data
updInverseValue (?, optional, default=None) – value to use for attribValue for inverse objects
- Returns:
rowsAffectedTotal
Note
Comprehensive changes to model data should be made via the SIR 3S user interface. Or via the SIR 3S import interfaces which - depending on type/operation/parameterization - can also overwrite (update) existing model data. Nonetheless, scripted model changes can be helpful.
- dfUpd’s cols used:
table i.e. ‘FWVB’
attrib i.e. ‘W0’
- dfUpd’s cols optional:
attribValue, default=dfUpd[attrib]
xk, default=’tk’
xkValue, default=dfUpd[xk]
- row-wise:
set attrib to attribValue in table where xk is xkValue
update an attribute of an object
- updInverseValue:
set attrib to updInverseValue for all objects of type table not mentioned in dfUpd
insert
- Dx.Dx.insert(self, table, dfIns, xkFct=<function fXk>)
Inserts into a dbFile’s table (SQLite only)
- Parameters:
table (str) – table to insert to
dfIns (df) – df with insert data
xkFct (func, optional, default=Dx.fXk) – func to call row-wise to obtain (pk, rk, tk) for an record to insert
- Returns:
rowsAffected, dfIns (a copy of dfIns; cols pk, rk, tk: inserted values; cols pkOrig, rkOrig, tkOrig: original values)
Note
New model mass data should be created via the SIR 3S import interfaces. Nevertheless, generating model mass data via script can be helpful.
- dfIns’ cols used:
all cols which are also cols of table
- row-wise:
insert into table
importFromSIR3S
- Dx.Dx.importFromSIR3S(self, dbSrc, tablesToImport=['STRASSE', 'LTGR', 'DTRO', 'DTRO_ROWD', 'KNOT', 'KNOT_BZ', 'ROHR', 'ROHR_BZ', 'FWVB', 'FWVB_BZ', 'LAYR'], fksNotToFillWithDstTemplateValues=['fkKI', 'fkKK', 'fkDTRO_ROWD', 'fkLTGR', 'fkSTRASSE'], fctsToCall={'*': <function fimportFromSIR3S>}, fctsToCallLogging=True)
Import data from an other SIR 3S Model (SQLite only)
- Parameters:
dbSrc (str) – SIR 3S dbFile to import from
tablesToImport (list of tabNames, optional, default=['STRASSE','LTGR','DTRO','DTRO_ROWD' ,'KNOT','KNOT_BZ','ROHR','ROHR_BZ','FWVB','FWVB_BZ' ,'LAYR']) – tabNames to import from
fksNotToFillWithDstTemplateValues (list of fk starting colNames, optional, default=['fkKI','fkKK','fkDTRO_ROWD','fkLTGR','fkSTRASSE']) – colNames starting with fk not to set to the corresponding Dst-Template-Value
fctsToCall (dct of functions, optional, default={'*':fimportFromSIR3S}; f('*') is called if defined and then the object-specific f(OBJ) is called if defined) – dct of functions to call before import
fctsToCallLogging (bool, optional, default=True) – decide if fctsToCall shall generate Log-Output
Note
Model data from annother SIR 3S Model should be imported via the SIR 3S export/import interfaces. I.e. export in Src Sdf/Csv, import in Dst the exported Sdf/Csv. Or copy in Src and paste in Dst. Or export/import SIR 3S Blocks. Nevertheless, importing from another Model via script can be helpful.
Note
Template-Objects are Objects with col ‘KENNUNG’ < 0. Template-Objects are not copied from Src to Dst. For objects with Templates defined all Non-Null fk-Starting Template-Attributes from Dst are set except for: fksNotToFillWithDstTemplateValues. It follows that i.e. for KNOT(_BZ), ROHR(_BZ), FWVB(_BZ) fkDE is set to the corresponding fkDE Dst-Template-Attribute if defined. For all objects fkDE is finally set to fkBASIS(fkBZ) of the SYSTEMKONFIG(3)-Model if SYSTEMKONFIG(3) is defined.
Note
Dst and Src: SIR 3S Version and CRS (coordinate reference system) should be identical, QGIS-Export should be done (to ensure correct and matching GEOMWKBs in Dst and Src).
setLayerContentTo
- Dx.Dx.setLayerContentTo(self, layerName, df)
Updates content of layerName to df’s-content
- Parameters:
layerName (str) – name of an existing layer
- Returns:
rowsAffected
Note
Groups or layers are used in SIR 3S as a feature for data access, data filtering and grouping. The assignment of objects to groups should be done (explicit) via the SIR 3S user interface or (implicit) via the SIR 3S import interfaces. Nonetheless, scripted assignment can be useful.
- df’s cols used:
TYPE
ID
SdfCsv
- sdfCsv.SdfCsv.__init__(self, csvFile='aSdfCsvFile.csv', encoding='cp1252')
- Parameters:
csvFile (str) – a SDF-CSV-File
encoding (str) – encoding
Note
SIR 3S imports SDF-CSV-Files. However sometimes it is convenient to have a look at the original SDF-CSV-File content with Python. I.e. to explore the original hierarchical layer structure in comparison to the flat layer structure in the SIR 3S model. Or i.e. to check against the SIR 3S SDF-CSV-File import- and export-function result. In general, one can say that the SDF-CSV format for pipe network data (for pipe network models) is so widespread in Germany that it makes sense to have an SIR 3S affine function which maps the SDF-CSV-File to pandas dfs.
The returned object has the following structure:
dataFrames: dct with dfs
dataFrames[‘FEL’]: a df with the definition of the columns of all types; i.e. ‘KNO’ is a type
dataFrames[‘KNO’]: a df with data for objects of type ‘KNO’
dataFramesDesc: dct with descs; i.e. dataFramesDesc[‘KNO’]: ‘Knotendaten’
The returned object has the following functions:
getHierarchicalLayernames: returns: {originalLayername:hierarchicalLayername, …}
Plot Network Color Diagram
- ncd.pNcd_pipes(ax=None, gdf=None, attribute=None, colors=['darkgreen', 'magenta'], legend_fmt=None, legend_values=None, norm_min=None, norm_max=None, query=None, line_width_factor=10, zorder=None)[source]
pNcd_pipes: Plots pipes on axis with customization options.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object. If None, a new axis is created.
gdf (geopandas.GeoDataFrame) – Geospatial DataFrame containing the data to plot.
attribute (str) – Column name in gdf of the data that should be plotted.
colors (list, optional) – List of colors to use for the colormap. Default is [‘darkgreen’, ‘magenta’].
legend_fmt (str, optional) – Legend text for attribute. Default is attribute + ‘{:.4f}’.
legend_values (list, optional) – Specific values to use for value steps in legend. Default is None.
norm_min (float, optional) – Minimum value for normalization. Default is None.
norm_max (float, optional) – Maximum value for normalization. Default is None.
query (str, optional) – Query string to filter the data. Default is None.
line_width_factor (float, optional) – Factor to influence width of the lines in the plot. Default is 10.
zorder (float, optional) – Determines order of plotting when calling the function multilpe times. Default is None.
- Returns:
patches.
- Return type:
matplotlib.patches.Patch
- ncd.pNcd_nodes(ax=None, gdf=None, attribute=None, colors=['darkgreen', 'magenta'], legend_fmt=None, legend_values=None, norm_min=None, norm_max=None, query=None, marker_style='o', marker_size_factor=1000.0, zorder=None)[source]
pNcd_nodes: Plots nodes on axis with customization options.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object. If None, a new axis is created.
gdf (geopandas.GeoDataFrame) – Geospatial DataFrame containing the data to plot.
attribute (str) – Column name in gdf of the data that should be plotted.
colors (list, optional) – List of colors to use for the colormap. Default is [‘darkgreen’, ‘magenta’].
legend_fmt (str, optional) – Legend text for attribute. Default is attribute + ‘{:.4f}’.
legend_values (list, optional) – Specific values to use for value steps in legend. Default is None.
norm_min (float, optional) – Minimum value for normalization. Default is None.
norm_max (float, optional) – Maximum value for normalization. Default is None.
query (str, optional) – Query string to filter the data. Default is None.
marker_style (str, optional) – Style of the markers in the plot. Default is ‘o’.
marker_size_factor (float, optional) – Factor to influence size of the markers in the plot. Default is 1000.0.
zorder (float, optional) – Determines order of plotting when calling the function multilpe times. Default is None.
- Returns:
patches.
- Return type:
matplotlib.patches.Patch
Usage Tutorial
Plot on an axes. Use pNcd_pipes for pipes and pNcd_nodes for nodes.
If you plot multiple times on the same axes, use zorder to determine plotting order.
Refer to Example 1: Interactive Map and Network Color Diagram. It uses this function.
>>> fig, ax = plt.subplots()
>>> pipes_patches = ncd.pNcd_pipes(ax=ax, gdf=gdf_ROHR, attribute='DI', zorder=1)
>>> nodes_patches = ncd.pNcd_nodes(ax=ax, gdf=gdf_FWVB, attribute='QM', zorder=2)
>>> all_patches = pipes_patches + nodes_patches
>>> ax.legend(handles=all_patches, loc='best')
>>> plt.show()
Figure(640x480)
Plot Source Spectrum
- ncd.plot_src_spectrum(ax=None, gdf=None, attribute=None, colors=None, line_width=2, dn_col='DN', lw_min=0.5, lw_max=6.0, plot_pies=False, n_pies=0, ratio_decimals=2, pie_radius_rel=0.02, connector_kwargs=None, pie_zorder=30, expand_limits_for_pies=True, force_equal_aspect=True, debug_pie_centers=False, n_angle_samples=24, pie_gap_rel=0.01, avoid_legend=True, show_pie_labels=True, label_decimals=0, label_color='k', label_fontsize=9, draw_mixture_scale=True, pie_label_inside=True, pie_label_r_rel=0.6, auto_contrast_labels=True, min_label_pct=0.0)[source]
Plots the source spectrum for a district heating network with optional pie annotations.
- Parameters:
ax (matplotlib.axes.Axes, optional) – Matplotlib axis object. If None, a new axis is created.
gdf (geopandas.GeoDataFrame) – Geospatial DataFrame containing the network geometries to plot. Must include a ‘geometry’ column with LineString or MultiLineString objects.
attribute (str or list[str]) – Mixture information per row. If a string, it is the name of a column whose entries are vector-like mixtures (e.g., [96, 4] or [0.96, 0.04]). If a list of strings, these columns are combined row-wise (in the given order) into a mixture vector. Values may be absolute contributions or percentages; they are normalized internally to sum to 1. If the sum is ~100, values are treated as percentages.
colors (list[numpy.ndarray] or list[Sequence[float]], length == number of sources) – Base RGB colors used for color mixing and pie wedges. Each color is a 3-component RGB sequence in the 0–255 range (alpha optional, ignored for mixing).
line_width (float, optional) – Fallback line width applied when DN-based scaling is unavailable or invalid.
dn_col (str, optional) – Name of the diameter (or similar) column used to scale line widths and to select representative pipes for pie placement.
lw_min (float, optional) – Minimum line width used when scaling by
dn_col.lw_max (float, optional) – Maximum line width used when scaling by
dn_col.plot_pies (bool, optional) – If True, annotate selected unique mixture ratios with pie charts positioned outside the network bounding box and connected via a line from a representative pipe.
n_pies (int, optional) – Number of pie annotations to place. For two sources: choose extremes (max per source), then the most balanced (closest to 50/50), then additional values spread across the spectrum. For more than two sources: one extreme per source, then most balanced (closest to uniform), then farthest-point sampling for diversity.
ratio_decimals (int, optional) – Rounding applied to normalized ratios for de-duplication of unique mixtures.
pie_radius_rel (float, optional) – Pie radius as a fraction of the larger side of the network bounding box. Adjust to tune visual size across differently scaled coordinate systems.
connector_kwargs (dict, optional) – Keyword arguments passed to
matplotlib.pyplot.plotfor connector styling (e.g.,dict(color='grey', lw=1.2, ls='--', alpha=0.9)).pie_zorder (int, optional) – Z-order for pie wedges and their connectors.
expand_limits_for_pies (bool, optional) – If True, expands the axis limits to fully include all pies (and a small margin), ensuring they remain visible even when placed outside the original data extent.
force_equal_aspect (bool, optional) – If True, forces equal aspect ratio so circular pies are rendered as circles.
debug_pie_centers (bool, optional) – If True, draws small markers at pie centers to aid debugging of placement.
n_angle_samples (int, optional) – Number of candidate connector angles to test per pie. The chosen angle minimizes the interior crossing distance and penalizes overlap with other pies and with the legend/mix-scale area (when avoidance is enabled).
pie_gap_rel (float, optional) – Minimum gap between pie outer circles, expressed as a fraction of the larger side of the network bounding box. Helps avoid pie‑pie overlap.
avoid_legend (bool, optional) – If True, pie placement avoids overlapping the existing legend and/or mixture scale axes when possible (requires a canvas draw to measure extents).
show_pie_labels (bool, optional) – If True, draw ratio labels next to each pie. For two sources, two labels are shown on opposite sides; for three or more sources, a single combined label (e.g., “30/50/20%”) is placed.
label_decimals (int, optional) – Number of decimal places to show in percentage labels.
label_color (str, optional) – Text color for pie labels.
label_fontsize (float, optional) – Font size for pie labels.
draw_mixture_scale (bool, optional) – If True, draw the mixture scale (e.g., gradient/ternary inset) for the color scheme. If False, suppresses this inset.
- Returns:
The axis used for plotting (useful for further chaining/customization).
- Return type:
matplotlib.axes.Axes
- Raises:
ValueError – If required parameters are missing, if the number of attribute columns does not match the number of colors/sources, or if color specifications are malformed.
KeyError – If the specified
attributecolumn(s) ordn_colare not present ingdf.TypeError – If
attributeis neither a string nor a list of strings.
- Mixtures are normalized to sum to 1. If the raw sum is approximately 100, values are interpreted
as percentages. Rows with invalid/empty mixtures fallback to a neutral light-gray color.
- DN-based width scaling maps the observed
dn_colrange linearly into[lw_min, lw_max]. If dn_colhas no numeric variation, a midpoint width is used.
- DN-based width scaling maps the observed
- Pie placement samples multiple angles and chooses the one minimizing interior travel distance while
avoiding overlap with other pies and the legend/mixture scale (when enabled). Axes limits are expanded to include pies when requested.
Refer to Example 7: Source Spectrum and Fluid Age. It uses this function.
Plot Fluid Age
- ncd.plot_ttr_network(df: DataFrame, dn_col: str = 'DN', geometry_col: str = 'geometry', fk_ki_col: str = 'fkKI', fk_kk_col: str = 'fkKK', cmap: str = 'viridis', node_size: float = 25.0, linewidth_range: tuple[float, float] = (0.6, 5.0), annotate: bool = False, annotation_fmt: str = '{:.1f}', ttr_label: str = 'TTR [h]', agg: str = 'max', ax: matplotlib.axes._axes.Axes | None = None, colorbar: bool = True, show_values: bool = False, dt_col: str | None = None, show_edge_dt: bool = False, ttr_norm: str = 'data', ttr_vmin: float | None = None, ttr_vmax: float | None = None, ttr_percentiles: tuple[float, float] = (2.0, 98.0), highlight_keys: list | tuple | set | None = None, highlight_marker_size: float = 140.0, highlight_match: str = 'auto')[source]
Plots a district heating network with edges from geometry and nodes colored by TTR values.
- Parameters:
df (pandas.DataFrame) – The DataFrame containing edge and node attributes.
dn_col (str, optional, default="DN") – Column name for pipe diameter used to scale edge linewidth.
geometry_col (str, optional, default="geometry") – Column name containing WKT or shapely geometries for edges.
fk_ki_col (str, optional, default="fkKI") – Column name for the foreign key of the start node (KI).
fk_kk_col (str, optional, default="fkKK") – Column name for the foreign key of the end node (KK).
cmap (str, optional, default="viridis") – Colormap for node coloring based on TTR values.
node_size (float, optional, default=25.0) – Size of the node markers.
linewidth_range (tuple of float, optional, default=(0.6, 5.0)) – Minimum and maximum linewidth for edges scaled by DN.
annotate (bool, optional, default=False) – Whether to annotate nodes with their TTR values.
annotation_fmt (str, optional, default="{:.1f}") – Format string for TTR annotations.
ttr_label (str, optional, default="TTR") – Label for the colorbar representing TTR values.
agg (str, optional, default="max") – Aggregation method for TTR when multiple edges share a node coordinate.
ax (matplotlib.axes.Axes, optional) – The axis to plot on. If None, a new axis is created.
colorbar (bool, optional, default=True) – Whether to display a colorbar for TTR values.
show_values (bool, optional, default=False) – Whether to display TTR values next to each node
dt_col (str, optional) – Column name containing the edge travel time to display (e.g., ‘dt’ or ‘dt_new’). If None or missing, no edge labels are drawn.
show_edge_dt (bool, optional, default=False) – If True, draw a black text label with the edge’s dt value near the edge midpoint.
ttr_norm (str, optional, default="data") – Method for TTR normalization: ‘data’, ‘clip’, or ‘percentile’.
ttr_vmin (float, optional) – Minimum TTR value for color scaling (used if ttr_norm=’clip’).
ttr_vmax (float, optional) – Maximum TTR value for color scaling (used if ttr_norm=’clip’).
ttr_percentiles (tuple of float, optional, default=(2.0, 98.0)) – Percentiles for TTR normalization when ttr_norm=’percentile’.
highlight_keys (list, tuple, or set, optional) – List of node keys to highlight (matches fkKI or fkKK).
highlight_marker_size (float, optional, default=140.0) – Size of the highlight star markers.
highlight_match (str, optional, default="auto") – Strategy for matching highlight keys: ‘auto’, ‘both’, ‘numeric’, or ‘string’.
- Returns:
A tuple containing: - ax: The matplotlib axis with the plot. - nodes_df: DataFrame of plotted nodes with columns [‘x’, ‘y’, ‘TTR’].
- Return type:
tuple(matplotlib.axes.Axes, pandas.DataFrame)
Refer to Example 7: Source Spectrum and Fluid Age or Example 9: Travel Time compared to Fluid Age. They use this function.
Plot Travel Time
- ncd.plot_travel_time_from_source(df: DataFrame, TMat: ndarray, map_nodes_tk_ind: dict, source, geometry_col: str = 'geometry', tki_col: str = 'tki', tkk_col: str = 'tkk', xki_col: str = 'XKOR_KI', yki_col: str = 'YKOR_KI', xkk_col: str = 'XKOR_KK', ykk_col: str = 'YKOR_KK', kvri_col: str = 'KVR_KI', kvrk_col: str = 'KVR_KK', dn_col: str = 'DN', cmap: str = 'viridis', node_size: float = 25.0, linewidth_range: tuple[float, float] = (0.6, 5.0), annotate: bool = False, annotation_fmt: str = '{:.1f}', agg: str = 'max', show_values: bool = False, dt_col: str | None = None, show_edge_dt: bool = False, ttr_norm: str = 'data', ttr_vmin: float | None = None, ttr_vmax: float | None = None, ttr_percentiles: tuple[float, float] = (2.0, 98.0), treat_zero_as_unreachable: bool = True, highlight_keys: list | tuple | set | None = None, highlight_match: str = 'auto', highlight_marker_size: float = 140.0, ax: matplotlib.axes._axes.Axes | None = None, colorbar: bool = True, colorbar_label: str = 'Travel time [h]', show_axis: bool = True)[source]
Plots travel time from a selected source node using a travel-time matrix and edge geometry.
- Parameters:
df (pandas.DataFrame) – The DataFrame describing edges and endpoints (KI/KK).
TMat (numpy.ndarray) – Square matrix with travel times; TMat[to_index, from_index] = time (hours).
map_nodes_tk_ind (dict) – Mapping from node key (tk/tki/tkk values) to matrix index (0..N-1).
source (str | int) – The selected source node; either a tk key (present in map_nodes_tk_ind) or an integer matrix index.
geometry_col (str, optional, default="geometry") – Column containing WKT or shapely geometries for edges.
tki_col (str, optional, default="tki") – Column with the KI node key (maps via map_nodes_tk_ind to a matrix index).
tkk_col (str, optional, default="tkk") – Column with the KK node key (maps via map_nodes_tk_ind to a matrix index).
xki_col (str, optional, default="XKOR_KI") – Column with KI X coordinate.
yki_col (str, optional, default="YKOR_KI") – Column with KI Y coordinate.
xkk_col (str, optional, default="XKOR_KK") – Column with KK X coordinate.
ykk_col (str, optional, default="YKOR_KK") – Column with KK Y coordinate.
kvri_col (str, optional, default="KVR_KI") – Column indicating KI visibility (plot only if equals 1).
kvrk_col (str, optional, default="KVR_KK") – Column indicating KK visibility (plot only if equals 1).
dn_col (str, optional, default="DN") – Column for pipe diameter used to scale edge linewidth.
cmap (str, optional, default="viridis") – Colormap for node coloring based on travel time.
node_size (float, optional, default=25.0) – Size of the node markers.
linewidth_range (tuple of float, optional, default=(0.6, 5.0)) – Min and max linewidth for edges scaled by DN.
annotate (bool, optional, default=False) – Whether to annotate nodes with their travel time values.
annotation_fmt (str, optional, default="{:.1f}") – Format string for numeric annotations.
agg (str, optional, default="max") – Aggregation for travel time when multiple edges reference the same node coordinates.
show_values (bool, optional, default=False) – If True, displays the travel-time value next to each plotted node in black.
dt_col (str, optional) – Column name containing the edge travel time to display (e.g., ‘dt’ or ‘dt_new’). If None or missing, no edge labels are drawn.
show_edge_dt (bool, optional, default=False) – If True, draw a black text label with the edge’s dt value near the edge midpoint.
ttr_norm (str, optional, default="data") – Normalization method: ‘data’, ‘clip’, or ‘percentile’.
ttr_vmin (float, optional) – Minimum value for color scaling (used if ttr_norm=’clip’).
ttr_vmax (float, optional) – Maximum value for color scaling (used if ttr_norm=’clip’).
ttr_percentiles (tuple of float, optional, default=(2.0, 98.0)) – Percentiles for normalization when ttr_norm=’percentile’.
treat_zero_as_unreachable (bool, optional, default=True) – Treat 0 in TMat as unreachable (hidden), except source which remains 0.0.
highlight_keys (list | tuple | set, optional) – Node keys to highlight (matched against tki/tkk), drawn as white stars.
highlight_match (str, optional, default="auto") – Strategy for matching highlight keys: ‘auto’, ‘both’, ‘numeric’, or ‘string’.
highlight_marker_size (float, optional, default=140.0) – Size of the highlight star markers.
ax (matplotlib.axes.Axes, optional) – Axis to plot on. If None, a new axis is created.
colorbar (bool, optional, default=True) – Whether to display a colorbar for travel time values.
colorbar_label (str, optional, default="Travel time [h]") – Label for the colorbar (units).
show_axis (bool, optional, default=True) – If False, hides the entire axis (ticks, labels, frame).
- Returns:
A tuple containing: - ax: The matplotlib axis with the plot. - nodes_df: DataFrame of plotted nodes with columns [‘x’, ‘y’, ‘TT’].
- Return type:
tuple(matplotlib.axes.Axes, pandas.DataFrame)
Refer to Example 9: Travel Time compared to Fluid Age. It uses this function.