Sourcecode Documentation

This section contains the API reference for the F|Heat project.

Preprocessing

The helper functions for loading, adjusting and further processing of the downloaded data.

Download Files

src.download_files.add_point(df)[source]

Adds a point geometry to the DataFrame based on X and Y coordinates.

This method creates a ‘point’ column in the DataFrame by generating Point geometries from the ‘X_MP_100m’ and ‘Y_MP_100m’ coordinate columns.

Parameters:

df (pd.DataFrame) – The DataFrame containing the ‘X_MP_100m’ and ‘Y_MP_100m’ columns representing the X and Y coordinates of the points.

Returns:

The DataFrame with an additional ‘point’ column containing the Point geometries.

Return type:

pd.DataFrame

src.download_files.clean_data(df)[source]

Cleans the DataFrame by replacing invalid characters.

This method replaces specific invalid characters in the given DataFrame with valid alternatives. The following replacements are made: - ‘–’ and ‘–’ are replaced with ‘-‘.

Parameters:

df (pd.DataFrame) – The DataFrame to clean.

Returns:

The cleaned DataFrame with invalid characters replaced.

Return type:

pd.DataFrame

src.download_files.create_square(point, size)[source]

Creates a square polygon around a given point with a specified size.

This method generates a square-shaped polygon centered on the provided point. The square’s side length is determined by the size parameter, and the square is oriented parallel to the axes.

Parameters:
  • point (shapely.geometry.Point) – The central point around which the square will be created. It should have ‘x’ and ‘y’ coordinates.

  • size (float) – The total side length of the square.

Returns:

A square-shaped polygon centered around the input point.

Return type:

shapely.geometry.Polygon

src.download_files.file_list_from_URL(url)[source]

lists downloadable files from given URL

This function downloads the content from the specified URL, decodes the content, evaluates it as a dictionary, and extracts a list of files from all dataset entries.

Parameters:

url (str) – The URL from which to download and extract the file list.

Returns:

A list of files found in all entries under ‘datasets’.

Return type:

list

src.download_files.filter_df(name, dataframe, parameter)[source]

Searches a DataFrame for a city name .

This function filters a given DataFrame based on a specified parameter (‘city’ or ‘gemeinde’) and searches for an exact match of the provided name. If a match is found, a new DataFrame containing the matching rows is returned; otherwise, a message is printed and None is returned.

Parameters:
  • name (str) – The name (city or municipality name) to search for in the DataFrame.

  • dataframe (pandas.DataFrame) – The DataFrame to search within.

  • parameter (str) – Specifies whether to search by ‘city’ (for city name) or ‘gemeinde’ (for municipality name).

Returns:

A DataFrame containing rows matching the specified name and parameter, or None if no match is found.

Return type:

pandas.DataFrame or None

src.download_files.get_shape_from_wfs(wfs_url, key, bbox, layer_name)[source]

Loads shapefiles within a bounding box from a WFS service and filters for ‘key’.

This function connects to a Web Feature Service (WFS), retrieves shapefiles within a specified bounding box, and filters the shapefiles based on the given key (Gemeinde or Gemarkung). If the number of features exceeds 100,000, a warning is printed.

Parameters:
  • wfs_url (str) – The URL of the WFS service.

  • key (str) – The key for filtering (e.g., Gemeinde or Gemarkung).

  • bbox (tuple) – The bounding box for filtering in the format (minx, miny, maxx, maxy).

  • layer_name (str) – The name of the layer containing the desired shapes.

Returns:

  • GeoDataFrame – A GeoDataFrame containing the filtered shapes.

  • int or None – An exception flag. If the number of features exceeds 100,000, returns 1; otherwise, None.

Examples

>>> wfs_url = "http://example.com/wfs"
>>> key = "123"
>>> bbox = (10.0, 50.0, 10.5, 50.5)
>>> layer_name = "example_layer"
>>> shapes, exception = get_shape_from_wfs(wfs_url, key, bbox, layer_name)
>>> shapes.head()
   nationalCadastralReference  geometry
0                        1234  POINT (10.00000 50.00000)
1                        1235  POINT (10.10000 50.10000)

Notes

The function assumes that the WFS service supports version 2.0.0 and returns data in ‘text/xml’ format. If the bounding box contains more than 100,000 features, a warning is printed, and the returned GeoDataFrame may be incomplete.

