tespy.tools module#

tespy.tools.analyses module#

Module for thermodynamic analyses.

The analyses module provides thermodynamic analysis tools for your simulation. Different analysis classes are available:

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/analyses.py

SPDX-License-Identifier: MIT

class tespy.tools.analyses.ExergyAnalysis(network, E_F, E_P, E_L=[], internal_busses=[])[source]#

Bases: object

Class for exergy analysis of TESPy models.

analyse(pamb, Tamb, Chem_Ex=None)[source]#

Run the exergy analysis.

Parameters:
  • pamb (float) – Ambient pressure value for analysis, provide value in network’s pressure unit.

  • Tamb (float) – Ambient temperature value for analysis, provide value in network’s temperature unit.

calculate_group_input_value(group_label)[source]#

Calculate the total exergy input of a component group.

create_group_data()[source]#

Collect the component group exergy data.

evaluate_busses(cp)[source]#

Evaluate the exergy balances of busses.

Parameters:

cp (tespy.components.component.Component) – Component to analyse the bus exergy balance of.

exergy_cats = ['chemical', 'physical', 'massless']#
generate_plotly_sankey_input(node_order=[], colors={}, display_thresold=0.001, disaggregate_flows=False)[source]#

Generate input data for sankey plots.

Only exergy flow above the display threshold is included. All component groups with transit only (one input and one output) are cut out of the display.

Parameters:
  • node_order (list) – Order for the nodes in the sankey diagram (optional). In case no order is passed, a generic order will be used.

  • colors (dict) – Dictionary containing a color for every stream type (optional). Stream type is the key, the color is the corresponding value. Stream types are:

    • E_F, E_P, E_L, E_D

    • names of the pure fluids of the tespy Network

    • mix (used in case of any gas mixture)

    • labels of internal busses

  • display_threshold (float) – Minimum value of flows to be displayed in the diagram, defaults to 1e-3.

  • disaggregate_flows (boolean) – Separate every flow by chemical, physical and massless exergy, defaults to False.

Returns:

tuple – Tuple containing the links and node_order for the plotly sankey diagram.

print_results(sort_desc=True, busses=True, components=True, connections=True, groups=True, network=True, aggregation=True)[source]#

Print the results of the exergy analysis to prompt.

  • The results are sorted beginning with the component having the biggest exergy destruction by default.

  • Components with an exergy destruction smaller than 1000 W is not printed to prompt by default.

Parameters:
  • sort_des (boolean) – Sort the component results descending by exergy destruction.

  • busses (boolean) – Print bus results, default value True.

  • components (boolean) – Print component results, default value True.

  • connections (boolean) – Print connection results, default value True.

  • network (boolean) – Print network results, default value True.

  • aggregation (boolean) – Print aggregated component results, default value True.

remove_transit_groups(group_data)[source]#

Remove transit only component groups from sankey display.

Method is recursively called if a group was removed from display to catch cases, where multiple groups are attached in line without any streams leaving the line.

Parameters:

group_data (dict) – Dictionary containing the modified component group data.

single_group_input(group_label, group_data)[source]#

Calculate the total exergy input of a component group.

tespy.tools.analyses.categorize_fluids(conn)[source]#

tespy.tools.characteristics module#

Module for characteristic functions.

The characteristics module provides the integration of characteristic lines and characteristic maps. The user can create custom characteristic lines or maps with individual data.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/characteristics.py

SPDX-License-Identifier: MIT

class tespy.tools.characteristics.CharLine(x=array([0, 1]), y=array([1., 1.]), extrapolate=False)[source]#

Bases: object

Class for characteristc lines.

Parameters:
  • x (ndarray) – An array for the x-values of the lookup table. Number of x and y values must be identical.

  • y (ndarray) – The corresponding y-values for the lookup table. Number of x and y values must be identical.

  • extrapolate (boolean) – If True linear extrapolation is performed when the x value is out of the defined value range.

Note

This class generates a lookup table from the given input data x and y, then performs linear interpolation. The x and y values may be specified by the user. There are some default characteristic lines for different components, see the tespy.data module. If you neither specify the method to use from the defaults nor specify x and y values, the characteristic line generated will be x = [0, 1], y = [1, 1].

evaluate(x)[source]#

Return characteristic line evaluation at x.

Parameters:

x (float) – Input value for linear interpolation.

Returns:

y (float) – Evaluation of characteristic line at x.

Note

This methods checks for the value range first. If extrapolate is False (default) and the x-value is outside of the specified range, the function will return the values at the corresponding boundary. If extrapolate is True the y-value is calculated by linear extrapolation.

\[y = y_0 + \frac{x-x_0}{x_1-x_0} \cdot \left(y_1-y_0 \right)\]

where the index \(x_0\) represents the lower and \(x_1\) the upper adjacent x-value. \(y_0\) and \(y_1\) are the corresponding y-values. On extrapolation the two smallest or the two largest value pairs are used respectively.

get_attr(key)[source]#

Get the value of an attribute.

Parameters:

key (str) – Object attribute to get value of.

Returns:

value (object) – Value of object attribute key.

get_domain_errors(x, c)[source]#

Prompt error messages, if x value is out of bounds.

Parameters:

x (float) – Input value for linear interpolation.

plot(path, title, xlabel, ylabel)[source]#
class tespy.tools.characteristics.CharMap(x=array([0, 1]), y=array([[1., 1.], [1., 1.]]), z=array([[1., 1.], [1., 1.]]))[source]#

Bases: object

Class for characteristic maps.

Parameters:
  • x (ndarray) – An array for the first dimension input of the map.

  • y (ndarray) – A two-dimensional array of the second dimension input of the map.

  • z (ndarray) – A two-dimensional array of the output of the map.

Note

This class generates a lookup table from the given input data x, y and z, then performs linear interpolation. The output parameter is z to be calculated as functions from x and y.

evaluate(x, y)[source]#

Evaluate CharMap for x and y inputs.

Parameters:
  • x (float) – Input for first dimension of CharMap.

  • y (float) – Input for second dimension of CharMap.

Returns:

z (float) – Resulting z value.

Note

\[\begin{split}\vec{y} = \vec{y_0} + \frac{x-x_0}{x_1-x_0} \cdot \left(\vec{y_1}-\vec{y_0} \right)\\ \vec{z} = \vec{z1_0} + \frac{x-x_0}{x_1-x_0} \cdot \left(\vec{z_1}-\vec{z_0} \right)\end{split}\]

