Net simulation pandapipes package
Advanced Plots for DistrictHeatingSim
Funktionsfähige erweiterte Plot-Funktionen für pandapipes Netzwerke. Diese Version umgeht die API-Limitierungen der pandapipes Collection-Funktionen und bietet robuste, produktionsreife Plotting-Alternativen.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
Features:
Druckverteilungsplots mit Statistiken
Temperaturverteilungsplots
Geschwindigkeitsanalyse
Druckprofile
Interaktive Dashboards
Drop-in Ersatz für config_plot
- districtheatingsim.net_simulation_pandapipes.advanced_plots.create_pressure_plot(net, ax: Axes | None = None, show_colorbar: bool = True)[source]
Pressure distribution plot with data-driven colors and statistics.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with simulation results
ax (Optional[plt.Axes]) – Matplotlib axis, creates new if None
show_colorbar (bool) – Display pressure colorbar, defaults to True
- Returns:
Matplotlib axis with pressure plot
- Return type:
plt.Axes
Note
Blue (low pressure) to red (high pressure). Plots junctions, pipes, consumers, pumps. Includes pressure range statistics.
- districtheatingsim.net_simulation_pandapipes.advanced_plots.create_temperature_plot(net, ax: Axes | None = None)[source]
Temperature distribution plot with data-driven colors and statistics.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with simulation results
ax (Optional[plt.Axes]) – Matplotlib axis, creates new if None
- Returns:
Matplotlib axis with temperature plot
- Return type:
plt.Axes
Note
Plasma colormap (blue=cold, red=hot). Converts Kelvin to Celsius. Shows temperature range statistics.
- districtheatingsim.net_simulation_pandapipes.advanced_plots.create_velocity_plot(net, ax: Axes | None = None)[source]
Velocity distribution plot for pipe flow analysis.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with simulation results
ax (Optional[plt.Axes]) – Matplotlib axis, creates new if None
- Returns:
Matplotlib axis with velocity plot
- Return type:
plt.Axes
Note
Viridis colormap (green=low, yellow=high). Plots pipe velocities with colorbar. Includes velocity range statistics.
- districtheatingsim.net_simulation_pandapipes.advanced_plots.create_pressure_profile(net, ax: Axes | None = None)[source]
Pressure profile along network path showing pressure drop.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with simulation results
ax (Optional[plt.Axes]) – Matplotlib axis, creates new if None
- Returns:
Matplotlib axis with pressure profile
- Return type:
plt.Axes
Note
Distance vs pressure plot. Shows total pressure drop statistics.
- districtheatingsim.net_simulation_pandapipes.advanced_plots.create_comparison_dashboard(net, figsize=(16, 12))[source]
Comprehensive analysis dashboard with 4 plot types.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with simulation results
figsize (tuple) – Figure size tuple (width, height), defaults to (16, 12)
- Returns:
Figure and axes array (2x2)
- Return type:
Tuple[plt.Figure, np.ndarray]
Note
4 subplots: topology, pressure profile, pressure distribution, temperature distribution. Includes network statistics text box.
- districtheatingsim.net_simulation_pandapipes.advanced_plots.get_network_statistics(net)[source]
Extract network statistics as formatted text string.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network
- Returns:
Formatted statistics string
- Return type:
Note
Returns junction count, pipe count, consumer count, total load [kW], pressure range [bar].
- districtheatingsim.net_simulation_pandapipes.advanced_plots.enhanced_config_plot(net, ax, plot_mode='traditional', **kwargs)[source]
Enhanced config_plot replacement with multiple visualization modes.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network to visualize
ax (matplotlib.axes.Axes) – Matplotlib axis for plotting
plot_mode (str) – Mode: ‘traditional’, ‘pressure’, ‘temperature’, ‘velocity’, ‘dashboard’
**kwargs – Additional arguments for plotting functions
- Returns:
Matplotlib axis (or figure for dashboard mode)
- Return type:
plt.Axes
Note
Drop-in replacement for config_plot. Dashboard mode returns new figure.
Config Plot Module
This module provides comprehensive visualization capabilities for district heating network analysis and presentation.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
It combines pandapipes network plotting with interactive features, contextual basemaps, and detailed component annotations to create professional-quality network visualizations for engineering analysis and stakeholder presentations.
The module supports various basemap providers, interactive hover annotations, and customizable component visibility to accommodate different visualization needs from technical analysis to public presentations. It integrates seamlessly with matplotlib and geographic visualization libraries for enhanced spatial context.
- districtheatingsim.net_simulation_pandapipes.config_plot.config_plot(net, ax: Axes, show_junctions: bool = True, show_pipes: bool = True, show_heat_consumers: bool = True, show_pump: bool = True, show_plot: bool = False, show_basemap: bool = True, map_type: str = 'OSM', show_all_annotations: bool = False, crs: str = 'EPSG:25833') None[source]
Interactive pandapipes network visualization with hover annotations and basemaps.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with topology and simulation results
ax (matplotlib.axes.Axes) – Matplotlib axis for rendering
show_junctions (bool) – Display junctions with pressure/temperature, defaults to True
show_pipes (bool) – Display pipes with flow rates/velocities, defaults to True
show_heat_consumers (bool) – Display heat consumers with demand info, defaults to True
show_pump (bool) – Display circulation pumps, defaults to True
show_plot (bool) – Immediately display with plt.show(), defaults to False
show_basemap (bool) – Include contextual basemap, defaults to True
map_type (str) – Basemap type: “OSM”, “Satellite”, “Topology”, defaults to “OSM”
show_all_annotations (bool) – Force all annotations visible, defaults to False
Note
Interactive hover annotations, distance-based visibility. Requires geodata and internet for basemap tiles. Annotations: junctions (pressure/temp), pipes (flow/velocity), consumers (demand), pumps (pressure lift).
Controllers Module
This module provides specialized controllers for district heating network operation using the pandapipes framework.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
It implements advanced control strategies for pressure management, temperature regulation, and system optimization to ensure efficient and reliable network operation under varying load conditions.
The controllers integrate with pandapower’s control system architecture and support both steady-state and time-series simulations. They handle complex control scenarios including bad point pressure control, minimum temperature enforcement, and multi-producer coordination in district heating systems.
- class districtheatingsim.net_simulation_pandapipes.controllers.BadPointPressureLiftController(net, circ_pump_pressure_idx: int = 0, target_dp_min_bar: float = 1.0, tolerance: float = 0.2, proportional_gain: float = 0.2, min_plift: float = 1.5, min_pflow: float = 3.5, **kwargs)[source]
Bases:
BasicCtrlDifferential pressure controller maintaining adequate pressure at network’s worst point.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network object
circ_pump_pressure_idx (int) – Main circulation pump index, defaults to 0
target_dp_min_bar (float) – Target minimum pressure difference [bar], defaults to 1.0
tolerance (float) – Pressure difference tolerance [bar], defaults to 0.2
proportional_gain (float) – Proportional gain factor, defaults to 0.2
min_plift (float) – Minimum pump lift during standby [bar], defaults to 1.5
min_pflow (float) – Minimum flow pressure during standby [bar], defaults to 3.5
**kwargs – Additional arguments for base controller
- Variables:
Note
German “Differenzdruckregelung im Schlechtpunkt”. Identifies worst point (lowest Δp) among active consumers, applies proportional control to pump pressures. Standby mode with minimal circulation when all demands zero. Updates bad point dynamically each step.
- __init__(net, circ_pump_pressure_idx: int = 0, target_dp_min_bar: float = 1.0, tolerance: float = 0.2, proportional_gain: float = 0.2, min_plift: float = 1.5, min_pflow: float = 3.5, **kwargs)[source]
- calculate_worst_point(net) tuple[float, int][source]
Find heat consumer with lowest pressure difference among active consumers.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with current simulation results
- Returns:
(dp_min, idx_min) - minimum pressure difference [bar] and consumer index
- Return type:
Note
Returns (0, -1) if no active consumers. Only considers consumers with qext_w != 0.
- time_step(net, time_step: int) int[source]
Reset controller state and recalculate worst point for new time step.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network object
time_step (int) – Current simulation time step index
- Returns:
Current time step (pass-through)
- Return type:
Note
Resets iteration counter to 0, recalculates worst point location.
- is_converged(net) bool[source]
Check convergence: standby or pressure within tolerance.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with current simulation results
- Returns:
True if converged, False otherwise
- Return type:
Note
Converged if: all qext_w == 0 (standby) OR |current_dp - target_dp| < tolerance
- control_step(net) None[source]
Adjust pump pressures based on pressure difference error at worst point.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network to control
Note
Standby mode if all qext_w == 0 (sets min_plift/min_pflow). Otherwise applies proportional control: error = target_dp - current_dp, adjustment = error × gain.
- class districtheatingsim.net_simulation_pandapipes.controllers.MinimumSupplyTemperatureController(net, heat_consumer_idx: int, min_supply_temperature: float = 65.0, tolerance: float = 2.0, max_iterations: int = 100, temperature_adjustment_step: float = 1.0, debug: bool = False, **kwargs)[source]
Bases:
BasicCtrlController maintaining minimum supply temperatures at heat consumers via return temperature adjustment.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network object
heat_consumer_idx (int) – Index of heat consumer to control
min_supply_temperature (float) – Minimum required supply temperature [°C], defaults to 65.0
tolerance (float) – Temperature tolerance for convergence [°C], defaults to 2.0
max_iterations (int) – Maximum iterations per time step, defaults to 100
temperature_adjustment_step (float) – Temperature adjustment step [°C], defaults to 1.0
debug (bool) – Enable debug output, defaults to False
**kwargs – Additional arguments for base controller
- Variables:
Note
Critical for cold networks with heat pumps. Monitors supply temperature, adjusts return temperature setpoint to increase supply (higher return → higher mass flow → higher supply). Uses weighted averaging for stability. Supports time-varying requirements via data_source.
- __init__(net, heat_consumer_idx: int, min_supply_temperature: float = 65.0, tolerance: float = 2.0, max_iterations: int = 100, temperature_adjustment_step: float = 1.0, debug: bool = False, **kwargs)[source]
- time_step(net, time_step: int) int[source]
Reset controller and update temperature setpoints for new time step.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network object
time_step (int) – Current simulation time step index
- Returns:
Current time step (pass-through)
- Return type:
Note
Resets iteration counter and temperature history. Stores/restores standard return temperature. Updates min_supply_temperature from data_source if available.
- get_weighted_average_temperature() float | None[source]
Calculate weighted average of recent supply temperatures for stability.
- Returns:
Weighted average temperature [°C], or None if no history
- Return type:
Optional[float]
Note
Linear weighting: recent values weighted more heavily. Prevents oscillations.
- control_step(net) None[source]
Adjust return temperature to ensure minimum supply temperature.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network to control
Note
Standby mode if all qext_w == 0. Uses weighted averaging for stability. Increases return temp if supply < minimum (higher return → higher mass flow → higher supply).
- is_converged(net) bool[source]
Check convergence: standby, temperature met and stable, or max iterations.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with current simulation results
- Returns:
True if converged, False otherwise
- Return type:
Note
Converged if: all qext_w == 0 (standby) OR (supply >= minimum AND change < tolerance) OR max iterations reached. Maintains temperature history for weighted averaging.
Interactive Network Plot Module
Modern interactive visualization for pandapipes district heating networks using Plotly.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
Features:
Interactive hover tooltips with detailed component information
Click events for component selection and inspection
Color-coded visualization of any network parameter
Multiple basemap options (OSM, Satellite, Topology)
Layer visibility controls
Dynamic parameter selection
Export capabilities (HTML, PNG)
- class districtheatingsim.net_simulation_pandapipes.interactive_network_plot.InteractiveNetworkPlot(net, crs: str = 'EPSG:25833')[source]
Bases:
objectInteractive Plotly-based network visualization with advanced features.
- Variables:
Note
Color-coded parameter visualization, hover tooltips, click events, multiple basemap options for comprehensive network analysis.
- __init__(net, crs: str = 'EPSG:25833')[source]
Initialize interactive network plot.
- Parameters:
net (pandapipes.pandapipesNet) – Network to visualize
crs (str) – Coordinate reference system, defaults to “EPSG:25833”
- create_interactive_plot_with_controls(basemap_style: str = 'carto-positron', colorscale: str = 'Viridis') Figure[source]
Create interactive plot with dropdown controls for parameter selection.
- Parameters:
- Returns:
Interactive Plotly figure with dropdown controls
- Return type:
go.Figure
Note
Pre-generates all visualizations for dropdown functionality in standalone HTML.
- create_plot_for_parameter(component_type: str, parameter: str, basemap_style: str = 'carto-positron', colorscale: str = 'Viridis') Figure[source]
Create plot for specific parameter visualization (on-demand loading).
- Parameters:
- Returns:
Interactive plot for the specific parameter
- Return type:
go.Figure
- create_plot(parameter: str | None = None, component_type: str | None = None, show_junctions: bool = True, show_pipes: bool = True, show_heat_consumers: bool = True, show_pumps: bool = True, show_flow_controls: bool = True, basemap_style: str = 'open-street-map', colorscale: str = 'Viridis') Figure[source]
Create interactive network plot with optional parameter visualization.
- Parameters:
parameter (Optional[str]) – Parameter to visualize (e.g., ‘p_bar’, ‘v_mean_m_per_s’), optional
component_type (Optional[str]) – Component type: ‘junction’, ‘pipe’, ‘heat_consumer’, ‘pump’, optional
show_junctions (bool) – Show junction nodes, defaults to True
show_pipes (bool) – Show pipe connections, defaults to True
show_heat_consumers (bool) – Show heat consumers, defaults to True
show_pumps (bool) – Show circulation pumps, defaults to True
show_flow_controls (bool) – Show flow control components, defaults to True
basemap_style (str) – Mapbox style: ‘open-street-map’, ‘satellite’, ‘white-bg’, ‘carto-positron’
colorscale (str) – Plotly colorscale name, defaults to ‘Viridis’
- Returns:
Interactive Plotly figure
- Return type:
go.Figure
Network Generation Data Class Module
This module provides data structures for comprehensive district heating network simulation and analysis.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
It defines the core data classes used throughout the simulation workflow, including network configuration parameters, input/output data management, and result processing capabilities.
The module supports various network configurations including traditional hot water networks, cold networks with decentralized heat pumps, and hybrid systems with multiple heat generators. It handles time series data, temperature control strategies, and comprehensive result analysis with automatic calculation of key performance indicators.
- districtheatingsim.net_simulation_pandapipes.NetworkDataClass.json_default(obj)[source]
json.dumpfallback that serialises numpy arrays losslessly as lists.The save path previously used
default=str, which stringifies arrays viastr(array)— numpy abbreviates long arrays ("[1. 2. … 9.]"), an unrecoverable, lossy save that also broke the load round-trip (BACKLOG C12). Arrays/scalars are now emitted as native JSON; anything else still falls back tostrso the save never fails. Pairs withNetworkGenerationData._coerce_arrayon load.
- class districtheatingsim.net_simulation_pandapipes.NetworkDataClass.SecondaryProducer(index: int, load_percentage: float, mass_flow: float | None = None)[source]
Bases:
objectSecondary heat producer with mass flow control based on load percentage.
- Variables:
Note
Load percentages across all secondary producers should not exceed 100%. Main producer handles remaining capacity. Extensible for additional parameters.
- class districtheatingsim.net_simulation_pandapipes.NetworkDataClass.NetworkGenerationData(import_type: str, network_geojson_path: str, heat_demand_json_path: str, netconfiguration: str, supply_temperature_control: str, max_supply_temperature_heat_generator: float, min_supply_temperature_heat_generator: float, max_air_temperature_heat_generator: float, min_air_temperature_heat_generator: float, flow_pressure_pump: float, lift_pressure_pump: float, min_supply_temperature_building_checked: bool, min_supply_temperature_building: float, fixed_return_temperature_heat_consumer_checked: bool, fixed_return_temperature_heat_consumer: float, dT_RL: float, building_temperature_checked: bool, pipetype: str, diameter_optimization_pipe_checked: bool, max_velocity_pipe: float, material_filter_pipe: str, k_mm_pipe: float, main_producer_location_index: int, secondary_producers: list[SecondaryProducer], COP_filename: str | None = None, TRY_filename: str | None = None, supply_temperature_buildings: ndarray | None = None, return_temperature_buildings: ndarray | None = None, supply_temperature_building_curve: ndarray | None = None, return_temperature_building_curve: ndarray | None = None, yearly_time_steps: ndarray | None = None, waerme_gebaeude_ges_W: ndarray | None = None, heizwaerme_gebaeude_ges_W: ndarray | None = None, ww_waerme_gebaeude_ges_W: ndarray | None = None, max_waerme_gebaeude_ges_W: ndarray | None = None, return_temperature_heat_consumer: ndarray | None = None, min_supply_temperature_heat_consumer: ndarray | None = None, waerme_hast_ges_W: ndarray | None = None, max_waerme_hast_ges_W: ndarray | None = None, strombedarf_hast_ges_W: ndarray | None = None, max_el_leistung_hast_ges_W: ndarray | None = None, waerme_hast_ges_kW: ndarray | None = None, strombedarf_hast_ges_kW: ndarray | None = None, waerme_ges_kW: ndarray | None = None, strombedarf_ges_kW: ndarray | None = None, net: Any | None = None, start_time_step: int | None = None, end_time_step: int | None = None, results_csv_filename: str | None = None, supply_temperature_heat_generator: float | ndarray | None = None, net_results: dict[str, Any] | None = None, pump_results: dict[str, Any] | None = None, plot_data: dict[str, Any] | None = None, kpi_results: dict[str, int | float | None] | None = None)[source]
Bases:
objectCentral data container for district heating network simulation and analysis.
- Variables:
import_type (str) – Import method type (currently “geoJSON”)
network_geojson_path (str) – Path to unified GeoJSON file (Wärmenetz.geojson)
heat_demand_json_path (str) – Path to building heat demand JSON
netconfiguration (str) – Network type (“kaltes Netz”, “Niedertemperaturnetz”)
supply_temperature_control (str) – Control strategy (“Statisch”, “Gleitend”)
max_supply_temperature_heat_generator (float) – Maximum supply temperature [°C]
min_supply_temperature_heat_generator (float) – Minimum supply temperature for sliding control [°C]
max_air_temperature_heat_generator (float) – Maximum outdoor air temperature [°C]
min_air_temperature_heat_generator (float) – Design outdoor air temperature [°C]
flow_pressure_pump (float) – Pump outlet pressure [bar]
lift_pressure_pump (float) – Pump pressure lift [bar]
pipetype (str) – Standard pipe type designation
diameter_optimization_pipe_checked (bool) – Enable diameter optimization
max_velocity_pipe (float) – Maximum water velocity [m/s]
material_filter_pipe (str) – Pipe material filter
k_mm_pipe (float) – Pipe roughness [mm]
main_producer_location_index (int) – Main heat producer index in GeoJSON
secondary_producers (List[SecondaryProducer]) – List of secondary producers
net (Optional[Any]) – Pandapipes network object
pump_results (Optional[Dict[str, Any]]) – Structured pump simulation results
plot_data (Optional[Dict[str, Any]]) – Processed visualization data
kpi_results (Optional[Dict[str, Union[int, float, None]]]) – Key performance indicators
Note
Supports GeoJSON-based initialization, time series simulation, KPI calculation. Handles cold networks (heat pumps), static/sliding temperature control. Data flow: GeoJSON+JSON → initialization → simulation → results → KPIs.
- secondary_producers: list[SecondaryProducer]
- calculate_results() dict[str, int | float | None][source]
Calculate network KPIs including heat density, losses, and pump consumption.
- Returns:
Dict with KPIs (Anzahl angeschlossene Gebäude, Jahresgesamtwärmebedarf [MWh/a], max. Heizlast [kW], Trassenlänge [m], Wärmebedarfsdichte [MWh/(a*m)], Anschlussdichte [kW/m], Jahreswärmeerzeugung [MWh], Pumpenstrom [MWh], Verteilverluste [MWh], rel. Verteilverluste [%])
- Return type:
Note
Density = demand/length. Losses = generation - demand. Pump power from mass flow and Δp. Network length divided by 2 (supply+return). Requires net, pump_results, waerme_ges_kW.
- prepare_plot_data() None[source]
Structure simulation results for visualization with labels, axes, and time alignment.
Note
Creates plot_data dict with entries: data (numpy array), label (string), axis (left/right), time (array). Includes heat demand, electrical data (cold networks), producer data (heat generation, mass flow, pressures, temperatures). Indexed by variable name and producer number.
- to_dict() dict[str, Any][source]
Serialize network data including KPIs for saving.
- Returns:
Dictionary with all object attributes including kpi_results
- Return type:
Dict[str, Any]
- classmethod from_dict(data: dict[str, Any]) NetworkGenerationData[source]
Deserialize network data from saved dictionary.
- Parameters:
data (Dict[str, Any]) – Dictionary with serialized network data
- Returns:
Reconstructed NetworkGenerationData object with KPIs
- Return type:
- __init__(import_type: str, network_geojson_path: str, heat_demand_json_path: str, netconfiguration: str, supply_temperature_control: str, max_supply_temperature_heat_generator: float, min_supply_temperature_heat_generator: float, max_air_temperature_heat_generator: float, min_air_temperature_heat_generator: float, flow_pressure_pump: float, lift_pressure_pump: float, min_supply_temperature_building_checked: bool, min_supply_temperature_building: float, fixed_return_temperature_heat_consumer_checked: bool, fixed_return_temperature_heat_consumer: float, dT_RL: float, building_temperature_checked: bool, pipetype: str, diameter_optimization_pipe_checked: bool, max_velocity_pipe: float, material_filter_pipe: str, k_mm_pipe: float, main_producer_location_index: int, secondary_producers: list[SecondaryProducer], COP_filename: str | None = None, TRY_filename: str | None = None, supply_temperature_buildings: ndarray | None = None, return_temperature_buildings: ndarray | None = None, supply_temperature_building_curve: ndarray | None = None, return_temperature_building_curve: ndarray | None = None, yearly_time_steps: ndarray | None = None, waerme_gebaeude_ges_W: ndarray | None = None, heizwaerme_gebaeude_ges_W: ndarray | None = None, ww_waerme_gebaeude_ges_W: ndarray | None = None, max_waerme_gebaeude_ges_W: ndarray | None = None, return_temperature_heat_consumer: ndarray | None = None, min_supply_temperature_heat_consumer: ndarray | None = None, waerme_hast_ges_W: ndarray | None = None, max_waerme_hast_ges_W: ndarray | None = None, strombedarf_hast_ges_W: ndarray | None = None, max_el_leistung_hast_ges_W: ndarray | None = None, waerme_hast_ges_kW: ndarray | None = None, strombedarf_hast_ges_kW: ndarray | None = None, waerme_ges_kW: ndarray | None = None, strombedarf_ges_kW: ndarray | None = None, net: Any | None = None, start_time_step: int | None = None, end_time_step: int | None = None, results_csv_filename: str | None = None, supply_temperature_heat_generator: float | ndarray | None = None, net_results: dict[str, Any] | None = None, pump_results: dict[str, Any] | None = None, plot_data: dict[str, Any] | None = None, kpi_results: dict[str, int | float | None] | None = None) None
Migrate pandapipes nets loaded from older saves to the current schema.
Projects saved on pandapipes 0.13 pickle a pipe table that uses the old KMR …
std-types and the removed diameter_m column. Loaded into 0.14 those nets crash
in pipeflow ('DataFrame' object has no attribute 'inner_diameter_mm') and the
GUI still shows the obsolete KMR names. migrate_loaded_net upgrades such a net in
place so old projects open and recalculate.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- districtheatingsim.net_simulation_pandapipes.net_migration.migrate_loaded_net(net)[source]
Migrate a freshly loaded pandapipes net to the current (0.14) schema, in place.
Re-anchor legacy
KMR …pipe std-types to their ISOPLUS successors, taking the diameter and heat-loss from the current catalog (the user’s KMR pipes are anchored as ISOPLUS in pandapipes 0.14).Ensure the pipe table has the 0.14
inner_diameter_mmcolumn, deriving it from the legacydiameter_m[m] for any pipe not covered by the remap.
- Parameters:
net – The loaded pandapipes network.
- Returns:
The same network, migrated.
Helpers for reading pandapipes pipe std-type properties (GUI-free, numpy-only).
pandapipes >= 0.14 ships ISOPLUS bonded-steel pipes (the successor to the old
“KMR …” types). Those carry their heat loss as u_w_per_mk [W/(m·K)] (per pipe
length) and leave the legacy u_w_per_m2k [W/(m²·K)] column empty, whereas the
0.13 KMR types stored u_w_per_m2k directly. Code that reads u_w_per_m2k from
the std-type table therefore gets NaN for ISOPLUS pipes.
resolve_pipe_u_w_per_m2k returns the per-area coefficient for either format,
converting the per-length value the same way pandapipes does internally
(u_w_per_m2k = u_w_per_mk / (π · outer_diameter)).
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- districtheatingsim.net_simulation_pandapipes.pipe_std_types.isoplus_std_type_names(std_types) list[str][source]
Filter a pandapipes pipe-std-type table to the ISOPLUS bonded-steel types.
- districtheatingsim.net_simulation_pandapipes.pipe_std_types.kmr_to_isoplus_std_type(name) str | None[source]
Map a legacy
KMR …pipe std-type name to its nominal ISOPLUS equivalent.KMR 100/250-2v→ISOPLUS_DRE100_2x. The returned type may not exist in pandapipes for every nominal width (e.g.ISOPLUS_DRE175_2x); usenearest_isoplus_for_kmr()to snap to an available size. ReturnsNonefor names that are not legacy KMR types (e.g. already-ISOPLUS names).- Parameters:
name – A pipe std-type name.
- Returns:
The nominal ISOPLUS name, or
Noneifnameis not a KMR type.- Return type:
str | None
- districtheatingsim.net_simulation_pandapipes.pipe_std_types.nearest_isoplus_for_kmr(name, catalog) str | None[source]
Map a legacy KMR name to an ISOPLUS std-type that exists in
catalog.Prefers the exact
ISOPLUS_DRE<DN>_<n>xsuccessor; if that nominal width is not offered (e.g. DN175), snaps to the same insulation grade at the nearest available nominal width, rounding up on a tie (the hydraulically safer, larger pipe).- Parameters:
name – A legacy KMR std-type name.
catalog – Pipe std-type catalog (a
DataFramewith the type names as index).
- Returns:
An ISOPLUS type present in
catalog, orNoneifnameis not KMR or no same-grade ISOPLUS type exists.- Return type:
str | None
- districtheatingsim.net_simulation_pandapipes.pipe_std_types.resolve_pipe_u_w_per_m2k(properties) float[source]
Per-area heat-transfer coefficient [W/(m²·K)] for a pipe std-type row.
- Parameters:
properties – A pipe std-type row (pandas Series or dict) with at least
outer_diameter_mmand one ofu_w_per_m2k/u_w_per_mk.- Returns:
u_w_per_m2k: the stored per-area value if present, otherwise the per-lengthu_w_per_mkconverted via the outer surface.- Return type:
- Raises:
ValueError – If neither a valid per-area nor per-length value is available.
Plot-data extraction for the interactive network plot (Plotly-free, GUI-free).
Pulls the data the interactive Plotly plot needs out of a pandapipes net into plain
Python structures, so the rendering layer (interactive_network_plot) no longer
mixes pandapipes queries with Plotly trace building (BACKLOG B1/B3). Being Plotly- and
GUI-free, this layer is unit-testable through the network test seam.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- class districtheatingsim.net_simulation_pandapipes.plot_data.JunctionPlotData(lats: ndarray, lons: ndarray, hover_texts: list[str], values: ndarray | None, ids: ndarray)[source]
Bases:
objectEverything the renderer needs to draw the junction markers — no pandapipes.
- districtheatingsim.net_simulation_pandapipes.plot_data.junction_geodata_wgs84(net, crs) GeoDataFrame[source]
Junction coordinates as a WGS84 GeoDataFrame (for Plotly mapbox).
- districtheatingsim.net_simulation_pandapipes.plot_data.junction_plot_data(net, crs, parameter: str | None = None) JunctionPlotData[source]
Extract junction marker data (coords, hover text, colour values) from the net.
- Parameters:
net – pandapipes network (duck-typed:
junction_geodata,junction, optionalres_junction).crs – source CRS of the junction geodata (reprojected to WGS84).
parameter –
res_junctioncolumn to colour by, orNone.
- Return type:
- districtheatingsim.net_simulation_pandapipes.plot_data.parameter_label(parameter: str) str[source]
German display label (with unit) for a result parameter.
- districtheatingsim.net_simulation_pandapipes.plot_data.parameter_value(res_df, idx, parameter)[source]
Value of
parameterfor componentidx, computing the deriveddt_k/dp_barfrom the from/to columns. ReturnsNoneif unavailable.
- class districtheatingsim.net_simulation_pandapipes.plot_data.PipeSegment(from_lat: float, from_lon: float, mid_lat: float, mid_lon: float, to_lat: float, to_lon: float, hover_text: str, value: float | None, idx: object, name: str)[source]
Bases:
objectOne pipe drawn as a from→mid→to polyline, with hover text and colour value.
- class districtheatingsim.net_simulation_pandapipes.plot_data.PipePlotData(segments: list[districtheatingsim.net_simulation_pandapipes.plot_data.PipeSegment], vmin: float | None, vmax: float | None, center_lat: float, center_lon: float)[source]
Bases:
object- segments: list[PipeSegment]
- districtheatingsim.net_simulation_pandapipes.plot_data.pipe_plot_data(net, junctions_wgs84, parameter: str | None = None) PipePlotData[source]
Extract pipe polyline data (endpoint/mid coords, hover, colour values) from the net.
- Parameters:
net – pandapipes network (duck-typed:
pipe, optionalres_pipe).junctions_wgs84 – WGS84 junction GeoDataFrame (from
junction_geodata_wgs84()).parameter –
res_pipecolumn (or deriveddt_k/dp_bar) to colour by.
- Return type:
- districtheatingsim.net_simulation_pandapipes.plot_data.heat_consumer_plot_data(net, junctions_wgs84, parameter: str | None = None) PipePlotData[source]
Extract heat-consumer polyline data (coords, hover, colour values) from the net.
Same line structure as
pipe_plot_data(); the hover fields are consumer-specific (heat demand, supply/return temperatures and pressures).
- districtheatingsim.net_simulation_pandapipes.plot_data.pump_plot_data(net, junctions_wgs84, parameter: str | None = None) PipePlotData[source]
Extract circulation-pump polyline data from the net (both pressure and mass pumps).
Same line structure as
pipe_plot_data(); segments from both pump tables are concatenated in order. The hover swaps supply/return as the renderer did.
- districtheatingsim.net_simulation_pandapipes.plot_data.flow_control_plot_data(net, junctions_wgs84, parameter: str | None = None) PipePlotData[source]
Extract flow-control polyline data from the net.
Same line structure as
pipe_plot_data(); hover reports the setpoint mass flow plus the solved mass flow and pressures.
- districtheatingsim.net_simulation_pandapipes.plot_data.available_plot_parameters(net) dict[str, list[str]][source]
The result parameters available for colour-coding per component type.
Inspects the net’s
res_*tables and returns the parameters the plot can offer for each component (junction, pipe, heat_consumer, pump, flow_control). Empty lists for components without results yet.
Pandapipes Network Initialization Module
This module provides comprehensive network initialization capabilities for district heating systems using GeoJSON-based geographic data.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
It handles the complete workflow from GeoJSON data processing to pandapipes network creation, including heat demand integration, temperature calculation, and multi-producer system configuration.
The module supports various network configurations including traditional hot water networks, cold networks with decentralized heat pumps, and hybrid systems with multiple heat generators. It automatically processes building heat demands, calculates temperature requirements, and creates appropriate network topologies with proper controller configurations.
- districtheatingsim.net_simulation_pandapipes.pp_net_initialisation_geojson.initialize_geojson(NetworkGenerationData) Any[source]
Initialize district heating network from unified GeoJSON and heat demand data.
- Parameters:
NetworkGenerationData (object) – Configuration with network_geojson_path, heat_demand_json_path, temperatures, pipe specs, producer config
- Returns:
Updated NetworkGenerationData with initialized net, time series, mass flows, building data
- Return type:
Any
- Raises:
FileNotFoundError – If GeoJSON or JSON files not found
ValueError – If temperature constraints violated (return > supply)
KeyError – If required JSON fields missing
Note
Loads unified GeoJSON (Wärmenetz.geojson), processes heat demands, validates temperatures. Handles cold networks (COP calculation), applies 2% min load. Calculates mass flows (main: total demand/ΔT, secondary: percentage-based). Creates complete pandapipes network.
- districtheatingsim.net_simulation_pandapipes.pp_net_initialisation_geojson.get_line_coords_and_lengths(gdf: GeoDataFrame) tuple[list[list[tuple]], list[float]][source]
Extract 2-D coordinates and lengths from LineString geometries.
Z-coordinates (elevation) are stripped here so that the returned coordinate tuples are always
(x, y). Elevation data is extracted separately viabuild_elevation_lookup_from_gdf()and passed to the junction-creation step asheight_m.- Parameters:
gdf (gpd.GeoDataFrame) – GeoDataFrame with LineString geometries (flow/return lines)
- Returns:
(all_line_coords, all_line_lengths) - 2-D coordinate sequences and lengths
- Return type:
Tuple[List[List[Tuple]], List[float]]
Note
Only processes LineString geometries, skips others with warning. Uses GeoPandas length property for geodetic calculation.
- districtheatingsim.net_simulation_pandapipes.pp_net_initialisation_geojson.build_elevation_lookup_from_gdf(gdf: GeoDataFrame) dict[tuple, float][source]
Build a
{(x, y): z_m}elevation lookup from a GeoDataFrame with 3-D geometries.Only vertices that actually carry a Z-coordinate contribute to the lookup. Vertices without Z are silently skipped (they will fall back to
height_m=0).
- districtheatingsim.net_simulation_pandapipes.pp_net_initialisation_geojson.get_all_point_coords_from_line_cords(all_line_coords: list[list[tuple]]) list[tuple][source]
Extract unique point coordinates for network junction creation.
- Parameters:
all_line_coords (List[List[Tuple]]) – List of 2-D coordinate sequences [(x1,y1), (x2,y2), …]
- Returns:
Unique point coordinates (x, y) for junction locations
- Return type:
List[Tuple]
Note
Removes duplicates using set operations. Order not guaranteed. Essential for proper network topology without duplicate junctions.
- districtheatingsim.net_simulation_pandapipes.pp_net_initialisation_geojson.create_network(gdf_dict: dict[str, GeoDataFrame], consumer_dict: dict[str, Any], pipe_dict: dict[str, Any], producer_dict: dict[str, Any]) pandapipesNet[source]
Create complete pandapipes network with junctions, pipes, consumers, and producers.
- Parameters:
gdf_dict (Dict[str, gpd.GeoDataFrame]) – GeoDataFrames with keys flow_line, return_line, heat_consumer, heat_producer
consumer_dict (Dict[str, Any]) – Heat consumer config (qext_w, min_supply_temperature_heat_consumer, return_temperature_heat_consumer)
pipe_dict (Dict[str, Any]) – Pipe config (pipetype, v_max_pipe, material_filter, pipe_creation_mode, k_mm)
producer_dict (Dict[str, Any]) – Producer config (supply_temperature, pressures, main_producer_location_index, secondary_producers)
- Returns:
Complete pandapipes network with optimized diameters and controllers
- Return type:
pp.pandapipesNet
Note
Steps: 1) junctions from coords, 2) pipes (supply/return), 3) heat consumers, 4) producers (main=circ_pump_pressure, secondary=circ_pump_mass), 5) pipeflow, 6) controllers, diameter optimization. Corrects flow directions automatically.
Pandapipes time series simulation for district heating networks including controller updates, temperature control, and result processing.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.update_heat_consumer_qext_controller(net, qext_w_profiles: list[ndarray], time_steps: range, start: int, end: int) None[source]
Update external heat demand controllers with time-dependent profiles.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with controllers
qext_w_profiles (List[np.ndarray]) – List of heat demand profiles for each consumer [W]
time_steps (range) – Time steps for simulation period
start (int) – Start index for slicing profiles
end (int) – End index for slicing profiles
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.update_heat_consumer_temperature_controller(net, min_supply_temperature_heat_consumer: ndarray | list, time_steps: range, start: int, end: int) None[source]
Update minimum supply temperature controllers with static or time-dependent profiles.
- Parameters:
Note
Handles both scalar (static) and array (dynamic) temperature requirements.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.update_heat_consumer_return_temperature_controller(net, return_temperature_heat_consumer: ndarray | list, time_steps: range, start: int, end: int) None[source]
Update return temperature controllers with static or dynamic profiles.
- Parameters:
Note
Automatically converts temperatures from °C to K (adds KELVIN_OFFSET).
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.update_secondary_producer_controller(net, secondary_producers: list[Any], time_steps: range, start: int, end: int) None[source]
Update secondary producer mass flow controllers for time series simulation.
- Parameters:
Note
Updates both circ_pump_mass and flow_control controllers for each producer.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.update_heat_generator_supply_temperature_controller(net, supply_temperature: ndarray, time_steps: range, start: int, end: int) None[source]
Update supply temperature controllers for heat generators with time-dependent profiles.
- Parameters:
Note
Converts °C to K, updates both circ_pump_pressure and circ_pump_mass controllers.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.create_log_variables(net) list[tuple[str, str]][source]
Create list of variables to log during time series simulation.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network to analyze for available components
- Returns:
List of (table_name, variable_name) tuples to log
- Return type:
Note
Logs junction pressures/temperatures, heat consumer data, and conditionally circ_pump_mass.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.time_series_preprocessing(NetworkGenerationData) Any[source]
Preprocess time series data including temperature control and COP calculations.
- Parameters:
NetworkGenerationData (object) – Network data with simulation parameters and profiles
- Returns:
Updated NetworkGenerationData with preprocessed time series
- Return type:
Any
Note
Implements static/sliding temperature control, COP calculations for cold networks, applies 2% minimum load, calculates secondary producer mass flows. Converts W to kW.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.thermohydraulic_time_series_net(NetworkGenerationData) Any[source]
Run thermohydraulic time series simulation with controller updates.
- Parameters:
NetworkGenerationData (object) – Network data with preprocessed model and parameters
- Returns:
Updated NetworkGenerationData with simulation results and pump operations
- Return type:
Any
Note
Runs bidirectional simulation with iter=100, alpha=0.5. Updates all controllers (heat demand, temperatures, secondary producers). Logs junction, heat consumer, and pump data.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.simplified_time_series_net(NetworkGenerationData) Any[source]
Run simplified time series by scaling design state with building heat demand.
- Parameters:
NetworkGenerationData (object) – Network data with design state from initialization
- Returns:
Updated NetworkGenerationData with scaled load profiles
- Return type:
Any
Note
No pipeflow calculation. Uses design state from net.res_*, scales with demand. Constant temperatures/pressures from design. Losses scaled proportionally. Much faster than thermohydraulic_time_series_net.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.calculate_results(net, net_results: dict, cp_kJ_kgK: float = 4.18) dict[str, dict[int, dict[str, ndarray]]][source]
Process and structure raw simulation results from pandapipes.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network with component definitions
net_results (Dict) – Raw results dictionary from time series simulation
cp_kJ_kgK (float) – Specific heat capacity of water [kJ/kg·K], defaults to CP_WATER_KJ_KGK (4.18)
- Returns:
Structured results dict: {producer_type: {index: {parameter: time_series}}}
- Return type:
Note
Converts K→°C, calculates heat from mass flow and ΔT. Parameters: mass_flow, flow_pressure, return_pressure, deltap, return_temp, flow_temp, qext_kW. Handles circ_pump_pressure (main) and circ_pump_mass (secondary).
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.save_results_csv(time_steps: ndarray, total_heat_KW: ndarray, strom_wp_kW: ndarray, pump_results: dict, filename: str) None[source]
Export simulation results to CSV file with German column headers.
- Parameters:
time_steps (np.ndarray) – Time step array
total_heat_KW (np.ndarray) – Building heat demand time series [kW]
strom_wp_kW (np.ndarray) – Heat pump electrical consumption [kW]
pump_results (Dict) – Structured pump results from calculate_results
filename (str) – Output CSV file path
Note
Semicolon-separated CSV with German column names. Includes Zeit, Gesamtwärmebedarf_Gebäude_kW, pump data (Wärmeerzeugung, Massenstrom, Delta p, temperatures, pressures). UTF-8-sig encoding.
- districtheatingsim.net_simulation_pandapipes.pp_net_time_series_simulation.import_results_csv(filename: str) tuple[ndarray, ndarray, ndarray, dict][source]
Import simulation results from CSV file created by save_results_csv.
- Parameters:
filename (str) – Input CSV file path
- Returns:
(time_steps, total_heat_KW, strom_wp_kW, pump_results)
- Return type:
Tuple[np.ndarray, np.ndarray, np.ndarray, Dict]
- Raises:
FileNotFoundError – If CSV file cannot be found
pd.errors.ParserError – If CSV format is invalid
KeyError – If required columns are missing
Note
Parses German semicolon-separated CSV. Reconstructs pump_results dict structure. Converts dtypes to datetime64/float64. Returns time_steps as datetime, heat/power as kW arrays, pump_results matching calculate_results.
Validation of pandapipes time-series simulation results (GUI-free, numpy-only).
A non-convergent or infeasible thermohydraulic run leaves NaN/inf in the result
arrays; without a check those silently propagate into the heat/temperature
post-processing. This module surfaces the failure as a clear RuntimeError
instead (BACKLOG C2). Kept dependency-light (numpy only) so it imports and unit-
tests without pulling in pandapipes.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- districtheatingsim.net_simulation_pandapipes.result_validation.validate_simulation_results(net_results: dict, *, context: str = '') None[source]
Raise
RuntimeErrorif the simulation produced no / non-finite results.- Parameters:
- Raises:
RuntimeError – If
net_resultsis empty, or any numeric result array contains NaN/inf — a sign the solver did not converge or the network is disconnected/infeasible.
- districtheatingsim.net_simulation_pandapipes.result_validation.validate_net_results(net, *, context: str = '') None[source]
Raise
RuntimeErrorif a solved net’s steady-state results are missing/non-finite.Called at network build time (
create_network): after the design pipeflow + diameter sizing theres_junctiontable must exist and be finite. An empty or NaN/inf result means the pipeflow did not converge (a disconnected or infeasible network — e.g. an unreachable consumer) and would otherwise silently poison the downstream time series.- Parameters:
net – A solved pandapipes network (duck-typed: needs
res_junction).context – Optional label included in the error message.
- Raises:
RuntimeError – If there are no junction results, or any are NaN/inf.
- districtheatingsim.net_simulation_pandapipes.result_validation.validate_pressure_plausibility(net, *, min_pressure_bar: float = 0.0, context: str = '') list[int][source]
Warn (do not raise) if a solved net has implausibly low absolute pressures.
pandapipes solves in absolute pressure, so a junction pressure
<= 0 baris physically impossible (vacuum / cavitation). The pipeflow can still “converge” to such a state — pandapipes only emits a transient UserWarning — and every other validator here (NaN/inf only) lets it pass silently. A negative final pressure means the pump head is too low for the network’s pressure losses: an under-dimensioned pump, or undersized pipes running above the velocity limit (highdp). See BACKLOG C14.This is intentionally a soft check (logs a warning, returns the offending junctions) rather than a
RuntimeError: an under-pressurized result is a legitimate intermediate planning state the user may want to inspect and fix by raising the pump pressure or enabling diameter optimization.- Parameters:
- Returns:
Indices of the junctions below the threshold (empty if all plausible).
- Return type:
- districtheatingsim.net_simulation_pandapipes.result_validation.validate_design_state(design_results: dict, *, context: str = '') None[source]
Raise
RuntimeErrorif the extracted producer design-state contains NaN/inf.The simplified time series scales this design state (read from
net.res_*after the initialization pipeflow) by the building demand. A NaN/inf here means the network initialization did not converge, which would otherwise silently poison every scaled time step.- Parameters:
- Raises:
RuntimeError – If any design-state value is NaN/inf.
Pandapipes network utility functions for district heating simulation, optimization, and analysis including heat pump calculations, controller creation, and diameter optimization.
- author:
Dipl.-Ing. (FH) Jonas Pfeiffer
- districtheatingsim.net_simulation_pandapipes.utilities.validate_minimum_pressure_difference(net, target_dp_min_bar: float = 1.0, verbose: bool = True) tuple[bool, list[dict[str, Any]]][source]
Validate that all heat consumers meet minimum pressure difference requirements.
- Parameters:
- Returns:
(all_ok, violations) - True if all consumers meet requirements, list of violations
- Return type:
Note
Design validation only - does NOT modify pump parameters like BadPointPressureLiftController.
- districtheatingsim.net_simulation_pandapipes.utilities.recalculate_net(net, mode: str = 'bidirectional', iter: int = 100)[source]
Re-run the steady-state thermohydraulic solve on
netin place.Runs a bidirectional pipeflow followed by the controllers — e.g. after the user edits pipe parameters in the GUI. This is the domain step behind the “recalculate network” button; keeping it here (rather than inline in the view) makes it testable and keeps the GUI free of solver calls (BACKLOG B2).
- Parameters:
net – Pandapipes network to recalculate (modified in place).
mode – Pipeflow mode, defaults to “bidirectional”.
iter – Maximum solver iterations, defaults to 100.
- Returns:
The same network, with refreshed
res_*tables.- Raises:
RuntimeError – If the solver does not converge (with run context), instead of an opaque pandapipes traceback.
- districtheatingsim.net_simulation_pandapipes.utilities.COP_WP(VLT_L: float | ndarray, QT: float | ndarray, values: ndarray | None = None) tuple[ndarray, ndarray][source]
Calculate heat pump Coefficient of Performance (COP) based on supply and source temperatures.
- Parameters:
- Returns:
(COP values [-], adjusted supply temperatures [°C])
- Return type:
Tuple[np.ndarray, np.ndarray]
- Raises:
ValueError – If QT array length doesn’t match VLT_L length
FileNotFoundError – If default COP data file not found
Note
Technical constraints: max temp lift 75°C (VLT_L ≤ QT + 75°C), min supply temp 35°C.
- districtheatingsim.net_simulation_pandapipes.utilities.create_controllers(net, qext_w: ndarray, supply_temperature_heat_generator: float, min_supply_temperature_heat_consumer: ndarray | None, return_temperature_heat_consumer: ndarray, secondary_producers: list[dict[str, Any]] | None = None)[source]
Create comprehensive control systems for district heating network operation.
- Parameters:
net (pandapipes.pandapipesNet) – Pandapipes network object
qext_w (np.ndarray) – External heat demand values for each consumer [W]
supply_temperature_heat_generator (float) – Supply temperature setpoint for main generator [°C]
min_supply_temperature_heat_consumer (Optional[np.ndarray]) – Minimum required supply temperatures [°C] (None if no constraints)
return_temperature_heat_consumer (np.ndarray) – Return temperature setpoints for consumers [°C]
secondary_producers (Optional[List[Dict[str, Any]]]) – List of secondary producer objects with index, mass_flow, load_percentage
- Returns:
Network with all controllers added
- Return type:
pandapipes.pandapipesNet
Note
Controllers include heat consumer demand, temperature regulation, secondary producers, and pressure management.
- districtheatingsim.net_simulation_pandapipes.utilities.correct_flow_directions(net) pandapipesNet[source]
Correct hydraulic flow directions by analyzing velocities and swapping junction connections.
- Parameters:
net (pandapipes.pandapipesNet) – Network with potentially incorrect flow directions
- Returns:
Network with corrected flow directions
- Return type:
pp.pandapipesNet
Note
Identifies pipes with negative velocities and swaps from_junction/to_junction for proper flow representation.
- districtheatingsim.net_simulation_pandapipes.utilities.optimize_diameter_parameters(net, element: str = 'pipe', v_max: float = 1.0, dx: float = 0.001, safety_factor: float = 1.5) pandapipesNet[source]
Optimize network element diameters to meet maximum velocity constraints using continuous adjustment.
- Parameters:
- Returns:
Network with optimized diameters
- Return type:
pp.pandapipesNet
Note
Iteratively adjusts diameters with step size dx. Effective v_max = v_max / safety_factor.
- districtheatingsim.net_simulation_pandapipes.utilities.init_diameter_types(net, v_max_pipe: float = 1.0, material_filter: str = 'P235GH/PUR/PEHD', k: float = 0.1) pandapipesNet[source]
Initialize pipe diameters using standard pipe types based on velocity requirements.
- Parameters:
- Returns:
Network with initialized standard pipe types
- Return type:
pp.pandapipesNet
Note
Selects closest available standard type from filtered catalog based on required diameter.
- districtheatingsim.net_simulation_pandapipes.utilities.build_diameter_ladders(filtered_by_material) dict[str, list[str]][source]
Group std-types by insulation grade, each ordered by ascending inner diameter.
- Parameters:
filtered_by_material – Catalog rows (a DataFrame indexed by std-type name with an
inner_diameter_mmcolumn) already filtered to one material.- Returns:
{grade: [type_name, …]}ordered small→large bore. Lets the optimizer step a pipe to the next/previous diameter without changing its insulation grade (the old position±1 stepping walked_STD``→``_1x``→``_2x, i.e. changed insulation without changing velocity).- Return type:
- districtheatingsim.net_simulation_pandapipes.utilities.neighbor_std_type(std_type: str, ladders: dict[str, list[str]], *, larger: bool) str | None[source]
Next-larger or next-smaller diameter std-type of the same insulation grade.
- Parameters:
std_type – Current pipe std-type name.
ladders – Output of
build_diameter_ladders().larger –
Truefor the next bigger bore,Falsefor the next smaller.
- Returns:
The neighbouring std-type name, or
Noneifstd_typeis already at the end of its grade ladder (or is not in the catalog).- Return type:
str | None
- districtheatingsim.net_simulation_pandapipes.utilities.optimize_diameter_types(net, v_max: float = 1.0, material_filter: str = 'P235GH/PUR/PEHD', k: float = 0.1) pandapipesNet[source]
Optimize pipe diameters using discrete standard pipe types through iterative adjustment.
- Parameters:
- Returns:
Network with optimized standard pipe types
- Return type:
pp.pandapipesNet
Note
Iteratively adjusts standard types: upsize pipes exceeding v_max, attempt downsizing below v_max.
- districtheatingsim.net_simulation_pandapipes.utilities.export_net_geojson(net, filename: str, crs: str = 'EPSG:25833') dict[source]
Export pandapipes network data to unified GeoJSON format (Version 2.0).
- Parameters:
- Returns:
Feature counts {‘flow’: int, ‘return’: int, ‘building’: int, ‘generator’: int}
- Return type:
Note
Creates single file with flow/return lines, building connections, and generator connections.