In this section we will introduce you to the details of component parametrisation and component characteristics. At the end of the section we show you how to create custom components.

List of components

More information on the components can be gathered from the code documentation. We have linked the base class containing a figure and basic information as well as the equations.

List of custom components

Here we list the components integrated in the customs module.

  • Evaporator for two-phase geothermal organic rankine cycle

Component parametrisation

All parameters of components are objects of a DataContainer class. The data container for component parameters is called ComponentProperties, ComponentCharacteristics for component characteristics, and ComponentCharacteristicMaps for characteristic maps. The main purpose of having a data container for the parameters (instead of pure numbers), is added flexibility for the user. There are different ways for you to specify and access component parameters.

Component parameters

The example shows different ways to specify the heat transfer coefficient of an evaporator and how to unset the parameter again.

from tespy.components import HeatExchanger
from import ComponentProperties as dc_cp
import numpy as np

he = HeatExchanger('evaporator')

# specify the value
# specify via dictionary
he.set_attr(kA={'val': 1e5, 'is_set': True})
# set data container parameters
he.kA.set_attr(val=1e5, is_set=True)

# possibilities to unset a value

Grouped parameters

Grouped parameters are used whenever a component property depends on multiple parameters. For instance, the pressure loss calculation via Darcy-Weissbach requires information about the length, diameter and roughness of the pipe. The solver will prompt a warning, if you do not specify all parameters required by a parameter group. If parameters of the group are missing, the equation will not be implemented by the solver.

from tespy.components import Pipe
import numpy as np

my_pipe = Pipe('pipe')

# specify grouped parameters
my_pipe.set_attr(D=0.1, L=20, ks=0.00005)

# the solver will not apply an equation, since the information of the
# pipe's length is missing.
my_pipe.set_attr(D=0.1, ks=0.00005)

There are several components using parameter groups:

  • heat_exchanger_simple and pipe

    • hydro_group (D, L, ks)

    • kA_group (kA, Tamb)

    • kA_char_group (kA_char, Tamb)

  • solar_collector

    • hydro_group (D, L, ks)

    • energy_group (E, eta_opt, lkf_lin, lkf_quad, A, Tamb)

  • parabolic_trough

    • hydro_group (D, L, ks)

    • energy_group (E, eta_opt, aoi, doc, c_1, c_2, iam_1, iam_2, A, Tamb)

  • compressor

    • char_map_eta_s_group (char_map_eta_s, igva)

    • char_map_pr_group (char_map_pr, igva)

Custom variables

It is possible to use component parameters as variables of your system of equations. In the component parameter list, if a parameter can be a string, it is possible to specify this parameter as custom variable. For example, given the pressure ratio pr, length L and roughness ks of a pipe you may want to calculate the pipe’s diameter D required to achieve the specified pressure ratio. In this case you need to specify the diameter the following way.

from tespy.components import Pipe
from import ComponentProperties as dc_cp
import numpy as np

# custom variables
my_pipe = Pipe('my pipe')

# make diameter variable of system
my_pipe.set_attr(pr=0.98, L=100, ks=0.00002, D='var')

# a second way of specifying this is similar to the
# way used in the component parameters section
# val will be used as starting value
my_pipe.set_attr(pr=0.98, L=100, ks=0.00002)
my_pipe.set_attr(D={'val': 0.2, 'is_set': True, 'is_var': True})

It is also possible to set value boundaries for you custom variable. You can do this, if you expect the result to be within a specific range. But beware: This might result in a non converging simulation, if the actual value is out of your specified range.

# data container specification with identical result,
# benefit: specification of bounds will increase stability
    'val': 0.2, 'is_set': True, 'is_var': True,
    'min_val': 0.1, 'max_val': 0.3}

Component characteristics

Several components integrate parameters using a characteristic function. These parameters come with default characteristics. The default characteristics available can be found in the module. Of course, it is possible to specify your own characteristic functions.


There are two different characteristics specifications

The characteristic function can be an auxiliary parameter of a different component property. This is the case for kA_char1 and kA_char2 of heat exchangers as well as the characteristics of a combustion engine: tiP_char, Q1_char, Q2_char and Qloss_char.

