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)[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.
- evaluate_busses(cp)[source]#
Evaluate the exergy balances of busses.
- Parameters
cp (tespy.components.component.Component) – Component to analyse the bus exergy balance of.
- generate_plotly_sankey_input(node_order=[], colors={}, display_thresold=0.001)[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
In case no colors are passed, the matplotlib
Set1
colormap will be applied.
- 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.
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 bex = [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
isFalse
(default) and the x-value is outside of the specified range, the function will return the values at the corresponding boundary. Ifextrapolate
isTrue
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.
- 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 and1
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.
- 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’.
- 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’.
- 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.
- 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 differentDataContainer
classes for specific objectives:component characteristics
tespy.tools.data_containers.ComponentCharacteristics
component characteristic maps
tespy.tools.data_containers.ComponentCharacteristicMaps
component properties
tespy.tools.data_containers.ComponentProperties
grouped component properites
tespy.tools.data_containers.GroupedComponentProperties
fluid composition
tespy.tools.data_containers.FluidComposition
fluid properties
tespy.tools.data_containers.FluidProperties
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, DataContainerSimple) >>> 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=[pi.L, pi.D, pi.ks], method='default')) <class 'tespy.tools.data_containers.GroupedComponentProperties'> >>> type(FluidComposition( ... val={'CO2': 0.1, 'H2O': 0.11, 'N2': 0.75, 'O2': 0.03}, ... val_set={'CO2': False, 'H2O': False, 'N2': False, 'O2': True}, ... balance=False)) <class 'tespy.tools.data_containers.FluidComposition'> >>> type(FluidProperties(val=5, val_SI=500000, val_set=True, unit='bar', ... ref=None, ref_set=False)) <class 'tespy.tools.data_containers.FluidProperties'> >>> type(DataContainerSimple(val=5, is_set=False)) <class 'tespy.tools.data_containers.DataContainerSimple'>
- static attr()[source]#
Return the available attributes for a DataContainer type object.
- Returns
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- class tespy.tools.data_containers.DataContainerSimple(**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: val_set=False.
- 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.
val_set (dict) – Which fluid mass fractions have been set, default val_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.
- 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.
val_set (boolean) – Has the value for this property been set? default: val_set=False.
ref (tespy.connections.ref) – Reference object, default: ref=None.
ref_set (boolean) – Has a value for this property been referenced to another connection? default: ref_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.
- 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=[].
- 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=[].
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.fluid_properties module#
Module for fluid property integration.
TESPy uses the CoolProp python interface for all 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.py
SPDX-License-Identifier: MIT
- class tespy.tools.fluid_properties.Memorise[source]#
Bases:
object
Memorization of fluid properties.
- T_ph = {}#
- T_ps = {}#
- static add_fluids(fluids, memorise_fluid_properties=True)[source]#
Add list of fluids to fluid memorisation class.
Generate arrays for fluid property lookup if memorisation is activated.
Calculate/set fluid property value ranges for convergence checks.
- Parameters
fluids (dict) – Dict of fluid and corresponding CoolProp back end for fluid property memorization.
memorise_fluid_properties (boolean) – Activate or deactivate fluid property value memorisation. Default state is activated (
True
).
Note
The Memorise class creates globally accessible variables for different fluid property calls as dictionaries:
T(p,h)
T(p,s)
v(p,h)
visc(p,h)
s(p,h)
Each dictionary uses the list of fluids passed to the Memorise class as identifier for the fluid property memorisation. The fluid properties are stored as numpy array, where each column represents the mass fraction of the respective fluid and the additional columns are the values for the fluid properties. The fluid property function will then look for identical fluid property inputs (p, h, (s), fluid mass fraction). If the inputs are in the array, the first column of that row is returned, see example.
Example
T(p,h) for set of fluids (‘water’, ‘air’):
row 1: [282.64527752319697, 10000, 40000, 1, 0]
row 2: [284.3140698256616, 10000, 47000, 1, 0]
- back_end = {}#
- static del_memory(fluids)[source]#
Delete non frequently used fluid property values from memorise class.
- Parameters
fluids (list) – List of fluid for fluid property memorization.
- s_ph = {}#
- state = {}#
- v_ph = {}#
- value_range = {}#
- visc_ph = {}#
- tespy.tools.fluid_properties.Q_ph(p, h, fluid)[source]#
Calculate vapor mass fraction from pressure and enthalpy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
h (float) – Specific enthalpy h / (J/kg).
fluid (str) – Fluid name.
- Returns
x (float) – Vapor mass fraction.
- tespy.tools.fluid_properties.T_bp_p(flow)[source]#
Calculate temperature from boiling point pressure.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
T (float) – Temperature at boiling point.
Note
This function works for pure fluids only!
- tespy.tools.fluid_properties.T_mix_ph(flow, T0=675)[source]#
Calculate the temperature from pressure and enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
T (float) – Temperature T / K.
Note
First, check if fluid property has been memorised already. If this is the case, return stored value, otherwise calculate value and store it in the memorisation class.
Uses CoolProp interface for pure fluids, newton algorithm for mixtures:
\[ \begin{align}\begin{aligned}\begin{split}T_{mix}\left(p,h\right) = T_{i}\left(p,h_{i}\right)\; \forall i \in \text{fluid components}\\\end{split}\\\begin{split}h_{i} = h \left(pp_{i}, T_{mix} \right)\\ pp: \text{partial pressure}\end{split}\end{aligned}\end{align} \]
- tespy.tools.fluid_properties.T_mix_ps(flow, s, T0=675)[source]#
Calculate the temperature from pressure and entropy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
s (float) – Entropy of flow in J / (kgK).
- Returns
T (float) – Temperature T / K.
Note
First, check if fluid property has been memorised already. If this is the case, return stored value, otherwise calculate value and store it in the memorisation class.
Uses CoolProp interface for pure fluids, newton algorithm for mixtures:
\[ \begin{align}\begin{aligned}\begin{split}T_{mix}\left(p,s\right) = T_{i}\left(p,s_{i}\right)\; \forall i \in \text{fluid components}\\\end{split}\\\begin{split}s_{i} = s \left(pp_{i}, T_{mix} \right)\\ pp: \text{partial pressure}\end{split}\end{aligned}\end{align} \]
- tespy.tools.fluid_properties.T_ph(p, h, fluid)[source]#
Calculate the temperature from pressure and enthalpy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
h (float) – Specific enthalpy h / (J/kg).
fluid (str) – Fluid name.
- Returns
T (float) – Temperature T / K.
- tespy.tools.fluid_properties.T_ps(p, s, fluid)[source]#
Calculate the temperature from pressure and entropy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
s (float) – Specific entropy h / (J/(kgK)).
fluid (str) – Fluid name.
- Returns
T (float) – Temperature T / K.
- tespy.tools.fluid_properties.calc_physical_exergy(conn, p0, T0)[source]#
Calculate specific physical exergy.
Physical exergy is allocated to a thermal and a mechanical share according to [22].
- Parameters
conn (tespy.connections.connection.Connection) – Connection to calculate specific physical exergy for.
p0 (float) – Ambient pressure p0 / Pa.
T0 (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.cond_check(y_i, x_i, p, n, T)[source]#
_summary_
- 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) – Temperatrure of mass flow.
- Returns
tuple – Tuple containing gasphase mass specific and molar specific compositions and overall liquid water mass fraction.
- tespy.tools.fluid_properties.dT_bp_dp(flow)[source]#
Calculate partial derivate of temperature to boiling point pressure.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dT / dp (float) – Partial derivative of temperature to boiling point pressure in K / Pa.
\[\begin{split}\frac{\partial h_{mix}}{\partial p} = \frac{T_{bp}(p+d)-T_{bp}(p-d)}{2 \cdot d}\\ Q: \text{vapour mass fraction}\end{split}\]
Note
This works for pure fluids only!
- tespy.tools.fluid_properties.dT_mix_dph(flow, T0=675)[source]#
Calculate partial derivate of temperature to pressure.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dT / dp (float) – Partial derivative of temperature to pressure dT /dp / (K/Pa).
\[\frac{\partial T_{mix}}{\partial p} = \frac{T_{mix}(p+d,h)- T_{mix}(p-d,h)}{2 \cdot d}\]
- tespy.tools.fluid_properties.dT_mix_pdh(flow, T0=675)[source]#
Calculate partial derivate of temperature to enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dT / dh (float) – Partial derivative of temperature to enthalpy dT /dh / ((kgK)/J).
\[\frac{\partial T_{mix}}{\partial h} = \frac{T_{mix}(p,h+d)- T_{mix}(p,h-d)}{2 \cdot d}\]
- tespy.tools.fluid_properties.dT_mix_ph_dfluid(flow, T0=675)[source]#
Calculate partial derivate of temperature to fluid composition.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dT / dfluid (ndarray) – Partial derivatives of temperature to fluid composition dT / dfluid / K.
\[\frac{\partial T_{mix}}{\partial fluid_{i}} = \frac{T_{mix}(p,h,fluid_{i}+d)- T_{mix}(p,h,fluid_{i}-d)}{2 \cdot d}\]
- tespy.tools.fluid_properties.d_mix_pT(flow, T)[source]#
Calculate the density from pressure and temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature T / K.
- Returns
d (float) – Density d / (kg/\(\mathrm{m}^3\)).
Note
Calculation for fluid mixtures.
\[\rho_{mix}\left(p,T\right)=\frac{1}{v_{mix}\left(p,T\right)}\]
- tespy.tools.fluid_properties.d_pT(p, T, fluid)[source]#
Calculate the density from pressure and temperature for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
T (float) – Temperature T / K.
fluid (str) – Fluid name.
- Returns
d (float) – Density d / (kg/\(\mathrm{m}^3\)).
- tespy.tools.fluid_properties.d_ph(p, h, fluid)[source]#
Calculate the density from pressure and enthalpy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
h (float) – Specific enthalpy h / (J/kg).
fluid (str) – Fluid name.
- Returns
d (float) – Density d / (kg/\(\mathrm{m}^3\)).
- tespy.tools.fluid_properties.dh_mix_dpQ(flow, Q)[source]#
Calculate partial derivate of enthalpy to vapour mass fraction.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
Q (float) – Vapour mass fraction Q / 1.
- Returns
dh / dQ (float) – Partial derivative of enthalpy to vapour mass fraction dh / dQ / (J/kg).
\[\begin{split}\frac{\partial h_{mix}}{\partial p} = \frac{h_{mix}(p+d,Q)-h_{mix}(p-d,Q)}{2 \cdot d}\\ Q: \text{vapour mass fraction}\end{split}\]
Note
This works for pure fluids only!
- tespy.tools.fluid_properties.dh_mix_pdT(flow, T)[source]#
Calculate partial derivate of enthalpy to temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature T / K.
- Returns
dh / dT (float) – Partial derivative of enthalpy to temperature dh / dT / (J/(kgK)).
\[\frac{\partial h_{mix}}{\partial T} = \frac{h_{mix}(p,T+d)-h_{mix}(p,T-d)}{2 \cdot d}\]
- tespy.tools.fluid_properties.dh_pds_IF97(params, s)[source]#
Calculate the derivative of enthalpy to entropy at constant pressure.
For pure fluids only, required for IF97 entropy iteration only.
- Parameters
p (float) – Pressure p / Pa.
s (float) – Specific entropy h / (J/(kgK)).
fluid (str) – Fluid name.
- Returns
dh (float) – Derivative of specific enthalpy dh / ds / K.
- tespy.tools.fluid_properties.ds_mix_pdT(flow, T)[source]#
Calculate partial derivate of entropy to temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature T / K.
- Returns
ds / dT (float) – Partial derivative of specific entropy to temperature ds / dT / (J/(kg \(\mathrm{K}^2\))).
\[\frac{\partial s_{mix}}{\partial T} = \frac{s_{mix}(p,T+d)-s_{mix}(p,T-d)}{2 \cdot d}\]
- tespy.tools.fluid_properties.dv_mix_dph(flow, T0=675)[source]#
Calculate partial derivate of specific volume to pressure.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dv / dp (float) – Partial derivative of specific volume to pressure dv /dp / (\(\mathrm{m}^3\)/(Pa kg)).
\[\frac{\partial v_{mix}}{\partial p} = \frac{v_{mix}(p+d,h)- v_{mix}(p-d,h)}{2 \cdot d}\]
- tespy.tools.fluid_properties.dv_mix_pdh(flow, T0=675)[source]#
Calculate partial derivate of specific volume to enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
dv / dh (float) – Partial derivative of specific volume to enthalpy dv /dh / (\(\mathrm{m}^3\)/J).
\[\frac{\partial v_{mix}}{\partial h} = \frac{v_{mix}(p,h+d)- v_{mix}(p,h-d)}{2 \cdot d}\]
- tespy.tools.fluid_properties.entropy_iteration_IF97(p, h, fluid, output)[source]#
Calculate state in IF97 back-end via entropy iteration.
- Parameters
p (float) – Pressure p / Pa.
h (float) – Specific enthalpy h / (J/kg).
fluid (str) – Fluid name.
- Returns
T (float) – Temperature T / K.
- tespy.tools.fluid_properties.get_T_crit(fluid)[source]#
Get critical point temperature.
- Parameters
fluid (str) – Fluid name.
- Returns
T_crit (float) – Critical point temperature.
- tespy.tools.fluid_properties.get_p_crit(fluid)[source]#
Get critical point pressure.
- Parameters
fluid (str) – Fluid name.
- Returns
p_crit (float) – Critical point pressure.
- tespy.tools.fluid_properties.h_mix_pQ(flow, Q)[source]#
Calculate the enthalpy from pressure and vapour mass fraction.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
Q (float) – Vapour mass fraction Q / 1.
- Returns
h (float) – Specific enthalpy h / (J/kg).
Note
This function works for pure fluids only!
- tespy.tools.fluid_properties.h_mix_pT(flow, T, force_gas=False)[source]#
Calculate the enthalpy from pressure and Temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature of flow T / K.
- Returns
h (float) – Enthalpy h / (J/kg).
Note
Calculation for fluid mixtures.
\[\begin{split}h_{mix}(p,T)=\sum_{i} h(pp_{i},T,fluid_{i})\; \forall i \in \text{fluid components}\\ pp: \text{partial pressure}\end{split}\]
- tespy.tools.fluid_properties.h_mix_ps(flow, s, T0=675)[source]#
Calculate the enthalpy from pressure and temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
s (float) – Specific entropy of flow s / (J/(kgK)).
- Returns
h (float) – Specific enthalpy h / (J/kg).
Note
Calculation for fluid mixtures.
\[h_{mix}\left(p,s\right)=h\left(p, T_{mix}\left(p,s\right)\right)\]
- tespy.tools.fluid_properties.h_pT(p, T, fluid, force_gas=False)[source]#
Calculate the enthalpy from pressure and temperature for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
T (float) – Temperature T / K.
fluid (str) – Fluid name.
- Returns
h (float) – Specific enthalpy h / (J/kg).
- tespy.tools.fluid_properties.h_ps(p, s, fluid)[source]#
Calculate the enthalpy from pressure and entropy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
s (float) – Specific entropy h / (J/(kgK)).
fluid (str) – Fluid name.
- Returns
h (float) – Specific enthalpy h / (J/kg).
- tespy.tools.fluid_properties.h_ps_IF97(params, s)[source]#
Calculate the enthalpy from pressure and entropy for IF97 backend.
- Parameters
fluid (str) – Fluid name.
p (float) – Pressure p / Pa.
s (float) – Specific entropy h / (J/(kgK)).
- Returns
h (float) – Specific enthalpy h / (J/kg).
- tespy.tools.fluid_properties.isentropic(inflow, outflow, T0=675)[source]#
Calculate the enthalpy at the outlet after isentropic process.
- Parameters
inflow (list) – Inflow fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
outflow (list) – Outflow fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
h_s (float) – Enthalpy after isentropic state change.
\[\begin{split}h_\mathrm{s} = \begin{cases} h\left(p_{out}, s\left(p_{in}, h_{in}\right) \right) & \text{pure fluids}\\ h\left(p_{out}, s\left(p_{in}, T_{in}\right) \right) & \text{mixtures}\\ \end{cases}\end{split}\]
- tespy.tools.fluid_properties.s_mix_pT(flow, T, force_gas=False)[source]#
Calculate the entropy from pressure and temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature T / K.
- Returns
s (float) – Specific entropy s / (J/(kgK)).
Note
Calculation for fluid mixtures.
\[\begin{split}s_{mix}(p,T)=\sum_{i} x_{i} \cdot s(pp_{i},T,fluid_{i})- \sum_{i} x_{i} \cdot R_{i} \cdot \ln \frac{pp_{i}}{p}\; \forall i \in \text{fluid components}\\ pp: \text{partial pressure}\\ R: \text{gas constant}\end{split}\]
- tespy.tools.fluid_properties.s_mix_ph(flow, T0=675)[source]#
Calculate the entropy from pressure and enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
s (float) – Specific entropy s / (J/(kgK)).
Note
First, check if fluid property has been memorised already. If this is the case, return stored value, otherwise calculate value and store it in the memorisation class.
Uses CoolProp interface for pure fluids, newton algorithm for mixtures:
\[s_{mix}\left(p,h\right) = s\left(p,T_{mix}(p,h)\right)\]
- tespy.tools.fluid_properties.s_pT(p, T, fluid, force_gas)[source]#
Calculate the entropy from pressure and temperature for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
T (float) – Temperature T / K.
fluid (str) – Fluid name.
- Returns
s (float) – Specific entropy s / (J/(kgK)).
- tespy.tools.fluid_properties.s_ph(p, h, fluid)[source]#
Calculate the entropy from pressure and enthalpy for a pure fluid.
- Parameters
p (float) – Pressure p / Pa.
h (float) – Specific enthalpy h / (J/kg).
fluid (str) – Fluid name.
- Returns
s (float) – Specific entropy s / (J/(kgK)).
- tespy.tools.fluid_properties.v_mix_pT(flow, T)[source]#
Calculate the specific volume from pressure and temperature.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
T (float) – Temperature T / K.
- Returns
v (float) – Specific volume v / (\(\mathrm{m}^3\)/kg).
Note
Calculation for fluid mixtures.
\[\begin{split}v_{mix}(p,T)=\frac{1}{\sum_{i} \rho(pp_{i}, T, fluid_{i})}\; \forall i \in \text{fluid components}\\ pp: \text{partial pressure}\end{split}\]
- tespy.tools.fluid_properties.v_mix_ph(flow, T0=675)[source]#
Calculate the specific volume from pressure and enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
v (float) – Specific volume v / (\(\mathrm{m}^3\)/kg).
Note
First, check if fluid property has been memorised already. If this is the case, return stored value, otherwise calculate value and store it in the memorisation class.
Uses CoolProp interface for pure fluids, newton algorithm for mixtures:
\[v_{mix}\left(p,h\right) = v\left(p,T_{mix}(p,h)\right)\]
- tespy.tools.fluid_properties.visc_mix_pT(flow, T)[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: [23].
- tespy.tools.fluid_properties.visc_mix_ph(flow, T0=675)[source]#
Calculate the dynamic viscorsity from pressure and enthalpy.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
visc (float) – Dynamic viscosity visc / Pa s.
Note
First, check if fluid property has been memorised already. If this is the case, return stored value, otherwise calculate value and store it in the memorisation class.
Uses CoolProp interface for pure fluids, newton algorithm for mixtures:
\[\eta_{mix}\left(p,h\right) = \eta\left(p,T_{mix}(p,h)\right)\]
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(param, idx)[source]#
Calculate partial derivative of the function func to dx numerically.
- Parameters
param (str) – Parameter to calculate partial derivative for.
idx (int) – Position of the connection to calculate the partial derivative for within the list of the connections
conns
.
- Returns
deriv (float/list) – Partial derivative(s) of the function \(f\) to variable(s) \(x\).
\[\frac{\partial f}{\partial x}=\frac{f(x+d)+f(x-d)}{2\cdot d}\]
- tespy.tools.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.helpers.bus_char_derivative(params, bus_value)[source]#
Calculate derivative for bus char evaluation.
- tespy.tools.helpers.bus_char_evaluation(params, bus_value)[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.colebrook(params, darcy_friction_factor)[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.helpers.colebrook_derivative(params, darcy_friction_factor)[source]#
Calculate derivative for Colebrook-White equation.
- 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.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: [24].
Example
Calculate the Darcy friction factor at different hydraulic states.
>>> from tespy.tools.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.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.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.helpers import fluid_structure >>> elements = fluid_structure('methane') >>> elements['C'], elements['H'] (1, 4)
- 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.hanakov(re)[source]#
Calculate friction coefficient according to Hanakov.
- Parameters
re (float) – Reynolds number.
- Returns
darcy_friction_factor (float) – Darcy friction factor.
- 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.molar_mass_flow(flow)[source]#
Calculate molar mass flow.
- Parameters
flow (list) – Fluid property vector containing mass flow, pressure, enthalpy and fluid composition.
- Returns
m_m (float) – Molar mass flow m_m / (mol/s).
\[\dot{m}_\mathrm{m} = \sum_{i} \left( \frac{x_{i}}{M_{i}} \right)\]
- tespy.tools.helpers.nested_OrderedDict(dictionary)[source]#
Create a nested OrderedDict from a nested dict.
- Parameters
dictionary (dict) – Nested dict.
- Returns
dictionary (collections.OrderedDict) – Nested OrderedDict.
- tespy.tools.helpers.newton(func, deriv, params, y, **kwargs)[source]#
Find zero crossings with 1-D newton algorithm.
- Parameters
func (function) – Function to find zero crossing in, \(0=y-func\left(x,\text{params}\right)\).
deriv (function) – First derivative of the function.
params (list) – Additional parameters for function, optional.
y (float) – Target function value.
val0 (float) – Starting value, default: val0=300.
valmin (float) – Lower value boundary, default: valmin=70.
valmax (float) – Upper value boundary, default: valmax=3000.
max_iter (int) – Maximum number of iterations, default: max_iter=10.
tol_rel (float) – Maximum relative tolerance \(|\frac{y - f(x)}{f(x)}|\), default value: 1e-6.
tol_abs (float) – Maximum absolute tolerance \(|y - f(x)|\), default value: 1e-6.
tol_mode (str) – Check for relative, absolute or both tolerances:
tol_mode='abs'
(default)tol_mode='rel'
tol_mode='both'
- Returns
val (float) – x-value of zero crossing.
Note
Algorithm
\[\begin{split}x_{i+1} = x_{i} - \frac{f(x_{i})}{\frac{df}{dx}(x_{i})}\\ f(x_{i}) \leq \epsilon\end{split}\]
- tespy.tools.helpers.num_fluids(fluids)[source]#
Return number of fluids in fluid mixture.
- Parameters
fluids (dict) – Fluid mass fractions.
- Returns
n (int) – Number of fluids in fluid mixture n / 1.
\[\begin{split}n = \sum_{i} \left( \begin{cases} 0 & x_{i} < \epsilon \\ 1 & x_{i} \geq \epsilon \end{cases} \right)\; \forall i \in \text{network fluids}\end{split}\]
- tespy.tools.helpers.prandtl_karman(params, darcy_friction_factor)[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.helpers.prandtl_karman_derivative(params, darcy_friction_factor)[source]#
Calculate derivative for Prandtl and v. Kármán equation.
- tespy.tools.helpers.reverse_2d(params, y)[source]#
Calculate the residual value of an inverse function.
- Parameters
params (list) – Variable function parameters.
y (float) – Function value of function \(y = f \left( x_1, x_2 \right)\).
- Returns
deriv (float) – Residual value of inverse function \(x_2 - f\left(x_1, y \right)\).
- tespy.tools.helpers.reverse_2d_deriv(params, y)[source]#
Calculate derivative of an inverse function.
- Parameters
params (list) – Variable function parameters.
y (float) – Function value of function \(y = f \left( x_1, x_2 \right)\), so that \(x_2 - f\left(x_1, y \right) = 0\)
- Returns
deriv (float) – Partial derivative \(\frac{\partial f}{\partial y}\).
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
- 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.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_version=True, log_path=True, timed_rotating=None)[source]#
Initialise customisable logger.
- Parameters
logfile (str) – Name of the log file, default: tespy.log
logpath (str) – The path for log files. By default a “.tespy’ folder is created in your home directory with subfolder called ‘log_files’.
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_version (boolean) – If True the actual version or commit is logged while initialising the logger.
log_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 WARNING 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 logging module. The oemof logger module has to be imported once to initialise it.
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_path=True, log_version=True, timed_rotating={'backupCount': 4}, ... screen_level=logging.ERROR, screen_datefmt = "no_date") >>> mypath[-9:] 'tespy.log' >>> logging.debug('Hi')
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 theOptimizationProblem
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 theget_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.