The index 0 represents the lower and 1 the upper adjacent x-value. Using the y-value as second input dimension the corresponding z-values are calculated, again using linear interpolation.

\[z = z_0 + \frac{y-y_0}{y_1-y_0} \cdot \left(z_1-z_0 \right)\]
evaluate_x(x)[source]#

Evaluate CharMap for x inputs.

Parameters:

x (float) – Input for first dimension of CharMap.

Returns:

  • yarr (ndarray) – Second dimension input array of CharMap calculated from first dimension input.

  • zarr (ndarray) – Output array of CharMap calculated from first dimension input.

evaluate_y(y, yarr, zarr)[source]#

Evaluate CharMap for y inputs.

Parameters:
  • y (float) – Input for second dimension of CharMap.

  • yarr (ndarray) – Second dimension array of CharMap calculated from first dimension input.

  • zarr (ndarray) – Output array of CharMap calculated from first dimension input.

get_attr(key)[source]#

Get the value of an attribute.

Parameters:

key (str) – Object attribute to get value of.

Returns:

value (object) – Value of object attribute key.

get_domain_errors(x, y, c)[source]#

Check the CharMap for bound violations.

Parameters:
  • x (float) – Input for first dimension of CharMap.

  • y (float) – Input for second dimension of CharMap.

get_domain_errors_x(x, c)[source]#

Prompt error message, if operation is out bounds in first dimension.

Parameters:
  • x (float) – Input for first dimension of CharMap.

  • c (str) – Label of the component, the CharMap is applied on.

Returns:

yarr (ndarray) – Second dimension input array of CharMap calculated from first dimension input.

get_domain_errors_y(y, yarr, c)[source]#

Prompt error message, if operation is out bounds in second dimension.

Parameters:
  • y (float) – Input for second dimension of CharMap.

  • yarr (ndarray) – Second dimension input array of CharMap calculated from first dimension input.

  • c (str) – Label of the component, the CharMap is applied on.

plot(path, title, xlabel, ylabel)[source]#
tespy.tools.characteristics.load_custom_char(name, char_type)[source]#

Load a characteristic line of map.

Parameters:
  • name (str) – Name of the characteristics.

  • char_type (class) – Class to be generate the object of.

Returns:

obj (object) – The characteristics (CharLine, CharMap) object.

tespy.tools.characteristics.load_default_char(component, parameter, function_name, char_type)[source]#

Load a characteristic line of map.

Parameters:
  • component (str) – Type of component.

  • parameter (str) – Component parameter using the characteristics.

  • function_name (str) – Name of the characteristics.

  • char_type (class) – Class to generate an instance of.

Returns:

obj (object) – The characteristics (CharLine, CharMap) object.

tespy.tools.data_containers module#

Module for data container classes.

The DataContainer class and its subclasses are used to store component or connection properties.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/data_containers.py

SPDX-License-Identifier: MIT

class tespy.tools.data_containers.ComponentCharacteristicMaps(**kwargs)[source]#

Bases: DataContainer

Data container for characteristic maps.

Parameters:
  • func (tespy.components.characteristics.characteristics) – Function to be applied for this characteristic map, default: None.

  • is_set (boolean) – Should this equation be applied?, default: is_set=False.

  • param (str) – Which parameter should be applied as the x value? default: method=’default’.

static attr()[source]#

Return the available attributes for a ComponentCharacteristicMaps type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.ComponentCharacteristics(**kwargs)[source]#

Bases: DataContainer

Data container for component characteristics.

Parameters:
  • func (tespy.components.characteristics.characteristics) – Function to be applied for this characteristics, default: None.

  • is_set (boolean) – Should this equation be applied?, default: is_set=False.

  • param (str) – Which parameter should be applied as the x value? default: method=’default’.

static attr()[source]#

Return the available attributes for a ComponentCharacteristics type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.ComponentProperties(**kwargs)[source]#

Bases: DataContainer

Data container for component properties.

Parameters:
  • val (float) – Value for this component attribute, default: val=1.

  • val_SI (float) – Value in SI_unit (available for temperatures only, unit transformation according to network’s temperature unit), default: val_SI=0.

  • is_set (boolean) – Has the value for this attribute been set?, default: is_set=False.

  • is_var (boolean) – Is this attribute part of the system variables?, default: is_var=False.

  • d (float) – Interval width for numerical calculation of partial derivative towards this attribute, it is part of the system variables, default d=1e-4.

  • min_val (float) – Minimum value for this attribute, used if attribute is part of the system variables, default: min_val=1.1e-4.

  • max_val (float) – Maximum value for this attribute, used if attribute is part of the system variables, default: max_val=1e12.

static attr()[source]#

Return the available attributes for a ComponentProperties type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.DataContainer(**kwargs)[source]#

Bases: object

The DataContainer is parent class for all data containers.

Parameters:

**kwargs – See the class documentation of desired DataContainer for available keywords.

Note

The initialisation method (__init__), setter method (set_attr) and getter method (get_attr) are used for instances of class DataContainer and its children. TESPy uses different DataContainer classes for specific objectives:

Grouped component properties are used, if more than one component property has to be specified in order to apply one equation, e.g. pressure drop in pipes by specified length, diameter and roughness. If you specify all three of these properties, the DataContainer for the group will be created automatically!

For the full list of available parameters for each data container, see its documentation.

Example

The examples below show the different (sub-)classes of DataContainers available.

>>> from tespy.tools.data_containers import (
... ComponentCharacteristics, ComponentCharacteristicMaps,
... ComponentProperties, FluidComposition, GroupedComponentProperties,
... FluidProperties, SimpleDataContainer)
>>> from tespy.components import Pipe
>>> type(ComponentCharacteristicMaps(is_set=True))
<class 'tespy.tools.data_containers.ComponentCharacteristicMaps'>
>>> type(ComponentCharacteristics(is_set=True, param='m'))
<class 'tespy.tools.data_containers.ComponentCharacteristics'>
>>> type(ComponentProperties(val=100, is_set=True, is_var=True,
...      max_val=1000, min_val=1))
<class 'tespy.tools.data_containers.ComponentProperties'>
>>> pi = Pipe('testpipe', L=100, D=0.5, ks=5e-5)
>>> type(GroupedComponentProperties(
... is_set=True, elements=["L", "D", "ks"]
... ))
<class 'tespy.tools.data_containers.GroupedComponentProperties'>
>>> type(FluidComposition(
... val={'CO2': 0.1, 'H2O': 0.11, 'N2': 0.75, 'O2': 0.03}, is_set={'O2'}
... ))
<class 'tespy.tools.data_containers.FluidComposition'>
>>> type(FluidProperties(val=5, val_SI=500000, is_set=True, unit='bar'))
<class 'tespy.tools.data_containers.FluidProperties'>
>>> type(SimpleDataContainer(val=5, is_set=False))
<class 'tespy.tools.data_containers.SimpleDataContainer'>
static attr()[source]#