For all other components, the characteristic function is an individual parameter of the component.

What does this mean?

For the auxiliary functionality the main parameter, e.g. kA_char of a heat exchanger must be set .kA_char.is_set=True.

For the other functionality the characteristics parameter must be set e.g. .eta_s_char.is_set=True.

For example, kA_char specification for heat exchangers:

from tespy.components import HeatExchanger
from import load_default_char as ldc
from import CharLine
import numpy as np

he = HeatExchanger('evaporator')

# the characteristic function requires the design value of the property,
# therefore the design value of kA must be set and additionally we set
# the kA_char method. This is performed automatically, if you specify the
# kA_char as offdesign parameter (usual case).
he.set_attr(kA={'design': 1e5}, kA_char={'is_set': True})

# use a characteristic line from the defaults: specify the component, the
# parameter and the name of the characteristic function. Also, specify,
# what type of characteristic function you want to use.
kA_char1 = ldc('heat exchanger', 'kA_char1', 'DEFAULT', CharLine)
kA_char2 = ldc('heat exchanger', 'kA_char2', 'EVAPORATING FLUID', CharLine)

# specification of a data container yields the same result. It is
# additionally possible to specify the characteristics parameter, e.g. mass
# flow for kA_char1 and volumetric flow for kA_char2
    kA_char1={'char_func': kA_char1, 'param': 'm'},
    kA_char2={'char_func': kA_char2, 'param': 'v'}

# or use custom values for the characteristic line e.g. kA vs volumetric
# flow
x = np.array([0, 0.5, 1, 2])
y = np.array([0, 0.8, 1, 1.2])
kA_char1 = CharLine(x, y)
he.set_attr(kA_char1={'char_func': kA_char1, 'param': 'v'})

Full working example for eta_s_char specification of a turbine.

from tespy.components import Sink, Source, Turbine
from tespy.connections import Connection
from tespy.networks import Network
from import CharLine
import numpy as np

nw = Network(p_unit='bar', T_unit='C', h_unit='kJ / kg')
si = Sink('sink')
so = Source('source')
t = Turbine('turbine')
inc = Connection(so, 'out1', t, 'in1')
outg = Connection(t, 'out1', si, 'in1')
nw.add_conns(inc, outg)

# design value specification, cone law and eta_s characteristic as
# offdesign parameters
eta_s_design = 0.855
t.set_attr(eta_s=eta_s_design, design=['eta_s'], offdesign=['eta_s_char','cone'])

# Characteristics x as m/m_design and y as eta_s(m)/eta_s_design
# make sure to cross the 1/1 point (design point) to yield the same
# output in the design state of the system
line = CharLine(
    x=[0.1, 0.3, 0.5, 0.7, 0.9, 1, 1.1],
    y=np.array([0.6, 0.65, 0.75, 0.82, 0.85, 0.855, 0.79]) / eta_s_design)

# default parameter for x is m / m_design
t.set_attr(eta_s_char={'char_func': line})
inc.set_attr(fluid={'water': 1}, m=10, T=550, p=110, design=['p'])
# change mass flow value, e.g. 3 kg/s and run offdesign calculation
nw.solve('offdesign', design_path='tmp')
# isentropic efficiency should be at 0.65

# alternatively, we can specify the volumetric flow v / v_design for
# the x lookup
t.set_attr(eta_s_char={'param': 'v'})
nw.solve('offdesign', design_path='tmp')

Instead of writing your custom characteristic line information directly into your Python script, TESPy provides a second method of implementation: It is possible to store your data in the HOME/.tespy/data folder and import from there. For additional information on formatting and usage, look into this part.

from import load_custom_char as lcc

eta_s_char = dc_cc(func=lcc('my_custom_char', CharLine), is_set=True)

It is possible to allow value extrapolation at the lower and upper limit of the value range at the creation of characteristic lines. Set the extrapolation parameter to True.

# use custom specification parameters
x = np.array([0, 0.5, 1, 2])
y = np.array([0, 0.8, 1, 1.2])
kA_char1 = CharLine(x, y, extrapolate=True)

