Skip to content

m3flow_lammps

Provider for molecular-dynamics tasks via LAMMPS: energy minimization, NVT/NPT/NVE runs, soft push-off, and mechanical deformation — deck generation, log parsing, and validation.

m3flow_lammps.main

m3flow-lammps: MD tasks via LAMMPS (deck generation, log parsing, validation).

Implements: energy_minimize, run_nvt, run_npt, run_nve, run_soft_pushoff, run_deform (tasks/lammps/*.yaml).

Conventions
  • canonical quantities arrive as {value, unit} in canonical units (K, bar, fs); LAMMPS real units need atm for pressure (bar / 1.01325)
  • only units real and units lj systems are supported; anything else is rejected before a deck is written
  • units lj systems (CG) carry no physical calibration. Inputs use a fixed convention, not a mapping: 1 K == T = 1, 1 bar == P = 1 and 1 tau == 1000 fs (so the duration/timestep ratio, i.e. the step count, is exact). Outputs of lj runs are labeled as reduced units (*_lj thermo columns, tau time axes) and never as physical units.
  • thermo output is never normalized per atom (thermo_modify norm no) so energy columns are extensive totals in every unit style
  • sampling metadata records the actual dump/thermo stride x timestep, not the requested interval (they differ when interval/dt is not integer)
  • state chaining: every run ends with write_data (coeffs + velocities) and write_restart; the next deck re-reads them

Ctx

Source code in providers/src/m3flow_lammps/main.py
class Ctx:
    def __init__(self, req):
        self.req = req
        self.params = req["parameters"]
        self.workdir = Path(req["workdir"])
        self.warnings = []
        # actual strides chosen by the deck builders (recorded in metadata)
        self.thermo_every = None
        self.dump_every = None
        self.n_steps = None
        inputs = req["inputs"]
        sys_in, state_in = inputs.get("system"), inputs.get("state")
        if (sys_in is None) == (state_in is None):
            raise ProviderFailure(
                "input_invalid", "input_error",
                "run tasks take exactly one of the 'system' or 'state' inputs")
        self.from_state = state_in is not None
        src = state_in or sys_in
        meta = src.get("metadata") or {}
        self.units = meta.get("units", "real")
        if self.units not in SUPPORTED_UNITS:
            raise ProviderFailure(
                "input_invalid", "input_error",
                f"LAMMPS unit style '{self.units}' is not supported (supported: "
                f"{', '.join(SUPPORTED_UNITS)}); decks would mis-scale time, "
                "pressure and damping parameters")
        self.atom_style = meta.get("atom_style", "full")
        files = src.get("files") or {}
        if self.from_state:
            self.data_file = self._stage(files, "data", "state.data")
            self.init_file = self._stage(files, "init", "state.in.init", required=False)
            rst = files.get("restart")
            if rst:
                shutil.copy(rst, self.workdir / "state.restart")
        else:
            self.data_file = self._stage(files, "data", "system.data")
            self.init_file = self._stage(files, "init", "system.in.init")
            self.settings_file = self._stage(files, "settings", "system.in.settings", required=False)
            chg = files.get("charges")
            if chg:
                shutil.copy(chg, self.workdir / "system.in.charges")
        if not self.init_file:
            raise ProviderFailure("input_invalid", "input_error",
                                  "input artifact lacks an 'init' include file")

    def _stage(self, files, key, dest, required=True):
        src = files.get(key)
        if not src:
            if required:
                raise ProviderFailure("input_invalid", "input_error",
                                      f"input artifact missing file '{key}'")
            return None
        shutil.copy(src, self.workdir / dest)
        return dest

    # quantity helpers (canonical units: K, bar, fs; unit field honored)
    _TIME_TO_FS = {"fs": 1.0, "ps": 1e3, "ns": 1e6, "us": 1e9, "s": 1e15}
    _PRESS_TO_BAR = {"bar": 1.0, "atm": 1.01325, "kPa": 0.01, "MPa": 10.0,
                     "GPa": 10000.0, "Pa": 1e-5, "psi": 0.0689476}

    def _q(self, name, default=None):
        q = self.params.get(name)
        return q if isinstance(q, dict) else ({"value": q, "unit": None} if q is not None else default)

    @staticmethod
    def _factor(table, unit, name, canonical):
        unit = unit or canonical
        if unit not in table:
            raise ProviderFailure(
                "input_invalid", "input_error",
                f"parameter '{name}': unknown unit '{unit}' "
                f"(accepted: {', '.join(table)})")
        return table[unit]

    def temperature(self, name, default=None):
        q = self._q(name)
        return float(q["value"]) if q else default

    def pressure_bar(self, name="pressure", default=None):
        q = self._q(name)
        if not q:
            return default
        return float(q["value"]) * self._factor(self._PRESS_TO_BAR, q.get("unit"), name, "bar")

    def pressure_lmp(self, name="pressure", default_bar=1.0):
        """Pressure in the deck's unit style: atm (real) or reduced (lj,
        by the 1 bar == P* = 1 input convention)."""
        bar = self.pressure_bar(name, default_bar)
        return bar if self.units == "lj" else bar * ATM_PER_BAR

    def time_fs(self, name, default=None):
        q = self._q(name)
        if not q:
            return default
        return float(q["value"]) * self._factor(self._TIME_TO_FS, q.get("unit"), name, "fs")

    def time_lmp(self, fs):
        """fs -> deck time unit (fs for real, tau for lj)."""
        return fs / FS_PER_TAU if self.units == "lj" else fs

    def timestep_fs(self):
        return self.time_fs("timestep", 1.0)

    def timestep_lammps(self):
        return self.time_lmp(self.timestep_fs())

    def steps(self, duration_fs):
        return max(1, int(round(duration_fs / self.timestep_fs())))

    def stride(self, name, default_fs):
        """Integer step stride for an output interval. The actual interval
        (stride x dt) is what downstream analysis must use; a mismatch with
        the request is reported as a warning, never hidden."""
        want = self.time_fs(name, default_fs)
        dt = self.timestep_fs()
        every = max(1, int(round(want / dt)))
        actual = every * dt
        if not math.isclose(actual, want, rel_tol=1e-9, abs_tol=1e-12):
            self.warnings.append(
                f"{name}: requested {want:g} fs is not a multiple of the "
                f"{dt:g} fs timestep; using every {every} steps = {actual:g} fs")
        return every

    def seed(self):
        s = self.params.get("seed")
        return 12345 if s is None else int(s)

pressure_lmp(name='pressure', default_bar=1.0)

Pressure in the deck's unit style: atm (real) or reduced (lj, by the 1 bar == P* = 1 input convention).

Source code in providers/src/m3flow_lammps/main.py
def pressure_lmp(self, name="pressure", default_bar=1.0):
    """Pressure in the deck's unit style: atm (real) or reduced (lj,
    by the 1 bar == P* = 1 input convention)."""
    bar = self.pressure_bar(name, default_bar)
    return bar if self.units == "lj" else bar * ATM_PER_BAR

time_lmp(fs)

fs -> deck time unit (fs for real, tau for lj).

Source code in providers/src/m3flow_lammps/main.py
def time_lmp(self, fs):
    """fs -> deck time unit (fs for real, tau for lj)."""
    return fs / FS_PER_TAU if self.units == "lj" else fs

stride(name, default_fs)

Integer step stride for an output interval. The actual interval (stride x dt) is what downstream analysis must use; a mismatch with the request is reported as a warning, never hidden.

Source code in providers/src/m3flow_lammps/main.py
def stride(self, name, default_fs):
    """Integer step stride for an output interval. The actual interval
    (stride x dt) is what downstream analysis must use; a mismatch with
    the request is reported as a warning, never hidden."""
    want = self.time_fs(name, default_fs)
    dt = self.timestep_fs()
    every = max(1, int(round(want / dt)))
    actual = every * dt
    if not math.isclose(actual, want, rel_tol=1e-9, abs_tol=1e-12):
        self.warnings.append(
            f"{name}: requested {want:g} fs is not a multiple of the "
            f"{dt:g} fs timestep; using every {every} steps = {actual:g} fs")
    return every

deck_deform(ctx)

Uniaxial constant-engineering-strain-rate deformation.

Strain is measured from the box (L - L0)/L0, so it is exact whatever the unit style; atoms are remapped with the box (remap x, the default for solid deformation — remap v is for SLLOD flows and would make the thermostat fight the imposed velocity profile).

Source code in providers/src/m3flow_lammps/main.py
def deck_deform(ctx):
    """Uniaxial constant-engineering-strain-rate deformation.

    Strain is measured from the box (L - L0)/L0, so it is exact whatever the
    unit style; atoms are remapped with the box (`remap x`, the default for
    solid deformation — `remap v` is for SLLOD flows and would make the
    thermostat fight the imposed velocity profile).
    """
    p = ctx.params
    lines = _preamble(ctx)
    t = ctx.temperature("temperature")
    if t is None:
        raise ProviderFailure("input_invalid", "input_error",
                              "run_deform requires parameter 'temperature'")
    direction = p.get("direction") or "z"
    if direction not in ("x", "y", "z"):
        raise ProviderFailure("input_invalid", "input_error",
                              f"direction must be x, y or z (got {direction!r})")
    erate = float(p["strain_rate"]) if p.get("strain_rate") is not None else 1e-7  # 1/fs
    max_strain = float(p["max_strain"]) if p.get("max_strain") is not None else 0.5
    if erate <= 0 or max_strain <= 0:
        raise ProviderFailure("input_invalid", "input_error",
                              "strain_rate and max_strain must be positive")
    dt = ctx.timestep_fs()
    steps = max(1, int(round(max_strain / (erate * dt))))
    ctx.n_steps = steps
    tdamp = ctx.time_lmp(ctx.time_fs("tdamp", 100.0))
    erate_lmp = erate * FS_PER_TAU if ctx.units == "lj" else erate  # 1/time unit

    lines += _velocity_if_needed(ctx, t)
    every = ctx.stride("sampling_interval", 500.0)
    ctx.dump_every = every
    lines += [
        f"variable m3tmp equal l{direction}",
        "variable m3L0 equal ${m3tmp}",
        f"fix m3def all deform 1 {direction} erate {erate_lmp} remap x units box",
        f"fix m3 all nvt temp {t} {t} {tdamp}",
        f"variable m3strain equal (l{direction}-v_m3L0)/v_m3L0",
        f"variable m3stress equal -p{direction}{direction}",
        f"fix m3out all print {every} \"${{m3strain}} ${{m3stress}}\" "
        f"file stress_strain.csv screen no",
        f"timestep {ctx.timestep_lammps()}",
        f"run {steps}",
        "unfix m3out",
        "unfix m3",
        "unfix m3def",
    ]
    lines += _finalize(ctx)
    return lines, False