src.download_files.read_file_from_zip(url, zipfile, file_pattern, file_type='.shp', encoding='utf-8', delimiter=';')[source]

Reads a file (GeoDataFrame for shapefiles or DataFrame for CSV) from a downloadable zip file.

This function downloads a zip file from a specified URL, extracts its contents, searches for a file matching a given pattern and file type (e.g., ‘.shp’, ‘.gpkg’, or ‘.csv’), and reads the file as either a GeoDataFrame (for spatial files) or a DataFrame (for CSV). It handles the extraction of files and cleans up temporary files afterward.

Parameters:
  • url (str) – The URL of the site where the zip file can be downloaded.

  • zipfile (str) – The name of the zip file to be downloaded.

  • file_pattern (str) – The pattern to search for in the file names within the zip file.

  • file_type (str, optional) – The type of file to be read (e.g., ‘.shp’, ‘.csv’, ‘.gpkg’), by default ‘.shp’.

  • encoding (str, optional) – The encoding to use when reading the file, by default ‘utf-8’.

Returns:

A GeoDataFrame if a shapefile or GeoPackage is found, or a DataFrame if a CSV is found.

Return type:

GeoDataFrame or DataFrame

Examples

>>> url = "http://example.com/files/"
>>> zipfile = "data.zip"
>>> file_pattern = "desired_file"
>>> data = read_file_from_zip(url, zipfile, file_pattern, file_type='.csv')
>>> data.head()
   column1  column2  column3
0        1        2        3
1        4        5        6

Notes

  • The function supports both spatial files (e.g., ‘.shp’, ‘.gpkg’) and CSV files.

  • Temporary files are extracted to ‘/tmp/extracted_zip’ and cleaned up after reading.

  • The file type must be specified via the ‘file_type’ argument, which defaults to ‘.shp’.

src.download_files.search_filename(files, city_id)[source]

Searches for a city in a list of files and returns the file name.

This function iterates through a list of file dictionaries, searching for the specified city identifier in the file names. The city identifier can be either a city name or a Gemeindeschlüssel. If a matching file is found, its name is returned; otherwise, a default message indicating that no file was found is returned.

Parameters:
  • files (list of dict) – A list of dictionaries, each representing a file with at least a ‘name’ key.

  • city_id (str or int) – The city identifier to search for in the file names. This can be a city name or a Gemeindeschlüssel.

Returns:

The name of the file that contains the city identifier, or ‘Keine Datei gefunden’ if no matching file is found.

Return type:

str

Adjust Files

class src.adjust_files.Buildings_adj(path, heat_att)[source]

Bases: object

A class to represent and manipulate building geometries and attributes.

This class provides methods for adding load profiles, filtering buildings, adding power attributes, classifying buildings by age, and merging building data with custom aggregations. It also allows for the integration of custom heat demand data based on building characteristics.

gdf

A GeoDataFrame containing building geometries and associated attributes.

Type:

GeoDataFrame

heat_att

The attribute name for heat data in the GeoDataFrame.

Type:

str

add_Vlh_Loadprofile(excel_data):

Adds full load hours (Vlh) and load profiles to the buildings based on external Excel data.

drop_unwanted():

Removes buildings that do not have a load profile.

add_power():

Adds a power attribute to the buildings based on the heat attribute and full load hours.

extract_year(date_str):

Extracts the year from a date string.

add_BAK(bins, labels):

Classifies buildings into age groups based on the provided bins and labels.

add_LANUV_age_and_type():

Extracts building age and type from the ‘GEBAEUDETY’ attribute and adds them as new columns.

merge_buildings():

Merges building geometries and attributes, performing custom aggregations.

add_custom_heat_demand(building_data):

Adds custom heat demand data to the existing GeoDataFrame based on building characteristics.

add_BAK(bins, labels)[source]

Adds building age classification based on the provided bins and labels.

This method classifies buildings into age groups based on the ‘validFrom’ attribute using the provided bins and labels.

Parameters:
  • bins (list of int) – The bin edges for classifying buildings by age.

  • labels (list of str) – The labels for the age bins.

Examples

>>> bins = [1800, 1900, 1950, 2000, 2024]
>>> labels = ["1800-1899", "1900-1949", "1950-1999", "2000-2024"]
add_LANUV_age_and_type()[source]

This method extracts the building age and type from the ‘GEBAEUDETY’ attribute and adds it as two new columns.

add_Vlh_Loadprofile(excel_data)[source]