Return the available attributes for a DataContainer type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

get_attr(key)[source]#

Get the value of a DataContainer’s attribute.

Parameters:

key (str) – The attribute you want to retrieve.

Returns:

out – Specified attribute.

set_attr(**kwargs)[source]#

Sets, resets or unsets attributes of a DataContainer type object.

Parameters:

**kwargs – See the class documentation of desired DataContainer for available keywords.

class tespy.tools.data_containers.FluidComposition(**kwargs)[source]#

Bases: DataContainer

Data container for fluid composition.

Parameters:
  • val (dict) – Mass fractions of the fluids in a mixture, default: val={}. Pattern for dictionary: keys are fluid name, values are mass fractions.

  • val0 (dict) – Starting values for mass fractions of the fluids in a mixture, default: val0={}. Pattern for dictionary: keys are fluid name, values are mass fractions.

  • is_set (dict) – Which fluid mass fractions have been set, default is_set={}. Pattern for dictionary: keys are fluid name, values are True or False.

  • balance (boolean) – Should the fluid balance equation be applied for this mixture? default: False.

static attr()[source]#

Return the available attributes for a FluidComposition type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.FluidProperties(**kwargs)[source]#

Bases: DataContainer

Data container for fluid properties.

Parameters:
  • val (float) – Value in user specified unit (or network unit) if unit is unspecified, default: val=np.nan.

  • val0 (float) – Starting value in user specified unit (or network unit) if unit is unspecified, default: val0=np.nan.

  • val_SI (float) – Value in SI_unit, default: val_SI=0.

  • is_set (boolean) – Has the value for this property been set? default: is_set=False.

  • unit (str) – Unit for this property, default: ref=None.

  • unit (boolean) – Has the unit for this property been specified manually by the user? default: unit_set=False.

static attr()[source]#

Return the available attributes for a FluidProperties type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.GroupedComponentCharacteristics(**kwargs)[source]#

Bases: DataContainer

Data container for grouped component characteristics.

Parameters:
  • is_set (boolean) – Should the equation for this parameter group be applied? default: is_set=False.

  • elements (list) – Which component properties are part of this component group? default elements=[].

static attr()[source]#

Return the available attributes for a GroupedComponentCharacteristics type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.GroupedComponentProperties(**kwargs)[source]#

Bases: DataContainer

Data container for grouped component parameters.

Parameters:
  • is_set (boolean) – Should the equation for this parameter group be applied? default: is_set=False.

  • method (str) – Which calculation method for this parameter group should be used? default: method=’default’.

  • elements (list) – Which component properties are part of this component group? default elements=[].

static attr()[source]#

Return the available attributes for a GroupedComponentProperties type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.ReferencedFluidProperties(**kwargs)[source]#

Bases: DataContainer

static attr()[source]#

Return the available attributes for a FluidProperties type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

class tespy.tools.data_containers.SimpleDataContainer(**kwargs)[source]#

Bases: DataContainer

Simple data container without data type restrictions to val field.

Parameters:
  • val (no specific datatype) – Value for the property, no predefined datatype.

  • is_set (boolean) – Has the value for this property been set? default: is_set=False.

static attr()[source]#

Return the available attributes for a SimpleDataContainer type object.

Returns:

out (dict) – Dictionary of available attributes (dictionary keys) with default values.

tespy.tools.document_models module#

Module for helper functions used by several other modules.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/document_models.py

SPDX-License-Identifier: MIT

tespy.tools.document_models.create_latex_CharLine(component, param, data, path, group=None)[source]#

Generate image and create LaTeX code for CharLine documentation.

Parameters:
  • component (object) – Component or Bus object the characteristics are applied on.

  • param (str) – Name of the parameter holding the CharLine information.

  • data (tespy.tools.data_containers.ComponentCharacteristics) – DataContainer holding the CharLine information.

  • path (str) – Basepath of the report.

  • group (str) – Name of the group if the parameter is part of a group, else None.

Returns:

latex (str) – LaTeX code for figure.

tespy.tools.document_models.create_latex_CharMap(component, param, data, path, group=None)[source]#

Generate image and create LaTeX code for CharMap documentation.

Parameters:
  • component (object) – Component or Bus object the characteristics are applied on.

  • param (str) – Name of the parameter holding the CharLine information.

  • data (tespy.tools.data_containers.ComponentCharacteristicMaps) – DataContainer holding the CharMap information.

  • path (str) – Basepath of the report.

  • group (str) – Name of the group if the parameter is part of a group, else None.

Returns:

latex (str) – LaTeX code for figure.

tespy.tools.document_models.create_latex_figure(path, caption, label)[source]#

Create LaTeX figure environment.

Parameters:
  • path (str) – Path to the figure.

  • caption (str) – Caption of the figure.

  • label (str) – LaTeX label for the figure.

Returns:

latex (str) – LaTeX code for figure.

tespy.tools.document_models.create_latex_table(df, caption, col_fmt=None)[source]#

Create LaTeX table environment from DataFrame df.

Parameters:
  • df (pandas.core.frame.DataFrame) – DataFrame to export.

  • caption (str) – Caption for the table.

Returns:

latex (str) – LaTeX code for table.

tespy.tools.document_models.data_to_df(data)[source]#

Create pandas DataFrame from list of dictionaries, remove nan columns.

Parameters:

data (list) – Rows for the DataFrame.

Returns:

df (pandas.core.frame.DataFrame) – Polished DataFrame.

tespy.tools.document_models.document_busses(nw, rpt)[source]#

Document bus specifications.

Parameters:
  • nw (tespy.networks.network.Network) – TESPy model.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for all busses.

