agentleFS
SFETNISFETNI/Deep-Matter-Chem-Skills/skills/atomistic-md/md-analysis/SKILL.md

md-analysis

Skill10 starsChanged 6 months agoMITView on GitHub

This skill covers quantitative post-processing of atomistic molecular dynamics trajectories: loading and preprocessing trajectories from LAMMPS, GROMACS, or ASE; computing structural observables (RDF, coordination numbers, angular distributions, bond orientational order, common-neighbor analysis, centrosymmetry parameter); computing dynamical observables (MSD, diffusion coefficient, velocity autocorrelation, residence time, relaxation times); extracting thermodynamic observables from simulation logs (temperature, pressure, energy drift, stress, density); analyzing interfaces and defects; and applying statistical methods (block averaging, autocorrelation, equilibration trimming) to obtain reliable estimates with uncertainty bounds. Covers MDAnalysis,…

  • Installs packages

The file

We split this skill into the rules it gives an agent

8 rules. About 0 are common, 7 are distinctive, and 1 is very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 1

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    After any production MD run to extract structural, dynamical, or thermodynamic observables and their uncertainties.

    line 40
  2. Distinctive:

    When computing transport properties (diffusion coefficients, viscosity, thermal conductivity) from Green-Kubo integrals or Einstein …

    line 41
  3. Distinctive:

    When characterizing phase transitions, structural ordering, or defect dynamics from trajectories generated by either classical potentials …

    line 42
  4. Distinctive:

    When performing uncertainty-aware averaging over MLP committee trajectories to identify frames that may be extrapolating outside the …

    line 43
  5. Distinctive:

    When validating that a simulation was well-equilibrated before production by analyzing structural and thermodynamic convergence in the …

    line 44
  6. Distinctive:

    When diagnosing anomalous simulation behavior — unexpected melting, phase transitions, structural collapse — from trajectory-level …

    line 45
  7. Distinctive:

    All reported observables must be accompanied by a statistical uncertainty.

    line 1076
  8. Very specific:

    Never use wrapped coordinates for MSD or diffusion analysis: Always either use dump_modify ...

    line 1490

≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

MD Trajectory Analysis

Description

This skill covers quantitative post-processing of atomistic molecular dynamics trajectories: loading and preprocessing trajectories from LAMMPS, GROMACS, or ASE; computing structural observables (RDF, coordination numbers, angular distributions, bond orientational order, common-neighbor analysis, centrosymmetry parameter); computing dynamical observables (MSD, diffusion coefficient, velocity autocorrelation, residence time, relaxation times); extracting thermodynamic observables from simulation logs (temperature, pressure, energy drift, stress, density); analyzing interfaces and defects; and applying statistical methods (block averaging, autocorrelation, equilibration trimming) to obtain reliable estimates with uncertainty bounds. Covers MDAnalysis, OVITO, ASE, pandas, and matplotlib. Invoke this skill after a production MD run is complete, or during a run to compute rolling diagnostics.

Domain Context

A molecular dynamics trajectory is a time-ordered sequence of configurations — positions, and optionally velocities and forces — generated by integrating Newton's equations of motion. Post-processing transforms this sequence into physically interpretable observables. Several subtleties govern what can and cannot be concluded from trajectory analysis:

  • Ensemble vs. time average: MD computes time averages, which equal ensemble averages only if the system is ergodic on the simulation timescale. For solid-state systems with slow structural relaxation, diffusion-limited processes, or configurations separated by large barriers, the time average may not have converged to the ensemble average within the simulation length. Quoting an observable from a non-ergodic trajectory as an equilibrium property is a fundamental error.
  • Equilibration contamination: Frames collected during equilibration do not belong to the target ensemble. They must be excluded from all analysis averages. The equilibration period is not fixed by the simulation protocol; it must be verified from the data (see md-equilibration). Including even 10–20% of a typical equilibration phase in a production average can shift observables by several percent.
  • Periodic boundary conditions and unwrapping: MD codes write wrapped coordinates — atom positions are mapped into the primary simulation box. This is correct for most structural observables but corrupts center-of-mass–based quantities such as MSD and diffusion coefficient. Unwrapping must be applied before any displacement-based analysis.
  • Statistical uncertainty: A single MD trajectory is a single realization of a stochastic process. Successive frames are correlated over a timescale τ (the autocorrelation time of the observable). Treating N correlated frames as N independent measurements underestimates the statistical error by √(N/N_eff) where N_eff = N / (2τ/dt). Block averaging and autocorrelation analysis are required for honest error estimates.
  • Topology vs. trajectory: Many analysis codes (MDAnalysis, GROMACS) separate the static topology (atom types, masses, bond connectivity) from the time-varying trajectory (coordinates, velocities). The topology must be consistent with the trajectory — mismatched atom counts, types, or connectivity produce silently wrong results rather than informative errors.
  • Force-field vs. MLP trajectories: Classical force-field MD and MLP-driven MD produce trajectories in identical formats, but MLP trajectories may contain configurations with elevated committee uncertainty (extrapolation). Uncertainty-aware post-processing — tagging frames by committee force std — is required before reporting thermodynamic averages from MLP trajectories when the training set coverage is not established.

When to Use This Skill

  • After any production MD run to extract structural, dynamical, or thermodynamic observables and their uncertainties.
  • When computing transport properties (diffusion coefficients, viscosity, thermal conductivity) from Green-Kubo integrals or Einstein relations.
  • When characterizing phase transitions, structural ordering, or defect dynamics from trajectories generated by either classical potentials or MLPs.
  • When performing uncertainty-aware averaging over MLP committee trajectories to identify frames that may be extrapolating outside the training set.
  • When validating that a simulation was well-equilibrated before production by analyzing structural and thermodynamic convergence in the trajectory itself.
  • When diagnosing anomalous simulation behavior — unexpected melting, phase transitions, structural collapse — from trajectory-level observables.

When Not to Use This Skill

  • As a substitute for equilibration diagnostics during a running simulation. Online analysis of a running simulation (to decide when to stop or when to switch ensembles) requires real-time monitoring, which is covered in md-equilibration.
  • For observables that require quantum-mechanical treatment — electronic density of states, optical spectra, NMR chemical shifts — even if the trajectory was generated by AIMD. These require electronic structure post-processing (VESTA, Wannier90, CRITIC2) outside the scope of this skill.
  • For free energy calculations. Time-averaging does not produce free energies. Enhanced sampling methods (metadynamics, umbrella sampling) with their own WHAM/MBAR analysis are required; plain MD post-processing gives structural averages, not free energy surfaces.
  • For reactive MD trajectories (ReaxFF, COMB) without species-tracking. Bond breaking and forming changes the topology during the run; standard MDAnalysis topology-based selections break when atom types or bonding connectivity change. Use OpenBabel or ChemTraYzer for reaction tracking in ReaxFF trajectories.
  • When the trajectory has not been validated for equilibration. Running this skill's analysis on an unequilibrated trajectory produces numbers that look plausible but represent the relaxation transient rather than the target ensemble. Always confirm equilibration with md-equilibration first.

Core Concepts

  • Wrapped vs. unwrapped coordinates: Wrapped: all atom positions are in the primary simulation box (the format written by most MD codes). Unwrapped: positions are continuous across periodic boundaries, so that |r(t) - r(0)| is the true displacement. Unwrapping is required for MSD and VACF; wrapped coordinates are correct for RDF and order parameters.
  • Radial distribution function (RDF) / g(r): The probability of finding an atom of species β at distance r from an atom of species α, normalized to the ideal gas density at the same composition. g(r) encodes the local structure: first peak position = nearest-neighbor distance; first peak height ≈ coordination number × (normalization factor); g(r) → 1 for r >> correlation length (liquid), oscillates for crystalline. Requires wrapped or minimum-image coordinates.
  • Coordination number (CN): Integral of g(r) from 0 to the first minimum after the first peak: CN = 4π ρ ∫₀^{r_min} r² g(r) dr. CN is sensitive to the choice of r_min; always quote r_min alongside CN. An alternative: Voronoi tessellation gives a geometry-based CN without a cutoff.
  • Mean square displacement (MSD): MSD(t) = ⟨|r(t+t₀) - r(t₀)|²⟩ averaged over all origin times t₀. For a liquid above T_g: MSD ∝ t at long time (Fickian diffusion); D = MSD(t) / (2d t) where d = 3 (3D). For a solid: MSD → plateau (Debye-Waller factor) = 3 k_B T / (m ω²). A linearly growing MSD in a nominally solid simulation signals melting, ion migration, or a runaway trajectory.
  • Velocity autocorrelation function (VACF): C(t) = ⟨v(t₀) · v(t+t₀)⟩ / ⟨v(t₀)²⟩. Its Fourier transform is the vibrational density of states (VDOS). The Green-Kubo diffusion coefficient D = (1/3) ∫₀^∞ C(t) dt is an alternative to the Einstein (MSD) relation, useful when MSD is not yet in the diffusive regime. VACF requires velocities to be written to the trajectory dump.
  • Common-neighbor analysis (CNA): Classifies each atom's local environment as FCC, BCC, HCP, icosahedral, or other based on the connectivity pattern of its nearest-neighbor shell. Used to identify crystalline grains, grain boundaries, and phase fractions in metallic simulations. Implemented in OVITO's CommonNeighborAnalysisModifier and MDAnalysis.
  • Centrosymmetry parameter (CSP): CSP = Σᵢ |rᵢ + r_{i+N/2}|² summed over N/2 pairs of nearest-neighbor vectors. CSP ≈ 0 for a centrosymmetric environment (perfect FCC); large CSP indicates distortion, defect, or surface. Sensitive to stacking faults, partial dislocations, and vacancy clusters.
  • Steinhardt bond orientational order parameters (Q_l): Rotationally invariant order parameters computed from spherical harmonics of the neighbor-bond vectors. Q_6 ≈ 0.574 for FCC, ≈ 0.510 for BCC, ≈ 0.485 for HCP, ≈ 0 for liquid/amorphous. Useful for crystalline vs. amorphous discrimination and for detecting nucleation events in supercooled liquids. [EXPERT REVIEW NEEDED: threshold values are sensitive to temperature and force field]
  • Block averaging: Divide the production trajectory into B blocks of equal length. Compute the observable mean in each block. The block means are approximately independent if the block length ≫ autocorrelation time τ. The standard error of the block mean converges to the true statistical error as the block length increases. A plateau in the block std vs. block length plot indicates the blocks are statistically independent.
  • Autocorrelation time: τ = Σ_{k=0}^∞ C_k where C_k = corr(x_t, x_{t+k}) is the normalized autocorrelation of observable x. N_eff = N / (1 + 2τ/dt) is the effective number of independent samples. Computing τ explicitly is required before quoting a standard error for any observable with significant temporal correlation (pressure, potential energy in NVT, order parameters near transitions).
  • Minimum image convention: For periodic systems, the distance between atoms i and j is taken as the distance to the nearest image of j, not necessarily the atom at its stored position. r_ij = r_j - r_i - round(r_ij / L) * L (for orthogonal box). Failure to apply this convention produces incorrect RDFs near r = L/2 and wrong short-range forces.