Adds full load hours and load profiles to the buildings.

This method merges the building data with external Excel data containing full load hours (Volllaststunden Vlh) and load profiles based on the ‘citygml_fu’ attribute of the buildings.

Parameters:

excel_data (DataFrame) – A DataFrame containing the load profile data with ‘Funktion’, ‘Lastprofil’, and ‘Vlh’ columns.

add_custom_heat_demand(wg_data, nwg_data)[source]

Adds custom heat demand data to the existing GeoDataFrame based on building characteristics from two datasets.

This method merges the existing GeoDataFrame with two external DataFrames (wg_data and nwg_data) to assign specific heat demand values for each building type (e.g., MFH or EFH) or function. The specific heat demand values are used to calculate the total heat demand for each building.

Parameters:
  • wg_data (pd.DataFrame) – A DataFrame containing building-specific heat demand data. It must include the following columns: - ‘Baualtersklasse’: Building age class. - ‘Waerme_MFH kWh/m²·a’: Specific heat demand for multi-family houses (MFH) in kWh/m²·a. - ‘Waerme_EFH kWh/m²·a’: Specific heat demand for single-family houses (EFH) in kWh/m²·a.

  • nwg_data (pd.DataFrame) – A DataFrame containing additional building data. It must include the following columns: - ‘Funktion’: Function classification of the building. - ‘WVBRpEBF’: Specific heat demand value based on the building function.

Notes

The method assumes that ‘Lastprofil’ in the GeoDataFrame specifies the building type as either ‘MFH’ or ‘EFH’. Buildings not classified as ‘MFH’ or ‘EFH’ will receive their heat demand value from the ‘WVBRpEBF’ column in nwg_data. If ‘WVBRpEBF’ is not available, the resulting demand will be NaN.

The total heat demand is calculated by multiplying the net floor area (‘NF’) by the assigned specific heat demand.

add_power()[source]

Adds a power attribute to the buildings.

This method calculates the power attribute for each building based on the heat attribute and full load hours. If full load hours (Vlh) are zero, it uses a default value of 1600.

drop_unwanted()[source]

Drops buildings that do not have a load profile.

This method removes all buildings that do not have a load profile, as these are buildings that are not needed or have other issues.

static extract_year(date_str)[source]

Extracts the year from a date string.

This method extracts the year as an integer from the beginning of a date string. If the date string is NaN, it returns NaN.

Parameters:

date_str (str) – The date string from which to extract the year.

Returns:

The extracted year or NaN if the date string is NaN.

Return type:

int or float

Examples

>>> Buildings_adj.extract_year("2023-07-17")
2023
>>> Buildings_adj.extract_year(None)
nan
merge_buildings()[source]

Merges building geometries and attributes, performing custom aggregations.

This method dissolves the building geometries based on ‘Flurstueck’, ‘citygml_fu’, and ‘Fortschrei’ attributes and performs custom aggregations on the attributes.

rename_and_order_columns()[source]

renames and order the columns of the buildings data frame.

class src.adjust_files.Parcels_adj(path)[source]

Bases: object

A class used to represent and manipulate parcel geometries.

This class provides a method to initialize a GeoDataFrame of parcel geometries from a shapefile.

gdf

A GeoDataFrame containing the parcel geometries.

Type:

GeoDataFrame

__init__(path):

Initializes the Parcels_adj class with a GeoDataFrame of parcel geometries.

class src.adjust_files.Streets_adj(path)[source]

Bases: object

A class used to represent and manipulate street geometries.

This class provides methods to round the coordinates of street geometries and to add a boolean column indicating possible routes.

gdf

A GeoDataFrame containing the street geometries.

Type:

GeoDataFrame

round_streets():

Rounds the coordinates of street geometries to 3 decimal places.

add_bool_column():

Adds a boolean column indicating possible routes.

add_bool_column()[source]

Adds a boolean column to the GeoDataFrame indicating possible routes.

This method adds a new column ‘Moegliche_Route’ (= possible route) to the GeoDataFrame, initialized with the value 1 for all rows.

round_streets()[source]

Rounds the coordinates of street geometries to 3 decimal places.

This method processes the geometries in the GeoDataFrame, converting any MultiLineString geometries to LineString geometries, and then rounds their coordinates to 3 decimal places.

Notes

  • If any MultiLineString geometries are found, they are converted to LineString geometries by taking the first component of the MultiLineString.

  • A warning is printed if any MultiLineString geometries are found and processed.

