Lennard-Jones fluid
Lennard-Jones particles in a periodic square box.
- Class:
LennardJonesFluidSystem - Import:
from skcomplex.systems.physics.statistical_mechanics import LennardJonesFluidSystem - Field:
physics/statistical_mechanics - Topics:
molecular dynamics,pair potential,ode - References:
- Lennard-Jones 1924
- Verlet 1967
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.statistical_mechanics import LennardJonesFluidSystem
trajectory = LennardJonesFluidSystem().prepare().simulate()
Parameters
The model parameters take these defaults, and set_params changes them.
| Parameter | Default |
|---|---|
n_particles |
400 |
density |
0.5 |
temperature |
None |
cutoff |
2.5 |
random_state |
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 | continuous |
| Laws | rate |
| Randomness | unknown |
| Domains | vector |
| Structure | fixed |
Class
The source of the class shows how it builds its components from its model parameters.
class LennardJonesFluidSystem(BaseSystem):
"""Lennard-Jones particles in a periodic square box.
A thermostat optionally holds the particles at a temperature.
The system has the particle group `fluid` in two dimensions.
Args:
n_particles:
The number of particles.
density:
The number of particles per unit area.
temperature:
The temperature of the Langevin thermostat, or `None` for constant energy. A thermostat makes the system
stochastic, so it runs with the Euler-Maruyama solver instead of the default velocity Verlet.
cutoff:
The distance beyond which pairs do not interact.
random_state:
The seed or generator of the initial jitter and velocities.
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.statistical_mechanics import LennardJonesFluidSystem
>>> LennardJonesFluidSystem(100).prepare().system_.elements[0].size
100
"""
field = 'physics/statistical_mechanics'
topics = ('molecular dynamics', 'pair potential', 'ode')
references = ('Lennard-Jones 1924', 'Verlet 1967')
until = 0.5
dt = 0.005
def __init__(
self,
n_particles: int = 400,
*,
density: float = 0.5,
temperature: float | None = None,
cutoff: float = 2.5,
random_state: int | np.random.Generator | None = 0,
label: str = 'system',
solver: BaseSolver | str = 'auto',
backend: BaseBackend | str = 'auto',
) -> None:
super().__init__(label, solver=solver, backend=backend)
self.n_particles = n_particles
self.density = density
self.temperature = temperature
self.cutoff = cutoff
self.random_state = random_state
def _prepare(self, context: Sequence[Observable] | None = None) -> None:
"""Set `system_` to the particles on a jittered grid, with an optional thermostat.
Args:
context:
The observables to compile with the problem, or `None` for none.
"""
super()._prepare(context)
rng = np.random.default_rng(self.random_state)
size = float(np.sqrt(self.n_particles / self.density))
side = int(np.ceil(np.sqrt(self.n_particles)))
spacing = size / side
grid = np.stack(np.meshgrid(np.arange(side), np.arange(side)), axis=-1).reshape(-1, 2)[: self.n_particles]
positions = np.mod((grid + 0.5) * spacing + rng.normal(0, 0.02 * spacing, (self.n_particles, 2)), size)
velocities = rng.normal(0, np.sqrt(self.temperature or 1.0), (self.n_particles, 2))
velocities -= velocities.mean(axis=0)
interactions: list[BaseInteraction] = [
LennardJonesInteraction('lj', target='fluid', cutoff=self.cutoff),
]
if self.temperature is not None:
interactions.append(
LangevinThermostatInteraction('thermostat', target='fluid', temperature=self.temperature),
)
box = ContinuousSpace(extent=(size, size), boundary='periodic')
fluid = MassPointElement('fluid', x=positions, values={"x'": velocities}, size=self.n_particles, space=box)
solver = VelocityVerletSolver() if self.temperature is None else 'auto'
self.system_ = System(self.label, elements=[fluid], interactions=interactions, space=box, solver=solver)
Components
The system uses these element and interaction classes, each with its nearest class of the core.
Elements:
MassPointElement, fromElement, through the shared recipePointElement
Interactions:
LennardJonesInteraction, fromInteraction
class MassPointElement(PointElement):
"""Point mass, a point at the position `x` with the mass `m`.
The forces on the point give the acceleration `x''` of its position divided by its mass, and its velocity is the
value `x'`. It is an atom of a gas, a bead of a polymer, or a star of a cluster.
Args:
label:
The label of the point.
x:
The initial position. A number applies to every component.
m:
The mass.
values:
Further values by name, such as the starting velocity `"x'"`.
size:
The number of points, or `None` for one.
space:
The space whose sites hold one point each, or `None`.
Examples:
>>> from skcomplex.systems.physics.common.particles import MassPointElement
>>> MassPointElement('ball', x=[0.0, 1.0], m=2.0, values={"x'": [1.0, 0.0]}).m
2.0
"""
def __init__(
self,
label: str,
x: npt.ArrayLike = 0.0,
*,
m: Annotated[float, RealSet.open(0, oo)] = 1.0,
values: Mapping[str, object] | None = None,
size: int | None = None,
space: BaseSpace | None = None,
) -> None:
super().__init__(label, x=x, values=values, size=size, space=space)
self.m = m
class LennardJonesInteraction(Interaction):
"""Lennard-Jones pair potential without a shift.
The potential is `U(r) = 4 epsilon ((sigma / r)^12 - (sigma / r)^6)`, and every member feels the force `-U'(r)`
along the line of centres from each member within the cutoff, `x_i'' += sum_j -U'(r_ij) (x_i - x_j) / (r_ij m_i)`.
In a periodic box the separations are minimum images. It is the force between atoms of a noble gas, a model fluid
of molecular dynamics, or colloids with a short-range attraction.
Args:
label:
The label of the interaction.
target:
The path of the group of particles.
cutoff:
The distance beyond which pairs do not interact.
epsilon:
The depth of the potential well.
sigma:
The distance at which the potential is zero.
Examples:
>>> from skcomplex.systems.physics.common.particles import LennardJonesInteraction
>>> LennardJonesInteraction('lj', target='gas', cutoff=2.5).sigma
1.0
"""
def __init__(
self,
label: str,
*,
target: Role,
cutoff: Annotated[float, RealSet.open(0, oo)] = 1.0,
epsilon: Annotated[float, RealSet.open(0, oo)] = 1.0,
sigma: Annotated[float, RealSet.open(0, oo)] = 1.0,
) -> None:
super().__init__(label)
self.target = target
self.cutoff = cutoff
self.epsilon = epsilon
self.sigma = sigma
def _prepare(self, context: SimpleNamespace) -> None:
"""Set the force of the neighbours within the cutoff on every particle.
Args:
context:
The namespace of the target, the time `t`, and the parameters.
"""
super()._prepare(context)
s, x = context, context.target.x
separation = x - s.target.other.x
r = sqrt(separation.dot_product(separation))
distance = SR.var('r', domain='positive')
energy = 4 * s.epsilon * ((s.sigma / distance) ** 12 - (s.sigma / distance) ** 6)
slope = energy.diff(distance).subs({distance: r})
force = neighbors(-slope * separation / r, RadiusNeighborhood(self.cutoff))
self.laws_ = [RateLaw(x.diff(s.t, 2), force / s.target.m)]