matcalc.backend._lammps_engine module

LAMMPS engine shared by the static, relaxation and MD drivers of the LAMMPS backend (_lammps.py).

Calculations run in an in-process LAMMPS instance driven through the lammps Python module. The LAMMPS force field is derived from the ASE calculator or model name in use:

  • MatGL TensorNet / M3GNet potentials are exported to TorchScript with matgl.ext.lammps.export_lammps_model and evaluated with MatGL’s own pair_style matgl, which requires LAMMPS built with the ML-MATGL package. To run through pair_style matgl/kk, build with Kokkos and set e.g. MATCALC_LAMMPS_ARGS="-k on g 1 -sf kk -pk kokkos newton on neigh half".

  • maml potentials wrapped in matcalc.utils.PESCalculator (SNAP, MTP, GAP, NNP) use the pair commands from Potential.write_param.

  • LAMMPSCalculator evaluates arbitrary LAMMPS force-field commands, e.g. EAM or Tersoff potentials.

LAMMPS instances (LAMMPSEngine) are cached per force field and element set, so repeated calculations (phonon displacements, strained cells, …) do not reload the model. Frame maps quantities between the input structure and its restricted-triclinic LAMMPS representation.

class Frame(rot: ndarray, basis: ndarray, ref_frac: ndarray, lammps_frac: ndarray, image_offset: ndarray)[source]

Bases: object

Maps quantities between the Cartesian frame and lattice basis of a structure and its LAMMPS representation.

rot[source]

Orthogonal matrix; Cartesian vectors map as v_lammps = v @ rot.

Type:

numpy.ndarray

basis[source]

Integer unimodular matrix with cell_lammps = basis @ (cell @ rot).

Type:

numpy.ndarray

ref_frac[source]

Fractional coordinates of the input structure, to which positions are unwrapped.

Type:

numpy.ndarray

lammps_frac[source]

Fractional coordinates in the LAMMPS cell as LAMMPS placed the atoms on loading (wrapped into its box, which may differ from ref_frac by lattice vectors, including for atoms on a box face).

Type:

numpy.ndarray

image_offset[source]

Integer lattice offsets, in the input basis, from the loaded LAMMPS images (positions plus image flags) to the input images.

Type:

numpy.ndarray

basis: ndarray[source]
cell(cell_lammps: ndarray) → ndarray[source]

LAMMPS cell -> cell in the input frame and lattice basis.

image_offset: ndarray[source]
lammps_frac: ndarray[source]
positions(x_lammps: ndarray, cell_lammps: ndarray, ref_frac: ndarray | None = None) → tuple[ndarray, ndarray][source]

LAMMPS positions (relative to the box origin) -> positions and fractional coordinates in the input frame.

Each atom takes the periodic image closest to ref_frac (default: the input structure), which undoes the wrapping into the LAMMPS box.

ref_frac: ndarray[source]
rot: ndarray[source]
tensor(tensor_lammps: ndarray) → ndarray[source]

Rank-2 tensor (stress) -> input frame.

vectors(vectors_lammps: ndarray) → ndarray[source]

Per-atom vectors (forces, velocities) -> input frame.

class LAMMPSCalculator(commands: Sequence[str], *, elements: Sequence[str] | None = None, potential_dir: str | Path | None = None, pre_commands: Sequence[str] = (), **kwargs: Any)[source]

Bases: Calculator

ASE calculator that evaluates a LAMMPS force field in an in-process LAMMPS instance.

It works with both simulation backends: with MATCALC_BACKEND=ASE ASE drives the optimizers and MD and calls LAMMPS for energies, forces and stresses; with MATCALC_BACKEND=LAMMPS everything runs in LAMMPS. Under the LAMMPS backend, PropCalc.calculator holds the LAMMPSCalculator for the given calculator (see to_lammps_calculator()), with the original in source.

potential[source]

The LAMMPS force field.

source[source]

The ASE calculator this one was converted from, or None.

Type:

ase.calculators.calculator.Calculator | None

Example