src.adjust_files.spatial_join(shape1, shape2, attributes)[source]

Performs a spatial join to add attributes from shape2 to the best fitting feature in shape1.

This function finds the best fitting feature in shape2 that intersects with each feature in shape1 based on the intersection area. It then adds the specified attributes from shape2 to shape1.

Parameters:
  • shape1 (GeoDataFrame) – The GeoDataFrame to which attributes will be added.

  • shape2 (GeoDataFrame) – The GeoDataFrame from which attributes will be sourced.

  • attributes (list of str) – List of attribute names to be transferred from shape2 to shape1.

Returns:

The updated shape1 GeoDataFrame with the specified attributes added from shape2.

Return type:

GeoDataFrame

Notes

If columns named ‘index_left’ or ‘index_right’ exist in either shape1 or shape2, they will be removed to avoid conflicts during the spatial join.

If an attribute specified in the attributes list does not exist in shape2, the function will attempt to use a column named {attribute}_left instead and will print a message indicating the update.

Examples

>>> shape1 = gpd.read_file("path/to/shape1.shp")
>>> shape2 = gpd.read_file("path/to/shape2.shp")
>>> attributes = ["attr1", "attr2"]
>>> updated_shape1 = spatial_join(shape1, shape2, attributes)

Demand Curve

Load Curve Generation

class src.load_curve.LoadProfile(net_result, excel_path, year, temperature_data, holidays)[source]

Bases: object

A class for managing and analyzing load profiles, including generating, sorting, and saving energy demand profiles.

net_result

The result object containing network data.

Type:

object

path

The path to the Excel file where results are stored.

Type:

str

year

The year for which the demand profiles are generated.

Type:

int

temperature

The temperature data series for the year.

Type:

pd.Series

holidays

List of holidays in the year.

Type:

list

demand_time_series

Time series index for the entire year at hourly frequency.

Type:

pd.DatetimeIndex

create_heat_demand_profile(building_type, building_class, wind_class, ww_incl, annual_heat_demand):

Creates a heating demand profile based on building characteristics and annual heat demand.

set_up_df(year, resolution, freq):

Creates a DataFrame for collecting generated profiles with the specified resolution and frequency.

sort_columns_by_sum(df):

Sorts the columns of a dataframe in ascending order based on their sum and returns the sorted dataframe.

add_loss(demand_df, df, resolution=8760):

Adds a loss column to the demand dataframe based on the maximum annual loss in another dataframe.

add_sum_buildings(df):

Adds a column for the sum of all building types in a dataframe and returns the modified dataframe.

add_sum(df):

Adds a total sum column that includes the sum of all building types and losses.

plot_bar_chart(dataframe, column_names, figsize=(18, 4), colors=['blue', 'orange'], filename='../Lastprofil.png'):

Plots a bar chart of specified columns in a dataframe.

save_in_excel(df, col=0, index_bool=False, sheet_option='replace', sheet='Lastprofil'):

Saves the dataframe to the specified Excel file and sheet.

embed_image_in_excel(row, col, sheet='Lastprofil', image_filename='../Lastprofil.png'):

Embeds an image into the specified Excel sheet at a given position.

open_excel_file():

Opens the Excel file using the default application.

static add_loss(demand_df, df, resolution=8760)[source]

Adds a loss column to the demand dataframe based on the maximum annual loss in another dataframe.

Parameters:
  • demand_df (pd.DataFrame) – The dataframe to which the loss column will be added.

  • df (pd.DataFrame) – The dataframe containing loss information.

  • resolution (int, optional) – The time resolution in hours (default is 8760 for an hourly resolution over a year).

Returns:

The modified demand dataframe with the added loss column.

Return type:

pd.DataFrame

static add_sum(df)[source]

Adds a total sum column that includes the sum of all building types and losses.

Parameters:

df (pd.DataFrame) – The dataframe to which the total sum column will be added.

Returns:

The modified dataframe with the total sum column.

Return type:

pd.DataFrame

static add_sum_buildings(df)[source]

Adds a column for the sum of all building types in a dataframe.

Parameters:

df (pd.DataFrame) – The dataframe to which the sum column will be added.

Returns:

The modified dataframe with the sum column.

Return type:

pd.DataFrame

create_heat_demand_profile(building_type, building_class, wind_class, ww_incl, annual_heat_demand)[source]