tespy.tools.document_models.document_components(nw, rpt)[source]#

Document component specifications.

Parameters:
  • nw (tespy.networks.network.Network) – TESPy model.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for all components.

tespy.tools.document_models.document_connection_fluids(df, specs, eqs, c, rpt)[source]#

Document fluid specifications of connections.

Parameters:
  • df (pandas.core.frame.DataFrame) – DataFrame containing the connection fluid data.

  • specs (pandas.core.frame.DataFrame) – DataFrame containing information on model input specifications.

  • eqs (list) – List of parameters to generate equations for.

  • c (tespy.connections.connection.Connection) – Connection object, required for LaTeX equation generation.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for all connections.

tespy.tools.document_models.document_connection_params(nw, df, specs, eqs, c, rpt)[source]#

Document parameter specification of connections.

Parameters:
  • nw (tespy.networks.network.Network) – Network object for unit information.

  • df (pandas.core.frame.DataFrame) – DataFrame containing the connection parameter data.

  • specs (pandas.core.frame.DataFrame) – DataFrame containing information on model input specifications.

  • eqs (list) – List of parameters to generate equations for.

  • c (tespy.connections.connection.Connection) – Connection object, required for LaTeX equation generation.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for all connections.

tespy.tools.document_models.document_connection_ref(df, property, c)[source]#

Document referenced connection properties

Parameters:
  • df (pandas.core.frame.DataFrame) – DataFrame containing the referenced connection data.

  • property (str) – Short name of specified property ('m', 'p', ...).

  • c (tespy.connections.connection.Connection) – Connection object, required for LaTeX equation generation.

Returns:

latex (str) – LaTeX code for all connections.

tespy.tools.document_models.document_connections(nw, rpt)[source]#

Document connection specifications.

Parameters:
  • nw (tespy.networks.network.Network) – TESPy model.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for all connections.

tespy.tools.document_models.document_model(nw, path='report', filename='report.tex', fmt={})[source]#

Generate LaTeX documentation for a TESPy model.

  • The documentation is stored at path/filename

  • Generated figures are stored at path/figures/

Parameters:
  • nw (tespy.networks.network.Network) – Network instance to document.

  • path (str) – Folder for the documentation, default report.

  • filename (str) – Desired filename for the LaTeX document, default report.tex.

  • fmt (dict) – Dictionary for formatting the report, for sample see respective section in online documentation.

tespy.tools.document_models.document_software_info(rpt)[source]#

Get software information.

Parameters:

rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for software information.

tespy.tools.document_models.document_ude(nw, path)[source]#

Document UserDefinedEquation specifications.

Parameters:
  • nw (tespy.networks.network.Network) – TESPy model.

  • path (str) – Folder for the documentation, default report.

Returns:

latex (str) – LaTeX code for all UserDefinedEquations.

tespy.tools.document_models.generate_latex_eq(obj, eqn, label)[source]#

Generate LaTeX code for equations.

Parameters:
  • obj (object) – Object equation is applied for.

  • eqn (str) – LaTeX code of the equation core.

  • label (str) – LaTeX label for the equation.

Returns:

latex (str) – LaTeX code for equation.

tespy.tools.document_models.get_char_specification(component, param, data, path, group=None)[source]#

Get CharLine or CharMap plotting latex code.

Parameters:
  • component (object) – Component or Bus object the characteristics are applied on.

  • param (str) – Name of the parameter holding the CharLine information.

  • data (tespy.tools.data_containers.DataContainer) – DataContainer holding the CharMap or CharLine information.

  • path (str) – Basepath of the report.

  • group (str) – Name of the group if the parameter is part of a group, else None.

Returns:

latex (str) – LaTeX code for characteristic figures.

tespy.tools.document_models.get_component_mandatory_constraints(cp, component_list, path)[source]#

Get latex code for mandatory constraints of component type cp.

Parameters:
  • cp (str) – Classname of the current class.

  • component_list (pandas.core.frame.DataFrame) – DataFrame of the components of Class cp.

  • path (str) – Folder for the documentation, default report.

Returns:

latex (str) – LaTeX code for mandatory component constraints.

tespy.tools.document_models.get_component_specifications(nw, cp, rpt)[source]#

Get latex code for component specifications of component type cp.

Parameters:
  • cp (str) – Classname of the current class.

  • component_list (pandas.core.frame.DataFrame) – DataFrame of the components of Class cp.

  • rpt (dict) – Formatting data for the report.

Returns:

latex (str) – LaTeX code for component parameter specification.

tespy.tools.document_models.place_figures(figures)[source]#

Generate LaTeX code for figure placement.

Parameters:

figures (list) – List holding LaTeX code of individual figures to be placed in document.

Returns:

latex (str) – LaTeX code for figure alignment.

tespy.tools.document_models.set_defaults(nw)[source]#

Set up defaults for report formatting.

Parameters:

nw (tespy.networks.network.Network) – TESPy Network instance.

Returns:

rpt (dict) – Dictionary containting the default formatting data.

tespy.tools.fluid_properties.functions module#

Module for fluid property functions.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/fluid_properties/functions.py

SPDX-License-Identifier: MIT

