maxwelllink.matter.md.md_engine module

Central built-in classical molecular-dynamics (MD) engine of MaxwellLink.

class maxwelllink.matter.md.md_engine.MDEngine[source]

Bases: object

Batch-first classical-MD propagator with a pluggable force field. Not used directly by users.

__init__(ff='qtip4pf', n_molecules=None, positions=None, xyz=None, batch_xyz=None, box=None, replicate=None, rcut=None, ewald_wrcut=None, thermostat='nve', temperature_K=300.0, friction_fs=100.0, init_velocities=True, pre_nvt=False, pre_nvt_duration_ps=20.0, reset_dipole=True, seed=0, force_evaluator='auto', property_filename=None, traj_filename=None, record_every_steps=10, record_max_steps=None, checkpoint=False, restart=False, verbose=False, *, property_list='base', traj_content='positions', pre_nvt_timestep_fs=None, pre_nvt_friction_fs=100.0, num=1, xp=np, label='MDEngine')[source]

Validate the run parameters and build the force field.

Parameters:
  • ff (str or DummyForceField, default: 'qtip4pf') – Name of a registered force field ('qtip4pf' for flexible water, 'co2jcp2021' for flexible CO2, 'cs2compass' for flexible CS2, 'ch4compass' for flexible CH4), or an already constructed DummyForceField instance.

  • n_molecules (int, optional) – Number of molecules to build when positions is not given (before any replicate). If None (the default) each force field applies its own default count (32 for water, 36 for CO2 and CS2, 100 for CH4, which load the bundled bulk boxes).

  • positions (array-like of float, shape (n_atoms, 3), optional) – Initial atomic positions in Bohr. If None the force field builds a default geometry from n_molecules (and box).

  • xyz (str, optional) – Path to an XYZ file (Angstrom) to take the starting geometry from, with the atoms in the order the force field expects ([C, O, O, ...] for CO2, [O, H, H, ...] for water, [C, S, S, ...] for CS2, [C, H, H, H, H, ...] for CH4). Overrides positions; but this also gives coordinates only, so a periodic system still needs box.

  • batch_xyz (str, optional) – Path to a multi-frame XYZ file (Angstrom) that gives every molecule its own starting geometry: molecule m starts from frame m, so a batch of drivers, or several batches, read consecutive frames and the same molecule ID always gets the same frame. Every frame must list the same atoms; there must be more frames than the largest molecule ID. Frame 0 doubles as the template geometry when neither xyz nor positions is given.

  • box (float or array-like of float, shape (3,), optional) – Periodic box lengths in Bohr. None treats the system as a finite cluster.

  • replicate (int or array-like of int, shape (3,), optional) – Replicate the periodic cell. The molecules and the box lengths grow together, so the density is unchanged.

  • rcut (float, optional) – Real-space cutoff in Bohr for the periodic non-bonded sums.

  • ewald_wrcut (float, optional) – Real-space cutoff in Bohr for the Ewald sum (periodic electrostatics).

  • thermostat ({'nve', 'nvt'}, default: 'nve') – Ensemble. 'nve' is plain velocity Verlet; 'nvt' adds a Langevin (Ornstein-Uhlenbeck) thermostat.

  • temperature_K (float, default: 300.0) – Target temperature in Kelvin (NVT) and temperature for the initial Maxwell-Boltzmann velocities.

  • friction_fs (float, default: 100.0) – Langevin relaxation time in femtoseconds (gamma = 1 / tau). Only used when thermostat == 'nvt'.

  • init_velocities (bool, default: True) – Whether to sample initial velocities from a Maxwell-Boltzmann distribution at temperature_K. If False the system starts at rest.

  • pre_nvt (bool, default: False) – Whether to thermally equilibrate the system inside initialize() before any production dynamics. The random seed is offset by the molecule ID so that different molecules are decorrelated even at the same seed.

  • pre_nvt_duration_ps (float, default: 20.0) – Duration of the pre-NVT equilibration in picoseconds. It uses a Langevin thermostat at temperature_K with pre_nvt_friction_fs damping, regardless of the production thermostat.

  • pre_nvt_friction_fs (float, default: 100.0) – Pre-NVT Langevin relaxation time in femtoseconds; must be finite and positive. Independent of the production friction_fs.

  • pre_nvt_timestep_fs (float, optional) – Pre-NVT timestep in femtoseconds; None uses the coupling timestep. The coupling timestep is restored after equilibration.

  • reset_dipole (bool, default: True) – Whether to report the dipole moment relative to its value at time zero.

  • seed (int, default: 0) – Base seed; system molecule_id draws from seed + molecule_id.

  • force_evaluator ({'auto', 'numba', 'numpy'}, default: 'auto') – Which force evaluator to use. 'numba' uses the compiled loop-form kernels, which are typically several times faster than the array-at-a-time NumPy reference and allocate no (na, na, 3) temporaries; 'numpy' forces the reference implementation. 'auto' picks 'numba' whenever the force field provides a compiled-kernel description and silently falls back to 'numpy' when it does not. The GPU backend always runs the compiled kernels.

  • property_filename (str, optional) – Turns on a run-time record of per-molecule properties written to this file every record_every_steps production steps: HDF5, streamed while the run goes, unless the name ends in .npz or h5py is missing.

  • property_list (str or list or tuple, default: "base") – Properties written to property_filename. Only used when property_filename is set. “base” selects _BASE_RECORD_NAMES; “all” selects _FULL_RECORD_NAMES. Other strings use semicolons between property names. Lists and tuples are also accepted. Duplicate names are removed while preserving their first occurrence.

  • traj_filename (str, optional) – Extended-XYZ output with one frame per independent system every record_every_steps production steps. Positions are in Angstrom, atomic velocities in Bohr per atomic time, and body-frame angular velocities in inverse atomic time. Angular output automatically includes the three corresponding principal moments of inertia in electron-mass times Bohr-squared units. A system may contain multiple physical molecules; each molecule’s six values are repeated for all its atoms.

  • traj_content (str, default: "positions") – Content to include in the trajectory file: “positions”, “velocities”, “angular_velocity_body”, or “all”. Angular output contains three angular-velocity components followed by their three principal moments of inertia. “all” includes positions, atomic velocities, and these six angular-output columns. Only used when traj_filename is set. Velocities and angular velocities are sampled before the final Langevin O half-step, at the same state as the kinetic properties. Body-frame components use instantaneous principal axes ordered by decreasing moment of inertia; their signs and degenerate directions are not tracked between frames.

  • record_every_steps (int, default: 10) – Record every this many production steps, for both files.

  • record_max_steps (int, optional) – Stop recording after this many records; None for no cap.

  • checkpoint (bool, default: False) – Whether the owning front end checkpoints this engine’s state.

  • restart (bool, default: False) – Whether initialize() restores a checkpointed state (handed in by the front end) instead of pre-equilibrating.

  • verbose (bool, default: False) – Kept for the front ends; the engine itself never prints per step.

  • num (int, keyword-only, default: 1) – Number of independent systems advanced together.

  • xp (module, keyword-only, default: numpy) – Array module exposing the NumPy API (numpy or cupy).

  • label (str, keyword-only, default: 'MDEngine') – Name used in printed messages, so each front end reports as itself.