Creates a heating demand profile based on building characteristics and annual heat demand.

Parameters:
  • building_type (str) – The type of the building (e.g. EFH = Einfamilienhaus).

  • building_class (int) – The building age class (1-11).

  • wind_class (int) – The wind load class.

  • ww_incl (bool) – Whether domestic hot water (DHW) is included.

  • annual_heat_demand (float) – The annual heat demand in MWh.

Returns:

The generated heat demand profile.

Return type:

pd.Series

embed_image_in_excel(row, col, sheet='Lastprofil', image_filename='../Lastprofil.png')[source]

Embeds an image into the specified Excel sheet at a given position.

Parameters:
  • row (int) – The row index where the image should be placed.

  • col (int) – The column index where the image should be placed.

  • sheet (str, optional) – The name of the Excel sheet (default is ‘Lastprofil’).

  • image_filename (str, optional) – The filename of the image to embed (default is ‘../Lastprofil.png’).

open_excel_file()[source]

Opens the Excel file using the default application.

static plot_bar_chart(dataframe, column_names, figsize=(18, 4), colors=['blue', 'orange'], filename='../Lastprofil.png', ylabel='Wärmebedarf und Verlust [MW]', title='Wärmebedarf und Verlust pro Stunde im Jahr')[source]

Plots a bar chart of specified columns in a dataframe.

Parameters:
  • dataframe (pd.DataFrame) – The data frame containing the data to plot.

  • column_names (list) – List of column names to plot.

  • figsize (tuple, optional) – Size of the figure (default is (18, 4)).

  • colors (list, optional) – List of colors for the bars (default is [‘blue’, ‘orange’]).

  • filename (str, optional) – The filename to save the plot (default is ‘../Lastprofil.png’).

save_in_excel(df, col=0, index_bool=False, sheet_option='replace', sheet='Lastprofil')[source]

Saves the dataframe to the specified Excel file and sheet.

Parameters:
  • df (pd.DataFrame) – The dataframe to save.

  • col (int, optional) – The starting column index in the Excel sheet (default is 0).

  • index_bool (bool, optional) – Whether to include the dataframe index in the Excel file (default is False).

  • sheet_option (str, optional) – The option for handling existing sheets (default is ‘replace’). Options: ‘error’, ‘new’, ‘replace’, ‘overlay’.

  • sheet (str, optional) – The name of the Excel sheet (default is ‘Lastprofil’).

static set_up_df(year, resolution, freq)[source]

Creates a DataFrame for collecting generated profiles with the specified resolution and frequency.

Parameters:
  • year (int) – The year for the time series index.

  • resolution (int) – The number of periods in the time series.

  • freq (str) – Frequency of the time series (e.g., ‘H’ for hourly).

Returns:

DataFrame with a time series index.

Return type:

pd.DataFrame

static sort_columns_by_sum(df)[source]

Sorts the columns of a dataframe in ascending order based on their sum.

Parameters:

df (pd.DataFrame) – The dataframe whose columns need to be sorted.

Returns:

Dataframe with columns sorted by their sum.

Return type:

pd.DataFrame

class src.load_curve.Temperature(url)[source]

Bases: object

A class to handle temperature data from a specified URL.

url

Base URL for temperature data.

Type:

str

url_all

URL for the file containing station descriptions.

Type:

str

stationsfromtxt():

Retrieves and processes station data from the URL.

nearestStation(poi, gdf, year, i=10):

Finds the nearest station to a given point of interest (POI) for a specific year.

tempdata(url, station_id, year, start_date, end_date, n=10):

Loads and returns mean temperature data from the last n years as a DataFrame.

nearestStation(poi, gdf, i=10)[source]

Searches for the nearest stations to a point of interest (POI) for a specific year.

Parameters:
  • poi (tuple) – Point of interest (x, y) where temperature data is needed.

  • gdf (GeoDataFrame) – GeoDataFrame with all stations.

  • i (int, optional) – Number of nearest stations to consider (default is 10).

Returns:

A GeoDataFrame with the nearest station(s).

Return type:

GeoDataFrame

stationsfromtxt()[source]

Retrieves and processes weather station data from the URL.

Returns:

A GeoDataFrame with station data including geometry for spatial operations.

Return type:

GeoDataFrame

tempdata(url, station_id, start_date, end_date, n=10)[source]

