tespy.components package¶
tespy.components.component module¶
Module class component.
All tespy components inherit from this class.
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/components/components.py
SPDX-License-Identifier: MIT
- class tespy.components.component.Component(label, **kwargs)[source]¶
Bases:
objectClass Component is the base class of all TESPy components.
- Parameters:
label (str) – The label of the component.
design (list) – List containing design parameters (stated as String).
offdesign (list) – List containing offdesign parameters (stated as String).
design_path (str) – Path to the components design case.
local_offdesign (boolean) – Treat this component in offdesign mode in a design calculation.
local_design (boolean) – Treat this component in design mode in an offdesign calculation.
char_warnings (boolean) – Ignore warnings on default characteristics usage for this component.
printout (boolean) – Include this component in the network’s results printout.
**kwargs – See the class documentation of desired component for available keywords.
Note
The initialisation method (__init__), setter method (set_attr) and getter method (get_attr) are used for instances of class component and its children.
Allowed keywords in kwargs are ‘design_path’, ‘design’ and ‘offdesign’. Additional keywords depend on the type of component you want to create.
Example
Basic example for a setting up a
tespy.components.component.Componentobject. This example does not run a tespy calculation.>>> from tespy.components.component import Component >>> comp = Component('myComponent') >>> type(comp) <class 'tespy.components.component.Component'>
- property all_connections¶
- property all_inlets¶
- property all_outlets¶
- calc_parameters()[source]¶
Postprocessing parameter calculation.
Each
ComponentPropertieswhosecalcattribute is set is called here in topological order (respectingcalc_depsdependencies).Note
Two patterns exist for
calcmethods, and it is important to keep them distinct:Pattern A - solver variables only (p, h, m, fluid composition, connection energies E): methods like
_calc_P()read only quantities that are unknowns of the solver, therefore these methods can also be used in the residual calculations during iterations.Pattern B - derived properties (T, v, x, …): methods like
_calc_ttd_uor_calc_td_logcall helpers such ascalc_T()which rely on values that are computed during connection postprocessing (e.g.connection.T.val_SI). These methods must only be called in postprocessing, never during iteration, because the derived values are not yet available.When adding a new
calcmethod, choose Pattern A if the result depends solely on solver variables; choose Pattern B otherwise, and make sure no caller invokes it during iteration.
- calc_results(units)[source]¶
Postprocess this component’s parameters.
Calculates the parameter results, checks the value limits and - for fixed input parameters - compares the calculated result against the originally specified value.
- Returns:
tuple – Two booleans: no parameter limits violated, all fixed input parameters match their calculated results.
- check_parameter_bounds()[source]¶
Check parameter value limits.
The check is relative to the magnitude of the parameter itself or - where a value is small by construction, e.g. a heat loss compared to the thermal input - to the magnitude of the parameter named in
limit_scale. A value beyond a bound by less thanLIMIT_RTOLtimes that scale is numerical noise of the converged solution: it is snapped onto the bound instead of being reported as a violation.
- dp_structure_matrix(k, dp=None, inconn=0, outconn=0)[source]¶
Create linear relationship between inflow and outflow pressure
\[p_{in} - dp = p_{out}\]- Parameters:
k (int) – equation number in systems of equations
dp (str) – Component parameter, e.g.
dp1.inconn (int) – Connection index of inlet.
outconn (int) – Connection index of outlet.
- get_attr(key)[source]¶
Get the value of a component’s attribute.
- Parameters:
key (str) – The attribute you want to retrieve.
- Returns:
out – Value of specified attribute.
- get_char_expr(param, type='rel', inconn=0, outconn=0)[source]¶
Generic method to access characteristic function parameters.
- Parameters:
param (str) – Parameter for characteristic function evaluation.
type (str) – Type of expression:
rel: relative to design valueabs: absolute value
inconn (int) – Index of inlet connection.
outconn (int) – Index of outlet connection.
- Returns:
expr (float) – Value of expression
- initial_state(port)[source]¶
Expected state at the given port for starting value selection.
Returns
Nonefor no expectation or a dict with a"phase"key ("liquid","gas"or"two-phase") and an optional temperature hint"T"in Kelvin. The phase refers to the side of the two phase dome below the critical pressure and to the side of the critical isotherm above it.
- initialise_source(c, key)[source]¶
Return a generic pressure starting value at the outlet.
Only consulted as the last fallback tier when neither user values, propagation nor the temperature field anchors covered the pressure. Enthalpy starting values are generated by the automatic starting value machinery instead.
- Parameters:
c (tespy.connections.connection.Connection) – Connection to perform initialisation on.
key (str) – Fluid property to retrieve.
- Returns:
val (float) – Starting value for pressure in SI units, 0 for no information.
\[\begin{split}val = \begin{cases} 0 & \text{key = 'p'}\\ 0 & \text{key = 'h'} \end{cases}\end{split}\]
- initialise_target(c, key)[source]¶
Return a generic pressure starting value at the inlet.
Only consulted as the last fallback tier when neither user values, propagation nor the temperature field anchors covered the pressure. Enthalpy starting values are generated by the automatic starting value machinery instead.
- Parameters:
c (tespy.connections.connection.Connection) – Connection to perform initialisation on.
key (str) – Fluid property to retrieve.
- Returns:
val (float) – Starting value for pressure in SI units, 0 for no information.
\[\begin{split}val = \begin{cases} 0 & \text{key = 'p'}\\ 0 & \text{key = 'h'} \end{cases}\end{split}\]
- property num_heat_i¶
- property num_heat_o¶
- property num_i¶
- property num_o¶
- property num_power_i¶
- property num_power_o¶
- classmethod port_schema()[source]¶
Return a description of the component’s port topology for UI tooling.
The default implementation derives fixed-port descriptions from the
@staticmethodinlets/outlets/powerinlets/poweroutletsmethods. Subclasses with variable or conditional port counts must override this method.- Returns:
dict – Keys are
"inlets","outlets","powerinlets","poweroutlets","heatinlets","heatoutlets". Each value is a dict with at least a"type"key:{"type": "fixed", "ports": [...]}The port list is static.
{"type": "variable", "parameter": str, "pattern": str, "min": int}Port count is controlled by parameter. pattern is a Python format string where
{n}is replaced by the 1-based port index (e.g."in{n}").
- pr_structure_matrix(k, pr=None, inconn=0, outconn=0)[source]¶
Create linear relationship between inflow and outflow pressure
\[p_{in} \cdot pr = p_{out}\]- Parameters:
k (int) – equation number in systems of equations
pr (str) – Component parameter, e.g.
pr1.inconn (int) – Connection index of inlet.
outconn (int) – Connection index of outlet.
- set_attr(**kwargs)[source]¶
Set, reset or unset attributes of a component for provided arguments.
- Parameters:
design (list) – List containing design parameters (stated as String).
offdesign (list) – List containing offdesign parameters (stated as String).
design_path (str) – Path to the components design case.
**kwargs – See the class documentation of desired component for available keywords.
Note
Allowed keywords in kwargs are obtained from class documentation as all components share the
tespy.components.component.Component.set_attr()method.
- variable_equality_structure_matrix(k, **kwargs)[source]¶
Create pairwise linear relationship between two variables
varfor all inlets and the respective outlets. This usually is applied to mass flow, pressure, enthalpy and fluid composition.\[var_\text{in,i} = var_\text{out,i}\]- Parameters:
k (int) – equation number in systems of equations
variable (str) – Connection variable name, e.g.
h.
- zeta_d4_func(zeta=None, inconn=0, outconn=0)[source]¶
Calculate residual value of the \(\zeta/D^4\) pressure loss equation.
- Parameters:
zeta (str) – Component parameter to evaluate the zeta_d4_func on, e.g.
zeta1_d4.inconn (int) – Connection index of inlet.
outconn (int) – Connection index of outlet.
- Returns:
residual (float) – Residual value of function.
\[0 = p_{in} - p_{out} - \frac{\zeta}{D^4} \cdot \frac{8 \cdot \dot{m}_{in} \cdot |\dot{m}_{in}| \cdot \frac{v_{in} + v_{out}}{2}}{\pi^2}\]
Note
The \(\zeta/D^4\) value is calculated on the basis of a given pressure loss at a given flow rate in the design case. As the cross sectional area A will not change, it is possible to handle the equation in this way:
\[\frac{\zeta}{D^4} = \frac{\Delta p \cdot \pi^2} {8 \cdot \dot{m}^2 \cdot v}\]The residual is formulated in terms of the pressure difference: the coefficient formulation saturates at the \(\zeta\) value with vanishing derivatives when the pressure difference approaches zero or the mass flow diverges, leaving the newton algorithm without gradient information exactly where the equation is most violated.
tespy.components.subsystem module¶
Module for custom component groups.
It is possible to create subsystems of component groups in tespy. The subsystem class is the base class for custom subsystems.
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/components/subsystems.py
SPDX-License-Identifier: MIT
- class tespy.components.subsystem.Subsystem(label)[source]¶
Bases:
objectClass Subsystem is the base class of all TESPy subsystems.
- Parameters:
label (str) – The label of the subsystem.
Notes
Subclasses must set the following attributes before calling
super().__init__()to declare the subsystem’s external interfaces:num_in/num_out- number of fluid inlet/outlet ports (exposed asin{n}/out{n}onself.inlet/self.outlet). Default: 0 with a warning.num_power_in/num_power_out- number ofPowerConnectioninlet/ outlet ports (exposed aspower_in{n}/power_out{n}). Default: 0, no warning.num_heat_in/num_heat_out- number ofHeatConnectioninlet/ outlet ports (exposed asheat_in{n}/heat_out{n}). Default: 0, no warning.
For every power or heat port pair the underlying
SubsystemInterfaceenforces \(\dot E_\text{in} = \dot E_\text{out}\), so energy passes through the boundary unchanged.Example
Basic example for a setting up a Subsystem object. This example does not run a TESPy calculation!
>>> from tespy.components import Subsystem >>> class MySubsystem(Subsystem): ... def create_network(self): ... pass >>> mysub = MySubsystem('mySubsystem') >>> type(mysub) <class 'tespy.components.subsystem.MySubsystem'> >>> mysub.label 'mySubsystem' >>> type(mysub.inlet) <class 'tespy.components.basics.subsystem_interface.SubsystemInterface'> >>> type(mysub.outlet) <class 'tespy.components.basics.subsystem_interface.SubsystemInterface'>
If you want to connect to the subsystem from outside of it in a Network, then you have to pass the respective number of inlet and outlet connections. The number is to your choice, but for the Subsystem to be functional, all of the available interfaces must be wired properly internally in the
create_networkmethod. For example, consider a subsystem which is just passing its inlet to the outlet:>>> from tespy.components import Source, Sink >>> from tespy.connections import Connection >>> from tespy.networks import Network >>> class MySubsystem(Subsystem): ... def __init__(self, label): ... self.num_in = 1 ... self.num_out = 1 ... super().__init__(label) ... ... def create_network(self): ... c1 = Connection(self.inlet, "out1", self.outlet, "in1", label="1") ... self.add_conns(c1) >>> mysub = MySubsystem('mySubsystem') >>> nw = Network() >>> so = Source("source") >>> si = Sink("sink") >>> c1 = Connection(so, "out1", mysub, "in1", label="1") >>> c2 = Connection(mysub, "out1", si, "in1", label="2") >>> nw.add_conns(c1, c2) >>> nw.add_subsystems(mysub)
We can run the
check_topologymethod to check if everything is properly connected and a valid topology was created, without needing to parametrize the system (for the sake of simplicity in this example).>>> nw.check_topology()
You can retrieve components and connections from inside the subsystem with their label, which is used inside the
create_networkmethod of the subsystem.>>> type(mysub.get_conn("1")) <class 'tespy.connections.connection.Connection'> >>> type(mysub.get_comp("inlet")) <class 'tespy.components.basics.subsystem_interface.SubsystemInterface'>
Their actual label is prefixed with the subsystem’s label, and therefore to get it from the network level, you must use that label:
>>> mysub.get_conn("1").label 'mySubsystem_1' >>> type(nw.get_conn('mySubsystem_1')) <class 'tespy.connections.connection.Connection'>
The same is true for components:
>>> mysub.get_comp("inlet").label 'mySubsystem_inlet' >>> type(nw.get_comp("mySubsystem_inlet")) <class 'tespy.components.basics.subsystem_interface.SubsystemInterface'>
- classmethod from_dict(subsystem_data, label=None)[source]¶
Create a
Subsysteminstance from serialized state.- Parameters:
subsystem_data (dict) – Serialized structure and parametrization of the subsystem, e.g. created through
from_network(). The data are not modified, so they can be reused to create multiple instances.label (str, optional) – Label of the subsystem. If not provided, the label stored in the
Subsystemsection of the data is used.
- Returns:
tespy.components.subsystem.Subsystem – The subsystem instance.
- classmethod from_network(label, nw, interface_exceptions=None, keep='specifications')[source]¶
Convert a network into a subsystem.
The system boundary components of the network are removed and the connections previously attached to them are rewired to ports of the subsystem’s interfaces, i.e.:
Sink,PowerSourceand
The subsystem’s
interface_mapattribute indicates which source or sink was transformed to which port.- Parameters:
label (str) – Label of the subsystem.
nw (tespy.networks.network.Network) – Network to convert into a subsystem.
interface_exceptions (list, optional) – Labels of boundary components to keep inside the subsystem instead of converting them to interface ports.
keep (str, optional) – Which state of the network to carry into the subsystem, default
"specifications"."specifications": all specifications and values are carried over unchanged."starting_values": all specifications are deactivated, the current values of the variables become starting values for the next solve."nothing": all specifications are deactivated and no values are carried over.
Model data, e.g. characteristic lines, polynomial coefficients or reference definitions, as well as the design/offdesign setup stay on the objects in all modes, only their activation state is cleared
- Returns:
tespy.components.subsystem.Subsystem – The subsystem instance.
Example
Set up a simple network with a heater and convert it to a subsystem.
>>> from tespy.components import SimpleHeatExchanger, Sink, Source >>> from tespy.components import Subsystem >>> from tespy.connections import Connection >>> from tespy.networks import Network >>> nw = Network(iterinfo=False) >>> so = Source("water inlet") >>> hx = SimpleHeatExchanger("heater") >>> si = Sink("water outlet") >>> c1 = Connection(so, "out1", hx, "in1", label="1") >>> c2 = Connection(hx, "out1", si, "in1", label="2") >>> nw.add_conns(c1, c2) >>> c1.set_attr(fluid={"water": 1}, T=20, p=1, m=1) >>> sub = Subsystem.from_network("heating block", nw)
The
interface_mapattribute shows which port of the subsystem replaces which boundary component of the network.>>> sub.interface_map {'in1': 'water inlet', 'out1': 'water outlet'} >>> sub.get_comp("heater").label 'heating block_heater'
All parameter specifications are taken over into the subsystem, including those on the rewired boundary connections.
>>> sub.get_conn("1").T.is_set True
With the
keepparameter the specifications can be deactivated instead, turning the network’s values into starting values for the next solve, or dropping them altogether.>>> sub2 = Subsystem.from_network( ... "heating block 2", nw, keep="starting_values" ... ) >>> sub2.get_conn("1").T.is_set False >>> sub2.get_conn("1").p.val0 1.0 >>> sub3 = Subsystem.from_network("heating block 3", nw, keep="nothing") >>> sub3.get_conn("1").p.val0 nan