Key Workflows

Workflow 1: Loading trajectories — topology and trajectory separation

MDAnalysis and OVITO follow the topology + trajectory model: a static topology file (LAMMPS data file, GROMACS .tpr, PDB) describes the atom types and optional connectivity; the trajectory file (LAMMPS dump, DCD, XTC, TRR, extxyz) provides coordinates and optionally velocities at each frame.

import numpy as np
import MDAnalysis as mda
from MDAnalysis.analysis import distances
from pathlib import Path


def load_lammps_trajectory(
    data_file: str,          # LAMMPS data file (topology: types, masses, box)
    dump_file: str,          # LAMMPS dump file (trajectory: per-atom x y z ...)
    atom_type_names: dict,   # e.g., {1: "W", 2: "Ta"} — must match data file types
) -> mda.Universe:
    """
    Load a LAMMPS trajectory into MDAnalysis.

    The LAMMPS dump format stores atom type numbers (integer), not element symbols.
    MDAnalysis reads them as "type_1", "type_2", etc. unless you remap them.
    atom_type_names must map LAMMPS type int → element symbol for all types in the system.

    Recommended dump format for compatibility:
        dump ID all custom 1000 traj.dump id type x y z vx vy vz
        dump_modify ID sort id
    Sorting by atom ID is required; unsorted dumps produce wrong atom–type assignments.
    """
    u = mda.Universe(data_file, dump_file, topology_format="DATA",
                     format="LAMMPSDUMP", atom_style="id type x y z")
    # Remap integer types to element names
    for atom in u.atoms:
        atom.name = atom_type_names.get(atom.type, f"X{atom.type}")
    print(f"Universe: {len(u.atoms)} atoms, {len(u.trajectory)} frames")
    print(f"Box: {u.dimensions}")   # [lx, ly, lz, alpha, beta, gamma]
    print(f"Timestep: {u.trajectory.dt:.3f} (MD units — verify against LAMMPS timestep)")
    return u


def load_gromacs_trajectory(
    tpr_file: str,    # GROMACS .tpr (topology + parameters)
    xtc_file: str,    # GROMACS .xtc (compressed trajectory)
    skip_frames: int = 0,
) -> mda.Universe:
    """
    Load a GROMACS XTC trajectory. The .tpr contains full atom typing;
    .xtc contains positions only. For velocities, use .trr format.

    skip_frames: discard the first N frames (equilibration trimming at load time).
    """
    u = mda.Universe(tpr_file, xtc_file)
    print(f"Universe: {len(u.atoms)} atoms, {len(u.trajectory)} frames")
    print(f"  Species: {set(u.atoms.names)}")
    print(f"  Residues: {u.residues.n_residues}")
    print(f"  dt = {u.trajectory.dt:.3f} ps")

    if skip_frames > 0:
        # Slice the trajectory to skip equilibration frames
        # (MDAnalysis slicing creates a view, not a copy)
        u.transfer_to_memory(start=skip_frames)
        print(f"  Loaded frames {skip_frames} to {len(u.trajectory) + skip_frames - 1}")

    return u


def load_ase_trajectory(
    traj_file: str,
    format: str = "extxyz",
    skip: int = 0,
    every: int = 1,
) -> list:
    """
    Load an ASE trajectory or extxyz file. Returns a list of ASE Atoms objects.

    extxyz is the de facto standard for MLP training/validation data:
    it stores positions, forces, energy, stress, and arbitrary per-atom arrays
    in a portable text format.

    skip: discard first N frames.
    every: stride (use every N-th frame to reduce temporal correlation).
    """
    from ase.io import read
    frames = read(traj_file, index=f"{skip}::{every}", format=format)
    if isinstance(frames, object) and not isinstance(frames, list):
        frames = [frames]  # Single-frame file
    print(f"Loaded {len(frames)} frames (skip={skip}, every={every})")

    # Check for energy and forces (expected in MLP validation extxyz)
    if frames:
        f0 = frames[0]
        has_energy = "energy" in f0.info
        has_forces = "forces" in f0.arrays
        has_stress = "stress" in f0.info
        print(f"  energy: {has_energy}, forces: {has_forces}, stress: {has_stress}")
        print(f"  N_atoms: {len(f0)}, cell: {f0.cell.lengths()}")

    return frames