Loads and returns mean temperature data from the last n years as a DataFrame.

Parameters:
  • url (str) – Base URL for temperature data.

  • station_id (str) – ID of the station.

  • year (int) – Year for which temperature data is wanted.

  • start_date (str) – Start date for the data.

  • end_date (str) – End date for the data.

  • n (int, optional) – Number of years to consider (default is 10).

Returns:

DataFrame containing the mean temperature data.

Return type:

DataFrame

Net Analysis

Net Analysis

class src.net_analysis.Buildings(path, heat_att, layer=None)[source]

Bases: object

A class to manage building geometries, add centroids, and find the closest points on street networks.

buildings_all

A GeoDataFrame containing all building geometries and attributes.

Type:

GeoDataFrame

gdf

A GeoDataFrame containing buildings with a specified heat attribute greater than zero.

Type:

GeoDataFrame

add_centroid():

Adds the centroid of each building’s geometry to the GeoDataFrame.

closest_points_buildings(streets):

Finds the closest point on the street network for each building and adds these points to the GeoDataFrame.

add_centroid()[source]

Adds the centroid of each building’s geometry to the GeoDataFrame.

Notes

The centroid is computed for each polygon in the GeoDataFrame and added as a new column ‘centroid’.

closest_points_buildings(streets)[source]

Finds the closest point on the street network for each building and adds these points to the GeoDataFrame.

Parameters:

streets (GeoDataFrame) – A GeoDataFrame containing street geometries and attributes.

Notes

For each building, this method computes the closest point on the street network and adds it to the GeoDataFrame along with the ID of the closest street.

class src.net_analysis.Graph(crs)[source]

Bases: object

A class to represent and manipulate a street network graph using NetworkX.

graph

A NetworkX graph representing the street network.

Type:

nx.Graph

crs

coordinate reference system

Type:

string

create_street_network(streets):

Creates a street network graph from a GeoDataFrame of streets.

connect_centroids(buildings):

Connects building centroids to the street network.

connect_source(sources):

Connects energy sources to the street network.

add_attribute_length():

Adds a ‘length’ attribute to each edge in the graph.

plot_G():

Plots the street network graph.

get_connected_points(input_point):

Returns the points connected to the given input point in the graph.

plot_graph(input_point, connected_points):

Plots the graph with connected points highlighted.

graph_to_gdf():

Converts the NetworkX graph to a GeoDataFrame.

save_nodes_to_shapefile(filename):

Saves the graph nodes as points in a shapefile, with node degree and coordinates annotated.

add_attribute_length()[source]

Adds a ‘length’ attribute to each edge in the graph.

connect_centroids(buildings)[source]

Connects building centroids to the street network.

Parameters:

buildings (GeoDataFrame) – A GeoDataFrame containing building geometries and centroids.

connect_source(sources)[source]

Connects energy sources to the street network.

Parameters:

sources (GeoDataFrame) – A GeoDataFrame containing energy source geometries.

create_street_network(streets)[source]

Creates a street network graph from a GeoDataFrame of streets.

Parameters:

streets (GeoDataFrame) – A GeoDataFrame containing street geometries.

get_connected_points(input_point)[source]

Returns the points connected to the given input point in the graph.

Parameters:

input_point (tuple) – The input point coordinates.

Returns:

A list of points connected to the input point.

Return type:

list

graph_to_gdf()[source]

Converts the NetworkX graph to a GeoDataFrame, including edge attributes.

Returns:

A GeoDataFrame representing the graph edges.

Return type:

GeoDataFrame

plot_G()[source]

Plots the street network graph.

plot_graph(input_point, connected_points, disconnected_buildings)[source]

Plots the graph with connected points highlighted.

Parameters:
  • input_point (tuple) – The input point coordinates.

  • connected_points (list) – A list of points connected to the input point.

  • disconnected_buildins (list) – A list of building centroids disconnected from the imput point

save_nodes_to_shapefile(filename)[source]

Saves the graph nodes as points in a shapefile, with node degree and coordinates annotated.

Parameters:

filename (str) – The file path to save the shapefile.

class src.net_analysis.Net(htemp, ltemp, crs)[source]

Bases: object

A class to represent and manipulate a network graph for heat distribution.

net

A NetworkX graph representing the network.

Type:

nx.Graph

htemp

Supply temperature.

Type:

float

ltemp

Return temperature.

Type:

float

crs

coordinate reference system

Type:

