matcalc.backend._lammps module
LAMMPS backend: static calculations, relaxations and molecular dynamics.
The three protocols run on the shared, cached LAMMPS instances of _lammps_engine.py:
run_lammpswithout relaxation is a singlerun 0.run_lammpswith relaxation usesminimize(withfix box/relaxfor the cell), judged by ASE’s convergence criterion.run_lammps_mdruns the ensembles ofMDCalcwith the equivalent LAMMPS time-integration fixes.
Relaxations and MD are separate drivers because LAMMPS treats them differently: minimize and run accept
different fixes (fix box/relax vs fix npt), and MD can be run in chunks without changing the trajectory, while
restarting minimize resets its search direction.
- class _CellTarget(pressure: float = 0.0, hydrostatic: bool = False, exp_cell_factor: float | None = None)[source]
Bases:
objectTarget and convergence settings of a cell relaxation, from ASE cell-filter keyword arguments.
- classmethod from_kwargs(kwargs: dict | None) _CellTarget[source]
- class _MinimizeRecorder(engine: LAMMPSEngine, interval: int)[source]
Bases:
objectRecords minimization frames through a dump file and the thermo log, and writes them as an ASE trajectory.
- write(traj_file: str, atoms: Atoms, final: Atoms) None[source]
Write the recorded frames, ending with
final, the accepted relaxed state.The last minimizer evaluation (e.g. a rejected line-search step) need not be the accepted state, so the final frame is written explicitly, as ASE’s optimizers do.
- _constraints(atoms: Atoms) tuple[list[int], FixSymmetry | None][source]
Indices of atoms fixed by
FixAtomsand theFixSymmetryconstraint, if any; others are not supported.
- _ensemble_fixes(ensemble: str, *, temperature: float, taut: float, taup: float, damp: float, ttime: float, fixed_cell: bool, pressure: float, external_stress: float | ndarray | None, compressibility_au: float | None, mask: Any, chains: str, seed: int | None) list[str][source]
LAMMPS fixes for an
MDCalcensemble; times in ps, pressures in bar.
- _min_style(optimizer: Any, *, relax_cell: bool, kokkos: bool = False) str[source]
Map an ASE optimizer (name or class) to a LAMMPS min_style.
- _minimize(engine: LAMMPSEngine, frame: Frame, atoms: Atoms, fixed: list[int], symmetry: FixSymmetry | None, target: _CellTarget, *, relax_cell: bool, max_steps: int, fmax: float, recorder: _MinimizeRecorder | None) tuple[bool, Frame][source]
Run
minimize(in chunks, see_relax) until ASE’s criterion is met; return it and the final frame.
- _needs_ase_cell_filter(cell_filter_kwargs: dict | None) bool[source]
Whether a cell relaxation needs a feature fix box/relax lacks: a constant volume or a cell mask.
- _read_thermo(log: Path) Any[source]
Thermo output of all runs in a LAMMPS log, with column names made attribute-safe.
- _relax(engine: LAMMPSEngine, atoms: Atoms, *, relax_cell: bool, optimizer: Any, max_steps: int, traj_file: str | None, interval: int, fmax: float, cell_filter_kwargs: dict | None) tuple[Atoms, float, np.ndarray, np.ndarray, bool][source]
Relax
atomswith LAMMPSminimize; returns the relaxed atoms, energy, forces, stress and verdict.LAMMPS scales the box degrees of freedom of
fix box/relaxby the volume rather than by the volume per atom, so its own stopping criterion is far stricter than ASE’s for cells. Cell relaxations therefore run in chunks of_CELL_RELAX_CHUNKiterations and stop once ASE’s criterion is met; restarting also resets the reference cell offix box/relax, as the LAMMPS documentation recommends.fix box/relaxtreats box lengths and tilt factors as independent degrees of freedom, so even a hydrostatic stress changes the shape of an oblique cell along the way, and the relaxation ends slightly off symmetry. ASE’s cell filters deform the cell homogeneously and keep it. After each chunk, the cell and positions are therefore projected onto the symmetry of the input (found with tolerance_SYMPREC) or of aFixSymmetryconstraint, as ASE’sFixSymmetrydoes, and reloaded.
- _residual_force(forces: ndarray, stress: ndarray, cell: ndarray, target: _CellTarget, *, relax_cell: bool) float[source]
Largest generalized force as seen by an ASE optimizer on
FrechetCellFilter(at zero strain).Rotation-dependent (row norms of the cell virial), so
stressmust be in the frame of the input structure.
- _result(atoms: Atoms, energy: float, forces: np.ndarray, stress: np.ndarray, *, structure: Structure | Atoms | None = None, converged: bool | None = None) SimulationResult[source]
Build a SimulationResult, applying the constraints of
atomsto forces and stress asrun_asedoes.
- _snapshot(engine: LAMMPSEngine, frame: Frame, atoms: Atoms) Atoms[source]
Current LAMMPS state as ASE Atoms in the input frame.
Image flags retain boundary crossings between saved frames; the initial lattice offset restores the input images.
- _symmetrize(engine: LAMMPSEngine, frame: Frame, current: Atoms, reference: Atoms, symmetry: FixSymmetry, fixed: list[int]) tuple[Atoms, Frame][source]
Project the change since
currentontosymmetry, as ASE’sFixSymmetrydoes, and reload it.The cell change is symmetrized as a deformation gradient and the internal (non-affine) displacements as vectors. Atoms fixed by
FixAtomskeep their fractional coordinates inreference. Returns the new state and frame.
- _type_masses(atoms: Atoms, engine: LAMMPSEngine) list[str][source]
masscommands so that LAMMPS uses the masses ofatoms(one mass per element).
- run_lammps(structure: Structure | Atoms, calculator: Calculator, *, relax_atoms: bool = False, relax_cell: bool = False, optimizer: Any = 'FIRE', max_steps: int = 500, traj_file: str | None = None, interval: int = 1, fmax: float = 0.1, cell_filter: Any = None, cell_filter_kwargs: dict | None = None) SimulationResult[source]
Run a static calculation or relaxation in LAMMPS with the force field of
calculator.Relaxations use
minimizeand, withrelax_cell,fix box/relax.FixAtomsconstraints becomefix setforce. Convergence is judged by the same criterion asrun_asewithFrechetCellFilter: the largest atomic force and the largest row of the cell virial divided by the number of atoms must not exceedfmax. LAMMPS has no constant-volume or masked cell relaxation; those run with ASE’s optimizer and cell filter, with LAMMPS evaluating every step.- Parameters:
structure – Input structure. Must be periodic in all three directions.
calculator – ASE calculator with a LAMMPS representation: a MatGL
PESCalculator(TensorNet or M3GNet), a maml-backedmatcalc.utils.PESCalculator, or aLAMMPSCalculator.relax_atoms – Whether to relax atomic positions.
relax_cell – Whether to also relax the cell (only with
relax_atoms, as inrun_ase).optimizer – ASE optimizer name or class, mapped to a LAMMPS
min_style(FIRE -> fire, BFGS-type -> cg, MDMin -> quickmin); LAMMPS names (cg, sd, fire, quickmin, hftn) are also accepted. Cell relaxations always use cg or sd, sincefix box/relaxrequires a line-search minimizer.max_steps – Maximum number of minimizer iterations.
traj_file – Optional ASE trajectory file for the relaxation frames.
interval – Frame interval for
traj_file.fmax – Force convergence criterion (eV/Å).
cell_filter – ASE cell filter, used only for constant-volume or masked cell relaxations (default
FrechetCellFilter); otherwise the cell is relaxed withfix box/relax.cell_filter_kwargs –
scalar_pressure(eV/Å^3),hydrostatic_strainandexp_cell_factor(cell_factorfor UnitCellFilter) run in LAMMPS;constant_volumeandmaskrun with ASE’s cell filter.
- Returns:
SimulationResult with energies (eV), forces (eV/Å) and stress (eV/Å^3, 3x3, ASE sign convention) in the Cartesian frame and lattice basis of
structure.convergedis None for a static calculation.- Raises:
TypeError – If
calculatorhas no LAMMPS representation.NotImplementedError – For constraints other than
FixAtomsor unsupportedcell_filter_kwargs.
- run_lammps_md(atoms: Atoms, calculator: Calculator, *, ensemble: str, temperature: float, timestep: float, steps: int, loginterval: int = 1, pressure: float = 0.0, taut: float, taup: float, friction: float = 0.001, ttime: float = 25.0, fixed_cell: bool = False, external_stress: float | np.ndarray | None = None, compressibility_au: float | None = None, mask: Any = None, tchain: int = 3, pchain: int = 3, tloop: int = 1, ploop: int = 1, seed: int | None = None, logfile: str | None = None) list[Atoms][source]
Run MD in LAMMPS with the force field of
calculator; parameters followMDCalcand ASE units.Initial velocities come from
atoms, so both backends start from identical conditions. The NVE integrator is the same velocity Verlet scheme as ASE’s; thermostats and barostats sample the same ensembles with different integrators (e.g. LAMMPSfix nptis MTK, ASENPTis Melchionna), so those trajectories only agree statistically.- Parameters:
atoms – Initial structure with velocities.
calculator – ASE calculator with a LAMMPS representation (see
run_lammps).ensemble –
MDCalcensemble name.nvt_andersenhas no LAMMPS equivalent.temperature – Target temperature (K).
timestep – Time step (fs).
steps – Number of MD steps.
loginterval – Interval between returned frames.
pressure – Target pressure (eV/Å^3) for the Berendsen and MTK barostats.
taut – Thermostat time constant (ASE time units).
taup – Barostat time constant (ASE time units); also used for
npt/npt_nose_hoover, whose ASEpfactorhas no LAMMPS equivalent.friction – Langevin friction (1 / ASE time units).
ttime – Thermostat time for
npt/npt_nose_hoover(fs).fixed_cell – For
npt/npt_nose_hoover, keep the cell fixed (Nose-Hoover NVT withttime), as ASENPTdoes withpfactor=None.external_stress – Target pressure (eV/Å^3, scalar) for
npt/npt_nose_hoover.compressibility_au – Compressibility (Å^3/eV) for the Berendsen barostats; required, as in ASE.
mask – Cell mask for
npt/npt_nose_hoover: None or diagonal (orthogonal cell changes, LAMMPSaniso) or all ones (fully flexible cell, LAMMPStri).tchain – Thermostat chain length (MTK ensembles).
pchain – Barostat chain length (MTK ensembles).
tloop – Thermostat sub-steps (MTK ensembles).
ploop – Barostat sub-steps (MTK ensembles).
seed – Seed for stochastic thermostats.
logfile – Optional LAMMPS log file with thermo output every
logintervalsteps.
- Returns:
Frames at steps 0, loginterval, 2 * loginterval, …, as ASE MD observers record them, each with velocities and a SinglePointCalculator holding energy, forces and stress. Positions are unwrapped.