API Documentation

network

This module is designed to hold the definition of the central ThermalNetwork object and its components.

This file is part of project dhnx (). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location:

SPDX-License-Identifier: MIT

class dhnx.network.ThermalNetwork(dirname=None)[source]

Bases: object

Class representing thermal (heating/cooling) networks.

Parameters:
  • availalable_components
  • component_attrs
  • components
  • sequences
  • results
  • graph

Examples

>>> from dhnx.network import ThermalNetwork
>>> tnw = ThermalNetwork('csv_folder')
>>> tnw.is_consistent()
True
add(class_name, id, **kwargs)[source]

Adds a row with id to the component DataFrame specified by class_name.

Parameters:
  • class_name
  • id
  • kwargs
from_csv_folder(dirname)[source]
is_consistent()[source]
Checks that
  • pipes connect to existing nodes,
  • pipes do not connect a node with itself,
  • there are no duplicate pipes between two nodes.
optimize_investment(invest_options, **kwargs)[source]
optimize_operation()[source]
remove(class_name, id)[source]

Removes the row with id from the component DataFrame specified by class_name.

Parameters:
  • class_name (str) – Name of the component class
  • id (int) – id of the component to remove
reproject(crs)[source]
set_defaults()[source]

Sets default values on component DataFrames.

Returns:
Return type:None
set_timeindex()[source]

Takes all sequences and checks if their timeindex is identical. If that is the case, it sets the timeindex attribute of the class. If there are no sequences given, the timeindex will keep the default value.

simulate(*args, **kwargs)[source]
to_csv_folder(dirname)[source]
to_nx_graph()[source]

gistools

This module holds functions for processing the geometry for setting up the geometry of a ThermalNetwork based on a street geometry and a table of buildings.

This file is part of project dhnx (). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location: https://github.com/oemof/DHNx

This module is not fully tested yet, so use it with care.

SPDX-License-Identifier: MIT

dhnx.gistools.connect_points.calc_lot_foot(line, point)[source]

Calculates the lot foot point.

Parameters:
  • line (shapely.geometry.LineString) –
  • point (shapely.geometry.Point) –
Returns:

Return type:

shapely.geometry.Point

dhnx.gistools.connect_points.check_geometry_type(gdf, types)[source]

Checks, if a geodataframe has only the given geometry types in its GeoSeries.

Parameters:
  • gdf (geopandas.GeoDataFrame) – DataFrame to be checked.
  • types (list) – List of types allowed for GeoDataFrame.
dhnx.gistools.connect_points.create_object_connections(points, lines, tol_distance=1)[source]

Connects points to a line network.

Generally, the nearest point of the next line is used as connection the point. Depending on the geometry, there are 3 options, the connection is created: - nearest point is line ending => the connection line starts from this line ending - nearest point is on the next line:

a) line endings are outside the tolerance => line is split and the nearest point is used as connection point b) line endings are within the tolerance distance => the next line ending is used as connection point

The tolerance distance avoids the generation of short line elements. This is for example the case if two buildings are directly opposite of the street. Using simply the nearest point method could result in very short lines.

Parameters:
  • points (geopandas.GeoDataFrame) – Points which should be connected to the line. GeoDataFrame with Points as geometry.
  • lines (geopandas.GeoDataFrame) – The line-network to which the Points should be connected. The line geometry needs to consists of simple lines based on one starting and one ending point. LineStrings which contain more than 2 points are not allowed.
  • tol_distance (float) – Tolerance distance for choosing the end of the line instead of the nearest point.