string

update_attribute(u, v, attribute, name):

Adds or updates an attribute to an edge in the network graph.

add_edge_attributes(pipe_info):

Adds attributes to the network edges such as GLF, power_th_GLF, volumeflow, DN, velocity, and loss.

network_analysis(G, buildings, sources, pipe_info, power_th_att, weight='length', progressBar=None):

Calculates the network by finding the shortest path to each building.

plot_network(streets, buildings, sources, filename, title='Street network and calculated network'):

Plots the street network, buildings, and calculated network, and saves the image.

ensure_power_th_attribute():

Ensures that each edge in the graph has the thermal power attribute.

graph_to_gdf():

Converts a NetworkX graph to a GeoDataFrame, including edge attributes.

add_edge_attributes(pipe_info)[source]

Adds attributes to the network edges such as GLF, power_th_GLF, volumeflow, DN, velocity, and loss.

Parameters:

pipe_info (DataFrame) – DataFrame containing pipe information.

ensure_power_th_attribute()[source]

Ensures that each edge in the graph has the thermal power attribute. If an edge does not have the attribute, it is initialized with a value of 0.

graph_to_gdf()[source]

Converts a NetworkX graph to a GeoDataFrame, including edge attributes.

network_analysis(G, buildings, sources, pipe_info, power_th_att, weight='length [m]', progressBar=None)[source]

Calculates the network by finding the shortest path to each building.

Parameters:
  • G (nx.Graph) – The street network graph.

  • buildings (GeoDataFrame) – GeoDataFrame of buildings.

  • sources (GeoDataFrame) – GeoDataFrame of energy sources.

  • pipe_info (DataFrame) – DataFrame containing pipe information.

  • power_th_att (str) – Attribute name for thermal power in the buildings GeoDataFrame.

  • weight (str, optional) – Edge weight attribute for shortest path calculation (default is ‘length [m]’).

  • progressBar (callable, optional) – Progress bar function (default is None).

plot_network(streets, buildings, sources, filename, title='Straßennetzwerk und berechnetes Netz')[source]

Plots the street network, buildings, and calculated network, and saves the image.

Parameters:
  • streets (GeoDataFrame) – GeoDataFrame of streets.

  • buildings (GeoDataFrame) – GeoDataFrame of buildings.

  • sources (GeoDataFrame) – GeoDataFrame of energy sources.

  • filename (str) – File name to save the image.

  • title (str, optional) – Title of the plot (default is ‘Street network and calculated network’).

rename_columns()[source]

renames columns of self.gdf.

update_attribute(u, v, attribute, name)[source]

Adds or updates an attribute to an edge in the network graph.

Parameters:
  • u (nodes) – Nodes defining the edge.

  • v (nodes) – Nodes defining the edge.

  • attribute (any) – Value of the attribute.

  • name (str) – Name of the attribute.

class src.net_analysis.Result(path)[source]

Bases: object

A class to handle and process results for exporting to Excel.

path

Path to the result file.

Type:

str

data_dict

Dictionary containing result data.

Type:

dict

create_data_dict(buildings, net, types, dn_list, heat_att, h_temp, l_temp):

Creates a dictionary for the results to be used in Excel.

create_df_from_dataDict(net_name='Netz'):

Converts the dictionary to a result DataFrame.

save_in_excel(col=0, index_bool=False, sheet_option='replace', sheet='Zusammenfassung'):

Saves the DataFrame to an Excel sheet.

static building_statistic(gdf)[source]

Computes statistics for buildings from a GeoDataFrame.

This function filters and aggregates building data to compute various statistics for each building type.

Parameters:

gdf (GeoDataFrame) – The GeoDataFrame containing building data. Expected columns include ‘type’, ‘NF’, ‘RW_spez’, ‘WW_spez’, ‘RW_WW_spez’, ‘age_LANUV’, and ‘BAK’.

Returns:

aggregated_stats – A DataFrame with aggregated statistics for each building type.

Return type:

DataFrame

copy_excel_file(source_path)[source]

Copies an Excel file from source to destination without modifying the content, format, or objects.

Parameters:
  • source_path (str) – The file path of the source Excel file.

  • destination_path (str) – The file path where the Excel file should be saved.

create_data_dict(buildings, net, types, dn_list, heat_att, h_temp, l_temp)[source]

Creates a dictionary for the results to be used in Excel.

