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:
objectClass 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.
- 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_Dnames 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.
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:
objectClass 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
Truelinear 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.datamodule. 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
extrapolateisFalse(default) and the x-value is outside of the specified range, the function will return the values at the corresponding boundary. IfextrapolateisTruethe 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:
objectClass 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
0represents the lower and1the 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:
DataContainerData 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.
- property num_eq¶
- class tespy.tools.data_containers.ComponentCharacteristics(**kwargs)[source]¶
Bases:
DataContainerData 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.
- property num_eq¶
- class tespy.tools.data_containers.ComponentMandatoryConstraints(**kwargs)[source]¶
Bases:
DataContainerData container for component mandatory constraints.
- static attr()[source]¶
Return the available attributes for a ComponentProperties type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- property num_eq¶
- class tespy.tools.data_containers.ComponentProperties(**kwargs)[source]¶
Bases:
DataContainerData 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.
- property J_col¶
- static attr()[source]¶
Return the available attributes for a ComponentProperties type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- get_reference_val_SI()[source]¶
Get value of the reference corresponding to own value
- Returns:
float – Value of reference container corresponding to this data container’s value.
- property is_var¶
- property num_eq¶
- property val¶
- class tespy.tools.data_containers.DataContainer(**kwargs)[source]¶
Bases:
objectThe 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 differentDataContainerclasses for specific objectives:component characteristics
tespy.tools.data_containers.ComponentCharacteristicscomponent characteristic maps
tespy.tools.data_containers.ComponentCharacteristicMapscomponent properties
tespy.tools.data_containers.ComponentPropertiesgrouped component properites
tespy.tools.data_containers.GroupedComponentPropertiesfluid composition
tespy.tools.data_containers.FluidCompositionfluid 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, 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.
- class tespy.tools.data_containers.FluidComposition(**kwargs)[source]¶
Bases:
DataContainerData 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.
- property J_col¶
- static attr()[source]¶
Return the available attributes for a FluidComposition type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- property is_set¶
- property is_var¶
- property val¶
- class tespy.tools.data_containers.FluidProperties(**kwargs)[source]¶
Bases:
DataContainerData 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.
- property J_col¶
- static attr()[source]¶
Return the available attributes for a FluidProperties type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- get_reference_val_SI()[source]¶
Get value of the reference corresponding to own value
- Returns:
float – Value of reference container corresponding to this data container’s value.
- property is_var¶
- property val_SI¶
- class tespy.tools.data_containers.GroupedComponentCharacteristics(**kwargs)[source]¶
Bases:
GroupedComponentPropertiesData 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:
DataContainerData 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.
- property num_eq¶
- class tespy.tools.data_containers.ReferencedFluidProperties(**kwargs)[source]¶
Bases:
DataContainer
- class tespy.tools.data_containers.ScalarVariable(**kwargs)[source]¶
Bases:
DataContainer- property J_col¶
- static attr()[source]¶
Return the available attributes for a FluidProperties type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- property d¶
- property is_var¶
- property val_SI¶
- class tespy.tools.data_containers.SimpleDataContainer(**kwargs)[source]¶
Bases:
DataContainerSimple 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.
- property num_eq¶
- property val¶
- class tespy.tools.data_containers.VectorVariable(**kwargs)[source]¶
Bases:
DataContainerData 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.
- property J_col¶
- static attr()[source]¶
Return the available attributes for a FluidComposition type object.
- Returns:
out (dict) – Dictionary of available attributes (dictionary keys) with default values.
- property d¶
- property is_var¶
- property val¶
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.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.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 [28].
- 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.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.isentropic(p_1, h_1, p_2, fluid_data, mixing_rule=None, T0=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_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.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: [29].
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.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.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_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.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: [30].
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
- class tespy.tools.fluid_properties.wrappers.FluidPropertyWrapper(fluid, back_end=None)[source]¶
Bases:
object
- class tespy.tools.fluid_properties.wrappers.IAPWSWrapper(fluid, back_end=None)[source]¶
Bases:
FluidPropertyWrapper
- class tespy.tools.fluid_properties.wrappers.PyromatWrapper(fluid, back_end=None)[source]¶
Bases:
FluidPropertyWrapper
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:
ExceptionCustom message for component related errors.
- exception tespy.tools.helpers.TESPyConnectionError[source]¶
Bases:
ExceptionCustom message for connection related errors.
- exception tespy.tools.helpers.TESPyNetworkError[source]¶
Bases:
ExceptionCustom message for network related errors.
- class tespy.tools.helpers.UserDefinedEquation(label: str, func: callable, dependents: callable, deriv: callable | None = None, conns: list = [], comps: list = [], params: dict = {})[source]¶
Bases:
object
- 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.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.merge_dicts(dict1, dict2)[source]¶
Return a new dictionary by merging two dictionaries recursively.
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.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_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.optimization module¶
- class tespy.tools.optimization.OptimizationProblem(model, variables={}, constraints={}, objective=[])[source]¶
Bases:
objectThe 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
.individualsattribute of theOptimizationProblemclass.
- 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 (list) – Name of the objective(s).
objectiveis passed to theget_objectivesmethod 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.