>>> calc = LAMMPSCalculator(
...     ["pair_style eam/alloy", "pair_coeff * * Cu_u3.eam.alloy {symbols}"],
...     elements=["Cu"],
... )
Parameters:
  • commands – LAMMPS force-field commands. {symbols} is replaced by the element symbols in atom-type order.

  • elements – Element symbols in LAMMPS atom-type order. Defaults to the elements of each structure, sorted by atomic number.

  • potential_dir – Directory in which commands are issued, for potential files given by relative paths. Defaults to the directory current at construction.

  • pre_commands – Commands issued before the simulation box is created.

  • **kwargs – Forwarded to ase.calculators.calculator.Calculator.

_abc_impl = <_abc._abc_data object>[source]
calculate(atoms: Atoms | None = None, properties: list[str] | None = None, system_changes: list[str] = ['positions', 'numbers', 'cell', 'pbc', 'initial_charges', 'initial_magmoms']) → None[source]

Compute energy, forces and stress with LAMMPS.

Parameters:
  • atoms – Structure to evaluate.

  • properties – Requested properties; all implemented properties are always computed.

  • system_changes – ASE change list.

classmethod from_potential(potential: LAMMPSPotential, *, source: Calculator | None = None, **kwargs: Any) → LAMMPSCalculator[source]

Create a calculator for an existing force-field specification.

Parameters:
  • potential – The LAMMPS force field.

  • source – The ASE calculator potential was derived from, kept for reference.

  • **kwargs – Forwarded to ase.calculators.calculator.Calculator.

Returns:

LAMMPSCalculator.

implemented_properties: list[str] = ['energy', 'free_energy', 'forces', 'stress'][source]

Properties calculator can handle (energy, forces, …)

source: Calculator | None[source]
class LAMMPSEngine(potential: LAMMPSPotential, elements: tuple[str, ...])[source]

Bases: object

A LAMMPS instance with a force field loaded, reused for any cell and number of atoms.

cell() → ndarray[source]

Current lower-triangular LAMMPS cell.

close() → None[source]

Release the LAMMPS instance.

compute(atoms: Atoms) → tuple[float, ndarray, ndarray][source]

Single point on atoms; forces and stress are returned in the Cartesian frame of atoms.

energy() → float[source]

Potential energy (eV) of the last evaluated step.

gather(name: str) → ndarray[source]

Per-atom 3-vectors (x, v, f or image flags) ordered by atom ID, in the LAMMPS frame.

load(atoms: Atoms, velocities: ndarray | None = None) → Frame[source]

Replace the atoms and box with atoms (velocities in Å/ps, input frame).

origin() → ndarray[source]

Current origin (lower corner, boxlo) of the LAMMPS box.

pin(indices: Sequence[int], frame: Frame) → None[source]

Put atoms indices back on their loaded fractional coordinates in the current cell.

positions() → ndarray[source]

Atom positions relative to the box origin, ordered by atom ID, in the LAMMPS frame.

Box changes (fix box/relax, fix npt, …) scale the box about its center, which moves its origin, so raw LAMMPS coordinates must be taken relative to it.

scoped(setup: Sequence[str], cleanup: Sequence[str]) → Iterator[None][source]

Issue setup, then cleanup on exit, also after an error, so that the cached instance stays reusable.

Cleanup commands run one at a time and failures are logged, not raised: after a failed setup command, cleanup for what was never set up (e.g. unfix of a fix that was not created) is expected to fail.

step() → int[source]

Current timestep (minimizer iterations also advance it).

stress() → ndarray[source]

Virial stress (eV/Å^3, ASE sign convention) of the last evaluated step, in the LAMMPS frame.

class LAMMPSPotential(commands: tuple[str, ...], elements: tuple[str, ...] | None = None, directory: str | None = None, pre_commands: tuple[str, ...] = ())[source]

Bases: object

LAMMPS force-field specification.

commands[source]

Force-field commands (pair_style, pair_coeff, …). The placeholder {symbols} is replaced by the element symbols in LAMMPS atom-type order.

Type:

tuple[str, …]

elements[source]

Element symbols in LAMMPS atom-type order. None uses the elements of each structure, sorted by atomic number, which creates one LAMMPS instance per element set.