Parameters:
  • buildings (DataFrame) – DataFrame of buildings.

  • net (DataFrame) – DataFrame of the network.

  • types (list) – List of building types.

  • dn_list (list) – List of possible pipe diameters.

  • heat_att (str) – Attribute name for heat demand in the buildings DataFrame.

  • h_temp (float) – Supply temperature.

  • l_temp (float) – Return temperature.

create_df_from_dataDict(net_name='Netz')[source]

Converts the dictionary to a result DataFrame.

Parameters:

net_name (str, optional) – Name of the network (default is ‘Netz’).

is_excel_file_open()[source]

Checks if the Excel file can be written to.

save_in_excel(result_table, col=0, row=0, index_bool=False, sheet_option='replace', sheet='Zusammenfassung')[source]

Saves the DataFrame to an Excel sheet.

Parameters:
  • col (int, optional) – Starting column (default is 0).

  • index_bool (bool, optional) – Whether to save the DataFrame with or without indices (default is False).

  • sheet_option (str, optional) – Option for handling existing sheets (‘replace’, ‘overlay’, or ‘new’) (default is ‘replace’).

  • sheet (str, optional) – Sheet name in the Excel file (default is ‘Zusammenfassung’).

class src.net_analysis.Source(path, layer=None)[source]

Bases: object

A class to manage energy source geometries and to find the closest points on street networks.

gdf

A GeoDataFrame containing source geometries and attributes.

Type:

GeoDataFrame

closest_points_sources(streets):

Finds the closest points on the street network for each energy source and adds these points to the GeoDataFrame.

closest_points_sources(streets)[source]

Finds the closest point on the street network for each energy source and adds these points to the GeoDataFrame.

Parameters:

streets (GeoDataFrame) – A GeoDataFrame containing street geometries and attributes.

class src.net_analysis.Streets(path, layer=None)[source]

Bases: object

A class to manage street geometries and to add connection points from buildings and energy sources to the streets.

gdf

A GeoDataFrame containing street geometries and attributes.

Type:

GeoDataFrame

add_connection_to_streets(buildings, sources):

Inserts connection points into the street lines based on buildings and energy sources.

add_connection_to_streets(buildings, sources)[source]

Inserts connection points from buildings and energy sources into the street lines.

Parameters:
  • buildings (GeoDataFrame) – A GeoDataFrame containing building geometries and attributes, including ‘street_id’ and ‘Anschlusspunkt’.

  • sources (GeoDataFrame) – A GeoDataFrame containing energy source geometries and attributes, including ‘street_id’ and ‘Anschlusspunkt’.

src.net_analysis.calculate_GLF(n)[source]

Calculate the simultaneity factor (Gleichzeitigkeitsfaktor).

Parameters:

n (int) – Number of buildings.

Returns:

The simultaneity factor.

Return type:

float

src.net_analysis.calculate_diameter_velocity_loss(volumeflow, htemp, ltemp, length, pipe_info, edge_type)[source]

Calculate the diameter, velocity, and loss of pipelines.

Parameters:
  • volumeflow (float) – Volumetric flow rate.

  • htemp (float) – Supply temperature.

  • ltemp (float) – Return temperature.

  • length (float) – Length of the pipeline.

  • pipe_info (DataFrame) – DataFrame containing pipeline information with columns ‘DN’, ‘di’, ‘U-Value’, ‘v_max’.

  • edge_type (string) – String containing the type of the edge e.g. ‘Hausanschluss’.

Returns:

A tuple containing: - DN (float): Nominal diameter. - velocity (float): Velocity in the pipeline. - loss (float): Heat loss. - loss_extra (float): Heat loss with extra insulation.

Return type:

tuple

src.net_analysis.calculate_volumeflow(kW_GLF, htemp, ltemp)[source]

Calculate the volumetric flow rate in a pipeline.

Parameters:
  • kW_GLF (float) – Thermal power with simultaneity factor applied.

  • htemp (float) – Supply temperature.

  • ltemp (float) – Return temperature.

Returns:

Volumetric flow rate in liters per second.

Return type:

float

src.net_analysis.get_closest_point(line, point)[source]

Calculate the closest point on a line to a given point.

Parameters:
  • line (shapely.geometry.LineString) – The line on which to find the closest point.

  • point (shapely.geometry.Point) – The point from which to find the closest point on the line.

Returns:

The closest point on the line to the given point.

Return type:

shapely.geometry.Point