BGK
The BGK equation of the Sod shock tube over one position and one velocity axis.
- Class:
BGKEquationSystem - Import:
from skcomplex.systems.physics.fluids import BGKEquationSystem - Field:
physics/fluids - Topics:
field,kinetic,phase space,shocks,pde - References:
- Bhatnagar, Gross, and Krook 1954
- Mieussens 2000
- Sod 1978
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 BGKEquationSystem
trajectory = BGKEquationSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
positions |
100 |
velocities |
32 |
knudsen |
0.01 |
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 BGKEquationSystem(BaseSystem):
"""The BGK equation of the Sod shock tube over one position and one velocity axis.
The density relaxes at every position towards the maximum-entropy density with its density, momentum, and energy,
and the gas starts from the two states of the shock tube of Sod on either side of the middle of a unit interval. As
the Knudsen number falls the density moment tends to the Euler solution with the adiabatic index 3 of one velocity
dimension. The system has the density `gas.x`.
Args:
positions:
The number of positions.
velocities:
The number of points of the velocity axis.
knudsen:
The Knudsen number, the relaxation time.
half_width:
The half-width of the 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 BGKEquationSystem
>>> BGKEquationSystem(8, 16).prepare().system_.elements[0].space.prepare().size_
128
"""
field = 'physics/fluids'
topics = ('field', 'kinetic', 'phase space', 'shocks', 'pde')
references = ('Bhatnagar, Gross, and Krook 1954', 'Mieussens 2000', 'Sod 1978')
until = 0.2
dt = 0.05
def __init__(
self,
positions: int = 100,
velocities: int = 32,
*,
knudsen: float = 1e-2,
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
@staticmethod
def _get_maxwellian(
density: npt.NDArray[np.float64],
mean: npt.NDArray[np.float64],
temperature: npt.NDArray[np.float64],
speeds: npt.NDArray[np.floating],
) -> npt.NDArray[np.float64]:
"""Return the Maxwellian of densities, mean velocities, and temperatures.
The Maxwellian is over a velocity axis, a row each.
"""
rows = (speeds[None, :] - mean[:, None]) ** 2 / (2 * temperature[:, None])
return density[:, None] * np.exp(-rows) / np.sqrt(2 * np.pi * temperature[:, None])
@staticmethod
def _get_streaming(_: SimpleNamespace) -> list[Expression]:
"""Return the drift of free streaming over one position and one velocity axis."""
return [coordinate('v'), 0]
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set the system of the Sod shock tube over one position and one velocity axis.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
position = LatticeSpace(
(self.positions,),
spacing=1.0 / self.positions,
boundary='reflecting',
discretization='finite-volume',
)
space = PhaseSpace(position, [AxisSpec('v', self.velocities, -self.half_width, self.half_width)]).prepare()
left = np.arange(self.positions) < self.positions // 2
density = np.where(left, 1.0, 0.125)
temperature = np.where(left, 1.0, 0.8)
values = self._get_maxwellian(density, np.zeros(self.positions), temperature, space.coordinates_['v'])
gas = GasDensityElement('gas', x=values.ravel(), space=space)
stream = AdvectionInteraction('stream', target='gas', state='x', drift=self._get_streaming)
relax = BhatnagarGrossKrookInteraction('relax', target='gas', axes=('v',), time=self.knudsen)
self.system_ = System(
self.label,
elements=[gas],
interactions=[stream, relax],
solver=StrangSplittingSolver(SSPRKSolver(), RK4Solver(0.005), 0.005),
)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
GasDensityElement, fromElement
Interactions:
AdvectionInteraction, fromInteractionBhatnagarGrossKrookInteraction, fromInteraction
class GasDensityElement(PhaseSpaceDensityElement):
"""Phase space density of a gas, drawn as its density along position.
Args:
label:
The label of the gas.
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.systems.physics.fluids._kinetic_equations import GasDensityElement
>>> GasDensityElement('gas', x=0.5).x
0.5
"""
visual = VisualSpec('image', {'moments': (0,)})
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 BhatnagarGrossKrookInteraction(RelaxationTimeInteraction):
"""Relaxation of Bhatnagar, Gross, and Krook of a density.
The density relaxes towards the maximum-entropy density with its moments.
Args:
label:
The label of the interaction, unique among the components of its system.
target:
The path of the field on a phase space.
state:
The name of the state of the density.
axes:
The names of the velocity axes.
time:
A function of the namespace that returns the relaxation time, or a positive number.
Examples:
>>> from skcomplex.systems.physics.fluids import BhatnagarGrossKrookInteraction
>>> BhatnagarGrossKrookInteraction('bgk', target='gas', axes=('v',), time=0.1).axes
('v',)
"""
def __init__(
self,
label: str,
*,
target: Role,
state: str = 'x',
axes: Sequence[str] = ('v',),
time: Callable[[SimpleNamespace], object] | float = 1.0,
) -> None:
super().__init__(label, target=target, state=state, goal=0.0, time=time)
self.axes = axes
def _get_goal(self, namespace: SimpleNamespace) -> object:
"""Return the maximum-entropy density with the moments of the state of the target."""
return maximum_entropy(getattr(namespace.target, self.state), axes=self.axes)