Type:

tuple[str, …] | None

directory[source]

Working directory while issuing commands, for potential files given by relative paths.

Type:

str | None

pre_commands[source]

Commands issued before the simulation box is created (e.g. newton on).

Type:

tuple[str, …]

commands: tuple[str, ...][source]
directory: str | None = None[source]
elements: tuple[str, ...] | None = None[source]
pre_commands: tuple[str, ...] = ()[source]
_from_maml(potential: Any) → LAMMPSPotential[source]

Build a LAMMPS force field from a maml Potential via write_param.

_from_matgl(potential: Any) → LAMMPSPotential[source]

Export a MatGL Potential to TorchScript for MatGL’s pair_style matgl.

get_engine(potential: LAMMPSPotential, atoms: Atoms) → LAMMPSEngine[source]

Return a cached LAMMPS instance with potential loaded whose atom types cover the elements of atoms.

get_lammps_potential(calculator: Calculator) → LAMMPSPotential[source]

Return the LAMMPS force field equivalent to an ASE calculator.

Parameters:

calculator – A LAMMPSCalculator, a maml-backed matcalc.utils.PESCalculator, or a MatGL PESCalculator wrapping a TensorNet or M3GNet potential.

Returns:

The LAMMPS force-field specification.

Raises:

TypeError – If calculator has no LAMMPS representation.

kokkos_cmdargs(args: Sequence[str]) → list[str][source]

Set atom/map no in the Kokkos package options of LAMMPS command-line arguments that do not set atom/map.

The device atom map (atom/map device, the Kokkos default on GPUs) crashes when an instance is reloaded with more atoms than it has held before (LAMMPS stable_22Jul2025_update5), which every cached engine does for supercells. The host map is as fast on GPU: pair_style matgl/kk looks atoms up in it in any case.

Parameters:

args – LAMMPS command-line arguments.

Returns:

The arguments with atom/map no inserted after each -pk kokkos, or appended as -pk kokkos atom/map no if Kokkos is enabled without -pk kokkos.

lammps_cell(cell: ndarray) → tuple[ndarray, ndarray][source]

Map a cell onto the restricted triclinic form required by LAMMPS.

The lattice vectors (rows of cell) are transformed by an orthogonal matrix rot into a lower-triangular cell with a positive diagonal, and the tilt factors are then reduced to |xy|, |xz| <= lx/2 and |yz| <= ly/2 by integer combinations of lattice vectors. The reduced cell describes the same periodic system, so energies, per-atom forces and the stress are unchanged. A left-handed cell gives an improper rot, which is fine for any O(3)-invariant potential.

Parameters:

cell – 3x3 matrix with lattice vectors as rows.

Returns:

Cartesian vectors map as v_lammps = v @ rot, and lammps_cell is the reduced lower-triangular cell in that frame.

Return type:

(rot, lammps_cell)

load_lammps_calculator(name: str) → LAMMPSCalculator[source]

Return a LAMMPSCalculator for a model name, without building an ASE calculator for it.

MatGL models (by registry name, alias, raw MatGL name or model directory) are loaded and exported to TorchScript for pair_style matgl once per process. Models of other providers have no LAMMPS representation and are rejected before anything is loaded.

Parameters:

name – Model name, as for PESCalculator.load_universal.

Returns:

LAMMPSCalculator (source is None).

Raises:
  • TypeError – If the model has no LAMMPS representation.

  • ValueError – If name is not a recognized model.

pressure_matrix(p: Sequence[float]) → np.ndarray[source]

3x3 pressure tensor from LAMMPS (xx, yy, zz, xy, xz, yz) components.

scratch_dir() → Path[source]

Per-process directory for exported models, potential files and trajectories, removed at exit.

to_lammps_calculator(calculator: Calculator) → LAMMPSCalculator[source]

Return a LAMMPSCalculator with the force field of an ASE calculator.

Parameters:

calculator – See get_lammps_potential(). A LAMMPSCalculator is returned unchanged.

Returns:

LAMMPSCalculator whose source is calculator.

Raises:

TypeError – If calculator has no LAMMPS representation.