close()[source]

Close the output files and drop the batch state (device buffers included).

close_outputs()[source]

Close the output files if any are being written.

equilibrate(duration_ps, friction_fs, temperature_K=None)[source]

Run a field-free Langevin trajectory to thermalize every system.

Each system carries its own random stream and remains uncorrelated with other systems. Nothing is recorded and the dipole baseline is untouched.

Parameters:
  • duration_ps (float) – Equilibration length in picoseconds.

  • friction_fs (float) – Langevin relaxation time in femtoseconds.

  • temperature_K (float, optional) – Bath temperature; the engine’s own temperature_K by default.

Returns:

Number of MD steps taken.

Return type:

int

initialize(dt_au, molecule_ids, restart_state=None)[source]

Allocate the batch state, then restore a checkpoint or pre-equilibrate.

Parameters:
  • dt_au (float) – The shared time step in atomic units (a.u.).

  • molecule_ids (array-like of int) – Molecule IDs assigned by the front end; must number exactly num.

  • restart_state (dict, optional) – A state produced by state_dict() (front ends read it from their checkpoint files). Only applied when the engine was built with restart=True and checkpoint=True; a restart skips the pre-NVT equilibration even when no state could be read.

Raises:

ValueError – If the number of molecule IDs does not match num, or the restart state holds a differently shaped batch.

load_state_dict(state)[source]

Restore a checkpointed state produced by state_dict().

Parameters:

state (dict) – time, x, p, F and optionally mu_initial (an old checkpoint without it keeps mu_initial unset, so the baseline is recaptured from the restored geometry).

Raises:

ValueError – If the state holds a differently shaped batch.

restore(snapshot)[source]

Restore the propagating state from a snapshot.

Parameters:

snapshot (dict) – A snapshot produced by snapshot().

set_thermostat(thermostat, temperature_K=None, friction_fs=None)[source]

Switch the production ensemble after initialize().

Parameters:
  • thermostat ({'nve', 'nvt'}) – The ensemble subsequent step() calls integrate.

  • temperature_K (float, optional) – New target temperature in Kelvin; unchanged by default.

  • friction_fs (float, optional) – New Langevin relaxation time in femtoseconds; unchanged by default.

snapshot()[source]

Return a deep-copied snapshot of the propagating state.

Returns:

The clock, positions, momenta, forces, and random-generator states.

Return type:

dict

state_dict()[source]

Return the checkpointable state as host arrays.

Returns:

time (float), x/p/F of shape (num, na, 3), mu_initial of shape (num, 3) and the molecule_ids.

Return type:

dict

step(efield_au)[source]

Advance every system by one OBABO velocity-Verlet step under the field.

Parameters:

efield_au (numpy.ndarray of float, shape (num, 3)) – Contiguous host array of effective electric field vectors in a.u.

Returns:

Columnar amplitude (dmu/dt), half-step dipole, force-time dipole, and energy for every system.

Return type:

MDStepResult

Raises:
  • RuntimeError – If called before initialize().

  • ValueError – If efield_au does not have shape (num, 3).

class maxwelllink.matter.md.md_engine.MDStepResult[source]

Bases: object

Columnar physics outputs of one engine step (contiguous host arrays).

All arrays are host (NumPy) arrays in atomic units for a batch of num systems; the field names match the aggregated hub’s BatchStepResult so the batch driver can forward them unchanged.

Variables:
  • amplitude_au (numpy.ndarray, shape (num, 3)) – Source amplitude dmu/dt consumed by the EM solver.

  • dipole_half_au (numpy.ndarray, shape (num, 3)) – Dipole half a step after the force time (relative to the baseline).

  • dipole_force_au (numpy.ndarray, shape (num, 3)) – Dipole at the force time (relative to the baseline).

  • energy_au (numpy.ndarray, shape (num,)) – Total (kinetic + potential) energy of every system.

__init__(amplitude_au, dipole_half_au, dipole_force_au, energy_au)
Parameters:
  • amplitude_au (ndarray)

  • dipole_half_au (ndarray)

  • dipole_force_au (ndarray)

  • energy_au (ndarray)

Return type:

None

amplitude_au: ndarray
dipole_force_au: ndarray
dipole_half_au: ndarray
energy_au: ndarray