Returns:

  • geopandas.GeoDataFrame (The newly created connection lines)
  • geopandas.GeoDataFrame (The updated lines (some lines are split.) – All lines should only touch at the line endings.

dhnx.gistools.connect_points.create_points_from_polygons(gdf, method='midpoint')[source]

Converts the geometry of a polygon layer to a point layer.

Parameters:
  • gdf (geopandas.GeoDataFrame) –
  • method (str) – Method to create a point from a polygon.
Returns:

geopandas.GeoDataFrame

Return type:

GeoDataFrame with a point geometry.

dhnx.gistools.connect_points.line_of_point(point, gdf_lines)[source]
Gets index of geometry of a GeoDataFrame, a point is located next to,
with a distance lower than 1e-8.
Parameters:
  • point (shapely.geometry.Point) –
  • gdf_lines (geopandas.GeoDataFrame) –
Returns:

int, float or str

Return type:

Index of GeoDataFrame or Warning, if no geometry found.

dhnx.gistools.connect_points.point_to_array(point)[source]

Returns the coordinates of a point as numpy.array

Parameters:point (shapely.geometry.Point) –
Returns:
Return type:numpy.array()
dhnx.gistools.connect_points.process_geometry(lines, consumers, producers, method='midpoint', projected_crs=4647, tol_distance=2)[source]

This function connects the consumers and producers to the line network, and prepares the attributes of the geopandas.GeoDataFrames for importing as dhnx.ThermalNetwork.

The ids of the lines are overwritten.

Parameters:
  • lines (geopandas.GeoDataFrame) – Potential routes for the DHS. Expected geometry Linestrings or MultilineStrings. The graph of this line network should be connected.
  • consumers (geopandas.GeoDataFrame) – Location of demand/consumers. Expected geometry: Polygons or Points.
  • producers (geopandas.GeoDataFrame) – Location of supply sites. Expected geometry: Polygons or Points.
  • method (str) – Method for creating the point if polygons are given for the consumers and producers.
  • multi_connections (bool) – Setting if a building should be connected to multiple streets.
  • projected_crs (EPSG integer code) – EPSG Coordinate reference system number (eg 4647), which is used for the geometry operations. A projected crs must be used!
  • tol_distance (float) – Tolerance distance at connection the points to the line network for choosing the end of the line instead of the lot.
Returns:

dict – equal to the components of the dhnx.ThermalNetwork: ‘forks’, ‘consumers’, ‘producers’, ‘pipes’.

Return type:

Dictionary with 4 geopandas.GeoDataFrames: The keys of the Dict are

model

This module is designed to base classes for optimization and simulation models.

This file is part of project dhnx (). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location:

SPDX-License-Identifier: MIT

class dhnx.model.InvestOptimizationModel(thermal_network)[source]

Bases: dhnx.model.Model

Abstract base class for investment optimization models.

is_consistent()[source]
class dhnx.model.Model(thermal_network)[source]

Bases: object

Abstract base class for different kind of models.

get_results()[source]
is_consistent()[source]
setup()[source]
solve()[source]
class dhnx.model.OperationOptimizationModel(thermal_network)[source]

Bases: dhnx.model.Model

Abstract base class for operational optimization models.

is_consistent()[source]
class dhnx.model.SimulationModel(thermal_network)[source]

Bases: dhnx.model.Model

Abstract base class for simulation models.

is_consistent()[source]

optimization

This module is designed to hold optimization model implementations. The implementation makes use of oemof-solph.

This file is part of project dhnx (). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location:

SPDX-License-Identifier: MIT

class dhnx.optimization.OemofInvestOptimizationModel(thermal_network, settings, investment_options)[source]

Bases: dhnx.model.InvestOptimizationModel

Implementation of an invest optimization model using oemof-solph.

settings

Dictionary holding the optimisation settings. See .

Type:dict
invest_options

Dictionary holding the investment options for the district heating system.

Type:dict
nodes

Empty list for collecting all oemof.solph nodes.

Type:list
buses

Empty dictionary for collecting all oemof.solph.Buses of the energy system.

Type:dict
es

Empty oemof.solph.EnergySystem.

Type:oemof.solph.EnergySystem
om

Attribute, which will be the oemof.solph.Model for optimisation.

Type:oemof.solph.Model
oemof_flow_attr

Possible flow attributes, which can be used additionally: {‘nominal_value’, ‘min’, ‘max’, ‘variable_costs’, ‘fix’}

Type:set
results

Empty dictionary for the results.

Type:dict
check_input():

Performs checks on the input data.

complete_exist_data():

Sets the investment status for the results dataframe of the pipes.

get_pipe_data():

Adds heat loss and investment costs to pipes dataframe.

setup_oemof_es():

The energy system es is build.

setup():

Calls check_input(), complete_exist_data(), get_pipe_data(), and setup_oemof_es().

check_existing()[source]

Checks if the attributes existing and hp_type are given in the pipes table. If not, the attribute is added, and set to None / 0.

Checks for all existing pipes, if the heatpipe type is given in the pipe type table .invest_options[‘network’][‘pipes’], and if the capacity is greater than zero.

check_input()[source]

Check 1:

Check and make sure, that the dtypes of the columns of the sequences and the indices (=ids) of the forks, pipes, producers and consumers are of type ‘str’. (They need to be the same dtye.)

Check 2:

Firstly, it is checked, if there are any not-allowed connection in the pipe data. The following connections are not allowed:

  • consumer -> consumer
  • producer -> producer
  • producer -> consumer
  • consumer -> fork

Secondly, it is checked, if a pipes goes to a consumer, which does not exist.

Check 3

Checks if graph of network is connected.

An error is raised if one of these connection occurs.

get_results_edges()[source]

Postprocessing of the investment results of the pipes.

prepare_heat_demand()[source]

This method performs the pre-processing of the heat demand data, depending on the given optimisation settings.

  • If attribute ‘P_heat_max’ not given at the consumers, the maximum heat demand is calculated from the timeseries and added the consumers table.
  • If the optimisation setting ‘heat_demand’ == scalar, the number of time steps of the optimisation is set to 1, and the ‘P_heat_max’ values are copied to the consumers heat flow sequences (which is always the input for the optimisation model).
  • The consumers heat flow sequences are multiplied by the simultaneity factor.
  • Finally, a sufficient length of the heat demand timeseries is checked.
Returns:
  • Updated .network.components[‘consumers’] and
  • .network.sequences[‘consumers’][‘heat_flow’]
remove_inactive()[source]

If the attribute active is present in any of the components columns, or in any the investment options tables, all rows with active == 0 are deleted, and the column active is deleted.

setup()[source]

Calls remove_inactive() check_input(), prepare_heat_demand(), complete_exist_data(), and setup_oemof_es().

setup_oemof_es()[source]

The oemof solph energy system is initialised based on the settings, and filled with oemof-solph object:

The oemof-solph objects of the consumers and producers are defined at the consumers and producers investment options.

For the heating infrastructure, there is a oemof.solph.Bus added for every fork, and a pipe component for every pipe as defined in /network/pipes.csv.

solve()[source]

Builds the oemof.solph.Model of the energysystem es.

class dhnx.optimization.OemofOperationOptimizationModel(thermal_network)[source]

Bases: dhnx.model.OperationOptimizationModel

Implementation of an operation optimization model using oemof-solph.

get_results()[source]
setup()[source]
solve()[source]
dhnx.optimization.optimize_operation(thermal_network)[source]

Takes a thermal network and returns the result of the operational optimization.

dhnx.optimization.setup_optimise_investment(thermal_network, invest_options, heat_demand='scalar', num_ts=1, time_res=1, start_date='1/1/2018', frequence='H', solver='cbc', solve_kw=None, solver_cmdline_options=None, simultaneity=1, bidirectional_pipes=False, dump_path=None, dump_name='dump.oemof', print_logging_info=False, write_lp_file=False)[source]

Function for setting up the oemof solph operational Model.

Parameters:
  • thermal_network (ThermalNetwork) – See the ThermalNetwork class.
  • invest_options (dict) – Dictionary holding the investment options for the district heating system.
  • heat_demand (str) – ‘scalar’: Peak heat load is used as heat consumers’ heat demand. ‘series’: Heat load time-series is used.
  • num_ts (int) – Number of time steps of optimisation.
  • time_res (float) – Time resolution.
  • start_date (str or datetime-like) – Startdate for oemof optimisation.
  • frequence (str or DateOffset) – Lenght of period.
  • solver (str) – Name of solver.
  • solve_kw (dict) – Solver kwargs.
  • solver_cmdline_options (dict) – Dictionary with command line options for solver.
  • simultaneity (float) – Simultaneity factor.
  • bidirectional_pipes (bool) – Bidirectional pipes leads to bi-directional flow attributes at the heatpipeline components {‘min’: -1, bidirectional: True}.
  • dump_path (str) – If a dump path is provided, the oemof dump file is stored.
  • dump_name (str) – Name of dump file.
  • print_logging_info (bool) – Additional logging info is printed.
  • write_lp_file (bool) – Linear program file is stored (‘User/.oemof/lp_files/DHNx.lp’).
Returns:

oemof.solph.Model

Return type:

The oemof.solph.Model is build.

dhnx.optimization.solve_optimisation_investment(model)[source]
Parameters:model (oemof.solph.Model) – The oemof model, which is optimized.
Returns:dict
  • ‘oemof’ : Complete “oemof” results of the energy system optimisation (.results[‘main’]).
  • ’oemof_meta’ : Meta results of oemof solph optimisation.
  • ’components’ : ‘pipes’ : Investment results of pipes.
Return type:Results of optimisation. Contains:

simulation

This module is designed to hold implementations of simulation models. The implementation uses oemof/tespy.

This file is part of project dhnx (). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location:

SPDX-License-Identifier: MIT

class dhnx.simulation.SimulationModelNumpy(thermal_network, rho=971.78, c=4190, mu=0.00035, eta_pump=1, tolerance=1e-10)[source]

Bases: dhnx.model.SimulationModel

Implementation of a simulation model using numpy.

prepare()[source]
solve()[source]
get_results()[source]
prepare_hydraulic_eqn()[source]

Prepares the input data for the hydraulic problem.

prepare_thermal_eqn()[source]

Prepares the input data for the thermal problem.

solve_hydraulic_eqn()[source]

Solves the hydraulic problem.

solve_thermal_eqn()[source]

Solves the thermal problem.

_concat_scalars(name)[source]

Concatenates scalars of all components with a given variable name

Parameters:name (str) – Name of the variable
Returns:concat_sequences – DataFrame containing the sequences
Return type:pd.DataFrame
_concat_sequences(name)[source]

Concatenates sequences of all components with a given variable name

Parameters:name (str) – Name of the variable
Returns:concat_sequences – DataFrame containing the sequences
Return type:pd.DataFrame
static _set_producers_mass_flow(m)[source]

Sets the mass flow of the producer.

Parameters:m (pd.DataFrame) – DataFrame with all know consumer mass flows.
Returns:m – DataFrame with all know mass flow of consumers and producer.
Return type:pd.DataFrame
_calculate_pipes_mass_flow()[source]

Determines the mass flow in all pipes using numpy’s least squares function.

Returns:pipes_mass_flow – Mass flow in the pipes [kg/s]
Return type:pd.DataFrame
_calculate_reynolds()[source]

Calculates the Reynolds number.

Re = \frac{4\dot{m}}{\pi\mu D}

Returns:re – Reynolds number for every time step and pipe [-]
Return type:pd.DataFrame
_calculate_lambda(reynolds)[source]

Calculates the darcy friction factor.

\lambda = 0.07 \cdot Re ^ {-0.13} \cdot D ^ {-0.14}

Parameters:re (pd.DataFrame) – Reynolds number for every time step and pipe [-]
Returns:lamb – Darcy friction factor for every time step and pipe [-]
Return type:pd.DataFrame
_calculate_pipes_distributed_pressure_losses(lamb)[source]

Calculates the pressure losses in the pipes.

Equal-sized inlet and return pipes are assumed which leads to equal mass flows and pressure losses for both. This introduces the initial factor of 2 in the equation.

\delta p = 2 \cdot \lambda \frac{8L}{\rho \pi^2 D^5}\dot{m}^2.

Parameters:lamb (pd.DataFrame) – Darcy friction factor for every time step and pipe [-]
Returns:pipes_pressure_losses – DataFrame with distributed pressure losses for inlet and return for every time step and pipe [Pa]
Return type:pd.DataFrame
_calculate_pipes_localized_pressure_losses()[source]

Calculates localized pressure losses at the nodes.

\Delta p_{loc} = \frac{8\zeta\dot{m}^2}{\rho \pi^2 D^4}

Returns:nodes_pressure_losses – Localized pressure losses at the nodes [Pa]
Return type:pd.DataFrame
_calculate_global_pressure_losses(pipes_pressure_losses)[source]

Calculates global pressure losses.

Finds the path with the maximal pressure loss among from the set of paths from the producer to all consumers.

Parameters:pipes_pressure_losses (pd.DataFrame) – Total pressure losses for every time step and pipe [Pa]
Returns:global_pressure_losses – Global pressure losses [Pa]
Return type:pd.DataFrame
_calculate_pump_power(global_pressure_losses)[source]

Calculates the pump power.

P_{el. pump} = \frac{1}{\eta_{el}\eta_{hyd}}\frac{\Delta p }{\rho} \dot{m}

Parameters:global_pressure_losses (pd.DataFrame) – Global pressure losses [Pa]
Returns:pump_power – Pump power [W]
Return type:pd.Series
_calculate_exponent_constant()[source]

Calculates the constant part of the exponent that determines the cooling of the medium in the pipes.

exp_{const} = - \frac{U \pi D L }{c}

Returns:exponent_constant – Constant part of the exponent [kg/s]
Return type:np.matrix
_calc_temps(exponent_constant, known_temp, direction)[source]

Calculate temperatures

T_{out} = T_{env} + (T_{in} - T_{env}) \cdot exp\{exp_{const} \cdot exp_{var}\} =
T_{out} = T_{env} + (T_{in} - T_{env}) \cdot exp\{-\frac{U \pi D L}{c \cdot \dot{m}}\}

Parameters:
  • exponent_constant (np.array) – Constant part of the exponent [kg/s]
  • known_temp (pd.DataFrame) – Known temperatures at producers or consumers [°C]
  • direction (+1 or -1) – For inlet and return flow [-]
Returns:

temp_df – DataFrame containing temperatures for all nodes [°C]

Return type:

pd.DataFrame

_set_temp_return_input(temp_inlet)[source]

Sets the temperature of the return pipes at the consumers.

T_{cons,r} = T_{cons,i} - T_{cons,drop}

Parameters:temp_inlet (pd.DataFrame) – Known inlet temperature [°C]
Returns:temp_return – Return temperature with the consumers values set [°C]
Return type:pd.DataFrame
_calculate_pipes_heat_losses(temp_node)[source]

Calculates the pipes’ heat losses given the temperatures.

\dot{Q}_{losses} = c \cdot \dot{m} \cdot \Delta T

Parameters:temp_node (pd.DataFrame) – Temperatures at the nodes [°C]
Returns:pipes_heat_losses – Heat losses in the pipes [W]
Return type:pd.DataFrame
dhnx.simulation.simulate(thermal_network, results_dir=None)[source]

Takes a thermal network and returns the result of the simulation.

Parameters:thermal_network
Returns:results
Return type:dict