# set extrapolation to True for existing lines, e.g.
he.kA_char1.func.extrapolate = True
pu.eta_s_char.func.extrapolate = True

Characteristics are available for the following components and parameters:

  • combustion engine

    • tiP_char: thermal input vs. power ratio.

    • Q1_char: heat output 1 vs. power ratio.

    • Q2_char: heat output 2 vs. power ratio.

    • Qloss_char: heat loss vs. power ratio.

  • compressor

    • char_map: pressure ratio vs. non-dimensional mass flow.

    • char_map: isentropic efficiency vs. non-dimensional mass flow.

    • eta_s_char: isentropic efficiency.

  • heat exchangers:

  • pump

  • simple heat exchangers

    • kA_char: heat transfer coefficient.

  • turbine

  • valve

    • dp_char: absolute pressure change.

  • water electrolyzer

For more information on how the characteristic functions work click here.

Extend components with new equations

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 places the partial derivatives in the Jacobian matrix of your component.

  • add a method, that returns the LaTeX code of your equation for the automatic documentation feature.

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 hydro_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),
'L': dc_cp(min_val=1e-1, d=1e-3),
'ks': dc_cp(val=1e-4, min_val=1e-7, max_val=1e-3, d=1e-8),
'hydro_group': dc_gcp(
    elements=['L', 'ks', 'D'], num_eq=1,
    func=self.hydro_group_func, deriv=self.hydro_group_deriv),
# [...]

latex, func and deriv are pointing to the method that should be applied for the corresponding purpose. For more information on defining the equations, derivatives and the LaTeX equation you will find the information in the next section on custom components.

Custom 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) and

  • calc_parameters(self).

The starting lines of your file should look like this:

from tespy.components.component import Component
from import ComponentCharacteristics as dc_cc
from 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,

  • the derivatives,

  • whether the derivatives are constant values or not (True/False) and

  • the LaTeX code for the model documentation.

For example, the mandatory equations of a valve look are the following:


The corresponding method looks like this. The equations, derivatives and LaTeX string generation are individual methods you need to define (see next sections).

