Skip to content

Boltzmann

The Boltzmann equation of Maxwell molecules.

  • Class: BoltzmannEquationSystem
  • Import: from skcomplex.systems.physics.fluids import BoltzmannEquationSystem
  • Field: physics/fluids
  • Topics: field, kinetic, phase space, collisions, pde
  • References:
    • Bellomo et al. 2017
    • Mouhot and Pareschi 2006

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.fluids import BoltzmannEquationSystem

trajectory = BoltzmannEquationSystem().prepare().simulate()

Parameters

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

Parameter Default
positions 8
velocities 12
knudsen 1.0
half_width 6.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 phase space
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 BoltzmannEquationSystem(BaseSystem):
    """The Boltzmann equation of Maxwell molecules.

    The equation is over one position and two velocity axes.

    Free streaming moves a density wave along the periodic position axis, and binary collisions redistribute the density
    over the velocities at every position, by the fast spectral method. The system has the density `gas.x`.

    Args:
        positions:
            The number of positions.

        velocities:
            The number of points of each velocity axis.

        knudsen:
            The Knudsen number, the inverse of the collision frequency.

        half_width:
            The half-width of each velocity axis.

        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 steps the system chooses.

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

    Examples:
        >>> from skcomplex.systems.physics.fluids import BoltzmannEquationSystem
        >>> BoltzmannEquationSystem(4, 8).prepare().system_.elements[0].space.prepare().size_
        256
    """

    field = 'physics/fluids'
    topics = ('field', 'kinetic', 'phase space', 'collisions', 'pde')
    references = ('Bellomo et al. 2017', 'Mouhot and Pareschi 2006')
    until = 0.5
    dt = 0.1

    @staticmethod
    def _get_plane_streaming(_: SimpleNamespace) -> list[Expression]:
        """Return the drift of free streaming over one position and two velocity axes."""
        return [coordinate('vx'), 0, 0]

    @staticmethod
    def _get_uniform_gas(
        positions: int,
        velocities: int,
        knudsen: float,
        half_width: float,
    ) -> tuple[PhaseSpaceDensityElement, float]:
        """Return a gas over one position and two velocity axes, and its collision rate.

        The gas has a density wave, and the rate is its collision frequency.
        """
        length = 2 * math.pi
        axes = [AxisSpec(name, velocities, -half_width, half_width) for name in VELOCITY_AXES]
        position = LatticeSpace((positions,), spacing=length / positions, discretization='finite-volume')
        space = PhaseSpace(position, axes).prepare()
        vx, vy = np.meshgrid(space.coordinates_['vx'], space.coordinates_['vy'], indexing='ij')
        x = np.arange(positions) * length / positions
        profile = np.exp(-(vx**2 + vy**2) / 2) / (2 * np.pi)
        values = np.multiply.outer(1.0 + 0.2 * np.sin(x), profile)
        return PhaseSpaceDensityElement('gas', x=values.ravel(), space=space), 1.0 / knudsen

    @staticmethod
    def _get_maxwell_molecules(_speed: object, _cosine: object) -> float:
        """Return the cross-section of Maxwell molecules in two velocity dimensions."""
        return 1 / (2 * math.pi)

    def __init__(
        self,
        positions: int = 8,
        velocities: int = 12,
        *,
        knudsen: float = 1.0,
        half_width: float = 6.0,
        label: str = 'system',
        solver: BaseSolver | str = 'auto',
        backend: BaseBackend | str = 'auto',
    ) -> None:
        super().__init__(label, solver=solver, backend=backend)
        self.positions = positions
        self.velocities = velocities
        self.knudsen = knudsen
        self.half_width = half_width

    def _prepare(self, context: Sequence[Observable] | None = None) -> None:
        """Set the system of a density wave of Maxwell molecules over one position and two velocity axes.

        Args:
            context:
                The observables to compile with the problem, or `None` for none.
        """
        super()._prepare(context)
        gas, frequency = BoltzmannEquationSystem._get_uniform_gas(
            self.positions,
            self.velocities,
            self.knudsen,
            self.half_width,
        )
        stream = AdvectionInteraction(
            'stream',
            target='gas',
            state='x',
            drift=BoltzmannEquationSystem._get_plane_streaming,
        )
        collide = EncounterInteraction(
            'collide',
            candidate='gas',
            cross_section=BoltzmannEquationSystem._get_maxwell_molecules,
            factor=lambda _: frequency,
        )
        self.system_ = System(
            self.label,
            elements=[gas],
            interactions=[stream, collide],
            solver=StrangSplittingSolver(SemiLagrangianSolver(0.1), RK4Solver(0.05), 0.1),
        )