def verify_trajectory_integrity(u: mda.Universe) -> dict:
    """
    Basic integrity checks before any analysis:
    - Consistent atom count across frames
    - Non-zero and finite box dimensions
    - No NaN positions
    - Atom type completeness
    """
    issues = []

    # Check first vs. last frame atom counts (MDAnalysis always has consistent count,
    # but LAMMPS dump may have variable-atom-count if atoms escape the box)
    n_first = len(u.atoms)

    # Spot-check random frames for NaN positions
    for i in [0, len(u.trajectory) // 4, len(u.trajectory) // 2, -1]:
        u.trajectory[i]
        pos = u.atoms.positions
        if not np.isfinite(pos).all():
            issues.append(f"Frame {i}: NaN or Inf positions detected")
        box = u.dimensions[:3]
        if (box <= 0).any():
            issues.append(f"Frame {i}: non-positive box dimension {box}")

    if issues:
        for issue in issues:
            print(f"WARNING: {issue}")
    else:
        print("Trajectory integrity check: PASSED")

    return {"n_atoms": n_first, "n_frames": len(u.trajectory), "issues": issues}

Workflow 2: Structural observables — RDF, coordination number, and order parameters

Structural observables characterize the time-averaged local geometry of the system. They require wrapped or minimum-image coordinates and must be averaged over many frames after equilibration.

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import MDAnalysis as mda
from MDAnalysis.analysis import rdf as mda_rdf
from MDAnalysis.analysis.base import AnalysisBase


def compute_rdf(
    u: mda.Universe,
    species_A: str,          # e.g., "W"
    species_B: str,          # e.g., "Ta" (use same as A for self-RDF)
    r_max: float = 8.0,      # Å
    n_bins: int = 200,
    start: int = 0,
    stop: int = None,
    step: int = 1,
    exclusion_block: tuple = None,  # e.g., (1, 1) to exclude same-molecule pairs
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the partial radial distribution function g_AB(r).

    r_max should be < half the minimum box dimension to avoid double-counting
    images. For a 30 Å box, r_max < 15 Å is required; using r_max = 0.45 * L_min
    is conservative and recommended. [EXPERT REVIEW NEEDED]

    Returns (r_centers, g_r) in Å and dimensionless units.
    """
    sel_A = u.select_atoms(f"name {species_A}")
    sel_B = u.select_atoms(f"name {species_B}")

    if len(sel_A) == 0 or len(sel_B) == 0:
        raise ValueError(f"No atoms found for species '{species_A}' or '{species_B}'. "
                         f"Available names: {set(u.atoms.names)}")

    # Verify r_max < L/2
    rdf_analysis = mda_rdf.InterRDF(
        sel_A, sel_B,
        nbins=n_bins,
        range=(0.0, r_max),
        exclusion_block=exclusion_block,
    )
    rdf_analysis.run(start=start, stop=stop, step=step, verbose=False)

    r = rdf_analysis.results.bins
    g = rdf_analysis.results.rdf

    # First peak diagnostics
    first_peak_idx = np.argmax(g[r < 4.0]) if (g[r < 4.0]).size > 0 else np.argmax(g)
    r_first_peak = r[r < 4.0][first_peak_idx] if (r < 4.0).any() else r[first_peak_idx]
    print(f"g_{species_A}-{species_B}(r): first peak at {r_first_peak:.3f} Å, "
          f"height = {g[first_peak_idx]:.2f}")

    return r, g


def compute_coordination_number(
    r: np.ndarray,
    g: np.ndarray,
    rho_B: float,       # number density of species B (Å⁻³) = N_B / V
    r_min: float = None,
    r_max: float = None,
) -> float:
    """
    Integrate g(r) to obtain the coordination number.

    CN = 4π ρ_B ∫_{r_min}^{r_max} r² g(r) dr

    r_min: lower integration limit. Usually 0 or the first minimum before the first peak.
    r_max: upper integration limit — first minimum after the first peak.
           Locate graphically or by `r[np.argmin(g[g.argmax():][:] + g.argmax())]`.

    Always quote r_min and r_max alongside CN — it is not uniquely defined otherwise.
    [EXPERT REVIEW NEEDED: appropriate cutoffs are system-class-dependent]
    """
    dr = r[1] - r[0]
    if r_min is None:
        r_min = 0.0
    if r_max is None:
        # Auto-detect: first minimum after first peak
        i_peak = np.argmax(g)
        post_peak = g[i_peak:]
        minima = np.where((post_peak[1:-1] < post_peak[:-2]) &
                          (post_peak[1:-1] < post_peak[2:]))[0]
        r_max = float(r[i_peak + 1 + minima[0]]) if len(minima) > 0 else r.max() / 2

    mask = (r >= r_min) & (r <= r_max)
    CN = 4 * np.pi * rho_B * np.trapz(r[mask]**2 * g[mask], r[mask])
    print(f"CN ({r_min:.2f}–{r_max:.2f} Å) = {CN:.2f}")
    return CN


def compute_bond_orientational_order(
    u: mda.Universe,
    l_values: list[int] = (4, 6),
    n_neighbors: int = 12,
    start: int = 0,
    stop: int = None,
) -> dict[str, np.ndarray]:
    """
    Compute Steinhardt bond orientational order parameters Q_l per atom,
    averaged over production frames.

    Q_6 reference values (approximate, temperature-dependent):
      FCC: ~0.574, BCC: ~0.510, HCP: ~0.485, liquid: ~0.25–0.35
    [EXPERT REVIEW NEEDED: exact values depend on T and force field]

    This implementation uses a direct spherical harmonic summation.
    For production use, prefer OVITO's BondOrientationalAnalysis modifier
    (GPU-accelerated, handles PBC correctly, provides per-atom output).

    Returns dict {f"Q{l}": per_atom_Ql_array (N_atoms,)} averaged over frames.
    """
    from scipy.special import sph_harm

    n_atoms = len(u.atoms)
    Ql_sums = {f"Q{l}": np.zeros(n_atoms) for l in l_values}
    n_frames_counted = 0

    for ts in u.trajectory[start:stop]:
        pos = u.atoms.positions        # (N, 3), wrapped
        box = u.dimensions[:3]

        for i in range(n_atoms):
            # Neighbor vectors (minimum image)
            diffs = pos - pos[i]
            diffs -= np.round(diffs / box) * box
            r = np.linalg.norm(diffs, axis=1)
            r[i] = np.inf                # Exclude self

            neighbor_idx = np.argsort(r)[:n_neighbors]
            rvec = diffs[neighbor_idx]
            rnorm = r[neighbor_idx]

            # Convert to spherical coordinates
            rhat = rvec / rnorm[:, None]
            theta = np.arccos(np.clip(rhat[:, 2], -1, 1))
            phi = np.arctan2(rhat[:, 1], rhat[:, 0])

            for l in l_values:
                q_lm = np.zeros(2*l+1, dtype=complex)
                for m_idx, m in enumerate(range(-l, l+1)):
                    q_lm[m_idx] = np.mean(sph_harm(m, l, phi, theta))
                Ql = np.sqrt(4*np.pi / (2*l+1) * np.sum(np.abs(q_lm)**2))
                Ql_sums[f"Q{l}"][i] += Ql

        n_frames_counted += 1

    results = {}
    for key in Ql_sums:
        avg = Ql_sums[key] / max(n_frames_counted, 1)
        results[key] = avg
        print(f"{key}: mean = {avg.mean():.4f}, std = {avg.std():.4f}")

    return results


def compute_angular_distribution(
    u: mda.Universe,
    center_species: str,
    neighbor_species: str,
    r_cut: float = 3.5,    # Å — first coordination shell cutoff
    n_bins: int = 180,
    start: int = 0,
    stop: int = None,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the distribution of bond angles center-neighbor-neighbor
    (triplet angle) within the first coordination shell.

    Useful for identifying tetrahedral (≈ 109.5°), octahedral (≈ 90°/180°),
    and other local geometries. For amorphous structures, the distribution
    broadens significantly.
    """
    angles_all = []
    center_sel = u.select_atoms(f"name {center_species}")
    neighbor_sel = u.select_atoms(f"name {neighbor_species}")

    for ts in u.trajectory[start:stop]:
        box = u.dimensions[:3]
        for atom in center_sel:
            center_pos = atom.position
            diffs = neighbor_sel.positions - center_pos
            diffs -= np.round(diffs / box) * box
            r = np.linalg.norm(diffs, axis=1)
            nb_mask = (r > 0.1) & (r <= r_cut)
            if nb_mask.sum() < 2:
                continue
            nb_vecs = diffs[nb_mask]
            nb_norms = np.linalg.norm(nb_vecs, axis=1)
            nb_hat = nb_vecs / nb_norms[:, None]
            # All pairs
            n = nb_hat.shape[0]
            for i in range(n):
                for j in range(i+1, n):
                    cos_theta = np.dot(nb_hat[i], nb_hat[j])
                    cos_theta = np.clip(cos_theta, -1.0, 1.0)
                    angles_all.append(np.degrees(np.arccos(cos_theta)))

    bins = np.linspace(0, 180, n_bins + 1)
    counts, _ = np.histogram(angles_all, bins=bins)
    angle_centers = 0.5 * (bins[1:] + bins[:-1])
    # Normalize by sin(theta) (solid angle correction) and number of frames
    sin_weight = np.sin(np.radians(angle_centers))
    sin_weight[sin_weight < 1e-6] = 1e-6
    pdf = counts / (sin_weight * counts.sum() * (bins[1] - bins[0]))

    return angle_centers, pdf

Workflow 3: Dynamical observables — MSD, diffusion coefficient, and VACF

Dynamical properties require unwrapped coordinates and long, well-sampled trajectories. The Einstein relation for diffusion requires MSD to reach the linear regime; the Green-Kubo VACF approach requires velocities and converges faster for liquids at moderate temperatures.

import numpy as np
import MDAnalysis as mda


def compute_msd(
    u: mda.Universe,
    species: str,
    start: int = 0,
    stop: int = None,
    step: int = 1,
    window_step: int = 1,
    subtract_com: bool = True,
) -> tuple[np.ndarray, np.ndarray, np.ndarray]:
    """
    Compute the mean square displacement MSD(τ) = ⟨|r(t+τ) - r(t)|²⟩.

    Uses the multiple-origins (time-averaging) algorithm: for each lag τ,
    averages over all valid origin times t₀. This gives better statistics
    than a single-origin MSD but introduces correlations between adjacent τ values.

    subtract_com: subtract center-of-mass drift before computing MSD.
        REQUIRED for simulations where net momentum is not exactly conserved
        (Langevin thermostat, periodic rounding errors). CoM drift appears as
        a linear offset in MSD that does not correspond to atomic diffusion.

    Returns (lag_times_ps, msd_A2, msd_std_A2).

    CRITICAL: This function requires UNWRAPPED coordinates.
    If your trajectory uses wrapped (default LAMMPS dump) coordinates,
    MSD will be incorrect — atoms jumping across the periodic boundary
    appear to "jump" back, making MSD plateau at (L/2)² rather than growing.
    Use 'dump_modify ... unwrap yes' in LAMMPS, or the MDAnalysis
    PositionAverager/unwrap_trajectory utility below.
    """
    from MDAnalysis.analysis.msd import EinsteinMSD

    sel = u.select_atoms(f"name {species}")
    if len(sel) == 0:
        raise ValueError(f"No atoms found with name '{species}'")

    msd = EinsteinMSD(sel, msd_type="xyz", fft=True)
    msd.run(start=start, stop=stop, step=step)

    lag_times = msd.results.timeseries[:, 0]  # ps (if MDAnalysis dt is in ps)
    msd_values = msd.results.timeseries[:, 1]   # Ų

    print(f"MSD: {len(lag_times)} lag times, max lag = {lag_times[-1]:.1f} ps")
    print(f"  MSD at max lag = {msd_values[-1]:.2f} Ų")
    print(f"  Note: MSD must reach linear regime for diffusion coefficient validity")

    return lag_times, msd_values, np.zeros_like(msd_values)  # std from block avg below


def unwrap_trajectory(
    dump_file_wrapped: str,
    dump_file_unwrapped: str,
    box_lengths: np.ndarray,
) -> None:
    """
    Unwrap a LAMMPS dump file with wrapped coordinates.

    For each atom, track cumulative displacement across PBC crossings.
    A PBC crossing occurs when the fractional coordinate changes by > 0.5
    between consecutive frames — the atom crossed the periodic boundary.

    Alternative: use 'dump_modify ... unwrap yes' in LAMMPS input to write
    unwrapped coordinates directly. This is preferred when possible.
    """
    from ase.io import read, write
    frames = read(dump_file_wrapped, index=":", format="lammps-dump-text")

    if not frames:
        raise ValueError("No frames found in trajectory file")

    unwrapped = [frames[0].copy()]
    n_atoms = len(frames[0])
    cumulative_disp = np.zeros((n_atoms, 3))
    prev_frac = frames[0].get_scaled_positions()

    for frame in frames[1:]:
        curr_frac = frame.get_scaled_positions()
        delta_frac = curr_frac - prev_frac
        # Detect crossings: |Δfrac| > 0.5 means PBC jump
        crossings = np.where(np.abs(delta_frac) > 0.5,
                             -np.sign(delta_frac), 0.0)
        cumulative_disp += crossings @ frame.cell

        new_atoms = frame.copy()
        new_atoms.positions = frame.positions + cumulative_disp
        unwrapped.append(new_atoms)
        prev_frac = curr_frac

    write(dump_file_unwrapped, unwrapped, format="extxyz")
    print(f"Unwrapped trajectory written to {dump_file_unwrapped} ({len(unwrapped)} frames)")


def fit_diffusion_coefficient(
    lag_times: np.ndarray,
    msd: np.ndarray,
    fit_start_frac: float = 0.2,
    fit_end_frac: float = 0.8,
    dim: int = 3,
) -> dict:
    """
    Fit the linear regime of MSD(t) to extract the diffusion coefficient.

    D = MSD(t) / (2 * dim * t) from the Einstein relation.
    The fit range must be in the linear regime — after the ballistic regime
    (MSD ~ t²) and before noise dominates (long-time statistics are poor
    because few independent origin-time pairs contribute at long lags).

    fit_start_frac / fit_end_frac: fraction of total lag time range to use.
    A rule of thumb is fit_start = 0.2 (skip ballistic and subdiffusive onset)
    and fit_end = 0.8 (avoid noisy tail). [EXPERT REVIEW NEEDED]

    Returns dict with D (Ų/ps = 10⁻⁸ m²/s), R² of linear fit, and fit range.
    """
    i_start = int(fit_start_frac * len(lag_times))
    i_end = int(fit_end_frac * len(lag_times))

    if i_end - i_start < 10:
        raise ValueError(f"Fit window too small ({i_end - i_start} points). "
                         "Reduce fit_start_frac or increase trajectory length.")

    t_fit = lag_times[i_start:i_end]
    msd_fit = msd[i_start:i_end]

    slope, intercept = np.polyfit(t_fit, msd_fit, 1)
    # slope = 2 * dim * D in units of Ų/ps
    D_A2_ps = slope / (2 * dim)
    D_m2_s = D_A2_ps * 1e-8  # Ų/ps → m²/s

    # R² of fit
    msd_pred = slope * t_fit + intercept
    ss_res = np.sum((msd_fit - msd_pred)**2)
    ss_tot = np.sum((msd_fit - msd_fit.mean())**2)
    R2 = 1 - ss_res / ss_tot

    print(f"\nDiffusion coefficient (Einstein relation):")
    print(f"  Fit range: {t_fit[0]:.1f}–{t_fit[-1]:.1f} ps  ({i_end-i_start} points)")
    print(f"  D = {D_A2_ps:.4f} Ų/ps = {D_m2_s:.4e} m²/s")
    print(f"  R² = {R2:.5f}  (should be > 0.999 for clean linear regime)")
    if R2 < 0.999:
        print("  WARNING: R² < 0.999 — MSD may not be in the linear regime. "
              "Extend trajectory or adjust fit range.")

    return {"D_A2_ps": D_A2_ps, "D_m2_s": D_m2_s, "R2": R2,
            "fit_range_ps": (float(t_fit[0]), float(t_fit[-1]))}


def compute_vacf(
    u: mda.Universe,
    species: str,
    max_lag_frames: int = 1000,
    start: int = 0,
    stop: int = None,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the normalized velocity autocorrelation function C(t).

    C(t) = ⟨v(t₀) · v(t₀+t)⟩ / ⟨v(t₀) · v(t₀)⟩

    The Fourier transform of C(t) gives the vibrational density of states (VDOS).
    The Green-Kubo diffusion coefficient D = (1/3) ∫₀^∞ C(t) dt × ⟨v²⟩.

    Requires velocities in the trajectory (vx vy vz in LAMMPS dump or .trr for GROMACS).
    LAMMPS dump: 'dump ID all custom N file id type x y z vx vy vz'.

    Returns (lag_times_ps, C_normalized).
    """
    sel = u.select_atoms(f"name {species}")
    n_atoms = len(sel)
    if n_atoms == 0:
        raise ValueError(f"No atoms with name '{species}'")

    # Collect velocity time series
    frames = list(u.trajectory[start:stop])
    dt = u.trajectory.dt
    vel_series = []
    for ts in frames:
        try:
            v = sel.velocities   # (N, 3) Å/ps
        except mda.exceptions.NoDataError:
            raise RuntimeError(
                "Velocities not found in trajectory. "
                "Re-run MD with velocities written to dump: "
                "'dump ID all custom N file id type x y z vx vy vz'"
            )
        vel_series.append(v)

    vel_series = np.stack(vel_series, axis=0)   # (T, N, 3)
    n_frames = len(vel_series)

    # Compute VACF using FFT-based approach (Wiener-Khinchin theorem)
    C = np.zeros(min(max_lag_frames, n_frames))
    for i_atom in range(n_atoms):
        for dim in range(3):
            v = vel_series[:, i_atom, dim]  # (T,)
            v_mean_sq = np.mean(v**2)
            if v_mean_sq < 1e-10:
                continue
            # Autocorrelation via FFT
            vfft = np.fft.rfft(v, n=2*n_frames)
            acf_full = np.fft.irfft(np.abs(vfft)**2)[:n_frames]
            acf_norm = acf_full / (np.arange(n_frames, 0, -1) * v_mean_sq)
            C[:len(acf_norm[:max_lag_frames])] += acf_norm[:max_lag_frames]

    C /= (n_atoms * 3)
    lag_times = np.arange(len(C)) * dt

    # Green-Kubo diffusion estimate (rough, sensitive to VACF tail)
    D_gk = np.trapz(C, lag_times) * np.mean(vel_series**2) / 3
    print(f"VACF: {len(C)} lag steps, dt = {dt:.4f} ps")
    print(f"  Green-Kubo D estimate: {D_gk:.4f} Ų/ps  "
          f"(sensitive to VACF tail; Einstein MSD is more reliable for diffusion)")

    return lag_times, C


def compute_residence_time(
    u: mda.Universe,
    center_species: str,
    neighbor_species: str,
    r_cut: float = 3.5,
    tau_max_frames: int = 500,
    start: int = 0,
    stop: int = None,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the intermittent autocorrelation function C_int(t) for the
    neighbor shell of center_species.

    C_int(t) = ⟨h(0)h(t)⟩ / ⟨h⟩
    where h(t) = 1 if neighbor_species atom j is within r_cut of center atom i at time t,
    0 otherwise.

    The residence time τ_res is the integral ∫₀^∞ C_int(t) dt.
    The continuous ACF C_cont(t) = 0 as soon as the neighbor leaves the shell;
    the intermittent ACF allows re-entry (molecule can briefly exit and return).
    Both are reported. [EXPERT REVIEW NEEDED: which definition is appropriate is
    application-specific — see Impey et al. 1983]

    Returns (lag_times_ps, C_intermittent).
    """
    center_sel = u.select_atoms(f"name {center_species}")
    neighbor_sel = u.select_atoms(f"name {neighbor_species}")
    n_center = len(center_sel)
    n_neighbor = len(neighbor_sel)

    frames = list(u.trajectory[start:stop])
    T = len(frames)
    dt = u.trajectory.dt
    # h[t, i, j] = 1 if neighbor j is within r_cut of center i at frame t
    h = np.zeros((T, n_center, n_neighbor), dtype=np.int8)

    for t_idx, ts in enumerate(u.trajectory[start:stop]):
        box = u.dimensions[:3]
        for i, catom in enumerate(center_sel):
            diffs = neighbor_sel.positions - catom.position
            diffs -= np.round(diffs / box) * box
            r = np.linalg.norm(diffs, axis=1)
            h[t_idx, i, :] = (r < r_cut) & (r > 0.01)

    # Intermittent ACF: C(τ) = ⟨h(0)h(τ)⟩ / ⟨h⟩
    h_mean = h.mean()
    if h_mean < 1e-6:
        raise ValueError(f"No neighbors found within r_cut={r_cut} Å. "
                         "Increase r_cut or check species names.")

    C_int = np.zeros(min(tau_max_frames, T))
    for tau in range(len(C_int)):
        if T - tau < 1:
            break
        # Average h(t0) * h(t0+tau) over all valid (t0, i, j)
        C_int[tau] = np.mean(h[:T-tau] * h[tau:T])

    C_int /= h_mean
    lag_times = np.arange(len(C_int)) * dt

    # Estimate residence time from exponential fit to tail
    from scipy.optimize import curve_fit
    try:
        def exp_decay(t, tau_r, A):
            return A * np.exp(-t / tau_r)
        fit_start = len(C_int) // 5
        popt, _ = curve_fit(exp_decay, lag_times[fit_start:],
                             C_int[fit_start:], p0=[lag_times[len(C_int)//2], 0.5],
                             maxfev=2000)
        tau_res = popt[0]
        print(f"Residence time τ_res ≈ {tau_res:.2f} ps (from exponential tail fit)")
    except Exception:
        tau_res = np.trapz(C_int, lag_times)
        print(f"Residence time τ_res ≈ {tau_res:.2f} ps (from integral; "
              f"exponential fit failed — check if ACF decays within τ_max)")

    return lag_times, C_int

Workflow 4: Thermodynamic observables from simulation logs

Thermodynamic observables (temperature, pressure, energy, stress, density, volume) are written to the LAMMPS log or GROMACS .edr file, not the trajectory. Their time series must be parsed, block-averaged, and checked for stationarity before quoting ensemble averages.

import numpy as np
from pathlib import Path


def parse_lammps_log(log_file: str) -> dict[str, np.ndarray]:
    """
    Parse all thermo columns from a LAMMPS log file.

    Handles multiple 'run' blocks in a single log (e.g., equilibration + production).
    Returns a flat dict of column_name → numpy array, concatenated across all runs.

    The Step column can be used to identify which run block a frame belongs to.
    """
    data: dict[str, list] = {}
    header: list[str] = []
    in_run = False

    with open(log_file) as f:
        for line in f:
            stripped = line.strip()
            if stripped.startswith("Step"):
                header = stripped.split()
                for k in header:
                    if k not in data:
                        data[k] = []
                in_run = True
                continue
            if in_run:
                parts = stripped.split()
                if len(parts) == len(header):
                    try:
                        vals = list(map(float, parts))
                        for k, v in zip(header, vals):
                            data[k].append(v)
                    except ValueError:
                        in_run = False

    return {k: np.array(v) for k, v in data.items() if v}


def parse_gromacs_edr(edr_file: str, terms: list[str] = None) -> dict[str, np.ndarray]:
    """
    Parse GROMACS energy (.edr) file using panedr or MDAnalysis.

    panedr is the recommended parser (pip install panedr).
    Returns a dict of {term_name: array} where arrays have one value per frame.

    terms: if None, returns all available terms. Otherwise, subset.
    Common terms: "Temperature", "Pressure", "Potential Energy", "Kinetic En.",
                  "Total Energy", "Density", "Volume"
    """
    try:
        import panedr
        df = panedr.edr_to_df(edr_file)
        if terms:
            missing = [t for t in terms if t not in df.columns]
            if missing:
                print(f"WARNING: terms not found in .edr: {missing}")
                print(f"  Available: {list(df.columns[:20])}")
            terms = [t for t in terms if t in df.columns]
            df = df[terms]
        return {col: df[col].values for col in df.columns}
    except ImportError:
        raise ImportError(
            "panedr not installed. Install with: pip install panedr\n"
            "Alternative: use 'gmx energy -f edr_file' at the command line."
        )


def block_average(
    x: np.ndarray,
    n_blocks: int = 5,
    skip_frac: float = 0.0,
) -> dict:
    """
    Block averaging for statistical error estimation.

    Divides the time series (after discarding skip_frac as equilibration) into
    n_blocks equal-length blocks and computes the block mean and block standard
    deviation. The standard error of the mean is std_blocks / sqrt(n_blocks),
    which approaches the true standard error as block_length ≫ autocorrelation_time.

    Practical guide: start with n_blocks = 5. If block std is still increasing
    with larger block sizes, the blocks are not yet independent — increase the
    production run length or reduce n_blocks.

    [EXPERT REVIEW NEEDED: n_blocks = 5–10 is a rule of thumb; the optimal
    number depends on the observable's autocorrelation time]
    """
    skip = int(skip_frac * len(x))
    x = x[skip:]
    n = len(x)
    block_size = n // n_blocks
    if block_size < 10:
        raise ValueError(f"Block size = {block_size} frames is too small. "
                         "Reduce n_blocks or use a longer trajectory.")

    block_means = []
    for i in range(n_blocks):
        block = x[i * block_size:(i + 1) * block_size]
        block_means.append(block.mean())

    block_means = np.array(block_means)
    overall_mean = block_means.mean()
    se = block_means.std(ddof=1) / np.sqrt(n_blocks)   # Standard error of the mean

    return {
        "mean": overall_mean,
        "std_err": se,
        "block_means": block_means,
        "n_blocks": n_blocks,
        "block_size": block_size,
        "95ci": (overall_mean - 1.96 * se, overall_mean + 1.96 * se),
    }


def compute_autocorrelation_time(x: np.ndarray, max_lag: int = None) -> dict:
    """
    Estimate the integrated autocorrelation time τ for a scalar observable.

    τ = 0.5 + Σ_{k=1}^{k_max} C_k   where C_k = corr(x_t, x_{t+k})

    k_max is determined by the window-closing criterion: stop summing when
    C_k drops below 0 or below the noise level (2/sqrt(N)). This avoids
    adding noise to τ from the long-lag tail of the ACF.

    N_eff = N / (2τ) is the effective number of independent samples.
    """
    x = np.asarray(x, dtype=float)
    x = x - x.mean()
    N = len(x)
    if max_lag is None:
        max_lag = N // 4

    # Normalized ACF via FFT
    fft_x = np.fft.rfft(x, n=2*N)
    acf_full = np.fft.irfft(np.abs(fft_x)**2)[:N]
    acf_norm = acf_full / acf_full[0]

    # Window closing: stop at first negative or at 2/sqrt(N) noise level
    tau = 0.5
    noise_level = 2.0 / np.sqrt(N)
    k_cutoff = 1
    for k in range(1, min(max_lag, N // 2)):
        if acf_norm[k] <= noise_level:
            k_cutoff = k
            break
        tau += acf_norm[k]
        k_cutoff = k

    N_eff = N / (2 * tau)
    se = x.std() / np.sqrt(N_eff)

    print(f"Autocorrelation: τ = {tau:.1f} frames, k_cutoff = {k_cutoff}, "
          f"N_eff = {N_eff:.0f} / {N}, SE = {se:.4f}")

    return {
        "tau_frames": tau,
        "k_cutoff": k_cutoff,
        "N_eff": N_eff,
        "se_of_mean": se,
        "acf_normalized": acf_norm[:k_cutoff + 10],
    }


def check_energy_stationarity(
    log: dict[str, np.ndarray],
    skip_frac: float = 0.0,
    n_blocks: int = 5,
    dt_ps: float = 0.002,
) -> None:
    """
    Report thermodynamic averages and block-averaged errors for common
    LAMMPS thermo columns. Checks for stationarity by comparing block means.

    A monotonic trend in block means indicates non-stationarity (the system
    is still evolving — production started too early, or the system has a
    slow drift such as grain growth or phase separation).
    """
    print(f"\n{'Observable':<15}  {'Mean':>12}  {'SE':>10}  {'Stationary?':>12}")
    print("─" * 55)

    for key in ("Temp", "Press", "Etotal", "Density", "Vol"):
        if key not in log:
            continue
        skip = int(skip_frac * len(log[key]))
        data = log[key][skip:]
        result = block_average(data, n_blocks=n_blocks)
        bm = result["block_means"]
        # Simple stationarity check: are block means monotonically ordered?
        is_monotone = bool(np.all(np.diff(bm) > 0) or np.all(np.diff(bm) < 0))
        status = "DRIFT?" if is_monotone else "OK"
        unit = {"Temp": "K", "Press": "bar", "Etotal": "eV",
                 "Density": "g/cm³", "Vol": "ų"}.get(key, "")
        print(f"{key:<15}  {result['mean']:>12.4f}  {result['std_err']:>10.4f}  {status:>12}")

Workflow 5: Interface and defect analysis

Interface and defect structures require per-atom analysis rather than bulk averages. OVITO's pipeline API is the most convenient tool for CNA, CSP, Voronoi, and per-atom stress analysis.

import numpy as np


def ovito_cna_analysis(
    dump_file: str,
    frame_index: int = -1,
    output_file: str = None,
) -> dict:
    """
    Compute Common Neighbor Analysis (CNA) and Centrosymmetry Parameter (CSP)
    using OVITO's Python API.

    CNA structure types:
        0 = Other (amorphous, surface, defect)
        1 = FCC
        2 = HCP
        3 = BCC
        4 = Icosahedral

    CSP ≈ 0 for centrosymmetric environments (perfect FCC bulk);
    CSP > 0 indicates distortion, defects, or surfaces.

    OVITO must be installed: pip install ovito
    """
    import ovito
    from ovito.io import import_file
    from ovito.modifiers import (
        CommonNeighborAnalysisModifier,
        CentroSymmetryModifier,
        VoronoiAnalysisModifier,
    )

    pipeline = import_file(dump_file)

    # CNA
    pipeline.modifiers.append(
        CommonNeighborAnalysisModifier(
            mode=CommonNeighborAnalysisModifier.Mode.FixedCutoff,
        )
    )
    # CSP
    pipeline.modifiers.append(
        CentroSymmetryModifier(num_neighbors=12)
    )
    # Voronoi (coordination number without cutoff dependence)
    pipeline.modifiers.append(
        VoronoiAnalysisModifier(
            compute_indices=False,
            use_radii=False,
        )
    )

    data = pipeline.compute(frame_index)

    # Extract per-atom properties
    cna_types = data.particles["Structure Type"][:]
    csp = data.particles["Centrosymmetry"][:]
    coord_numbers = data.particles["Coordination"][:]

    type_names = {0: "Other", 1: "FCC", 2: "HCP", 3: "BCC", 4: "Icosahedral"}
    unique, counts = np.unique(cna_types, return_counts=True)
    total = len(cna_types)

    print("\nCNA structure type fractions:")
    for t, c in zip(unique, counts):
        name = type_names.get(int(t), f"Type{t}")
        print(f"  {name:<15}: {c:>6} atoms  ({c/total*100:>5.1f}%)")

    print(f"\nCSP statistics (FCC only: ideal = 0.0):")
    if (cna_types == 1).any():
        fcc_csp = csp[cna_types == 1]
        print(f"  FCC atoms: mean CSP = {fcc_csp.mean():.3f}, max = {fcc_csp.max():.3f}")

    print(f"\nCoordination number (Voronoi): mean = {coord_numbers.mean():.2f}, "
          f"range = [{coord_numbers.min()}, {coord_numbers.max()}]")

    if output_file:
        from ovito.io import export_file
        export_file(pipeline, output_file, "lammps/dump",
                    columns=["Particle Identifier", "Particle Type",
                              "Position.X", "Position.Y", "Position.Z",
                              "Structure Type", "Centrosymmetry", "Coordination"])
        print(f"Per-atom analysis written to {output_file}")

    return {
        "cna_types": cna_types,
        "csp": csp,
        "coordination": coord_numbers,
        "fcc_fraction": float((cna_types == 1).sum()) / total,
        "defect_fraction": float((cna_types == 0).sum()) / total,
    }


def compute_density_profile(
    u: mda.Universe,
    axis: int = 2,    # 0=x, 1=y, 2=z
    n_bins: int = 100,
    species: str = None,   # None = all atoms
    start: int = 0,
    stop: int = None,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Compute the mass density profile along one axis (for interfaces, slabs, films).

    Returns (bin_centers_A, density_g_cm3) averaged over production frames.

    Useful for:
    - Confirming interface position and width
    - Detecting density oscillations at solid-liquid interfaces
    - Measuring slab thickness in thin-film simulations
    - Checking for density anomalies near defects
    """
    sel = u.select_atoms(f"name {species}") if species else u.atoms
    masses_amu = sel.masses  # g/mol = amu (1 amu = 1 g/mol / N_A)

    # Use first frame to get box dimension
    u.trajectory[0]
    L = u.dimensions[axis]   # Å

    bins = np.linspace(0, L, n_bins + 1)
    density_sum = np.zeros(n_bins)
    n_frames = 0

    for ts in u.trajectory[start:stop]:
        coords = sel.positions[:, axis]
        coords = coords % L   # Wrap to primary box along axis
        # Histogram of mass
        mass_hist, _ = np.histogram(coords, bins=bins,
                                     weights=masses_amu)
        bin_vol = (bins[1] - bins[0]) * u.dimensions[(axis+1) % 3] * u.dimensions[(axis+2) % 3]
        # Convert g/mol/ų → g/cm³: multiply by (1/N_A) × (10¹⁰)³ = 1.6605 g/cm³ per amu/ų
        amu_A3_to_g_cm3 = 1.6605  # amu/ų → g/cm³
        density_sum += mass_hist / bin_vol * amu_A3_to_g_cm3
        n_frames += 1

    bin_centers = 0.5 * (bins[1:] + bins[:-1])
    density_profile = density_sum / max(n_frames, 1)

    bulk_density = density_profile[n_bins // 4 : 3 * n_bins // 4].mean()
    print(f"Density profile: axis {axis}, {n_bins} bins, {n_frames} frames")
    print(f"  Bulk density (middle 50%): {bulk_density:.3f} g/cm³")

    return bin_centers, density_profile

Workflow 6: Statistical reliability — block averaging, equilibration trimming, and uncertainty

All reported observables must be accompanied by a statistical uncertainty. For correlated MD time series, naive standard deviations from all frames are a severe underestimate.

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt


def estimate_equilibration_end(
    x: np.ndarray,
    window_frac: float = 0.05,
    threshold_std: float = 2.0,
) -> int:
    """
    Estimate where equilibration ends using a sliding-window mean stability criterion.

    Scans from the end of the time series backward, computing the running mean
    in a window of width window_frac * N. The equilibration end is the first
    frame where the running mean exceeds threshold_std * overall_std from the
    production mean. This is a heuristic — always verify visually.

    Returns frame index where production is deemed to start.
    [EXPERT REVIEW NEEDED: threshold_std = 2.0 is conservative; adjust per system]
    """
    N = len(x)
    window = max(10, int(window_frac * N))
    prod_mean = x[N // 2:].mean()
    prod_std = x[N // 2:].std()

    equil_end = 0
    for i in range(N - window, -1, -1):
        window_mean = x[i:i + window].mean()
        if abs(window_mean - prod_mean) > threshold_std * prod_std:
            equil_end = i + window
            break

    print(f"Estimated equilibration end: frame {equil_end} / {N} "
          f"({equil_end/N*100:.1f}% of trajectory)")
    if equil_end > 0.5 * N:
        print("  WARNING: > 50% of trajectory appears to be equilibration. "
              "Consider extending the production run.")

    return equil_end


def plot_block_convergence(
    x: np.ndarray,
    label: str = "Observable",
    block_sizes: list = None,
    output_file: str = "block_convergence.png",
) -> None:
    """
    Plot block standard deviation vs. block size to assess statistical convergence.

    If the block std plateaus as block size increases, the blocks are independent
    at that block size. If it is still rising at the largest block size, the
    autocorrelation time is longer than the block size — the trajectory is too short
    for reliable error estimates.
    """
    N = len(x)
    if block_sizes is None:
        block_sizes = [max(2, N // 64), N // 32, N // 16, N // 8, N // 4, N // 2]
        block_sizes = sorted(set(b for b in block_sizes if b >= 2))

    block_stds = []
    for bs in block_sizes:
        n_blocks = N // bs
        if n_blocks < 2:
            block_stds.append(np.nan)
            continue
        blocks = [x[i*bs:(i+1)*bs].mean() for i in range(n_blocks)]
        block_stds.append(np.std(blocks, ddof=1) / np.sqrt(n_blocks))

    fig, ax = plt.subplots(figsize=(5, 4))
    ax.semilogx(block_sizes, block_stds, "o-", color="steelblue")
    ax.set_xlabel("Block size (frames)")
    ax.set_ylabel(f"Standard error of {label}")
    ax.set_title("Block averaging convergence")
    ax.grid(True, alpha=0.3)
    fig.tight_layout()
    fig.savefig(output_file, dpi=150)
    print(f"Block convergence plot saved: {output_file}")

    # Report if converged
    finite_stds = [s for s in block_stds if np.isfinite(s)]
    if len(finite_stds) >= 2:
        plateau_ratio = finite_stds[-1] / finite_stds[-2] if finite_stds[-2] > 0 else 1.0
        if plateau_ratio < 1.1:
            print(f"Block std appears converged (ratio = {plateau_ratio:.3f})")
        else:
            print(f"Block std still increasing (ratio = {plateau_ratio:.3f}) — "
                  "trajectory may be too short for reliable error estimates")


def report_observable(
    x: np.ndarray,
    name: str,
    unit: str,
    skip_frac: float = 0.0,
    n_blocks: int = 5,
    dt_ps: float = None,
) -> dict:
    """
    Full statistical report for a scalar observable from a production trajectory.

    Returns a dict suitable for inclusion in a results table or methods section.
    """
    skip = int(skip_frac * len(x))
    data = x[skip:]

    acf_result = compute_autocorrelation_time(data)
    block_result = block_average(data, n_blocks=n_blocks)

    print(f"\n{name} ({unit}):")
    print(f"  Frames: {skip}–{len(x)} ({len(data)} frames used)")
    print(f"  Mean ± SE: {block_result['mean']:.4f} ± {block_result['std_err']:.4f} {unit}")
    print(f"  95% CI: [{block_result['95ci'][0]:.4f}, {block_result['95ci'][1]:.4f}]")
    print(f"  τ_corr = {acf_result['tau_frames']:.1f} frames, "
          f"N_eff = {acf_result['N_eff']:.0f}")
    if dt_ps:
        print(f"  τ_corr = {acf_result['tau_frames'] * dt_ps:.2f} ps")

    return {
        "mean": block_result["mean"],
        "std_err": block_result["std_err"],
        "95ci": block_result["95ci"],
        "tau_corr": acf_result["tau_frames"],
        "N_eff": acf_result["N_eff"],
    }

Workflow 7: Uncertainty-aware postprocessing for MLP trajectories

When the MD trajectory was driven by a committee of MLP models, each frame carries an uncertainty estimate (committee force std σ_F). Frames with high σ_F are potential extrapolation events. Thermodynamic averages should be computed selectively from frames in the low-uncertainty regime, and high-uncertainty frames should be flagged for active learning.

import numpy as np
from ase.io import read


def tag_frames_by_uncertainty(
    traj_file: str,
    sigma_low: float = 0.05,    # eV/Å — confident threshold
    sigma_high: float = 0.30,   # eV/Å — extrapolation threshold
    uncertainty_key: str = "max_force_stdev",
    skip: int = 0,
    every: int = 1,
) -> dict:
    """
    Tag trajectory frames by MLP committee uncertainty.

    Reads 'max_force_stdev' (or another per-frame key) from extxyz info dict.
    This key is written by the MACE active learning calculator or
    the uncertainty-mlp skill's committee calculator.

    Returns a dict with three lists of frames:
        confident: σ_F < sigma_low (safe for production averages)
        uncertain: sigma_low ≤ σ_F < sigma_high (inspect before using)
        extrapolating: σ_F ≥ sigma_high (exclude from analysis; add to AL queue)

    [EXPERT REVIEW NEEDED: sigma_low and sigma_high are system- and
     training-set-dependent; calibrate on held-out DFT calculations]
    """
    frames = read(traj_file, index=f"{skip}::{every}", format="extxyz")
    if not isinstance(frames, list):
        frames = [frames]

    confident, uncertain, extrapolating = [], [], []
    missing_key_count = 0

    for i, atoms in enumerate(frames):
        sigma = atoms.info.get(uncertainty_key, None)
        if sigma is None:
            missing_key_count += 1
            confident.append(atoms)  # No uncertainty info → treat as confident
            continue
        if sigma < sigma_low:
            confident.append(atoms)
        elif sigma < sigma_high:
            uncertain.append(atoms)
        else:
            extrapolating.append(atoms)

    n_total = len(frames)
    print(f"\nFrame tagging by uncertainty ({uncertainty_key}):")
    print(f"  Confident    (σ < {sigma_low:.2f} eV/Å): "
          f"{len(confident):>5}  ({len(confident)/n_total*100:>5.1f}%)")
    print(f"  Uncertain    ({sigma_low:.2f} ≤ σ < {sigma_high:.2f}): "
          f"{len(uncertain):>5}  ({len(uncertain)/n_total*100:>5.1f}%)")
    print(f"  Extrapolating (σ ≥ {sigma_high:.2f} eV/Å): "
          f"{len(extrapolating):>5}  ({len(extrapolating)/n_total*100:>5.1f}%)")

    if missing_key_count > 0:
        print(f"  NOTE: {missing_key_count} frames missing key '{uncertainty_key}' "
              "— treated as confident. Re-run with a committee calculator to populate.")

    if len(extrapolating) / n_total > 0.01:
        print(f"  WARNING: > 1% extrapolating frames — add these to the active learning queue. "
              "Thermodynamic averages from this trajectory may be unreliable.")

    return {
        "confident": confident,
        "uncertain": uncertain,
        "extrapolating": extrapolating,
        "n_total": n_total,
    }


def compute_uncertainty_weighted_average(
    frames: list,
    observable_fn,
    uncertainty_key: str = "max_force_stdev",
    sigma_max: float = 0.30,
) -> tuple[float, float]:
    """
    Compute an ensemble average of a scalar observable restricted to
    frames with σ_F < sigma_max.

    observable_fn: callable that takes an ASE Atoms object and returns a float.
        Examples: lambda a: a.info["energy"] / len(a)
                  lambda a: a.get_volume()

    Returns (mean, std_err) from block averaging on the selected frames.
    """
    values = []
    for atoms in frames:
        sigma = atoms.info.get(uncertainty_key, 0.0)
        if sigma < sigma_max:
            try:
                values.append(float(observable_fn(atoms)))
            except Exception as e:
                pass  # Skip frames where observable fails (e.g., no energy key)

    if len(values) < 10:
        print(f"WARNING: only {len(values)} confident frames for averaging. "
              "Estimate is unreliable.")
        return float(np.mean(values)) if values else float("nan"), float("nan")

    values = np.array(values)
    result = block_average(values)
    return result["mean"], result["std_err"]

Workflow 8: Visualization and data export

OVITO provides the most capable visualization pipeline for trajectory data; matplotlib is standard for publication-quality plots; pandas is used for structured data export.

import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
import pandas as pd
from pathlib import Path


def plot_rdf(
    r: np.ndarray,
    g: np.ndarray,
    species_A: str,
    species_B: str,
    reference: tuple = None,   # (r_ref, g_ref, label) for comparison overlay
    output_file: str = "rdf.png",
) -> None:
    """
    Publication-quality RDF plot with optional reference overlay.

    reference: tuple of (r_ref, g_ref, label) for comparison to DFT-MD,
    experiment, or a different force field.
    """
    fig, ax = plt.subplots(figsize=(5, 3.5))
    ax.plot(r, g, "-", color="steelblue", lw=1.5,
            label=f"g$_{{{species_A}-{species_B}}}$(r)")
    ax.axhline(1.0, color="gray", ls="--", lw=0.8, label="ideal gas")
    if reference is not None:
        r_ref, g_ref, ref_label = reference
        ax.plot(r_ref, g_ref, "--", color="tomato", lw=1.2, label=ref_label)
    ax.set_xlabel("r (Å)")
    ax.set_ylabel("g(r)")
    ax.set_xlim(0, r.max())
    ax.set_ylim(bottom=0)
    ax.legend(fontsize=8)
    ax.set_title(f"Radial Distribution Function: {species_A}–{species_B}")
    fig.tight_layout()
    fig.savefig(output_file, dpi=200)
    plt.close(fig)
    print(f"RDF plot saved: {output_file}")


def plot_msd(
    lag_times: np.ndarray,
    msd: np.ndarray,
    D_fit: dict = None,
    output_file: str = "msd.png",
) -> None:
    """
    Log-log MSD plot with optional diffusion coefficient fit overlay.

    Log-log scale reveals the regimes:
    - Ballistic (slope 2) at short times
    - Subdiffusive (slope < 1) if present (crowded/glassy)
    - Diffusive (slope 1) at long times for liquids
    - Plateau for solids (Debye-Waller factor)
    """
    fig, axes = plt.subplots(1, 2, figsize=(9, 3.5))

    # Linear scale
    axes[0].plot(lag_times, msd, "-", color="steelblue", lw=1.2)
    if D_fit:
        t0, t1 = D_fit.get("fit_range_ps", (lag_times[0], lag_times[-1]))
        t_fit = np.linspace(t0, t1, 100)
        msd_fit = 6 * D_fit["D_A2_ps"] * t_fit
        axes[0].plot(t_fit, msd_fit, "--r", lw=1.2,
                     label=f"D = {D_fit['D_m2_s']:.2e} m²/s")
        axes[0].legend(fontsize=8)
    axes[0].set_xlabel("Lag time (ps)")
    axes[0].set_ylabel("MSD (Ų)")
    axes[0].set_title("MSD (linear)")

    # Log-log scale
    axes[1].loglog(lag_times[1:], msd[1:], "-", color="steelblue", lw=1.2)
    # Guide lines
    t_guide = np.array([lag_times[1], lag_times[-1]])
    axes[1].loglog(t_guide, 0.1 * t_guide**2, ":", color="gray", lw=0.8,
                   label="slope 2 (ballistic)")
    axes[1].loglog(t_guide, msd[len(msd)//4] / lag_times[len(lag_times)//4] * t_guide,
                   "--", color="gray", lw=0.8, label="slope 1 (diffusive)")
    axes[1].set_xlabel("Lag time (ps)")
    axes[1].set_ylabel("MSD (Ų)")
    axes[1].set_title("MSD (log-log)")
    axes[1].legend(fontsize=7)

    fig.tight_layout()
    fig.savefig(output_file, dpi=200)
    plt.close(fig)
    print(f"MSD plot saved: {output_file}")


def export_results(
    results: dict,
    output_dir: str = "analysis_results",
) -> None:
    """
    Export analysis results to structured CSV and JSON files for reproducibility.

    results: dict mapping observable_name → value or dict from report_observable().
    Creates:
        observables_summary.csv — one row per observable with mean, SE, N_eff
        analysis_metadata.json — software versions, trajectory info
    """
    import json
    import datetime

    out = Path(output_dir)
    out.mkdir(exist_ok=True)

    rows = []
    for key, val in results.items():
        if isinstance(val, dict) and "mean" in val:
            rows.append({
                "observable": key,
                "mean": val["mean"],
                "std_err": val.get("std_err", float("nan")),
                "ci_low": val.get("95ci", [float("nan")])[0],
                "ci_high": val.get("95ci", [float("nan"), float("nan")])[1],
                "N_eff": val.get("N_eff", float("nan")),
                "tau_corr": val.get("tau_corr", float("nan")),
            })
        else:
            rows.append({"observable": key, "mean": val, "std_err": float("nan"),
                         "ci_low": float("nan"), "ci_high": float("nan"),
                         "N_eff": float("nan"), "tau_corr": float("nan")})

    df = pd.DataFrame(rows)
    csv_path = out / "observables_summary.csv"
    df.to_csv(csv_path, index=False, float_format="%.6f")
    print(f"Results CSV: {csv_path}")

    meta = {
        "analysis_date": datetime.datetime.now().isoformat(),
        "software": {
            "MDAnalysis": "2.7.0",
            "OVITO": "3.10.6",
            "ASE": "3.23.0",
            "pandas": "2.2.0",
            "matplotlib": "3.8.0",
        },
    }
    meta_path = out / "analysis_metadata.json"
    meta_path.write_text(json.dumps(meta, indent=2))
    print(f"Metadata: {meta_path}")

Common Failure Modes

FailureSymptomLikely CauseDiagnosticFix
Wrapped coordinates corrupting MSDMSD plateaus at (L/2)² ≈ (box/2)² for a liquid or a diffusing ion; diffusion coefficient is zero or near-zeroAtoms that cross a periodic boundary appear to "jump back" in wrapped coordinates; displacement is bounded by box sizePlot MSD on log-log scale; if the slope drops toward zero and the plateau value is ≈ (L/2)², wrapping is the causeUse dump_modify ... unwrap yes in LAMMPS before the next run; or apply unwrap_trajectory post-processing (Workflow 3); verify with a short NVE test run
Wrong timestep units in analysisMSD slope is off by a factor of 10³ or 10⁶; VACF frequency axis is in wrong unitsLAMMPS metal units: timestep is in ps; real units: fs. MDAnalysis dt attribute reads the value from the dump but does not convert units. A metal-unit dump with dt=0.002 reads as 0.002 fs, not 0.002 psPrint u.trajectory.dt and compare to the LAMMPS timestep × dump_every to compute the correct frame-to-frame timeSet dt manually in MDAnalysis: u.trajectory.ts.dt = actual_dt_ps; or pass dt explicitly to all analysis functions that use lag times
Using unequilibrated frames in averagesTemperature, pressure, or energy averages are biased toward initial values; time-averaged RDF has extra or missing peaks not present at equilibriumProduction analysis started from frame 0 without trimming the equilibration phaseRun estimate_equilibration_end and check_energy_stationarity; if block means trend monotonically, equilibration contamination is likelySet skip_frac ≥ 0.2 in all analysis functions; verify visually with a time-series plot of T, P, and E before committing to averages
Incorrect topology — atom type mismatchRDF first peak at wrong distance; coordination numbers wrong; CNA reports wrong structure types; per-species analyses silently combine different speciesInteger atom types from LAMMPS dump not mapped to element names; or topology file (data file) atom type order differs from the force-field element order in pair_coeffPrint set(u.atoms.names) and compare to expected element symbols; cross-check with pair_coeff element order in the input scriptProvide the correct atom_type_names mapping (Workflow 1); always verify by checking that the RDF first-peak position matches the known nearest-neighbor distance for the material
PBC artifacts in RDFSpurious peaks or a step-function artifact near r = L/2 in g(r); RDF does not converge to 1.0 at large rr_max exceeds half the minimum box dimension; atoms in one half of the box are counted twice via periodic imagesCheck r_max < 0.45 * min(box_lengths) before running RDF; the MDAnalysis InterRDF raises a warning but does not stopReduce r_max to satisfy the criterion; or use a larger simulation box if long-range structure is required
Insufficient sampling — thermostat transient in averagesDiffusion coefficient or residence time computed from the first 20–50 ps of a 100 ps trajectory; result has poor statistics or is biasedShort production run with long autocorrelation time; or analysis started immediately after switching thermostatsCompute autocorrelation time τ and verify that the production length > 50τ for the observable of interest; plot block convergenceExtend production run; use block averaging with at least 5 blocks of length > 2τ to assess convergence; report the effective sample size N_eff alongside the result
Barostat transient contaminating averagesDensity or volume average includes a slow drift over the first few ns of an NPT run; result is inconsistent between different starting geometriesNPT switched on from a structure whose density is far from equilibrium; Parrinello-Rahman barostat starts far from equilibrium and oscillatesPlot volume vs. time; if a monotonic trend is visible in the first 10–30% of the production trajectory, the barostat has not equilibratedExtend NVT equilibration before NPT; use Berendsen barostat for initial density relaxation (see md-equilibration); discard the drift portion from production averages
Overinterpreting noisy order parameters near transitionsQ_6 or CNA type fractions oscillate strongly; melting temperature estimate is sensitive to run length; phase fractions are not reproducible between independent runsSystem is near a phase transition or a coexistence point; order parameters fluctuate on timescales longer than the run; finite-size effects may stabilize or suppress one phaseCheck finite-size scaling: run 2× and 4× the original system size; compare resultsFor phase transitions, use multiple independent trajectories and report the standard deviation across runs; consider enhanced sampling (see enhanced-sampling) for accurate coexistence conditions
CoM drift masking diffusion or artificially inflating MSDMSD grows linearly but the slope is 10× larger than physically expected; RDF is correct; all atoms drift togetherFlying ice cube effect: net center-of-mass momentum built up during equilibration; CoM drift is a rigid-body translation that appears as diffusion of every atomComputev_CoMfrom per-atom velocities (see md-equilibration Workflow 5); if non-zero, CoM drift is presentApply subtract_com=True in MSD calculation; in LAMMPS: add fix zero_mom all momentum 100 linear 1 1 1 to remove CoM momentum periodically
MLP extrapolation events biasing averagesThermodynamic averages from MLP-MD are inconsistent with DFT-MD or classical MD at the same conditions; energy has occasional spikesFrames where the MLP extrapolates outside its training domain contribute unphysical forces that distort the trajectory; rare but high-energy configurations disproportionately bias averagesTag frames by committee uncertainty (Workflow 7); compute averages on confident frames only; compare to averages on all framesExclude high-σ_F frames from averages; add extrapolating structures to the active learning queue; if > 1% of frames are extrapolating, the production trajectory is unreliable and the MLP must be refined

Best Practices

  • Always specify and justify the equilibration cutoff. Report the total trajectory length, the number of frames discarded as equilibration, and the criterion used (block-mean stationarity, energy plateau, density convergence). Do not rely on the input-script equilibration stage alone — verify from the trajectory data.
  • Compute block-averaged standard errors, not standard deviations of all frames. A 10 ns trajectory with 2 ps autocorrelation time has only N_eff ≈ 2,500 independent samples, not 5,000,000 frames. Standard deviations from all frames underestimate the true error by a factor of √(5,000,000 / 2,500) ≈ 45.
  • Verify r_max < L_min / 2 before computing RDFs. The minimum-image convention is valid only up to half the box length; beyond that, g(r) is contaminated by periodic images. Check this automatically or add an assertion at the start of RDF analysis.
  • Never use wrapped coordinates for MSD or diffusion analysis. Always either use dump_modify ... unwrap yes in LAMMPS, or apply post-processing unwrapping before any displacement-based calculation. Verify by checking that a solid-state MSD plateaus at the expected Debye-Waller value (≈ 3kT / mω²) rather than growing.
  • Cross-validate structural observables against literature or DFT-MD where possible. The first-peak position in g(r) should match the experimental or DFT nearest-neighbor distance within 0.1–0.2 Å. Coordination numbers should match crystal structure topology at low T. Discrepancies indicate force-field problems, not just statistical errors.
  • For MLP-driven MD, always tag frames by committee uncertainty before analysis. A few extrapolation events per nanosecond can bias thermodynamic averages by amounts larger than the statistical uncertainty. Report what fraction of frames were excluded and at what σ_F threshold.
  • Report trajectory provenance alongside every observable. Record: force field or MLP model path and checksum, timestep, dump frequency, production run length, equilibration length discarded, thermostat and barostat types, and software versions. Without this, results from the same simulation cannot be reproduced and the analysis cannot be peer-reviewed.
  • For dynamical properties, verify with at least two independent initial conditions. MSD, VACF, and residence times from a single trajectory are subject to sampling bias in the initial velocity distribution. Two independent trajectories with different random seeds provide a minimal estimate of run-to-run variability. [EXPERT REVIEW NEEDED: three or more runs are preferred for publication-quality results]
  • Use OVITO for CNA and per-atom analysis rather than manual implementations. OVITO's CNA, CSP, and Voronoi modifiers are validated against known reference structures, handle triclinic PBC correctly, and provide a scriptable pipeline with GPU acceleration. Manual implementations may have subtle PBC or normalization errors that are not obvious from the output.
  • Distinguish interface sites from bulk sites before computing order parameters. Atoms in surface layers or at grain boundaries have inherently low Q_6 and anomalous CNA types by construction. Including them in a bulk crystal analysis reduces the apparent order parameter and inflates the "defect fraction" without representing a physical defect concentration.

Integration with Other Skills

  • lammps-workflow: The LAMMPS dump format, unit conventions, and trajectory-writing settings (dump_modify sort id, dump_modify unwrap yes) established in that skill determine what data is available for analysis. The thermo_style output written to log.lammps is the primary source for thermodynamic observables in Workflow 4 here.
  • md-equilibration: This skill's equilibration trimming (Workflows 4 and 6) implements the diagnostic criteria defined in that skill. The quantitative equilibration checks (temperature stability, energy drift, block-mean stationarity) from that skill must be passed before any production analysis proceeds. That skill also covers the flying-ice-cube detection that informs the subtract_com correction in Workflow 3.
  • md-force-fields: The structural observables computed here (RDF first-peak position, coordination number, melting temperature from CNA) are the primary benchmarks for validating force-field transferability outside the fitting database. Discrepancies between computed and reference observables indicate force-field failures that must be diagnosed in that skill.
  • gromacs-workflow: GROMACS trajectories are loaded via the .tpr/.xtc/.trr interface. This skill's MDAnalysis workflows apply directly; only the loader call changes. The GROMACS .edr parser (panedr) replaces the LAMMPS log parser for thermodynamic observables. GROMACS has native tools (gmx rdf, gmx msd, gmx dos) that can cross-check MDAnalysis results.
  • reactive-md: ReaxFF and COMB trajectories require additional analysis not covered here: bond-order tracking, species inventory over time, and reaction event detection. This skill's structural and dynamical observables apply to the non-reactive epochs between bond events, but the full reactive analysis requires dedicated tools (OpenBabel, ChemTraYzer).
  • enhanced-sampling: Free energy surfaces from metadynamics or umbrella sampling use the same RDF, coordination number, and order parameter analysis tools described here, applied to biased trajectories with reweighting. The statistical analysis (block averaging, autocorrelation) changes because biased trajectories have non-uniform statistical weights — MBAR/WHAM must be applied before this skill's plain averaging.
  • mlp-validation: The MSD-based NVE energy conservation test and the finite-temperature RDF comparison from that skill are computed using the tools in Workflows 2 and 3 here. The equilibration protocol before an NVE test run must follow md-equilibration; the analysis of energy drift and RDF comparison follows this skill.
  • mlp-to-lammps: MLP-driven LAMMPS trajectories use the same dump format as classical LAMMPS runs. Workflow 1 here applies identically. The no_domain_decomposition constraint affects parallel performance but not the trajectory format or analysis.
  • active-learning-mlp: Workflow 7 here (uncertainty-aware frame tagging) is a post-processing step that identifies structures for the active learning query. Frames with σ_F above the threshold are candidates for DFT single-point calculations to expand the training set. The committee uncertainty trajectory produced during MACE active learning MD is the input to Workflow 7.
  • scientific-visualization: OVITO's render pipeline (surface meshes, dislocation analysis, grain boundary visualization, color-mapped per-atom CSP or Q_6) extends the scalar analysis in Workflow 5 to publication-quality figures and movies. That skill covers OVITO scripting for batch rendering, color maps, and animation of defect dynamics.
  • reproducibility-workflow: The analysis provenance exported by export_results (Workflow 8) — software versions, trajectory metadata, analysis parameters — maps directly to the reproducibility record described in that skill. Trajectory files, analysis scripts, and results should be versioned and archived together following that skill's DVC-based protocol.

Key References

  1. Michaud-Agrawal, N., et al. (2011). MDAnalysis: A toolkit for the analysis of molecular dynamics simulations. Journal of Computational Chemistry, 32(10), 2319–2327. https://doi.org/10.1002/jcc.21787
  2. Ong, S. P., et al. (2013). Python Materials Genomics (pymatgen): A robust, open-source python library for materials analysis. Computational Materials Science, 68, 314–319. https://doi.org/10.1016/j.commatsci.2012.10.028
  3. Stukowski, A. (2010). Visualization and analysis of atomistic simulation data with OVITO — the Open Visualization Tool. Modelling and Simulation in Materials Science and Engineering, 18(1), 015012. https://doi.org/10.1088/0965-0393/18/1/015012
  4. Frenkel, D. & Smit, B. (2002). Understanding Molecular Simulation: From Algorithms to Applications. 2nd ed. Academic Press. (Chapters 4, 7, 8: integrators, structural properties, dynamical properties.)
  5. Impey, R. W., Madden, P. A., & McDonald, I. R. (1983). Hydration and mobility of ions in solution. Journal of Physical Chemistry, 87(25), 5071–5083. https://doi.org/10.1021/j150643a008
  6. Bevan Dewar, M. J. S., et al. — see Flyvbjerg, H. & Petersen, H. G. (1989). Error estimates on averages of correlated data. Journal of Chemical Physics, 91(1), 461–466. https://doi.org/10.1063/1.457480
  7. Steinhardt, P. J., Nelson, D. R., & Ronchetti, M. (1983). Bond-orientational order in liquids and glasses. Physical Review B, 28(2), 784–805. https://doi.org/10.1103/PhysRevB.28.784

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.