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

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.

SPDX-License-Identifier: 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 (zE-N).

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 end-points of each LineString.

Also, an index for every fork is given, and the columns ‘full-id’ (=”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. forks-3, consumers-5). 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.

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:

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 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 (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 (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. U-shaped 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:

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

dhnx.optimization.optimization_models

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.optimization_models.OemofInvestOptimizationModel(thermal_network, settings, investment_options)[source]

Bases: dhnx.model.InvestOptimizationModel

Implementation of an invest optimization model using oemof-solph.

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 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.optimization_models.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.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 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 (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 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

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 oemof-solph 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 oemof-solph objects.
  • busd (dict) – Dictionary collecting all oemof-solph Buses. Keys: labels of the oemof-solph Buses; Values: oemof-solph Buses.
Returns:

list, dict (List of all oemof-solph objects and dictionary of oemof-solph 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 oemof-solph 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 oemof-solph 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 oemof-solph objects.
  • busd (dict) – Dictionary collecting all oemof-solph Buses. Keys: labels of the oemof-solph Buses; Values: oemof-solph Buses.
  • label_1 (str) – First tag of the label, which is either producers or consumers.
Returns:

list, dict (List of all oemof-solph objects and dictionary of oemof-solph Buses.)

dhnx.optimization.add_components

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

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:

Example for table of Buses
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 label-tuple.
  • 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 label-tuple.
  • series (dict) – Contain the heat demand time-series 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 label-tuple
  • 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 label-tuple.
  • 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. Time-series 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 label-tuple.
  • 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 label-tuple.
  • 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 label-tuple.
  • 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 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.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 single-input-single-output 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

Examples

# TODO : example

constraint_group()[source]
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!

\dot{Q}_{out}(t) = \dot{Q}_{in}(t) \cdot
\frac{\eta_{out}}{\eta_{in}} - \dot{Q}_{loss}(t)

\dot{Q}_{loss}(t) = f_{loss}(t) \cdot l \cdot \dot{Q}_{nominal}

The symbols used are defined as follows (with Variables (V) and Parameters (P)):

symbol attribute type explanation
\dot{Q}_{out}(t) flow[n, o, t] V Heat output
\dot{Q}_{in}(t) flow[i, n, t] V Heat input
\dot{Q}_{loss}(t) heat_loss[n, t] P Heat loss of heat pipeline
\dot{Q}_{nominal} flows[n, o].nominal_value P Nominal capacity of heating pipeline
\eta_{out} conversion_factors[o][t] P Conversion factor of output flow (Heat Output)
\eta_{in} conversion_factors[i][t] P Conversion factor of input flow (Heat Input)
f_{loss}(t) heat_loss_factor P Specific heat loss factor for pipeline
l 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!

\dot{Q}_{out}(t) = \dot{Q}_{in}(t) \cdot
\frac{\eta_{out}}{\eta_{in}} - \dot{Q}_{loss}(t)

\dot{Q}_{loss}(t) = f_{loss}(t) \cdot l \cdot \dot{Q}_{nominal}

The symbols used are defined as follows (with Variables (V) and Parameters (P)):

symbol attribute type explanation
\dot{Q}_{out}(t) flow[n, o, t] V Heat output
\dot{Q}_{in}(t) flow[i, n, t] V Heat input
\dot{Q}_{loss}(t) heat_loss[n, t] V Heat loss of heat pipeline
\dot{Q}_{nominal} flows[n, o].nominal_value V Nominal capacity of heating pipeline
\eta_{out} conversion_factors[o][t] P Conversion factor of output flow (heat output)
\eta_{in} conversion_factors[i][t] P Conversion factor of input flow (heat input)
f_{loss}(t) heat_loss_factor P Specific heat loss factor for pipeline
l length P Length of heating pipeline
CONSTRAINT_GROUP = True
class dhnx.optimization.oemof_heatpipe.Label[source]

Bases: dhnx.optimization.oemof_heatpipe.solph_label

dhnx.optimization.precalc_hydraulic

This module is designed to hold functions for pre-calculation 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.math-tech.at/Beispiele/upload/gra_Druckverlust_in_Rohrleitungen.PDF https://www.schweizer-fn.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:

SPDX-License-Identifier: 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

\frac{v \cdot d_i}{\nu}

Parameters:
  • v (numeric) – v: flow velocity [m/s]
  • d_i (numeric) – d_i: inner pipe diameter [m]
  • k_v (numeric) – \nu: 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

\Delta p = \lambda \frac{l}{d_i} \frac{\rho}{2} v^2

Parameters:
  • lam (numeric) – \lambda: Darcy friction factor [-]
  • length (numeric) – l: length of the pipe [m]
  • d_i (numeric) – d_i: inner pipe diameter [m]
  • d (numeric) – \rho: density [kg/m³]
  • v (numeric) – v: 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

\nu = \frac{\eta}{\rho}

Parameters:
  • d_v (numeric) – \eta: dynamic viskosity [kg/(m*s)]
  • d (numeric) – \rho: 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

\lambda=\frac{64}{Re}

Parameters:Re (numeric) – Re: 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)

\lambda =\frac{1}{(2 log(3,71\frac{d_i}{k}))^2}

Parameters:
  • d_i (numeric) – d_i: inner pipe diameter [m]
  • k (numeric) – k: 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) – Re: Reynolds number [-]
  • k (numeric) – k: roughness of inner pipeline surface [mm]
  • d_i (numeric) – d_i: 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)

\lambda = 0,3164\cdot Re ^{-0,25}

Parameters:Re (numeric) – Re: 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)