Components

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

Elements:

  • PhaseSpaceDensityElement, from Element

Interactions:

  • AdvectionInteraction, from Interaction
  • EncounterInteraction, from Interaction, through the shared recipe EncounterInteraction
class PhaseSpaceDensityElement(Element):
    """Value `x` of the one-particle density of kinetic theory at every point of a phase space.

    A gas is one member per position and velocity of a `PhaseSpace`, and streaming, collisions, and relaxation change
    it. The density is nonnegative.

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

        x:
            The initial density, one nonnegative value per point or one for all.

        space:
            The phase space of the points, or `None` for one point.

    Examples:
        >>> from skcomplex.core.components.spaces import AxisSpec, LatticeSpace, PhaseSpace
        >>> from skcomplex.systems.physics.common.fields import PhaseSpaceDensityElement
        >>> space = PhaseSpace(LatticeSpace(4), [AxisSpec('v', 8, -3.0, 3.0)])
        >>> PhaseSpaceDensityElement('gas', x=0.2, space=space).space.prepare().size_
        32
    """

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

class AdvectionInteraction(Interaction):
    """Advection `du/dt + divergence(a u) = source(ns)` of a state `u` of a field by a drift.

    Physics names it advection, the transport of a state by a flow or by the streaming of a phase-space density.
    The drift field is `a(ns)`. The flux of the conservation law is the drift times the state, written in conservative
    form, so the total of the state on a periodic field stays constant and, on a spectral field, the dealiasing of
    products applies to it. The drift is one expression for a field of one dimension, or one per dimension, of the
    states and parameters of the field, and may read other states than the one it carries, such as the flow of a fluid
    derived from a streamfunction, or the drift of a probability density in a Fokker-Planck equation.

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

        target:
            The path of the field whose state is carried.

        state:
            The name of the carried state of the field.

        drift:
            A function of the namespace that returns the drift, or one drift per dimension.

        source:
            A function of the namespace that returns the source, or `None` for none.

    Raises:
        ValidationError:
            The state is not a name, or a function is not callable.

    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 AdvectionInteraction
        >>> space = LatticeSpace((50,), spacing=0.1, boundary='periodic', discretization='finite-volume')
        >>> values = {'u': np.exp(-((np.arange(50) - 25) / 5.0) ** 2)}
        >>> tracer = Element('tracer', values=values, space=space)
        >>> drift = AdvectionInteraction('drift', target='tracer', state='u', drift=lambda s: 1.0)
        >>> trajectory = System(elements=[tracer], interactions=[drift]).prepare().simulate(until=1.0, dt=0.01)
        >>> total = trajectory.get_values('tracer.u')[-1].sum()
        >>> round(float(total), 6) == round(float(values['u'].sum()), 6)
        True
    """

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

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

        Raises:
            ValidationError:
                The state is not a name, the drift is not callable, or the source is neither callable nor `None`.
        """
        super()._check_arguments()
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} carries the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if not callable(self.drift):
            error_msg = f'The drift of {self.label!r} is {self.drift!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)
        if self.source is not None and not callable(self.source):
            error_msg = f'The source of {self.label!r} is {self.source!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate of the divergence of the flux `a u` and the rate of the source.

        Args:
            context:
                The namespace of the field, the time `t`, and the parameters.
        """
        super()._prepare(context)
        u = getattr(context.target, self.state)
        drift = cast('Callable[[SimpleNamespace], object]', self.drift)(context)
        components = drift if isinstance(drift, FreeModuleElement | list | tuple) else [drift]
        self.laws_ = [RateLaw(u, -divergence([SR(component) * u for component in components]))]
        if self.source is not None:
            self.laws_.append(RateLaw(u, self.source(context)))

