Skip to content

Heated room with a thermostat

A room assembled from thermal and electrical components.

  • Class: HeatedRoomSystem
  • Import: from skcomplex.systems.engineering.control import HeatedRoomSystem
  • Field: engineering/control
  • Topics: control, thermal, acausal components, hysteresis, ode, events
  • References:
    • Fritzson 2015

Use this system

The block imports the class and simulates the system with its default parameters and its tuned run settings.

from skcomplex.systems.engineering.control import HeatedRoomSystem

trajectory = HeatedRoomSystem().prepare().simulate()

Parameters

The model parameters take these defaults, and set_params changes them.

Parameter Default
T 10.0
setting 20.0
band 1.0
outside 5.0
V 230.0
R 25.0
C 200000.0
wall_capacity 1000000.0
wall_conductance 100.0
surface_conductance 50.0
solver 'auto'
backend 'auto'

Tags

The system with its default parameters has these capability tags, which solvers and analyses check.

Tag Values
Time continuous
Space none
Laws equation, update
Randomness deterministic
Domains real
Structure fixed

Class

The source of the class shows how it builds its components from its model parameters.

class HeatedRoomSystem(BaseSystem):
    """A room assembled from thermal and electrical components.

    It is heated under a thermostat with hysteresis. A voltage source drives a heating resistor whose heat enters the
    room, and the room loses heat through a wall of its own heat capacity to the outside air. The thermostat opens the
    switch of the resistor when the room rises through `setting + band / 2` and closes it when the room falls through
    `setting - band / 2`. The system has the room temperature `room.T` and the switch `heater.closed`, in seconds.

    Args:
        T:
            The initial temperature of the room.

        setting:
            The temperature the thermostat keeps.

        band:
            The width of the hysteresis band around the setting.

        outside:
            The temperature of the outside air, which is also the initial temperature of the wall.

        V:
            The voltage of the source.

        R:
            The resistance of the heater.

        C:
            The heat capacity of the room.

        wall_capacity:
            The heat capacity of the wall.

        wall_conductance:
            The thermal conductance between the room and the wall.

        surface_conductance:
            The convective conductance between the wall and the outside air.

        label:
            The label of the system, which names it when it is nested in another one.

        solver:
            The solver of the problem, or `'auto'` for the one the system chooses.

        backend:
            The backend that evaluates the compiled functions, or `'auto'` for the one the system chooses.

    Examples:
        >>> from skcomplex.systems.engineering.control import HeatedRoomSystem
        >>> HeatedRoomSystem(setting=22.0).prepare().system_.interactions[-1].threshold
        21.5
    """

    field = 'engineering/control'
    topics = ('control', 'thermal', 'acausal components', 'hysteresis', 'ode', 'events')
    references = ('Fritzson 2015',)
    until = 14400.0
    dt = 10.0
    observables = (Observable('power', _get_heating_power),)

    def __init__(
        self,
        T: float = 10.0,
        *,
        setting: float = 20.0,
        band: float = 1.0,
        outside: float = 5.0,
        V: float = 230.0,
        R: float = 25.0,
        C: float = 2e5,
        wall_capacity: float = 1e6,
        wall_conductance: float = 100.0,
        surface_conductance: float = 50.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.T = T
        self.setting = setting
        self.band = band
        self.outside = outside
        self.V = V
        self.R = R
        self.C = C
        self.wall_capacity = wall_capacity
        self.wall_conductance = wall_conductance
        self.surface_conductance = surface_conductance

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set `system_` to the components of the system built from its model parameters."""
        super()._prepare(context)
        upper, lower = self.setting + self.band / 2, self.setting - self.band / 2
        self.system_ = System(
            self.label,
            elements=[
                Element('supply', values={'v': 0.0}),
                Element('neutral', values={'v': 0.0}),
                Element('source', values={'i': 0.0}),
                Element('earth', values={'i': 0.0}),
                Element('heater', values={'closed': 1.0}),
                Element('room', values={'T': self.T}),
                Element('wall', values={'T': self.outside}),
            ],
            interactions=[
                VoltageSourceInteraction('mains', a='supply', b='neutral', branch='source', V=self.V),
                GroundInteraction('ground', node='neutral', branch='earth'),
                HeatingResistorInteraction(
                    'heating',
                    a='supply',
                    b='neutral',
                    heated='room',
                    switch='heater',
                    R=self.R,
                ),
                HeatCapacityInteraction('air', node='room', C=self.C),
                ThermalConductorInteraction('inner', a='room', b='wall', G=self.wall_conductance),
                HeatCapacityInteraction('masonry', node='wall', C=self.wall_capacity),
                ConvectionInteraction('surface', node='wall', h=self.surface_conductance, fluid=self.outside),
                SwitchInteraction('open_switch', sensor='room', switch='heater', threshold=upper, value=0.0),
                SwitchInteraction(
                    'close_switch',
                    sensor='room',
                    switch='heater',
                    threshold=lower,
                    value=1.0,
                    direction=-1,
                ),
            ],
        )

Components

The system uses these element and interaction classes, each with its nearest class of the core.

Elements:

Interactions:

  • VoltageSourceInteraction, from Interaction
  • GroundInteraction, from Interaction
  • HeatingResistorInteraction, from Interaction
  • HeatCapacityInteraction, from Interaction
  • ThermalConductorInteraction, from Interaction
  • ConvectionInteraction, from Interaction
  • SwitchInteraction, from Interaction
class Element(BaseElement):
    """An element that holds named values of one thing or of a group of members.

    It holds its values by name, such as the height and mass of a ball in
    `Element('ball', values={'x': 10.0, 'm': 1.0})`, and the laws of the interactions decide which values change. With
    `size` it holds a group of members with values of their own, such as 1000 molecules of a gas, and with `space` one
    member per site, such as the cells of a grid. A subclass may take its values as arguments of `__init__` instead,
    such as a population class with a growth rate. Members whose values change by agent rules, Python functions run for
    each member at each step, act as agents, and their values may be any Python object. It holds a prey population, a
    firm of an economy, and the charge of a capacitor.

    Read more in the user guide, under Elements.

    Args:
        label:
            The name of the element, unique among the components of its system, such as `'rabbits'`.

        values:
            Values by name, such as `{'x': 10.0, 'm': 1.0}`. A derivative or a past value that a law reads starts from
            the value named with primes or a past index, such as `{'x': 10.0, "x'": 3.0}` for a ball thrown upwards or
            `{'y': 1.0, 'y[-1]': 0.5}` for an economy. A group of members takes one value per member as an array.

        size:
            The number of members, each with its own values, such as `1000` molecules of a gas, or `None` for one.

        space:
            The space of the element, with one member per site, such as a lattice of cells, or `None` for none.

        on:
            The part of a network space that holds one member each: `'edges'` for every link, `'hyperedges'` for every
            hyperedge, the name of a layer for every link of that layer, such as `'immune'`, or `None` for every site.

    Attributes:
        default_visual_:
            How the element is drawn by default, the `visual` of its class.

    See Also:
        BaseElement: The base of every element.
        Interaction: States the laws that change the values of elements.

    Examples:
        >>> from skcomplex.core.components.elements import Element
        >>> ball = Element('ball', values={'x': 10.0, 'm': 1.0})
        >>> ball.get_params()['x']
        10.0
    """

    law_classes: ClassVar[tuple[type, ...]] = ()

    def __init__(
        self,
        label: str,
        *,
        values: Mapping[str, object] | None = None,
        size: int | None = None,
        space: BaseSpace | None = None,
        on: str | None = None,
    ) -> None:
        super().__init__(label)
        self.values = values
        self.size = size
        self.space = space
        self.on: object = on

    def get_params(self, deep: bool = True) -> dict[str, Any]:
        """Return the parameters of the element, with each entry of `values` when deep.

        An entry of `values` whose name is a Python identifier is listed under its own name, so a system lists it as
        `<element>__<name>` and `set_params(ball__x=2.0)`, grid searches, and sweeps reach it. A primed or past value,
        such as `"x'"` or `'x[-1]'`, is no identifier and stays inside `values`. An entry that has the name of an
        argument is not listed twice.

        Args:
            deep:
                Whether to add the parameters of nested estimators and the entries of `values`.

        Returns:
            params:
                The parameters by name.

        Examples:
            >>> from skcomplex.core.components.elements import Element
            >>> params = Element('ball', values={'x': 10.0, "x'": 3.0}).get_params()
            >>> params['x'], "x'" in params
            (10.0, False)
        """
        params = super().get_params(deep=deep)
        if deep and isinstance(self.values, Mapping):
            entries = self._get_value_entries()
            params.update({name: value for name, value in entries.items() if name not in params})
        return params

    def set_params(self, **params: object) -> Self:
        """Set parameters of the element and entries of `values` by name.

        An entry of `values` takes its new value in a new mapping, so the mapping the user gave never changes, as
        `clone` of scikit-learn leaves the arguments of an estimator unchanged. A new `values` is set first, so the
        output of `get_params` is accepted as it is.

        Args:
            **params:
                The new values, by the name of a parameter or of an entry of `values`, such as `x=2.0`.

        Returns:
            self:
                The element.

        Examples:
            >>> from skcomplex.core.components.elements import Element
            >>> values = {'x': 10.0}
            >>> Element('ball', values=values).set_params(x=2.0).values, values
            ({'x': 2.0}, {'x': 10.0})
        """
        arguments = super().get_params(deep=True)
        if 'values' in params:
            super().set_params(values=params['values'])
        entries = self._get_value_entries()
        changed = {name: value for name, value in params.items() if name in entries and name not in arguments}
        rest = {name: value for name, value in params.items() if name not in changed and name != 'values'}
        super().set_params(**rest)
        if changed:
            self.values = {**(self.values or {}), **changed}
        return self

    def _get_value_entries(self) -> dict[str, object]:
        """Return the entries of `values` whose names are Python identifiers."""
        values = self.values if isinstance(self.values, Mapping) else {}
        return {name: value for name, value in values.items() if name.isidentifier()}

    def _prepare(self, context: BaseSpace | None = None) -> None:
        """Set `default_visual_`, checking the reserved names.

        Args:
            context:
                The space the element inherits from its system, which an element with `on` and no space of its own
                sits on.

        Raises:
            ValidationError:
                `size` is not a number of members, `space` is not a space, or `values` is not a mapping, as when a
                subclass stores a quantity of its own under a reserved name.
        """
        super()._prepare(context)
        size = self.size
        checks = {
            'size': size is None or (isinstance(size, numbers.Integral) and not isinstance(size, bool) and size >= 1),
            'space': self.space is None or isinstance(self.space, BaseSpace),
            'values': self.values is None or isinstance(self.values, Mapping),
        }
        for name, valid in checks.items():
            if not valid:
                error_msg = (
                    f'Element {self.label!r} has {name} = {getattr(self, name)!r}, but {name} is the '
                    f'{RESERVED_MEANINGS[name]}. The names {", ".join(RESERVED)} are reserved, so rename the value, '
                    f'such as half_side for the half side of a table.'
                )
                raise ValidationError(error_msg)
        self._check_on(self.space if self.space is not None else context)

    def _get_tags(self) -> Tags:
        """Return the tags of the element, with the tags of its space when it has one.

        A field on a phase space thus asks for a solver that supports phase spaces, as a group on it does.
        """
        tags = super()._get_tags()
        if not isinstance(self.space, BaseSpace):
            return tags
        return replace(tags, space=self.space.get_tags().space)

    def _check_on(self, space: BaseSpace | None) -> None:
        """Raise an error for an `on` that names no part of a network space.

        A value named `on` that the element declares as its own state or parameter names no place. The space is the
        element's own, or else that of its system.
        """
        if isinstance(type(self)._get_specs().get('on'), _StateSpec | _ParameterSpec):
            return
        on = getattr(self, 'on', None)
        if on is None or (isinstance(space, NetworkSpace) and (on in LINKS or on in space.prepare().graphs_)):
            return
        error_msg = (
            f'Element {self.label!r} has on = {on!r}, but on is the part of a network space that holds one member '
            "each, 'edges', 'hyperedges', or the name of a layer for its edges, such as "
            "Element('links', values={'sign': 1}, space=network, on='edges'). The names "
            f'{", ".join(RESERVED)} are reserved, so rename a value of the element named on, such as closed for a '
            'switch.'
        )
        raise ValidationError(error_msg)

    @staticmethod
    def _get_domain_of(annotation: object, value: object) -> object:
        """Return the domain of a value from its annotation or its Python type.

        A value without an annotation, such as one given through `values`, takes the domain of its type, so `3` is an
        integer and `0.5 + 1j` is complex. The annotation `object` says nothing of the kind, so a value annotated so,
        such as a point that may be one number or an array of complex numbers, also takes the domain of its type, and
        so does a value of one of several types, such as `float | Sequence[float]`. A subshift, such as
        `Annotated[int, SubshiftSpec(LatticeNeighborhood(((0,), (1,))), ((1, 1),))]`, is the domain of the cells of a
        lattice whose configurations hold no forbidden word.
        """
        if get_origin(annotation) is Annotated:
            for item in get_args(annotation)[1:]:
                if isinstance(item, set | frozenset):
                    return FiniteEnumeratedSet(sorted(item, key=str))
                allowed = hasattr(item, '__contains__') and not isinstance(item, str | MatrixGroupSpec)
                if allowed or isinstance(item, SubshiftSpec | PowerSeriesSpec):
                    return item
            annotation = get_args(annotation)[0]
        annotated = isinstance(annotation, type) and annotation not in {inspect.Parameter.empty, object}
        kind = annotation if annotated else type(value)
        if kind is bool:
            return BOOLEAN
        if kind is int:
            return ZZ
        if kind is complex or (isinstance(kind, type) and issubclass(kind, np.complexfloating)):
            return CC
        return RR

    def _get_domain_tags(self) -> frozenset[str]:
        """Return the domain tags of the states of the element.

        An element that declares no states has the domains of all its numeric values, since the laws of the system
        decide which of them are states, such as `boolean` for `opinion: Annotated[int, {0, 1}] = 0`.
        """
        if self._get_component_specs():
            return super()._get_domain_tags()
        params = self.get_params(deep=False)
        values = {name: params.get(name) for name in self._get_hints()}
        values |= {name: value for name, value in (self.values or {}).items() if name.isidentifier()}
        hints = self._get_hints()
        domains = {
            _StateSpec(domain=self._get_domain_of(hints.get(name, inspect.Parameter.empty), value))._get_domain_tag()
            for name, value in values.items()
            if isinstance(value, numbers.Number | list | np.ndarray)
        }
        return frozenset(domain for domain in domains if domain is not None)

    def _get_hints(self) -> dict[str, object]:
        """Return the type hint of every value argument by name, in their order.

        The hints are the annotations of the arguments of the class, such as `Annotated[float, Quantity('energy')]`,
        from which the kind, the allowed values, the quantity, and the period of each value are read. A generic
        subclass that takes its values through `values` gives their hints here instead, and the arguments it leaves
        out, such as the allowed values themselves, are no values.
        """
        parameters = inspect.signature(type(self)).parameters
        return {name: parameter.annotation for name, parameter in parameters.items() if name not in RESERVED}

    @classmethod
    def _get_view(cls) -> type | None:
        """Return the class of the views of the element's agents.

        The result is `None` for the engine's plain view. An agent element names a subclass of the engine's `AgentView`
        that annotates its states and parameters, such as `class WordView(AgentView): count: float`, so its rules read
        them with checked types.
        """
        return None

class VoltageSourceInteraction(BranchInteraction):
    """Ideal source that holds the node `a` at the voltage `V` above the node `b`.

    Its current `i`, from `a` through the source to `b`, lives on the element `branch`.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the positive node.

        b:
            The path of the negative node.

        branch:
            The path of the element that holds the current `i` of the source.

        V:
            The voltage.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import VoltageSourceInteraction
        >>> VoltageSourceInteraction('battery', a='plus', b='minus', branch='cell', V=9.0).V
        9.0
    """

    def __init__(self, label: str, *, a: Role, b: Role, branch: Role, V: float = 1.0) -> None:
        super().__init__(label, a=a, b=b)
        self.branch = branch
        self.V = V

    def _get_branch_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the voltage of the source as the equation of its current, and the current into both balances."""
        i = s.branch.i
        return [
            ConstraintLaw(s.a.v - s.b.v, s.V, target=i),
            ConstraintLaw(-i, 0, target=s.a.v),
            ConstraintLaw(i, 0, target=s.b.v),
        ]

class GroundInteraction(Interaction):
    """Reference that holds the potential of a node at zero.

    The current that the ground feeds into the node, `i` of the element `branch`, balances the node.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        node:
            The path of the node held at zero potential.

        branch:
            The path of the element that holds the current `i` from the ground into the node.

    Examples:
        >>> from skcomplex.systems.engineering.common.electrical import GroundInteraction
        >>> GroundInteraction('ground', node='bottom', branch='earth').node
        'bottom'
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (ConstraintLaw,)

    def __init__(self, label: str, *, node: Role, branch: Role) -> None:
        super().__init__(label)
        self.node = node
        self.branch = branch

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the zero potential as the equation of the current, and the current into the balance of the node.

        Args:
            context:
                The namespace of the node and the branch.
        """
        super()._prepare(context)
        i = context.branch.i
        self.laws_: list[BaseLaw] = [
            ConstraintLaw(context.node.v, 0, target=i),
            ConstraintLaw(i, 0, target=context.node.v),
        ]

class HeatingResistorInteraction(BranchInteraction):
    """Resistor between the electrical nodes `a` and `b` that heats the thermal node `heated`.

    It conducts while the value `closed` of the element `switch` is 1. Its current is `closed (a.v - b.v) / R`, and
    the power it dissipates, the voltage times the current, flows into the heated node.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the electrical node the current leaves.

        b:
            The path of the electrical node the current enters.

        heated:
            The path of the thermal node the heat enters, an element with the temperature `T`.

        switch:
            The path of the element that holds the switch `closed`, 1 for closed and 0 for open.

        R:
            The resistance.

    Examples:
        >>> from skcomplex.systems.engineering.control import HeatingResistorInteraction
        >>> HeatingResistorInteraction('heating', a='supply', b='neutral', heated='room', switch='heater', R=25.0).R
        25.0
    """

    def __init__(
        self,
        label: str,
        *,
        a: Role,
        b: Role,
        heated: Role,
        switch: Role,
        R: Annotated[float, POSITIVE] = 1.0,
    ) -> None:
        super().__init__(label, a=a, b=b)
        self.heated = heated
        self.switch = switch
        self.R = R

    def _get_branch_laws(self, s: SimpleNamespace) -> list[BaseLaw]:
        """Return the switched current into both electrical balances and the power into the thermal balance."""
        voltage = s.a.v - s.b.v
        current = s.switch.closed * voltage / s.R
        return [
            ConstraintLaw(-current, 0, target=s.a.v),
            ConstraintLaw(current, 0, target=s.b.v),
            ConstraintLaw(voltage * current, 0, target=s.heated.T),
        ]

class HeatCapacityInteraction(Interaction):
    """Heat capacity `C` of a node of temperature `T`, which stores the heat `C T'` that flows into the node.

    The heat flows of the components that join a node add into its balance, which is zero, so with a capacity the node
    warms at `T' = Q / C` under the net heat flow `Q` into it.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        node:
            The path of the node, an element with the temperature `T`.

        C:
            The heat capacity.

    Examples:
        >>> from skcomplex.systems.engineering.control import HeatCapacityInteraction
        >>> HeatCapacityInteraction('air', node='room', C=2e5).C
        200000.0
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (ConstraintLaw,)

    def __init__(self, label: str, *, node: Role, C: Annotated[float, POSITIVE] = 1.0) -> None:
        super().__init__(label)
        self.node = node
        self.C = C

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the heat the capacity stores as a term of the balance of the node.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        T = context.node.T
        self.laws_: list[BaseLaw] = [ConstraintLaw(-context.C * T.diff(context.t), 0, target=T)]

class ThermalConductorInteraction(Interaction):
    """Conductor of the heat flow `G (a.T - b.T)` from the node `a` to the node `b`.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        a:
            The path of the node the heat leaves.

        b:
            The path of the node the heat enters.

        G:
            The thermal conductance.

    Examples:
        >>> from skcomplex.systems.engineering.control import ThermalConductorInteraction
        >>> ThermalConductorInteraction('wall', a='room', b='outside', G=2.0).G
        2.0
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (ConstraintLaw,)

    def __init__(self, label: str, *, a: Role, b: Role, G: Annotated[float, POSITIVE] = 1.0) -> None:
        super().__init__(label)
        self.a = a
        self.b = b
        self.G = G

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the heat flow as a term of the balances of both nodes.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        a, b = context.a.T, context.b.T
        flow = context.G * (a - b)
        self.laws_: list[BaseLaw] = [ConstraintLaw(-flow, 0, target=a), ConstraintLaw(flow, 0, target=b)]

class ConvectionInteraction(Interaction):
    """Surface of a node that loses the heat flow `h (T - fluid)` to a fluid of a fixed temperature.

    Args:
        label:
            The label of the interaction, unique among the components of its system.

        node:
            The path of the node, an element with the temperature `T`.

        h:
            The convective conductance of the surface.

        fluid:
            The temperature of the fluid.

    Examples:
        >>> from skcomplex.systems.engineering.control import ConvectionInteraction
        >>> ConvectionInteraction('outside', node='wall', fluid=5.0).fluid
        5.0
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (ConstraintLaw,)

    def __init__(
        self,
        label: str,
        *,
        node: Role,
        h: Annotated[float, POSITIVE] = 1.0,
        fluid: float = 0.0,
    ) -> None:
        super().__init__(label)
        self.node = node
        self.h = h
        self.fluid = fluid

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the heat lost to the fluid as a term of the balance of the node.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        T = context.node.T
        self.laws_: list[BaseLaw] = [ConstraintLaw(-context.h * (T - context.fluid), 0, target=T)]

class SwitchInteraction(Interaction):
    """Switch that opens or closes when the temperature of a sensor crosses a threshold.

    When the temperature `T` of `sensor` crosses `threshold` in `direction`, the value `closed` of `switch` becomes
    `value`, as a thermostat switches a heater or a pressure switch a pump.

    Args:
        label:
            The label of the interaction, which names its events.

        sensor:
            The path of the element whose temperature `T` the switch watches.

        switch:
            The path of the element that holds the switch `closed`.

        threshold:
            The temperature at which the switch acts.

        value:
            The value the switch takes, 1 for closed and 0 for open.

        direction:
            The direction of the crossing, 1 when the temperature rises and -1 when it falls.

    Examples:
        >>> from skcomplex.systems.engineering.control import SwitchInteraction
        >>> SwitchInteraction('open_switch', sensor='room', switch='heater', threshold=20.5, value=0.0).direction
        1
    """

    law_classes: ClassVar[tuple[type[BaseLaw], ...]] = (EventLaw,)

    def __init__(
        self,
        label: str,
        *,
        sensor: Role,
        switch: Role,
        threshold: float = 0.0,
        value: float = 0.0,
        direction: int = 1,
    ) -> None:
        super().__init__(label)
        self.sensor = sensor
        self.switch = switch
        self.threshold = threshold
        self.value = value
        self.direction = direction

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the crossing of the threshold and the value of the switch it sets.

        Args:
            context:
                The namespace of the elements a binding of the roles names.
        """
        super()._prepare(context)
        guard = context.sensor.T - context.threshold
        self.laws_: list[BaseLaw] = [
            EventLaw(guard, {context.switch.closed: context.value}, direction=self.direction),
        ]