def get_mandatory_constraints(self):
    return {
        'enthalpy_equality_constraints': {
            'func': self.enthalpy_equality_func,
            'deriv': self.enthalpy_equality_deriv,
            'constant_deriv': True,
            'latex': self.enthalpy_equality_func_doc,
            'num_eq': 1}
  • func: Method to be applied (returns residual value of equation).

  • deriv: Partial derivatives of equation to primary variables.

  • latex: Method returning the LaTeX string of the equation.


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, using DataContainers instead of dictionaries, e.g. for the Valve:

def get_parameters(self):
    return {
        'pr': dc_cp(
            min_val=1e-4, max_val=1, num_eq=1,
            deriv=self.pr_deriv, func=self.pr_func,
            func_params={'pr': 'pr'}, latex=self.pr_func_doc),
        'zeta': dc_cp(
            min_val=0, max_val=1e15, num_eq=1,
            deriv=self.zeta_deriv, func=self.zeta_func,
            func_params={'zeta': 'zeta'}, latex=self.zeta_func_doc),
        'dp_char': dc_cc(
            param='m', num_eq=1,
            deriv=self.dp_char_deriv, func=self.dp_char_func,
            char_params={'type': 'abs'}, latex=self.dp_char_func_doc)

Inlets and outlets

inlets(self) and outlets(self) respectively must return a list of strings. The list may look like this:

def inlets(self):
    return ['in1', 'in2']

def outlets(self):
    return ['out1', 'out2']

The number of inlets and outlets might even be generic, e.g. if you have added an attribute 'num_in' your code could look like this:

def inlets(self):
    if self.num_in.is_set:
        return ['in' + str(i + 1) for i in range(self.num_in.val)]
        # default number is 2
        return ['in1', 'in2']

Defining equations and derivatives

Every equation required by the mandatory constraints and in the variables of the component must be individual methods returning the residual value of the equation applied. This logic accounts for the derivatives and the LaTeX equation, too. The Valve’s dp_char parameter methods are the following.

def dp_char_func(self):
    Equation for characteristic line of difference pressure to mass flow.

    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 + '.')
        raise ValueError(msg)

    return (
        self.inl[0].p.val_SI - self.outl[0].p.val_SI -

def dp_char_func_doc(self, label):
    Equation for characteristic line of difference pressure to mass flow.

    label : str
        Label for equation.

    latex : str
        LaTeX code of equations applied.
    p = self.dp_char.param
    expr = self.get_char_expr_doc(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 + '.')
        raise ValueError(msg)

    latex = (
        r'0=p_\mathrm{in}-p_\mathrm{out}-f\left(' + expr +
    return generate_latex_eq(self, latex, label)

def dp_char_deriv(self, increment_filter, k):
    Calculate partial derivatives of difference pressure characteristic.

    increment_filter : ndarray
        Matrix for filtering non-changing variables.

    k : int
        Position of derivatives in Jacobian matrix (k-th equation).
    f = self.dp_char_func
    i = self.inl[0]
    o = self.outl[0]
    if self.is_variable(i.m, increment_filter):
        self.jacobian[k, i.m.J_col] = self.numeric_deriv(f, 'm', i)
    if self.dp_char.param == 'v':
        if self.is_variable(i.p, increment_filter):
            self.jacobian[k, i.p.J_col] = self.numeric_deriv(
                self.dp_char_func, 'p', i
        if self.is_variable(i.h, increment_filter):
            self.jacobian[k, i.h.J_col] = self.numeric_deriv(
                self.dp_char_func, 'h', i
        if self.is_variable(i.p, increment_filter):
            self.jacobian[k, i.p.J_col] = 1

    if self.is_variable(o.p):
        self.jacobian[k, o.p.J_col] = -1

For the Jacobian, the partial derivatives to all variables of the network are required. This means, that you have to calculate the partial derivatives to mass flow, pressure, enthalpy and all fluids in the fluid vector on each connection affecting the equation defined before. To check, whether these are actually variable (e.g. not user specified or presolved), you can use the is_variable method. You have to then assign the result of the derivative to the correct location in the Jacobian. The row is the k-th equation and the column is given in the J_col attribute of the variable.

The derivatives can be calculated analytically (preferred if possible) or numerically by using the inbuilt method tespy.components.component.Component.numeric_deriv(), where

  • func is the function you want to calculate the derivatives for.

  • dx is the variable you want to calculate the derivative to.

  • conn is the connection you want to calculate the derivative for.

  • kwargs are additional keyword arguments required for the function.

LaTeX documentation

Finally, add a method that returns the equation as LaTeX string for the automatic model documentation feature. Simple write the equation and return it with the method, which automatically generates a LaTeX equation environment and labels the equation, so you can reference it later. Therefore, the latex generation methods needs the label as parameter.

Need assistance?

You are very welcome to submit an issue on our GitHub!

Component Groups: Subsystems

Subsystems are an easy way to add frequently used component groups such as a drum with evaporator or a preheater with desuperheater to your system. In this section you will learn how to create a subsystem and implement it in your work. The subsystems are highly customizable and thus a very powerful tool, if you require using specific component groups frequently. We provide an example, of how to create a simple subsystem and use it in a simulation.

Custom subsystems

Create a .py file in your working-directory. This file contains the class definition of your subsystem and at minimum two methods:

  • create_comps: Method to create the components of your subsystem and save them in the Subsystem.comps attribute (dictionary).

  • create_conns: Method to create the connections of your subsystem and save them in the Subsystem.conns attribute (dictionary).

All other functionalities are inherited by the parent class of the subsystem object.


Create the subsystem

We create a subsystem for the usage of a waste heat steam generator. The subsystem is built up of a superheater, an evaporator, a drum and an economizer as seen in the figure below.

Topology of the waste heat steam generator

Figure: Topology of the waste heat steam generator

Topology of the waste heat steam generator

Figure: Topology of the waste heat steam generator

Create a file, e.g. and add the following lines:

  • Imports of the necessary classes from tespy.

  • Class definition of the subsystem (inheriting from subsystem class).

  • Methods for component and connection creation. Both, components and connections, are stored in a dictionary for easy access by their respective label.

from tespy.components import Subsystem, HeatExchanger, Drum
from tespy.connections import Connection

class WasteHeatSteamGenerator(Subsystem):
    """Class documentation"""

    def create_comps(self):
        """Create the subsystem's components."""
        self.comps['eco'] = HeatExchanger('economizer')
        self.comps['eva'] = HeatExchanger('evaporator')
        self.comps['sup'] = HeatExchanger('superheater')
        self.comps['drum'] = Drum('drum')

    def create_conns(self):
        """Define the subsystem's connections."""
        self.conns['eco_dr'] = Connection(
            self.comps['eco'], 'out2', self.comps['drum'], 'in1')
        self.conns['dr_eva'] = Connection(
            self.comps['drum'], 'out1', self.comps['eva'], 'in2')
        self.conns['eva_dr'] = Connection(
            self.comps['eva'], 'out2', self.comps['drum'], 'in2')
        self.conns['dr_sup'] = Connection(
            self.comps['drum'], 'out2', self.comps['sup'], 'in2')
        self.conns['sup_eva'] = Connection(
            self.comps['sup'], 'out1', self.comps['eva'], 'in1')
        self.conns['eva_eco'] = Connection(
            self.comps['eva'], 'out1', self.comps['eco'], 'in1')

Import your subsystem

In a different script, we create a network and import the subsystem we just created along with the different tespy classes required. The location of the file must be known by your python installation or lie within the same folder as your script.

from tespy.networks import Network
from tespy.components import Source, Sink
from tespy.connections import Connection
import numpy as np

from mysubsystems import WasteHeatSteamGenerator as WHSG

# %% network definition

nw = Network(p_unit='bar', T_unit='C')

# %% component definition

feed_water = Source('feed water inlet')
steam = Sink('live steam outlet')

waste_heat = Source('waste heat inlet')
chimney = Sink('waste heat chimney')

sg = WHSG('waste heat steam generator')

# %% connection definition

fw_sg = Connection(feed_water, 'out1', sg.comps['eco'], 'in2')
sg_ls = Connection(sg.comps['sup'], 'out2', steam, 'in1')
fg_sg = Connection(waste_heat, 'out1', sg.comps['sup'], 'in1')
sg_ch = Connection(sg.comps['eco'], 'out1', chimney, 'in1')

nw.add_conns(fw_sg, sg_ls, fg_sg, sg_ch)

# %% connection parameters

fw_sg.set_attr(fluid={'water': 1}, T=25)
fg_sg.set_attr(fluid={'air': 1}, T=650, m=100)



# %% component parameters

    pr1=0.999,  pr2=0.97, design=['pr1', 'pr2', 'ttd_u'],
    offdesign=['zeta1', 'zeta2', 'kA_char']

    pr1=0.999, ttd_l=20, design=['pr1', 'ttd_l'],
    offdesign=['zeta1', 'kA_char']

    pr1=0.999,  pr2=0.99, ttd_u=50, design=['pr1', 'pr2', 'ttd_u'],
    offdesign=['zeta1', 'zeta2', 'kA_char']

sg.conns['eco_dr'].set_attr(Td_bp=-5, design=['Td_bp'])

# %% solve

# solve design case

# offdesign test
nw.solve('offdesign', design_path='tmp')

Add more flexibility

If you want to add even more flexibility, you might need to manipulate the __init__ method of your custom subsystem class. Usually, you do not need to override this method. However, if you need additional parameters, e.g. in order to alter the subsystem’s topology or specify additional information, take a look at the tespy.components.subsystem.Subsystem class and add your code between the label declaration and the components and connection creation in the __init__ method.

For example, if you want a variable number of inlets and outlets because you have a variable number of components groups within your subsystem, you may introduce an attribute which is set on initialisation and lets you create and parameterize components and connections generically. This might be very interesting for district heating systems, turbines with several sections of equal topology, etc.. For a good start, you can have a look at the of the district heating network in the oemof_examples repository.