\lambda = 0,0032 + 0,221 \cdot Re ^{-0,237}

Parameters:Re (numeric) – Re: 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) – Re: 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.

\dot{m} = \pi \rho_{T_av}  v  \big( \frac{d_i}{2}  \big) ^2

Parameters:
  • v (numeric) – v: flow velocity [m/s]
  • di (numeric) – d_i: inner diameter [m]
  • T_av (numeric) – T_av: temperature level [°C]
  • p (numeric) – p: 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.

\dot{m} = \frac{P}{c_{P_{T_{av}}} \cdot \Delta T}

Parameters:
  • P (numeric) – P: power [W]
  • T_av (numeric) – T_{av}: average temperature [°C]
  • delta_T (numeric) – \Delta T: temperature difference [K]
  • p (numeric) – p: 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.

P_{loss} = (T_{average} - T_{ground}) \cdot U

Parameters:
  • temp_average (float) – T_{average}: 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) – U: 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) – T_{ground}: 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.

P_{th} = \dot{m} \cdot (c_{p_{VL}} \cdot T_{VL} - c_{p_{RL}} \cdot T_{RL})

Parameters:
  • T_vl (numeric) – T_{VL}: forward temperature [°C]
  • T_rl (numeric) – T_{RL}: return temperature [C°]
  • mf (numeric) – \dot{m}: mass flow [kg/s]
  • p (numeric) – p: 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.

v_{flow}=\frac{\dot{V}}{(\frac{d_i}{2})^2*\pi}

Parameters:
  • vol_flow (numeric) – \dot{V}: volume flow [m³/h]
  • d_i (numeric) – d_i: 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.

v = \frac{\dot{m}}{\pi \rho \cdot \big( \frac{d_i}{2} \big)^2 }

Parameters:
  • mf (numeric) – dot{m}: mass flow [kg/s]

  • di (numeric) – d_i: inner diameter [m]

  • T_av (numeric) – T_{av}: average temperature [°C]

    p: numeric

    p: 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) – v: flow velocity [m/s]
  • d_i (numeric) – d_i: inner pipe diameter [m]
  • k (numeric) – k: roughness of inner pipeline surface [mm]
  • T_medium (numeric) – T_{medium}: fluid temperature [°C]
  • length (numeric) – l: length of the pipe [m]
  • pressure (numeric) – p: pressure in the pipe [Pa]
  • R_crit (numeric) – Re_{crit}: 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)

f(x) = x-2 \cdot log\Big(\frac{Re}{2,51x}\Big)

Parameters:
  • x (numeric) – x: function variable [-]
  • R_e (numeric) – Re: 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 (Prandtl-Colebrook)

f(x)=x+2\cdot log \big(  \frac{2,51x}{Re} \cdot \frac{k}{3,71d_i} \big)

Parameters:
  • x (numeric) – x: function variable () [-]
  • R_e (numeric) – Re: Reynolds number [-]
  • k (numeric) – k: roughness of inner pipeline surface [mm]
  • d_i (numeric) – d_i: 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 bi-section method.

If either of the stop-criteria p_epsilon or v_epsilon is reached, the iterative calculation is stopped.

Parameters:
  • d_i (numeric) – d_i: inner diameter [m]
  • T_average (numeric) – T_{av}: average temperature [°C]
  • k (numeric) – k: roughness of inner pipeline surface [mm]
  • p_max (numeric) – p_{max}: maximum pressure drop in pipeline [Pa]
  • p_epsilon (numeric) – p_\epsilon: accuracy of pressure [Pa]
  • v_epsilon (numeric) – v_\epsilon: accuracy of velocity [m/s]
  • v_0 (numeric) – v_0: first value of initial guess for maximum flow velocity [m/s]
  • v_1 (numeric) – v_1: second value of initial guess for maximum flow velocity [m/s]
  • pressure (numeric) – p: 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) – d_i: inner diameter [m]
  • T_average (numeric) – T_{av}: average temperature [°C]
  • k (numeric) – k: roughness of inner pipeline surface [mm]
  • p_max (numeric) – p_{max}: maximum pressure drop in pipeline [Pa]
  • p_epsilon (numeric) – p_\epsilon: accuracy of pressure [Pa]
  • v_0 (numeric) – v_0: first value of initial guess for maximum flow velocity [m/s]
  • v_1 (numeric) – v_1: second value of initial guess for maximum flow velocity [m/s]
  • pressure (numeric) – p: 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:

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

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

Returns:re (pd.DataFrame) – Reynolds number for every time step and pipe [-]
_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 (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.

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

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

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.

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

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

Returns:exponent_constant (np.matrix) – Constant part of the exponent [kg/s]
_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 (pd.DataFrame) – DataFrame containing temperatures for all nodes [°C]

_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 (pd.DataFrame) – Return temperature with the consumers values set [°C]
_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 (pd.DataFrame) – Heat losses in the pipes [W]
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 (dict)