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:
SPDXLicenseIdentifier: 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() >>> 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

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.

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
gistools¶
dhnx.gistools.geometry_operations¶
This modules holds functions for geometry operations, that are needed for the geometry processing module connect_points.py.
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.
SPDXLicenseIdentifier: MIT

dhnx.gistools.geometry_operations.
any_check
(geom_test, gdf, how)[source]¶ Improve speed for an ‘any()’ test on a list comprehension.
Replace a statement like…
if any([geom_test.touches(g) for g in gdf.geometry]):
… with the following:
if any_check(geom_test, gdf, how='touches'):
Instead of iterating through all of ‘g in gdf.geometry’, return ‘True’ after the first match.
Parameters:  geom_test (Shapely object) – Object which’s function ‘how’ is called.
 gdf (GeoDataFrame) – All geometries in gdf are passed to ‘how’.
 how (str) – Shapely object function like equals, almost_equals, contains, crosses, disjoint, intersects, touches, within.
Returns: bool – True if any call of function ‘how’ is True.

dhnx.gistools.geometry_operations.
check_crs
(gdf, crs=4647)[source]¶ Convert CRS to EPSG:4647  ETRS89 / UTM zone 32N (zEN).
This is the (only?) Coordinate Reference System that gives the correct results for distance calculations.

dhnx.gistools.geometry_operations.
check_double_points
(gdf, radius=0.001, id_column=None)[source]¶ Check for points, which are close to each other.
In case, two points are close, the index of the points are printed.
Parameters:  gdf (geopandas.GeoDataFrame) – GeoDataFrame with Points as geometry.
 radius (float) – Maximum distance.
 id_column (str or None) – Column name which should be printed in case of near points. If None, the index is printed.
Returns: list (Indices of “near” points.)

dhnx.gistools.geometry_operations.
create_forks
(lines)[source]¶ Creates a forks(nodes) GeoDataFrame from a “line”GeoDataFrame based on the endpoints of each LineString.
Also, an index for every fork is given, and the columns ‘fullid’ (=”forks” + index”), ‘lat’ and ‘lon’, which results from the geometry, are added to the GeoDataFrame.
Parameters: lines (geopandas.GeoDataFrame) Returns: geopandas.GeoDataFrame (GeoDataFrame with Points as geometry.)

dhnx.gistools.geometry_operations.
gdf_to_df
(gdf)[source]¶ Converts a GeoDataFrame to a pandas.DataFrame by deleting the geometry column.

dhnx.gistools.geometry_operations.
insert_node_ids
(lines, nodes)[source]¶ Creates the columns from_node, to_node and inserts the node ids (eg. forks3, consumers5). The updated “line”GeoDataFrame is returned.
Parameters:  lines (geopandas.GeoDataFrame)
 nodes (geopandas.GeoDataFrame)
Returns: geopandas.GeoDataFrame

dhnx.gistools.geometry_operations.
split_multilinestr_to_linestr
(gdf_input)[source]¶ Simplifies GeoDataFrames with LineStrings as geometry.
The LineStrings (whether LineStrings, or MulitLineStings) are split into LineStrings with only two coordinates, one starting and one ending point.
The other values of the GeoDataFrame are copied to the new rows for each row, who’s geometry is split.
Parameters: gdf_lines (geopandas.GeoDataFrame) Returns: geopandas.GeoDataFrame

dhnx.gistools.geometry_operations.
weld_segments
(gdf_line_net, gdf_line_gen, gdf_line_houses, debug_plotting=False)[source]¶ Weld continuous line segments together and cut loose ends.
This is a public function that recursively calls the internal function weld_line_segments_(), until the problem cannot be simplified further.
Find all lines that only connect to one other line and connect those to a single MultiLine object. Points that connect to Generators and Houses are not simplified. Loose ends are shortened where possible.
Parameters:  gdf_line_net (GeoDataFrame) – Potential pipe network.
 gdf_line_gen (GeoDataFrame) – Generators that need to be connected.
 gdf_line_houses (GeoDataFrame) – Houses that need to be connected.
 debug_plotting (bool, optional) – Plot the selection process.