tespy.tools.fluid_properties.functions.Q_mix_ph(p, h, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.T_mix_ph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.T_mix_ps(p, s, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.T_sat_p(p, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.calc_chemical_exergy(pamb, Tamb, fluid_data, Chem_Ex, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.calc_physical_exergy(h, s, p, pamb, Tamb, fluid_data, mixing_rule=None, T0=None)[source]#

Calculate specific physical exergy.

Physical exergy is allocated to a thermal and a mechanical share according to [26].

Parameters:
  • pamb (float) – Ambient pressure p0 / Pa.

  • Tamb (float) – Ambient temperature T0 / K.

Returns:

e_ph (tuple) – Specific thermal and mechanical exergy (\(e^\mathrm{T}\), \(e^\mathrm{M}\)) in J / kg.

\[ \begin{align}\begin{aligned}e^\mathrm{T} = \left( h - h \left( p, T_0 \right) \right) - T_0 \cdot \left(s - s\left(p, T_0\right)\right)\\e^\mathrm{M}=\left(h\left(p,T_0\right)-h\left(p_0,T_0\right)\right) -T_0\cdot\left(s\left(p, T_0\right)-s\left(p_0,T_0\right)\right)\\e^\mathrm{PH} = e^\mathrm{T} + e^\mathrm{M}\end{aligned}\end{align} \]

tespy.tools.fluid_properties.functions.dT_mix_dph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.dT_mix_pdh(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.dT_mix_ph_dfluid(p, h, fluid, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.dT_sat_dp(p, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.dh_mix_dpQ(p, Q, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.dv_mix_dph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.dv_mix_pdh(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.h_mix_pQ(p, Q, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.h_mix_pT(p, T, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.isentropic(p_1, h_1, p_2, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.p_sat_T(T, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.s_mix_pT(p, T, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.s_mix_ph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.v_mix_pT(p, T, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.v_mix_ph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#
tespy.tools.fluid_properties.functions.viscosity_mix_pT(p, T, fluid_data, mixing_rule=None)[source]#
tespy.tools.fluid_properties.functions.viscosity_mix_ph(p, h, fluid_data, mixing_rule=None, T0=None)[source]#

tespy.tools.fluid_properties.helpers module#

Module for fluid property helper functions.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/fluid_properties/helpers.py

SPDX-License-Identifier: MIT

tespy.tools.fluid_properties.helpers.blasius(re)[source]#

Calculate friction coefficient according to Blasius.

Parameters:

re (float) – Reynolds number.

Returns:

darcy_friction_factor (float) – Darcy friction factor.

tespy.tools.fluid_properties.helpers.calc_molar_mass_mixture(fluid_data, molar_fractions)[source]#
tespy.tools.fluid_properties.helpers.colebrook(reynolds, ks, diameter, darcy_friction_factor, **kwargs)[source]#

Calculate friction coefficient accroding to Colebrook-White equation.

Applied in transition zone and rough conditions.

Parameters:
  • re (float) – Reynolds number.

  • ks (float) – Equivalent sand roughness.

  • d (float) – Pipe’s diameter.

  • darcy_friction_factor (float) – Darcy friction factor.

Returns:

darcy_friction_factor (float) – Darcy friction factor.

tespy.tools.fluid_properties.helpers.darcy_friction_factor(re, ks, d)[source]#

Calculate the Darcy friction factor.

Parameters:
  • re (float) – Reynolds number re / 1.

  • ks (float) – Pipe roughness ks / m.

  • d (float) – Pipe diameter/characteristic lenght d / m.

Returns:

darcy_friction_factor (float) – Darcy friction factor \(\lambda\) / 1

Note

Laminar flow (\(re \leq 2320\))

\[\lambda = \frac{64}{re}\]

turbulent flow (\(re > 2320\))

hydraulically smooth: \(\frac{re \cdot k_{s}}{d} < 65\)

\[\begin{split}\lambda = \begin{cases} 0.03164 \cdot re^{-0.25} & re \leq 10^4\\ \left(1.8 \cdot \log \left(re\right) -1.5 \right)^{-2} & 10^4 < re < 10^6\\ solve \left(0 = 2 \cdot \log\left(re \cdot \sqrt{\lambda} \right) -0.8 - \frac{1}{\sqrt{\lambda}}\right) & re \geq 10^6\\ \end{cases}\end{split}\]

transition zone and hydraulically rough:

\[\lambda = solve \left( 0 = 2 \cdot \log \left( \frac{2.51}{re \cdot \sqrt{\lambda}} + \frac{k_{s}}{d \cdot 3.71} \right) - \frac{1}{\sqrt{\lambda}} \right)\]

Reference: [27].

Example

Calculate the Darcy friction factor at different hydraulic states.

>>> from tespy.tools.fluid_properties.helpers import darcy_friction_factor
>>> ks = 5e-5
>>> d = 0.05
>>> re_laminar = 2000
>>> re_turb_smooth = 5000
>>> re_turb_trans = 70000
>>> re_high = 1000000
>>> d_high = 0.8
>>> re_very_high = 6000000
>>> d_very_high = 1
>>> ks_low = 1e-5
>>> ks_rough = 1e-3
>>> darcy_friction_factor(re_laminar, ks, d)
0.032
>>> round(darcy_friction_factor(re_turb_smooth, ks, d), 3)
0.038
>>> round(darcy_friction_factor(re_turb_trans, ks, d), 3)
0.023
>>> round(darcy_friction_factor(re_turb_trans, ks_rough, d), 3)
0.049
>>> round(darcy_friction_factor(re_high, ks, d_high), 3)
0.012
>>> round(darcy_friction_factor(re_very_high, ks_low, d_very_high), 3)
0.009
tespy.tools.fluid_properties.helpers.fluid_structure(fluid)[source]#

Return the checmical formula of fluid.

Parameters:

fluid (str) – Name of the fluid.

Returns:

parts (dict) – Dictionary of the chemical base elements as keys and the number of atoms in a molecule as values.

Example

Get the chemical formula of methane.

>>> from tespy.tools.fluid_properties.helpers import fluid_structure
>>> elements = fluid_structure('methane')
>>> elements['C'], elements['H']
(1, 4)
tespy.tools.fluid_properties.helpers.get_mixture_temperature_range(fluid_data)[source]#
tespy.tools.fluid_properties.helpers.get_molar_fractions(fluid_data)[source]#
tespy.tools.fluid_properties.helpers.get_number_of_fluids(fluid_data)[source]#
tespy.tools.fluid_properties.helpers.get_pure_fluid(fluid_data)[source]#
tespy.tools.fluid_properties.helpers.hanakov(re)[source]#

Calculate friction coefficient according to Hanakov.

Parameters:

re (float) – Reynolds number.

Returns:

darcy_friction_factor (float) – Darcy friction factor.

tespy.tools.fluid_properties.helpers.inverse_temperature_mixture(p=None, target_value=None, fluid_data=None, T0=None, f=None)[source]#
tespy.tools.fluid_properties.helpers.prandtl_karman(reynolds, darcy_friction_factor, **kwargs)[source]#

Calculate friction coefficient according to Prandtl and v. Kármán.

Applied in smooth conditions.

Parameters:
  • re (float) – Reynolds number.

  • darcy_friction_factor (float) – Darcy friction factor.

Returns:

darcy_friction_factor (float) – Darcy friction factor.

tespy.tools.fluid_properties.helpers.prandtl_karman_derivative(reynolds, darcy_friction_factor, **kwargs)[source]#

Calculate derivative for Prandtl and v. Kármán equation.

tespy.tools.fluid_properties.helpers.single_fluid(fluid_data)[source]#

Return the name of the pure fluid in a fluid vector.

tespy.tools.fluid_properties.mixtures module#

Module for fluid property mixture routines.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/fluid_properties/mixtures.py

SPDX-License-Identifier: MIT

tespy.tools.fluid_properties.mixtures.cond_check(p, T, fluid_data, water_alias)[source]#

Check if water is partially condensing in gaseous mixture.

Parameters:
  • y_i (dict) – Mass specific fluid composition.

  • x_i (dict) – Mole specific fluid composition.

  • p (float) – Pressure of mass flow.

  • n (float) – Molar mass flow.

  • T (float) – Temperature of mass flow.

Returns:

tuple – Tuple containing gas phase mass specific and molar specific compositions and overall liquid water mass fraction.

tespy.tools.fluid_properties.mixtures.exergy_chemical_ideal_cond(pamb, Tamb, fluid_data, Chem_Ex)[source]#
tespy.tools.fluid_properties.mixtures.h_mix_pT_forced_gas(p, T, fluid_data, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.h_mix_pT_ideal(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.h_mix_pT_ideal_cond(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.h_mix_pT_incompressible(p, T, fluid_data, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.s_mix_pT_ideal(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.s_mix_pT_ideal_cond(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.s_mix_pT_incompressible(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.v_mix_pT_ideal(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.v_mix_pT_ideal_cond(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.v_mix_pT_incompressible(p=None, T=None, fluid_data=None, **kwargs)[source]#
tespy.tools.fluid_properties.mixtures.viscosity_mix_pT_ideal(p=None, T=None, fluid_data=None, **kwargs)[source]#

Calculate dynamic viscosity from pressure and temperature.

Parameters:
  • flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.

  • T (float) – Temperature T / K.

Returns:

visc (float) – Dynamic viscosity visc / Pa s.

Note

Calculation for fluid mixtures.

\[\begin{split}\eta_{mix}(p,T)=\frac{\sum_{i} \left( \eta(p,T,fluid_{i}) \cdot y_{i} \cdot \sqrt{M_{i}} \right)} {\sum_{i} \left(y_{i} \cdot \sqrt{M_{i}} \right)}\; \forall i \in \text{fluid components}\\ y: \text{volume fraction}\\ M: \text{molar mass}\end{split}\]

Reference: [28].

tespy.tools.fluid_properties.mixtures.viscosity_mix_pT_incompressible(p=None, T=None, fluid_data=None, **kwargs)[source]#

tespy.tools.fluid_properties.wrappers module#

Module for fluid property wrappers.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/fluid_properties/wrappers.py

SPDX-License-Identifier: MIT

class tespy.tools.fluid_properties.wrappers.CoolPropWrapper(fluid, back_end=None)[source]#

Bases: FluidPropertyWrapper

Q_ph(p, h)[source]#
T_ph(p, h)[source]#
T_ps(p, s)[source]#
T_sat(p)[source]#
d_QT(Q, T)[source]#
d_pT(p, T)[source]#
d_ph(p, h)[source]#
get_T_max(p)[source]#
h_QT(Q, T)[source]#
h_pQ(p, Q)[source]#
h_pT(p, T)[source]#
h_ps(p, s)[source]#
isentropic(p_1, h_1, p_2)[source]#
p_sat(T)[source]#
s_QT(Q, T)[source]#
s_pT(p, T)[source]#
s_ph(p, h)[source]#
viscosity_pT(p, T)[source]#
viscosity_ph(p, h)[source]#
class tespy.tools.fluid_properties.wrappers.FluidPropertyWrapper(fluid, back_end=None)[source]#

Bases: object

Q_ph(p, h)[source]#
T_ph(p, h)[source]#
T_ps(p, s)[source]#
T_sat(p)[source]#
d_QT(Q, T)[source]#
d_pT(p, T)[source]#
d_ph(p, h)[source]#
h_QT(Q, T)[source]#
h_pT(p, T)[source]#
isentropic(p_1, h_1, p_2)[source]#
p_sat(T)[source]#
s_QT(Q, T)[source]#
s_pT(p, T)[source]#
s_ph(p, h)[source]#
viscosity_pT(p, T)[source]#
viscosity_ph(p, h)[source]#
class tespy.tools.fluid_properties.wrappers.IAPWSWrapper(fluid, back_end=None)[source]#

Bases: FluidPropertyWrapper

Q_ph(p, h)[source]#
T_ph(p, h)[source]#
T_ps(p, s)[source]#
T_sat(p)[source]#
d_QT(Q, T)[source]#
d_pT(p, T)[source]#
d_ph(p, h)[source]#
h_QT(Q, T)[source]#
h_pQ(p, Q)[source]#
h_pT(p, T)[source]#
h_ps(p, s)[source]#
isentropic(p_1, h_1, p_2)[source]#
p_sat(T)[source]#
s_QT(Q, T)[source]#
s_pT(p, T)[source]#
s_ph(p, h)[source]#
viscosity_pT(p, T)[source]#
viscosity_ph(p, h)[source]#
class tespy.tools.fluid_properties.wrappers.PyromatWrapper(fluid, back_end=None)[source]#

Bases: FluidPropertyWrapper

Q_ph(p, h)[source]#
T_boiling(p)[source]#
T_ph(p, h)[source]#
T_ps(p, s)[source]#
d_QT(Q, T)[source]#
d_pT(p, T)[source]#
d_ph(p, h)[source]#
h_QT(Q, T)[source]#
h_pT(p, T)[source]#
h_ps(p, s)[source]#
isentropic(p_1, h_1, p_2)[source]#
p_boiling(T)[source]#
s_QT(Q, T)[source]#
s_pT(p, T)[source]#
s_ph(p, h)[source]#
class tespy.tools.fluid_properties.wrappers.SerializableAbstractState(back_end, fluid_name)[source]#

Bases: AbstractState

tespy.tools.helpers module#

Module for helper functions used by several other modules.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/helpers.py

SPDX-License-Identifier: MIT

exception tespy.tools.helpers.TESPyComponentError[source]#

Bases: Exception

Custom message for component related errors.

exception tespy.tools.helpers.TESPyConnectionError[source]#

Bases: Exception

Custom message for connection related errors.

exception tespy.tools.helpers.TESPyNetworkError[source]#

Bases: Exception

Custom message for network related errors.

class tespy.tools.helpers.UserDefinedEquation(label, func, deriv, conns, params={}, latex={})[source]#

Bases: object

numeric_deriv(dx, conn)[source]#

Calculate partial derivative of the user defined function to dx.

For details see tespy.tools.helpers._numeric_deriv()

solve()[source]#
tespy.tools.helpers.bus_char_derivative(component_value, char_func, reference_value, bus_value, **kwargs)[source]#

Calculate derivative for bus char evaluation.

tespy.tools.helpers.bus_char_evaluation(component_value, char_func, reference_value, bus_value, **kwargs)[source]#

Calculate the value of a bus.

Parameters:
  • comp_value (float) – Value of the energy transfer at the component.

  • reference_value (float) – Value of the bus in reference state.

  • char_func (tespy.tools.characteristics.char_line) – Characteristic function of the bus.

Returns:

residual (float) – Residual of the equation.

\[residual = \dot{E}_\mathrm{bus} - \frac{\dot{E}_\mathrm{component}} {f\left(\frac{\dot{E}_\mathrm{bus}} {\dot{E}_\mathrm{bus,ref}}\right)}\]

tespy.tools.helpers.central_difference(function=None, parameter=None, delta=None, **kwargs)[source]#
tespy.tools.helpers.convert_from_SI(property, SI_value, unit)[source]#

Get a value in the network’s unit system from SI value.

Parameters:
  • property (str) – Fluid property to convert.

  • SI_value (float) – SI value to convert.

  • unit (str) – Unit of the value.

Returns:

value (float) – Specified fluid property value in network’s unit system.

tespy.tools.helpers.convert_to_SI(property, value, unit)[source]#

Convert a value to its SI value.

Parameters:
  • property (str) – Fluid property to convert.

  • value (float) – Value to convert.

  • unit (str) – Unit of the value.

Returns:

SI_value (float) – Specified fluid property in SI value.

tespy.tools.helpers.extend_basic_path(subfolder)[source]#

Return a path based on the basic tespy path and creates it if necessary.

The subfolder is the name of the path extension.

tespy.tools.helpers.fluidalias_in_list(fluid, fluid_list)[source]#
tespy.tools.helpers.get_all_subdictionaries(data)[source]#
tespy.tools.helpers.get_basic_path()[source]#

Return the basic tespy path and creates it if necessary.

The basic path is the ‘.tespy’ folder in the $HOME directory.

tespy.tools.helpers.get_chem_ex_lib(name)[source]#

Return a new dictionary by merging two dictionaries recursively.

tespy.tools.helpers.latex_unit(unit)[source]#

Convert unit to LaTeX.

Parameters:

unit (str) – Value of unit for input, e.g. m3 / kg.

Returns:

unit (str) – Value of unit for output, e.g. $unitfrac{m3}{kg}$.

tespy.tools.helpers.merge_dicts(dict1, dict2)[source]#

Return a new dictionary by merging two dictionaries recursively.

tespy.tools.helpers.modify_path_os(path)[source]#

Modify a path according the os.

Also detects weather the path specification is absolute or relative and adjusts the path respectively.

Parameters:

path (str) – Path to modify.

Returns:

path (str) – Modified path.

tespy.tools.helpers.newton_with_kwargs(derivative, target_value, val0=300, valmin=70, valmax=3000, max_iter=10, tol_rel=1e-06, tol_abs=1e-12, tol_mode='rel', **function_kwargs)[source]#

tespy.tools.logger module#

Module for logging specification.

This file is part of project TESPy (github.com/oemof/tespy). It’s copyrighted by the contributors recorded in the version control history of the file, available from its original location tespy/tools/logger.py

SPDX-License-Identifier: MIT

class tespy.tools.logger.FutureWarningHandler(logger)[source]#

Bases: object

tespy.tools.logger.add_console_logging(logformat=None, logdatefmt='%H:%M:%S', loglevel=20, log_the_version=True)[source]#

Initialise customizable console logger.

Parameters:
  • logformat (str) – Format of the screen output. Default: “%(asctime)s-%(levelname)s-%(message)s”

  • logdatefmt (str) – Format of the datetime in the screen output. Default: “%H:%M:%S”

  • loglevel (int) – Level of logging to stdout. Default: 20 (logging.INFO)

  • log_the_version (boolean) – If True, version information is logged while initialising the logger.

tespy.tools.logger.add_file_logging(logpath=None, logfile=None, logrotation=None, logformat=None, logdatefmt=None, loglevel=10, log_the_version=True, log_the_path=True)[source]#

Initialise customisable file logger.

Parameters:
  • logpath (str) – The path for log files. By default a “.tespy’ folder is created in your home directory with subfolder called ‘log_files’.

  • logfile (str) – Name of the log file, default: tespy.log

  • logrotation (dict) – Option to pass parameters to the TimedRotatingFileHandler.

  • logformat (str) – Format of the file output. Default: “%(asctime)s - %(levelname)s - %(module)s - %(message)s”

  • logdatefmt (str) – Format of the datetime in the file output. Default: None

  • loglevel (int) – Level of logging to file. Default: 10 (logging.DEBUG)

  • log_the_version (boolean) – If True, version information is logged while initialising the logger.

  • log_the_path (boolean) – If True, the used file path is logged while initialising the logger.

Returns:

file (str) – Place where the log file is stored.

tespy.tools.logger.check_git_branch()[source]#

Pass the used branch and commit to the logger.

The following test reacts on a local system different than on Travis-CI. Therefore, a try/except test is created.

Example

>>> from tespy import logger
>>> try:
...    v = logger.check_git_branch()
... except FileNotFoundError:
...    v = 'dsfafasdfsdf'
>>> type(v)
<class 'str'>
tespy.tools.logger.check_version()[source]#

Return the actual version number of the used TESPy version.

Example

>>> from tespy.tools import logger
>>> v = logger.check_version()
>>> int(v.split('.')[0])
0
tespy.tools.logger.critical(msg, *args, **kwargs)[source]#

Log ‘msg % args’ with severity ‘CRITICAL’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

critical(“Houston, we have a %s”, “major disaster”, exc_info=1)

tespy.tools.logger.debug(msg, *args, **kwargs)[source]#

Log ‘msg % args’ with severity ‘DEBUG’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

debug(“Houston, we have a %s”, “thorny problem”, exc_info=1)

tespy.tools.logger.define_logging(logpath=None, logfile='tespy.log', file_format=None, screen_format=None, file_datefmt=None, screen_datefmt=None, screen_level=20, file_level=10, log_the_version=True, log_the_path=True, timed_rotating=None)[source]#

Initialise customisable logger.

Parameters:
  • logpath (str) – The path for log files. By default a “.tespy’ folder is created in your home directory with subfolder called ‘log_files’.

  • logfile (str) – Name of the log file, default: tespy.log

  • file_format (str) – Format of the file output. Default: “%(asctime)s - %(levelname)s - %(module)s - %(message)s”

  • screen_format (str) – Format of the screen output. Default: “%(asctime)s-%(levelname)s-%(message)s”

  • file_datefmt (str) – Format of the datetime in the file output. Default: None

  • screen_datefmt (str) – Format of the datetime in the screen output. Default: “%H:%M:%S”

  • screen_level (int) – Level of logging to stdout. Default: 20 (logging.INFO)

  • file_level (int) – Level of logging to file. Default: 10 (logging.DEBUG)

  • log_the_version (boolean) – If True the actual version or commit is logged while initialising the logger.

  • log_the_path (boolean) – If True the used file path is logged while initialising the logger.

  • timed_rotating (dict) – Option to pass parameters to the TimedRotatingFileHandler.

Returns:

file (str) – Place where the log file is stored.

Notes

By default the INFO level is printed on the screen and the DEBUG level in a file, but you can easily configure the logger. Every module that wants to create logging messages has to import the logger.

Examples

To define the default logger you have to import the python logging library and this function. The first logging message should be the path where the log file is saved to.

>>> import logging
>>> from tespy.tools import logger
>>> mypath = logger.define_logging(
...     log_the_path=True, log_the_version=True, timed_rotating={'backupCount': 4},
...     screen_level=logging.ERROR, screen_datefmt = "no_date"
... )
>>> mypath[-9:]
'tespy.log'
>>> logger.debug('Hi')
tespy.tools.logger.error(msg, *args, **kwargs)[source]#

Log ‘msg % args’ with severity ‘ERROR’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

error(“Houston, we have a %s”, “major problem”, exc_info=1)

tespy.tools.logger.exception(msg, *args, exc_info=True, **kwargs)[source]#

Convenience method for logging an ERROR with exception information.

tespy.tools.logger.get_logger()[source]#
tespy.tools.logger.get_version()[source]#

Return a string part of the used version.

If the commit and the branch is available the commit and the branch will b returned otherwise the version number.

Example

>>> from tespy.tools import logger
>>> v = logger.get_version()
>>> type(v)
<class 'str'>
tespy.tools.logger.increment_stacklevel(kwargs)[source]#

“Method to force the logging framework to trace past this file

tespy.tools.logger.info(msg, *args, **kwargs)[source]#

Log ‘msg % args’ with severity ‘INFO’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

info(“Houston, we have a %s”, “interesting problem”, exc_info=1)

tespy.tools.logger.log(level, msg, *args, **kwargs)[source]#

Log ‘msg % args’ with the integer severity ‘level’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

log(level, “We have a %s”, “mysterious problem”, exc_info=1)

tespy.tools.logger.progress(value, msg, *args, **kwargs)[source]#

Report progress values between 0 and 100, you can also use the extra dict to modify the progress limits. Additionally, log ‘msg % args’ with severity ‘TESPY_PROGRESS_LOG_LEVEL’.

progress(51, “Houston, we have completed step %d of 100.”, 51) progress(0.51, “Houston, we have completed %f percent of the mission.”, 0.51*100, extra=dict(progress_min=0.0, progress_max=1.0))

tespy.tools.logger.result(msg, *args, **kwargs)[source]#

Report result values by logging ‘msg % args’ with severity ‘TESPY_RESULT_LOG_LEVEL’.

result(“The result is %f”, 1.23456)

tespy.tools.logger.warning(msg, *args, **kwargs)[source]#

Log ‘msg % args’ with severity ‘WARNING’.

To pass exception information, use the keyword argument exc_info with a true value, e.g.

warning(“Houston, we have a %s”, “bit of a problem”, exc_info=1)

tespy.tools.optimization module#

class tespy.tools.optimization.OptimizationProblem(model, variables={}, constraints={}, objective='objective')[source]#

Bases: object

The OptimizationProblem handles the optimization.

  • Set up the optimization problems by specifying constraints, upper and lower bounds for the decision variables and selection of the objective function.

  • Run the optimization, see tespy.tools.optimization.OptimizationProblem.run().

  • Provide the optimization results DataFrame in the .individuals attribute of the OptimizationProblem class.

Parameters:
  • model (custom class) – Object of some class, which provides all the methods required by the optimization suite, see the Example section for a downloadable template of the implementation.

  • variables (dict) – Dictionary containing the decision variables and their respective bounds.

  • constraints (dict) – Dictionary containing the constraints for the model.

  • objective (str) – Name of the objective. objective is passed to the get_objective method of your tespy model instance.

Note

For the required structure of the input dictionaries see the example in below.

Installation of pygmo via pip is not available for Windows and OSX users currently. Please use conda instead or refer to their documentation.

Example

For an example please go to the tutorials section of TESPy’s online documentation.

collect_constraints(border, build=False)[source]#

Collect the constraints

Parameters:
  • border (str) – “upper” or “lower”, determine which constraints to collect.

  • build (bool, optional) – If True, the constraints are evaluated and returned, by default False

Returns:

tuple – Return the upper and lower constraints evaluation lists.

fitness(x)[source]#

Evaluate the fitness function of an individual.

Parameters:

x (list) – List of the decision variables’ values of the current individual.

Returns:

fitness (list) – A list containing the fitness function evaluation as well as the evaluation of the upper and lower constraints.

get_bounds()[source]#

Return bounds of decision variables.

get_nic()[source]#

Return number of inequality constraints.

get_nobj()[source]#

Return number of objectives.

run(algo, pop, num_ind, num_gen)[source]#

Run the optimization algorithm.

Parameters:
  • algo (pygmo.core.algorithm) – PyGMO optimization algorithm.

  • pop (pygmo.core.population) – PyGMO population.

  • num_ind (int) – Number of individuals.

  • num_gen (int) – Number of generations.