Customize Components¶
On this page you will find a general overview on what you have to consider
when adapting existing components or creating new ones. Furthermore, there is
tutorial available on how we built the PolynomialCompressorWithCooling
together at the first tespy user meeting
here.
Extend existing components¶
You can easily add custom equations to the existing components. In order to do this, you need to implement four changes to the desired component class:
modify the
get_parameters(self)method.add a method, that returns the result of your equation.
add a method, that returns the variables your equation depends on.
In the get_parameters(self) method, add an entry for your new equation.
If the equation uses a single parameter, use the ComponentProperties
type DataContainer (or the ComponentCharacteristics type in case you
only apply a characteristic curve). If your equations requires multiple
parameters, add these parameters as ComponentProperties or
ComponentCharacteristics respectively and add a
GroupedComponentProperties type DataContainer holding the information,
e.g. like the darcy_group parameter of the
tespy.components.heat_exchangers.simple.SimpleHeatExchanger
class shown below.
# [...]
'D': dc_cp(min_val=1e-2, max_val=2, d=1e-4, quantity="length"),
'L': dc_cp(min_val=1e-1, d=1e-3, quantity="length"),
'ks': dc_cp(val=1e-4, min_val=1e-7, max_val=1e-3, d=1e-8, quantity="length"),
'darcy_group': dc_gcp(
elements=['L', 'ks', 'D'], num_eq_sets=1,
func=self.darcy_func,
dependents=self.darcy_dependents
),
# [...]
Tip
With the quantity keyword, tespy will automatically understand what
unit conversion to apply to the respective parameter. E.g. in case you
want to specify the roughness ks in millimeter, you can either
set the default unit for length of your Network to millimeter, or
you can pass the ks value as pint.Quantity to your
component using millimeter as unit. Then the conversion to the SI unit is
taken care of automatically in the preprocessing and the respective
equation will make use of the SI value.
func and dependents are pointing to the method that should be
applied for the corresponding purpose. For more information on defining the
equations and dependents see the next section on custom components. When
defining the dependents in a standalone way, the partial derivatives are
calculated automatically. If you want to insert the partial derivatives
manually, you can define another function and pass with the deriv
keyword.
Create own components¶
You can add own components. The class should inherit from the
Component class or its
children. In order to do that, you can use the customs module or create a
python file in your working directory and import the base class for your
custom component. Now create a class for your component and at least add the
following methods.
component(self),get_parameters(self),get_mandatory_constraints(self),inlets(self),outlets(self)andcalc_parameters(self).
Optionally, you can add
powerinlets(self)andpoweroutlets(self)
in case your component should have methods to connect the material flows with
non-material flows associated with a PowerConnection.
Note
For more information on the PowerConnection please check the
respective section in the docs.
The starting lines of your file should look like this:
from tespy.components.component import Component
from tespy.tools import ComponentCharacteristics as dc_cc
from tespy.tools import ComponentMandatoryConstraints as dc_cmc
from tespy.tools import ComponentProperties as dc_cp
class MyCustomComponent(Component):
"""
This is a custom component.
You can add your documentation here. From this part, it should be clear
for the user, which parameters are available, which mandatory equations
are applied and which optional equations can be applied using the
component parameters.
"""
def component(self):
return 'name of your component'
Mandatory Constraints¶
The get_mandatory_constraints() method must return a dictionary
containing the information for the mandatory constraints of your component.
The corresponding equations are applied independently of the user
specification. Every key of the mandatory constraints represents one set of
equations. It holds another dictionary with information on
the equations,
the number of equations for this constraint and
the variables each equation depends on.
Furthermore more optional specifications can be made
the partial derivatives,
whether the derivatives are constant values or not (
True/False) andthe structure_matrix keyword.
For example, the mandatory equations of the class Valve look are the
following:
The corresponding method looks like this:
def get_mandatory_constraints(self):
constraints = super().get_mandatory_constraints()
constraints.update({
'enthalpy_constraints': dc_cmc(**{
'structure_matrix': self.variable_equality_structure_matrix,
'num_eq_sets': 1,
'func_params': {'variable': 'h'},
"description": "equation for enthalpy equality"
})
})
return constraints
The method inherits from the Component base class and then adds the
enthalpy equality constraint on top of the mass flow equality and fluid
equality constraints.
Note
In this simple case only the structure_matrix has to be provided.
It creates a mapping between linearly dependent pairs of variables and is
utilized to simplify the problem during presolving. It is generally
optional.
For equations, that depend on more than two variables, or that do not have
direct linear relationsships additional parameters have to be supplied, e.g.
see the respective method of the class HeatExchanger.
def get_mandatory_constraints(self):
constraints = super().get_mandatory_constraints()
constraints.update({
'energy_balance_constraints': dc_cmc(**{
'func': self.energy_balance_func,
'dependents': self.energy_balance_dependents,
'num_eq_sets': 1,
"description": "hot side to cold side heat transfer equation"
})
})
return constraints
Here we have the following keywords:
func: Method to be applied (returns residual value of equation)dependents: Method to return the variablesfuncdepends onnum_eq_sets: Number of equations
Note
In some cases the number of equations can depend on the length of the fluid
vectors associated with the component. num_eq_sets specifically
points to the number of equation per all fluids in the fluid vector. Since
this number is not necessarily known prior to solving the problem, there is
a possibility to update the number of equations after presolving to
determine the correct number. This update is only relevant for classes like
Merge and CombustionChamber etc.. Feel free to reach out in
the discussion forum, if you have any questions about it.
With the above mentioned specifications, tespy will apply the method to
calculate the residual value of your equation and automatically calculates its
partial derivatives towards all variables specified in the dependents
list.
Finally, sometimes it is reasonable to not let tespy automatically calculate all partial derivatives, because the calculation can be computationally expensive. Instead you can additionally provide the following keyword:
deriv: A method that calculate the partial derivatives.
You will find more information and examples on this in the next sections.
You can also define mandatory constraints that are conditional, e.g. in context
of PowerConnections. For example, the connection between the material
flow variables of the inlet and the outlet of the turbine to the non-material
energy output variable of the turbine should only be made, in case the turbine
is actually connected with a PowerConnection:
def get_mandatory_constraints(self):
constraints = super().get_mandatory_constraints()
if len(self.power_outl) > 0:
constraints["energy_connector_balance"] = dc_cmc(**{
"func": self.energy_connector_balance_func,
"dependents": self.energy_connector_dependents,
"num_eq_sets": 1
})
return constraints
Attributes¶
This part is very similar to the previous one. The get_parameters()
method must return a dictionary with the attributes you want to use for your
component. The keys represent the attributes and the respective values the type
of data container used for this attribute. By using the data container
attributes, it is possible to add defaults. Defaults for characteristic lines
or characteristic maps are loaded automatically by the component initialisation
method of class
tespy.components.component.Component. For more information on the
default characteristics consider this
chapter.
The structure is very similar to the mandatory constraints, e.g. for the
class Valve:
def get_parameters(self):
return {
'pr': dc_cp(
min_val=1e-4, max_val=1, num_eq_sets=1,
structure_matrix=self.pr_structure_matrix,
func_params={'pr': 'pr'},
quantity="ratio"
),
'dp': dc_cp(
min_val=0,
num_eq_sets=1,
structure_matrix=self.dp_structure_matrix,
func_params={"inconn": 0, "outconn": 0, "dp": "dp"},
quantity="pressure",
description="inlet to outlet absolute pressure change"
),
'zeta': dc_cp(
min_val=0, max_val=1e15, num_eq_sets=1,
func=self.zeta_func,
dependents=self.zeta_dependents,
func_params={'zeta': 'zeta'}
),
'dp_char': dc_cc(
param='m', num_eq_sets=1,
dependents=self.dp_char_dependents,
func=self.dp_char_func,
char_params={'type': 'abs'},
description="inlet to outlet absolute pressure change as function of mass flow lookup table"
)
}
Inlets and outlets¶
inlets(self) and outlets(self) respectively must return a list
of strings. The list may look like this (of class HeatExchanger)
@staticmethod
def inlets():
return ['in1', 'in2']
@staticmethod
def outlets():
return ['out1', 'out2']
The number of inlets and outlets might even be variable, e.g. if you have added
an attribute 'num_in' your code could look like this (as in class
Merge):
def inlets(self):
if self.num_in.is_set:
return [f'in{i + 1}' for i in range(self.num_in.val)]
else:
self.set_attr(num_in=2)
return self.inlets()
Inlets and outlets for PowerConnections¶
If your component should incorporate PowerConnections you can define
connctor ids in a similar way, for example power inlet for compressors or
power outlet for turbines. Here the methods are powerinlets and
poweroutlets.
@staticmethod
def powerinlets():
return ["power"]
@staticmethod
def poweroutlets():
return ["power"]
In a similar way, you can add flexibility with a dynamic number of inlets and outlets:
def powerinlets(self):
return [f"power_in{i + 1}" for i in range(self.num_in.val)]
def poweroutlets(self):
return [f"power_out{i + 1}" for i in range(self.num_out.val)]
Define the required methods¶
In the above section the concept of the component mandatory constraints and their attributes was introduced. Now we need to fill the respective parts with some life, i.e. how to define
the
structure_matrix(optional),the
func,the
dependentsandthe
deriv(optional) methods.
Define a structure matrix¶
As mentioned, with the structure matrix you can make a mapping, in case two
variables are linked to each other with a linear relationship. The presolving
of a model will utilize this information to reduce the number of variables.
For example, for a specified pressure ratio pr of a component, where
the inlet and the outlet pressure are linked through this equation:
We can create a method and reference to it from the component mandatory constraints or attribute dictionaries. In this method you have to
place the partial derivatives towards both variables in the component’s
_structure_matrixattribute.place any offset in the component’s
_rhsattribute.
For the example above, the derivative to the inlet pressure is pr, and
to the outlet pressure -1. The offset/right hand side value of the
equation is 0.
def pr_structure_matrix(self, k, pr=None, inconn=0, outconn=0):
r"""
Create linear relationship between inflow and outflow pressure
.. math::
p_{in} \cdot pr = p_{out}
Parameters
----------
k : int
equation number in systems of equations
pr : str
Component parameter, e.g. :code:`pr1`.
inconn : int
Connection index of inlet.
outconn : int
Connection index of outlet.
"""
pr = self.get_attr(pr)
i = self.inl[inconn]
o = self.outl[outconn]
self._structure_matrix[k, i.p.sm_col] = pr.val_SI
self._structure_matrix[k, o.p.sm_col] = -1
A different equation to simplify with this method could be the delta pressure
dp. In this case, the _rhs is not zero, it is the value of
dp.
def dp_structure_matrix(self, k, dp=None, inconn=0, outconn=0):
r"""
Create linear relationship between inflow and outflow pressure
.. math::
p_{in} - dp = p_{out}
Parameters
----------
k : int
equation number in systems of equations
dp : str
Component parameter, e.g. :code:`dp1`.
inconn : int
Connection index of inlet.
outconn : int
Connection index of outlet.
"""
inlet_conn = self.inl[inconn]
outlet_conn = self.outl[outconn]
self._structure_matrix[k, inlet_conn.p.sm_col] = 1
self._structure_matrix[k, outlet_conn.p.sm_col] = -1
self._rhs[k] = self.get_attr(dp).val_SI
Define the equations¶
The definition of an equation is quite straight forward: It must return its
residual value. For example, the equation of the dp_char parameter
associated with the class Valve is the following:
def dp_char_func(self):
r"""
Equation for characteristic line of difference pressure to mass flow.
Returns
-------
residual : ndarray
Residual value of equation.
.. math::
0=p_\mathrm{in}-p_\mathrm{out}-f\left( expr \right)
"""
p = self.dp_char.param
expr = self.get_char_expr(p, **self.dp_char.char_params)
if not expr:
msg = ('Please choose a valid parameter, you want to link the '
'pressure drop to at component ' + self.label + '.')
logger.error(msg)
raise ValueError(msg)
return (
self.inl[0].p.val_SI - self.outl[0].p.val_SI
- self.dp_char.char_func.evaluate(expr)
)
Caution
Your equations should only use and access the SI values val_SI
associated with connection or component parameters in the back-end .
Define the dependents¶
Next, you have to define the list of variables the equation depends on, i.e. towards which variables the partial derivatives should be calculated. In this example, it is the inlet and the outlet pressure, as well as the mass flow and in case the volumetric flow should be used to assess the characteristic function, the inlet enthalpy.
def dp_char_dependents(self):
dependents = [
self.inl[0].m,
self.inl[0].p,
self.outl[0].p,
]
if self.dp_char.param == 'v':
dependents += [self.inl[0].h]
return dependents
The solver will automatically determine, which of the variables returned by this method are actual variables (have not been presolved) and the calculate the derivative to the specified equation numerically using a central finite difference. In the case of this method, this will be an extra 6 or 8 function evaluations to determine the partial derivatives, if all of the indicated variables are actually system variables (have not been presolved).
The only thing you have to do is, to make the method return a list of variables the equation depends on.
It can be more complex than that when dealing with equations, which have
partial derivatives towards components of a fluid mixture. For example, the
energy balance of the CommbustionChamber depends on the fuel’s mass
fraction in the fluid mixtures of its inlets. To account for this in the
dependents specification, your method has to return a dictionary instead,
which uses the keys
scalarsfor all “standard” variablesvectorsfor all fluid mixture component variables
In the example below, the variable mixture components of the inlets are the
union of the set of fuels available in the CombustionChamber and the
fluid components that are actually variable in the mixture. For this, a
subdictionary is created, which is a mapping of the fluid mixture container
c.fluid to a set of fluid names
self.fuel_list & c.fluid.is_var.
def energy_balance_dependents(self):
inl, outl = self._get_combustion_connections()
return {
"scalars": [var for c in inl + outl for var in [c.m, c.h]],
"vectors": [{
c.fluid: self.fuel_list & c.fluid.is_var for c in inl + outl
}]
}
Define the derivatives¶
The downside of the simple to use approach of defining the equation together with its dependents is, that it can be computationally expensive to calculate the partial derivatives. In this case, it may be reasonable to implement a method specifically for the calculation of the partial derivatives.
For example, consider the isentropic efficiency equation of a Turbine:
def eta_s_func(self):
r"""
Equation for given isentropic efficiency of a turbine.
Returns
-------
residual : float
Residual value of equation.
.. math::
0 = -\left( h_{out} - h_{in} \right) +
\left( h_{out,s} - h_{in} \right) \cdot \eta_{s,e}
"""
inl = self.inl[0]
outl = self.outl[0]
return (
-(outl.h.val_SI - inl.h.val_SI)
+ (
isentropic(
inl.p.val_SI,
inl.h.val_SI,
outl.p.val_SI,
inl.fluid_data,
inl.mixing_rule,
T0=inl.T.val_SI
)
- inl.h.val_SI
) * self.eta_s.val_SI
)
The partial derivatives to the inlet and outlet pressure as well as the inlet
enthalpy can only be determined numerically. However, the partial derivative to
the outlet enthalpy can be obtained analytically, it is 1. To save the
extra evaluation of the equation in case the outlet enthalpy is a variable, we
can define the following method:
def eta_s_deriv(self, increment_filter, k, dependents=None):
r"""
Partial derivatives for isentropic efficiency function.
Parameters
----------
increment_filter : ndarray
Matrix for filtering non-changing variables.
k : int
Position of derivatives in Jacobian matrix (k-th equation).
"""
dependents = dependents["scalars"][0]
f = self.eta_s_func
i = self.inl[0]
o = self.outl[0]
if o.h._reference_container != i.h._reference_container:
self._partial_derivative(o.h, k, -1, increment_filter)
# remove o.h from the dependents
dependents = dependents.difference(_get_dependents([o.h])[0])
for dependent in dependents:
self._partial_derivative(dependent, k, f, increment_filter)
To place the partial derivative you can use the _partial_derivative
method and pass
the variable
the equation number (passed to your method through the argument k)
the value of the partial derivative (a number or a callable)
in case you pass a number, it will put the value directly into the Jacobian
in case you pass a callable, the derivative will be determined numerically for the specified callable and the result will then be passed to the Jacobian
the
increment_filter, which is a lookup for variables, that do not change anymore from one iteration to the next. In this case, the calculation of the derivative will be skipped.
Caution
We cannot simply put down the derivatives for all variables in the Jacobian because we do not necessarily know (prior to solving) which variables will be mapped to a single variable because they are linearly dependent. Thus, we have to use the set of dependents, that is passed to our derivative method. Otherwise, the calculation of the derivative, e.g. for outlet pressure may override the value for inlet pressure, even though both are pointing to the same variable. In case of numerical derivative calculation this is not an issue except for the extra computational effort. But if you have determined the derivatives analytically, then their value might change if two variables are mapped to a single one.
Need assistance?¶
You are very welcome to open a discussion or submit an issue on the GitHub repository!