Returns: gdf_line_net_new (GeoDataFrame) – Simplified potential pipe network.
dhnx.gistools.connect_points¶
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.
SPDXLicenseIdentifier: 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: shapely.geometry.Point

dhnx.gistools.connect_points.
check_duplicate_geometries
(gdf)[source]¶ Test the input GeoDataFrame for duplicate geometries and plot them.

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 linenetwork 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 (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 1e8.
Parameters:  point (shapely.geometry.Point)
 gdf_lines (geopandas.GeoDataFrame)
Returns: int, float or str (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: numpy.array()

dhnx.gistools.connect_points.
process_geometry
(lines, consumers, producers, method='midpoint', projected_crs=4647, tol_distance=2, reset_index=True)[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. Method ‘midpoint’ uses the centroid of each building polygon. Method ‘boundary’ moves the point to the boundary (wall) of the building, along the line constructed from centroid to the street.
 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.
 reset_index (bool) – If True, reset the index and ignore the existing index. If False, use the existing index for consumer and producer identificators. Default: True
Returns: dict (Dictionary with 4 geopandas.GeoDataFrames: The keys of the Dict are) – equal to the components of the dhnx.ThermalNetwork: ‘forks’, ‘consumers’, ‘producers’, ‘pipes’.

dhnx.gistools.connect_points.
run_point_method_boundary
(consumers_poly, consumers, producers_poly, producers, lines_consumers, lines_producers)[source]¶ Run ‘boundary’ method for finding the building connection point.
The ‘midpoint’ method (using the centroid) must already have been run, generating the default connection lines from street to centroid.
If there is only one intersection between that line and the boundary of the building, this intersection point is used as the connection point instead (and the connection line is shortened accordingly).
However, complex building shapes can produce multiple intersections. In this case, the intersection with the ‘convex hull’ of the building is used instead. This may result in connection points that do not touch an actual building wall, but it should still be an improvement compared to the ‘midpoint’ method.
In case of no intersections with the building boundary (possible for e.g. Ushaped buildings), the original centroid is used.
Parameters:  consumers_poly (geopandas.GeoDataFrame) – Polygons of the consumer buildings. Point geometries are also allowed, but they are not changed.
 consumers (geopandas.GeoDataFrame) – Points of the consumer buildings (as returned by ‘midpoint’ method).
 producers_poly (geopandas.GeoDataFrame) – Polygons of the producer buildings. Point geometries are also allowed, but they are not changed.
 producers (geopandas.GeoDataFrame) – Points of the producer buildings (as returned by ‘midpoint’ method).
 lines_consumers (geopandas.GeoDataFrame) – Connection lines from street to each consumer point.
 lines_producers (geopandas.GeoDataFrame) – Connection lines from street to each producer point.
Returns:  consumers (geopandas.GeoDataFrame) – Updated points of the consumer buildings.
 producers (geopandas.GeoDataFrame) – Updated points of the producer buildings.
 lines_consumers (geopandas.GeoDataFrame) – Updated connection lines from street to each consumer point.
 lines_producers (geopandas.GeoDataFrame) – Updated connection lines from street to each producer point.
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:
SPDXLicenseIdentifier: MIT

class
dhnx.model.
InvestOptimizationModel
(thermal_network)[source]¶ Bases:
dhnx.model.Model
Abstract base class for investment optimization models.

class
dhnx.model.
Model
(thermal_network)[source]¶ Bases:
object
Abstract base class for different kind of models.

class
dhnx.model.
OperationOptimizationModel
(thermal_network)[source]¶ Bases:
dhnx.model.Model
Abstract base class for operational optimization models.

class
dhnx.model.
SimulationModel
(thermal_network)[source]¶ Bases:
dhnx.model.Model
Abstract base class for simulation models.
optimization¶
dhnx.optimization.optimization_models¶
This module is designed to hold optimization model implementations. The implementation makes use of oemofsolph.
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:
SPDXLicenseIdentifier: MIT

class
dhnx.optimization.optimization_models.
OemofInvestOptimizationModel
(thermal_network, settings, investment_options)[source]¶ Bases:
dhnx.model.InvestOptimizationModel
Implementation of an invest optimization model using oemofsolph.
…
Variables:  settings (dict) – Dictionary holding the optimisation settings. See .
 invest_options (dict) – Dictionary holding the investment options for the district heating system.
 nodes (list) – Empty list for collecting all oemof.solph nodes.
 buses (dict) – Empty dictionary for collecting all oemof.solph.Buses of the energy system.
 es (oemof.solph.EnergySystem) – Empty oemof.solph.EnergySystem.
 om (oemof.solph.Model) – Attribute, which will be the oemof.solph.Model for optimisation.
 oemof_flow_attr (set) – Possible flow attributes, which can be used additionally: {‘nominal_value’, ‘min’, ‘max’, ‘variable_costs’, ‘fix’}
 results (dict) – Empty dictionary for the results.

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 notallowed 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.

prepare_heat_demand
()[source]¶ This method performs the preprocessing 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 oemofsolph object:
The oemofsolph 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.

class
dhnx.optimization.optimization_models.
OemofOperationOptimizationModel
(thermal_network)[source]¶ Bases:
dhnx.model.OperationOptimizationModel
Implementation of an operation optimization model using oemofsolph.

dhnx.optimization.optimization_models.
optimize_operation
(thermal_network)[source]¶ Takes a thermal network and returns the result of the operational optimization.

dhnx.optimization.optimization_models.
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 timeseries is used.
 num_ts (int) – Number of time steps of optimisation.
 time_res (float) – Time resolution.
 start_date (str or datetimelike) – 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 bidirectional 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 (The oemof.solph.Model is build.)

dhnx.optimization.optimization_models.
solve_optimisation_investment
(model)[source]¶ Parameters: model (oemof.solph.Model) – The oemof model, which is optimized. Returns: dict (Results of optimisation. Contains:) –  ‘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.
dhnx.optimization.dhs_nodes¶
This module is designed to hold optimization model implementations. The implementation makes use of oemofsolph.
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:
SPDXLicenseIdentifier: MIT

dhnx.optimization.dhs_nodes.
add_nodes_dhs
(opti_network, gd, nodes, busd)[source]¶ Based on the forks and pipes of the ThermalNetwork of the OemofInvestOptimisationModel, the oemofsolph components for the district heating network optimisation are initialised.
For all forks, a solph.Bus with the label infrastructure_heat_bus_forks<id> (string representation) is generated.
For all pipes, a ‘HeatPipeline’ with the label infrastructure_heat_<type>_<from_node><to_node> (string representation) is generated. Depending on the attributes in pipes, an investment pipe, or an existing pipe is built.
Parameters:  opti_network (OemofInvestOptimisationModel)
 gd (dict) – General optimisation settings.
 nodes (list) – List for collecting all oemofsolph objects.
 busd (dict) – Dictionary collecting all oemofsolph Buses. Keys: labels of the oemofsolph Buses; Values: oemofsolph Buses.
Returns: list, dict (List of all oemofsolph objects and dictionary of oemofsolph Buses.)

dhnx.optimization.dhs_nodes.
add_nodes_houses
(opti_network, nodes, busd, label_1)[source]¶ For each consumers/producers of the ThermalNetwork of the OemofInvestOptimisationModel, the oemofsolph components for the consumers/producers are initialised depending on the given tables of the
invest_options
of the OemofInvestOptimisationModel.The tables of invest_options provide the information and attributes for the oemofsolph components, which should be build at every consumer/producer.
The minimum requirement is to provide table with at least one heat Bus for all consumers and all producers, a table with a heat sink as demand for all consumers, and a table with at least one heat source for all producers.
Additionally, further tables with Transformer, Storages, and further Sources and Sinks can be added.
For the attributes for each table, you need to provide, please see:
Parameters:  opti_network (OemofInvestOptimisationModel)
 gd (dict) – General optimisation settings.
 nodes (list) – List for collecting all oemofsolph objects.
 busd (dict) – Dictionary collecting all oemofsolph Buses. Keys: labels of the oemofsolph Buses; Values: oemofsolph Buses.
 label_1 (str) – First tag of the label, which is either producers or consumers.
Returns: list, dict (List of all oemofsolph objects and dictionary of oemofsolph Buses.)
dhnx.optimization.add_components¶
This module is designed to hold optimization model implementations. The implementation makes use of oemofsolph.
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:
SPDXLicenseIdentifier: MIT

dhnx.optimization.add_components.
add_buses
(it, labels, nodes, busd)[source]¶ This function initialises the oemof.solph.Bus classes of the energysystem based on the given tabular information. Additionally, a sink or a source can be added to every bus and costs for this source (shortage) or sink (excess) can be defined.
The table must be given as follows:
¶ label_2 active excess shortage shortage costs excess costs heat 1 0 0 99999 99999 Parameters:  it (pd.DateFrame) – Table of attributes for Buses for the producers and consumers.
 labels (dict) – Dictonary containing tag1 and tag4 of labeltuple.
 nodes (list) – All oemof.solph components are added to the list.
 busd (dict) – All buses are added to this dictionary.
Returns: list, dict (Updated list of nodes and dict of Buses.)

dhnx.optimization.add_components.
add_demand
(it, labels, series, nodes, busd)[source]¶ Initialisation of oemof.solph.Sinks which represent demands.
Parameters:  it (pd.DataFrame) – Table of attributes for Sources for the producers and consumers.
 labels (dict) – Dictonary containing specifications for labeltuple.
 series (dict) – Contain the heat demand timeseries of all consumers.
 nodes (list) – All oemof.solph components are added to the list.
 busd (dict) – All oemof.solph.Bus objects are given by this dictionary.
Returns: list (Updated list of nodes.)

dhnx.optimization.add_components.
add_heatpipes
(it, labels, bidirectional, length, b_in, b_out, nodes)[source]¶ Adds HeatPipeline objects with Investment attribute to the list of oemof.solph components.
Parameters:  it (pd.DataFrame) – Table of Heatpipeline attributes of the district heating grid
 labels (dict) – Dictonary containing specifications for labeltuple
 bidirectional (bool) – Settings for creating bidirectional heatpipelines
 length (float) – Length of pipeline
 b_in (oemof.solph.Bus) – Bus of Inflow
 b_out (oemof.solph.Bus) – Bus of Outflow
 nodes (list) – All oemof.solph components are added to the list
Returns: list (Updated list of nodes.)

dhnx.optimization.add_components.
add_heatpipes_exist
(pipes, labels, gd, q, b_in, b_out, nodes)[source]¶ Adds HeatPipeline objects with fix capacity for existing pipes to the list of oemof.solph components.
Parameters:  pipes
 labels (dict) – Dictonary containing specifications for labeltuple.
 gd (dict) – Settings of the investment optimisation of the ThermalNetwork
 q (pd.Series) – Specific Pipe of ThermalNetwork
 b_in (oemof.solph.Bus) – Bus of Inflow
 b_out (oemof.solph.Bus) – Bus of Outflow
 nodes (list) – All oemof.solph components are added to the list
Returns: list (Updated list of nodes.)

dhnx.optimization.add_components.
add_sources
(on, it, c, labels, nodes, busd)[source]¶ The oemof.solph.Source components for the producers and consumers are initialised based on the given tabular information of the investment_options of the OemofInvestOptimizationModel. Timeseries can also be used as attribute values for the outflow of the Source. Therefore, a table with the filename ‘source_timeseries’ must be given.
Parameters:  on (OemofInvestOptimizationModel)
 it (DataFrame) – Table of attributes for Sources for the producers and consumers.
 c (Series) – Attributes of specific producer or consumer from the ThermalNetwork.
 labels (dict) – Dictonary containing specifications for labeltuple.
 nodes (list) – All oemof.solph components are added to the list.
 busd (dict) – All oemof.solph.Bus objects are given by this dictionary.
Returns: list (Updated list of nodes.)

dhnx.optimization.add_components.
add_storage
(it, labels, nodes, busd)[source]¶ Adds oemof.solph.GenericStorage objects to the list of components.
If attribute invest is True, the investment version of the Storage is created.
Parameters:  it (pd.DataFrame) – Table of storage attributes of the producers / consumers.
 labels (dict) – Dictonary containing specifications for labeltuple.
 nodes (list) – All oemof.solph components are added to the list.
 busd (dict) – All oemof.solph.Bus objects are given by this dictionary.
Returns: list (Updated list of nodes.)

dhnx.optimization.add_components.
add_transformer
(it, labels, nodes, busd)[source]¶ Adds oemof.solph.Transformer objects to the list of components.
If attribute invest is True, an Investment attribute is added to the outflow of the Transformer.
Parameters:  it (pd.DataFrame) – Table of transformer attributes of the producers / consumers.
 labels (dict) – Dictonary containing specifications for labeltuple.
 nodes (list) – All oemof.solph components are added to the list.
 busd (dict) – All oemof.solph.Bus objects are given by this dictionary.
Returns: list (Updated list of nodes.)
dhnx.optimization.oemof_heatpipe¶
This module is designed to hold optimization model implementations. The implementation makes use of oemofsolph.
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:
SPDXLicenseIdentifier: MIT

class
dhnx.optimization.oemof_heatpipe.
HeatPipeline
(*args, **kwargs)[source]¶ Bases:
oemof.solph.network.transformer.Transformer
A HeatPipeline represent a Pipeline in a district heating system. This is done by a Transformer with a constant energy loss independent of actual power, but dependent on the nominal power and the length parameter. The HeatPipeline is a singleinputsingleoutput transformer. Additionally, conversion factors for in and output flow can be applied.
Parameters:  length (float) – Length of HeatPipeline.
 heat_loss_factor (float) – Heat loss per length unit as fraction of the nominal power. Can also be defined by a series.
Note
This component is experimental. Use it with care. See also
Transformer
. The following sets, variables, constraints and objective parts are created
HeatPipelineBlock
(if no Investment object present)HeatPipelineInvestBlock
(if Investment object present)
Examples
# TODO : example

class
dhnx.optimization.oemof_heatpipe.
HeatPipelineBlock
(*args, **kwargs)[source]¶ Bases:
pyomo.core.base.block.SimpleBlock
Block representing a pipeline of a district heating system.
HeatPipeline
The following constraints are created:
# TODO : Check and fix equations!
The symbols used are defined as follows (with Variables (V) and Parameters (P)):
symbol attribute type explanation flow[n, o, t]
V Heat output flow[i, n, t]
V Heat input heat_loss[n, t]
P Heat loss of heat pipeline flows[n, o].nominal_value
P Nominal capacity of heating pipeline conversion_factors[o][t]
P Conversion factor of output flow (Heat Output) conversion_factors[i][t]
P Conversion factor of input flow (Heat Input) heat_loss_factor
P Specific heat loss factor for pipeline length
P Length of heating pipeline 
CONSTRAINT_GROUP
= True¶


class
dhnx.optimization.oemof_heatpipe.
HeatPipelineInvestBlock
(*args, **kwargs)[source]¶ Bases:
pyomo.core.base.block.SimpleBlock
Block representing a pipeline of a district heating system.
HeatPipeline
The following constraints are created:
# TODO : Check and fix equations!
The symbols used are defined as follows (with Variables (V) and Parameters (P)):
symbol attribute type explanation flow[n, o, t]
V Heat output flow[i, n, t]
V Heat input heat_loss[n, t]
V Heat loss of heat pipeline flows[n, o].nominal_value
V Nominal capacity of heating pipeline conversion_factors[o][t]
P Conversion factor of output flow (heat output) conversion_factors[i][t]
P Conversion factor of input flow (heat input) heat_loss_factor
P Specific heat loss factor for pipeline length
P Length of heating pipeline 
CONSTRAINT_GROUP
= True¶

dhnx.optimization.precalc_hydraulic¶
This module is designed to hold functions for precalculation of hydraulic parameters for the district heating network dimensioning.
The aim is to calculate the maximum heat transport capacity of pipelines given a maximum pressure drop per meter, roughness of the pipes inner surface, and an estimated delta T of the forward and return pipes.
The equations and values used for the calculation can be found here: http://www.mathtech.at/Beispiele/upload/gra_Druckverlust_in_Rohrleitungen.PDF https://www.schweizerfn.de/stroemung/rauhigkeit/rauhigkeit.php
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:
SPDXLicenseIdentifier: MIT

dhnx.optimization.precalc_hydraulic.
calc_Re
(v, d_i, k_v)[source]¶ Calculates the Reynolds number for a given velocity, inner diameter and kinematic viscosity
Parameters:  v (numeric) – : flow velocity [m/s]
 d_i (numeric) – : inner pipe diameter [m]
 k_v (numeric) – : kinematic viscosity [m²/s]
Returns: Reynolds number [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_d_p
(lam, length, d_i, d, v)[source]¶ Calculates the pressure drop in a pipe for a given Darcy friction factor
Parameters:  lam (numeric) – : Darcy friction factor []
 length (numeric) – : length of the pipe [m]
 d_i (numeric) – : inner pipe diameter [m]
 d (numeric) – : density [kg/m³]
 v (numeric) – : flow velocity [m/s]
Returns: Pressure drop [Pa] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_k_v
(d_v, d)[source]¶ Calcutlates the kinematic viscosity for given density and dynamic viscosity
Parameters:  d_v (numeric) – : dynamic viskosity [kg/(m*s)]
 d (numeric) – : density [kg/m³]
Returns: kinematic viscosity [m²/s] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_laminar
(Re)[source]¶ Calculates the Darcy friction factor for a given Reynolds number for a laminar flow
Parameters: Re (numeric) – : Reynolds number [] Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_rough
(d_i, k)[source]¶ Calculates the Darcy friction factor for a turbulent flow and a rough inner pipe surface (Prandtl & Nikuradse)
Parameters:  d_i (numeric) – : inner pipe diameter [m]
 k (numeric) – : roughness of inner pipeline surface [mm]
Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_transition
(R_e, k, d_i)[source]¶ Calculates the Darcy friction factor for a given Reynolds number for a turbulent flow and the transition area between a rough and smooth pipe surface.
See also
eq_transition()
.Parameters:  R_e (numeric) – : Reynolds number []
 k (numeric) – : roughness of inner pipeline surface [mm]
 d_i (numeric) – : inner pipe diameter [m]
Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_turb1
(Re)[source]¶ Calculates the Darcy friction factor for a given Reynolds number for a turbulent flow, a smooth pipe and a Reynolds number smaller than 10^5 (Blasius)
Parameters: Re (numeric) – : Reynolds number [] Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_turb2
(Re)[source]¶ Calculates the Darcy friction factor for a given Reynolds number for a turbulent flow, a smooth pipe and a Reynolds number between 10^5 and 10^6 (Nikuradse)
Parameters: Re (numeric) – : Reynolds number [] Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_lambda_turb3
(Re)[source]¶ Calculates the Darcy friction factor for a given Reynolds number for a turbulent flow, a smooth pipe and a Reynolds number higher than 10^6. For a formula, see
eq_smooth()
.Parameters: Re (numeric) – : Reynolds number [] Returns: Darcy friction factor [] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_mass_flow
(v, di, T_av, p=101325)[source]¶ Calculates the mass flow in a pipe for a given density, diameter and flow velocity. The average temperature is needed for a correct value of the density.
Parameters:  v (numeric) – : flow velocity [m/s]
 di (numeric) – : inner diameter [m]
 T_av (numeric) – : temperature level [°C]
 p (numeric) – : pressure [Pa]
Returns: mass flow [kg/s] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_mass_flow_P
(P, T_av, delta_T, p=101325)[source]¶ Calculates the mass flow in a pipe for a given power and heat difference. The average temperature is needed for a correct value of the heat capacity.
Parameters:  P (numeric) – : power [W]
 T_av (numeric) – : average temperature [°C]
 delta_T (numeric) – : temperature difference [K]
 p (numeric) – : pressure [Pa]
Returns: mass flow [kg/s] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_pipe_loss
(temp_average, u_value, temp_ground=10)[source]¶ Calculates the heat loss of a DHS pipe trench.
Temperatures must be given in the same unit, K or °C.
Parameters:  temp_average (float) – : Average temperature of medium in (if u_value relates to forward and return pipe, the average temperature of forward and return must be given.)
 u_value (float) – : Heat transmission coefficient of whole trench in W/(m*K) (u_value of forward and return pipe must be summed up, if total heat loss should be calculated.)
 temp_ground (float) – : Temperature of surrounding, e.g. ground.
Returns: Heat loss of pipe trench [W/m] (float)

dhnx.optimization.precalc_hydraulic.
calc_power
(T_vl=80, T_rl=50, mf=3, p=101325)[source]¶ Function to calculate the thermal power based on mass flow and temperature difference.
Parameters:  T_vl (numeric) – : forward temperature [°C]
 T_rl (numeric) – : return temperature [C°]
 mf (numeric) – : mass flow [kg/s]
 p (numeric) – : pressure [Pa]
Returns: thermal power [W] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_v
(vol_flow, d_i)[source]¶ Calculates the velocity for a given volume flow and inner diameter of a pipe.
Parameters:  vol_flow (numeric) – : volume flow [m³/h]
 d_i (numeric) – : inner diameter [m]
Returns: flow velocity [m/s] (numeric)

dhnx.optimization.precalc_hydraulic.
calc_v_mf
(mf, di, T_av, p=101325)[source]¶ Calculates the flow velocity for a given mass flow and inner diameter. The average temperature is needed for a correct value of the density.
Parameters: mf (numeric) – : mass flow [kg/s]
di (numeric) – : inner diameter [m]
T_av (numeric) – : average temperature [°C]
 p: numeric
: pressure [Pa]
Returns: flow velocity [m/s] (numeric)

dhnx.optimization.precalc_hydraulic.
delta_p
(v, d_i, k=0.1, T_medium=90, length=1, pressure=101325, R_crit=2320, fluid='IF97::Water')[source]¶ Function to calculate the pressure loss in a pipeline
Parameters:  v (numeric) – : flow velocity [m/s]
 d_i (numeric) – : inner pipe diameter [m]
 k (numeric) – : roughness of inner pipeline surface [mm]
 T_medium (numeric) – : fluid temperature [°C]
 length (numeric) – : length of the pipe [m]
 pressure (numeric) – : pressure in the pipe [Pa]
 R_crit (numeric) – : critical Reynolds number between laminar and turbulent flow []
 fluid (str) – name of the fluid used
Returns: Pressure drop [bar] (numeric)

dhnx.optimization.precalc_hydraulic.
eq_smooth
(x, R_e)[source]¶ Calculation of the pressure drop of hydraulic smooth surfaces. (Prandtl & Karman)
Parameters:  x (numeric) – : function variable []
 R_e (numeric) – : Reynolds number []
Returns: Equation (numeric)

dhnx.optimization.precalc_hydraulic.
eq_transition
(x, R_e, k, d_i)[source]¶ Equation to be solved for the transition range between a smooth and rough pipe surface (PrandtlColebrook)
Parameters:  x (numeric) – : function variable () []
 R_e (numeric) – : Reynolds number []
 k (numeric) – : roughness of inner pipeline surface [mm]
 d_i (numeric) – : inner diameter [m]
Returns: Equation (numeric)

dhnx.optimization.precalc_hydraulic.
v_max_bisection
(d_i, T_average, k=0.1, p_max=100, p_epsilon=0.1, v_epsilon=0.001, v_0=0.01, v_1=10, pressure=101325, fluid='IF97::Water')[source]¶ Calculates the maximum velocity via bisection for a given pressure drop.
The two starting values v_0 and v_1 need to be given, with v_0 below the expected flow velocity and v_1 above. These are the starting values for the bisection method.
If either of the stopcriteria p_epsilon or v_epsilon is reached, the iterative calculation is stopped.
Parameters:  d_i (numeric) – : inner diameter [m]
 T_average (numeric) – : average temperature [°C]
 k (numeric) – : roughness of inner pipeline surface [mm]
 p_max (numeric) – : maximum pressure drop in pipeline [Pa]
 p_epsilon (numeric) – : accuracy of pressure [Pa]
 v_epsilon (numeric) – : accuracy of velocity [m/s]
 v_0 (numeric) – : first value of initial guess for maximum flow velocity [m/s]
 v_1 (numeric) – : second value of initial guess for maximum flow velocity [m/s]
 pressure (numeric) – : pressure level [Pa]
 fluid (str) – type of fluid, default: ‘IF97::Water’
Returns: maximum flow velocity [m/s] (numeric)

dhnx.optimization.precalc_hydraulic.
v_max_secant
(d_i, T_average, k=0.1, p_max=100, p_epsilon=1, v_0=1, v_1=2, pressure=101325, fluid='IF97::Water')[source]¶ Calculates the maximum velocity via iterative approach using the secant method.
The two different starting values v_0 and v_1 should be in the area of the maximum flow velocity, as iteration starts from there.
Parameters:  d_i (numeric) – : inner diameter [m]
 T_average (numeric) – : average temperature [°C]
 k (numeric) – : roughness of inner pipeline surface [mm]
 p_max (numeric) – : maximum pressure drop in pipeline [Pa]
 p_epsilon (numeric) – : accuracy of pressure [Pa]
 v_0 (numeric) – : first value of initial guess for maximum flow velocity [m/s]
 v_1 (numeric) – : second value of initial guess for maximum flow velocity [m/s]
 pressure (numeric) – : pressure level [pa]
 fluid (str) – type of fluid, default: ‘IF97::Water’
Returns: maximum flow velocity [m/s] (numeric)
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:
SPDXLicenseIdentifier: MIT

class
dhnx.simulation.
SimulationModelNumpy
(thermal_network, rho=971.78, c=4190, mu=0.00035, eta_pump=1, tolerance=1e10)[source]¶ Bases:
dhnx.model.SimulationModel
Implementation of a simulation model using numpy.

_concat_scalars
(name)[source]¶ Concatenates scalars of all components with a given variable name
Parameters: name (str) – Name of the variable Returns: concat_sequences (pd.DataFrame) – DataFrame containing the sequences

_concat_sequences
(name)[source]¶ Concatenates sequences of all components with a given variable name
Parameters: name (str) – Name of the variable Returns: concat_sequences (pd.DataFrame) – DataFrame containing the sequences

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 (pd.DataFrame) – DataFrame with all know mass flow of consumers and producer.

_calculate_pipes_mass_flow
()[source]¶ Determines the mass flow in all pipes using numpy’s least squares function.
Returns: pipes_mass_flow (pd.DataFrame) – Mass flow in the pipes [kg/s]

_calculate_reynolds
()[source]¶ Calculates the Reynolds number.
Returns: re (pd.DataFrame) – Reynolds number for every time step and pipe []

_calculate_lambda
(reynolds)[source]¶ Calculates the darcy friction factor.
Parameters: re (pd.DataFrame) – Reynolds number for every time step and pipe [] Returns: lamb (pd.DataFrame) – Darcy friction factor for every time step and pipe []

_calculate_pipes_distributed_pressure_losses
(lamb)[source]¶ Calculates the pressure losses in the pipes.
Equalsized 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.
Parameters: lamb (pd.DataFrame) – Darcy friction factor for every time step and pipe [] Returns: pipes_pressure_losses (pd.DataFrame) – DataFrame with distributed pressure losses for inlet and return for every time step and pipe [Pa]

_calculate_pipes_localized_pressure_losses
()[source]¶ Calculates localized pressure losses at the nodes.
Returns: nodes_pressure_losses (pd.DataFrame) – Localized pressure losses at the nodes [Pa]

_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 (pd.DataFrame) – Global pressure losses [Pa]

_calculate_pump_power
(global_pressure_losses)[source]¶ Calculates the pump power.
Parameters: global_pressure_losses (pd.DataFrame) – Global pressure losses [Pa] Returns: pump_power (pd.Series) – Pump power [W]

_calculate_exponent_constant
()[source]¶ Calculates the constant part of the exponent that determines the cooling of the medium in the pipes.
Returns: exponent_constant (np.matrix) – Constant part of the exponent [kg/s]

_calc_temps
(exponent_constant, known_temp, direction)[source]¶ Calculate temperatures
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 (pd.DataFrame) – DataFrame containing temperatures for all nodes [°C]