class EncounterInteraction(Interaction):
    """An interaction where members of two distributions meet and change class.

    A distribution is a group of `NonnegativeElement` with one member per class of a trait. A candidate at class `h`
    meets the field at class `k` at the rate `rate[h, k]`, and the `outcome` says what follows:

    - `'conservative'`: the candidate moves to class `i` with the probability `kernel[h, k, i]`.
    - `'destructive'`: the candidate is removed.
    - `'proliferative'`: the candidate creates a new candidate at class `i` with the probability `kernel[h, k, i]`, or
      at its own class without a kernel.

    The rate and the kernel are functions of the namespace, which holds `namespace.candidate`, `namespace.field`, and
    the parameters. On a `PhaseSpace` encounters pair classes at the same position. Without a field the encounter is a
    linear redistribution between classes. With a `cross_section` the rate is the binary collision integral of kinetic
    theory, evaluated by a fast spectral method, which keeps the density exactly and the momentum and energy to spectral
    accuracy.

    Unlike the `bilinear` form of the core, which its rate laws hold, it names the outcomes of an encounter and builds
    the rates and kernels from them. Choose it when the change of a population comes from binary meetings of its
    members.

    It appears in many fields. Traders exchange wealth when they meet, people shift their opinion after a conversation,
    immune cells destroy tumour cells they meet, and gas molecules change velocity when they collide.

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

        candidate:
            The path of the group of the candidate density.

        field:
            The path of the group of the field density, or `None` for a linear redistribution.

        rate:
            The function `rate(namespace)` of the encounter rate, a number or an expression, or an array `eta[h, k]`
            of them, or `eta[h]` without a field, or `None` with a cross-section.

        kernel:
            The function `kernel(namespace)` of the array `kernel[h, k, i]` of the probabilities of the class of the
            moved or created candidate, or `kernel[h, i]` without a field, or `None` for a destructive encounter or the
            candidate's own class.

        outcome:
            `'conservative'`, `'destructive'`, or `'proliferative'`.

        state:
            The name of the state of the densities.

        cross_section:
            The function `B(speed, cosine)` of arrays of the relative speed and the cosine of the deflection angle, or
            `None` for encounters at a rate.

        factor:
            A function of the namespace that returns a factor of the collision frequency, such as a function of the
            density moment, or `None` for none.

    Raises:
        ValidationError:
            The outcome is unknown, the state is no name, a function is not callable, a conservative encounter has no
            kernel, an encounter without a field is not conservative, an encounter has neither a rate nor a
            cross-section, or a cross-section comes with a rate, a kernel, a field, or an outcome.

    Examples:
        >>> import numpy as np
        >>> from skcomplex.systems.general.kinetics import EncounterInteraction
        >>> kernel = np.full((3, 3, 3), 1 / 3)
        >>> mixing = EncounterInteraction(
        ...     'mixing', candidate='population', field='population', rate=lambda s: 1.0, kernel=lambda s: kernel
        ... )
        >>> mixing.outcome
        'conservative'
        >>> collide = EncounterInteraction('collide', candidate='gas', cross_section=lambda speed, cosine: 1.0)
        >>> collide.rate is None
        True
    """

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

    def __init__(
        self,
        label: str,
        *,
        candidate: Role,
        field: Role | None = None,
        rate: Callable[[SimpleNamespace], object] | None = None,
        kernel: Callable[[SimpleNamespace], object] | None = None,
        outcome: str = 'conservative',
        state: str = 'x',
        cross_section: Callable[..., object] | None = None,
        factor: Callable[[SimpleNamespace], object] | None = None,
    ) -> None:
        super().__init__(label)
        self.candidate = candidate
        self.field = field
        self.rate = rate
        self.kernel = kernel
        self.outcome = outcome
        self.state = state
        self.cross_section = cross_section
        self.factor = factor

    def _check_collision(self) -> None:
        """Raise an error for a cross-section or factor that is no function, or misused.

        A cross-section may not come with the others.
        """
        if not callable(self.cross_section):
            error_msg = f'The cross-section of {self.label!r} is {self.cross_section!r}. Give a function of two arrays.'
            raise ValidationError(error_msg)
        if self.factor is not None and not callable(self.factor):
            error_msg = f'The factor of {self.label!r} is {self.factor!r}. Give a function of the namespace.'
            raise ValidationError(error_msg)
        others = self.rate, self.kernel, self.field
        if any(item is not None for item in others) or self.outcome != 'conservative':
            error_msg = f'The cross-section of {self.label!r} sets the rate. Give no rate, kernel, field, or outcome.'
            raise ValidationError(error_msg)

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

        Raises:
            ValidationError:
                The outcome is unknown, the state is no name, a function is not callable, a conservative encounter has
                no kernel, an encounter without a field is not conservative, an encounter has neither a rate nor a
                cross-section, or a cross-section comes with a rate, a kernel, a field, or an outcome.
        """
        super()._check_arguments()
        self._check_encounter()

    def _prepare(self, context: SimpleNamespace) -> None:
        """Set the rate law of the candidate for a binding.

        Args:
            context:
                The namespace of the candidate and the field.
        """
        super()._prepare(context)
        self.laws_: list[BaseLaw] = self._get_encounter_laws(context)

    def _check_encounter(self) -> None:
        """Raise an error for an unknown outcome, a bad function, or a missing kernel."""
        if not isinstance(self.state, str) or not self.state.isidentifier():
            error_msg = f'{type(self).__name__} {self.label!r} reads the state {self.state!r}, which is no name.'
            raise ValidationError(error_msg)
        if self.cross_section is not None:
            self._check_collision()
            return
        if self.factor is not None:
            error_msg = f'The factor of {self.label!r} scales a cross-section. Give `cross_section`.'
            raise ValidationError(error_msg)
        if self.outcome not in OUTCOMES:
            error_msg = (
                f'The outcome of encounter {self.label!r} is {self.outcome!r}. Use one of {", ".join(OUTCOMES)}.'
            )
            raise ValidationError(error_msg)
        if not callable(self.rate) or (self.kernel is not None and not callable(self.kernel)):
            error_msg = f'The rate and the kernel of encounter {self.label!r} must be functions of the namespace.'
            raise ValidationError(error_msg)
        if self.outcome == 'conservative' and self.kernel is None:
            error_msg = f'The conservative encounter {self.label!r} moves candidates by a kernel. Give `kernel`.'
            raise ValidationError(error_msg)
        if self.field is None and self.outcome != 'conservative':
            error_msg = f'The {self.outcome} encounter {self.label!r} reads a density of others. Give `field`.'
            raise ValidationError(error_msg)

    def _get_linear_laws(self, candidate: Expression, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the rate law of a redistribution without a field.

        Its rate is a conserved bilinear form.

        It uses one field class of value one.
        """
        assert self.rate is not None
        rate = np.asarray(self.rate(namespace), dtype=object)
        rates = rate if rate.ndim == 0 else rate.reshape(-1, 1)
        kernel = np.asarray(self.kernel(namespace) if self.kernel is not None else (), dtype=object)
        outcomes = np.expand_dims(kernel, axis=1)
        form = bilinear(rates[()], outcomes, candidate, conserved=True)
        return [RateLaw(candidate, form)]

    def _get_encounter_laws(self, namespace: SimpleNamespace) -> list[BaseLaw]:
        """Return the rate law of the encounters or the collisions of the candidate."""
        candidate = getattr(self._get_member(namespace, 'candidate'), self.state)
        if self.cross_section is not None:
            factor = SR(1 if self.factor is None else self.factor(namespace))
            return [RateLaw(candidate, factor * collision_integral(candidate, self.cross_section))]
        if self.field is None:
            return self._get_linear_laws(candidate, namespace)
        field = getattr(self._get_member(namespace, 'field'), self.state)
        assert self.rate is not None
        rate = self.rate(namespace)
        kernel = None if self.kernel is None else self.kernel(namespace)
        if self.outcome == 'destructive':
            loss = -np.asarray(rate, dtype=object)
            form = bilinear(loss, None, candidate, field)
        elif self.outcome == 'proliferative':
            form = bilinear(rate, kernel, candidate, field)
        else:
            form = bilinear(rate, kernel, candidate, field, conserved=True)
        return [RateLaw(candidate, form)]