Skip to content

Heat diffusion

Heat diffusing on a plate from a hot square in its middle.

  • Class: HeatDiffusionSystem
  • Import: from skcomplex.systems.physics.heat import HeatDiffusionSystem
  • Field: physics/heat
  • Topics: field, diffusion, pde
  • References:
    • Fourier 1822
    • Datseris and Parlitz 2022

Use this system

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

from skcomplex.systems.physics.heat import HeatDiffusionSystem

trajectory = HeatDiffusionSystem().prepare().simulate()

Parameters

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

Parameter Default
shape (64, 64)
D 1.0
spacing 1.0
boundary 'zero-flux'
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 lattice
Laws rate
Randomness unknown
Domains real
Structure fixed

Class

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

class HeatDiffusionSystem(BaseSystem):
    """Heat diffusing on a plate from a hot square in its middle.

    The temperature follows `du/dt = D laplacian(u)`.

    The system has the temperature `plate.u`.

    Args:
        shape:
            The number of sites along every dimension.

        D:
            The diffusion coefficient.

        spacing:
            The distance between sites.

        boundary:
            `'periodic'`, `'zero-flux'` for an insulated plate, or `'fixed'` for edges held at zero.

        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.physics.heat import HeatDiffusionSystem
        >>> HeatDiffusionSystem((10, 10), boundary='fixed').prepare().system_.elements[0].space.boundary
        {'u': ('fixed', 0.0)}
    """

    field = 'physics/heat'
    topics = ('field', 'diffusion', 'pde')
    references = ('Fourier 1822', 'Datseris and Parlitz 2022')
    until = 50.0
    dt = 1.0

    def __init__(
        self,
        shape: Sequence[int] = (64, 64),
        *,
        D: float = 1.0,
        spacing: float = 1.0,
        boundary: str = 'zero-flux',
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.shape = shape
        self.D = D
        self.spacing = spacing
        self.boundary = boundary

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of heat diffusing on a plate from a hot square in its middle.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        shape = tuple(self.shape)
        u = np.zeros(shape)
        middle = tuple(slice(size // 2 - max(size // 8, 1), size // 2 + max(size // 8, 1)) for size in shape)
        u[middle] = 1.0
        condition = ('fixed', 0.0) if self.boundary == 'fixed' else self.boundary
        space = LatticeSpace(shape, spacing=self.spacing, boundary={'u': condition})
        plate = HeatElement('plate', u=u.ravel(), D=self.D, space=space)
        conduction = DiffusivityInteraction('conduction', target='plate', state='u', coefficient=lambda s: s.target.D)
        self.system_ = System(self.label, elements=[plate], interactions=[conduction])

Components

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

Elements:

Interactions:

  • DiffusivityInteraction, from Interaction
class HeatElement(Element):
    """Sites of a plate with the temperature `u` and the heat diffusion coefficient `D`.

    Args:
        label:
            The label of the plate.

        u:
            The initial temperature, one value per site or one for all.

        D:
            The diffusion coefficient.

        space:
            The lattice or the mesh of the sites, or `None` for one site.

    Examples:
        >>> from skcomplex.systems.physics.heat import HeatElement
        >>> HeatElement('site', D=0.5).D
        0.5
    """

    def __init__(
        self,
        label: str,
        *,
        u: object = 0.0,
        D: Annotated[float, RealSet.closed_open(0, oo)] = 1.0,
        space: BaseSpace | None = None,
    ) -> None:
        super().__init__(label, space=space)
        self.u = u
        self.D = D

class DiffusivityInteraction(Interaction):
    """Diffusion `du/dt = D laplacian(u)` of a state `u` of a field by a diffusivity `D`.

    Physics names the coefficient a diffusivity, as the thermal diffusivity of heat conduction or the kinematic
    viscosity of the vorticity of a fluid. The diffusivity is uniform in space, a number or a function of the namespace
    that returns an expression of parameters and time. The rate is the Laplacian of the field, which its discretization
    evaluates, so the total of the state on a periodic field stays constant and a point mass spreads as the heat kernel.

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

        target:
            The path of the field whose state diffuses.

        state:
            The name of the state of the field that diffuses.

        coefficient:
            A function of the namespace that returns the diffusivity, or a number.

    Raises:
        ValidationError:
            The state is not a name, or the coefficient is neither callable nor a number.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.core.components.elements import Element
        >>> from skcomplex.core.components.spaces import LatticeSpace
        >>> from skcomplex.core.systems import System
        >>> from skcomplex.systems.physics.common.fields import DiffusivityInteraction
        >>> space = LatticeSpace((40,), spacing=0.1, boundary='periodic')
        >>> rod = Element('rod', values={'u': np.eye(40)[20]}, space=space)
        >>> heat = DiffusivityInteraction('heat', target='rod', state='u', coefficient=0.1)
        >>> trajectory = System(elements=[rod], interactions=[heat]).prepare().simulate(until=1.0, dt=0.01)
        >>> round(float(trajectory.get_values('rod.u')[-1].sum()), 6)
        1.0
    """

    def __init__(
        self,
        label: str,
        *,
        target: Role,
        state: str = 'u',
        coefficient: Callable[[SimpleNamespace], object] | float = 1.0,
    ) -> None:
        super().__init__(label)
        self.target = target
        self.state = state
        self.coefficient = coefficient

    def _check_arguments(self) -> None:
        """Raise an error for an argument the interaction cannot take.

        Raises:
            ValidationError:
                The state is not a name, or the coefficient is neither callable nor a number.
        """
        super()._check_arguments()
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} diffuses the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if not (callable(self.coefficient) or isinstance(self.coefficient, int | float)):
            error_msg = f'The coefficient of {self.label!r} is {self.coefficient!r}. Give a function or a number.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate `D laplacian(u)` of the state.

        Args:
            context:
                The namespace of the field, the time `t`, and the parameters.
        """
        super()._prepare(context)
        u = getattr(context.target, self.state)
        coefficient = self.coefficient(context) if callable(self.coefficient) else self.coefficient
        self.laws_ = [RateLaw(u, coefficient * laplacian(u))]