diff --git a/amorphouspy/src/amorphouspy/properties/vibrational.py b/amorphouspy/src/amorphouspy/properties/vibrational.py deleted file mode 100644 index a017b067..00000000 --- a/amorphouspy/src/amorphouspy/properties/vibrational.py +++ /dev/null @@ -1,2877 +0,0 @@ -"""Vibrational properties of glass systems: vibrational density of states and related quantities. - -Frequencies in this module are ordinary frequencies in THz (not angular frequencies) unless stated otherwise. - -Author: Achraf Atila (achraf.atila@bam.de) -""" - -import contextlib -import math -import tempfile -import time -import warnings -from collections.abc import Iterator -from pathlib import Path -from typing import TYPE_CHECKING, Any, Literal - -import numpy as np -import pandas as pd -import scipy.fft -import scipy.linalg -import scipy.signal -from numpy.typing import ArrayLike, NDArray -from scipy.constants import Boltzmann, atomic_mass, c, e, h - -from amorphouspy.atoms.neighbors import cell_perpendicular_heights -from amorphouspy.lammps.runner import ( - Thermostat, - _is_positive_int, - _run_lammps_dynamical_matrix, - _run_lammps_md, - _validate_minimize_arguments, - thermostat_ensembles, -) -from amorphouspy.properties.structural.all import ( - _build_cutoff_map, - _classify_elements, - _former_oxygen_pair_cutoffs, - _network_former_types, -) -from amorphouspy.properties.structural.qn import CutoffSpec, compute_qn_and_classify, compute_qn_per_atom -from amorphouspy.properties.structural.rdf import compute_rdf - -if TYPE_CHECKING: - from ase import Atoms - -FrequencyUnit = Literal["THz", "cm-1", "meV", "rad/ps"] - -# Value of 1 THz in each unit. -_THZ_TO_UNIT: dict[str, float] = { - "THz": 1.0, - "cm-1": 1e12 / (100 * c), - "meV": (h * 1e12 / e) * 1e3, - "rad/ps": 2 * np.pi, -} - - -def convert_frequency( - values: float | NDArray, from_unit: FrequencyUnit, to_unit: FrequencyUnit -) -> float | NDArray[np.float64]: - """Convert frequencies between THz, cm^-1, meV and rad/ps. - - The conversion goes through THz. Negative values (the convention for imaginary harmonic modes) keep their sign. - - Args: - values: Frequency or array of frequencies in ``from_unit``. - from_unit: Unit of ``values``: ``"THz"``, ``"cm-1"``, ``"meV"`` or ``"rad/ps"``. - to_unit: Target unit, one of the same four. - - Returns: - A float for scalar input, otherwise a new float64 array of the same shape as ``values``. The input is never - modified; ``from_unit == to_unit`` returns a copy. - - Raises: - ValueError: If ``from_unit`` or ``to_unit`` is not one of the allowed units. - - Example: - >>> round(convert_frequency(1.0, "THz", "cm-1"), 5) - 33.35641 - >>> convert_frequency(np.array([-1.0, 2.0]), "THz", "rad/ps").round(4) - array([-6.2832, 12.5664]) - """ - for unit in (from_unit, to_unit): - if unit not in _THZ_TO_UNIT: - msg = f"Unknown frequency unit {unit!r}; allowed units are {list(_THZ_TO_UNIT)}." - raise ValueError(msg) - converted = np.asarray(values, dtype=np.float64) * (_THZ_TO_UNIT[to_unit] / _THZ_TO_UNIT[from_unit]) - if converted.ndim == 0: - return float(converted) - return converted - - -def _positions_by_label(labels: dict[int, str], id_to_position: dict[int, int]) -> dict[str, np.ndarray]: - """Group atom IDs by label and convert them to sorted int64 positions.""" - grouped: dict[str, list[int]] = {} - for atom_id, label in labels.items(): - grouped.setdefault(label, []).append(id_to_position[atom_id]) - return {label: np.sort(np.array(positions, dtype=np.int64)) for label, positions in sorted(grouped.items())} - - -def classify_vibrational_groups( - structure: "Atoms", - cutoff: CutoffSpec | None = None, - former_types: list[int] | None = None, - o_type: int = 8, -) -> dict[str, dict[str, np.ndarray]]: - """Label every atom by element, oxygen class and network-former Q^n for partial VDOS. - - Oxygen classes and Q^n come from :func:`compute_qn_and_classify` and :func:`compute_qn_per_atom`. Missing - ``cutoff`` and ``former_types`` are derived as in :func:`analyze_structure`: formers are the glass formers and - intermediates present, and each former-O cutoff is the first minimum of its RDF (``r_max=10.0``, - ``n_bins=500``), with the same fallbacks. - - Args: - structure: The atomic structure as ASE object. Atom IDs are read from the ``"id"`` array if present, - else taken as 1-based indices; the returned indices are always 0-based positions in ``structure``. - cutoff: Former-O cutoff in Å, either a scalar or a per-pair dict ``{(z_i, z_j): r_cut}``. Derived from - the RDF if ``None``. - former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. - o_type: Atomic number of oxygen. - - Returns: - A dict with three groupings, each mapping a label to a sorted int64 array of 0-based positions: - ``"element"``: element symbol, e.g. ``"Si"``, ``"O"``, ``"Na"``. - ``"oxygen"``: ``"O_BO"``, ``"O_NBO"``, ``"O_free"``, ``"O_tri"``. - ``"qn"``: former symbol and number of bridging oxygens, e.g. ``"Si_Q3"``, ``"B_Q4"``. - Labels without atoms are omitted. Without oxygen, ``"oxygen"`` and ``"qn"`` are empty; with oxygen but - no formers, ``"qn"`` is empty and every oxygen is ``"O_free"``. - - Raises: - ValueError: If the ``"id"`` array contains duplicate IDs. - - Example: - ```pycon - >>> from ase import Atoms - >>> d = 1.6 - >>> positions = [[10, 10, 10], [10 + 2 * d, 10, 10], [10 + d, 10, 10], - ... [10 - d, 10, 10], [10, 10 + d, 10], [10, 10, 10 + d], - ... [10 + 3 * d, 10, 10], [10 + 2 * d, 10 + d, 10], [10 + 2 * d, 10, 10 + d]] - >>> dimer = Atoms("Si2O7", positions=positions, cell=[30, 30, 30], pbc=True) - >>> groups = classify_vibrational_groups(dimer, cutoff=2.0, former_types=[14]) - >>> groups["element"]["Si"].tolist(), groups["oxygen"]["O_BO"].tolist(), groups["qn"]["Si_Q1"].tolist() - ([0, 1], [2], [0, 1]) - - ``` - """ - n_atoms = len(structure) - if "id" in structure.arrays: - atom_ids = structure.arrays["id"].astype(np.int64) - else: - atom_ids = np.arange(1, n_atoms + 1, dtype=np.int64) - if len(np.unique(atom_ids)) != n_atoms: - msg = "The 'id' array contains duplicate atom IDs." - raise ValueError(msg) - id_to_position = {int(atom_id): position for position, atom_id in enumerate(atom_ids)} - - symbols = np.array(structure.get_chemical_symbols()) - groups: dict[str, dict[str, np.ndarray]] = { - "element": {str(sym): np.flatnonzero(symbols == sym).astype(np.int64) for sym in sorted(set(symbols))}, - "oxygen": {}, - "qn": {}, - } - atomic_numbers = structure.get_atomic_numbers() - if o_type not in atomic_numbers: - return groups - - unique_z = np.unique(atomic_numbers) - type_map, network_formers, _modifiers, _oxygen_present = _classify_elements(unique_z) - if former_types is None: - former_types = _network_former_types(type_map, network_formers) - if not former_types: - groups["oxygen"] = {"O_free": np.flatnonzero(atomic_numbers == o_type).astype(np.int64)} - return groups - if cutoff is None: - r, rdfs, _cumcn = compute_rdf(structure, r_max=10.0, n_bins=500) - cutoff_map = _build_cutoff_map(unique_z, type_map, former_types, [o_type], r, rdfs) - cutoff = _former_oxygen_pair_cutoffs(former_types, o_type, type_map, cutoff_map) - - _total_qn, _partial_qn, oxygen_classes = compute_qn_and_classify(structure, cutoff, former_types, o_type) - qn_per_atom = compute_qn_per_atom(structure, cutoff, former_types, o_type) - id_to_symbol = {int(atom_id): str(sym) for atom_id, sym in zip(atom_ids, symbols, strict=True)} - groups["oxygen"] = _positions_by_label({aid: f"O_{cls}" for aid, cls in oxygen_classes.items()}, id_to_position) - groups["qn"] = _positions_by_label( - {aid: f"{id_to_symbol[aid]}_Q{n}" for aid, n in qn_per_atom.items()}, id_to_position - ) - return groups - - -VdosNormalization = Literal["unit", "3N", "none"] -VdosWindow = Literal["hann", "hamming", "blackmanharris"] | tuple[Literal["gaussian"], float] | None -VacfNormalization = Literal["unit", "none"] - -# Target size of one chunk of velocities; the complex spectrum of a chunk is about the same size. -_CHUNK_BYTES = 64 * 2**20 -_VELOCITY_NDIM = 3 # (n_frames, n_atoms, 3) -_N_COMPONENTS = 3 -_MIN_FRAMES = 2 -# Internal (centre-of-mass-free) kinetic sum at or below this fraction of the uncentred one counts as no internal -# motion. It sits well above the rounding noise of removing the centre of mass from a uniform translation. -_ZERO_SPECTRUM_RTOL = 1e-10 -_WINDOWS = ("hann", "hamming", "blackmanharris") -_GAUSSIAN_LEN = 2 # ("gaussian", std) - - -def _atoms_per_chunk(n_frames: int, itemsize: int) -> int: - return max(1, _CHUNK_BYTES // (n_frames * _N_COMPONENTS * itemsize)) - - -def _validate_trajectory(velocities: NDArray, masses: NDArray, dt_fs: float) -> tuple[NDArray, NDArray[np.float64]]: - velocities = np.asarray(velocities) - masses = np.asarray(masses, dtype=np.float64) - if velocities.ndim != _VELOCITY_NDIM or velocities.shape[2] != _N_COMPONENTS or velocities.shape[1] == 0: - msg = f"velocities must have shape (n_frames, n_atoms, 3) with n_atoms >= 1, got {velocities.shape}." - raise ValueError(msg) - n_frames, n_atoms, _ = velocities.shape - if masses.shape != (n_atoms,): - msg = f"masses must have shape ({n_atoms},) to match velocities, got {masses.shape}." - raise ValueError(msg) - if n_frames < _MIN_FRAMES: - msg = f"At least 2 frames are needed, got {n_frames}." - raise ValueError(msg) - if not np.isfinite(dt_fs) or dt_fs <= 0: - msg = f"dt_fs must be positive and finite, got {dt_fs}." - raise ValueError(msg) - if not np.all(np.isfinite(masses) & (masses > 0)): - msg = "All masses must be positive and finite." - raise ValueError(msg) - return velocities, masses - - -def _validate_window(window: object) -> None: - gaussian = ( - isinstance(window, tuple) - and len(window) == _GAUSSIAN_LEN - and window[0] == "gaussian" - and isinstance(window[1], int | float | np.integer | np.floating) - and not isinstance(window[1], bool) - and np.isfinite(window[1]) - and window[1] > 0 - ) - if not (gaussian or window is None or (isinstance(window, str) and window in _WINDOWS)): - msg = ( - f"Unknown window {window!r}; allowed values are 'hann', 'hamming', 'blackmanharris', " - "('gaussian', std) with std > 0 in frames, and None." - ) - raise ValueError(msg) - - -def _validate_vdos_inputs( - velocities: NDArray, masses: NDArray, dt_fs: float, normalization: str, window: object -) -> tuple[NDArray, NDArray[np.float64]]: - velocities, masses = _validate_trajectory(velocities, masses, dt_fs) - if normalization not in ("unit", "3N", "none"): - msg = f"Unknown normalization {normalization!r}; allowed values are 'unit', '3N' and 'none'." - raise ValueError(msg) - _validate_window(window) - return velocities, masses - - -def _validate_selection(indices: NDArray, n_atoms: int, name: str) -> NDArray[np.intp]: - selection = np.asarray(indices) - if selection.ndim != 1 or selection.size == 0 or not np.issubdtype(selection.dtype, np.integer): - msg = f"{name} must be a non-empty 1-D array of integer atom positions." - raise ValueError(msg) - if selection.min() < 0 or selection.max() >= n_atoms: - msg = f"{name} contains positions outside [0, {n_atoms})." - raise ValueError(msg) - if np.unique(selection).size != selection.size: - msg = f"{name} contains duplicate positions." - raise ValueError(msg) - return selection.astype(np.intp) - - -def _trajectory_statistics( - velocities: NDArray, masses: NDArray[np.float64], weights: NDArray[np.float64] | None, *, remove_com: bool -) -> tuple[NDArray[np.float64] | None, float, float]: - """One read of all atoms: centre-of-mass velocity per frame and the trapezoid integral of the total spectrum. - - The integral of sum_i m_i |rfft(w v_i)|^2 over the rfft grid follows from Parseval's theorem without any FFT: - (dnu / 2) * (n_frames * K - K_top), with K = sum_t w_t^2 sum_i m_i |v_i(t)|^2 and K_top the mass-weighted power - of the last frequency bin of the windowed signal, which only enters for an odd number of frames. ``weights=None`` - means w = 1. With centre-of-mass removal both sums are reduced by the centre-of-mass term, since - sum_i m_i (v_i - v_com) = 0. Non-finite velocities make the unwindowed sum non-finite, so the finiteness check - costs nothing extra; the finiteness and zero-spectrum checks use the unwindowed sums. - - Returns: - The centre-of-mass velocity ``(n_frames, 3)`` (``None`` without removal), the integral divided by dnu / 2, - and the unwindowed sum_t sum_i m_i |v_i(t) - v_com(t)|^2 (``v_com = 0`` without removal). - """ - n_frames, n_atoms, _ = velocities.shape - chunk = _atoms_per_chunk(n_frames, velocities.itemsize) - odd = n_frames % 2 == 1 - phase = np.arange(n_frames) * (2 * np.pi * ((n_frames - 1) // 2) / n_frames) - cos_t, sin_t = np.cos(phase), np.sin(phase) - if weights is not None: - cos_t, sin_t = cos_t * weights, sin_t * weights - kinetic = np.zeros(n_frames) # sum_i m_i |v_i(t)|^2 per frame - momentum = np.zeros((n_frames, _N_COMPONENTS)) - top_momentum = np.zeros((2, _N_COMPONENTS)) - raw_sq = 0.0 - top_sq = 0.0 - for start in range(0, n_atoms, chunk): - block = velocities[:, start : start + chunk] - block_masses = masses[start : start + chunk] - if weights is None: - block_sq = float(np.einsum("tia,tia->i", block, block, dtype=np.float64) @ block_masses) - else: - frame_sq = np.einsum("tia,tia->ti", block, block, dtype=np.float64) @ block_masses - block_sq = float(frame_sq.sum()) - kinetic += frame_sq - if not np.isfinite(block_sq): - msg = "velocities contain NaN or inf (or values too large to square)." - raise ValueError(msg) - raw_sq += block_sq - momentum += np.einsum("tia,i->ta", block, block_masses, dtype=np.float64) - if odd: - top = np.stack( - [ - np.einsum("t,tia->ia", cos_t, block, dtype=np.float64), - np.einsum("t,tia->ia", sin_t, block, dtype=np.float64), - ] - ) - top_sq += float(np.einsum("cia,cia,i->", top, top, block_masses)) - top_momentum += np.einsum("cia,i->ca", top, block_masses) - if not raw_sq > 0: - msg = "The velocity spectrum is zero (all velocities are zero)." - raise ValueError(msg) - window_sq = None if weights is None else weights**2 - if not remove_com: - weighted_sq = raw_sq if window_sq is None else float(window_sq @ kinetic) - return None, n_frames * weighted_sq - top_sq, raw_sq - total_mass = masses.sum() - com_velocity = momentum / total_mass - centred_sq = raw_sq - total_mass * float(np.sum(com_velocity**2)) - if centred_sq <= _ZERO_SPECTRUM_RTOL * raw_sq: - msg = "The velocity spectrum is zero after removing the centre-of-mass velocity (no internal motion)." - raise ValueError(msg) - weighted_sq = centred_sq - if window_sq is not None: - weighted_sq = float(window_sq @ kinetic) - total_mass * float(window_sq @ np.sum(com_velocity**2, axis=1)) - return com_velocity, n_frames * weighted_sq - (top_sq - float(np.sum(top_momentum**2)) / total_mass), centred_sq - - -def _accumulate_power( - velocities: NDArray, - masses: NDArray[np.float64], - com_velocity: NDArray[np.float64] | None, - membership: NDArray, - weights: NDArray[np.float64] | None, - n_fft: int | None = None, -) -> NDArray[np.float64]: - """Sum m_i * sum_a |rfft(w * (v_ia - v_com,a))|^2 over the atoms of each column of ``membership`` (n_atoms, n_cols). - - Only atoms that belong to at least one column are transformed. A contiguous range of atoms is sliced as a view; - other selections are gathered chunk by chunk. float32 velocities are transformed in single precision (complex64) - and float64 or other input in double precision, with the same forward, unnormalised DFT as ``np.fft.rfft``; - per-atom powers are combined in float64. The window ``weights`` (``None`` for none) is applied per chunk in the - working precision, never in place on a view of the input. ``n_fft`` zero-pads each signal to that length before - the transform (``None``: no padding), and chunks are sized for the padded length. - """ - n_frames = velocities.shape[0] - n_transform = n_frames if n_fft is None else n_fft - work = np.float32 if velocities.dtype == np.float32 else np.float64 - needed = np.flatnonzero(membership.any(axis=1)) - contiguous = needed[-1] - needed[0] + 1 == needed.size - chunk = _atoms_per_chunk(n_transform, np.dtype(work).itemsize) - com_work = None if com_velocity is None else com_velocity.astype(work)[:, None, :] - window_work = None if weights is None else weights.astype(work)[:, None, None] - power = np.zeros((n_transform // 2 + 1, membership.shape[1])) - for start in range(0, needed.size, chunk): - atoms = needed[start : start + chunk] - is_view = False - if contiguous: - block = velocities[:, atoms[0] : atoms[-1] + 1] - if com_work is not None: - block = np.subtract(block, com_work, dtype=work) - elif block.dtype != work: - block = block.astype(work) - else: - is_view = True - else: - block = velocities[:, atoms].astype(work, copy=False) - if com_work is not None: - block -= com_work - if window_work is not None: - if is_view: - block = block * window_work - else: - block *= window_work - # scipy.fft transforms float32 natively; np.fft computes in double internally and needs ~3x the memory. - spectrum = np.ascontiguousarray(scipy.fft.rfft(block, n=n_fft, axis=0)) - del block - # |z|^2 = Re(z)^2 + Im(z)^2 summed over x, y, z through a real view, without full-size temporaries. - parts = spectrum.view(work).reshape(spectrum.shape[0], spectrum.shape[1], 2 * _N_COMPONENTS) - atom_power = np.einsum("fik,fik->fi", parts, parts) - del spectrum, parts - power += atom_power @ (masses[atoms, None] * membership[atoms]) - return power - - -def _membership(selections: dict[str, NDArray] | None, n_atoms: int) -> NDArray[np.float64]: - """Membership matrix (n_atoms, n_cols): one column of ones for ``None``, else one 0/1 column per selection.""" - if selections is None: - return np.ones((n_atoms, 1)) - membership = np.zeros((n_atoms, len(selections))) - for column, (name, indices) in enumerate(selections.items()): - membership[_validate_selection(indices, n_atoms, name), column] = 1.0 - return membership - - -def _group_selections(groups: dict[str, dict[str, NDArray]]) -> tuple[list[tuple[str, str]], dict[str, NDArray]]: - """Flatten ``{grouping: {label: indices}}`` into ordered keys and selections named after each group.""" - keys = [(grouping, label) for grouping, labels in groups.items() for label in labels] - if not keys: - msg = "groups contains no labels." - raise ValueError(msg) - return keys, {f"groups[{g!r}][{label!r}]": groups[g][label] for g, label in keys} - - -def _columns_by_group( - groups: dict[str, dict[str, NDArray]], keys: list[tuple[str, str]], columns: NDArray[np.float64] -) -> dict[str, dict[str, NDArray[np.float64]]]: - """Split the result columns back into the ``{grouping: {label: array}}`` layout of ``groups``.""" - partial: dict[str, dict[str, NDArray[np.float64]]] = {grouping: {} for grouping in groups} - for column, (grouping, label) in enumerate(keys): - partial[grouping][label] = np.ascontiguousarray(columns[:, column]) - return partial - - -def _vdos_columns( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - selections: dict[str, NDArray] | None, - normalization: str, - *, - remove_com: bool, - window: VdosWindow, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: - """Shared implementation: VDOS of the whole system (``selections=None``) or of each named selection, as columns.""" - velocities, masses = _validate_vdos_inputs(velocities, masses, dt_fs, normalization, window) - n_frames, n_atoms, _ = velocities.shape - membership = _membership(selections, n_atoms) - # get_window builds the periodic (DFT-even) form of each window. - weights = None if window is None else np.asarray(scipy.signal.get_window(window, n_frames), dtype=np.float64) - com_velocity, parseval_sum, _ = _trajectory_statistics(velocities, masses, weights, remove_com=remove_com) - power = _accumulate_power(velocities, masses, com_velocity, membership, weights) - - dt_ps = dt_fs * 1e-3 - frequencies_thz = np.asarray(np.fft.rfftfreq(n_frames, d=dt_ps), dtype=np.float64) - if normalization == "none": - if weights is None: - return frequencies_thz, power * (2 * dt_ps / n_frames) - return frequencies_thz, power * (2 * dt_ps / float(np.sum(weights**2))) - reference_integral = 0.5 * float(frequencies_thz[1]) * parseval_sum - scale = 1.0 if normalization == "unit" else 3.0 * n_atoms - return frequencies_thz, power * (scale / reference_integral) - - -def compute_vdos_from_velocities( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - *, - indices: NDArray | None = None, - normalization: VdosNormalization = "unit", - remove_com: bool = True, - window: VdosWindow = None, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: - r"""Compute the vibrational density of states from an MD velocity trajectory. - - The VDOS is the mass-weighted velocity power spectrum - - $$g(\nu_k) \propto \sum_{i} m_i \sum_{\alpha} |V_{i\alpha}(\nu_k)|^2, - \quad V_{i\alpha}(\nu_k) = \sum_{t=0}^{N-1} v_{i\alpha}(t)\, e^{-2\pi \mathrm{i} k t / N},$$ - - the unnormalised forward DFT along time (the ``np.fft.rfft`` convention; computed with ``scipy.fft.rfft``), on the - one-sided grid - $\nu_k = k / (N \Delta t)$, $k = 0, \dots, \lfloor N/2 \rfloor$, in THz. The frequency resolution is - $1 / (N \Delta t)$ and the highest frequency is the Nyquist frequency $1 / (2 \Delta t)$. No zero padding or - per-atom mean subtraction is applied, and no window unless ``window`` is set. - - With a window, the (centre-of-mass-free) velocities are multiplied by $w_t$, $t = 0, \dots, N-1$, before the - transform. All windows are periodic (``scipy.signal.get_window(window, N)``): - - - ``"hann"``: $w_t = \tfrac{1}{2}\left(1 - \cos(2\pi t / N)\right)$. - - ``"hamming"``: $w_t = 0.54 - 0.46 \cos(2\pi t / N)$. Lower first sidelobe than Hann, but the edges are not - zero (0.08), so leakage far from a peak decays more slowly. - - ``"blackmanharris"``: the 4-term Blackman-Harris window $w_t = \sum_{j=0}^{3} (-1)^j a_j \cos(2\pi j t / N)$, - $a = (0.35875, 0.48829, 0.14128, 0.01168)$, with sidelobes below $-92$ dB. - - ``("gaussian", std)``: $w_t = \exp\left(-\tfrac{1}{2}\left((t - N/2) / \sigma\right)^2\right)$ with - $\sigma$ = ``std`` in frames, so its width relative to the block depends on $N$. It is truncated at the edges - (edge value $e^{-8} \approx 3 \times 10^{-4}$ for $\sigma = N/8$). A narrow window ($\sigma \ll N/8$) widens - every peak and can spread power further than no window at all. - - A window suppresses spectral leakage from the finite trajectory length at the cost of resolution. The effective - resolution is $\mathrm{ENBW} / (N \Delta t)$ with the equivalent noise bandwidth - $\mathrm{ENBW} = N \sum_t w_t^2 / (\sum_t w_t)^2$ bins: 1.5 (Hann), 1.36 (Hamming), 2.0 (Blackman-Harris) and - about $N / (2 \sqrt{\pi} \sigma)$ (Gaussian, $\sigma \ll N$). For 10 ps blocks that is 0.15, 0.14 and 0.20 THz, - and 0.23 THz for a Gaussian with $\sigma = N/8$. With ``window=None`` (default) the full $1 / (N \Delta t)$ - resolution is kept, and a peak between grid points leaks into distant bins. - - With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, - $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every - frame before the transform, also when ``indices`` selects a subset. With ``remove_com=False`` the velocities are - transformed as given, and any centre-of-mass drift appears at and near zero frequency. - - Normalisation (all integrals are trapezoidal over the returned grid): - - - ``"unit"`` (default): the total VDOS integrates to 1 (units 1/THz). - - ``"3N"``: the total VDOS integrates to ``3 * n_atoms`` (the number of degrees of freedom, including the 3 - removed with the centre of mass). - - ``"none"``: the power spectral density $S(\nu_k) = (2 \Delta t / N) \sum_i m_i \sum_\alpha |V_{i\alpha}|^2$ in - amu (velocity unit)$^2$ ps. For an even number of frames its integral equals the time average of - $\sum_i m_i |\mathbf{v}_i|^2$ (twice the mean kinetic energy) exactly, by Parseval's theorem; for an odd number - it is lower by half the last bin. With a window, $V_{i\alpha}$ is the transform of the windowed velocities and - the prefactor is $2 \Delta t / \sum_t w_t^2$ instead of $2 \Delta t / N$; the integral is then the - $w^2$-weighted time average $\sum_t w_t^2 \sum_i m_i |\mathbf{v}_i(t)|^2 / \sum_t w_t^2$ (exact for an even - number of frames). - - With a window, ``"unit"`` and ``"3N"`` are applied to the windowed total VDOS, which still integrates to exactly 1 - and ``3 * n_atoms``. - - A partial VDOS (``indices`` given) is the same spectrum summed over the selected atoms only and is scaled by the - total VDOS's normalisation, so partials over disjoint selections add up to the total. Its integral is the - selection's share of the total kinetic energy, which is close to its share of atoms by equipartition: about - ``3 * len(indices)`` for ``"3N"``. The integral of the total spectrum comes from Parseval's theorem in the time - domain, so a partial only transforms the selected atoms. Use :func:`compute_partial_vdos` for many groups. - - Memory: the trajectory is read twice in chunks of atoms (about 64 MB each), once for the centre-of-mass velocity, - the normalisation and the finiteness check, and once for the transforms. Besides the input, peak memory is about - two chunks. float32 input is transformed in single precision (no float64 copy); the spectrum is accumulated in - float64. The input is never modified, and it may be a read-only ``np.memmap`` (e.g. ``np.load(path, - mmap_mode="r")``), in which case only the chunks being processed are read from disk. - - Args: - velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` and ``"3N"`` remove the - scale. - masses: Atomic masses of shape ``(n_atoms,)`` in amu. - dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). - indices: 0-based positions of the atoms in a partial VDOS, e.g. one entry of - :func:`classify_vibrational_groups`. ``None`` (default) gives the total VDOS. - normalization: ``"unit"``, ``"3N"`` or ``"none"``, see above. - remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. - window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames, - or ``None`` (default) for no window, see above. - - Returns: - A tuple ``(frequencies_thz, vdos)`` of float64 arrays of length ``n_frames // 2 + 1``: the frequencies in THz - from ``np.fft.rfftfreq(n_frames, d=dt_fs * 1e-3)`` and the VDOS in 1/THz (``"unit"``, ``"3N"``) or the power - spectral density (``"none"``). - - Raises: - ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not - have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs <= 0``, any mass is not positive and - finite, ``velocities`` contains NaN or inf, ``normalization`` or ``window`` is unknown, ``indices`` is - empty, not 1-D integer, out of range or has duplicates, or the spectrum vanishes (all velocities zero, or - no motion left after centre-of-mass removal, e.g. every atom moves with the same velocity). - - Example: - ```pycon - >>> from amorphouspy import get_atomic_mass - >>> dt_fs, n_frames = 5.0, 2000 - >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3 - >>> velocities = np.zeros((n_frames, 2, 3)) - >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps) - >>> velocities[:, 1, 0] = -velocities[:, 0, 0] - >>> masses = np.full(2, get_atomic_mass("Si")) - >>> frequencies_thz, vdos = compute_vdos_from_velocities(velocities, masses, dt_fs) - >>> float(frequencies_thz[np.argmax(vdos)]) - 10.0 - >>> round(float(np.trapezoid(vdos, frequencies_thz)), 6) - 1.0 - >>> _, partial = compute_vdos_from_velocities( - ... velocities, masses, dt_fs, indices=np.array([0]), normalization="3N" - ... ) - >>> round(float(np.trapezoid(partial, frequencies_thz)), 6) - 3.0 - >>> _, vdos_hann = compute_vdos_from_velocities(velocities, masses, dt_fs, window="hann") - >>> float(frequencies_thz[np.argmax(vdos_hann)]), round(float(np.trapezoid(vdos_hann, frequencies_thz)), 6) - (10.0, 1.0) - - ``` - """ - selections = None if indices is None else {"indices": indices} - frequencies_thz, columns = _vdos_columns( - velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window - ) - return frequencies_thz, np.ascontiguousarray(columns[:, 0]) - - -def compute_partial_vdos( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - groups: dict[str, dict[str, NDArray]], - *, - normalization: VdosNormalization = "unit", - remove_com: bool = True, - window: VdosWindow = None, -) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]: - """Compute partial VDOS for many atom groups with one transform per atom. - - Each partial is exactly what :func:`compute_vdos_from_velocities` returns with ``indices`` set to the group - (same centre-of-mass treatment, window, normalisation and units), but every atom is transformed once, however many - groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`: classify once, then - reuse the indices for any number of trajectories or blocks. Within one grouping that covers every atom once (e.g. - ``"element"``), the partials add up to the total VDOS computed with the same window and normalisation. - - Args: - velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit. - masses: Atomic masses of shape ``(n_atoms,)`` in amu. - dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). - groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of - :func:`classify_vibrational_groups`. Atoms may appear in several groupings. - normalization: ``"unit"``, ``"3N"`` or ``"none"``, as in :func:`compute_vdos_from_velocities`. - remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. - window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` or ``None`` (default), as in - :func:`compute_vdos_from_velocities`. - - Returns: - A tuple ``(frequencies_thz, partial)``: the frequencies in THz and ``{grouping: {label: vdos}}`` with the - same keys as ``groups``, each a float64 array of length ``n_frames // 2 + 1``. - - Raises: - ValueError: As :func:`compute_vdos_from_velocities` (including an unknown ``window``), for any group's - indices, or if ``groups`` has no labels. - - Example: - ```pycon - >>> rng = np.random.default_rng(0) - >>> velocities = rng.normal(size=(100, 3, 3)) - >>> masses = np.array([28.085, 15.999, 15.999]) - >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}} - >>> frequencies_thz, partial = compute_partial_vdos(velocities, masses, 5.0, groups) - >>> _, total = compute_vdos_from_velocities(velocities, masses, 5.0) - >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total)) - True - - ``` - """ - keys, selections = _group_selections(groups) - frequencies_thz, columns = _vdos_columns( - velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window - ) - return frequencies_thz, _columns_by_group(groups, keys, columns) - - -def _vacf_columns( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - selections: dict[str, NDArray] | None, - max_lag_frames: int | None, - normalization: str, - *, - remove_com: bool, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: - """Shared implementation: VACF of the whole system (``selections=None``) or of each named selection, as columns.""" - velocities, masses = _validate_trajectory(velocities, masses, dt_fs) - if normalization not in ("unit", "none"): - msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and 'none'." - raise ValueError(msg) - n_frames, n_atoms, _ = velocities.shape - if max_lag_frames is None: - max_lag_frames = n_frames // 2 - elif not (isinstance(max_lag_frames, int | np.integer) and 1 <= max_lag_frames <= n_frames - 1): - msg = f"max_lag_frames must be an integer in [1, {n_frames - 1}], got {max_lag_frames!r}." - raise ValueError(msg) - membership = _membership(selections, n_atoms) - com_velocity, _, kinetic_sum = _trajectory_statistics(velocities, masses, None, remove_com=remove_com) - # Zero padding to 2N makes the correlation linear. The inverse transform is linear, so it is applied once to the - # mass-weighted power of each column instead of once per atom. - power = _accumulate_power(velocities, masses, com_velocity, membership, None, n_fft=2 * n_frames) - n_lags = max_lag_frames + 1 - origins = n_frames - np.arange(n_lags) - vacf = scipy.fft.irfft(power, n=2 * n_frames, axis=0)[:n_lags] / origins[:, None] - if normalization == "unit": - vacf /= kinetic_sum / n_frames - lag_ps = np.arange(n_lags) * dt_fs * 1e-3 - return lag_ps, vacf - - -def compute_vacf_from_velocities( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - *, - indices: NDArray | None = None, - max_lag_frames: int | None = None, - normalization: VacfNormalization = "unit", - remove_com: bool = True, -) -> tuple[NDArray[np.float64], NDArray[np.float64]]: - r"""Compute the mass-weighted velocity autocorrelation function (VACF) from an MD velocity trajectory. - - The VACF is - - $$C(t_k) = \frac{\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle} - {\sum_i m_i \langle |\mathbf{v}_i|^2 \rangle}, \quad t_k = k \Delta t,$$ - - where $\langle \cdot \rangle$ is the average over all time origins with the unbiased estimator: lag $k$ averages - the $N - k$ available products, - - $$\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle - = \frac{1}{N - k} \sum_{t=0}^{N-1-k} \sum_i m_i\, \mathbf{v}_i(t) \cdot \mathbf{v}_i(t + k),$$ - - for $k = 0, \dots,$ ``max_lag_frames``, with $N$ frames. Fewer origins enter at larger lags, so the statistical - noise grows with the lag; the default ``max_lag_frames = N // 2`` keeps at least $N/2$ origins at every lag. - - The sums over origins are computed with FFTs (``scipy.fft``). Every velocity component of every atom is - zero-padded to $2N$ frames before the forward transform, so the correlation is linear, not circular (no - wrap-around from the end of the trajectory to its start). The squared transforms are weighted by the masses and - summed over the atoms, and the sum is transformed back once, which is exact because the inverse transform is - linear. No window is applied: the VACF always uses the unwindowed velocities. - - With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, - $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every - frame first, also when ``indices`` selects a subset, exactly as in :func:`compute_vdos_from_velocities`. With - ``remove_com=False`` the velocities are used as given; a constant centre-of-mass velocity $\mathbf{V}$ then adds - $\sum_i m_i |\mathbf{V}|^2$ to the unnormalised total VACF at every lag. - - Normalisation: - - - ``"unit"`` (default): divided by the total VACF at zero lag, the time average of - $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (of $\sum_i m_i |\mathbf{v}_i|^2$ with - ``remove_com=False``), so the total $C(0) = 1$ to rounding. Dimensionless. - - ``"none"``: the numerator $\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle$ in amu - (velocity unit)$^2$. Its value at zero lag is the time average of - $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (twice the mean internal kinetic energy). - - A partial VACF (``indices`` given) sums the numerator over the selected atoms only and, with ``"unit"``, is divided - by the same denominator as the total, so partials over disjoint selections add up to the total VACF, and a - partial's $C(0)$ is the selection's share of the centred kinetic sum. The denominator comes from the - statistics read over all atoms, so a partial only transforms the selected atoms. Use - :func:`compute_partial_vacf` for many groups. - - Relation to the VDOS: by the Wiener-Khinchin theorem the VDOS is the Fourier transform of the unnormalised VACF. - For a finite trajectory, the ``"none"`` spectral density of :func:`compute_vdos_from_velocities` (no window, same - ``remove_com``) on its grid $\nu_j = j / (N \Delta t)$ is exactly - - $$S(\nu_j) = 2 \Delta t \left[C(0) + 2 \sum_{k=1}^{N-1} \left(1 - \frac{k}{N}\right) C(t_k) - \cos\left(\frac{2 \pi j k}{N}\right)\right],$$ - - with $C$ the ``"none"`` VACF up to ``max_lag_frames = N - 1`` and $\Delta t$ in ps: the transform over all lags - with a triangular weight. The library computes the VDOS directly from the velocity spectrum, not from this - function; transforming a VACF truncated at a shorter lag gives a lower-resolution spectrum. - - Memory: as in :func:`compute_vdos_from_velocities`, the trajectory is read twice in chunks of atoms, once for the - centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms, with chunks - sized for the padded length $2N$. float32 input is transformed in single precision (no float64 copy); the - correlation is accumulated in float64. The input is never modified, and it may be a read-only ``np.memmap``. - - Args: - velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` removes the scale. - masses: Atomic masses of shape ``(n_atoms,)`` in amu. - dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). - indices: 0-based positions of the atoms in a partial VACF, e.g. one entry of - :func:`classify_vibrational_groups`. ``None`` (default) gives the total VACF. - max_lag_frames: Largest lag in frames, from 1 to ``n_frames - 1``. ``None`` (default) means - ``n_frames // 2``. - normalization: ``"unit"`` or ``"none"``, see above. - remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. - - Returns: - A tuple ``(lag_ps, vacf)`` of float64 arrays of length ``max_lag_frames + 1``: the lags - ``np.arange(max_lag_frames + 1) * dt_fs * 1e-3`` in ps and the VACF (dimensionless for ``"unit"``, amu - (velocity unit)$^2$ for ``"none"``). - - Raises: - ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not - have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs <= 0``, any mass is not positive and - finite, ``velocities`` contains NaN or inf, ``normalization`` is unknown, ``max_lag_frames`` is not an - integer from 1 to ``n_frames - 1``, ``indices`` is empty, not 1-D integer, out of range or has - duplicates, or there is no motion (all velocities zero, or none left after centre-of-mass removal). - - Example: - ```pycon - >>> from amorphouspy import get_atomic_mass - >>> dt_fs, n_frames = 5.0, 2000 - >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3 - >>> velocities = np.zeros((n_frames, 2, 3)) - >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps) - >>> velocities[:, 1, 0] = -velocities[:, 0, 0] - >>> masses = np.full(2, get_atomic_mass("Si")) - >>> lag_ps, vacf = compute_vacf_from_velocities(velocities, masses, dt_fs) - >>> lag_ps.shape, round(float(lag_ps[10]), 6) - ((1001,), 0.05) - >>> round(float(vacf[0]), 6), round(float(vacf[10]), 6) # half a 10 THz period after 0.05 ps - (1.0, -1.0) - >>> _, partial = compute_vacf_from_velocities(velocities, masses, dt_fs, indices=np.array([0])) - >>> round(float(partial[0]), 6) - 0.5 - - ``` - """ - selections = None if indices is None else {"indices": indices} - lag_ps, columns = _vacf_columns( - velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com - ) - return lag_ps, np.ascontiguousarray(columns[:, 0]) - - -def compute_partial_vacf( - velocities: NDArray, - masses: NDArray, - dt_fs: float, - groups: dict[str, dict[str, NDArray]], - *, - max_lag_frames: int | None = None, - normalization: VacfNormalization = "unit", - remove_com: bool = True, -) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]: - """Compute partial VACFs for many atom groups with one transform per atom. - - Each partial is exactly what :func:`compute_vacf_from_velocities` returns with ``indices`` set to the group - (same centre-of-mass treatment, lags, normalisation and units), but every atom is transformed once, however many - groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`. Within one - grouping that covers every atom once (e.g. ``"element"``), the partials add up to the total VACF. - - Args: - velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit. - masses: Atomic masses of shape ``(n_atoms,)`` in amu. - dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). - groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of - :func:`classify_vibrational_groups`. Atoms may appear in several groupings. - max_lag_frames: Largest lag in frames, as in :func:`compute_vacf_from_velocities`. - normalization: ``"unit"`` or ``"none"``, as in :func:`compute_vacf_from_velocities`. - remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. - - Returns: - A tuple ``(lag_ps, partial)``: the lags in ps and ``{grouping: {label: vacf}}`` with the same keys as - ``groups``, each a float64 array of length ``max_lag_frames + 1``. - - Raises: - ValueError: As :func:`compute_vacf_from_velocities`, for any group's indices, or if ``groups`` has no labels. - - Example: - ```pycon - >>> rng = np.random.default_rng(0) - >>> velocities = rng.normal(size=(100, 3, 3)) - >>> masses = np.array([28.085, 15.999, 15.999]) - >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}} - >>> lag_ps, partial = compute_partial_vacf(velocities, masses, 5.0, groups) - >>> _, total = compute_vacf_from_velocities(velocities, masses, 5.0) - >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total)) - True - - ``` - """ - keys, selections = _group_selections(groups) - lag_ps, columns = _vacf_columns( - velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com - ) - return lag_ps, _columns_by_group(groups, keys, columns) - - -# 1 GPa / (1 g/cm^3) = 1e9 Pa / 1e3 kg/m^3, in m^2/s^2. -_GPA_PER_G_CM3_TO_M2_S2 = 1e6 - - -def compute_debye_level( - structure: "Atoms", - bulk_modulus_gpa: float, - shear_modulus_gpa: float, - *, - normalization: VdosNormalization = "unit", -) -> dict[str, float]: - r"""Compute the Debye level of the reduced VDOS from elastic moduli and the density of a structure. - - The isotropic elastic continuum with bulk modulus $B$, shear modulus $G$ and mass density $\rho$ has the - longitudinal and transverse sound velocities - - $$v_L = \sqrt{\frac{B + 4G/3}{\rho}}, \quad v_T = \sqrt{\frac{G}{\rho}},$$ - - in m/s for $B$, $G$ in GPa and $\rho$ in g/cm$^3$ (1 GPa / (1 g/cm$^3$) = $10^6$ m$^2$/s$^2$). With the number - density $n$, the Debye frequency and temperature are - - $$\nu_D^3 = \frac{9 n}{4 \pi \left(1 / v_L^3 + 2 / v_T^3\right)}, \quad \theta_D = \frac{h \nu_D}{k_B},$$ - - and the Debye VDOS $g_D(\nu) = 3 \nu^2 / \nu_D^3$ ($\nu \le \nu_D$, normalised to 1) gives the Debye level - $g_D(\nu) / \nu^2 = 3 / \nu_D^3$ in THz$^{-3}$, the low-frequency limit of the reduced VDOS of an isotropic solid. - For ``"3N"`` the level is $3N$ times larger, matching a VDOS that integrates to $3N$. - - The moduli are taken as given: no fit of the VDOS is made, so without moduli there is no Debye level. Use moduli of - the same model and state as the VDOS, e.g. ``elastic_simulation(...)["moduli"]["B"]`` and ``["G"]``, which are in - GPa. Only the masses (``structure.get_masses()``, in amu) and the cell volume enter $\rho$ and $n$; the positions - are not used. - - The lowest frequency the periodic box supports is $\nu_\mathrm{min} = v_T / L_\mathrm{max}$, the transverse - acoustic mode whose wavelength is the largest perpendicular cell height $L_\mathrm{max}$ (the edge $L$ of a cubic - box). The box has no acoustic modes below it, so the reduced VDOS there does not represent the bulk glass. Taking - $L_\mathrm{max}$ as the longest wavelength is exact for orthogonal boxes and assumes a cell that is not strongly - skewed otherwise. - - Args: - structure: Periodic structure as an ASE object, with a 3-D cell of positive volume. - bulk_modulus_gpa: Bulk modulus $B$ in GPa. - shear_modulus_gpa: Shear modulus $G$ in GPa. - normalization: ``"unit"`` (default) or ``"3N"``, the normalisation of the VDOS the level is compared with, as - in :func:`compute_vdos_from_velocities`. ``"none"`` is rejected: a power spectral density has no Debye - level. - - Returns: - A dict of floats: - ``"longitudinal_velocity_m_s"`` and ``"transverse_velocity_m_s"``: $v_L$ and $v_T$ in m/s. - ``"debye_frequency_thz"``: $\nu_D$ in THz. - ``"debye_temperature_k"``: $\theta_D$ in K. - ``"debye_level_thz-3"``: $3 / \nu_D^3$ (``"unit"``) or $9N / \nu_D^3$ (``"3N"``) in THz$^{-3}$. - ``"lowest_box_frequency_thz"``: $\nu_\mathrm{min} = v_T / L_\mathrm{max}$ in THz. - ``"density_g_cm3"``: $\rho$ in g/cm$^3$. - ``"number_density_per_a3"``: $n$ in atoms/Å$^3$. - - Raises: - ValueError: If a modulus is not positive and finite, ``normalization`` is not ``"unit"`` or ``"3N"``, - ``structure`` has no atoms, is not periodic in all three directions, or its cell volume is not positive. - - Example: - ```pycon - >>> from ase import Atoms - >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3 - >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2) - >>> round(debye["density_g_cm3"], 3), round(debye["transverse_velocity_m_s"]) - (2.2, 3766) - >>> round(debye["debye_frequency_thz"], 2), round(debye["debye_temperature_k"]) - (10.4, 499) - >>> round(debye["lowest_box_frequency_thz"], 3) - 1.056 - - ``` - """ - for name, modulus in (("bulk_modulus_gpa", bulk_modulus_gpa), ("shear_modulus_gpa", shear_modulus_gpa)): - if not (np.isfinite(modulus) and modulus > 0): - msg = f"{name} must be positive and finite, got {modulus}." - raise ValueError(msg) - if normalization not in ("unit", "3N"): - msg = ( - f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N' " - "(a power spectral density has no Debye level)." - ) - raise ValueError(msg) - n_atoms = len(structure) - if n_atoms == 0: - msg = "structure contains no atoms." - raise ValueError(msg) - if not np.all(structure.pbc): - msg = "structure must be periodic in all three directions." - raise ValueError(msg) - volume_a3 = float(structure.cell.volume) - if not volume_a3 > 0: - msg = "structure must have a 3-D cell with positive volume." - raise ValueError(msg) - - # amu -> g and A^3 -> cm^3. - density_g_cm3 = float(structure.get_masses().sum()) * atomic_mass * 1e3 / (volume_a3 * 1e-24) - number_density_per_a3 = n_atoms / volume_a3 - longitudinal_modulus_gpa = bulk_modulus_gpa + 4 * shear_modulus_gpa / 3 - v_longitudinal = float(np.sqrt(longitudinal_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2)) - v_transverse = float(np.sqrt(shear_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2)) - # Number density in m^-3 and velocities in m/s give the Debye frequency in Hz. - debye_frequency_hz = ( - 9 * number_density_per_a3 * 1e30 / (4 * np.pi * (1 / v_longitudinal**3 + 2 / v_transverse**3)) - ) ** (1 / 3) - debye_frequency_thz = debye_frequency_hz * 1e-12 - scale = 1.0 if normalization == "unit" else 3.0 * n_atoms - largest_height_a = float(cell_perpendicular_heights(structure.cell.array).max()) - return { - "longitudinal_velocity_m_s": v_longitudinal, - "transverse_velocity_m_s": v_transverse, - "debye_frequency_thz": debye_frequency_thz, - "debye_temperature_k": h * debye_frequency_hz / Boltzmann, - "debye_level_thz-3": scale * 3 / debye_frequency_thz**3, - "lowest_box_frequency_thz": v_transverse / (largest_height_a * 1e-10) * 1e-12, - "density_g_cm3": density_g_cm3, - "number_density_per_a3": number_density_per_a3, - } - - -def compute_reduced_vdos( - frequencies_thz: NDArray, - vdos: NDArray, - *, - peak_range_thz: tuple[float, float] = (0.5, 5.0), - debye: dict[str, float] | None = None, -) -> dict[str, Any]: - r"""Compute the reduced VDOS $g(\nu) / \nu^2$, the boson-peak position and its height over the Debye level. - - The boson peak is the raw maximum of $g(\nu) / \nu^2$ within ``peak_range_thz``, with no smoothing or fit, so pass - a block-averaged VDOS (e.g. a Hann-windowed mean over blocks); the maximum of a single noisy spectrum is mostly - noise. The default range of 0.5 to 5 THz is a generic choice for oxide glasses (silica peaks near 1 THz); set it - for the system at hand. A maximum on the first or last bin of the range (``"peak_at_range_edge"``) means no peak - was found inside it, e.g. a reduced VDOS that rises steeply towards zero frequency. - - With ``debye`` (the output of :func:`compute_debye_level`), the peak height is also divided by the Debye level, and - every frequency below the lowest one the box supports is marked unreliable. The level is only compared, never - fitted: without ``debye`` none of these keys is returned. The VDOS and ``debye`` must use the same normalisation - (``"unit"`` or ``"3N"``). - - Any VDOS works, including a partial VDOS, but the Debye comparison is meaningful for the total VDOS only. - - Args: - frequencies_thz: Frequencies in THz, 1-D, non-negative and strictly increasing, e.g. from - :func:`compute_vdos_from_velocities`. - vdos: VDOS on ``frequencies_thz``, 1-D of the same length, in 1/THz. - peak_range_thz: ``(low, high)`` in THz, both ends included, in which the boson peak is searched. The - frequency 0 is never part of the range. - debye: The dict returned by :func:`compute_debye_level`, or ``None`` (default). - - Returns: - A dict with: - ``"reduced_vdos"``: $g(\nu) / \nu^2$ in THz$^{-3}$, a float64 array of the input length, NaN at - $\nu = 0$. - ``"boson_peak_thz"``: frequency of the maximum within ``peak_range_thz``, in THz. - ``"boson_peak_height"``: reduced VDOS at that frequency, in THz$^{-3}$. - ``"peak_at_range_edge"``: True if the maximum is on the first or last bin of the range. - With ``debye`` also: - ``"debye_level_thz-3"``: the Debye level from ``debye``. - ``"boson_peak_over_debye"``: ``boson_peak_height`` divided by the Debye level. - ``"reliable"``: boolean array, True where the frequency is at or above the lowest box frequency. - ``"peak_below_box_limit"``: True if the boson peak lies below the lowest box frequency. - - Raises: - ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length, contain NaN or inf, - a frequency is negative, the frequencies are not strictly increasing, ``peak_range_thz`` does not satisfy - ``low < high``, or the range contains no frequency above 0. - - Example: - ```pycon - >>> from ase import Atoms - >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3 - >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2) - >>> frequencies_thz = np.linspace(0.0, 10.0, 201) - >>> excess = 1 + np.exp(-0.5 * ((frequencies_thz - 1.2) / 0.4) ** 2) - >>> vdos = debye["debye_level_thz-3"] * frequencies_thz**2 * excess # Debye VDOS with an excess at 1.2 THz - >>> result = compute_reduced_vdos(frequencies_thz, vdos, debye=debye) - >>> round(result["boson_peak_thz"], 3), result["peak_at_range_edge"], round(result["boson_peak_over_debye"], 3) - (1.2, False, 2.0) - >>> bool(np.isnan(result["reduced_vdos"][0])), result["reduced_vdos"].shape - (True, (201,)) - >>> round(float(frequencies_thz[result["reliable"]][0]), 3), result["peak_below_box_limit"] - (1.1, False) - - ``` - """ - frequencies_thz = np.asarray(frequencies_thz, dtype=np.float64) - vdos = np.asarray(vdos, dtype=np.float64) - if frequencies_thz.ndim != 1 or vdos.shape != frequencies_thz.shape: - msg = ( - "frequencies_thz and vdos must be 1-D arrays of the same length, " - f"got shapes {frequencies_thz.shape} and {vdos.shape}." - ) - raise ValueError(msg) - if not (np.all(np.isfinite(frequencies_thz)) and np.all(np.isfinite(vdos))): - msg = "frequencies_thz and vdos must not contain NaN or inf." - raise ValueError(msg) - if np.any(frequencies_thz < 0): - msg = "frequencies_thz must not be negative." - raise ValueError(msg) - if np.any(np.diff(frequencies_thz) <= 0): - msg = "frequencies_thz must be strictly increasing." - raise ValueError(msg) - low, high = peak_range_thz - if not low < high: - msg = f"peak_range_thz must satisfy low < high, got {peak_range_thz}." - raise ValueError(msg) - - positive = frequencies_thz > 0 - reduced = np.full_like(vdos, np.nan) - np.divide(vdos, frequencies_thz**2, out=reduced, where=positive) - in_range = np.flatnonzero(positive & (frequencies_thz >= low) & (frequencies_thz <= high)) - if in_range.size == 0: - msg = f"peak_range_thz {peak_range_thz} contains no frequency bins above 0 THz." - raise ValueError(msg) - peak = in_range[np.argmax(reduced[in_range])] - result: dict[str, Any] = { - "reduced_vdos": reduced, - "boson_peak_thz": float(frequencies_thz[peak]), - "boson_peak_height": float(reduced[peak]), - "peak_at_range_edge": bool(peak in (in_range[0], in_range[-1])), - } - if debye is not None: - level = float(debye["debye_level_thz-3"]) - lowest_thz = float(debye["lowest_box_frequency_thz"]) - result["debye_level_thz-3"] = level - result["boson_peak_over_debye"] = result["boson_peak_height"] / level - result["reliable"] = frequencies_thz >= lowest_thz - result["peak_below_box_limit"] = bool(frequencies_thz[peak] < lowest_thz) - return result - - -# h nu / k_B in K for nu = 1 THz (about 48 K), and k_B T in meV for T = 1 K. -_THZ_TO_K = h * 1e12 / Boltzmann -_K_TO_MEV = Boltzmann / e * 1e3 -_MIN_GRID_POINTS = 2 - - -def _validate_thermodynamics_inputs( - frequencies_thz: NDArray, vdos: NDArray, temperatures_k: ArrayLike -) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]: - frequencies_thz = np.asarray(frequencies_thz, dtype=np.float64) - vdos = np.asarray(vdos, dtype=np.float64) - temperatures_k = np.array(temperatures_k, dtype=np.float64, ndmin=1) - if frequencies_thz.ndim != 1 or vdos.shape != frequencies_thz.shape: - msg = ( - "frequencies_thz and vdos must be 1-D arrays of the same length, " - f"got shapes {frequencies_thz.shape} and {vdos.shape}." - ) - raise ValueError(msg) - if frequencies_thz.size < _MIN_GRID_POINTS: - msg = f"At least 2 frequencies are needed, got {frequencies_thz.size}." - raise ValueError(msg) - if not (np.all(np.isfinite(frequencies_thz)) and np.all(np.isfinite(vdos))): - msg = "frequencies_thz and vdos must not contain NaN or inf." - raise ValueError(msg) - if np.any(vdos < 0): - msg = "vdos must not be negative." - raise ValueError(msg) - if np.any(np.diff(frequencies_thz) <= 0): - msg = "frequencies_thz must be strictly increasing." - raise ValueError(msg) - if not np.any(frequencies_thz > 0): - msg = "frequencies_thz must contain at least one frequency above 0 THz." - raise ValueError(msg) - _check_temperatures(temperatures_k) - return frequencies_thz, vdos, temperatures_k - - -def _check_temperatures(temperatures_k: NDArray[np.float64]) -> None: - """Raise unless ``temperatures_k`` (float64, at least 1-D) is a non-empty 1-D array of finite values >= 0.""" - valid_temperatures = np.all(np.isfinite(temperatures_k) & (temperatures_k >= 0)) - if temperatures_k.ndim != 1 or temperatures_k.size == 0 or not valid_temperatures: - msg = "temperatures_k must be a scalar or a non-empty 1-D array of finite, non-negative values." - raise ValueError(msg) - - -def compute_vibrational_thermodynamics( - frequencies_thz: NDArray, - vdos: NDArray, - temperatures_k: ArrayLike, - *, - lowest_frequency_thz: float | None = None, -) -> dict[str, Any]: - r"""Compute the harmonic heat capacity, entropy and energies from a VDOS, with a lower temperature bound. - - Each mode of frequency $\nu$ is a quantum harmonic oscillator. With $x = h \nu / (k_B T)$ it contributes - - $$C_V = k_B \frac{x^2 e^x}{(e^x - 1)^2}, \quad - S = k_B \left[\frac{x}{e^x - 1} - \ln\left(1 - e^{-x}\right)\right],$$ - - $$U = \frac{h \nu}{2} + \frac{h \nu}{e^x - 1}, \quad F = \frac{h \nu}{2} + k_B T \ln\left(1 - e^{-x}\right), - \quad E_\mathrm{ZP} = \frac{h \nu}{2},$$ - - and a quantity per atom is $Q(T) = 3 \int g(\nu)\, q(\nu, T)\, d\nu$ (three modes per atom), integrated with the - trapezoid rule on the given grid, as the VDOS functions of this module normalise. The VDOS must therefore be - normalised to 1 (``normalization="unit"`` in :func:`compute_vdos_from_velocities`); this is not enforced, and - ``"vdos_integral"`` lets the caller check it. A partial VDOS from :func:`compute_partial_vdos` with ``"unit"`` gives - that group's additive contribution per atom of the whole system, so the partials sum to the total. At $T = 0$ the - exact limits are returned: $C_V = S = 0$ and $U = F = E_\mathrm{ZP}$. Large $x$ is evaluated in forms that cannot - overflow (with ``np.expm1`` and ``np.log1p(-np.exp(-x))``). - - $S$ and $F$ diverge as $\nu \to 0$, so only $\nu > 0$ is integrated: the integrand is set to zero at every grid - point with $\nu \le 0$ (the zero-frequency bin of the VACF route, and imaginary harmonic modes stored as negative - frequencies) and the trapezoid rule runs over the full grid. Nothing is dropped silently: ``"vdos_integral"`` is the - integral of $g$ over the full grid, and ``"excluded_weight"`` is that integral minus the integral of $g$ with the - points at $\nu \le 0$ set to zero, i.e. the share of modes left out. At high $T$, $C_V$ tends to - $3 \, (\mathrm{vdos\_integral} - \mathrm{excluded\_weight})$ k$_B$ per atom. - - At low temperature the values depend on the low-frequency VDOS, which a finite box or a short trajectory does not - resolve. Below $T_\mathrm{min} = h \nu_\mathrm{low} / k_B$ (1 THz corresponds to 48 K) the values are flagged as - unreliable, not removed. Usual choices of $\nu_\mathrm{low}$ (``lowest_frequency_thz``) are - ``debye["lowest_box_frequency_thz"]`` from :func:`compute_debye_level` (the lowest acoustic mode of the box), the - frequency resolution $1 / (N \Delta t)$ of the VACF route, or the lowest non-zero mode of the harmonic route. With - ``None`` the first positive grid frequency is used, which is only the resolution of the grid, not the box limit, so - the bound is then too optimistic for a small box. $T = 0$ is always flagged. - - Args: - frequencies_thz: Frequencies in THz, 1-D and strictly increasing. Zero and negative values are allowed and - excluded from the integrals. - vdos: VDOS on ``frequencies_thz``, 1-D of the same length, non-negative, in 1/THz and normalised to 1. - temperatures_k: Temperatures in K, a scalar, a list or a 1-D array of finite values $\ge 0$. - lowest_frequency_thz: $\nu_\mathrm{low}$ in THz for the temperature bound, positive and finite, or ``None`` - (default) for the first positive grid frequency. - - Returns: - A dict with: - ``"temperatures_k"``: the temperatures as a float64 array (length 1 for a scalar). - ``"heat_capacity_kb_per_atom"``: $C_V$ in k$_B$ per atom, an array of the same length. - ``"entropy_kb_per_atom"``: $S$ in k$_B$ per atom. - ``"internal_energy_mev_per_atom"``: $U$ in meV per atom, including the zero-point energy. - ``"free_energy_mev_per_atom"``: $F$ in meV per atom, including the zero-point energy. - ``"zero_point_energy_mev_per_atom"``: $E_\mathrm{ZP}$ in meV per atom, a float. - ``"temperature_bound_k"``: $T_\mathrm{min}$ in K, a float. - ``"reliable"``: boolean array, True where $T \ge T_\mathrm{min}$. - ``"lowest_frequency_thz"``: $\nu_\mathrm{low}$ in THz. - ``"lowest_frequency_source"``: ``"caller"`` or ``"grid"``. - ``"vdos_integral"``: trapezoid integral of ``vdos`` over the full grid. - ``"excluded_weight"``: the part of ``"vdos_integral"`` at $\nu \le 0$ that is left out. - - Raises: - ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length with at least 2 points, - contain NaN or inf, ``vdos`` is negative anywhere, the frequencies are not strictly increasing or none is - above 0, a temperature is negative or not finite, or ``lowest_frequency_thz`` is not positive and finite. - - Example: - ```pycon - >>> frequencies_thz = np.linspace(0.0, 10.0, 1001) - >>> vdos = 3 * frequencies_thz**2 / 10.0**3 # Debye VDOS with nu_D = 10 THz (theta_D = 480 K) - >>> thermo = compute_vibrational_thermodynamics( - ... frequencies_thz, vdos, [0.0, 300.0, 3000.0], lowest_frequency_thz=1.0 - ... ) - >>> thermo["heat_capacity_kb_per_atom"].round(3) - array([0. , 2.649, 2.996]) - >>> round(thermo["temperature_bound_k"], 1), thermo["reliable"].tolist() - (48.0, [False, True, True]) - >>> round(thermo["zero_point_energy_mev_per_atom"], 2) # 9/8 h nu_D - 46.53 - - ``` - """ - frequencies_thz, vdos, temperatures_k = _validate_thermodynamics_inputs(frequencies_thz, vdos, temperatures_k) - positive = frequencies_thz > 0 - if lowest_frequency_thz is None: - lowest_thz = float(frequencies_thz[positive][0]) - source = "grid" - else: - if not (np.isfinite(lowest_frequency_thz) and lowest_frequency_thz > 0): - msg = f"lowest_frequency_thz must be positive and finite, got {lowest_frequency_thz}." - raise ValueError(msg) - lowest_thz = float(lowest_frequency_thz) - source = "caller" - - # Trapezoid weights of the full grid, so that sum(weights * f) is np.trapezoid(f, frequencies_thz). Keeping only the - # points with nu > 0 integrates the integrand set to zero at nu <= 0. Three modes per atom. - spacing = np.diff(frequencies_thz) - weights = np.zeros_like(frequencies_thz) - weights[:-1] += spacing / 2 - weights[1:] += spacing / 2 - mode_weights = 3 * (weights * vdos)[positive] - mode_k = frequencies_thz[positive] * _THZ_TO_K - mode_mev = frequencies_thz[positive] * _THZ_TO_UNIT["meV"] - vdos_integral = float(np.trapezoid(vdos, frequencies_thz)) - positive_integral = float(np.trapezoid(np.where(positive, vdos, 0.0), frequencies_thz)) - - zero_point = float(mode_weights @ mode_mev) / 2 - heat_capacity = np.zeros_like(temperatures_k) - entropy = np.zeros_like(temperatures_k) - internal_energy = np.full_like(temperatures_k, zero_point) - free_energy = np.full_like(temperatures_k, zero_point) - for i in np.flatnonzero(temperatures_k > 0): - x = mode_k / temperatures_k[i] - exp_neg = np.exp(-x) - one_minus_exp_neg = -np.expm1(-x) - occupation = exp_neg / one_minus_exp_neg # 1 / (e^x - 1) without overflow - log_term = np.log1p(-exp_neg) # ln(1 - e^-x) - # x^2 e^x / (e^x - 1)^2 written so that neither e^x nor x^2 is formed. - heat_capacity[i] = mode_weights @ (x * np.exp(-x / 2) / one_minus_exp_neg) ** 2 - entropy[i] = mode_weights @ (x * occupation - log_term) - internal_energy[i] += mode_weights @ (mode_mev * occupation) - free_energy[i] += _K_TO_MEV * temperatures_k[i] * (mode_weights @ log_term) - - temperature_bound_k = lowest_thz * _THZ_TO_K - return { - "temperatures_k": temperatures_k, - "heat_capacity_kb_per_atom": heat_capacity, - "entropy_kb_per_atom": entropy, - "internal_energy_mev_per_atom": internal_energy, - "free_energy_mev_per_atom": free_energy, - "zero_point_energy_mev_per_atom": zero_point, - "temperature_bound_k": temperature_bound_k, - "reliable": temperatures_k >= temperature_bound_k, - "lowest_frequency_thz": lowest_thz, - "lowest_frequency_source": source, - "vdos_integral": vdos_integral, - "excluded_weight": vdos_integral - positive_integral, - } - - -# Spectra of silicate glasses reach about 40 THz; a lower Nyquist frequency cuts and aliases the highest modes. -_MIN_NYQUIST_THZ = 50.0 -# Name of the text dump written by lammpsparser in each run directory. -_DUMP_FILE = "dump.out" - - -def _whole_steps(name: str, duration_ps: float, timestep: float) -> int: - """Return ``duration_ps`` in MD steps; raise if it is not a whole number of timesteps.""" - steps = duration_ps * 1000 / timestep - whole_steps = round(steps) - if not math.isclose(steps, whole_steps, rel_tol=1e-9): - msg = f"{name}={duration_ps} ps is not a whole number of {timestep} fs timesteps ({steps:g} steps)." - raise ValueError(msg) - return whole_steps - - -def _vdos_simulation_settings( - potential: pd.DataFrame, - temperature_sim: float, - timestep: float, - production_ps: float, - block_ps: float, - dump_every: int, - equilibration_steps: int, - normalization: str, - window: object, -) -> tuple[int, int, int, float]: - """Validate the arguments of :func:`vdos_simulation`; return ``(block_steps, block_frames, n_blocks, dt_fs)``.""" - if potential.empty: - msg = "No matching potential found for the given configuration." - raise ValueError(msg) - for name, value in ( - ("temperature_sim", temperature_sim), - ("timestep", timestep), - ("block_ps", block_ps), - ("production_ps", production_ps), - ): - if not (np.isfinite(value) and value > 0): - msg = f"{name} must be positive and finite, got {value}." - raise ValueError(msg) - if isinstance(dump_every, bool) or not isinstance(dump_every, int | np.integer) or dump_every < 1: - msg = f"dump_every must be a positive integer, got {dump_every!r}." - raise ValueError(msg) - if equilibration_steps < 0: - msg = f"equilibration_steps must not be negative, got {equilibration_steps}." - raise ValueError(msg) - if normalization not in ("unit", "3N"): - msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N'." - raise ValueError(msg) - _validate_window(window) - block_steps = _whole_steps("block_ps", block_ps, timestep) - if block_steps % dump_every: - msg = f"The block of {block_steps} steps is not a multiple of dump_every={dump_every}." - raise ValueError(msg) - block_frames = block_steps // dump_every - if block_frames < _MIN_FRAMES: - msg = f"A block needs at least 2 frames, got {block_frames} ({block_steps} steps, dump_every={dump_every})." - raise ValueError(msg) - production_steps = _whole_steps("production_ps", production_ps, timestep) - if production_steps % block_steps: - msg = f"The production of {production_steps} steps is not a multiple of the block of {block_steps} steps." - raise ValueError(msg) - return block_steps, block_frames, production_steps // block_steps, timestep * dump_every - - -def _split_total(partial: dict[str, dict[str, NDArray[np.float64]]]) -> dict[str, Any]: - """Move the all-atoms group of :func:`vdos_simulation` to a top-level ``"total"`` entry.""" - return {"total": partial["total"]["all"], **{name: labels for name, labels in partial.items() if name != "total"}} - - -def _nve_block( - structure: "Atoms", - nve_kwargs: dict[str, Any], - block: int, - n_blocks: int, - block_frames: int, - masses: NDArray[np.float64], - dt_fs: float, - spectral_groups: dict[str, dict[str, NDArray]], - normalization: Literal["unit", "3N"], - window: VdosWindow, - block_dir: str | None, - *, - keep_trajectory: bool, -) -> tuple["Atoms", dict[str, Any], NDArray[np.float64], NDArray[np.float64], float]: - """Run NVE block number ``block`` (1-based) in ``block_dir``. - - Return ``(final structure, spectra, temperature, energy_tot, step-0 energy_tot)``. Unless ``block_dir`` is None - or ``keep_trajectory`` is True, the block's dump is deleted once its spectra and thermo are extracted. - - The parsed output is local to this function, so its trajectory arrays are freed on return, before the next block - is launched. Nothing returned here may hold a view of them. - """ - structure_final, parsed_output = _run_lammps_md(structure=structure, **nve_kwargs, tmp_working_directory=block_dir) - - # LAMMPS also dumps step 0 (the end state of the previous stage); it is dropped below. - generic = parsed_output["generic"] - for key in ("velocities", "temperature", "energy_tot"): - if len(generic[key]) != block_frames + 1: - msg = ( - f"NVE block {block} of {n_blocks} returned {len(generic[key])} frames of {key!r}, expected " - f"{block_frames + 1} ({block_frames} plus the step-0 frame)." - ) - if block_dir is not None: - dumps = [str(dump) for dump in sorted(Path(block_dir).rglob(_DUMP_FILE))] or [block_dir] - msg += f" Its dump is kept in {', '.join(dumps)}." - raise RuntimeError(msg) - velocities = np.asarray(generic["velocities"])[1:] - - frequencies_thz, no_window = compute_partial_vdos( - velocities, masses, dt_fs, spectral_groups, normalization=normalization - ) - vdos = {"no_window": _split_total(no_window)} - if window is not None: - _, windowed = compute_partial_vdos( - velocities, masses, dt_fs, spectral_groups, normalization=normalization, window=window - ) - vdos["windowed"] = _split_total(windowed) - lag_ps, vacf = compute_partial_vacf(velocities, masses, dt_fs, spectral_groups) - - spectra = {"frequencies_thz": frequencies_thz, "lag_ps": lag_ps, "vdos": vdos, "vacf": _split_total(vacf)} - temperature, energy_tot = np.asarray(generic["temperature"]), np.asarray(generic["energy_tot"]) - - if block_dir is not None and not keep_trajectory: - dumps = sorted(Path(block_dir).rglob(_DUMP_FILE)) - if not dumps: - warnings.warn( - f"No {_DUMP_FILE} found under {block_dir} for NVE block {block}; nothing was deleted.", - UserWarning, - stacklevel=3, - ) - for dump in dumps: - dump.unlink() - return structure_final, spectra, temperature[1:], energy_tot[1:], float(energy_tot[0]) - - -def _slope(x: ArrayLike, y: ArrayLike) -> float: - """Return the least-squares slope of ``y`` against ``x``.""" - x_array, y_array = np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64) - x_centred, y_centred = x_array - x_array.mean(), y_array - y_array.mean() - return float(x_centred @ y_centred / (x_centred @ x_centred)) - - -def _nve_drift( - temperature: NDArray[np.float64], - energy_tot: NDArray[np.float64], - step0_energies: list[float], - n_atoms: int, - dt_fs: float, -) -> dict[str, Any]: - """Return the energy and temperature drift of the concatenated kept NVE frames; see :func:`vdos_simulation`.""" - n_blocks = len(step0_energies) - energy_mev = energy_tot * 1e3 / n_atoms - time_ps = (np.arange(len(energy_tot)) + 1) * dt_fs * 1e-3 - block_energy, block_time = energy_mev.reshape(n_blocks, -1), time_ps.reshape(n_blocks, -1) - return { - "energy_drift_mev_per_atom_ps": _slope(time_ps, energy_mev), - "block_energy_drift_mev_per_atom_ps": np.array( - [_slope(t, e) for t, e in zip(block_time, block_energy, strict=True)] - ), - "boundary_energy_jump_mev_per_atom": np.asarray(step0_energies[1:]) * 1e3 / n_atoms - block_energy[:-1, -1], - "max_energy_deviation_mev_per_atom": float(np.max(np.abs(energy_mev - energy_mev[0]))), - "temperature_mean_k": float(np.mean(temperature)), - "temperature_std_k": float(np.std(temperature)), - "temperature_drift_k_per_ps": _slope(time_ps, temperature), - } - - -def _block_statistics(blocks: list[dict[str, Any]]) -> tuple[dict[str, Any], dict[str, Any]]: - """Return the mean and the standard error over blocks of every curve in nested dicts of one layout.""" - mean, sem = {}, {} - for key, value in blocks[0].items(): - values = [block[key] for block in blocks] - if isinstance(value, dict): - mean[key], sem[key] = _block_statistics(values) - else: - mean[key] = np.mean(values, axis=0) - # The standard error of one block is undefined, and np.std with ddof=1 would warn. - single = len(blocks) == 1 - sem[key] = np.full_like(value, np.nan) if single else np.std(values, axis=0, ddof=1) / np.sqrt(len(blocks)) - return mean, sem - - -def vdos_simulation( - structure: "Atoms", - potential: pd.DataFrame, - temperature_sim: float = 300.0, - timestep: float = 1.0, - server_kwargs: dict[str, Any] | None = None, - *, - thermostat: Thermostat, - equilibration_steps: int = 100_000, - production_ps: float = 200.0, - block_ps: float = 10.0, - dump_every: int = 5, - normalization: Literal["unit", "3N"] = "unit", - window: VdosWindow = "hann", - cutoff: CutoffSpec | None = None, - former_types: list[int] | None = None, - o_type: int = 8, - seed: int = 12345, - tmp_working_directory: str | Path | None = None, - keep_trajectory: bool = False, -) -> dict[str, Any]: - r"""Equilibrate a structure, run consecutive NVE blocks and average their VDOS and VACF, total and per atom group. - - Three MD stages run in LAMMPS at the constant volume of the input cell: - - 1. Langevin thermalisation at ``temperature_sim`` for 10,000 steps, with velocities created at ``temperature_sim`` - (as in :func:`diffusion_simulation`). - 2. NVT equilibration with ``thermostat`` for ``equilibration_steps`` steps, with velocities created again at - ``temperature_sim``. ``equilibration_steps=0`` skips this stage. - 3. NVE production of ``production_ps``, run as ``n_blocks = production_steps // block_steps`` consecutive blocks of - ``block_ps``, i.e. ``block_steps = block_ps * 1000 / timestep`` steps each, with velocities and thermo output - every ``dump_every`` steps. The first block starts from the velocities of the previous stage and every later - block from the end of the block before it, as a new LAMMPS run. - - The production is microcanonical because a thermostat perturbs the velocities and distorts the spectrum. LAMMPS - also writes the frame of step 0 of every block, which is the end state of the previous stage or block. It is - dropped, so the kept frames of consecutive blocks do not overlap. Each block holds ``n_frames = block_steps // - dump_every`` frames spaced by ``dt_fs = timestep * dump_every`` fs, and the frequency resolution is exactly - ``1 / block_ps`` THz. If the parsed output of a block does not hold ``n_frames + 1`` frames, a ``RuntimeError`` is - raised; no frame is trimmed silently. The Nyquist frequency is ``1 / (2 dt_fs)``: 100 THz for the defaults (1 fs, - every 5 steps). - - From the kept frames of each block (velocities in Å/fs, masses from ``structure.get_masses()`` in amu) the function - computes: - - - The VDOS without a window and, unless ``window`` is ``None``, with ``window`` (Hann by default), both with - :func:`compute_partial_vdos`, the given ``normalization`` and one shared frequency axis. The total is computed - as the partial VDOS of a group of all atoms, so it is the total VDOS of :func:`compute_vdos_from_velocities` - and integrates to 1 (``"unit"``) or ``3 * n_atoms`` (``"3N"``); within each grouping the partials add up to it. - - The VACF with :func:`compute_partial_vacf`, unwindowed, normalised so that the total $C(0) = 1$, with lags up to - half the block. - - The centre-of-mass velocity of the whole system is removed from every frame in both. - - Every returned curve is the mean over blocks, with the block standard error ``std(ddof=1) / sqrt(n_blocks)`` in - ``"vdos_sem"`` and ``"vacf_sem"``; with one block the standard error is NaN. Each block's VDOS and VACF are - normalised by that block's own kinetic energy, so the mean of the block curves integrates exactly to the - normalisation, the total VACF has $C(0) = 1$ exactly, and within each grouping the mean partials still add up to - the mean total. The standard errors are not additive: the standard error of a total is not the sum of those of - its partials. - - The standard error is the scatter between the blocks of this run, and it assumes that they are independent. The - blocks come from one NVE trajectory of one glass, so it contains no glass-to-glass variation at all, and nothing - that stays constant over the run: neither the energy of the run nor a nearly harmonic mode that keeps its energy - between blocks. A calibration compared the means of two independent thermal histories of one 300-atom - $\mathrm{SiO_2}$ glass (PMMCS, 300 K, 10 blocks of 10 ps each), where exact standard errors put 94 % of the bins - within two combined standard errors. Between 5 and 34 THz this held for 93 % (no window) and 95 % (Hann) of the - bins. Below 5 THz it held for 96 % and 98 %, so no low-frequency underestimate was seen, although 50 bins would not - show a small one. Between 34 and 40 THz, above the top of the spectrum, it held for only 75 % and 78 %: the weight - there differed by 4 to 5 %, as did the temperature of the two runs. The lag-1 correlation of the block residuals - was close to the -0.1 of independent blocks, but a part that is constant over the run cannot show up in it. One - pair of runs says nothing about larger boxes, lower temperatures or shorter blocks. - - The atom groups (element, oxygen class, $\mathrm{Q}^n$) come from :func:`classify_vibrational_groups` on the input - ``structure``, before any MD, so thermal motion of bonds near the cutoff cannot change them. They stay fixed for - all blocks. - - Memory: the velocities of one block take ``n_frames * n_atoms * 3 * 8`` bytes as float64, e.g. 0.29 GB for 2000 - frames (10 ps at 5 fs) of 6000 atoms. The parsed LAMMPS output holds three more arrays of that size (positions, - unwrapped positions and forces), and parsing it needs more still: a 10 ps block of 5400 atoms peaked 4.5 GB above - the baseline, 17 times its velocities (measured). The peak scales with one block, not with the whole production: a - block's parsed output is freed before the next block starts, and only the spectra and the thermo output accumulate. - Not all freed memory goes back to the system, though: over 8 blocks of 2 ps the resident size levelled off at 1.7 - times the peak of the first block (measured on macOS). - - Disk: with ``tmp_working_directory=None`` every run removes its files. In a caller-supplied directory every run - keeps a sub-directory, and each NVE block runs in its own ``vdos_nve_block__`` directory. Its dump - (``dump.out``, 88 bytes per atom per frame, measured: 0.47 MB per frame and 0.95 GB per 10 ps block at 5400 atoms) - is deleted once the block's spectra and thermo output are extracted, before the next block starts, so at most one - dump is on disk at a time. ``log.lammps``, the input script and the data file stay, as do all files of the Langevin - and NVT stages. ``keep_trajectory=True`` keeps every dump (20 for the defaults). A block that fails keeps its dump, - and the error names it. If no dump is found to delete, a warning is raised and the result is still returned. - - Drift: ``"nve_drift"`` reports the energy and temperature of the kept NVE frames, frame ``k`` (0-based over all - blocks) at ``t = (k + 1) * dt_fs`` fs. Each block restarts from the positions and velocities of the previous - block's dump, written with 6 significant digits, so the total energy can jump at a block boundary. The jump is - measured between the last kept frame of a block and the step-0 frame of the next, which hold the same state, so it - is the restart loss alone. The thermo output has 8 significant digits, so energies are resolved to about - ``|E_tot| / N * 1e-5`` meV/atom, one unit in the last digit (measured for $\mathrm{SiO_2}$ with PMMCS: 3.3e-4 - meV/atom at 300 atoms, 1.9e-4 at 5400). In those runs (300 K, blocks of 2 and 10 ps) every jump was within two - such units, at most 6.7e-4 meV/atom, and smaller than the drift within any block over the block length. - - Args: - structure: Input structure, e.g. a quenched glass. Its cell sets the volume of every stage, and the atom - groups and masses are taken from it. - potential: LAMMPS potential as a pandas DataFrame. - temperature_sim: Temperature of the Langevin and NVT stages in K. - timestep: MD timestep in fs. - server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``). - thermostat: Thermostat of the NVT stage, ``"nose_hoover"`` or ``"langevin"``. - equilibration_steps: Length of the NVT stage in MD steps; 0 skips it. Use a small value for quick demos and - the default for production-quality runs. - production_ps: Total length of the NVE production in ps, a whole number of timesteps and a multiple of - ``block_ps``; nothing is truncated. - block_ps: Length of one NVE block in ps, a whole number of timesteps. It sets the resolution 1 / ``block_ps`` - THz. - dump_every: Interval between dumped frames in MD steps, a positive integer that divides the block. - normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``). The - VACF is always normalised to $C(0) = 1$. - window: Window of the second VDOS, as in :func:`compute_partial_vdos`: ``"hann"`` (default), ``"hamming"``, - ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames (``dt_fs`` apart, so 250 frames - are 1.25 ps at the defaults), or ``None`` to compute only the unwindowed VDOS. - cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF - if ``None``. - former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. - o_type: Atomic number of oxygen. - seed: Random seed for the velocities created in the Langevin and NVT stages. - tmp_working_directory: Directory for temporary simulation files. If None, every run removes its files. - keep_trajectory: Keep the dump of every NVE block in ``tmp_working_directory`` instead of deleting it once its - spectra are computed. Requires ``tmp_working_directory``. - - Returns: - A dict with: - ``"frequencies_thz"``: frequency axis in THz, length ``n_frames // 2 + 1``, shared by both VDOS. - ``"vdos"``: mean over blocks, ``{"no_window": ..., "windowed": ...}`` (no ``"windowed"`` entry for - ``window=None``), each ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels - of ``"groups"``, in 1/THz. - ``"vdos_sem"``: block standard error of ``"vdos"``, same layout and units; NaN for one block. - ``"lag_ps"``: VACF lags in ps, length ``n_frames // 2 + 1``. - ``"vacf"``: mean over blocks, ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}``, - dimensionless. - ``"vacf_sem"``: block standard error of ``"vacf"``, same layout; NaN for one block. - ``"groups"``: the output of :func:`classify_vibrational_groups` on the input structure. - ``"structure"``: the final structure of the last NVE block. - ``"temperature"``: thermo temperature in K of each kept frame of all blocks, as parsed, length - ``n_blocks * n_frames``. - ``"energy_tot"``: total energy in eV of each kept frame of all blocks, as parsed, length - ``n_blocks * n_frames``. - ``"nve_drift"``: a dict over all kept NVE frames, energies per atom (``N`` atoms): - ``"energy_drift_mev_per_atom_ps"``, the least-squares slope of ``E_tot / N`` in meV/atom/ps over all - blocks, boundary jumps included; ``"block_energy_drift_mev_per_atom_ps"``, the same slope within each - block, array of length ``n_blocks``; ``"boundary_energy_jump_mev_per_atom"``, ``E_tot / N`` of the step-0 - frame of block ``b + 1`` minus that of the last kept frame of block ``b`` in meV/atom, array of length - ``n_blocks - 1``; ``"max_energy_deviation_mev_per_atom"``, the largest ``|E_tot - E_tot[0]| / N`` in - meV/atom from the first kept frame; ``"temperature_mean_k"`` and ``"temperature_std_k"`` (population - standard deviation, ddof=0) in K; and ``"temperature_drift_k_per_ps"``, the least-squares slope in K/ps. - ``"dt_fs"``: time between frames in fs. - ``"n_blocks"``: number of NVE blocks. - ``"n_frames"``: number of kept frames per block. - ``"resolution_thz"``: 1 / ``block_ps``. - ``"nyquist_thz"``: 1 / (2 ``dt_fs``) in THz. - ``"normalization"``: the VDOS normalisation. - ``"window"``: the window of ``vdos["windowed"]``, as passed. - - Raises: - ValueError: Before any MD, if the potential is empty, ``temperature_sim``, ``timestep``, ``block_ps`` or - ``production_ps`` is not positive and finite, ``dump_every`` is not a positive integer, - ``equilibration_steps`` is negative, ``normalization`` is not ``"unit"`` or ``"3N"``, ``window`` is - unknown, ``block_ps`` or ``production_ps`` is not a whole number of timesteps, the block is not a multiple - of ``dump_every`` or holds fewer than 2 frames, the production is not a multiple of the block, - ``thermostat`` is unknown, or ``keep_trajectory`` is True without a ``tmp_working_directory``. - RuntimeError: If the output of an NVE block does not hold ``n_frames + 1`` frames of velocities, temperature - and total energy. The message names the block and, with a ``tmp_working_directory``, its kept dump; no - later block is run. - - Warns: - UserWarning: If the Nyquist frequency is below 50 THz, or if no dump of a block is found to delete. - - Example: - ```pycon - >>> out = vdos_simulation(structure, potential, thermostat="nose_hoover") # doctest: +SKIP - >>> out["n_blocks"], out["n_frames"], out["resolution_thz"], out["nyquist_thz"] # doctest: +SKIP - (20, 2000, 0.1, 100.0) - >>> out["vdos"]["windowed"]["element"]["Si"] # doctest: +SKIP - >>> out["vdos_sem"]["windowed"]["element"]["Si"] # doctest: +SKIP - >>> out["nve_drift"]["energy_drift_mev_per_atom_ps"] # doctest: +SKIP - - ``` - """ - if keep_trajectory and tmp_working_directory is None: - msg = "keep_trajectory=True needs a tmp_working_directory; without one every run removes its files." - raise ValueError(msg) - block_steps, block_frames, n_blocks, dt_fs = _vdos_simulation_settings( - potential, - temperature_sim, - timestep, - production_ps, - block_ps, - dump_every, - equilibration_steps, - normalization, - window, - ) - nyquist_thz = 500.0 / dt_fs - if nyquist_thz < _MIN_NYQUIST_THZ: - warnings.warn( - f"The Nyquist frequency is {nyquist_thz:g} THz (timestep {timestep} fs, dump_every {dump_every}), below " - f"{_MIN_NYQUIST_THZ:g} THz; silicate spectra reach about 40 THz, so the highest modes are cut and aliased.", - UserWarning, - stacklevel=2, - ) - nvt_ensemble, _ = thermostat_ensembles(thermostat) - groups = classify_vibrational_groups(structure, cutoff, former_types, o_type) - masses = structure.get_masses() - - equilibrated, _ = _run_lammps_md( - structure=structure, - potential=potential, - tmp_working_directory=tmp_working_directory, - temperature=temperature_sim, - n_ionic_steps=10_000, - timestep=timestep, - n_print_thermo=1000, - initial_temperature=temperature_sim, - ensemble="nvt_langevin", - seed=seed, - server_kwargs=server_kwargs, - ) - if equilibration_steps > 0: - equilibrated, _ = _run_lammps_md( - structure=equilibrated, - potential=potential, - tmp_working_directory=tmp_working_directory, - temperature=temperature_sim, - n_ionic_steps=equilibration_steps, - timestep=timestep, - n_print_thermo=1000, - initial_temperature=temperature_sim, - ensemble=nvt_ensemble, - seed=seed, - server_kwargs=server_kwargs, - ) - # No temperature and no initial temperature: plain fix nve from the velocities of the previous stage. - nve_kwargs = { - "potential": potential, - "temperature": None, - "initial_temperature": None, - "n_ionic_steps": block_steps, - "timestep": timestep, - "n_dump": dump_every, - "ensemble": "nve", - "seed": seed, - "server_kwargs": server_kwargs, - } - spectral_groups = {"total": {"all": np.arange(len(structure))}, **groups} - structure_final = equilibrated - spectra, temperatures, energies, step0_energies = [], [], [], [] - for block in range(1, n_blocks + 1): - # Own directory per block, so its dump can be found and deleted; a random suffix avoids collisions on reuse. - block_dir = ( - None - if tmp_working_directory is None - else tempfile.mkdtemp(prefix=f"vdos_nve_block_{block:03d}_", dir=tmp_working_directory) - ) - structure_final, block_spectra, temperature, energy_tot, step0_energy = _nve_block( - structure_final, - nve_kwargs, - block, - n_blocks, - block_frames, - masses, - dt_fs, - spectral_groups, - normalization, - window, - block_dir, - keep_trajectory=keep_trajectory, - ) - spectra.append(block_spectra) - temperatures.append(temperature) - energies.append(energy_tot) - step0_energies.append(step0_energy) - - vdos, vdos_sem = _block_statistics([block_spectra["vdos"] for block_spectra in spectra]) - vacf, vacf_sem = _block_statistics([block_spectra["vacf"] for block_spectra in spectra]) - temperature, energy_tot = np.concatenate(temperatures), np.concatenate(energies) - - return { - "frequencies_thz": spectra[0]["frequencies_thz"], - "vdos": vdos, - "vdos_sem": vdos_sem, - "lag_ps": spectra[0]["lag_ps"], - "vacf": vacf, - "vacf_sem": vacf_sem, - "groups": groups, - "structure": structure_final, - "temperature": temperature, - "energy_tot": energy_tot, - "nve_drift": _nve_drift(temperature, energy_tot, step0_energies, len(structure), dt_fs), - "dt_fs": dt_fs, - "n_blocks": n_blocks, - "n_frames": block_frames, - "resolution_thz": 1.0 / block_ps, - "nyquist_thz": nyquist_thz, - "normalization": normalization, - "window": window, - } - - -# --------------------------------------------------------------------------- -# Harmonic route: dynamical matrix -# --------------------------------------------------------------------------- - -DynamicalMatrixStyle = Literal["regular", "eskm"] - -# LAMMPS writes ``eskm`` as ``regular`` times this literal (measured: ratio 9648.5 to 2e-16 on LAMMPS 29 Aug 2024). -# The CODATA value e N_A / 10 = 9648.533 is 3.4e-6 higher; dividing by it would not recover the ``regular`` matrix. -_ESKM_PER_REGULAR = 9648.5 -_DYNAMICAL_MATRIX_STYLES = ("regular", "eskm") - - -def _check_value_count(count: int, n_atoms: int, source: str) -> None: - """Raise if ``count`` values cannot form the (3 n_atoms, 3 n_atoms) matrix; name the n_atoms they imply.""" - expected = 9 * n_atoms**2 - if count == expected: - return - msg = f"{source} holds {count} values, expected 9 N² = {expected} for n_atoms={n_atoms}" - side = math.isqrt(count // 9) - if count and count % 9 == 0 and side**2 == count // 9: - msg += f"; {count} values imply n_atoms={side}" - raise ValueError(msg + ".") - - -def read_dynamical_matrix( - path: str | Path, - n_atoms: int, - *, - binary: bool = True, - style: DynamicalMatrixStyle = "regular", -) -> NDArray[np.float64]: - r"""Read a dynamical-matrix file written by the LAMMPS ``dynamical_matrix`` command. - - The dynamical matrix is the mass-weighted Hessian - - $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}, \quad - \Phi_{i\alpha, j\beta} = \frac{\partial^2 E}{\partial r_{i\alpha}\, \partial r_{j\beta}},$$ - - with $E$ the potential energy, $r_{i\alpha}$ the coordinates and $m_i$ the masses. It is returned in eV/Ų/amu - (LAMMPS ``regular`` in metal units). An eigenvalue $\lambda$ of $D$ gives the angular frequency - $\omega = \sqrt{\lambda}$ and the frequency $\nu = \sqrt{\lambda} / (2\pi)$, where - $\sqrt{1\ \mathrm{eV/Å^2/amu}}$ corresponds to $\nu = 15.633$ THz. Row and column $3i + \alpha$ belong to atom - $i$ (0-based, the LAMMPS atom id minus one) and $\alpha \in \{x, y, z\}$ ($0, 1, 2$), so the atom order is the - LAMMPS id order. For files written by ``_run_lammps_dynamical_matrix`` that is the order of the atoms in the - structure. - - The matrix is returned as written, NOT symmetrised. A finite-difference matrix is symmetric only to the - difference error, and a larger asymmetry $\max|D - D^\mathsf{T}| / \max|D|$ flags corrupted entries, for example - a pair that crosses a cutoff with a force jump during a displacement. The asymmetry is therefore left for the - caller to measure before symmetrising. - - File formats (verified on LAMMPS 29 Aug 2024): - - - ``binary=True`` (``binary yes``): raw float64 in native byte order, no header, exactly $9 N^2 \times 8$ bytes. - It is read with ``np.fromfile`` and reshaped without a copy. - - ``binary=False`` (``binary no``): three values per line in ``%.8f``, one line per atom of a row, so each matrix - row spans $N$ lines. Eight fixed decimals limit the precision to $5 \times 10^{-9}$ eV/Ų/amu absolute. The - text is parsed with ``np.loadtxt``, which is about six times faster than ``np.fromfile(sep=" ")`` here. - - With ``style="eskm"`` the file holds the matrix in 10 J/mol/Ų/(g/mol); it is divided in place by 9648.5, the - factor LAMMPS uses (the CODATA value $e N_\mathrm{A} / 10 = 9648.533$ differs by $3.4 \times 10^{-6}$), and - returned in eV/Ų/amu. - - Memory: the result is one array of $9 N^2 \times 8$ bytes, 2.6 GB at 6000 atoms and 7.2 GB at 10,000. A binary - read needs nothing more. Parsing text peaks at about 2.2 times the matrix (numpy allocations measured at 1000 and - 2000 atoms), about 16 GB at 10,000 atoms. Non-finite values are checked in blocks of rows, so the check adds at - most ``_CHUNK_BYTES / 8`` bytes. - - Args: - path: The dynamical-matrix file. - n_atoms: Number of atoms $N$ in the structure the matrix was computed on. - binary: True for a file written with ``binary yes``, False for ``binary no``. - style: The LAMMPS style the file was written with, ``"regular"`` or ``"eskm"``. - - Returns: - The $(3N, 3N)$ dynamical matrix in eV/Ų/amu, float64, C-contiguous and writable. - - Raises: - ValueError: If ``n_atoms`` is not a positive integer, ``style`` is unknown, the file does not hold $9 N^2$ - values (the size is checked before a binary file is read), or the matrix contains NaN or inf. - FileNotFoundError: If ``path`` does not exist. - - Example: - ```pycon - >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP - >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP - >>> asymmetry = np.abs(matrix - matrix.T).max() / np.abs(matrix).max() # doctest: +SKIP - ``` - """ - if isinstance(n_atoms, bool) or not isinstance(n_atoms, int | np.integer) or n_atoms < 1: - msg = f"n_atoms must be a positive integer, got {n_atoms!r}." - raise ValueError(msg) - if style not in _DYNAMICAL_MATRIX_STYLES: - msg = f"Unknown style {style!r}; allowed styles are {list(_DYNAMICAL_MATRIX_STYLES)}." - raise ValueError(msg) - n_dof = 3 * int(n_atoms) - if binary: - n_bytes = Path(path).stat().st_size - itemsize = np.dtype(np.float64).itemsize - if n_bytes % itemsize: - msg = f"The binary file {path} has {n_bytes} bytes, not a whole number of float64 values." - raise ValueError(msg) - _check_value_count(n_bytes // itemsize, n_atoms, f"The binary file {path}") - values = np.fromfile(path, dtype=np.float64) - else: - values = np.loadtxt(path, dtype=np.float64).ravel() - _check_value_count(values.size, n_atoms, f"The text file {path}") - matrix = values.reshape(n_dof, n_dof) - rows_per_chunk = max(1, _CHUNK_BYTES // (n_dof * matrix.itemsize)) - for start in range(0, n_dof, rows_per_chunk): - if not np.isfinite(matrix[start : start + rows_per_chunk]).all(): - msg = ( - f"The dynamical matrix in {path} contains NaN or inf " - f"in rows {start} to {min(start + rows_per_chunk, n_dof) - 1}." - ) - raise ValueError(msg) - if style == "eskm": - matrix /= _ESKM_PER_REGULAR - return matrix - - -# Frequency in THz of an eigenvalue of 1 eV/Ų/amu: sqrt(e / (1e-20 atomic_mass)) / (2 pi) / 1e12 = 15.633. -_THZ_PER_SQRT_EV_PER_A2_AMU = math.sqrt(e / (1e-20 * atomic_mass)) / (2 * math.pi) / 1e12 -_MATRIX_NDIM = 2 -EigenDriver = Literal["ev", "evd", "evr", "evx"] -_EIGH_DRIVERS = ("ev", "evd", "evr", "evx") -_N_TRANSLATIONS = 3 -# Smallest squared projection of a dropped mode on the rigid translations that counts as a translation. -_MIN_TRANSLATIONAL_OVERLAP = 0.9 - - -def _eigenvalues_to_thz(eigenvalues: NDArray[np.float64]) -> NDArray[np.float64]: - return np.sign(eigenvalues) * np.sqrt(np.abs(eigenvalues)) * _THZ_PER_SQRT_EV_PER_A2_AMU - - -def _validate_dynamical_matrix_input( - matrix: NDArray, - masses: ArrayLike | None, - *, - overwrite_matrix: bool, - eigenvectors: bool, - driver: str, - imaginary_threshold_thz: float, -) -> NDArray[np.float64] | None: - """Check everything except finiteness; return the masses as float64 (or None).""" - if matrix.ndim != _MATRIX_NDIM or matrix.shape[0] != matrix.shape[1]: - msg = f"matrix must be a square 2-D array, got shape {matrix.shape}." - raise ValueError(msg) - n_dof = matrix.shape[0] - if n_dof % 3 or n_dof < 2 * 3: - msg = f"matrix must be (3N, 3N) with N >= 2 atoms, got size {n_dof}." - raise ValueError(msg) - if matrix.dtype != np.float64: - msg = f"matrix must be float64 (a cast would copy it), got {matrix.dtype}." - raise ValueError(msg) - if overwrite_matrix and not (matrix.flags.writeable and (matrix.flags.c_contiguous or matrix.flags.f_contiguous)): - msg = "overwrite_matrix=True needs a writable C- or F-contiguous matrix; otherwise it would be copied." - raise ValueError(msg) - _validate_eigh_options(driver, imaginary_threshold_thz) - if masses is None: - return None - if not eigenvectors: - msg = "masses are only used for the translational overlap, which needs eigenvectors=True." - raise ValueError(msg) - masses = np.asarray(masses, dtype=np.float64) - if masses.shape != (n_dof // 3,) or not np.all(np.isfinite(masses) & (masses > 0)): - msg = f"masses must be {n_dof // 3} positive finite values, one per atom, got shape {masses.shape}." - raise ValueError(msg) - return masses - - -def _validate_eigh_options(driver: str, imaginary_threshold_thz: float) -> None: - """Raise for an unknown LAPACK driver or a threshold that is not >= 0.""" - if driver not in _EIGH_DRIVERS: - msg = f"Unknown driver {driver!r}; allowed drivers are {list(_EIGH_DRIVERS)}." - raise ValueError(msg) - if not imaginary_threshold_thz >= 0: - msg = f"imaginary_threshold_thz must be >= 0, got {imaginary_threshold_thz!r}." - raise ValueError(msg) - - -def _row_blocks(n_dof: int) -> range: - return range(0, n_dof, max(1, _CHUNK_BYTES // (n_dof * np.dtype(np.float64).itemsize))) - - -def _asymmetry(matrix: NDArray[np.float64]) -> tuple[float, tuple[int, int] | None]: - """Relative asymmetry max|D - D^T| / max|D| and the atom pair of the worst entry; raise on NaN or inf. - - Each block of rows [s, e) is compared over the columns from s on with the matching columns, so every entry and - every (r, c) pair is seen (the diagonal block twice) and no temporary exceeds one block. - """ - n_dof = matrix.shape[0] - rows = _row_blocks(n_dof) - max_abs, max_diff, worst = 0.0, 0.0, (0, 0) - for start in rows: - stop = min(start + rows.step, n_dof) - top, left = matrix[start:stop, start:], matrix[start:, start:stop].T - block_max = (float(np.abs(top).max()), float(np.abs(left).max())) # NaN and inf propagate through max - if not all(math.isfinite(value) for value in block_max): - msg = f"The dynamical matrix contains NaN or inf in rows or columns {start} to {stop - 1}." - raise ValueError(msg) - max_abs = max(max_abs, *block_max) - diff = top - left - np.abs(diff, out=diff) - flat = int(diff.argmax()) - if diff.flat[flat] > max_diff: - max_diff = float(diff.flat[flat]) - row, column = divmod(flat, diff.shape[1]) - worst = (start + row, start + column) - if not max_diff: - return 0.0, None - first, second = sorted((worst[0] // 3, worst[1] // 3)) - return max_diff / max_abs, (first, second) - - -def _symmetrise_in_place(work: NDArray[np.float64]) -> None: - """Replace ``work`` by (work + work^T) / 2 block by block, without a full-size temporary. - - The block of rows [s, e) writes rows [s, e) and columns [s, e) from s on; later blocks only touch rows and - columns from e on, so no entry is read after it was written. The diagonal block of the average is symmetric, so - its two writes agree. - """ - n_dof = work.shape[0] - rows = _row_blocks(n_dof) - for start in rows: - stop = min(start + rows.step, n_dof) - average = work[start:stop, start:] + work[start:, start:stop].T - average *= 0.5 - work[start:stop, start:] = average - work[start:, start:stop] = average.T - - -def diagonalize_dynamical_matrix( - matrix: NDArray[np.float64], - *, - masses: ArrayLike | None = None, - overwrite_matrix: bool = False, - eigenvectors: bool = True, - driver: EigenDriver = "evr", - imaginary_threshold_thz: float = 0.01, -) -> dict[str, Any]: - r"""Symmetrise and diagonalise a mass-weighted dynamical matrix and drop the three translational modes. - - The input is the dynamical matrix of :func:`read_dynamical_matrix`, - - $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}$$ - - in eV/Ų/amu, $(3N, 3N)$, row and column $3i + \alpha$ for atom $i$ and direction $\alpha$. An eigenvalue - $\lambda$ gives the frequency $\nu = \sqrt{\lambda} / (2\pi)$, which is - $\nu = 15.633\ \mathrm{THz} \times \sqrt{\lambda / (\mathrm{eV/Å^2/amu})}$ (the factor is - $\sqrt{e / (10^{-20}\, m_\mathrm{u})} / (2\pi) / 10^{12}$ from ``scipy.constants``). An imaginary mode, - $\lambda < 0$, is reported as a negative frequency $\nu = -\sqrt{|\lambda|} / (2\pi)$. - - Steps: - - 1. Asymmetry of the raw matrix, $\max|D - D^\mathsf{T}| / \max|D|$, and the atom pair $(i, j)$, $i \le j$, of the - worst entry. A finite-difference matrix is symmetric only to the difference error. A pair that crosses a cutoff - where the force jumps during a displacement $h$ (an energy-shifted pair style such as the PMMCS ``pedone`` term - at 5.5 Å) gets a spurious term of about jump / (2h) in one entry but not in its transpose, so a large asymmetry - points at such corrupted entries, and the atom pair tells where. It is measured before symmetrising, in blocks - of rows, together with the check for NaN and inf. - 2. Symmetrisation to $(D + D^\mathsf{T}) / 2$ in place, in the same blocks. With ``overwrite_matrix=False`` this - works on one copy of the input; with True on the input itself. - 3. Diagonalisation with ``scipy.linalg.eigh(..., overwrite_a=True, driver=driver)``. This deliberately replaces - the ``numpy.linalg.eigh`` of the original plan: numpy always copies the matrix and uses the divide-and-conquer - driver, which with eigenvectors needs four matrices besides the input, against one for ``"evr"`` (see Memory). - 4. The three translational modes are dropped: the three eigenvalues of smallest $|\lambda|$, which are three - consecutive ones of the ascending spectrum. With ``masses``, each dropped mode's squared projection on the span - of the mass-weighted rigid translations $t_\alpha = \sqrt{m_i}\, e_\alpha / \sqrt{\sum_i m_i}$ is reported; it - is 1 for a pure translation. A value below 0.9 warns: a soft mode is mixed in, or the translations are not the - smallest $|\lambda|$ (a sum-rule violation that lifts them, or an isolated cluster, whose rotations are zero - modes too). - 5. Kept frequencies below ``-imaginary_threshold_thz`` count as imaginary and warn, with the asymmetry atoms. - - Memory (benchmark: a 3000-atom spring network, n = 9000, OpenBLAS 0.3.34 on 12 Apple M-series cores; peak - allocations, confirmed by the peak process RSS; scaled as $n^2$ to $N$ = 6000 and 10,000 atoms, where one matrix - is 2.6 GB and 7.2 GB). Totals include the input matrix; ``overwrite_matrix=False`` adds one copy: - - - eigenvalues only, any driver: 1 matrix, 2.6 / 7.2 GB (2 matrices, 5.2 / 14.4 GB without overwrite). - - ``"evr"`` with eigenvectors: 2 matrices (the eigenvectors are a new array), 5.2 / 14.4 GB (7.8 / 21.6 GB). - - ``"evx"`` with eigenvectors: the same as ``"evr"``. - - ``"evd"`` with eigenvectors: 3 matrices (the eigenvectors overwrite the input, plus two of workspace), - 7.8 / 21.6 GB (10.4 / 28.8 GB). - - ``"ev"`` with eigenvectors: 1 matrix (the eigenvectors overwrite the input), 2.6 / 7.2 GB (5.2 / 14.4 GB). - - For comparison, ``numpy.linalg.eigh``: 5 matrices, 13 / 36 GB. - - The asymmetry and symmetrisation passes add up to about 0.2 GB of row blocks (``_CHUNK_BYTES`` each), independent - of $N$, and LAPACK $O(n)$ workspace. - - Time at n = 9000, with eigenvectors (scaled as $n^3$, by 8 and 37, to 6000 and 10,000 atoms): ``"evr"`` 33 s - (4.4 min, 20 min), ``"evd"`` 27 s (3.6 min, 16 min; 66 s in a first, disturbed run), ``"evx"`` 316 s (42 min, - 3.2 h), ``"ev"`` 339 s (45 min, 3.5 h). Eigenvalues only: about 10 s with every driver (1.3 min, 6 min). - ``"evr"`` is the default: within about 20 % of the fastest, ``"evd"``, at one matrix less, and memory is the limit - at 10,000 atoms. - - With ``overwrite_matrix=True`` the input's contents are undefined afterwards (LAPACK overwrites it); with - ``"ev"`` or ``"evd"`` the returned eigenvectors share its memory. Only a writable C- or F-contiguous array can - be used without a copy, which is checked. - - Args: - matrix: The $(3N, 3N)$ mass-weighted dynamical matrix in eV/Ų/amu, float64 (no cast is made, since a cast - would copy it). Not symmetrised. - masses: Atomic masses in amu, shape $(N,)$, in the order of the matrix rows. Only used for the - translational overlap, so it needs ``eigenvectors=True``. - overwrite_matrix: Symmetrise and diagonalise ``matrix`` itself instead of a copy, saving one matrix of memory. - Its contents are undefined afterwards. - eigenvectors: Also return the eigenvectors of the kept modes. - driver: The LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (MRRR), ``"evd"`` (divide and conquer), - ``"ev"`` (QR iteration) or ``"evx"`` (bisection and inverse iteration). - imaginary_threshold_thz: Kept frequencies below minus this value, in THz, count as imaginary. - - Returns: - A dictionary with: - ``"frequencies_thz"``: the $3N - 3$ kept frequencies in THz, ascending, negative for imaginary modes. - ``"eigenvectors"``: $(3N, 3N - 3)$ array whose orthonormal columns are the kept modes, in the order of - ``"frequencies_thz"`` (a view of the LAPACK output), or None with ``eigenvectors=False``. - ``"translational_frequencies_thz"``: the three dropped frequencies in THz, ascending. - ``"translational_overlap"``: the dropped modes' squared projections on the rigid translations, shape - (3,), or None without ``masses``. - ``"asymmetry"``: $\max|D - D^\mathsf{T}| / \max|D|$ of the raw matrix (0.0 if exactly symmetric). - ``"asymmetry_atoms"``: the atom pair $(i, j)$, $i \le j$, of the largest $|D - D^\mathsf{T}|$, or None if - the matrix is exactly symmetric. $i = j$ when the worst entry lies in an atom's own $3 \times 3$ block; - after a cutoff crossing that atom is one of the crossing pair. - ``"n_imaginary"``: the number of kept frequencies below ``-imaginary_threshold_thz``. - ``"min_frequency_thz"``: the lowest kept frequency in THz. - ``"n_atoms"``: $N$. - ``"driver"``: the LAPACK driver used. - - Raises: - ValueError: If ``matrix`` is not square and 2-D, its size is not $3N$ with $N \ge 2$, it is not float64, it - contains NaN or inf, or with ``overwrite_matrix=True`` it is read-only or not C- or F-contiguous; if - ``masses`` does not hold $N$ positive finite values or is given with ``eigenvectors=False``; if - ``driver`` is unknown or ``imaginary_threshold_thz`` is negative. - - Warns: - UserWarning: If a dropped mode overlaps the rigid translations by less than 0.9, or if any kept frequency is - imaginary. - - Example: - ```pycon - >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP - >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP - >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP - ... matrix, masses=minimised.get_masses(), overwrite_matrix=True - ... ) - >>> modes["asymmetry"], modes["n_imaginary"], modes["translational_overlap"] # doctest: +SKIP - - ``` - """ - matrix = np.asarray(matrix) - masses = _validate_dynamical_matrix_input( - matrix, - masses, - overwrite_matrix=overwrite_matrix, - eigenvectors=eigenvectors, - driver=driver, - imaginary_threshold_thz=imaginary_threshold_thz, - ) - n_dof = matrix.shape[0] - asymmetry, asymmetry_atoms = _asymmetry(matrix) - work = matrix if overwrite_matrix else np.array(matrix) - _symmetrise_in_place(work) - # LAPACK works on Fortran-ordered arrays; f2py copies anything else. The transpose of a C-ordered symmetric - # matrix is the same matrix in Fortran order, so passing it avoids the copy. - lapack_input = work.T if work.flags.c_contiguous else work - del work - result = scipy.linalg.eigh( - lapack_input, overwrite_a=True, check_finite=False, driver=driver, eigvals_only=not eigenvectors - ) - del lapack_input - eigenvalues, vectors = result if eigenvectors else (result, None) - - # The eigenvalues are ascending, so the three of smallest |λ| are three consecutive ones: the window - # [first, first + 3) with the smallest max |λ| (the first such window on an exact tie). - magnitudes = np.abs(eigenvalues) - first = int(np.argmin(np.maximum(np.maximum(magnitudes[:-2], magnitudes[1:-1]), magnitudes[2:]))) - dropped = slice(first, first + _N_TRANSLATIONS) - translational_frequencies = _eigenvalues_to_thz(eigenvalues[dropped]) - frequencies = _eigenvalues_to_thz(np.delete(eigenvalues, dropped)) - - translational_overlap = None - if vectors is not None: - if masses is not None: - weights = np.sqrt(masses) / math.sqrt(masses.sum()) - projections = np.einsum("i,iam->am", weights, vectors[:, dropped].reshape(-1, 3, _N_TRANSLATIONS)) - translational_overlap = (projections**2).sum(axis=0) - if translational_overlap.min() < _MIN_TRANSLATIONAL_OVERLAP: - warnings.warn( - f"The dropped modes at {np.array2string(translational_frequencies, precision=4)} THz overlap the " - f"rigid translations by only {np.array2string(translational_overlap, precision=3)} (< " - f"{_MIN_TRANSLATIONAL_OVERLAP}): a soft mode is mixed in, or the translations are not the three " - "smallest |eigenvalues|.", - UserWarning, - stacklevel=2, - ) - # Instead of copying the (3N, 3N - 3) kept columns, shift the `first` columns before the translations (the - # modes below them, usually the few imaginary ones) three to the right, over the translations. Every column - # after the translations is already in place, so the kept modes are then columns 3 onwards, in their original - # order: a view. numpy buffers the overlapping assignment, which costs `first` columns, not the matrix. - vectors[:, _N_TRANSLATIONS : first + _N_TRANSLATIONS] = vectors[:, :first] - vectors = vectors[:, _N_TRANSLATIONS:] - - n_imaginary = int(np.count_nonzero(frequencies < -imaginary_threshold_thz)) - min_frequency = float(frequencies[0]) - if n_imaginary: - warnings.warn( - f"{n_imaginary} imaginary mode(s) below -{imaginary_threshold_thz} THz; the most negative is " - f"{min_frequency:.4g} THz. Raw-matrix asymmetry {asymmetry:.3g}, largest between atoms {asymmetry_atoms}.", - UserWarning, - stacklevel=2, - ) - return { - "frequencies_thz": frequencies, - "eigenvectors": vectors, - "translational_frequencies_thz": translational_frequencies, - "translational_overlap": translational_overlap, - "asymmetry": asymmetry, - "asymmetry_atoms": asymmetry_atoms, - "n_imaginary": n_imaginary, - "min_frequency_thz": min_frequency, - "n_atoms": n_dof // 3, - "driver": driver, - } - - -HarmonicNormalization = Literal["unit", "3N"] -# Default grid of compute_harmonic_vdos: step sigma / 5, from 0 to the highest mode plus 5 sigma. -_GAUSSIAN_STEPS_PER_SIGMA = 5 -_GAUSSIAN_TAIL_SIGMAS = 5.0 -# A caller grid warns when a spacing exceeds sigma / 2 by more than this; np.fft.rfftfreq spacings carry ulp noise. -_GRID_SPACING_RTOL = 1e-9 - - -def _mode_atom_weights(eigenvectors: NDArray[np.float64], n_atoms: int) -> Iterator[tuple[slice, NDArray[np.float64]]]: - """Yield ``(columns, a)`` over blocks of modes: a[i, k] = sum_alpha e[3i + alpha, k]^2, shape (n_atoms, block). - - Each block holds about ``_CHUNK_BYTES`` of eigenvectors. The per-atom reshape of a column block is a view for C- and - F-ordered input, so only ``a`` (a third of the block) is allocated: never a squared copy of the eigenvectors or an - (n_atoms, n_modes) array. :func:`compute_participation_ratio` reuses this code, not the weights of a - :func:`compute_harmonic_vdos` call: its second pass over the eigenvectors costs memory bandwidth, not memory. - """ - n_modes = eigenvectors.shape[1] - step = max(1, _CHUNK_BYTES // (eigenvectors.shape[0] * eigenvectors.itemsize)) - for start in range(0, n_modes, step): - columns = slice(start, min(start + step, n_modes)) - block = eigenvectors[:, columns].reshape(n_atoms, _N_COMPONENTS, -1) - yield columns, np.einsum("iak,iak->ik", block, block) - - -def _validate_harmonic_inputs( - frequencies_thz: ArrayLike, - eigenvectors: NDArray | None, - groups: dict[str, dict[str, NDArray]] | None, - broadening_thz: float, - normalization: str, -) -> tuple[NDArray[np.float64], NDArray[np.float64] | None, int]: - """Check the inputs; return the frequencies as float64, the eigenvectors and N (rows / 3, else (M + 3) // 3).""" - frequencies = np.asarray(frequencies_thz, dtype=np.float64) - if frequencies.ndim != 1 or frequencies.size == 0 or not np.all(np.isfinite(frequencies)): - msg = f"frequencies_thz must be a non-empty 1-D array of finite values, got shape {frequencies.shape}." - raise ValueError(msg) - n_modes = frequencies.size - _validate_broadening_options(broadening_thz, normalization) - if eigenvectors is None: - if groups is not None: - msg = "groups need eigenvectors: the group weights come from the eigenvector components." - raise ValueError(msg) - if normalization == "3N" and n_modes % _N_COMPONENTS: - msg = f"normalization='3N' without eigenvectors needs 3N - 3 frequencies; {n_modes} is not a multiple of 3." - raise ValueError(msg) - return frequencies, None, (n_modes + _N_TRANSLATIONS) // _N_COMPONENTS - eigenvectors = np.asarray(eigenvectors) - if eigenvectors.ndim != _MATRIX_NDIM or eigenvectors.dtype != np.float64: - msg = ( - "eigenvectors must be a 2-D float64 array (a cast would copy it), " - f"got {eigenvectors.ndim}-D {eigenvectors.dtype}." - ) - raise ValueError(msg) - if n_modes % _N_COMPONENTS or eigenvectors.shape != (n_modes + _N_TRANSLATIONS, n_modes): - msg = f"eigenvectors must have shape (3N, 3N - 3) to match {n_modes} frequencies, got {eigenvectors.shape}." - raise ValueError(msg) - return frequencies, eigenvectors, eigenvectors.shape[0] // _N_COMPONENTS - - -def _validate_broadening_options(broadening_thz: float, normalization: str) -> None: - """Raise for an unknown normalisation or a broadening that is not positive and finite.""" - if normalization not in ("unit", "3N"): - msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N'." - raise ValueError(msg) - if not np.isfinite(broadening_thz) or broadening_thz <= 0: - msg = f"broadening_thz must be positive and finite, got {broadening_thz!r}." - raise ValueError(msg) - - -def _validate_frequency_grid(frequency_grid_thz: ArrayLike) -> NDArray[np.float64]: - """Return a caller's grid as float64; raise unless it is 1-D, finite, strictly increasing, with >= 2 points.""" - grid = np.asarray(frequency_grid_thz, dtype=np.float64) - if grid.ndim != 1 or grid.size < _MIN_GRID_POINTS or not np.all(np.isfinite(grid)) or not np.all(np.diff(grid) > 0): - msg = "frequency_grid_thz must be a 1-D, finite, strictly increasing array with at least 2 points." - raise ValueError(msg) - return grid - - -def _harmonic_grid( - frequency_grid_thz: ArrayLike | None, frequencies: NDArray[np.float64], broadening_thz: float -) -> NDArray[np.float64]: - """The caller's grid after checks, or the default grid with step sigma / 5 whose last point is >= max + 5 sigma.""" - if frequency_grid_thz is None: - step = broadening_thz / _GAUSSIAN_STEPS_PER_SIGMA - top = max(float(frequencies.max()), 0.0) + _GAUSSIAN_TAIL_SIGMAS * broadening_thz - return np.arange(math.ceil(top / step) + 1) * step - grid = _validate_frequency_grid(frequency_grid_thz) - spacing = float(np.diff(grid).max()) - if spacing > 0.5 * broadening_thz * (1 + _GRID_SPACING_RTOL): - warnings.warn( - f"The largest grid spacing, {spacing:.4g} THz, exceeds half the broadening ({broadening_thz:.4g} THz): " - "the Gaussians are undersampled and the trapezoid integral is inaccurate.", - UserWarning, - stacklevel=3, - ) - return grid - - -def compute_harmonic_vdos( - frequencies_thz: ArrayLike, - eigenvectors: NDArray[np.float64] | None = None, - *, - groups: dict[str, dict[str, NDArray]] | None = None, - frequency_grid_thz: ArrayLike | None = None, - broadening_thz: float = 0.2, - normalization: HarmonicNormalization = "unit", -) -> dict[str, Any]: - r"""Compute the harmonic VDOS and its group partials from the modes of :func:`diagonalize_dynamical_matrix`. - - The input is the $M = 3N - 3$ kept modes: frequencies $\nu_k$ in THz (negative for imaginary modes) and the - mass-weighted eigenvectors $e_k$, orthonormal columns with row $3i + \alpha$ for atom $i$ and direction $\alpha$. - The weight of atom $i$ in mode $k$ and of a group $G$ are - - $$a_{ik} = \sum_\alpha e_{3i+\alpha,k}^2, \quad \sum_i a_{ik} = 1, \qquad w_{kG} = \sum_{i \in G} a_{ik},$$ - - and the VDOS and its partials are sums of unit-area Gaussians of standard deviation $\sigma$ (``broadening_thz``), - - $$g(\nu) = c \sum_{k:\, \nu_k \ge 0} G_\sigma(\nu - \nu_k), \quad - g_G(\nu) = c \sum_{k:\, \nu_k \ge 0} w_{kG}\, G_\sigma(\nu - \nu_k), \quad - G_\sigma(x) = \frac{e^{-x^2 / 2\sigma^2}}{\sigma \sqrt{2\pi}}.$$ - - Partials within a grouping that covers every atom once (e.g. ``"element"``) sum to the total, and the classes of - a grouping that covers a subset sum to that subset's partial (e.g. the ``"oxygen"`` classes to ``"O"``). - - Normalisation: - - - ``"unit"`` (default): $c = 1/M$, so the total integrates to 1 over all modes. - - ``"3N"``: $c = 3N/M$, so the total integrates to $3N$, as with the VACF route, although the three translations - were dropped: each kept mode carries $3N/M$ instead of 1. - - What is not counted: - - - Imaginary modes ($\nu_k < 0$, any negative value, unlike the ``imaginary_threshold_thz`` of - :func:`diagonalize_dynamical_matrix`) are excluded from all sums and counted in ``"n_imaginary_excluded"``. They - stay in $M$, so the integral falls short of 1 (or $3N$) by their share, ``"imaginary_weight"`` $= n/M$. - - Gaussian weight below or above the grid is not renormalised either: the default grid starts at 0, so modes within - a few $\sigma$ of 0 lose part of their weight. ``"grid_integral"`` is the trapezoid integral of the total on the - grid. A grid spacing up to $\sigma/2$ integrates a Gaussian to better than $10^{-10}$. - - Completeness: summed over all $3N$ modes, $\sum_k w_{kG} = 3 N_G$. The translations are the mass-weighted rigid - shifts $\sqrt{m_i / m_\mathrm{tot}}$, so over the kept modes it is $3 N_G - 3 m_G / m_\mathrm{tot}$, with $N_G$ - the atom count and $m_G$ the mass of the group. - - Relation to the VACF route: in mode $k$, atom $i$ carries the share $a_{ik}$ of the mode's kinetic energy, since - its mass-weighted velocity is proportional to $e_{3i+\alpha,k}$. A partial of - :func:`compute_partial_vdos` is the group's share of the mass-weighted velocity power, so with every mode at the - same mean kinetic energy (classical equipartition in a harmonic solid) the two routes use the same partial - definition, and the same normalisations. - - The eigenvectors are not checked for orthonormality, which would cost a full $(M, M)$ matrix product; columns that - are not orthonormal break $\sum_i a_{ik} = 1$ and the sums above. - - Memory: the eigenvectors are read in blocks of columns of ``_CHUNK_BYTES`` (64 MB), each reduced at once to the - groups, and the Gaussians are evaluated in blocks of modes of the same size. Neither a squared copy of the - eigenvectors nor an $(N, M)$ weight array is built. - - Args: - frequencies_thz: The $M = 3N - 3$ mode frequencies in THz, negative for imaginary modes, e.g. - ``"frequencies_thz"`` of :func:`diagonalize_dynamical_matrix`. - eigenvectors: The $(3N, M)$ float64 eigenvectors with orthonormal columns in the order of - ``frequencies_thz``, e.g. ``"eigenvectors"`` of :func:`diagonalize_dynamical_matrix` (any memory order; - no cast or copy is made). Only needed for ``groups``, and for ``"3N"`` it gives $N$. - groups: ``{grouping: {label: indices}}`` with 0-based atom positions in the order of the matrix rows, e.g. the - output of :func:`classify_vibrational_groups` on the minimised structure. Needs ``eigenvectors``. - frequency_grid_thz: The frequencies in THz at which the VDOS is evaluated: 1-D, finite, strictly increasing, - at least 2 points. ``None`` (default): from 0 in steps of exactly $\sigma/5$ up to the first point at or - above $\max(\nu_k, 0) + 5\sigma$. - broadening_thz: The standard deviation $\sigma$ of the Gaussians in THz (not the FWHM, which is - $2.355\sigma$). - normalization: ``"unit"`` or ``"3N"``, see above. - - Returns: - A dictionary with: - ``"frequencies_thz"``: the grid in THz. - ``"vdos"``: ``{"total": g}`` and, with ``groups``, ``{grouping: {label: g_G}}`` (the layout of - :func:`vdos_simulation`), each a float64 array on the grid in 1/THz. - ``"mode_weights"``: ``{grouping: {label: w}}`` with the $(M,)$ weights $w_{kG}$ of every mode, - imaginary ones included; only with ``groups``. - ``"n_modes"``: $M$. - ``"n_imaginary_excluded"``: the number of modes with $\nu_k < 0$. - ``"imaginary_weight"``: their share of the normalisation, ``n_imaginary_excluded / n_modes``. - ``"grid_integral"``: the trapezoid integral of the total on the grid. - ``"broadening_thz"``: $\sigma$ in THz. - ``"normalization"``: ``"unit"`` or ``"3N"``. - - Raises: - ValueError: If ``frequencies_thz`` is empty, not 1-D or not finite; ``eigenvectors`` is not 2-D float64 or - not $(M + 3, M)$ with $M$ a multiple of 3; ``broadening_thz`` is not positive and finite; - ``normalization`` is unknown, or ``"3N"`` without eigenvectors and $M$ not a multiple of 3; - ``groups`` is given without ``eigenvectors``, has no labels or has invalid indices; - ``frequency_grid_thz`` is not 1-D, finite and strictly increasing with at least 2 points. - - Warns: - UserWarning: If the largest spacing of ``frequency_grid_thz`` exceeds $\sigma/2$. - - Example: - ```pycon - >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP - >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP - >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP - ... matrix, masses=minimised.get_masses(), overwrite_matrix=True - ... ) - >>> groups = classify_vibrational_groups(minimised) # doctest: +SKIP - >>> vdos = compute_harmonic_vdos( # doctest: +SKIP - ... modes["frequencies_thz"], modes["eigenvectors"], groups=groups, broadening_thz=0.1 - ... ) - >>> vdos["vdos"]["oxygen"]["O_NBO"], vdos["grid_integral"], vdos["n_imaginary_excluded"] # doctest: +SKIP - - ``` - """ - frequencies, eigenvectors, n_atoms = _validate_harmonic_inputs( - frequencies_thz, eigenvectors, groups, broadening_thz, normalization - ) - grid = _harmonic_grid(frequency_grid_thz, frequencies, broadening_thz) - n_modes = frequencies.size - kept = frequencies >= 0 - - # Column 0 weighs every mode by 1 (the total); with groups, one column per group label follows. - weights = np.ones((n_modes, 1)) - keys: list[tuple[str, str]] = [] - if groups is not None and eigenvectors is not None: - keys, selections = _group_selections(groups) - membership = _membership(selections, n_atoms) - weights = np.ones((n_modes, 1 + membership.shape[1])) - for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms): - weights[columns, 1:] = atom_weights.T @ membership - - centres, kept_weights = frequencies[kept], weights[kept] - spectra = np.zeros((grid.size, weights.shape[1])) - step = max(1, _CHUNK_BYTES // (grid.size * grid.itemsize)) - buffer = np.empty((grid.size, min(step, centres.size))) # one block, reused for every chunk of modes - for start in range(0, centres.size, step): - gaussians = buffer[:, : min(step, centres.size - start)] - np.subtract(grid[:, None], centres[None, start : start + step], out=gaussians) - gaussians /= broadening_thz - np.square(gaussians, out=gaussians) - gaussians *= -0.5 - np.exp(gaussians, out=gaussians) - spectra += gaussians @ kept_weights[start : start + step] - spectra *= (1.0 if normalization == "unit" else 3.0 * n_atoms) / (n_modes * broadening_thz * math.sqrt(2 * math.pi)) - - total = np.ascontiguousarray(spectra[:, 0]) - result: dict[str, Any] = {"frequencies_thz": grid, "vdos": {"total": total}} - if groups is not None: - result["vdos"] = {"total": total, **_columns_by_group(groups, keys, spectra[:, 1:])} - result["mode_weights"] = _columns_by_group(groups, keys, weights[:, 1:]) - n_imaginary = n_modes - int(np.count_nonzero(kept)) - result.update( - { - "n_modes": n_modes, - "n_imaginary_excluded": n_imaginary, - "imaginary_weight": n_imaginary / n_modes, - "grid_integral": float(np.trapezoid(total, grid)), - "broadening_thz": float(broadening_thz), - "normalization": normalization, - } - ) - return result - - -def compute_participation_ratio(eigenvectors: NDArray[np.float64], masses: ArrayLike) -> NDArray[np.float64]: - r"""Compute the participation ratio of every mode from the displacements of its mass-weighted eigenvector. - - The eigenvectors $e_{3i+\alpha,k}$ of the mass-weighted dynamical matrix (atom $i$, direction $\alpha$, mode $k$) - give the atomic displacements $u_{3i+\alpha,k} \propto e_{3i+\alpha,k} / \sqrt{m_i}$. With the squared displacement - of atom $i$, the participation ratio is (Taraskin and Elliott, Phys. Rev. B 56, 8605 (1997), Eq. 16, a definition - they attribute to Bell and Dean) - - $$b_{ik} = \frac{1}{m_i} \sum_\alpha e_{3i+\alpha,k}^2, \qquad - P_k = \frac{\left(\sum_i b_{ik}\right)^2}{N \sum_i b_{ik}^2}.$$ - - The ratio form makes $P_k$ independent of the scale and sign of each column, so the displacements need no - normalisation. $P_k = 1$ when every atom moves by the same amount (a rigid translation, whatever the masses), - $1/N$ for a mode on one atom and $n/N$ for a mode shared equally by $n$ atoms. The per-atom weight is summed over - the three directions before squaring, so $P_k$ does not depend on the orientation of the axes. Unlike the - kinetic-energy share $m_i b_{ik}$ used by :func:`compute_harmonic_vdos`, $b_{ik}$ counts atoms by amplitude; the - two coincide for a single element. - - An extended mode has $P$ of order 1 at any size, but a mode on a fixed number of atoms has $P \propto 1/N$, and in a - small box the two can be hard to tell apart: a claim that a mode is localised needs the same band compared across - box sizes. - - - Args: - eigenvectors: The $(3N, K)$ float64 eigenvectors of the mass-weighted dynamical matrix, one mode per column - with row $3i + \alpha$ for atom $i$ and direction $\alpha$, e.g. ``"eigenvectors"`` of - :func:`diagonalize_dynamical_matrix` (any memory order; no cast or copy is made). Columns need not be - normalised. - masses: Atomic masses, shape $(N,)$, in the order of the rows, e.g. ``minimised.get_masses()``. Only their - ratios matter. - - Returns: - The $(K,)$ float64 participation ratios, in the order of the columns, between $1/N$ and 1. - - Raises: - ValueError: If ``eigenvectors`` is not a 2-D float64 array, its row count is not a positive multiple of 3, - it has no columns, or a column is zero or contains NaN or inf; if ``masses`` does not hold $N$ positive - finite values. - - Example: - ```pycon - >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP - >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP - >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP - ... matrix, masses=minimised.get_masses(), overwrite_matrix=True - ... ) - >>> ratios = compute_participation_ratio(modes["eigenvectors"], minimised.get_masses()) # doctest: +SKIP - >>> bands = np.digitize(modes["frequencies_thz"], [8.0, 20.0, 28.0]) # doctest: +SKIP - >>> np.bincount(bands, weights=ratios) / np.bincount(bands) # mean P per band # doctest: +SKIP - - ``` - """ - eigenvectors = np.asarray(eigenvectors) - if eigenvectors.ndim != _MATRIX_NDIM or eigenvectors.dtype != np.float64: - msg = ( - "eigenvectors must be a 2-D float64 array (a cast would copy it), " - f"got {eigenvectors.ndim}-D {eigenvectors.dtype}." - ) - raise ValueError(msg) - n_rows, n_modes = eigenvectors.shape - if n_rows == 0 or n_rows % _N_COMPONENTS or n_modes == 0: - msg = f"eigenvectors must have 3N rows (N >= 1) and at least one column, got shape {eigenvectors.shape}." - raise ValueError(msg) - n_atoms = n_rows // _N_COMPONENTS - masses = np.asarray(masses, dtype=np.float64) - if masses.shape != (n_atoms,) or not np.all(np.isfinite(masses) & (masses > 0)): - msg = f"masses must be {n_atoms} positive finite values, one per atom, got shape {masses.shape}." - raise ValueError(msg) - ratios = np.empty(n_modes) - for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms): - np.divide(atom_weights, masses[:, None], out=atom_weights) # squared displacements, in place in our block - # The weights are non-negative, so NaN or inf anywhere in a column makes its sum of squares non-finite. - squares = np.einsum("ik,ik->k", atom_weights, atom_weights) - if not np.all(np.isfinite(squares)): - msg = f"eigenvectors contain NaN or inf (mode {columns.start + int(np.argmin(np.isfinite(squares)))})." - raise ValueError(msg) - if np.any(squares == 0): - msg = f"eigenvectors has a zero column (mode {columns.start + int(np.argmax(squares == 0))})." - raise ValueError(msg) - ratios[columns] = atom_weights.sum(axis=0) ** 2 / (n_atoms * squares) - return ratios - - -# --------------------------------------------------------------------------- -# Harmonic route: workflow -# --------------------------------------------------------------------------- - -# The matrix file inside the directory that harmonic_vdos_simulation makes for it. -_HARMONIC_MATRIX_FILE = "dynamical_matrix.bin" -# Peak of diagonalize_dynamical_matrix with eigenvectors and overwrite_matrix=True, in matrices. -_HARMONIC_PEAK_MATRICES = 2 -# Defaults of _run_lammps_minimize that harmonic_vdos_simulation does not expose; used only to validate upfront. -_MINIMIZE_ENERGY_TOLERANCE = 0.0 -_MINIMIZE_N_PRINT = 100 - - -def _harmonic_simulation_settings( - structure: "Atoms", - potential: pd.DataFrame, - max_atoms: int, - displacement: float, - force_tolerance: float, - max_iter: int, - broadening_thz: float, - frequency_grid_thz: ArrayLike | None, - normalization: str, - temperatures_k: ArrayLike | None, - driver: str, - imaginary_threshold_thz: float, - *, - tmp_working_directory: str | Path | None, - keep_dynamical_matrix: bool, -) -> None: - """Validate the arguments of :func:`harmonic_vdos_simulation` before anything runs.""" - if not _is_positive_int(max_atoms): - msg = f"max_atoms must be a positive integer, got {max_atoms!r}." - raise ValueError(msg) - n_atoms = len(structure) - if n_atoms > max_atoms: - matrix_gb = 9 * n_atoms**2 * 8 / 1e9 - msg = ( - f"The structure has {n_atoms} atoms, more than max_atoms={max_atoms}. Its dynamical matrix takes " - f"9 N² x 8 bytes = {matrix_gb:.3g} GB, and the diagonalisation with eigenvectors peaks at " - f"{_HARMONIC_PEAK_MATRICES} matrices, {_HARMONIC_PEAK_MATRICES * matrix_gb:.3g} GB. Raise max_atoms " - "deliberately to run it anyway." - ) - raise ValueError(msg) - if potential.empty: - msg = "No matching potential found for the given configuration." - raise ValueError(msg) - if not np.isfinite(displacement) or displacement <= 0: - msg = f"displacement must be positive and finite (Å), got {displacement!r}." - raise ValueError(msg) - _validate_minimize_arguments(force_tolerance, _MINIMIZE_ENERGY_TOLERANCE, max_iter, "fire", None, _MINIMIZE_N_PRINT) - _validate_broadening_options(broadening_thz, normalization) - if frequency_grid_thz is not None: - _validate_frequency_grid(frequency_grid_thz) - if temperatures_k is not None: - _check_temperatures(np.array(temperatures_k, dtype=np.float64, ndmin=1)) - _validate_eigh_options(driver, imaginary_threshold_thz) - if keep_dynamical_matrix and tmp_working_directory is None: - msg = "keep_dynamical_matrix=True needs a tmp_working_directory; without one every run removes its files." - raise ValueError(msg) - - -def harmonic_vdos_simulation( - structure: "Atoms", - potential: pd.DataFrame, - server_kwargs: dict[str, Any] | None = None, - *, - max_atoms: int = 10_000, - displacement: float = 1e-5, - force_tolerance: float = 1e-6, - max_iter: int = 100_000, - broadening_thz: float = 0.2, - frequency_grid_thz: ArrayLike | None = None, - normalization: HarmonicNormalization = "unit", - temperatures_k: ArrayLike | None = None, - cutoff: CutoffSpec | None = None, - former_types: list[int] | None = None, - o_type: int = 8, - driver: EigenDriver = "evr", - imaginary_threshold_thz: float = 0.01, - tmp_working_directory: str | Path | None = None, - keep_dynamical_matrix: bool = False, - keep_eigenvectors: bool = False, -) -> dict[str, Any]: - r"""Minimise a structure, compute its finite-difference dynamical matrix and return the harmonic VDOS and modes. - - The harmonic counterpart of :func:`vdos_simulation`: the VDOS of the 0 K inherent structure from its normal modes, - with no MD and no statistical noise. Steps: - - 1. Minimisation at fixed cell and the dynamical matrix, both in LAMMPS (``_run_lammps_dynamical_matrix``). - 2. The atom groups (element, oxygen class, $\mathrm{Q}^n$) with :func:`classify_vibrational_groups` and the - masses, both from the minimised structure. - 3. The matrix is read with :func:`read_dynamical_matrix` and diagonalised in place with - :func:`diagonalize_dynamical_matrix`, which drops the three translations. - 4. The broadened VDOS and its group partials with :func:`compute_harmonic_vdos`, the participation ratio of every - mode with :func:`compute_participation_ratio` and, with ``temperatures_k``, the harmonic thermodynamics with - :func:`compute_vibrational_thermodynamics`. - - The structure is used as given. Preparing it (melt-quench, NPT relaxation to the target pressure) is the caller's - job; this function adds only the minimisation. The minimisation uses FIRE at fixed cell - (``min_style="fire"``, no ``box/relax``) down to ``force_tolerance``, the LAMMPS ``ftol``: the 2-norm of the global - force vector in eV/Å, not a per-atom maximum. A fixed cell leaves a residual pressure, reported in - ``"minimization"`` (``"pressure_gpa"`` and ``"mean_pressure_gpa"``; for FIRE they also hold the kinetic term of - the residual velocities), together with the iteration count, the stopping criterion and the final forces. If the - tolerance is not reached, the minimiser warns and the result is still returned; the step-0 forces of the - structure that was differentiated are in ``"dynamical_matrix"`` (``"max_force_ev_per_a"``). - - Finite differences: each entry of the matrix is a central difference of the forces with step ``displacement``. - - Imaginary modes are reported as negative frequencies in ``"mode_frequencies_thz"``. Those below - ``-imaginary_threshold_thz`` are counted in ``"diagonalization"`` (``"n_imaginary"``, with a warning that names - the asymmetry atoms); they point at an incomplete minimisation or a corrupted entry. Every negative frequency is - left out of the VDOS (``"n_imaginary_excluded"`` and ``"imaginary_weight"``) and of the thermodynamics. - - ``max_atoms`` guards against an accidental large run: above it the function raises before anything runs, and the - message gives the matrix size and the expected peak. It can be raised deliberately. - - The groups are classified on the minimised structure, the one whose modes are computed. Errors in ``cutoff``, - ``former_types`` or ``o_type`` therefore surface only after the LAMMPS runs. - - The thermodynamics is computed from the broadened total VDOS on the frequency grid, not from a sum over the modes, - with ``lowest_frequency_thz`` set to the smallest positive mode frequency, the lowest mode the box supports: the - values below its temperature are flagged as unreliable. With ``normalization="3N"`` the total is divided by 3N - first, as :func:`compute_vibrational_thermodynamics` needs a VDOS normalised to 1. On the 300-atom PMMCS glass at - 300 K with the default 0.2 THz broadening, the values differ from an exact sum over the modes by -1.3e-5 (C_V), - 8.5e-4 (S), 3.0e-5 (U) and -3.7e-4 (F), relative. The default grid starts at 0, so modes within a few - ``broadening_thz`` of 0 lose part of their weight (``"excluded_weight"`` and ``"vdos_integral"`` report it). - - Disk and memory: the matrix file takes 9 N² x 8 bytes (2.6 GB at 6000 atoms, 7.2 GB at 10,000) and is deleted once - it is read unless ``keep_dynamical_matrix``. The peak in memory is still 2 matrices, during the diagonalisation. - Without the eigenvectors, the result holds only O(M x number of labels) floats (the mode frequencies, participation - ratios and group weights) plus the VDOS curves on the frequency grid. An eigenvector-based analysis later needs - ``keep_eigenvectors=True`` or a rerun. - - Args: - structure: The structure, e.g. a quenched and NPT-relaxed glass, used as given. It is not modified. - potential: LAMMPS potential as a pandas DataFrame. - server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``), used by both LAMMPS runs. - max_atoms: Largest number of atoms accepted, a positive integer. - displacement: Finite-difference displacement in Å. - force_tolerance: FIRE stops when the 2-norm of the global force vector is below this, in eV/Å. - max_iter: Maximum number of FIRE iterations. - broadening_thz: Standard deviation of the Gaussian broadening of each mode in THz (not the FWHM). - frequency_grid_thz: Frequencies in THz at which the VDOS is evaluated, 1-D, finite and strictly increasing. - ``None``: from 0 in steps of ``broadening_thz / 5`` up to the highest mode plus 5 ``broadening_thz``. - normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``), each - short by the share of imaginary modes. - temperatures_k: Temperatures in K for the harmonic thermodynamics, a scalar or a 1-D array of finite values - >= 0. ``None`` skips it. - cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF - of the minimised structure if ``None``. - former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. - o_type: Atomic number of oxygen. - driver: LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (default), ``"evd"``, ``"evx"`` or ``"ev"``; see - :func:`diagonalize_dynamical_matrix` for their memory and time. - imaginary_threshold_thz: A mode below ``-imaginary_threshold_thz`` counts as imaginary in - ``"diagonalization"``. - tmp_working_directory: Directory for the LAMMPS runs and the matrix file. The run directories, with their - logs, input and data files, are kept. The matrix file goes to its own ``harmonic_vdos_*`` subdirectory, - which is removed once the matrix is read unless ``keep_dynamical_matrix``; nothing else in the directory is - removed. If None, every run and the matrix file are removed. - keep_dynamical_matrix: Keep the matrix file, in ``harmonic_vdos_*/dynamical_matrix.bin`` under - ``tmp_working_directory``, instead of deleting it once read. Needs a ``tmp_working_directory``. - keep_eigenvectors: Return the eigenvectors in ``"eigenvectors"``, one matrix in memory, instead of dropping - them once the VDOS, the group partials and the participation ratios are computed. - - Returns: - A dict with: - ``"frequencies_thz"``: the frequency grid in THz. - ``"vdos"``: ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels of - ``"groups"``, in 1/THz, the layout of :func:`vdos_simulation`. - ``"groups"``: the output of :func:`classify_vibrational_groups` on the minimised structure. - ``"structure"``: the minimised structure. - ``"normalization"``: the VDOS normalisation. - ``"broadening_thz"``: the broadening in THz. - ``"mode_frequencies_thz"``: the $M = 3N - 3$ mode frequencies in THz, ascending, negative for imaginary - modes. - ``"participation_ratio"``: the participation ratio of every mode, shape $(M,)$. - ``"mode_weights"``: ``{grouping: {label: w}}``, each group's $(M,)$ share of every mode, as in - :func:`compute_harmonic_vdos`. - ``"n_imaginary_excluded"``: the number of modes with a negative frequency, left out of the VDOS. - ``"imaginary_weight"``: their share of the normalisation. - ``"grid_integral"``: the trapezoid integral of the total VDOS on the grid. - ``"eigenvectors"``: the $(3N, M)$ mass-weighted eigenvectors, one mode per column; None unless - ``keep_eigenvectors``. - ``"dynamical_matrix"``: the summary of the LAMMPS dynamical-matrix run (``"matrix_path"``, - ``"matrix_bytes"``, ``"n_atoms"``, ``"displacement_a"``, ``"style"``, the step-0 ``"max_force_ev_per_a"`` - and ``"force_norm_ev_per_a"``, ``"minimization"`` and ``"wall_time_s"``). ``"matrix_path"`` is the - absolute path of the kept file; None unless ``keep_dynamical_matrix``. - ``"minimization"``: the FIRE summary: ``"converged"``, ``"stopping_criterion"``, ``"n_iterations"``, - ``"max_force_ev_per_a"``, ``"force_norm_ev_per_a"``, ``"pressure_gpa"``, ``"mean_pressure_gpa"``, the - energies and volumes. - ``"diagonalization"``: ``"asymmetry"``, ``"asymmetry_atoms"``, ``"translational_frequencies_thz"``, - ``"translational_overlap"``, ``"n_imaginary"``, ``"min_frequency_thz"`` and ``"driver"``. - ``"thermodynamics"``: the output of :func:`compute_vibrational_thermodynamics`, or None without - ``temperatures_k``. - ``"displacement_a"``: the finite-difference displacement in Å. - ``"wall_time_s"``: ``{"lammps", "diagonalization", "analysis"}`` in s: both LAMMPS runs; reading and - diagonalising the matrix; the groups, VDOS, participation ratios and thermodynamics. - - Raises: - ValueError: Before any LAMMPS run, if ``max_atoms`` is not a positive integer, the structure has more than - ``max_atoms`` atoms, the potential is empty, ``displacement`` is not positive and finite, - ``force_tolerance`` is negative, zero or not finite, ``max_iter`` is not a positive integer, - ``broadening_thz`` is not positive and finite, ``normalization`` is unknown, ``frequency_grid_thz`` is not - 1-D, finite and strictly increasing with at least 2 points, ``temperatures_k`` is not finite and >= 0, - ``driver`` is unknown, ``imaginary_threshold_thz`` is not >= 0, or ``keep_dynamical_matrix`` is True - without a ``tmp_working_directory``. After the LAMMPS runs, if ``cutoff``, ``former_types`` or ``o_type`` - is invalid for :func:`classify_vibrational_groups`. - RuntimeError: If a LAMMPS run fails or the matrix file is missing or has the wrong size. - - Warns: - UserWarning: If the minimisation stops on a criterion other than the force or energy tolerance, the - diagonalisation finds imaginary modes or dropped modes that are not translations, or a caller's - ``frequency_grid_thz`` is coarser than ``broadening_thz / 2``. - - Example: - ```pycon - >>> out = harmonic_vdos_simulation(glass, potential, temperatures_k=[300.0]) # doctest: +SKIP - >>> out["minimization"]["converged"], out["diagonalization"]["asymmetry"] # doctest: +SKIP - >>> out["diagonalization"]["n_imaginary"], out["grid_integral"] # doctest: +SKIP - >>> out["vdos"]["oxygen"]["O_BO"] # doctest: +SKIP - >>> out["thermodynamics"]["heat_capacity_kb_per_atom"] # doctest: +SKIP - - ``` - """ - _harmonic_simulation_settings( - structure, - potential, - max_atoms, - displacement, - force_tolerance, - max_iter, - broadening_thz, - frequency_grid_thz, - normalization, - temperatures_k, - driver, - imaginary_threshold_thz, - tmp_working_directory=tmp_working_directory, - keep_dynamical_matrix=keep_dynamical_matrix, - ) - with ( - contextlib.nullcontext(tempfile.mkdtemp(prefix="harmonic_vdos_", dir=tmp_working_directory)) - if keep_dynamical_matrix - else tempfile.TemporaryDirectory(prefix="harmonic_vdos_", dir=tmp_working_directory) - ) as matrix_dir: - start = time.perf_counter() - minimised, summary = _run_lammps_dynamical_matrix( - structure, - potential, - Path(matrix_dir) / _HARMONIC_MATRIX_FILE, - displacement=displacement, - minimize=True, - minimize_kwargs={ - "min_style": "fire", - "pressure": None, - "force_tolerance": force_tolerance, - "max_iter": max_iter, - }, - server_kwargs=server_kwargs, - tmp_working_directory=tmp_working_directory, - ) - lammps_s = time.perf_counter() - start - start = time.perf_counter() - groups = classify_vibrational_groups(minimised, cutoff, former_types, o_type) - masses = minimised.get_masses() - groups_s = time.perf_counter() - start - start = time.perf_counter() - matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) - if not keep_dynamical_matrix: - summary = {**summary, "matrix_path": None} - # Diagonalised in place; dropping the only reference afterwards frees the overwritten matrix, so the peak is the - # matrix plus its eigenvectors and only the eigenvectors stay. - modes = diagonalize_dynamical_matrix( - matrix, - masses=masses, - overwrite_matrix=True, - eigenvectors=True, - driver=driver, - imaginary_threshold_thz=imaginary_threshold_thz, - ) - del matrix - diagonalization_s = time.perf_counter() - start - - start = time.perf_counter() - mode_frequencies, eigenvectors = modes["frequencies_thz"], modes.pop("eigenvectors") - vdos = compute_harmonic_vdos( - mode_frequencies, - eigenvectors, - groups=groups, - frequency_grid_thz=frequency_grid_thz, - broadening_thz=broadening_thz, - normalization=normalization, - ) - participation_ratio = compute_participation_ratio(eigenvectors, masses) - if not keep_eigenvectors: - # The last reference to the eigenvector buffer: dropping it frees one matrix before the thermodynamics. - eigenvectors = None - thermodynamics = None - if temperatures_k is not None: - total = vdos["vdos"]["total"] if normalization == "unit" else vdos["vdos"]["total"] / (3 * len(minimised)) - thermodynamics = compute_vibrational_thermodynamics( - vdos["frequencies_thz"], - total, - temperatures_k, - lowest_frequency_thz=float(mode_frequencies[mode_frequencies > 0].min()), - ) - analysis_s = groups_s + time.perf_counter() - start - - return { - "frequencies_thz": vdos["frequencies_thz"], - "vdos": vdos["vdos"], - "groups": groups, - "structure": minimised, - "normalization": normalization, - "broadening_thz": vdos["broadening_thz"], - "mode_frequencies_thz": mode_frequencies, - "participation_ratio": participation_ratio, - "mode_weights": vdos["mode_weights"], - "n_imaginary_excluded": vdos["n_imaginary_excluded"], - "imaginary_weight": vdos["imaginary_weight"], - "grid_integral": vdos["grid_integral"], - "eigenvectors": eigenvectors, - "dynamical_matrix": summary, - "minimization": summary["minimization"], - "diagonalization": { - key: modes[key] - for key in ( - "asymmetry", - "asymmetry_atoms", - "translational_frequencies_thz", - "translational_overlap", - "n_imaginary", - "min_frequency_thz", - "driver", - ) - }, - "thermodynamics": thermodynamics, - "displacement_a": summary["displacement_a"], - "wall_time_s": {"lammps": lammps_s, "diagonalization": diagonalization_s, "analysis": analysis_s}, - } diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/__init__.py b/amorphouspy/src/amorphouspy/properties/vibrational/__init__.py new file mode 100644 index 00000000..899e187e --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/__init__.py @@ -0,0 +1,56 @@ +"""Vibrational properties of glass systems: vibrational density of states and related quantities. + +Frequencies in this module are ordinary frequencies in THz (not angular frequencies) unless stated otherwise. + +Author: Achraf Atila (achraf.atila@bam.de) +""" + +from amorphouspy.properties.vibrational._common import VdosNormalization +from amorphouspy.properties.vibrational.classification import classify_vibrational_groups +from amorphouspy.properties.vibrational.debye import compute_debye_level, compute_reduced_vdos +from amorphouspy.properties.vibrational.dynamical_matrix import ( + DynamicalMatrixStyle, + EigenDriver, + diagonalize_dynamical_matrix, + read_dynamical_matrix, +) +from amorphouspy.properties.vibrational.harmonic import ( + HarmonicNormalization, + compute_harmonic_vdos, + compute_participation_ratio, +) +from amorphouspy.properties.vibrational.harmonic_simulation import harmonic_vdos_simulation +from amorphouspy.properties.vibrational.simulation import vdos_simulation +from amorphouspy.properties.vibrational.thermodynamics import compute_vibrational_thermodynamics +from amorphouspy.properties.vibrational.units import FrequencyUnit, convert_frequency +from amorphouspy.properties.vibrational.vacf import ( + VacfNormalization, + compute_partial_vacf, + compute_vacf_from_velocities, +) +from amorphouspy.properties.vibrational.vdos import VdosWindow, compute_partial_vdos, compute_vdos_from_velocities + +__all__ = [ + "DynamicalMatrixStyle", + "EigenDriver", + "FrequencyUnit", + "HarmonicNormalization", + "VacfNormalization", + "VdosNormalization", + "VdosWindow", + "classify_vibrational_groups", + "compute_debye_level", + "compute_harmonic_vdos", + "compute_partial_vacf", + "compute_partial_vdos", + "compute_participation_ratio", + "compute_reduced_vdos", + "compute_vacf_from_velocities", + "compute_vdos_from_velocities", + "compute_vibrational_thermodynamics", + "convert_frequency", + "diagonalize_dynamical_matrix", + "harmonic_vdos_simulation", + "read_dynamical_matrix", + "vdos_simulation", +] diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/_common.py b/amorphouspy/src/amorphouspy/properties/vibrational/_common.py new file mode 100644 index 00000000..348d138f --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/_common.py @@ -0,0 +1,64 @@ +"""Constants and group helpers shared by the vibrational modules.""" + +from typing import Literal + +import numpy as np +from numpy.typing import NDArray + +VdosNormalization = Literal["unit", "3N", "none"] +# Target size of one chunk of velocities; the complex spectrum of a chunk is about the same size. +_CHUNK_BYTES = 64 * 2**20 +_N_COMPONENTS = 3 + + +def _is_real_number(value: object) -> bool: + """True for a Python or numpy real scalar; False for bool, None, strings and arrays.""" + return isinstance(value, int | float | np.integer | np.floating) and not isinstance(value, bool) + + +def _validate_selection(indices: NDArray, n_atoms: int, name: str) -> NDArray[np.intp]: + selection = np.asarray(indices) + if selection.ndim != 1 or selection.size == 0 or not np.issubdtype(selection.dtype, np.integer): + msg = f"{name} must be a non-empty 1-D array of integer atom positions." + raise ValueError(msg) + if selection.min() < 0 or selection.max() >= n_atoms: + msg = f"{name} contains positions outside [0, {n_atoms})." + raise ValueError(msg) + if np.unique(selection).size != selection.size: + msg = f"{name} contains duplicate positions." + raise ValueError(msg) + return selection.astype(np.intp) + + +def _membership(selections: dict[str, NDArray] | None, n_atoms: int) -> NDArray[np.float64]: + """Membership matrix (n_atoms, n_cols): one column of ones for ``None``, else one 0/1 column per selection.""" + if selections is None: + return np.ones((n_atoms, 1)) + membership = np.zeros((n_atoms, len(selections))) + for column, (name, indices) in enumerate(selections.items()): + membership[_validate_selection(indices, n_atoms, name), column] = 1.0 + return membership + + +def _group_selections(groups: dict[str, dict[str, NDArray]]) -> tuple[list[tuple[str, str]], dict[str, NDArray]]: + """Flatten ``{grouping: {label: indices}}`` into ordered keys and selections named after each group.""" + keys = [(grouping, label) for grouping, labels in groups.items() for label in labels] + if not keys: + msg = "groups contains no labels." + raise ValueError(msg) + return keys, {f"groups[{g!r}][{label!r}]": groups[g][label] for g, label in keys} + + +def _columns_by_group( + groups: dict[str, dict[str, NDArray]], keys: list[tuple[str, str]], columns: NDArray[np.float64] +) -> dict[str, dict[str, NDArray[np.float64]]]: + """Split the result columns back into the ``{grouping: {label: array}}`` layout of ``groups``.""" + partial: dict[str, dict[str, NDArray[np.float64]]] = {grouping: {} for grouping in groups} + for column, (grouping, label) in enumerate(keys): + partial[grouping][label] = np.ascontiguousarray(columns[:, column]) + return partial + + +_MIN_GRID_POINTS = 2 +_MATRIX_NDIM = 2 +_N_TRANSLATIONS = 3 diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/_trajectory.py b/amorphouspy/src/amorphouspy/properties/vibrational/_trajectory.py new file mode 100644 index 00000000..7257755f --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/_trajectory.py @@ -0,0 +1,170 @@ +"""Velocity-trajectory validation, chunking and power accumulation for the VDOS and VACF.""" + +import numpy as np +import scipy.fft +from numpy.typing import NDArray + +from amorphouspy.properties.vibrational import _common +from amorphouspy.properties.vibrational._common import _N_COMPONENTS, _is_real_number + +_VELOCITY_NDIM = 3 # (n_frames, n_atoms, 3) +_MIN_FRAMES = 2 +# Internal (centre-of-mass-free) kinetic sum at or below this fraction of the uncentred one counts as no internal +# motion. It sits well above the rounding noise of removing the centre of mass from a uniform translation. +_ZERO_SPECTRUM_RTOL = 1e-10 + + +def _atoms_per_chunk(n_frames: int, itemsize: int) -> int: + return max(1, _common._CHUNK_BYTES // (n_frames * _N_COMPONENTS * itemsize)) # noqa: SLF001 + + +def _validate_trajectory(velocities: NDArray, masses: NDArray, dt_fs: float) -> tuple[NDArray, NDArray[np.float64]]: + velocities = np.asarray(velocities) + masses = np.asarray(masses, dtype=np.float64) + if velocities.ndim != _VELOCITY_NDIM or velocities.shape[2] != _N_COMPONENTS or velocities.shape[1] == 0: + msg = f"velocities must have shape (n_frames, n_atoms, 3) with n_atoms >= 1, got {velocities.shape}." + raise ValueError(msg) + if not (np.issubdtype(velocities.dtype, np.floating) or np.issubdtype(velocities.dtype, np.integer)): + msg = f"velocities must be a real numeric array, got dtype {velocities.dtype}." + raise ValueError(msg) + n_frames, n_atoms, _ = velocities.shape + if masses.shape != (n_atoms,): + msg = f"masses must have shape ({n_atoms},) to match velocities, got {masses.shape}." + raise ValueError(msg) + if n_frames < _MIN_FRAMES: + msg = f"At least 2 frames are needed, got {n_frames}." + raise ValueError(msg) + if not _is_real_number(dt_fs) or not np.isfinite(dt_fs) or dt_fs <= 0: + msg = f"dt_fs must be positive and finite, got {dt_fs}." + raise ValueError(msg) + if not np.all(np.isfinite(masses) & (masses > 0)): + msg = "All masses must be positive and finite." + raise ValueError(msg) + return velocities, masses + + +def _trajectory_statistics( + velocities: NDArray, masses: NDArray[np.float64], weights: NDArray[np.float64] | None, *, remove_com: bool +) -> tuple[NDArray[np.float64] | None, float, float]: + """One read of all atoms: centre-of-mass velocity per frame and the trapezoid integral of the total spectrum. + + The integral of sum_i m_i |rfft(w v_i)|^2 over the rfft grid follows from Parseval's theorem without any FFT: + (dnu / 2) * (n_frames * K - K_top), with K = sum_t w_t^2 sum_i m_i |v_i(t)|^2 and K_top the mass-weighted power + of the last frequency bin of the windowed signal, which only enters for an odd number of frames. ``weights=None`` + means w = 1. With centre-of-mass removal both sums are reduced by the centre-of-mass term, since + sum_i m_i (v_i - v_com) = 0. Non-finite velocities make the unwindowed sum non-finite, so the finiteness check + costs nothing extra; the finiteness and zero-spectrum checks use the unwindowed sums. + + Returns: + The centre-of-mass velocity ``(n_frames, 3)`` (``None`` without removal), the integral divided by dnu / 2, + and the unwindowed sum_t sum_i m_i |v_i(t) - v_com(t)|^2 (``v_com = 0`` without removal). + """ + n_frames, n_atoms, _ = velocities.shape + chunk = _atoms_per_chunk(n_frames, velocities.itemsize) + odd = n_frames % 2 == 1 + phase = np.arange(n_frames) * (2 * np.pi * ((n_frames - 1) // 2) / n_frames) + cos_t, sin_t = np.cos(phase), np.sin(phase) + if weights is not None: + cos_t, sin_t = cos_t * weights, sin_t * weights + kinetic = np.zeros(n_frames) # sum_i m_i |v_i(t)|^2 per frame + momentum = np.zeros((n_frames, _N_COMPONENTS)) + top_momentum = np.zeros((2, _N_COMPONENTS)) + raw_sq = 0.0 + top_sq = 0.0 + for start in range(0, n_atoms, chunk): + block = velocities[:, start : start + chunk] + block_masses = masses[start : start + chunk] + if weights is None: + block_sq = float(np.einsum("tia,tia->i", block, block, dtype=np.float64) @ block_masses) + else: + frame_sq = np.einsum("tia,tia->ti", block, block, dtype=np.float64) @ block_masses + block_sq = float(frame_sq.sum()) + kinetic += frame_sq + if not np.isfinite(block_sq): + msg = "velocities contain NaN or inf (or values too large to square)." + raise ValueError(msg) + raw_sq += block_sq + momentum += np.einsum("tia,i->ta", block, block_masses, dtype=np.float64) + if odd: + top = np.stack( + [ + np.einsum("t,tia->ia", cos_t, block, dtype=np.float64), + np.einsum("t,tia->ia", sin_t, block, dtype=np.float64), + ] + ) + top_sq += float(np.einsum("cia,cia,i->", top, top, block_masses)) + top_momentum += np.einsum("cia,i->ca", top, block_masses) + if not raw_sq > 0: + msg = "The velocity spectrum is zero (all velocities are zero)." + raise ValueError(msg) + window_sq = None if weights is None else weights**2 + if not remove_com: + weighted_sq = raw_sq if window_sq is None else float(window_sq @ kinetic) + return None, n_frames * weighted_sq - top_sq, raw_sq + total_mass = masses.sum() + com_velocity = momentum / total_mass + centred_sq = raw_sq - total_mass * float(np.sum(com_velocity**2)) + if centred_sq <= _ZERO_SPECTRUM_RTOL * raw_sq: + msg = "The velocity spectrum is zero after removing the centre-of-mass velocity (no internal motion)." + raise ValueError(msg) + weighted_sq = centred_sq + if window_sq is not None: + weighted_sq = float(window_sq @ kinetic) - total_mass * float(window_sq @ np.sum(com_velocity**2, axis=1)) + return com_velocity, n_frames * weighted_sq - (top_sq - float(np.sum(top_momentum**2)) / total_mass), centred_sq + + +def _accumulate_power( + velocities: NDArray, + masses: NDArray[np.float64], + com_velocity: NDArray[np.float64] | None, + membership: NDArray, + weights: NDArray[np.float64] | None, + n_fft: int | None = None, +) -> NDArray[np.float64]: + """Sum m_i * sum_a |rfft(w * (v_ia - v_com,a))|^2 over the atoms of each column of ``membership`` (n_atoms, n_cols). + + Only atoms that belong to at least one column are transformed. A contiguous range of atoms is sliced as a view; + other selections are gathered chunk by chunk. float32 velocities are transformed in single precision (complex64) + and float64 or other input in double precision, with the same forward, unnormalised DFT as ``np.fft.rfft``; + per-atom powers are combined in float64. The window ``weights`` (``None`` for none) is applied per chunk in the + working precision, never in place on a view of the input. ``n_fft`` zero-pads each signal to that length before + the transform (``None``: no padding), and chunks are sized for the padded length. + """ + n_frames = velocities.shape[0] + n_transform = n_frames if n_fft is None else n_fft + work = np.float32 if velocities.dtype == np.float32 else np.float64 + needed = np.flatnonzero(membership.any(axis=1)) + contiguous = needed[-1] - needed[0] + 1 == needed.size + chunk = _atoms_per_chunk(n_transform, np.dtype(work).itemsize) + com_work = None if com_velocity is None else com_velocity.astype(work)[:, None, :] + window_work = None if weights is None else weights.astype(work)[:, None, None] + power = np.zeros((n_transform // 2 + 1, membership.shape[1])) + for start in range(0, needed.size, chunk): + atoms = needed[start : start + chunk] + is_view = False + if contiguous: + block = velocities[:, atoms[0] : atoms[-1] + 1] + if com_work is not None: + block = np.subtract(block, com_work, dtype=work) + elif block.dtype != work: + block = block.astype(work) + else: + is_view = True + else: + block = velocities[:, atoms].astype(work, copy=False) + if com_work is not None: + block -= com_work + if window_work is not None: + if is_view: + block = block * window_work + else: + block *= window_work + # scipy.fft transforms float32 natively; np.fft computes in double internally and needs ~3x the memory. + spectrum = np.ascontiguousarray(scipy.fft.rfft(block, n=n_fft, axis=0)) + del block + # |z|^2 = Re(z)^2 + Im(z)^2 summed over x, y, z through a real view, without full-size temporaries. + parts = spectrum.view(work).reshape(spectrum.shape[0], spectrum.shape[1], 2 * _N_COMPONENTS) + atom_power = np.einsum("fik,fik->fi", parts, parts) + del spectrum, parts + power += atom_power @ (masses[atoms, None] * membership[atoms]) + return power diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/classification.py b/amorphouspy/src/amorphouspy/properties/vibrational/classification.py new file mode 100644 index 00000000..82cfac70 --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/classification.py @@ -0,0 +1,113 @@ +"""Classification of atoms into element, oxygen and Qn groups for partial spectra.""" + +from typing import TYPE_CHECKING + +import numpy as np + +from amorphouspy.properties.structural.all import ( + _build_cutoff_map, + _classify_elements, + _former_oxygen_pair_cutoffs, + _network_former_types, +) +from amorphouspy.properties.structural.qn import CutoffSpec, compute_qn_and_classify, compute_qn_per_atom +from amorphouspy.properties.structural.rdf import compute_rdf + +if TYPE_CHECKING: + from ase import Atoms + + +def _positions_by_label(labels: dict[int, str], id_to_position: dict[int, int]) -> dict[str, np.ndarray]: + """Group atom IDs by label and convert them to sorted int64 positions.""" + grouped: dict[str, list[int]] = {} + for atom_id, label in labels.items(): + grouped.setdefault(label, []).append(id_to_position[atom_id]) + return {label: np.sort(np.array(positions, dtype=np.int64)) for label, positions in sorted(grouped.items())} + + +def classify_vibrational_groups( + structure: "Atoms", + cutoff: CutoffSpec | None = None, + former_types: list[int] | None = None, + o_type: int = 8, +) -> dict[str, dict[str, np.ndarray]]: + """Label every atom by element, oxygen class and network-former Q^n for partial VDOS. + + Oxygen classes and Q^n come from :func:`compute_qn_and_classify` and :func:`compute_qn_per_atom`. Missing + ``cutoff`` and ``former_types`` are derived as in :func:`analyze_structure`: formers are the glass formers and + intermediates present, and each former-O cutoff is the first minimum of its RDF (``r_max=10.0``, + ``n_bins=500``), with the same fallbacks. + + Args: + structure: The atomic structure as ASE object. Atom IDs are read from the ``"id"`` array if present, + else taken as 1-based indices; the returned indices are always 0-based positions in ``structure``. + cutoff: Former-O cutoff in Å, either a scalar or a per-pair dict ``{(z_i, z_j): r_cut}``. Derived from + the RDF if ``None``. + former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. + o_type: Atomic number of oxygen. + + Returns: + A dict with three groupings, each mapping a label to a sorted int64 array of 0-based positions: + ``"element"``: element symbol, e.g. ``"Si"``, ``"O"``, ``"Na"``. + ``"oxygen"``: ``"O_BO"``, ``"O_NBO"``, ``"O_free"``, ``"O_tri"``. + ``"qn"``: former symbol and number of bridging oxygens, e.g. ``"Si_Q3"``, ``"B_Q4"``. + Labels without atoms are omitted. Without oxygen, ``"oxygen"`` and ``"qn"`` are empty; with oxygen but + no formers, ``"qn"`` is empty and every oxygen is ``"O_free"``. + + Raises: + ValueError: If the ``"id"`` array contains duplicate IDs. + + Example: + ```pycon + >>> from ase import Atoms + >>> d = 1.6 + >>> positions = [[10, 10, 10], [10 + 2 * d, 10, 10], [10 + d, 10, 10], + ... [10 - d, 10, 10], [10, 10 + d, 10], [10, 10, 10 + d], + ... [10 + 3 * d, 10, 10], [10 + 2 * d, 10 + d, 10], [10 + 2 * d, 10, 10 + d]] + >>> dimer = Atoms("Si2O7", positions=positions, cell=[30, 30, 30], pbc=True) + >>> groups = classify_vibrational_groups(dimer, cutoff=2.0, former_types=[14]) + >>> groups["element"]["Si"].tolist(), groups["oxygen"]["O_BO"].tolist(), groups["qn"]["Si_Q1"].tolist() + ([0, 1], [2], [0, 1]) + + ``` + """ + n_atoms = len(structure) + if "id" in structure.arrays: + atom_ids = structure.arrays["id"].astype(np.int64) + else: + atom_ids = np.arange(1, n_atoms + 1, dtype=np.int64) + if len(np.unique(atom_ids)) != n_atoms: + msg = "The 'id' array contains duplicate atom IDs." + raise ValueError(msg) + id_to_position = {int(atom_id): position for position, atom_id in enumerate(atom_ids)} + + symbols = np.array(structure.get_chemical_symbols()) + groups: dict[str, dict[str, np.ndarray]] = { + "element": {str(sym): np.flatnonzero(symbols == sym).astype(np.int64) for sym in sorted(set(symbols))}, + "oxygen": {}, + "qn": {}, + } + atomic_numbers = structure.get_atomic_numbers() + if o_type not in atomic_numbers: + return groups + + unique_z = np.unique(atomic_numbers) + type_map, network_formers, _modifiers, _oxygen_present = _classify_elements(unique_z) + if former_types is None: + former_types = _network_former_types(type_map, network_formers) + if not former_types: + groups["oxygen"] = {"O_free": np.flatnonzero(atomic_numbers == o_type).astype(np.int64)} + return groups + if cutoff is None: + r, rdfs, _cumcn = compute_rdf(structure, r_max=10.0, n_bins=500) + cutoff_map = _build_cutoff_map(unique_z, type_map, former_types, [o_type], r, rdfs) + cutoff = _former_oxygen_pair_cutoffs(former_types, o_type, type_map, cutoff_map) + + _total_qn, _partial_qn, oxygen_classes = compute_qn_and_classify(structure, cutoff, former_types, o_type) + qn_per_atom = compute_qn_per_atom(structure, cutoff, former_types, o_type) + id_to_symbol = {int(atom_id): str(sym) for atom_id, sym in zip(atom_ids, symbols, strict=True)} + groups["oxygen"] = _positions_by_label({aid: f"O_{cls}" for aid, cls in oxygen_classes.items()}, id_to_position) + groups["qn"] = _positions_by_label( + {aid: f"{id_to_symbol[aid]}_Q{n}" for aid, n in qn_per_atom.items()}, id_to_position + ) + return groups diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/debye.py b/amorphouspy/src/amorphouspy/properties/vibrational/debye.py new file mode 100644 index 00000000..35da2d0e --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/debye.py @@ -0,0 +1,245 @@ +"""Debye level and reduced VDOS g(nu) / nu^2.""" + +from typing import TYPE_CHECKING, Any + +import numpy as np +from numpy.typing import NDArray +from scipy.constants import Boltzmann, atomic_mass, h + +from amorphouspy.atoms.neighbors import cell_perpendicular_heights +from amorphouspy.properties.vibrational._common import VdosNormalization, _is_real_number + +if TYPE_CHECKING: + from ase import Atoms + +# 1 GPa / (1 g/cm^3) = 1e9 Pa / 1e3 kg/m^3, in m^2/s^2. +_GPA_PER_G_CM3_TO_M2_S2 = 1e6 + + +def compute_debye_level( + structure: "Atoms", + bulk_modulus_gpa: float, + shear_modulus_gpa: float, + *, + normalization: VdosNormalization = "unit", +) -> dict[str, float]: + r"""Compute the Debye level of the reduced VDOS from elastic moduli and the density of a structure. + + The isotropic elastic continuum with bulk modulus $B$, shear modulus $G$ and mass density $\rho$ has the + longitudinal and transverse sound velocities + + $$v_L = \sqrt{\frac{B + 4G/3}{\rho}}, \quad v_T = \sqrt{\frac{G}{\rho}},$$ + + in m/s for $B$, $G$ in GPa and $\rho$ in g/cm$^3$ (1 GPa / (1 g/cm$^3$) = $10^6$ m$^2$/s$^2$). With the number + density $n$, the Debye frequency and temperature are + + $$\nu_D^3 = \frac{9 n}{4 \pi \left(1 / v_L^3 + 2 / v_T^3\right)}, \quad \theta_D = \frac{h \nu_D}{k_B},$$ + + and the Debye VDOS $g_D(\nu) = 3 \nu^2 / \nu_D^3$ ($\nu \le \nu_D$, normalised to 1) gives the Debye level + $g_D(\nu) / \nu^2 = 3 / \nu_D^3$ in THz$^{-3}$, the low-frequency limit of the reduced VDOS of an isotropic solid. + For ``"3N"`` the level is $3N$ times larger, matching a VDOS that integrates to $3N$. + + The moduli are taken as given: no fit of the VDOS is made, so without moduli there is no Debye level. Use moduli of + the same model and state as the VDOS, e.g. ``elastic_simulation(...)["moduli"]["B"]`` and ``["G"]``, which are in + GPa. Only the masses (``structure.get_masses()``, in amu) and the cell volume enter $\rho$ and $n$; the positions + are not used. + + The lowest frequency the periodic box supports is $\nu_\mathrm{min} = v_T / L_\mathrm{max}$, the transverse + acoustic mode whose wavelength is the largest perpendicular cell height $L_\mathrm{max}$ (the edge $L$ of a cubic + box). The box has no acoustic modes below it, so the reduced VDOS there does not represent the bulk glass. Taking + $L_\mathrm{max}$ as the longest wavelength is exact for orthogonal boxes and assumes a cell that is not strongly + skewed otherwise. + + Args: + structure: Periodic structure as an ASE object, with a 3-D cell of positive volume. + bulk_modulus_gpa: Bulk modulus $B$ in GPa. + shear_modulus_gpa: Shear modulus $G$ in GPa. + normalization: ``"unit"`` (default) or ``"3N"``, the normalisation of the VDOS the level is compared with, as + in :func:`compute_vdos_from_velocities`. ``"none"`` is rejected: a power spectral density has no Debye + level. + + Returns: + A dict of floats: + ``"longitudinal_velocity_m_s"`` and ``"transverse_velocity_m_s"``: $v_L$ and $v_T$ in m/s. + ``"debye_frequency_thz"``: $\nu_D$ in THz. + ``"debye_temperature_k"``: $\theta_D$ in K. + ``"debye_level_thz-3"``: $3 / \nu_D^3$ (``"unit"``) or $9N / \nu_D^3$ (``"3N"``) in THz$^{-3}$. + ``"lowest_box_frequency_thz"``: $\nu_\mathrm{min} = v_T / L_\mathrm{max}$ in THz. + ``"density_g_cm3"``: $\rho$ in g/cm$^3$. + ``"number_density_per_a3"``: $n$ in atoms/Å$^3$. + + Raises: + ValueError: If a modulus is not positive and finite, ``normalization`` is not ``"unit"`` or ``"3N"``, + ``structure`` has no atoms, is not periodic in all three directions, or its cell volume is not positive. + + Example: + ```pycon + >>> from ase import Atoms + >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3 + >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2) + >>> round(debye["density_g_cm3"], 3), round(debye["transverse_velocity_m_s"]) + (2.2, 3766) + >>> round(debye["debye_frequency_thz"], 2), round(debye["debye_temperature_k"]) + (10.4, 499) + >>> round(debye["lowest_box_frequency_thz"], 3) + 1.056 + + ``` + """ + for name, modulus in (("bulk_modulus_gpa", bulk_modulus_gpa), ("shear_modulus_gpa", shear_modulus_gpa)): + if not (_is_real_number(modulus) and np.isfinite(modulus) and modulus > 0): + msg = f"{name} must be positive and finite, got {modulus}." + raise ValueError(msg) + if normalization not in ("unit", "3N"): + msg = ( + f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N' " + "(a power spectral density has no Debye level)." + ) + raise ValueError(msg) + n_atoms = len(structure) + if n_atoms == 0: + msg = "structure contains no atoms." + raise ValueError(msg) + if not np.all(structure.pbc): + msg = "structure must be periodic in all three directions." + raise ValueError(msg) + volume_a3 = float(structure.cell.volume) + if not volume_a3 > 0: + msg = "structure must have a 3-D cell with positive volume." + raise ValueError(msg) + + # amu -> g and A^3 -> cm^3. + density_g_cm3 = float(structure.get_masses().sum()) * atomic_mass * 1e3 / (volume_a3 * 1e-24) + number_density_per_a3 = n_atoms / volume_a3 + longitudinal_modulus_gpa = bulk_modulus_gpa + 4 * shear_modulus_gpa / 3 + v_longitudinal = float(np.sqrt(longitudinal_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2)) + v_transverse = float(np.sqrt(shear_modulus_gpa / density_g_cm3 * _GPA_PER_G_CM3_TO_M2_S2)) + # Number density in m^-3 and velocities in m/s give the Debye frequency in Hz. + debye_frequency_hz = ( + 9 * number_density_per_a3 * 1e30 / (4 * np.pi * (1 / v_longitudinal**3 + 2 / v_transverse**3)) + ) ** (1 / 3) + debye_frequency_thz = debye_frequency_hz * 1e-12 + scale = 1.0 if normalization == "unit" else 3.0 * n_atoms + largest_height_a = float(cell_perpendicular_heights(structure.cell.array).max()) + return { + "longitudinal_velocity_m_s": v_longitudinal, + "transverse_velocity_m_s": v_transverse, + "debye_frequency_thz": debye_frequency_thz, + "debye_temperature_k": h * debye_frequency_hz / Boltzmann, + "debye_level_thz-3": scale * 3 / debye_frequency_thz**3, + "lowest_box_frequency_thz": v_transverse / (largest_height_a * 1e-10) * 1e-12, + "density_g_cm3": density_g_cm3, + "number_density_per_a3": number_density_per_a3, + } + + +def compute_reduced_vdos( + frequencies_thz: NDArray, + vdos: NDArray, + *, + peak_range_thz: tuple[float, float] = (0.5, 5.0), + debye: dict[str, float] | None = None, +) -> dict[str, Any]: + r"""Compute the reduced VDOS $g(\nu) / \nu^2$, the boson-peak position and its height over the Debye level. + + The boson peak is the raw maximum of $g(\nu) / \nu^2$ within ``peak_range_thz``, with no smoothing or fit, so pass + a block-averaged VDOS (e.g. a Hann-windowed mean over blocks); the maximum of a single noisy spectrum is mostly + noise. The default range of 0.5 to 5 THz is a generic choice for oxide glasses (silica peaks near 1 THz); set it + for the system at hand. A maximum on the first or last bin of the range (``"peak_at_range_edge"``) means no peak + was found inside it, e.g. a reduced VDOS that rises steeply towards zero frequency. + + With ``debye`` (the output of :func:`compute_debye_level`), the peak height is also divided by the Debye level, and + every frequency below the lowest one the box supports is marked unreliable. The level is only compared, never + fitted: without ``debye`` none of these keys is returned. The VDOS and ``debye`` must use the same normalisation + (``"unit"`` or ``"3N"``). + + Any VDOS works, including a partial VDOS, but the Debye comparison is meaningful for the total VDOS only. + + Args: + frequencies_thz: Frequencies in THz, 1-D, non-negative and strictly increasing, e.g. from + :func:`compute_vdos_from_velocities`. + vdos: VDOS on ``frequencies_thz``, 1-D of the same length, in 1/THz. + peak_range_thz: ``(low, high)`` in THz, both ends included, in which the boson peak is searched. The + frequency 0 is never part of the range. + debye: The dict returned by :func:`compute_debye_level`, or ``None`` (default). + + Returns: + A dict with: + ``"reduced_vdos"``: $g(\nu) / \nu^2$ in THz$^{-3}$, a float64 array of the input length, NaN at + $\nu = 0$. + ``"boson_peak_thz"``: frequency of the maximum within ``peak_range_thz``, in THz. + ``"boson_peak_height"``: reduced VDOS at that frequency, in THz$^{-3}$. + ``"peak_at_range_edge"``: True if the maximum is on the first or last bin of the range. + With ``debye`` also: + ``"debye_level_thz-3"``: the Debye level from ``debye``. + ``"boson_peak_over_debye"``: ``boson_peak_height`` divided by the Debye level. + ``"reliable"``: boolean array, True where the frequency is at or above the lowest box frequency. + ``"peak_below_box_limit"``: True if the boson peak lies below the lowest box frequency. + + Raises: + ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length, contain NaN or inf, + a frequency is negative, the frequencies are not strictly increasing, ``peak_range_thz`` does not satisfy + ``low < high``, or the range contains no frequency above 0. + + Example: + ```pycon + >>> from ase import Atoms + >>> silica = Atoms("Si1000O2000", cell=[35.661] * 3, pbc=True) # 2.2 g/cm^3 + >>> debye = compute_debye_level(silica, bulk_modulus_gpa=36.7, shear_modulus_gpa=31.2) + >>> frequencies_thz = np.linspace(0.0, 10.0, 201) + >>> excess = 1 + np.exp(-0.5 * ((frequencies_thz - 1.2) / 0.4) ** 2) + >>> vdos = debye["debye_level_thz-3"] * frequencies_thz**2 * excess # Debye VDOS with an excess at 1.2 THz + >>> result = compute_reduced_vdos(frequencies_thz, vdos, debye=debye) + >>> round(result["boson_peak_thz"], 3), result["peak_at_range_edge"], round(result["boson_peak_over_debye"], 3) + (1.2, False, 2.0) + >>> bool(np.isnan(result["reduced_vdos"][0])), result["reduced_vdos"].shape + (True, (201,)) + >>> round(float(frequencies_thz[result["reliable"]][0]), 3), result["peak_below_box_limit"] + (1.1, False) + + ``` + """ + frequencies_thz = np.asarray(frequencies_thz, dtype=np.float64) + vdos = np.asarray(vdos, dtype=np.float64) + if frequencies_thz.ndim != 1 or vdos.shape != frequencies_thz.shape: + msg = ( + "frequencies_thz and vdos must be 1-D arrays of the same length, " + f"got shapes {frequencies_thz.shape} and {vdos.shape}." + ) + raise ValueError(msg) + if not (np.all(np.isfinite(frequencies_thz)) and np.all(np.isfinite(vdos))): + msg = "frequencies_thz and vdos must not contain NaN or inf." + raise ValueError(msg) + if np.any(frequencies_thz < 0): + msg = "frequencies_thz must not be negative." + raise ValueError(msg) + if np.any(np.diff(frequencies_thz) <= 0): + msg = "frequencies_thz must be strictly increasing." + raise ValueError(msg) + low, high = peak_range_thz + if not low < high: + msg = f"peak_range_thz must satisfy low < high, got {peak_range_thz}." + raise ValueError(msg) + + positive = frequencies_thz > 0 + reduced = np.full_like(vdos, np.nan) + np.divide(vdos, frequencies_thz**2, out=reduced, where=positive) + in_range = np.flatnonzero(positive & (frequencies_thz >= low) & (frequencies_thz <= high)) + if in_range.size == 0: + msg = f"peak_range_thz {peak_range_thz} contains no frequency bins above 0 THz." + raise ValueError(msg) + peak = in_range[np.argmax(reduced[in_range])] + result: dict[str, Any] = { + "reduced_vdos": reduced, + "boson_peak_thz": float(frequencies_thz[peak]), + "boson_peak_height": float(reduced[peak]), + "peak_at_range_edge": bool(peak in (in_range[0], in_range[-1])), + } + if debye is not None: + level = float(debye["debye_level_thz-3"]) + lowest_thz = float(debye["lowest_box_frequency_thz"]) + result["debye_level_thz-3"] = level + result["boson_peak_over_debye"] = result["boson_peak_height"] / level + result["reliable"] = frequencies_thz >= lowest_thz + result["peak_below_box_limit"] = bool(frequencies_thz[peak] < lowest_thz) + return result diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py b/amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py new file mode 100644 index 00000000..b69c9abf --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/dynamical_matrix.py @@ -0,0 +1,432 @@ +"""Harmonic route: reading and diagonalising the LAMMPS dynamical matrix.""" + +import math +import warnings +from pathlib import Path +from typing import Any, Literal + +import numpy as np +import scipy.linalg +from numpy.typing import ArrayLike, NDArray +from scipy.constants import atomic_mass, e + +from amorphouspy.properties.vibrational import _common +from amorphouspy.properties.vibrational._common import _MATRIX_NDIM, _N_TRANSLATIONS + +DynamicalMatrixStyle = Literal["regular", "eskm"] + +# LAMMPS writes ``eskm`` as ``regular`` times this literal (measured: ratio 9648.5 to 2e-16 on LAMMPS 29 Aug 2024). +# The CODATA value e N_A / 10 = 9648.533 is 3.4e-6 higher; dividing by it would not recover the ``regular`` matrix. +_ESKM_PER_REGULAR = 9648.5 +_DYNAMICAL_MATRIX_STYLES = ("regular", "eskm") + + +def _check_value_count(count: int, n_atoms: int, source: str) -> None: + """Raise if ``count`` values cannot form the (3 n_atoms, 3 n_atoms) matrix; name the n_atoms they imply.""" + expected = 9 * n_atoms**2 + if count == expected: + return + msg = f"{source} holds {count} values, expected 9 N² = {expected} for n_atoms={n_atoms}" + side = math.isqrt(count // 9) + if count and count % 9 == 0 and side**2 == count // 9: + msg += f"; {count} values imply n_atoms={side}" + raise ValueError(msg + ".") + + +def read_dynamical_matrix( + path: str | Path, + n_atoms: int, + *, + binary: bool = True, + style: DynamicalMatrixStyle = "regular", +) -> NDArray[np.float64]: + r"""Read a dynamical-matrix file written by the LAMMPS ``dynamical_matrix`` command. + + The dynamical matrix is the mass-weighted Hessian + + $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}, \quad + \Phi_{i\alpha, j\beta} = \frac{\partial^2 E}{\partial r_{i\alpha}\, \partial r_{j\beta}},$$ + + with $E$ the potential energy, $r_{i\alpha}$ the coordinates and $m_i$ the masses. It is returned in eV/Ų/amu + (LAMMPS ``regular`` in metal units). An eigenvalue $\lambda$ of $D$ gives the angular frequency + $\omega = \sqrt{\lambda}$ and the frequency $\nu = \sqrt{\lambda} / (2\pi)$, where + $\sqrt{1\ \mathrm{eV/Å^2/amu}}$ corresponds to $\nu = 15.633$ THz. Row and column $3i + \alpha$ belong to atom + $i$ (0-based, the LAMMPS atom id minus one) and $\alpha \in \{x, y, z\}$ ($0, 1, 2$), so the atom order is the + LAMMPS id order. For files written by ``_run_lammps_dynamical_matrix`` that is the order of the atoms in the + structure. + + The matrix is returned as written, NOT symmetrised. A finite-difference matrix is symmetric only to the + difference error, and a larger asymmetry $\max|D - D^\mathsf{T}| / \max|D|$ flags corrupted entries, for example + a pair that crosses a cutoff with a force jump during a displacement. The asymmetry is therefore left for the + caller to measure before symmetrising. + + File formats (verified on LAMMPS 29 Aug 2024): + + - ``binary=True`` (``binary yes``): raw float64 in native byte order, no header, exactly $9 N^2 \times 8$ bytes. + It is read with ``np.fromfile`` and reshaped without a copy. + - ``binary=False`` (``binary no``): three values per line in ``%.8f``, one line per atom of a row, so each matrix + row spans $N$ lines. Eight fixed decimals limit the precision to $5 \times 10^{-9}$ eV/Ų/amu absolute. The + text is parsed with ``np.loadtxt``, which is about six times faster than ``np.fromfile(sep=" ")`` here. + + With ``style="eskm"`` the file holds the matrix in 10 J/mol/Ų/(g/mol); it is divided in place by 9648.5, the + factor LAMMPS uses (the CODATA value $e N_\mathrm{A} / 10 = 9648.533$ differs by $3.4 \times 10^{-6}$), and + returned in eV/Ų/amu. + + Memory: the result is one array of $9 N^2 \times 8$ bytes, 2.6 GB at 6000 atoms and 7.2 GB at 10,000. A binary + read needs nothing more. Parsing text peaks at about 2.2 times the matrix (numpy allocations measured at 1000 and + 2000 atoms), about 16 GB at 10,000 atoms. Non-finite values are checked in blocks of rows, so the check adds at + most ``_CHUNK_BYTES / 8`` bytes. + + Args: + path: The dynamical-matrix file. + n_atoms: Number of atoms $N$ in the structure the matrix was computed on. + binary: True for a file written with ``binary yes``, False for ``binary no``. + style: The LAMMPS style the file was written with, ``"regular"`` or ``"eskm"``. + + Returns: + The $(3N, 3N)$ dynamical matrix in eV/Ų/amu, float64, C-contiguous and writable. + + Raises: + ValueError: If ``n_atoms`` is not a positive integer, ``style`` is unknown, the file does not hold $9 N^2$ + values (the size is checked before a binary file is read), or the matrix contains NaN or inf. + FileNotFoundError: If ``path`` does not exist. + + Example: + ```pycon + >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP + >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP + >>> asymmetry = np.abs(matrix - matrix.T).max() / np.abs(matrix).max() # doctest: +SKIP + ``` + """ + if isinstance(n_atoms, bool) or not isinstance(n_atoms, int | np.integer) or n_atoms < 1: + msg = f"n_atoms must be a positive integer, got {n_atoms!r}." + raise ValueError(msg) + if style not in _DYNAMICAL_MATRIX_STYLES: + msg = f"Unknown style {style!r}; allowed styles are {list(_DYNAMICAL_MATRIX_STYLES)}." + raise ValueError(msg) + n_dof = 3 * int(n_atoms) + if binary: + n_bytes = Path(path).stat().st_size + itemsize = np.dtype(np.float64).itemsize + if n_bytes % itemsize: + msg = f"The binary file {path} has {n_bytes} bytes, not a whole number of float64 values." + raise ValueError(msg) + _check_value_count(n_bytes // itemsize, n_atoms, f"The binary file {path}") + values = np.fromfile(path, dtype=np.float64) + else: + values = np.loadtxt(path, dtype=np.float64).ravel() + _check_value_count(values.size, n_atoms, f"The text file {path}") + matrix = values.reshape(n_dof, n_dof) + rows_per_chunk = max(1, _common._CHUNK_BYTES // (n_dof * matrix.itemsize)) # noqa: SLF001 + for start in range(0, n_dof, rows_per_chunk): + if not np.isfinite(matrix[start : start + rows_per_chunk]).all(): + msg = ( + f"The dynamical matrix in {path} contains NaN or inf " + f"in rows {start} to {min(start + rows_per_chunk, n_dof) - 1}." + ) + raise ValueError(msg) + if style == "eskm": + matrix /= _ESKM_PER_REGULAR + return matrix + + +# Frequency in THz of an eigenvalue of 1 eV/Ų/amu: sqrt(e / (1e-20 atomic_mass)) / (2 pi) / 1e12 = 15.633. +_THZ_PER_SQRT_EV_PER_A2_AMU = math.sqrt(e / (1e-20 * atomic_mass)) / (2 * math.pi) / 1e12 +EigenDriver = Literal["ev", "evd", "evr", "evx"] +_EIGH_DRIVERS = ("ev", "evd", "evr", "evx") +# Smallest squared projection of a dropped mode on the rigid translations that counts as a translation. +_MIN_TRANSLATIONAL_OVERLAP = 0.9 + + +def _eigenvalues_to_thz(eigenvalues: NDArray[np.float64]) -> NDArray[np.float64]: + return np.sign(eigenvalues) * np.sqrt(np.abs(eigenvalues)) * _THZ_PER_SQRT_EV_PER_A2_AMU + + +def _validate_dynamical_matrix_input( + matrix: NDArray, + masses: ArrayLike | None, + *, + overwrite_matrix: bool, + eigenvectors: bool, + driver: str, + imaginary_threshold_thz: float, +) -> NDArray[np.float64] | None: + """Check everything except finiteness; return the masses as float64 (or None).""" + if matrix.ndim != _MATRIX_NDIM or matrix.shape[0] != matrix.shape[1]: + msg = f"matrix must be a square 2-D array, got shape {matrix.shape}." + raise ValueError(msg) + n_dof = matrix.shape[0] + if n_dof % 3 or n_dof < 2 * 3: + msg = f"matrix must be (3N, 3N) with N >= 2 atoms, got size {n_dof}." + raise ValueError(msg) + if matrix.dtype != np.float64: + msg = f"matrix must be float64 (a cast would copy it), got {matrix.dtype}." + raise ValueError(msg) + if overwrite_matrix and not (matrix.flags.writeable and (matrix.flags.c_contiguous or matrix.flags.f_contiguous)): + msg = "overwrite_matrix=True needs a writable C- or F-contiguous matrix; otherwise it would be copied." + raise ValueError(msg) + _validate_eigh_options(driver, imaginary_threshold_thz) + if masses is None: + return None + if not eigenvectors: + msg = "masses are only used for the translational overlap, which needs eigenvectors=True." + raise ValueError(msg) + masses = np.asarray(masses, dtype=np.float64) + if masses.shape != (n_dof // 3,) or not np.all(np.isfinite(masses) & (masses > 0)): + msg = f"masses must be {n_dof // 3} positive finite values, one per atom, got shape {masses.shape}." + raise ValueError(msg) + return masses + + +def _validate_eigh_options(driver: str, imaginary_threshold_thz: float) -> None: + """Raise for an unknown LAPACK driver or a threshold that is not >= 0.""" + if driver not in _EIGH_DRIVERS: + msg = f"Unknown driver {driver!r}; allowed drivers are {list(_EIGH_DRIVERS)}." + raise ValueError(msg) + if not imaginary_threshold_thz >= 0: + msg = f"imaginary_threshold_thz must be >= 0, got {imaginary_threshold_thz!r}." + raise ValueError(msg) + + +def _row_blocks(n_dof: int) -> range: + return range(0, n_dof, max(1, _common._CHUNK_BYTES // (n_dof * np.dtype(np.float64).itemsize))) # noqa: SLF001 + + +def _asymmetry(matrix: NDArray[np.float64]) -> tuple[float, tuple[int, int] | None]: + """Relative asymmetry max|D - D^T| / max|D| and the atom pair of the worst entry; raise on NaN or inf. + + Each block of rows [s, e) is compared over the columns from s on with the matching columns, so every entry and + every (r, c) pair is seen (the diagonal block twice) and no temporary exceeds one block. + """ + n_dof = matrix.shape[0] + rows = _row_blocks(n_dof) + max_abs, max_diff, worst = 0.0, 0.0, (0, 0) + for start in rows: + stop = min(start + rows.step, n_dof) + top, left = matrix[start:stop, start:], matrix[start:, start:stop].T + block_max = (float(np.abs(top).max()), float(np.abs(left).max())) # NaN and inf propagate through max + if not all(math.isfinite(value) for value in block_max): + msg = f"The dynamical matrix contains NaN or inf in rows or columns {start} to {stop - 1}." + raise ValueError(msg) + max_abs = max(max_abs, *block_max) + diff = top - left + np.abs(diff, out=diff) + flat = int(diff.argmax()) + if diff.flat[flat] > max_diff: + max_diff = float(diff.flat[flat]) + row, column = divmod(flat, diff.shape[1]) + worst = (start + row, start + column) + if not max_diff: + return 0.0, None + first, second = sorted((worst[0] // 3, worst[1] // 3)) + return max_diff / max_abs, (first, second) + + +def _symmetrise_in_place(work: NDArray[np.float64]) -> None: + """Replace ``work`` by (work + work^T) / 2 block by block, without a full-size temporary. + + The block of rows [s, e) writes rows [s, e) and columns [s, e) from s on; later blocks only touch rows and + columns from e on, so no entry is read after it was written. The diagonal block of the average is symmetric, so + its two writes agree. + """ + n_dof = work.shape[0] + rows = _row_blocks(n_dof) + for start in rows: + stop = min(start + rows.step, n_dof) + average = work[start:stop, start:] + work[start:, start:stop].T + average *= 0.5 + work[start:stop, start:] = average + work[start:, start:stop] = average.T + + +def diagonalize_dynamical_matrix( + matrix: NDArray[np.float64], + *, + masses: ArrayLike | None = None, + overwrite_matrix: bool = False, + eigenvectors: bool = True, + driver: EigenDriver = "evr", + imaginary_threshold_thz: float = 0.01, +) -> dict[str, Any]: + r"""Symmetrise and diagonalise a mass-weighted dynamical matrix and drop the three translational modes. + + The input is the dynamical matrix of :func:`read_dynamical_matrix`, + + $$D_{i\alpha, j\beta} = \frac{\Phi_{i\alpha, j\beta}}{\sqrt{m_i m_j}}$$ + + in eV/Ų/amu, $(3N, 3N)$, row and column $3i + \alpha$ for atom $i$ and direction $\alpha$. An eigenvalue + $\lambda$ gives the frequency $\nu = \sqrt{\lambda} / (2\pi)$, which is + $\nu = 15.633\ \mathrm{THz} \times \sqrt{\lambda / (\mathrm{eV/Å^2/amu})}$ (the factor is + $\sqrt{e / (10^{-20}\, m_\mathrm{u})} / (2\pi) / 10^{12}$ from ``scipy.constants``). An imaginary mode, + $\lambda < 0$, is reported as a negative frequency $\nu = -\sqrt{|\lambda|} / (2\pi)$. + + Steps: + + 1. Asymmetry of the raw matrix, $\max|D - D^\mathsf{T}| / \max|D|$, and the atom pair $(i, j)$, $i \le j$, of the + worst entry. A finite-difference matrix is symmetric only to the difference error. A pair that crosses a cutoff + where the force jumps during a displacement $h$ (an energy-shifted pair style such as the PMMCS ``pedone`` term + at 5.5 Å) gets a spurious term of about jump / (2h) in one entry but not in its transpose, so a large asymmetry + points at such corrupted entries, and the atom pair tells where. It is measured before symmetrising, in blocks + of rows, together with the check for NaN and inf. + 2. Symmetrisation to $(D + D^\mathsf{T}) / 2$ in place, in the same blocks. With ``overwrite_matrix=False`` this + works on one copy of the input; with True on the input itself. + 3. Diagonalisation with ``scipy.linalg.eigh(..., overwrite_a=True, driver=driver)``. This deliberately replaces + the ``numpy.linalg.eigh`` of the original plan: numpy always copies the matrix and uses the divide-and-conquer + driver, which with eigenvectors needs four matrices besides the input, against one for ``"evr"`` (see Memory). + 4. The three translational modes are dropped: the three eigenvalues of smallest $|\lambda|$, which are three + consecutive ones of the ascending spectrum. With ``masses``, each dropped mode's squared projection on the span + of the mass-weighted rigid translations $t_\alpha = \sqrt{m_i}\, e_\alpha / \sqrt{\sum_i m_i}$ is reported; it + is 1 for a pure translation. A value below 0.9 warns: a soft mode is mixed in, or the translations are not the + smallest $|\lambda|$ (a sum-rule violation that lifts them, or an isolated cluster, whose rotations are zero + modes too). + 5. Kept frequencies below ``-imaginary_threshold_thz`` count as imaginary and warn, with the asymmetry atoms. + + Memory (benchmark: a 3000-atom spring network, n = 9000, OpenBLAS 0.3.34 on 12 Apple M-series cores; peak + allocations, confirmed by the peak process RSS; scaled as $n^2$ to $N$ = 6000 and 10,000 atoms, where one matrix + is 2.6 GB and 7.2 GB). Totals include the input matrix; ``overwrite_matrix=False`` adds one copy: + + - eigenvalues only, any driver: 1 matrix, 2.6 / 7.2 GB (2 matrices, 5.2 / 14.4 GB without overwrite). + - ``"evr"`` with eigenvectors: 2 matrices (the eigenvectors are a new array), 5.2 / 14.4 GB (7.8 / 21.6 GB). + - ``"evx"`` with eigenvectors: the same as ``"evr"``. + - ``"evd"`` with eigenvectors: 3 matrices (the eigenvectors overwrite the input, plus two of workspace), + 7.8 / 21.6 GB (10.4 / 28.8 GB). + - ``"ev"`` with eigenvectors: 1 matrix (the eigenvectors overwrite the input), 2.6 / 7.2 GB (5.2 / 14.4 GB). + - For comparison, ``numpy.linalg.eigh``: 5 matrices, 13 / 36 GB. + + The asymmetry and symmetrisation passes add up to about 0.2 GB of row blocks (``_CHUNK_BYTES`` each), independent + of $N$, and LAPACK $O(n)$ workspace. + + Time at n = 9000, with eigenvectors (scaled as $n^3$, by 8 and 37, to 6000 and 10,000 atoms): ``"evr"`` 33 s + (4.4 min, 20 min), ``"evd"`` 27 s (3.6 min, 16 min; 66 s in a first, disturbed run), ``"evx"`` 316 s (42 min, + 3.2 h), ``"ev"`` 339 s (45 min, 3.5 h). Eigenvalues only: about 10 s with every driver (1.3 min, 6 min). + ``"evr"`` is the default: within about 20 % of the fastest, ``"evd"``, at one matrix less, and memory is the limit + at 10,000 atoms. + + With ``overwrite_matrix=True`` the input's contents are undefined afterwards (LAPACK overwrites it); with + ``"ev"`` or ``"evd"`` the returned eigenvectors share its memory. Only a writable C- or F-contiguous array can + be used without a copy, which is checked. + + Args: + matrix: The $(3N, 3N)$ mass-weighted dynamical matrix in eV/Ų/amu, float64 (no cast is made, since a cast + would copy it). Not symmetrised. + masses: Atomic masses in amu, shape $(N,)$, in the order of the matrix rows. Only used for the + translational overlap, so it needs ``eigenvectors=True``. + overwrite_matrix: Symmetrise and diagonalise ``matrix`` itself instead of a copy, saving one matrix of memory. + Its contents are undefined afterwards. + eigenvectors: Also return the eigenvectors of the kept modes. + driver: The LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (MRRR), ``"evd"`` (divide and conquer), + ``"ev"`` (QR iteration) or ``"evx"`` (bisection and inverse iteration). + imaginary_threshold_thz: Kept frequencies below minus this value, in THz, count as imaginary. + + Returns: + A dictionary with: + ``"frequencies_thz"``: the $3N - 3$ kept frequencies in THz, ascending, negative for imaginary modes. + ``"eigenvectors"``: $(3N, 3N - 3)$ array whose orthonormal columns are the kept modes, in the order of + ``"frequencies_thz"`` (a view of the LAPACK output), or None with ``eigenvectors=False``. + ``"translational_frequencies_thz"``: the three dropped frequencies in THz, ascending. + ``"translational_overlap"``: the dropped modes' squared projections on the rigid translations, shape + (3,), or None without ``masses``. + ``"asymmetry"``: $\max|D - D^\mathsf{T}| / \max|D|$ of the raw matrix (0.0 if exactly symmetric). + ``"asymmetry_atoms"``: the atom pair $(i, j)$, $i \le j$, of the largest $|D - D^\mathsf{T}|$, or None if + the matrix is exactly symmetric. $i = j$ when the worst entry lies in an atom's own $3 \times 3$ block; + after a cutoff crossing that atom is one of the crossing pair. + ``"n_imaginary"``: the number of kept frequencies below ``-imaginary_threshold_thz``. + ``"min_frequency_thz"``: the lowest kept frequency in THz. + ``"n_atoms"``: $N$. + ``"driver"``: the LAPACK driver used. + + Raises: + ValueError: If ``matrix`` is not square and 2-D, its size is not $3N$ with $N \ge 2$, it is not float64, it + contains NaN or inf, or with ``overwrite_matrix=True`` it is read-only or not C- or F-contiguous; if + ``masses`` does not hold $N$ positive finite values or is given with ``eigenvectors=False``; if + ``driver`` is unknown or ``imaginary_threshold_thz`` is negative. + + Warns: + UserWarning: If a dropped mode overlaps the rigid translations by less than 0.9, or if any kept frequency is + imaginary. + + Example: + ```pycon + >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP + >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP + >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP + ... matrix, masses=minimised.get_masses(), overwrite_matrix=True + ... ) + >>> modes["asymmetry"], modes["n_imaginary"], modes["translational_overlap"] # doctest: +SKIP + + ``` + """ + matrix = np.asarray(matrix) + masses = _validate_dynamical_matrix_input( + matrix, + masses, + overwrite_matrix=overwrite_matrix, + eigenvectors=eigenvectors, + driver=driver, + imaginary_threshold_thz=imaginary_threshold_thz, + ) + n_dof = matrix.shape[0] + asymmetry, asymmetry_atoms = _asymmetry(matrix) + work = matrix if overwrite_matrix else np.array(matrix) + _symmetrise_in_place(work) + # LAPACK works on Fortran-ordered arrays; f2py copies anything else. The transpose of a C-ordered symmetric + # matrix is the same matrix in Fortran order, so passing it avoids the copy. + lapack_input = work.T if work.flags.c_contiguous else work + del work + result = scipy.linalg.eigh( + lapack_input, overwrite_a=True, check_finite=False, driver=driver, eigvals_only=not eigenvectors + ) + del lapack_input + eigenvalues, vectors = result if eigenvectors else (result, None) + + # The eigenvalues are ascending, so the three of smallest |λ| are three consecutive ones: the window + # [first, first + 3) with the smallest max |λ| (the first such window on an exact tie). + magnitudes = np.abs(eigenvalues) + first = int(np.argmin(np.maximum(np.maximum(magnitudes[:-2], magnitudes[1:-1]), magnitudes[2:]))) + dropped = slice(first, first + _N_TRANSLATIONS) + translational_frequencies = _eigenvalues_to_thz(eigenvalues[dropped]) + frequencies = _eigenvalues_to_thz(np.delete(eigenvalues, dropped)) + + translational_overlap = None + if vectors is not None: + if masses is not None: + weights = np.sqrt(masses) / math.sqrt(masses.sum()) + projections = np.einsum("i,iam->am", weights, vectors[:, dropped].reshape(-1, 3, _N_TRANSLATIONS)) + translational_overlap = (projections**2).sum(axis=0) + if translational_overlap.min() < _MIN_TRANSLATIONAL_OVERLAP: + warnings.warn( + f"The dropped modes at {np.array2string(translational_frequencies, precision=4)} THz overlap the " + f"rigid translations by only {np.array2string(translational_overlap, precision=3)} (< " + f"{_MIN_TRANSLATIONAL_OVERLAP}): a soft mode is mixed in, or the translations are not the three " + "smallest |eigenvalues|.", + UserWarning, + stacklevel=2, + ) + # Instead of copying the (3N, 3N - 3) kept columns, shift the `first` columns before the translations (the + # modes below them, usually the few imaginary ones) three to the right, over the translations. Every column + # after the translations is already in place, so the kept modes are then columns 3 onwards, in their original + # order: a view. numpy buffers the overlapping assignment, which costs `first` columns, not the matrix. + vectors[:, _N_TRANSLATIONS : first + _N_TRANSLATIONS] = vectors[:, :first] + vectors = vectors[:, _N_TRANSLATIONS:] + + n_imaginary = int(np.count_nonzero(frequencies < -imaginary_threshold_thz)) + min_frequency = float(frequencies[0]) + if n_imaginary: + warnings.warn( + f"{n_imaginary} imaginary mode(s) below -{imaginary_threshold_thz} THz; the most negative is " + f"{min_frequency:.4g} THz. Raw-matrix asymmetry {asymmetry:.3g}, largest between atoms {asymmetry_atoms}.", + UserWarning, + stacklevel=2, + ) + return { + "frequencies_thz": frequencies, + "eigenvectors": vectors, + "translational_frequencies_thz": translational_frequencies, + "translational_overlap": translational_overlap, + "asymmetry": asymmetry, + "asymmetry_atoms": asymmetry_atoms, + "n_imaginary": n_imaginary, + "min_frequency_thz": min_frequency, + "n_atoms": n_dof // 3, + "driver": driver, + } diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py b/amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py new file mode 100644 index 00000000..fd6d2033 --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/harmonic.py @@ -0,0 +1,363 @@ +"""Harmonic route: VDOS, partials and participation ratio from eigenvectors.""" + +import math +import warnings +from collections.abc import Iterator +from typing import Any, Literal + +import numpy as np +from numpy.typing import ArrayLike, NDArray + +from amorphouspy.properties.vibrational import _common +from amorphouspy.properties.vibrational._common import ( + _MATRIX_NDIM, + _MIN_GRID_POINTS, + _N_COMPONENTS, + _N_TRANSLATIONS, + _columns_by_group, + _group_selections, + _is_real_number, + _membership, +) + +HarmonicNormalization = Literal["unit", "3N"] +# Default grid of compute_harmonic_vdos: step sigma / 5, from 0 to the highest mode plus 5 sigma. +_GAUSSIAN_STEPS_PER_SIGMA = 5 +_GAUSSIAN_TAIL_SIGMAS = 5.0 +# A caller grid warns when a spacing exceeds sigma / 2 by more than this; np.fft.rfftfreq spacings carry ulp noise. +_GRID_SPACING_RTOL = 1e-9 + + +def _mode_atom_weights(eigenvectors: NDArray[np.float64], n_atoms: int) -> Iterator[tuple[slice, NDArray[np.float64]]]: + """Yield ``(columns, a)`` over blocks of modes: a[i, k] = sum_alpha e[3i + alpha, k]^2, shape (n_atoms, block). + + Each block holds about ``_CHUNK_BYTES`` of eigenvectors. The per-atom reshape of a column block is a view for C- and + F-ordered input, so only ``a`` (a third of the block) is allocated: never a squared copy of the eigenvectors or an + (n_atoms, n_modes) array. :func:`compute_participation_ratio` reuses this code, not the weights of a + :func:`compute_harmonic_vdos` call: its second pass over the eigenvectors costs memory bandwidth, not memory. + """ + n_modes = eigenvectors.shape[1] + step = max(1, _common._CHUNK_BYTES // (eigenvectors.shape[0] * eigenvectors.itemsize)) # noqa: SLF001 + for start in range(0, n_modes, step): + columns = slice(start, min(start + step, n_modes)) + block = eigenvectors[:, columns].reshape(n_atoms, _N_COMPONENTS, -1) + yield columns, np.einsum("iak,iak->ik", block, block) + + +def _validate_harmonic_inputs( + frequencies_thz: ArrayLike, + eigenvectors: NDArray | None, + groups: dict[str, dict[str, NDArray]] | None, + broadening_thz: float, + normalization: str, +) -> tuple[NDArray[np.float64], NDArray[np.float64] | None, int]: + """Check the inputs; return the frequencies as float64, the eigenvectors and N (rows / 3, else (M + 3) // 3).""" + frequencies = np.asarray(frequencies_thz, dtype=np.float64) + if frequencies.ndim != 1 or frequencies.size == 0 or not np.all(np.isfinite(frequencies)): + msg = f"frequencies_thz must be a non-empty 1-D array of finite values, got shape {frequencies.shape}." + raise ValueError(msg) + n_modes = frequencies.size + _validate_broadening_options(broadening_thz, normalization) + if eigenvectors is None: + if groups is not None: + msg = "groups need eigenvectors: the group weights come from the eigenvector components." + raise ValueError(msg) + if normalization == "3N" and n_modes % _N_COMPONENTS: + msg = f"normalization='3N' without eigenvectors needs 3N - 3 frequencies; {n_modes} is not a multiple of 3." + raise ValueError(msg) + return frequencies, None, (n_modes + _N_TRANSLATIONS) // _N_COMPONENTS + eigenvectors = np.asarray(eigenvectors) + if eigenvectors.ndim != _MATRIX_NDIM or eigenvectors.dtype != np.float64: + msg = ( + "eigenvectors must be a 2-D float64 array (a cast would copy it), " + f"got {eigenvectors.ndim}-D {eigenvectors.dtype}." + ) + raise ValueError(msg) + if n_modes % _N_COMPONENTS or eigenvectors.shape != (n_modes + _N_TRANSLATIONS, n_modes): + msg = f"eigenvectors must have shape (3N, 3N - 3) to match {n_modes} frequencies, got {eigenvectors.shape}." + raise ValueError(msg) + return frequencies, eigenvectors, eigenvectors.shape[0] // _N_COMPONENTS + + +def _validate_broadening_options(broadening_thz: float, normalization: str) -> None: + """Raise for an unknown normalisation or a broadening that is not positive and finite.""" + if normalization not in ("unit", "3N"): + msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N'." + raise ValueError(msg) + if not _is_real_number(broadening_thz) or not np.isfinite(broadening_thz) or broadening_thz <= 0: + msg = f"broadening_thz must be positive and finite, got {broadening_thz!r}." + raise ValueError(msg) + + +def _validate_frequency_grid(frequency_grid_thz: ArrayLike) -> NDArray[np.float64]: + """Return a caller's grid as float64; raise unless it is 1-D, finite, strictly increasing, with >= 2 points.""" + grid = np.asarray(frequency_grid_thz, dtype=np.float64) + if grid.ndim != 1 or grid.size < _MIN_GRID_POINTS or not np.all(np.isfinite(grid)) or not np.all(np.diff(grid) > 0): + msg = "frequency_grid_thz must be a 1-D, finite, strictly increasing array with at least 2 points." + raise ValueError(msg) + return grid + + +def _harmonic_grid( + frequency_grid_thz: ArrayLike | None, frequencies: NDArray[np.float64], broadening_thz: float +) -> NDArray[np.float64]: + """The caller's grid after checks, or the default grid with step sigma / 5 whose last point is >= max + 5 sigma.""" + if frequency_grid_thz is None: + step = broadening_thz / _GAUSSIAN_STEPS_PER_SIGMA + top = max(float(frequencies.max()), 0.0) + _GAUSSIAN_TAIL_SIGMAS * broadening_thz + return np.arange(math.ceil(top / step) + 1) * step + grid = _validate_frequency_grid(frequency_grid_thz) + spacing = float(np.diff(grid).max()) + if spacing > 0.5 * broadening_thz * (1 + _GRID_SPACING_RTOL): + warnings.warn( + f"The largest grid spacing, {spacing:.4g} THz, exceeds half the broadening ({broadening_thz:.4g} THz): " + "the Gaussians are undersampled and the trapezoid integral is inaccurate.", + UserWarning, + stacklevel=3, + ) + return grid + + +def compute_harmonic_vdos( + frequencies_thz: ArrayLike, + eigenvectors: NDArray[np.float64] | None = None, + *, + groups: dict[str, dict[str, NDArray]] | None = None, + frequency_grid_thz: ArrayLike | None = None, + broadening_thz: float = 0.2, + normalization: HarmonicNormalization = "unit", +) -> dict[str, Any]: + r"""Compute the harmonic VDOS and its group partials from the modes of :func:`diagonalize_dynamical_matrix`. + + The input is the $M = 3N - 3$ kept modes: frequencies $\nu_k$ in THz (negative for imaginary modes) and the + mass-weighted eigenvectors $e_k$, orthonormal columns with row $3i + \alpha$ for atom $i$ and direction $\alpha$. + The weight of atom $i$ in mode $k$ and of a group $G$ are + + $$a_{ik} = \sum_\alpha e_{3i+\alpha,k}^2, \quad \sum_i a_{ik} = 1, \qquad w_{kG} = \sum_{i \in G} a_{ik},$$ + + and the VDOS and its partials are sums of unit-area Gaussians of standard deviation $\sigma$ (``broadening_thz``), + + $$g(\nu) = c \sum_{k:\, \nu_k \ge 0} G_\sigma(\nu - \nu_k), \quad + g_G(\nu) = c \sum_{k:\, \nu_k \ge 0} w_{kG}\, G_\sigma(\nu - \nu_k), \quad + G_\sigma(x) = \frac{e^{-x^2 / 2\sigma^2}}{\sigma \sqrt{2\pi}}.$$ + + Partials within a grouping that covers every atom once (e.g. ``"element"``) sum to the total, and the classes of + a grouping that covers a subset sum to that subset's partial (e.g. the ``"oxygen"`` classes to ``"O"``). + + Normalisation: + + - ``"unit"`` (default): $c = 1/M$, so the total integrates to 1 over all modes. + - ``"3N"``: $c = 3N/M$, so the total integrates to $3N$, as with the VACF route, although the three translations + were dropped: each kept mode carries $3N/M$ instead of 1. + + What is not counted: + + - Imaginary modes ($\nu_k < 0$, any negative value, unlike the ``imaginary_threshold_thz`` of + :func:`diagonalize_dynamical_matrix`) are excluded from all sums and counted in ``"n_imaginary_excluded"``. They + stay in $M$, so the integral falls short of 1 (or $3N$) by their share, ``"imaginary_weight"`` $= n/M$. + - Gaussian weight below or above the grid is not renormalised either: the default grid starts at 0, so modes within + a few $\sigma$ of 0 lose part of their weight. ``"grid_integral"`` is the trapezoid integral of the total on the + grid. A grid spacing up to $\sigma/2$ integrates a Gaussian to better than $10^{-10}$. + + Completeness: summed over all $3N$ modes, $\sum_k w_{kG} = 3 N_G$. The translations are the mass-weighted rigid + shifts $\sqrt{m_i / m_\mathrm{tot}}$, so over the kept modes it is $3 N_G - 3 m_G / m_\mathrm{tot}$, with $N_G$ + the atom count and $m_G$ the mass of the group. + + Relation to the VACF route: in mode $k$, atom $i$ carries the share $a_{ik}$ of the mode's kinetic energy, since + its mass-weighted velocity is proportional to $e_{3i+\alpha,k}$. A partial of + :func:`compute_partial_vdos` is the group's share of the mass-weighted velocity power, so with every mode at the + same mean kinetic energy (classical equipartition in a harmonic solid) the two routes use the same partial + definition, and the same normalisations. + + The eigenvectors are not checked for orthonormality, which would cost a full $(M, M)$ matrix product; columns that + are not orthonormal break $\sum_i a_{ik} = 1$ and the sums above. + + Memory: the eigenvectors are read in blocks of columns of ``_CHUNK_BYTES`` (64 MB), each reduced at once to the + groups, and the Gaussians are evaluated in blocks of modes of the same size. Neither a squared copy of the + eigenvectors nor an $(N, M)$ weight array is built. + + Args: + frequencies_thz: The $M = 3N - 3$ mode frequencies in THz, negative for imaginary modes, e.g. + ``"frequencies_thz"`` of :func:`diagonalize_dynamical_matrix`. + eigenvectors: The $(3N, M)$ float64 eigenvectors with orthonormal columns in the order of + ``frequencies_thz``, e.g. ``"eigenvectors"`` of :func:`diagonalize_dynamical_matrix` (any memory order; + no cast or copy is made). Only needed for ``groups``, and for ``"3N"`` it gives $N$. + groups: ``{grouping: {label: indices}}`` with 0-based atom positions in the order of the matrix rows, e.g. the + output of :func:`classify_vibrational_groups` on the minimised structure. Needs ``eigenvectors``. + frequency_grid_thz: The frequencies in THz at which the VDOS is evaluated: 1-D, finite, strictly increasing, + at least 2 points. ``None`` (default): from 0 in steps of exactly $\sigma/5$ up to the first point at or + above $\max(\nu_k, 0) + 5\sigma$. + broadening_thz: The standard deviation $\sigma$ of the Gaussians in THz (not the FWHM, which is + $2.355\sigma$). + normalization: ``"unit"`` or ``"3N"``, see above. + + Returns: + A dictionary with: + ``"frequencies_thz"``: the grid in THz. + ``"vdos"``: ``{"total": g}`` and, with ``groups``, ``{grouping: {label: g_G}}`` (the layout of + :func:`vdos_simulation`), each a float64 array on the grid in 1/THz. + ``"mode_weights"``: ``{grouping: {label: w}}`` with the $(M,)$ weights $w_{kG}$ of every mode, + imaginary ones included; only with ``groups``. + ``"n_modes"``: $M$. + ``"n_imaginary_excluded"``: the number of modes with $\nu_k < 0$. + ``"imaginary_weight"``: their share of the normalisation, ``n_imaginary_excluded / n_modes``. + ``"grid_integral"``: the trapezoid integral of the total on the grid. + ``"broadening_thz"``: $\sigma$ in THz. + ``"normalization"``: ``"unit"`` or ``"3N"``. + + Raises: + ValueError: If ``frequencies_thz`` is empty, not 1-D or not finite; ``eigenvectors`` is not 2-D float64 or + not $(M + 3, M)$ with $M$ a multiple of 3; ``broadening_thz`` is not positive and finite; + ``normalization`` is unknown, or ``"3N"`` without eigenvectors and $M$ not a multiple of 3; + ``groups`` is given without ``eigenvectors``, has no labels or has invalid indices; + ``frequency_grid_thz`` is not 1-D, finite and strictly increasing with at least 2 points. + + Warns: + UserWarning: If the largest spacing of ``frequency_grid_thz`` exceeds $\sigma/2$. + + Example: + ```pycon + >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP + >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP + >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP + ... matrix, masses=minimised.get_masses(), overwrite_matrix=True + ... ) + >>> groups = classify_vibrational_groups(minimised) # doctest: +SKIP + >>> vdos = compute_harmonic_vdos( # doctest: +SKIP + ... modes["frequencies_thz"], modes["eigenvectors"], groups=groups, broadening_thz=0.1 + ... ) + >>> vdos["vdos"]["oxygen"]["O_NBO"], vdos["grid_integral"], vdos["n_imaginary_excluded"] # doctest: +SKIP + + ``` + """ + frequencies, eigenvectors, n_atoms = _validate_harmonic_inputs( + frequencies_thz, eigenvectors, groups, broadening_thz, normalization + ) + grid = _harmonic_grid(frequency_grid_thz, frequencies, broadening_thz) + n_modes = frequencies.size + kept = frequencies >= 0 + + # Column 0 weighs every mode by 1 (the total); with groups, one column per group label follows. + weights = np.ones((n_modes, 1)) + keys: list[tuple[str, str]] = [] + if groups is not None and eigenvectors is not None: + keys, selections = _group_selections(groups) + membership = _membership(selections, n_atoms) + weights = np.ones((n_modes, 1 + membership.shape[1])) + for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms): + weights[columns, 1:] = atom_weights.T @ membership + + centres, kept_weights = frequencies[kept], weights[kept] + spectra = np.zeros((grid.size, weights.shape[1])) + step = max(1, _common._CHUNK_BYTES // (grid.size * grid.itemsize)) # noqa: SLF001 + buffer = np.empty((grid.size, min(step, centres.size))) # one block, reused for every chunk of modes + for start in range(0, centres.size, step): + gaussians = buffer[:, : min(step, centres.size - start)] + np.subtract(grid[:, None], centres[None, start : start + step], out=gaussians) + gaussians /= broadening_thz + np.square(gaussians, out=gaussians) + gaussians *= -0.5 + np.exp(gaussians, out=gaussians) + spectra += gaussians @ kept_weights[start : start + step] + spectra *= (1.0 if normalization == "unit" else 3.0 * n_atoms) / (n_modes * broadening_thz * math.sqrt(2 * math.pi)) + + total = np.ascontiguousarray(spectra[:, 0]) + result: dict[str, Any] = {"frequencies_thz": grid, "vdos": {"total": total}} + if groups is not None: + result["vdos"] = {"total": total, **_columns_by_group(groups, keys, spectra[:, 1:])} + result["mode_weights"] = _columns_by_group(groups, keys, weights[:, 1:]) + n_imaginary = n_modes - int(np.count_nonzero(kept)) + result.update( + { + "n_modes": n_modes, + "n_imaginary_excluded": n_imaginary, + "imaginary_weight": n_imaginary / n_modes, + "grid_integral": float(np.trapezoid(total, grid)), + "broadening_thz": float(broadening_thz), + "normalization": normalization, + } + ) + return result + + +def compute_participation_ratio(eigenvectors: NDArray[np.float64], masses: ArrayLike) -> NDArray[np.float64]: + r"""Compute the participation ratio of every mode from the displacements of its mass-weighted eigenvector. + + The eigenvectors $e_{3i+\alpha,k}$ of the mass-weighted dynamical matrix (atom $i$, direction $\alpha$, mode $k$) + give the atomic displacements $u_{3i+\alpha,k} \propto e_{3i+\alpha,k} / \sqrt{m_i}$. With the squared displacement + of atom $i$, the participation ratio is (Taraskin and Elliott, Phys. Rev. B 56, 8605 (1997), Eq. 16, a definition + they attribute to Bell and Dean) + + $$b_{ik} = \frac{1}{m_i} \sum_\alpha e_{3i+\alpha,k}^2, \qquad + P_k = \frac{\left(\sum_i b_{ik}\right)^2}{N \sum_i b_{ik}^2}.$$ + + The ratio form makes $P_k$ independent of the scale and sign of each column, so the displacements need no + normalisation. $P_k = 1$ when every atom moves by the same amount (a rigid translation, whatever the masses), + $1/N$ for a mode on one atom and $n/N$ for a mode shared equally by $n$ atoms. The per-atom weight is summed over + the three directions before squaring, so $P_k$ does not depend on the orientation of the axes. Unlike the + kinetic-energy share $m_i b_{ik}$ used by :func:`compute_harmonic_vdos`, $b_{ik}$ counts atoms by amplitude; the + two coincide for a single element. + + An extended mode has $P$ of order 1 at any size, but a mode on a fixed number of atoms has $P \propto 1/N$, and in a + small box the two can be hard to tell apart: a claim that a mode is localised needs the same band compared across + box sizes. + + + Args: + eigenvectors: The $(3N, K)$ float64 eigenvectors of the mass-weighted dynamical matrix, one mode per column + with row $3i + \alpha$ for atom $i$ and direction $\alpha$, e.g. ``"eigenvectors"`` of + :func:`diagonalize_dynamical_matrix` (any memory order; no cast or copy is made). Columns need not be + normalised. + masses: Atomic masses, shape $(N,)$, in the order of the rows, e.g. ``minimised.get_masses()``. Only their + ratios matter. + + Returns: + The $(K,)$ float64 participation ratios, in the order of the columns, between $1/N$ and 1. + + Raises: + ValueError: If ``eigenvectors`` is not a 2-D float64 array, its row count is not a positive multiple of 3, + it has no columns, or a column is zero or contains NaN or inf; if ``masses`` does not hold $N$ positive + finite values. + + Example: + ```pycon + >>> minimised, summary = _run_lammps_dynamical_matrix(glass, potential, "dynmat.bin") # doctest: +SKIP + >>> matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) # doctest: +SKIP + >>> modes = diagonalize_dynamical_matrix( # doctest: +SKIP + ... matrix, masses=minimised.get_masses(), overwrite_matrix=True + ... ) + >>> ratios = compute_participation_ratio(modes["eigenvectors"], minimised.get_masses()) # doctest: +SKIP + >>> bands = np.digitize(modes["frequencies_thz"], [8.0, 20.0, 28.0]) # doctest: +SKIP + >>> np.bincount(bands, weights=ratios) / np.bincount(bands) # mean P per band # doctest: +SKIP + + ``` + """ + eigenvectors = np.asarray(eigenvectors) + if eigenvectors.ndim != _MATRIX_NDIM or eigenvectors.dtype != np.float64: + msg = ( + "eigenvectors must be a 2-D float64 array (a cast would copy it), " + f"got {eigenvectors.ndim}-D {eigenvectors.dtype}." + ) + raise ValueError(msg) + n_rows, n_modes = eigenvectors.shape + if n_rows == 0 or n_rows % _N_COMPONENTS or n_modes == 0: + msg = f"eigenvectors must have 3N rows (N >= 1) and at least one column, got shape {eigenvectors.shape}." + raise ValueError(msg) + n_atoms = n_rows // _N_COMPONENTS + masses = np.asarray(masses, dtype=np.float64) + if masses.shape != (n_atoms,) or not np.all(np.isfinite(masses) & (masses > 0)): + msg = f"masses must be {n_atoms} positive finite values, one per atom, got shape {masses.shape}." + raise ValueError(msg) + ratios = np.empty(n_modes) + for columns, atom_weights in _mode_atom_weights(eigenvectors, n_atoms): + np.divide(atom_weights, masses[:, None], out=atom_weights) # squared displacements, in place in our block + # The weights are non-negative, so NaN or inf anywhere in a column makes its sum of squares non-finite. + squares = np.einsum("ik,ik->k", atom_weights, atom_weights) + if not np.all(np.isfinite(squares)): + msg = f"eigenvectors contain NaN or inf (mode {columns.start + int(np.argmin(np.isfinite(squares)))})." + raise ValueError(msg) + if np.any(squares == 0): + msg = f"eigenvectors has a zero column (mode {columns.start + int(np.argmax(squares == 0))})." + raise ValueError(msg) + ratios[columns] = atom_weights.sum(axis=0) ** 2 / (n_atoms * squares) + return ratios diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/harmonic_simulation.py b/amorphouspy/src/amorphouspy/properties/vibrational/harmonic_simulation.py new file mode 100644 index 00000000..df82f4e2 --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/harmonic_simulation.py @@ -0,0 +1,399 @@ +"""Harmonic route workflow: minimisation, dynamical matrix, VDOS and thermodynamics.""" + +import contextlib +import shutil +import tempfile +import time +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Any + +import numpy as np +import pandas as pd +from numpy.typing import ArrayLike + +from amorphouspy.lammps.runner import _is_positive_int, _run_lammps_dynamical_matrix, _validate_minimize_arguments +from amorphouspy.properties.structural.qn import CutoffSpec +from amorphouspy.properties.vibrational._common import _is_real_number +from amorphouspy.properties.vibrational.classification import classify_vibrational_groups +from amorphouspy.properties.vibrational.dynamical_matrix import ( + EigenDriver, + _validate_eigh_options, + diagonalize_dynamical_matrix, + read_dynamical_matrix, +) +from amorphouspy.properties.vibrational.harmonic import ( + HarmonicNormalization, + _validate_broadening_options, + _validate_frequency_grid, + compute_harmonic_vdos, + compute_participation_ratio, +) +from amorphouspy.properties.vibrational.thermodynamics import ( + _check_temperatures, + _temperatures_array, + compute_vibrational_thermodynamics, +) + +if TYPE_CHECKING: + from ase import Atoms + +# The matrix file inside the directory that harmonic_vdos_simulation makes for it. +_HARMONIC_MATRIX_FILE = "dynamical_matrix.bin" +# Peak of diagonalize_dynamical_matrix with eigenvectors and overwrite_matrix=True, in matrices. +_HARMONIC_PEAK_MATRICES = 2 +# Defaults of _run_lammps_minimize that harmonic_vdos_simulation does not expose; used only to validate upfront. +_MINIMIZE_ENERGY_TOLERANCE = 0.0 +_MINIMIZE_N_PRINT = 100 + + +def _harmonic_simulation_settings( + structure: "Atoms", + potential: pd.DataFrame, + max_atoms: int, + displacement: float, + force_tolerance: float, + max_iter: int, + broadening_thz: float, + frequency_grid_thz: ArrayLike | None, + normalization: str, + temperatures_k: ArrayLike | None, + driver: str, + imaginary_threshold_thz: float, + *, + tmp_working_directory: str | Path | None, + keep_dynamical_matrix: bool, +) -> None: + """Validate the arguments of :func:`harmonic_vdos_simulation` before anything runs.""" + if not _is_positive_int(max_atoms): + msg = f"max_atoms must be a positive integer, got {max_atoms!r}." + raise ValueError(msg) + n_atoms = len(structure) + if n_atoms > max_atoms: + matrix_gb = 9 * n_atoms**2 * 8 / 1e9 + msg = ( + f"The structure has {n_atoms} atoms, more than max_atoms={max_atoms}. Its dynamical matrix takes " + f"9 N² x 8 bytes = {matrix_gb:.3g} GB, and the diagonalisation with eigenvectors peaks at " + f"{_HARMONIC_PEAK_MATRICES} matrices, {_HARMONIC_PEAK_MATRICES * matrix_gb:.3g} GB. Raise max_atoms " + "deliberately to run it anyway." + ) + raise ValueError(msg) + if potential.empty: + msg = "No matching potential found for the given configuration." + raise ValueError(msg) + if not _is_real_number(displacement) or not np.isfinite(displacement) or displacement <= 0: + msg = f"displacement must be positive and finite (Å), got {displacement!r}." + raise ValueError(msg) + _validate_minimize_arguments(force_tolerance, _MINIMIZE_ENERGY_TOLERANCE, max_iter, "fire", None, _MINIMIZE_N_PRINT) + _validate_broadening_options(broadening_thz, normalization) + if frequency_grid_thz is not None: + _validate_frequency_grid(frequency_grid_thz) + if temperatures_k is not None: + _check_temperatures(_temperatures_array(temperatures_k)) + _validate_eigh_options(driver, imaginary_threshold_thz) + if keep_dynamical_matrix and tmp_working_directory is None: + msg = "keep_dynamical_matrix=True needs a tmp_working_directory; without one every run removes its files." + raise ValueError(msg) + matrix_parent = tempfile.gettempdir() if tmp_working_directory is None else tmp_working_directory + matrix_bytes = 9 * n_atoms**2 * 8 + free_bytes = shutil.disk_usage(matrix_parent).free + if free_bytes < matrix_bytes: + msg = ( + f"The dynamical-matrix file takes 9 N² x 8 bytes = {matrix_bytes / 1e9:.3g} GB, but {matrix_parent} has " + f"only {free_bytes / 1e9:.3g} GB free. Pass a tmp_working_directory with enough space." + ) + raise ValueError(msg) + + +def harmonic_vdos_simulation( + structure: "Atoms", + potential: pd.DataFrame, + server_kwargs: dict[str, Any] | None = None, + *, + max_atoms: int = 10_000, + displacement: float = 1e-5, + force_tolerance: float = 1e-6, + max_iter: int = 100_000, + broadening_thz: float = 0.2, + frequency_grid_thz: ArrayLike | None = None, + normalization: HarmonicNormalization = "unit", + temperatures_k: ArrayLike | None = None, + cutoff: CutoffSpec | None = None, + former_types: list[int] | None = None, + o_type: int = 8, + driver: EigenDriver = "evr", + imaginary_threshold_thz: float = 0.01, + tmp_working_directory: str | Path | None = None, + keep_dynamical_matrix: bool = False, + keep_eigenvectors: bool = False, +) -> dict[str, Any]: + r"""Minimise a structure, compute its finite-difference dynamical matrix and return the harmonic VDOS and modes. + + The harmonic counterpart of :func:`vdos_simulation`: the VDOS of the 0 K inherent structure from its normal modes, + with no MD and no statistical noise. Steps: + + 1. Minimisation at fixed cell and the dynamical matrix, both in LAMMPS (``_run_lammps_dynamical_matrix``). + 2. The atom groups (element, oxygen class, $\mathrm{Q}^n$) with :func:`classify_vibrational_groups` and the + masses, both from the minimised structure. + 3. The matrix is read with :func:`read_dynamical_matrix` and diagonalised in place with + :func:`diagonalize_dynamical_matrix`, which drops the three translations. + 4. The broadened VDOS and its group partials with :func:`compute_harmonic_vdos`, the participation ratio of every + mode with :func:`compute_participation_ratio` and, with ``temperatures_k``, the harmonic thermodynamics with + :func:`compute_vibrational_thermodynamics`. + + The structure is used as given. Preparing it (melt-quench, NPT relaxation to the target pressure) is the caller's + job; this function adds only the minimisation. The minimisation uses FIRE at fixed cell + (``min_style="fire"``, no ``box/relax``) down to ``force_tolerance``, the LAMMPS ``ftol``: the 2-norm of the global + force vector in eV/Å, not a per-atom maximum. A fixed cell leaves a residual pressure, reported in + ``"minimization"`` (``"pressure_gpa"`` and ``"mean_pressure_gpa"``; for FIRE they also hold the kinetic term of + the residual velocities), together with the iteration count, the stopping criterion and the final forces. If the + tolerance is not reached, the minimiser warns and the result is still returned; the step-0 forces of the + structure that was differentiated are in ``"dynamical_matrix"`` (``"max_force_ev_per_a"``). + + Finite differences: each entry of the matrix is a central difference of the forces with step ``displacement``. + + Imaginary modes are reported as negative frequencies in ``"mode_frequencies_thz"``. Those below + ``-imaginary_threshold_thz`` are counted in ``"diagonalization"`` (``"n_imaginary"``, with a warning that names + the asymmetry atoms); they point at an incomplete minimisation or a corrupted entry. Every negative frequency is + left out of the VDOS (``"n_imaginary_excluded"`` and ``"imaginary_weight"``) and of the thermodynamics. + + ``max_atoms`` guards against an accidental large run: above it the function raises before anything runs, and the + message gives the matrix size and the expected peak. It can be raised deliberately. + + The groups are classified on the minimised structure, the one whose modes are computed. Errors in ``cutoff``, + ``former_types`` or ``o_type`` therefore surface only after the LAMMPS runs. + + The thermodynamics is computed from the broadened total VDOS on the frequency grid, not from a sum over the modes, + with ``lowest_frequency_thz`` set to the smallest positive mode frequency, the lowest mode the box supports: the + values below its temperature are flagged as unreliable. With ``normalization="3N"`` the total is divided by 3N + first, as :func:`compute_vibrational_thermodynamics` needs a VDOS normalised to 1. On the 300-atom PMMCS glass at + 300 K with the default 0.2 THz broadening, the values differ from an exact sum over the modes by -1.3e-5 (C_V), + 8.5e-4 (S), 3.0e-5 (U) and -3.7e-4 (F), relative. The default grid starts at 0, so modes within a few + ``broadening_thz`` of 0 lose part of their weight (``"excluded_weight"`` and ``"vdos_integral"`` report it). + + Disk and memory: the matrix file takes 9 N² x 8 bytes (2.6 GB at 6000 atoms, 7.2 GB at 10,000) and is deleted once + it is read unless ``keep_dynamical_matrix``. It is written under ``tmp_working_directory`` or, if that is None, + under the system temporary directory (``tempfile.gettempdir()``, set by ``TMPDIR``); the free space there is + checked before anything runs. The peak in memory is still 2 matrices, during the diagonalisation. + Without the eigenvectors, the result holds only O(M x number of labels) floats (the mode frequencies, participation + ratios and group weights) plus the VDOS curves on the frequency grid. An eigenvector-based analysis later needs + ``keep_eigenvectors=True`` or a rerun. + + Args: + structure: The structure, e.g. a quenched and NPT-relaxed glass, used as given. It is not modified. + potential: LAMMPS potential as a pandas DataFrame. + server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``), used by both LAMMPS runs. + max_atoms: Largest number of atoms accepted, a positive integer. + displacement: Finite-difference displacement in Å. + force_tolerance: FIRE stops when the 2-norm of the global force vector is below this, in eV/Å. + max_iter: Maximum number of FIRE iterations. + broadening_thz: Standard deviation of the Gaussian broadening of each mode in THz (not the FWHM). + frequency_grid_thz: Frequencies in THz at which the VDOS is evaluated, 1-D, finite and strictly increasing. + ``None``: from 0 in steps of ``broadening_thz / 5`` up to the highest mode plus 5 ``broadening_thz``. + normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``), each + short by the share of imaginary modes. + temperatures_k: Temperatures in K for the harmonic thermodynamics, a scalar or a 1-D array of finite values + >= 0. ``None`` skips it. + cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF + of the minimised structure if ``None``. + former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. + o_type: Atomic number of oxygen. + driver: LAPACK driver of ``scipy.linalg.eigh``: ``"evr"`` (default), ``"evd"``, ``"evx"`` or ``"ev"``; see + :func:`diagonalize_dynamical_matrix` for their memory and time. + imaginary_threshold_thz: A mode below ``-imaginary_threshold_thz`` counts as imaginary in + ``"diagonalization"``. + tmp_working_directory: Directory for the LAMMPS runs and the matrix file. The run directories, with their + logs, input and data files, are kept. The matrix file goes to its own ``harmonic_vdos_*`` subdirectory, + which is removed once the matrix is read unless ``keep_dynamical_matrix``; nothing else in the directory is + removed. If None, every run and the matrix file are removed. + keep_dynamical_matrix: Keep the matrix file, in ``harmonic_vdos_*/dynamical_matrix.bin`` under + ``tmp_working_directory``, instead of deleting it once read. Needs a ``tmp_working_directory``. + keep_eigenvectors: Return the eigenvectors in ``"eigenvectors"``, one matrix in memory, instead of dropping + them once the VDOS, the group partials and the participation ratios are computed. + + Returns: + A dict with: + ``"frequencies_thz"``: the frequency grid in THz. + ``"vdos"``: ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels of + ``"groups"``, in 1/THz, the layout of :func:`vdos_simulation`. + ``"groups"``: the output of :func:`classify_vibrational_groups` on the minimised structure. + ``"structure"``: the minimised structure. + ``"normalization"``: the VDOS normalisation. + ``"broadening_thz"``: the broadening in THz. + ``"mode_frequencies_thz"``: the $M = 3N - 3$ mode frequencies in THz, ascending, negative for imaginary + modes. + ``"participation_ratio"``: the participation ratio of every mode, shape $(M,)$. + ``"mode_weights"``: ``{grouping: {label: w}}``, each group's $(M,)$ share of every mode, as in + :func:`compute_harmonic_vdos`. + ``"n_imaginary_excluded"``: the number of modes with a negative frequency, left out of the VDOS. + ``"imaginary_weight"``: their share of the normalisation. + ``"grid_integral"``: the trapezoid integral of the total VDOS on the grid. + ``"eigenvectors"``: the $(3N, M)$ mass-weighted eigenvectors, one mode per column; None unless + ``keep_eigenvectors``. + ``"dynamical_matrix"``: the summary of the LAMMPS dynamical-matrix run (``"matrix_path"``, + ``"matrix_bytes"``, ``"n_atoms"``, ``"displacement_a"``, ``"style"``, the step-0 ``"max_force_ev_per_a"`` + and ``"force_norm_ev_per_a"``, ``"minimization"`` and ``"wall_time_s"``). ``"matrix_path"`` is the + absolute path of the kept file; None unless ``keep_dynamical_matrix``. + ``"minimization"``: the FIRE summary: ``"converged"``, ``"stopping_criterion"``, ``"n_iterations"``, + ``"max_force_ev_per_a"``, ``"force_norm_ev_per_a"``, ``"pressure_gpa"``, ``"mean_pressure_gpa"``, the + energies and volumes. + ``"diagonalization"``: ``"asymmetry"``, ``"asymmetry_atoms"``, ``"translational_frequencies_thz"``, + ``"translational_overlap"``, ``"n_imaginary"``, ``"min_frequency_thz"`` and ``"driver"``. + ``"thermodynamics"``: the output of :func:`compute_vibrational_thermodynamics`, or None without + ``temperatures_k`` or when no mode has a positive frequency (with a warning). + ``"displacement_a"``: the finite-difference displacement in Å. + ``"wall_time_s"``: ``{"lammps", "diagonalization", "analysis"}`` in s: both LAMMPS runs; reading and + diagonalising the matrix; the groups, VDOS, participation ratios and thermodynamics. + + Raises: + ValueError: Before any LAMMPS run, if ``max_atoms`` is not a positive integer, the structure has more than + ``max_atoms`` atoms, the potential is empty, ``displacement`` is not positive and finite, + ``force_tolerance`` is negative, zero or not finite, ``max_iter`` is not a positive integer, + ``broadening_thz`` is not positive and finite, ``normalization`` is unknown, ``frequency_grid_thz`` is not + 1-D, finite and strictly increasing with at least 2 points, ``temperatures_k`` is not finite and >= 0, + ``driver`` is unknown, ``imaginary_threshold_thz`` is not >= 0, ``keep_dynamical_matrix`` is True + without a ``tmp_working_directory``, or the directory of the matrix file has less free space than the + file needs. After the LAMMPS runs, if ``cutoff``, ``former_types`` or ``o_type`` + is invalid for :func:`classify_vibrational_groups`. + RuntimeError: If a LAMMPS run fails or the matrix file is missing or has the wrong size. + + Warns: + UserWarning: If the minimisation stops on a criterion other than the force or energy tolerance, the + diagonalisation finds imaginary modes or dropped modes that are not translations, a caller's + ``frequency_grid_thz`` is coarser than ``broadening_thz / 2``, or ``temperatures_k`` is given but no + mode has a positive frequency. + + Example: + ```pycon + >>> out = harmonic_vdos_simulation(glass, potential, temperatures_k=[300.0]) # doctest: +SKIP + >>> out["minimization"]["converged"], out["diagonalization"]["asymmetry"] # doctest: +SKIP + >>> out["diagonalization"]["n_imaginary"], out["grid_integral"] # doctest: +SKIP + >>> out["vdos"]["oxygen"]["O_BO"] # doctest: +SKIP + >>> out["thermodynamics"]["heat_capacity_kb_per_atom"] # doctest: +SKIP + + ``` + """ + _harmonic_simulation_settings( + structure, + potential, + max_atoms, + displacement, + force_tolerance, + max_iter, + broadening_thz, + frequency_grid_thz, + normalization, + temperatures_k, + driver, + imaginary_threshold_thz, + tmp_working_directory=tmp_working_directory, + keep_dynamical_matrix=keep_dynamical_matrix, + ) + with ( + contextlib.nullcontext(tempfile.mkdtemp(prefix="harmonic_vdos_", dir=tmp_working_directory)) + if keep_dynamical_matrix + else tempfile.TemporaryDirectory(prefix="harmonic_vdos_", dir=tmp_working_directory) + ) as matrix_dir: + start = time.perf_counter() + minimised, summary = _run_lammps_dynamical_matrix( + structure, + potential, + Path(matrix_dir) / _HARMONIC_MATRIX_FILE, + displacement=displacement, + minimize=True, + minimize_kwargs={ + "min_style": "fire", + "pressure": None, + "force_tolerance": force_tolerance, + "max_iter": max_iter, + }, + server_kwargs=server_kwargs, + tmp_working_directory=tmp_working_directory, + ) + lammps_s = time.perf_counter() - start + start = time.perf_counter() + groups = classify_vibrational_groups(minimised, cutoff, former_types, o_type) + masses = minimised.get_masses() + groups_s = time.perf_counter() - start + start = time.perf_counter() + matrix = read_dynamical_matrix(summary["matrix_path"], summary["n_atoms"]) + if not keep_dynamical_matrix: + summary = {**summary, "matrix_path": None} + # Diagonalised in place; dropping the only reference afterwards frees the overwritten matrix, so the peak is the + # matrix plus its eigenvectors and only the eigenvectors stay. + modes = diagonalize_dynamical_matrix( + matrix, + masses=masses, + overwrite_matrix=True, + eigenvectors=True, + driver=driver, + imaginary_threshold_thz=imaginary_threshold_thz, + ) + del matrix + diagonalization_s = time.perf_counter() - start + + start = time.perf_counter() + mode_frequencies, eigenvectors = modes["frequencies_thz"], modes.pop("eigenvectors") + vdos = compute_harmonic_vdos( + mode_frequencies, + eigenvectors, + groups=groups, + frequency_grid_thz=frequency_grid_thz, + broadening_thz=broadening_thz, + normalization=normalization, + ) + participation_ratio = compute_participation_ratio(eigenvectors, masses) + if not keep_eigenvectors: + # The last reference to the eigenvector buffer: dropping it frees one matrix before the thermodynamics. + eigenvectors = None + thermodynamics = None + positive_modes = mode_frequencies[mode_frequencies > 0] + if temperatures_k is not None and positive_modes.size == 0: + warnings.warn( + "No mode has a positive frequency, so the thermodynamics are not computed ('thermodynamics' is None); " + f"the lowest mode is {modes['min_frequency_thz']:.4g} THz. Check the minimisation and the asymmetry.", + UserWarning, + stacklevel=2, + ) + elif temperatures_k is not None: + total = vdos["vdos"]["total"] if normalization == "unit" else vdos["vdos"]["total"] / (3 * len(minimised)) + thermodynamics = compute_vibrational_thermodynamics( + vdos["frequencies_thz"], + total, + temperatures_k, + lowest_frequency_thz=float(positive_modes.min()), + ) + analysis_s = groups_s + time.perf_counter() - start + + return { + "frequencies_thz": vdos["frequencies_thz"], + "vdos": vdos["vdos"], + "groups": groups, + "structure": minimised, + "normalization": normalization, + "broadening_thz": vdos["broadening_thz"], + "mode_frequencies_thz": mode_frequencies, + "participation_ratio": participation_ratio, + "mode_weights": vdos["mode_weights"], + "n_imaginary_excluded": vdos["n_imaginary_excluded"], + "imaginary_weight": vdos["imaginary_weight"], + "grid_integral": vdos["grid_integral"], + "eigenvectors": eigenvectors, + "dynamical_matrix": summary, + "minimization": summary["minimization"], + "diagonalization": { + key: modes[key] + for key in ( + "asymmetry", + "asymmetry_atoms", + "translational_frequencies_thz", + "translational_overlap", + "n_imaginary", + "min_frequency_thz", + "driver", + ) + }, + "thermodynamics": thermodynamics, + "displacement_a": summary["displacement_a"], + "wall_time_s": {"lammps": lammps_s, "diagonalization": diagonalization_s, "analysis": analysis_s}, + } diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/simulation.py b/amorphouspy/src/amorphouspy/properties/vibrational/simulation.py new file mode 100644 index 00000000..1fe13dae --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/simulation.py @@ -0,0 +1,517 @@ +"""VACF route workflow: NVE production blocks with block-averaged VDOS and VACF.""" + +import math +import tempfile +import warnings +from pathlib import Path +from typing import TYPE_CHECKING, Any, Literal + +import numpy as np +import pandas as pd +from numpy.typing import ArrayLike, NDArray + +from amorphouspy.lammps.runner import Thermostat, _run_lammps_md, thermostat_ensembles +from amorphouspy.properties.structural.qn import CutoffSpec +from amorphouspy.properties.vibrational._common import _is_real_number +from amorphouspy.properties.vibrational._trajectory import _MIN_FRAMES +from amorphouspy.properties.vibrational.classification import classify_vibrational_groups +from amorphouspy.properties.vibrational.vacf import compute_partial_vacf +from amorphouspy.properties.vibrational.vdos import VdosWindow, _validate_window, compute_partial_vdos + +if TYPE_CHECKING: + from ase import Atoms + +# Spectra of silicate glasses reach about 40 THz; a lower Nyquist frequency cuts and aliases the highest modes. +_MIN_NYQUIST_THZ = 50.0 +# Name of the text dump written by lammpsparser in each run directory. +_DUMP_FILE = "dump.out" + + +def _whole_steps(name: str, duration_ps: float, timestep: float) -> int: + """Return ``duration_ps`` in MD steps; raise if it is not a whole number of timesteps.""" + steps = duration_ps * 1000 / timestep + whole_steps = round(steps) + if not math.isclose(steps, whole_steps, rel_tol=1e-9): + msg = f"{name}={duration_ps} ps is not a whole number of {timestep} fs timesteps ({steps:g} steps)." + raise ValueError(msg) + return whole_steps + + +def _vdos_simulation_settings( + potential: pd.DataFrame, + temperature_sim: float, + timestep: float, + production_ps: float, + block_ps: float, + dump_every: int, + equilibration_steps: int, + normalization: str, + window: object, +) -> tuple[int, int, int, float]: + """Validate the arguments of :func:`vdos_simulation`; return ``(block_steps, block_frames, n_blocks, dt_fs)``.""" + if potential.empty: + msg = "No matching potential found for the given configuration." + raise ValueError(msg) + for name, value in ( + ("temperature_sim", temperature_sim), + ("timestep", timestep), + ("block_ps", block_ps), + ("production_ps", production_ps), + ): + if not (_is_real_number(value) and np.isfinite(value) and value > 0): + msg = f"{name} must be positive and finite, got {value}." + raise ValueError(msg) + if isinstance(dump_every, bool) or not isinstance(dump_every, int | np.integer) or dump_every < 1: + msg = f"dump_every must be a positive integer, got {dump_every!r}." + raise ValueError(msg) + if ( + isinstance(equilibration_steps, bool) + or not isinstance(equilibration_steps, int | np.integer) + or equilibration_steps < 0 + ): + msg = f"equilibration_steps must not be negative and must be an integer, got {equilibration_steps!r}." + raise ValueError(msg) + if normalization not in ("unit", "3N"): + msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and '3N'." + raise ValueError(msg) + _validate_window(window) + block_steps = _whole_steps("block_ps", block_ps, timestep) + if block_steps % dump_every: + msg = f"The block of {block_steps} steps is not a multiple of dump_every={dump_every}." + raise ValueError(msg) + block_frames = block_steps // dump_every + if block_frames < _MIN_FRAMES: + msg = f"A block needs at least 2 frames, got {block_frames} ({block_steps} steps, dump_every={dump_every})." + raise ValueError(msg) + production_steps = _whole_steps("production_ps", production_ps, timestep) + if production_steps % block_steps: + msg = f"The production of {production_steps} steps is not a multiple of the block of {block_steps} steps." + raise ValueError(msg) + return block_steps, block_frames, production_steps // block_steps, timestep * dump_every + + +def _split_total(partial: dict[str, dict[str, NDArray[np.float64]]]) -> dict[str, Any]: + """Move the all-atoms group of :func:`vdos_simulation` to a top-level ``"total"`` entry.""" + return {"total": partial["total"]["all"], **{name: labels for name, labels in partial.items() if name != "total"}} + + +def _nve_block( + structure: "Atoms", + nve_kwargs: dict[str, Any], + block: int, + n_blocks: int, + block_frames: int, + masses: NDArray[np.float64], + dt_fs: float, + spectral_groups: dict[str, dict[str, NDArray]], + normalization: Literal["unit", "3N"], + window: VdosWindow, + block_dir: str | None, + *, + keep_trajectory: bool, +) -> tuple["Atoms", dict[str, Any], NDArray[np.float64], NDArray[np.float64], float]: + """Run NVE block number ``block`` (1-based) in ``block_dir``. + + Return ``(final structure, spectra, temperature, energy_tot, step-0 energy_tot)``. Unless ``block_dir`` is None + or ``keep_trajectory`` is True, the block's dump is deleted once its spectra and thermo are extracted. + + The parsed output is local to this function, so its trajectory arrays are freed on return, before the next block + is launched. Nothing returned here may hold a view of them. + """ + structure_final, parsed_output = _run_lammps_md(structure=structure, **nve_kwargs, tmp_working_directory=block_dir) + + # LAMMPS also dumps step 0 (the end state of the previous stage); it is dropped below. + generic = parsed_output["generic"] + for key in ("velocities", "temperature", "energy_tot"): + if len(generic[key]) != block_frames + 1: + msg = ( + f"NVE block {block} of {n_blocks} returned {len(generic[key])} frames of {key!r}, expected " + f"{block_frames + 1} ({block_frames} plus the step-0 frame)." + ) + if block_dir is not None: + dumps = [str(dump) for dump in sorted(Path(block_dir).rglob(_DUMP_FILE))] or [block_dir] + msg += f" Its dump is kept in {', '.join(dumps)}." + raise RuntimeError(msg) + velocities = np.asarray(generic["velocities"])[1:] + + frequencies_thz, no_window = compute_partial_vdos( + velocities, masses, dt_fs, spectral_groups, normalization=normalization + ) + vdos = {"no_window": _split_total(no_window)} + if window is not None: + _, windowed = compute_partial_vdos( + velocities, masses, dt_fs, spectral_groups, normalization=normalization, window=window + ) + vdos["windowed"] = _split_total(windowed) + lag_ps, vacf = compute_partial_vacf(velocities, masses, dt_fs, spectral_groups) + + spectra = {"frequencies_thz": frequencies_thz, "lag_ps": lag_ps, "vdos": vdos, "vacf": _split_total(vacf)} + temperature, energy_tot = np.asarray(generic["temperature"]), np.asarray(generic["energy_tot"]) + + if block_dir is not None and not keep_trajectory: + dumps = sorted(Path(block_dir).rglob(_DUMP_FILE)) + if not dumps: + warnings.warn( + f"No {_DUMP_FILE} found under {block_dir} for NVE block {block}; nothing was deleted.", + UserWarning, + stacklevel=3, + ) + for dump in dumps: + dump.unlink() + return structure_final, spectra, temperature[1:], energy_tot[1:], float(energy_tot[0]) + + +def _slope(x: ArrayLike, y: ArrayLike) -> float: + """Return the least-squares slope of ``y`` against ``x``.""" + x_array, y_array = np.asarray(x, dtype=np.float64), np.asarray(y, dtype=np.float64) + x_centred, y_centred = x_array - x_array.mean(), y_array - y_array.mean() + return float(x_centred @ y_centred / (x_centred @ x_centred)) + + +def _nve_drift( + temperature: NDArray[np.float64], + energy_tot: NDArray[np.float64], + step0_energies: list[float], + n_atoms: int, + dt_fs: float, +) -> dict[str, Any]: + """Return the energy and temperature drift of the concatenated kept NVE frames; see :func:`vdos_simulation`.""" + n_blocks = len(step0_energies) + energy_mev = energy_tot * 1e3 / n_atoms + time_ps = (np.arange(len(energy_tot)) + 1) * dt_fs * 1e-3 + block_energy, block_time = energy_mev.reshape(n_blocks, -1), time_ps.reshape(n_blocks, -1) + return { + "energy_drift_mev_per_atom_ps": _slope(time_ps, energy_mev), + "block_energy_drift_mev_per_atom_ps": np.array( + [_slope(t, e) for t, e in zip(block_time, block_energy, strict=True)] + ), + "boundary_energy_jump_mev_per_atom": np.asarray(step0_energies[1:]) * 1e3 / n_atoms - block_energy[:-1, -1], + "max_energy_deviation_mev_per_atom": float(np.max(np.abs(energy_mev - energy_mev[0]))), + "temperature_mean_k": float(np.mean(temperature)), + "temperature_std_k": float(np.std(temperature)), + "temperature_drift_k_per_ps": _slope(time_ps, temperature), + } + + +def _block_statistics(blocks: list[dict[str, Any]]) -> tuple[dict[str, Any], dict[str, Any]]: + """Return the mean and the standard error over blocks of every curve in nested dicts of one layout.""" + mean, sem = {}, {} + for key, value in blocks[0].items(): + values = [block[key] for block in blocks] + if isinstance(value, dict): + mean[key], sem[key] = _block_statistics(values) + else: + mean[key] = np.mean(values, axis=0) + # The standard error of one block is undefined, and np.std with ddof=1 would warn. + single = len(blocks) == 1 + sem[key] = np.full_like(value, np.nan) if single else np.std(values, axis=0, ddof=1) / np.sqrt(len(blocks)) + return mean, sem + + +def vdos_simulation( + structure: "Atoms", + potential: pd.DataFrame, + temperature_sim: float = 300.0, + timestep: float = 1.0, + server_kwargs: dict[str, Any] | None = None, + *, + thermostat: Thermostat, + equilibration_steps: int = 100_000, + production_ps: float = 200.0, + block_ps: float = 10.0, + dump_every: int = 5, + normalization: Literal["unit", "3N"] = "unit", + window: VdosWindow = "hann", + cutoff: CutoffSpec | None = None, + former_types: list[int] | None = None, + o_type: int = 8, + seed: int = 12345, + tmp_working_directory: str | Path | None = None, + keep_trajectory: bool = False, +) -> dict[str, Any]: + r"""Equilibrate a structure, run consecutive NVE blocks and average their VDOS and VACF, total and per atom group. + + Three MD stages run in LAMMPS at the constant volume of the input cell: + + 1. Langevin thermalisation at ``temperature_sim`` for 10,000 steps, with velocities created at ``temperature_sim`` + (as in :func:`diffusion_simulation`). + 2. NVT equilibration with ``thermostat`` for ``equilibration_steps`` steps, with velocities created again at + ``temperature_sim``. ``equilibration_steps=0`` skips this stage. + 3. NVE production of ``production_ps``, run as ``n_blocks = production_steps // block_steps`` consecutive blocks of + ``block_ps``, i.e. ``block_steps = block_ps * 1000 / timestep`` steps each, with velocities and thermo output + every ``dump_every`` steps. The first block starts from the velocities of the previous stage and every later + block from the end of the block before it, as a new LAMMPS run. + + The production is microcanonical because a thermostat perturbs the velocities and distorts the spectrum. LAMMPS + also writes the frame of step 0 of every block, which is the end state of the previous stage or block. It is + dropped, so the kept frames of consecutive blocks do not overlap. Each block holds ``n_frames = block_steps // + dump_every`` frames spaced by ``dt_fs = timestep * dump_every`` fs, and the frequency resolution is exactly + ``1 / block_ps`` THz. If the parsed output of a block does not hold ``n_frames + 1`` frames, a ``RuntimeError`` is + raised; no frame is trimmed silently. The Nyquist frequency is ``1 / (2 dt_fs)``: 100 THz for the defaults (1 fs, + every 5 steps). + + From the kept frames of each block (velocities in Å/fs, masses from ``structure.get_masses()`` in amu) the function + computes: + + - The VDOS without a window and, unless ``window`` is ``None``, with ``window`` (Hann by default), both with + :func:`compute_partial_vdos`, the given ``normalization`` and one shared frequency axis. The total is computed + as the partial VDOS of a group of all atoms, so it is the total VDOS of :func:`compute_vdos_from_velocities` + and integrates to 1 (``"unit"``) or ``3 * n_atoms`` (``"3N"``); within each grouping the partials add up to it. + - The VACF with :func:`compute_partial_vacf`, unwindowed, normalised so that the total $C(0) = 1$, with lags up to + half the block. + + The centre-of-mass velocity of the whole system is removed from every frame in both. + + Every returned curve is the mean over blocks, with the block standard error ``std(ddof=1) / sqrt(n_blocks)`` in + ``"vdos_sem"`` and ``"vacf_sem"``; with one block the standard error is NaN. Each block's VDOS and VACF are + normalised by that block's own kinetic energy, so the mean of the block curves integrates exactly to the + normalisation, the total VACF has $C(0) = 1$ exactly, and within each grouping the mean partials still add up to + the mean total. The standard errors are not additive: the standard error of a total is not the sum of those of + its partials. + + The standard error is the scatter between the blocks of this run, and it assumes that they are independent. The + blocks come from one NVE trajectory of one glass, so it contains no glass-to-glass variation at all, and nothing + that stays constant over the run: neither the energy of the run nor a nearly harmonic mode that keeps its energy + between blocks. A calibration compared the means of two independent thermal histories of one 300-atom + $\mathrm{SiO_2}$ glass (PMMCS, 300 K, 10 blocks of 10 ps each), where exact standard errors put 94 % of the bins + within two combined standard errors. Between 5 and 34 THz this held for 93 % (no window) and 95 % (Hann) of the + bins. Below 5 THz it held for 96 % and 98 %, so no low-frequency underestimate was seen, although 50 bins would not + show a small one. Between 34 and 40 THz, above the top of the spectrum, it held for only 75 % and 78 %: the weight + there differed by 4 to 5 %, as did the temperature of the two runs. The lag-1 correlation of the block residuals + was close to the -0.1 of independent blocks, but a part that is constant over the run cannot show up in it. One + pair of runs says nothing about larger boxes, lower temperatures or shorter blocks. + + The atom groups (element, oxygen class, $\mathrm{Q}^n$) come from :func:`classify_vibrational_groups` on the input + ``structure``, before any MD, so thermal motion of bonds near the cutoff cannot change them. They stay fixed for + all blocks. + + Memory: the velocities of one block take ``n_frames * n_atoms * 3 * 8`` bytes as float64, e.g. 0.29 GB for 2000 + frames (10 ps at 5 fs) of 6000 atoms. The parsed LAMMPS output holds three more arrays of that size (positions, + unwrapped positions and forces), and parsing it needs more still: a 10 ps block of 5400 atoms peaked 4.5 GB above + the baseline, 17 times its velocities (measured). The peak scales with one block, not with the whole production: a + block's parsed output is freed before the next block starts, and only the spectra and the thermo output accumulate. + Not all freed memory goes back to the system, though: over 8 blocks of 2 ps the resident size levelled off at 1.7 + times the peak of the first block (measured on macOS). + + Disk: with ``tmp_working_directory=None`` every run removes its files. In a caller-supplied directory every run + keeps a sub-directory, and each NVE block runs in its own ``vdos_nve_block__`` directory. Its dump + (``dump.out``, 88 bytes per atom per frame, measured: 0.47 MB per frame and 0.95 GB per 10 ps block at 5400 atoms) + is deleted once the block's spectra and thermo output are extracted, before the next block starts, so at most one + dump is on disk at a time. ``log.lammps``, the input script and the data file stay, as do all files of the Langevin + and NVT stages. ``keep_trajectory=True`` keeps every dump (20 for the defaults). A block that fails keeps its dump, + and the error names it. If no dump is found to delete, a warning is raised and the result is still returned. + + Drift: ``"nve_drift"`` reports the energy and temperature of the kept NVE frames, frame ``k`` (0-based over all + blocks) at ``t = (k + 1) * dt_fs`` fs. Each block restarts from the positions and velocities of the previous + block's dump, written with 6 significant digits, so the total energy can jump at a block boundary. The jump is + measured between the last kept frame of a block and the step-0 frame of the next, which hold the same state, so it + is the restart loss alone. The thermo output has 8 significant digits, so energies are resolved to about + ``|E_tot| / N * 1e-5`` meV/atom, one unit in the last digit (measured for $\mathrm{SiO_2}$ with PMMCS: 3.3e-4 + meV/atom at 300 atoms, 1.9e-4 at 5400). In those runs (300 K, blocks of 2 and 10 ps) every jump was within two + such units, at most 6.7e-4 meV/atom, and smaller than the drift within any block over the block length. + + Args: + structure: Input structure, e.g. a quenched glass. Its cell sets the volume of every stage, and the atom + groups and masses are taken from it. + potential: LAMMPS potential as a pandas DataFrame. + temperature_sim: Temperature of the Langevin and NVT stages in K. + timestep: MD timestep in fs. + server_kwargs: Additional arguments for the LAMMPS server (e.g. ``{"cores": 4}``). + thermostat: Thermostat of the NVT stage, ``"nose_hoover"`` or ``"langevin"``. + equilibration_steps: Length of the NVT stage in MD steps; 0 skips it. Use a small value for quick demos and + the default for production-quality runs. + production_ps: Total length of the NVE production in ps, a whole number of timesteps and a multiple of + ``block_ps``; nothing is truncated. + block_ps: Length of one NVE block in ps, a whole number of timesteps. It sets the resolution 1 / ``block_ps`` + THz. + dump_every: Interval between dumped frames in MD steps, a positive integer that divides the block. + normalization: ``"unit"`` (the total VDOS integrates to 1, in 1/THz) or ``"3N"`` (to ``3 * n_atoms``). The + VACF is always normalised to $C(0) = 1$. + window: Window of the second VDOS, as in :func:`compute_partial_vdos`: ``"hann"`` (default), ``"hamming"``, + ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames (``dt_fs`` apart, so 250 frames + are 1.25 ps at the defaults), or ``None`` to compute only the unwindowed VDOS. + cutoff: Former-O cutoff in Å for the groups, as in :func:`classify_vibrational_groups`. Derived from the RDF + if ``None``. + former_types: Atomic numbers of the network formers. Derived from the composition if ``None``. + o_type: Atomic number of oxygen. + seed: Random seed for the velocities created in the Langevin and NVT stages. + tmp_working_directory: Directory for temporary simulation files. If None, every run removes its files. + keep_trajectory: Keep the dump of every NVE block in ``tmp_working_directory`` instead of deleting it once its + spectra are computed. Requires ``tmp_working_directory``. + + Returns: + A dict with: + ``"frequencies_thz"``: frequency axis in THz, length ``n_frames // 2 + 1``, shared by both VDOS. + ``"vdos"``: mean over blocks, ``{"no_window": ..., "windowed": ...}`` (no ``"windowed"`` entry for + ``window=None``), each ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}`` with the labels + of ``"groups"``, in 1/THz. + ``"vdos_sem"``: block standard error of ``"vdos"``, same layout and units; NaN for one block. + ``"lag_ps"``: VACF lags in ps, length ``n_frames // 2 + 1``. + ``"vacf"``: mean over blocks, ``{"total": array, "element": {...}, "oxygen": {...}, "qn": {...}}``, + dimensionless. + ``"vacf_sem"``: block standard error of ``"vacf"``, same layout; NaN for one block. + ``"groups"``: the output of :func:`classify_vibrational_groups` on the input structure. + ``"structure"``: the final structure of the last NVE block. + ``"temperature"``: thermo temperature in K of each kept frame of all blocks, as parsed, length + ``n_blocks * n_frames``. + ``"energy_tot"``: total energy in eV of each kept frame of all blocks, as parsed, length + ``n_blocks * n_frames``. + ``"nve_drift"``: a dict over all kept NVE frames, energies per atom (``N`` atoms): + ``"energy_drift_mev_per_atom_ps"``, the least-squares slope of ``E_tot / N`` in meV/atom/ps over all + blocks, boundary jumps included; ``"block_energy_drift_mev_per_atom_ps"``, the same slope within each + block, array of length ``n_blocks``; ``"boundary_energy_jump_mev_per_atom"``, ``E_tot / N`` of the step-0 + frame of block ``b + 1`` minus that of the last kept frame of block ``b`` in meV/atom, array of length + ``n_blocks - 1``; ``"max_energy_deviation_mev_per_atom"``, the largest ``|E_tot - E_tot[0]| / N`` in + meV/atom from the first kept frame; ``"temperature_mean_k"`` and ``"temperature_std_k"`` (population + standard deviation, ddof=0) in K; and ``"temperature_drift_k_per_ps"``, the least-squares slope in K/ps. + ``"dt_fs"``: time between frames in fs. + ``"n_blocks"``: number of NVE blocks. + ``"n_frames"``: number of kept frames per block. + ``"resolution_thz"``: 1 / ``block_ps``. + ``"nyquist_thz"``: 1 / (2 ``dt_fs``) in THz. + ``"normalization"``: the VDOS normalisation. + ``"window"``: the window of ``vdos["windowed"]``, as passed. + + Raises: + ValueError: Before any MD, if the potential is empty, ``temperature_sim``, ``timestep``, ``block_ps`` or + ``production_ps`` is not positive and finite, ``dump_every`` is not a positive integer, + ``equilibration_steps`` is negative or not an integer, ``normalization`` is not ``"unit"`` or ``"3N"``, + ``window`` is unknown, ``block_ps`` or ``production_ps`` is not a whole number of timesteps, the block is + not a multiple of ``dump_every`` or holds fewer than 2 frames, the production is not a multiple of the + block, ``thermostat`` is unknown, or ``keep_trajectory`` is True without a ``tmp_working_directory``. + RuntimeError: If the output of an NVE block does not hold ``n_frames + 1`` frames of velocities, temperature + and total energy. The message names the block and, with a ``tmp_working_directory``, its kept dump; no + later block is run. + + Warns: + UserWarning: If the Nyquist frequency is below 50 THz, or if no dump of a block is found to delete. + + Example: + ```pycon + >>> out = vdos_simulation(structure, potential, thermostat="nose_hoover") # doctest: +SKIP + >>> out["n_blocks"], out["n_frames"], out["resolution_thz"], out["nyquist_thz"] # doctest: +SKIP + (20, 2000, 0.1, 100.0) + >>> out["vdos"]["windowed"]["element"]["Si"] # doctest: +SKIP + >>> out["vdos_sem"]["windowed"]["element"]["Si"] # doctest: +SKIP + >>> out["nve_drift"]["energy_drift_mev_per_atom_ps"] # doctest: +SKIP + + ``` + """ + if keep_trajectory and tmp_working_directory is None: + msg = "keep_trajectory=True needs a tmp_working_directory; without one every run removes its files." + raise ValueError(msg) + block_steps, block_frames, n_blocks, dt_fs = _vdos_simulation_settings( + potential, + temperature_sim, + timestep, + production_ps, + block_ps, + dump_every, + equilibration_steps, + normalization, + window, + ) + nyquist_thz = 500.0 / dt_fs + if nyquist_thz < _MIN_NYQUIST_THZ: + warnings.warn( + f"The Nyquist frequency is {nyquist_thz:g} THz (timestep {timestep} fs, dump_every {dump_every}), below " + f"{_MIN_NYQUIST_THZ:g} THz; silicate spectra reach about 40 THz, so the highest modes are cut and aliased.", + UserWarning, + stacklevel=2, + ) + nvt_ensemble, _ = thermostat_ensembles(thermostat) + groups = classify_vibrational_groups(structure, cutoff, former_types, o_type) + masses = structure.get_masses() + + equilibrated, _ = _run_lammps_md( + structure=structure, + potential=potential, + tmp_working_directory=tmp_working_directory, + temperature=temperature_sim, + n_ionic_steps=10_000, + timestep=timestep, + n_print_thermo=1000, + initial_temperature=temperature_sim, + ensemble="nvt_langevin", + seed=seed, + server_kwargs=server_kwargs, + ) + if equilibration_steps > 0: + equilibrated, _ = _run_lammps_md( + structure=equilibrated, + potential=potential, + tmp_working_directory=tmp_working_directory, + temperature=temperature_sim, + n_ionic_steps=equilibration_steps, + timestep=timestep, + n_print_thermo=1000, + initial_temperature=temperature_sim, + ensemble=nvt_ensemble, + seed=seed, + server_kwargs=server_kwargs, + ) + # No temperature and no initial temperature: plain fix nve from the velocities of the previous stage. + nve_kwargs = { + "potential": potential, + "temperature": None, + "initial_temperature": None, + "n_ionic_steps": block_steps, + "timestep": timestep, + "n_dump": dump_every, + "ensemble": "nve", + "seed": seed, + "server_kwargs": server_kwargs, + } + spectral_groups = {"total": {"all": np.arange(len(structure))}, **groups} + structure_final = equilibrated + spectra, temperatures, energies, step0_energies = [], [], [], [] + for block in range(1, n_blocks + 1): + # Own directory per block, so its dump can be found and deleted; a random suffix avoids collisions on reuse. + block_dir = ( + None + if tmp_working_directory is None + else tempfile.mkdtemp(prefix=f"vdos_nve_block_{block:03d}_", dir=tmp_working_directory) + ) + structure_final, block_spectra, temperature, energy_tot, step0_energy = _nve_block( + structure_final, + nve_kwargs, + block, + n_blocks, + block_frames, + masses, + dt_fs, + spectral_groups, + normalization, + window, + block_dir, + keep_trajectory=keep_trajectory, + ) + spectra.append(block_spectra) + temperatures.append(temperature) + energies.append(energy_tot) + step0_energies.append(step0_energy) + + vdos, vdos_sem = _block_statistics([block_spectra["vdos"] for block_spectra in spectra]) + vacf, vacf_sem = _block_statistics([block_spectra["vacf"] for block_spectra in spectra]) + temperature, energy_tot = np.concatenate(temperatures), np.concatenate(energies) + + return { + "frequencies_thz": spectra[0]["frequencies_thz"], + "vdos": vdos, + "vdos_sem": vdos_sem, + "lag_ps": spectra[0]["lag_ps"], + "vacf": vacf, + "vacf_sem": vacf_sem, + "groups": groups, + "structure": structure_final, + "temperature": temperature, + "energy_tot": energy_tot, + "nve_drift": _nve_drift(temperature, energy_tot, step0_energies, len(structure), dt_fs), + "dt_fs": dt_fs, + "n_blocks": n_blocks, + "n_frames": block_frames, + "resolution_thz": 1.0 / block_ps, + "nyquist_thz": nyquist_thz, + "normalization": normalization, + "window": window, + } diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/thermodynamics.py b/amorphouspy/src/amorphouspy/properties/vibrational/thermodynamics.py new file mode 100644 index 00000000..b5fb2952 --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/thermodynamics.py @@ -0,0 +1,208 @@ +"""Harmonic vibrational thermodynamics from a VDOS.""" + +from typing import Any + +import numpy as np +from numpy.typing import ArrayLike, NDArray +from scipy.constants import Boltzmann, e, h + +from amorphouspy.properties.vibrational._common import _MIN_GRID_POINTS, _is_real_number +from amorphouspy.properties.vibrational.units import _THZ_TO_UNIT + +# h nu / k_B in K for nu = 1 THz (about 48 K), and k_B T in meV for T = 1 K. +_THZ_TO_K = h * 1e12 / Boltzmann +_K_TO_MEV = Boltzmann / e * 1e3 +# Cap of x = h nu / (k_B T): exp(-x / 2) is exactly 0 from x = 1491 on, so every term of a capped mode is 0. +_MAX_REDUCED_FREQUENCY = 1500.0 + + +def _validate_thermodynamics_inputs( + frequencies_thz: NDArray, vdos: NDArray, temperatures_k: ArrayLike +) -> tuple[NDArray[np.float64], NDArray[np.float64], NDArray[np.float64]]: + frequencies_thz = np.asarray(frequencies_thz, dtype=np.float64) + vdos = np.asarray(vdos, dtype=np.float64) + temperatures_k = _temperatures_array(temperatures_k) + if frequencies_thz.ndim != 1 or vdos.shape != frequencies_thz.shape: + msg = ( + "frequencies_thz and vdos must be 1-D arrays of the same length, " + f"got shapes {frequencies_thz.shape} and {vdos.shape}." + ) + raise ValueError(msg) + if frequencies_thz.size < _MIN_GRID_POINTS: + msg = f"At least 2 frequencies are needed, got {frequencies_thz.size}." + raise ValueError(msg) + if not (np.all(np.isfinite(frequencies_thz)) and np.all(np.isfinite(vdos))): + msg = "frequencies_thz and vdos must not contain NaN or inf." + raise ValueError(msg) + if np.any(vdos < 0): + msg = "vdos must not be negative." + raise ValueError(msg) + if np.any(np.diff(frequencies_thz) <= 0): + msg = "frequencies_thz must be strictly increasing." + raise ValueError(msg) + if not np.any(frequencies_thz > 0): + msg = "frequencies_thz must contain at least one frequency above 0 THz." + raise ValueError(msg) + _check_temperatures(temperatures_k) + return frequencies_thz, vdos, temperatures_k + + +def _temperatures_array(temperatures_k: ArrayLike) -> NDArray[np.float64]: + """Return ``temperatures_k`` as a float64 array of at least 1-D; raise for booleans, which would cast to 0 and 1.""" + if np.asarray(temperatures_k).dtype == np.bool_: + msg = "temperatures_k must be a scalar or a non-empty 1-D array of finite, non-negative values, not booleans." + raise ValueError(msg) + return np.array(temperatures_k, dtype=np.float64, ndmin=1) + + +def _check_temperatures(temperatures_k: NDArray[np.float64]) -> None: + """Raise unless ``temperatures_k`` (float64, at least 1-D) is a non-empty 1-D array of finite values >= 0.""" + valid_temperatures = np.all(np.isfinite(temperatures_k) & (temperatures_k >= 0)) + if temperatures_k.ndim != 1 or temperatures_k.size == 0 or not valid_temperatures: + msg = "temperatures_k must be a scalar or a non-empty 1-D array of finite, non-negative values." + raise ValueError(msg) + + +def compute_vibrational_thermodynamics( + frequencies_thz: NDArray, + vdos: NDArray, + temperatures_k: ArrayLike, + *, + lowest_frequency_thz: float | None = None, +) -> dict[str, Any]: + r"""Compute the harmonic heat capacity, entropy and energies from a VDOS, with a lower temperature bound. + + Each mode of frequency $\nu$ is a quantum harmonic oscillator. With $x = h \nu / (k_B T)$ it contributes + + $$C_V = k_B \frac{x^2 e^x}{(e^x - 1)^2}, \quad + S = k_B \left[\frac{x}{e^x - 1} - \ln\left(1 - e^{-x}\right)\right],$$ + + $$U = \frac{h \nu}{2} + \frac{h \nu}{e^x - 1}, \quad F = \frac{h \nu}{2} + k_B T \ln\left(1 - e^{-x}\right), + \quad E_\mathrm{ZP} = \frac{h \nu}{2},$$ + + and a quantity per atom is $Q(T) = 3 \int g(\nu)\, q(\nu, T)\, d\nu$ (three modes per atom), integrated with the + trapezoid rule on the given grid, as the VDOS functions of this module normalise. The VDOS must therefore be + normalised to 1 (``normalization="unit"`` in :func:`compute_vdos_from_velocities`); this is not enforced, and + ``"vdos_integral"`` lets the caller check it. A partial VDOS from :func:`compute_partial_vdos` with ``"unit"`` gives + that group's additive contribution per atom of the whole system, so the partials sum to the total. At $T = 0$ the + exact limits are returned: $C_V = S = 0$ and $U = F = E_\mathrm{ZP}$. Large $x$ is evaluated in forms that cannot + overflow (with ``np.expm1`` and ``np.log1p(-np.exp(-x))``). + + $S$ and $F$ diverge as $\nu \to 0$, so only $\nu > 0$ is integrated: the integrand is set to zero at every grid + point with $\nu \le 0$ (the zero-frequency bin of the VACF route, and imaginary harmonic modes stored as negative + frequencies) and the trapezoid rule runs over the full grid. Nothing is dropped silently: ``"vdos_integral"`` is the + integral of $g$ over the full grid, and ``"excluded_weight"`` is that integral minus the integral of $g$ with the + points at $\nu \le 0$ set to zero, i.e. the share of modes left out. At high $T$, $C_V$ tends to + $3 \, (\mathrm{vdos\_integral} - \mathrm{excluded\_weight})$ k$_B$ per atom. + + At low temperature the values depend on the low-frequency VDOS, which a finite box or a short trajectory does not + resolve. Below $T_\mathrm{min} = h \nu_\mathrm{low} / k_B$ (1 THz corresponds to 48 K) the values are flagged as + unreliable, not removed. Usual choices of $\nu_\mathrm{low}$ (``lowest_frequency_thz``) are + ``debye["lowest_box_frequency_thz"]`` from :func:`compute_debye_level` (the lowest acoustic mode of the box), the + frequency resolution $1 / (N \Delta t)$ of the VACF route, or the lowest non-zero mode of the harmonic route. With + ``None`` the first positive grid frequency is used, which is only the resolution of the grid, not the box limit, so + the bound is then too optimistic for a small box. $T = 0$ is always flagged. + + Args: + frequencies_thz: Frequencies in THz, 1-D and strictly increasing. Zero and negative values are allowed and + excluded from the integrals. + vdos: VDOS on ``frequencies_thz``, 1-D of the same length, non-negative, in 1/THz and normalised to 1. + temperatures_k: Temperatures in K, a scalar, a list or a 1-D array of finite values $\ge 0$. + lowest_frequency_thz: $\nu_\mathrm{low}$ in THz for the temperature bound, positive and finite, or ``None`` + (default) for the first positive grid frequency. + + Returns: + A dict with: + ``"temperatures_k"``: the temperatures as a float64 array (length 1 for a scalar). + ``"heat_capacity_kb_per_atom"``: $C_V$ in k$_B$ per atom, an array of the same length. + ``"entropy_kb_per_atom"``: $S$ in k$_B$ per atom. + ``"internal_energy_mev_per_atom"``: $U$ in meV per atom, including the zero-point energy. + ``"free_energy_mev_per_atom"``: $F$ in meV per atom, including the zero-point energy. + ``"zero_point_energy_mev_per_atom"``: $E_\mathrm{ZP}$ in meV per atom, a float. + ``"temperature_bound_k"``: $T_\mathrm{min}$ in K, a float. + ``"reliable"``: boolean array, True where $T \ge T_\mathrm{min}$. + ``"lowest_frequency_thz"``: $\nu_\mathrm{low}$ in THz. + ``"lowest_frequency_source"``: ``"caller"`` or ``"grid"``. + ``"vdos_integral"``: trapezoid integral of ``vdos`` over the full grid. + ``"excluded_weight"``: the part of ``"vdos_integral"`` at $\nu \le 0$ that is left out. + + Raises: + ValueError: If ``frequencies_thz`` and ``vdos`` are not 1-D arrays of the same length with at least 2 points, + contain NaN or inf, ``vdos`` is negative anywhere, the frequencies are not strictly increasing or none is + above 0, a temperature is negative or not finite, or ``lowest_frequency_thz`` is not positive and finite. + + Example: + ```pycon + >>> frequencies_thz = np.linspace(0.0, 10.0, 1001) + >>> vdos = 3 * frequencies_thz**2 / 10.0**3 # Debye VDOS with nu_D = 10 THz (theta_D = 480 K) + >>> thermo = compute_vibrational_thermodynamics( + ... frequencies_thz, vdos, [0.0, 300.0, 3000.0], lowest_frequency_thz=1.0 + ... ) + >>> thermo["heat_capacity_kb_per_atom"].round(3) + array([0. , 2.649, 2.996]) + >>> round(thermo["temperature_bound_k"], 1), thermo["reliable"].tolist() + (48.0, [False, True, True]) + >>> round(thermo["zero_point_energy_mev_per_atom"], 2) # 9/8 h nu_D + 46.53 + + ``` + """ + frequencies_thz, vdos, temperatures_k = _validate_thermodynamics_inputs(frequencies_thz, vdos, temperatures_k) + positive = frequencies_thz > 0 + if lowest_frequency_thz is None: + lowest_thz = float(frequencies_thz[positive][0]) + source = "grid" + else: + is_number = _is_real_number(lowest_frequency_thz) + if not (is_number and np.isfinite(lowest_frequency_thz) and lowest_frequency_thz > 0): + msg = f"lowest_frequency_thz must be positive and finite, got {lowest_frequency_thz}." + raise ValueError(msg) + lowest_thz = float(lowest_frequency_thz) + source = "caller" + + # Trapezoid weights of the full grid, so that sum(weights * f) is np.trapezoid(f, frequencies_thz). Keeping only the + # points with nu > 0 integrates the integrand set to zero at nu <= 0. Three modes per atom. + spacing = np.diff(frequencies_thz) + weights = np.zeros_like(frequencies_thz) + weights[:-1] += spacing / 2 + weights[1:] += spacing / 2 + mode_weights = 3 * (weights * vdos)[positive] + mode_k = frequencies_thz[positive] * _THZ_TO_K + mode_mev = frequencies_thz[positive] * _THZ_TO_UNIT["meV"] + vdos_integral = float(np.trapezoid(vdos, frequencies_thz)) + positive_integral = float(np.trapezoid(np.where(positive, vdos, 0.0), frequencies_thz)) + + zero_point = float(mode_weights @ mode_mev) / 2 + heat_capacity = np.zeros_like(temperatures_k) + entropy = np.zeros_like(temperatures_k) + internal_energy = np.full_like(temperatures_k, zero_point) + free_energy = np.full_like(temperatures_k, zero_point) + for i in np.flatnonzero(temperatures_k > 0): + # Capped where exp(-x / 2) is already exactly 0, so an overflow of x at a subnormal T cannot give inf * 0. + with np.errstate(over="ignore"): + x = np.minimum(mode_k / temperatures_k[i], _MAX_REDUCED_FREQUENCY) + exp_neg = np.exp(-x) + one_minus_exp_neg = -np.expm1(-x) + occupation = exp_neg / one_minus_exp_neg # 1 / (e^x - 1) without overflow + log_term = np.log1p(-exp_neg) # ln(1 - e^-x) + # x^2 e^x / (e^x - 1)^2 written so that neither e^x nor x^2 is formed. + heat_capacity[i] = mode_weights @ (x * np.exp(-x / 2) / one_minus_exp_neg) ** 2 + entropy[i] = mode_weights @ (x * occupation - log_term) + internal_energy[i] += mode_weights @ (mode_mev * occupation) + free_energy[i] += _K_TO_MEV * temperatures_k[i] * (mode_weights @ log_term) + + temperature_bound_k = lowest_thz * _THZ_TO_K + return { + "temperatures_k": temperatures_k, + "heat_capacity_kb_per_atom": heat_capacity, + "entropy_kb_per_atom": entropy, + "internal_energy_mev_per_atom": internal_energy, + "free_energy_mev_per_atom": free_energy, + "zero_point_energy_mev_per_atom": zero_point, + "temperature_bound_k": temperature_bound_k, + "reliable": temperatures_k >= temperature_bound_k, + "lowest_frequency_thz": lowest_thz, + "lowest_frequency_source": source, + "vdos_integral": vdos_integral, + "excluded_weight": vdos_integral - positive_integral, + } diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/units.py b/amorphouspy/src/amorphouspy/properties/vibrational/units.py new file mode 100644 index 00000000..fcaca3ca --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/units.py @@ -0,0 +1,52 @@ +"""Frequency units of the vibrational modules: THz, cm^-1, meV and rad/ps.""" + +from typing import Literal + +import numpy as np +from numpy.typing import NDArray +from scipy.constants import c, e, h + +FrequencyUnit = Literal["THz", "cm-1", "meV", "rad/ps"] + +# Value of 1 THz in each unit. +_THZ_TO_UNIT: dict[str, float] = { + "THz": 1.0, + "cm-1": 1e12 / (100 * c), + "meV": (h * 1e12 / e) * 1e3, + "rad/ps": 2 * np.pi, +} + + +def convert_frequency( + values: float | NDArray, from_unit: FrequencyUnit, to_unit: FrequencyUnit +) -> float | NDArray[np.float64]: + """Convert frequencies between THz, cm^-1, meV and rad/ps. + + The conversion goes through THz. Negative values (the convention for imaginary harmonic modes) keep their sign. + + Args: + values: Frequency or array of frequencies in ``from_unit``. + from_unit: Unit of ``values``: ``"THz"``, ``"cm-1"``, ``"meV"`` or ``"rad/ps"``. + to_unit: Target unit, one of the same four. + + Returns: + A float for scalar input, otherwise a new float64 array of the same shape as ``values``. The input is never + modified; ``from_unit == to_unit`` returns a copy. + + Raises: + ValueError: If ``from_unit`` or ``to_unit`` is not one of the allowed units. + + Example: + >>> round(convert_frequency(1.0, "THz", "cm-1"), 5) + 33.35641 + >>> convert_frequency(np.array([-1.0, 2.0]), "THz", "rad/ps").round(4) + array([-6.2832, 12.5664]) + """ + for unit in (from_unit, to_unit): + if unit not in _THZ_TO_UNIT: + msg = f"Unknown frequency unit {unit!r}; allowed units are {list(_THZ_TO_UNIT)}." + raise ValueError(msg) + converted = np.asarray(values, dtype=np.float64) * (_THZ_TO_UNIT[to_unit] / _THZ_TO_UNIT[from_unit]) + if converted.ndim == 0: + return float(converted) + return converted diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/vacf.py b/amorphouspy/src/amorphouspy/properties/vibrational/vacf.py new file mode 100644 index 00000000..1e58293c --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/vacf.py @@ -0,0 +1,227 @@ +"""Velocity autocorrelation function from velocity trajectories, total and per group.""" + +from typing import Literal + +import numpy as np +import scipy.fft +from numpy.typing import NDArray + +from amorphouspy.properties.vibrational._common import _columns_by_group, _group_selections, _membership +from amorphouspy.properties.vibrational._trajectory import ( + _accumulate_power, + _trajectory_statistics, + _validate_trajectory, +) + +VacfNormalization = Literal["unit", "none"] + + +def _vacf_columns( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + selections: dict[str, NDArray] | None, + max_lag_frames: int | None, + normalization: str, + *, + remove_com: bool, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Shared implementation: VACF of the whole system (``selections=None``) or of each named selection, as columns.""" + velocities, masses = _validate_trajectory(velocities, masses, dt_fs) + if normalization not in ("unit", "none"): + msg = f"Unknown normalization {normalization!r}; allowed values are 'unit' and 'none'." + raise ValueError(msg) + n_frames, n_atoms, _ = velocities.shape + if max_lag_frames is None: + max_lag_frames = n_frames // 2 + elif isinstance(max_lag_frames, bool) or not ( + isinstance(max_lag_frames, int | np.integer) and 1 <= max_lag_frames <= n_frames - 1 + ): + msg = f"max_lag_frames must be an integer in [1, {n_frames - 1}], got {max_lag_frames!r}." + raise ValueError(msg) + membership = _membership(selections, n_atoms) + com_velocity, _, kinetic_sum = _trajectory_statistics(velocities, masses, None, remove_com=remove_com) + # Zero padding to 2N makes the correlation linear. The inverse transform is linear, so it is applied once to the + # mass-weighted power of each column instead of once per atom. + power = _accumulate_power(velocities, masses, com_velocity, membership, None, n_fft=2 * n_frames) + n_lags = max_lag_frames + 1 + origins = n_frames - np.arange(n_lags) + vacf = scipy.fft.irfft(power, n=2 * n_frames, axis=0)[:n_lags] / origins[:, None] + if normalization == "unit": + vacf /= kinetic_sum / n_frames + lag_ps = np.arange(n_lags) * dt_fs * 1e-3 + return lag_ps, vacf + + +def compute_vacf_from_velocities( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + *, + indices: NDArray | None = None, + max_lag_frames: int | None = None, + normalization: VacfNormalization = "unit", + remove_com: bool = True, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + r"""Compute the mass-weighted velocity autocorrelation function (VACF) from an MD velocity trajectory. + + The VACF is + + $$C(t_k) = \frac{\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle} + {\sum_i m_i \langle |\mathbf{v}_i|^2 \rangle}, \quad t_k = k \Delta t,$$ + + where $\langle \cdot \rangle$ is the average over all time origins with the unbiased estimator: lag $k$ averages + the $N - k$ available products, + + $$\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle + = \frac{1}{N - k} \sum_{t=0}^{N-1-k} \sum_i m_i\, \mathbf{v}_i(t) \cdot \mathbf{v}_i(t + k),$$ + + for $k = 0, \dots,$ ``max_lag_frames``, with $N$ frames. Fewer origins enter at larger lags, so the statistical + noise grows with the lag; the default ``max_lag_frames = N // 2`` keeps at least $N/2$ origins at every lag. + + The sums over origins are computed with FFTs (``scipy.fft``). Every velocity component of every atom is + zero-padded to $2N$ frames before the forward transform, so the correlation is linear, not circular (no + wrap-around from the end of the trajectory to its start). The squared transforms are weighted by the masses and + summed over the atoms, and the sum is transformed back once, which is exact because the inverse transform is + linear. No window is applied: the VACF always uses the unwindowed velocities. + + With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, + $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every + frame first, also when ``indices`` selects a subset, exactly as in :func:`compute_vdos_from_velocities`. With + ``remove_com=False`` the velocities are used as given; a constant centre-of-mass velocity $\mathbf{V}$ then adds + $\sum_i m_i |\mathbf{V}|^2$ to the unnormalised total VACF at every lag. + + Normalisation: + + - ``"unit"`` (default): divided by the total VACF at zero lag, the time average of + $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (of $\sum_i m_i |\mathbf{v}_i|^2$ with + ``remove_com=False``), so the total $C(0) = 1$ to rounding. Dimensionless. + - ``"none"``: the numerator $\sum_i m_i \langle \mathbf{v}_i(0) \cdot \mathbf{v}_i(t_k) \rangle$ in amu + (velocity unit)$^2$. Its value at zero lag is the time average of + $\sum_i m_i |\mathbf{v}_i - \mathbf{v}_\mathrm{COM}|^2$ (twice the mean internal kinetic energy). + + A partial VACF (``indices`` given) sums the numerator over the selected atoms only and, with ``"unit"``, is divided + by the same denominator as the total, so partials over disjoint selections add up to the total VACF, and a + partial's $C(0)$ is the selection's share of the centred kinetic sum. The denominator comes from the + statistics read over all atoms, so a partial only transforms the selected atoms. Use + :func:`compute_partial_vacf` for many groups. + + Relation to the VDOS: by the Wiener-Khinchin theorem the VDOS is the Fourier transform of the unnormalised VACF. + For a finite trajectory, the ``"none"`` spectral density of :func:`compute_vdos_from_velocities` (no window, same + ``remove_com``) on its grid $\nu_j = j / (N \Delta t)$ is exactly + + $$S(\nu_j) = 2 \Delta t \left[C(0) + 2 \sum_{k=1}^{N-1} \left(1 - \frac{k}{N}\right) C(t_k) + \cos\left(\frac{2 \pi j k}{N}\right)\right],$$ + + with $C$ the ``"none"`` VACF up to ``max_lag_frames = N - 1`` and $\Delta t$ in ps: the transform over all lags + with a triangular weight. The library computes the VDOS directly from the velocity spectrum, not from this + function; transforming a VACF truncated at a shorter lag gives a lower-resolution spectrum. + + Memory: as in :func:`compute_vdos_from_velocities`, the trajectory is read twice in chunks of atoms, once for the + centre-of-mass velocity, the normalisation and the finiteness check, and once for the transforms, with chunks + sized for the padded length $2N$. float32 input is transformed in single precision (no float64 copy); the + correlation is accumulated in float64. The input is never modified, and it may be a read-only ``np.memmap``. + + Args: + velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` removes the scale. + masses: Atomic masses of shape ``(n_atoms,)`` in amu. + dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). + indices: 0-based positions of the atoms in a partial VACF, e.g. one entry of + :func:`classify_vibrational_groups`. ``None`` (default) gives the total VACF. + max_lag_frames: Largest lag in frames, from 1 to ``n_frames - 1``. ``None`` (default) means + ``n_frames // 2``. + normalization: ``"unit"`` or ``"none"``, see above. + remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. + + Returns: + A tuple ``(lag_ps, vacf)`` of float64 arrays of length ``max_lag_frames + 1``: the lags + ``np.arange(max_lag_frames + 1) * dt_fs * 1e-3`` in ps and the VACF (dimensionless for ``"unit"``, amu + (velocity unit)$^2$ for ``"none"``). + + Raises: + ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not + have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs`` is not a positive finite number, any + mass is not positive and finite, ``velocities`` is not real numeric or contains NaN or inf, + ``normalization`` is unknown, ``max_lag_frames`` is not an integer from 1 to ``n_frames - 1``, + ``indices`` is empty, not 1-D integer, out of range or has duplicates, or there is no motion (all + velocities zero, or none left after centre-of-mass removal). + + Example: + ```pycon + >>> from amorphouspy import get_atomic_mass + >>> dt_fs, n_frames = 5.0, 2000 + >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3 + >>> velocities = np.zeros((n_frames, 2, 3)) + >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps) + >>> velocities[:, 1, 0] = -velocities[:, 0, 0] + >>> masses = np.full(2, get_atomic_mass("Si")) + >>> lag_ps, vacf = compute_vacf_from_velocities(velocities, masses, dt_fs) + >>> lag_ps.shape, round(float(lag_ps[10]), 6) + ((1001,), 0.05) + >>> round(float(vacf[0]), 6), round(float(vacf[10]), 6) # half a 10 THz period after 0.05 ps + (1.0, -1.0) + >>> _, partial = compute_vacf_from_velocities(velocities, masses, dt_fs, indices=np.array([0])) + >>> round(float(partial[0]), 6) + 0.5 + + ``` + """ + selections = None if indices is None else {"indices": indices} + lag_ps, columns = _vacf_columns( + velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com + ) + return lag_ps, np.ascontiguousarray(columns[:, 0]) + + +def compute_partial_vacf( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + groups: dict[str, dict[str, NDArray]], + *, + max_lag_frames: int | None = None, + normalization: VacfNormalization = "unit", + remove_com: bool = True, +) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]: + """Compute partial VACFs for many atom groups with one transform per atom. + + Each partial is exactly what :func:`compute_vacf_from_velocities` returns with ``indices`` set to the group + (same centre-of-mass treatment, lags, normalisation and units), but every atom is transformed once, however many + groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`. Within one + grouping that covers every atom once (e.g. ``"element"``), the partials add up to the total VACF. + + Args: + velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit. + masses: Atomic masses of shape ``(n_atoms,)`` in amu. + dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). + groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of + :func:`classify_vibrational_groups`. Atoms may appear in several groupings. + max_lag_frames: Largest lag in frames, as in :func:`compute_vacf_from_velocities`. + normalization: ``"unit"`` or ``"none"``, as in :func:`compute_vacf_from_velocities`. + remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. + + Returns: + A tuple ``(lag_ps, partial)``: the lags in ps and ``{grouping: {label: vacf}}`` with the same keys as + ``groups``, each a float64 array of length ``max_lag_frames + 1``. + + Raises: + ValueError: As :func:`compute_vacf_from_velocities`, for any group's indices, or if ``groups`` has no labels. + + Example: + ```pycon + >>> rng = np.random.default_rng(0) + >>> velocities = rng.normal(size=(100, 3, 3)) + >>> masses = np.array([28.085, 15.999, 15.999]) + >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}} + >>> lag_ps, partial = compute_partial_vacf(velocities, masses, 5.0, groups) + >>> _, total = compute_vacf_from_velocities(velocities, masses, 5.0) + >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total)) + True + + ``` + """ + keys, selections = _group_selections(groups) + lag_ps, columns = _vacf_columns( + velocities, masses, dt_fs, selections, max_lag_frames, normalization, remove_com=remove_com + ) + return lag_ps, _columns_by_group(groups, keys, columns) diff --git a/amorphouspy/src/amorphouspy/properties/vibrational/vdos.py b/amorphouspy/src/amorphouspy/properties/vibrational/vdos.py new file mode 100644 index 00000000..1019c474 --- /dev/null +++ b/amorphouspy/src/amorphouspy/properties/vibrational/vdos.py @@ -0,0 +1,276 @@ +"""Vibrational density of states from velocity trajectories, total and per group.""" + +from typing import Literal + +import numpy as np +import scipy.signal +from numpy.typing import NDArray + +from amorphouspy.properties.vibrational._common import ( + VdosNormalization, + _columns_by_group, + _group_selections, + _membership, +) +from amorphouspy.properties.vibrational._trajectory import ( + _accumulate_power, + _trajectory_statistics, + _validate_trajectory, +) + +VdosWindow = Literal["hann", "hamming", "blackmanharris"] | tuple[Literal["gaussian"], float] | None +_WINDOWS = ("hann", "hamming", "blackmanharris") +_GAUSSIAN_LEN = 2 # ("gaussian", std) + + +def _validate_window(window: object) -> None: + gaussian = ( + isinstance(window, tuple) + and len(window) == _GAUSSIAN_LEN + and window[0] == "gaussian" + and isinstance(window[1], int | float | np.integer | np.floating) + and not isinstance(window[1], bool) + and np.isfinite(window[1]) + and window[1] > 0 + ) + if not (gaussian or window is None or (isinstance(window, str) and window in _WINDOWS)): + msg = ( + f"Unknown window {window!r}; allowed values are 'hann', 'hamming', 'blackmanharris', " + "('gaussian', std) with std > 0 in frames, and None." + ) + raise ValueError(msg) + + +def _validate_vdos_inputs( + velocities: NDArray, masses: NDArray, dt_fs: float, normalization: str, window: object +) -> tuple[NDArray, NDArray[np.float64]]: + velocities, masses = _validate_trajectory(velocities, masses, dt_fs) + if normalization not in ("unit", "3N", "none"): + msg = f"Unknown normalization {normalization!r}; allowed values are 'unit', '3N' and 'none'." + raise ValueError(msg) + _validate_window(window) + return velocities, masses + + +def _vdos_columns( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + selections: dict[str, NDArray] | None, + normalization: str, + *, + remove_com: bool, + window: VdosWindow, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + """Shared implementation: VDOS of the whole system (``selections=None``) or of each named selection, as columns.""" + velocities, masses = _validate_vdos_inputs(velocities, masses, dt_fs, normalization, window) + n_frames, n_atoms, _ = velocities.shape + membership = _membership(selections, n_atoms) + # get_window builds the periodic (DFT-even) form of each window. + weights = None if window is None else np.asarray(scipy.signal.get_window(window, n_frames), dtype=np.float64) + com_velocity, parseval_sum, _ = _trajectory_statistics(velocities, masses, weights, remove_com=remove_com) + power = _accumulate_power(velocities, masses, com_velocity, membership, weights) + + dt_ps = dt_fs * 1e-3 + frequencies_thz = np.asarray(np.fft.rfftfreq(n_frames, d=dt_ps), dtype=np.float64) + if normalization == "none": + if weights is None: + return frequencies_thz, power * (2 * dt_ps / n_frames) + return frequencies_thz, power * (2 * dt_ps / float(np.sum(weights**2))) + if not parseval_sum > 0: + msg = "The windowed velocity spectrum is zero (the window removes all motion)." + raise ValueError(msg) + reference_integral = 0.5 * float(frequencies_thz[1]) * parseval_sum + scale = 1.0 if normalization == "unit" else 3.0 * n_atoms + return frequencies_thz, power * (scale / reference_integral) + + +def compute_vdos_from_velocities( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + *, + indices: NDArray | None = None, + normalization: VdosNormalization = "unit", + remove_com: bool = True, + window: VdosWindow = None, +) -> tuple[NDArray[np.float64], NDArray[np.float64]]: + r"""Compute the vibrational density of states from an MD velocity trajectory. + + The VDOS is the mass-weighted velocity power spectrum + + $$g(\nu_k) \propto \sum_{i} m_i \sum_{\alpha} |V_{i\alpha}(\nu_k)|^2, + \quad V_{i\alpha}(\nu_k) = \sum_{t=0}^{N-1} v_{i\alpha}(t)\, e^{-2\pi \mathrm{i} k t / N},$$ + + the unnormalised forward DFT along time (the ``np.fft.rfft`` convention; computed with ``scipy.fft.rfft``), on the + one-sided grid + $\nu_k = k / (N \Delta t)$, $k = 0, \dots, \lfloor N/2 \rfloor$, in THz. The frequency resolution is + $1 / (N \Delta t)$ and the highest frequency is the Nyquist frequency $1 / (2 \Delta t)$. No zero padding or + per-atom mean subtraction is applied, and no window unless ``window`` is set. + + With a window, the (centre-of-mass-free) velocities are multiplied by $w_t$, $t = 0, \dots, N-1$, before the + transform. All windows are periodic (``scipy.signal.get_window(window, N)``): + + - ``"hann"``: $w_t = \tfrac{1}{2}\left(1 - \cos(2\pi t / N)\right)$. + - ``"hamming"``: $w_t = 0.54 - 0.46 \cos(2\pi t / N)$. Lower first sidelobe than Hann, but the edges are not + zero (0.08), so leakage far from a peak decays more slowly. + - ``"blackmanharris"``: the 4-term Blackman-Harris window $w_t = \sum_{j=0}^{3} (-1)^j a_j \cos(2\pi j t / N)$, + $a = (0.35875, 0.48829, 0.14128, 0.01168)$, with sidelobes below $-92$ dB. + - ``("gaussian", std)``: $w_t = \exp\left(-\tfrac{1}{2}\left((t - N/2) / \sigma\right)^2\right)$ with + $\sigma$ = ``std`` in frames, so its width relative to the block depends on $N$. It is truncated at the edges + (edge value $e^{-8} \approx 3 \times 10^{-4}$ for $\sigma = N/8$). A narrow window ($\sigma \ll N/8$) widens + every peak and can spread power further than no window at all. + + A window suppresses spectral leakage from the finite trajectory length at the cost of resolution. The effective + resolution is $\mathrm{ENBW} / (N \Delta t)$ with the equivalent noise bandwidth + $\mathrm{ENBW} = N \sum_t w_t^2 / (\sum_t w_t)^2$ bins: 1.5 (Hann), 1.36 (Hamming), 2.0 (Blackman-Harris) and + about $N / (2 \sqrt{\pi} \sigma)$ (Gaussian, $\sigma \ll N$). For 10 ps blocks that is 0.15, 0.14 and 0.20 THz, + and 0.23 THz for a Gaussian with $\sigma = N/8$. With ``window=None`` (default) the full $1 / (N \Delta t)$ + resolution is kept, and a peak between grid points leaks into distant bins. + + With ``remove_com=True`` (default), the instantaneous mass-weighted centre-of-mass velocity of the whole system, + $\mathbf{v}_\mathrm{COM}(t) = \sum_i m_i \mathbf{v}_i(t) / \sum_i m_i$, is subtracted from every atom in every + frame before the transform, also when ``indices`` selects a subset. With ``remove_com=False`` the velocities are + transformed as given, and any centre-of-mass drift appears at and near zero frequency. + + Normalisation (all integrals are trapezoidal over the returned grid): + + - ``"unit"`` (default): the total VDOS integrates to 1 (units 1/THz). + - ``"3N"``: the total VDOS integrates to ``3 * n_atoms`` (the number of degrees of freedom, including the 3 + removed with the centre of mass). + - ``"none"``: the power spectral density $S(\nu_k) = (2 \Delta t / N) \sum_i m_i \sum_\alpha |V_{i\alpha}|^2$ in + amu (velocity unit)$^2$ ps. For an even number of frames its integral equals the time average of + $\sum_i m_i |\mathbf{v}_i|^2$ (twice the mean kinetic energy) exactly, by Parseval's theorem; for an odd number + it is lower by half the last bin. With a window, $V_{i\alpha}$ is the transform of the windowed velocities and + the prefactor is $2 \Delta t / \sum_t w_t^2$ instead of $2 \Delta t / N$; the integral is then the + $w^2$-weighted time average $\sum_t w_t^2 \sum_i m_i |\mathbf{v}_i(t)|^2 / \sum_t w_t^2$ (exact for an even + number of frames). + + With a window, ``"unit"`` and ``"3N"`` are applied to the windowed total VDOS, which still integrates to exactly 1 + and ``3 * n_atoms``. + + A partial VDOS (``indices`` given) is the same spectrum summed over the selected atoms only and is scaled by the + total VDOS's normalisation, so partials over disjoint selections add up to the total. Its integral is the + selection's share of the total kinetic energy, which is close to its share of atoms by equipartition: about + ``3 * len(indices)`` for ``"3N"``. The integral of the total spectrum comes from Parseval's theorem in the time + domain, so a partial only transforms the selected atoms. Use :func:`compute_partial_vdos` for many groups. + + Memory: the trajectory is read twice in chunks of atoms (about 64 MB each), once for the centre-of-mass velocity, + the normalisation and the finiteness check, and once for the transforms. Besides the input, peak memory is about + two chunks. float32 input is transformed in single precision (no float64 copy); the spectrum is accumulated in + float64. The input is never modified, and it may be a read-only ``np.memmap`` (e.g. ``np.load(path, + mmap_mode="r")``), in which case only the chunks being processed are read from disk. + + Args: + velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit; ``"unit"`` and ``"3N"`` remove the + scale. + masses: Atomic masses of shape ``(n_atoms,)`` in amu. + dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). + indices: 0-based positions of the atoms in a partial VDOS, e.g. one entry of + :func:`classify_vibrational_groups`. ``None`` (default) gives the total VDOS. + normalization: ``"unit"``, ``"3N"`` or ``"none"``, see above. + remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. + window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` with ``std > 0`` in frames, + or ``None`` (default) for no window, see above. + + Returns: + A tuple ``(frequencies_thz, vdos)`` of float64 arrays of length ``n_frames // 2 + 1``: the frequencies in THz + from ``np.fft.rfftfreq(n_frames, d=dt_fs * 1e-3)`` and the VDOS in 1/THz (``"unit"``, ``"3N"``) or the power + spectral density (``"none"``). + + Raises: + ValueError: If ``velocities`` is not ``(n_frames, n_atoms, 3)`` with at least one atom, ``masses`` does not + have shape ``(n_atoms,)``, there are fewer than 2 frames, ``dt_fs`` is not a positive finite number, any + mass is not positive and finite, ``velocities`` is not real numeric or contains NaN or inf, + ``normalization`` or ``window`` is unknown, ``indices`` is empty, not 1-D integer, out of range or has + duplicates, or the spectrum vanishes (all velocities zero, no motion left after centre-of-mass removal, + e.g. every atom moves with the same velocity, or, with ``"unit"`` or ``"3N"``, no motion left after the + window). + + Example: + ```pycon + >>> from amorphouspy import get_atomic_mass + >>> dt_fs, n_frames = 5.0, 2000 + >>> t_ps = np.arange(n_frames) * dt_fs * 1e-3 + >>> velocities = np.zeros((n_frames, 2, 3)) + >>> velocities[:, 0, 0] = np.cos(2 * np.pi * 10.0 * t_ps) + >>> velocities[:, 1, 0] = -velocities[:, 0, 0] + >>> masses = np.full(2, get_atomic_mass("Si")) + >>> frequencies_thz, vdos = compute_vdos_from_velocities(velocities, masses, dt_fs) + >>> float(frequencies_thz[np.argmax(vdos)]) + 10.0 + >>> round(float(np.trapezoid(vdos, frequencies_thz)), 6) + 1.0 + >>> _, partial = compute_vdos_from_velocities( + ... velocities, masses, dt_fs, indices=np.array([0]), normalization="3N" + ... ) + >>> round(float(np.trapezoid(partial, frequencies_thz)), 6) + 3.0 + >>> _, vdos_hann = compute_vdos_from_velocities(velocities, masses, dt_fs, window="hann") + >>> float(frequencies_thz[np.argmax(vdos_hann)]), round(float(np.trapezoid(vdos_hann, frequencies_thz)), 6) + (10.0, 1.0) + + ``` + """ + selections = None if indices is None else {"indices": indices} + frequencies_thz, columns = _vdos_columns( + velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window + ) + return frequencies_thz, np.ascontiguousarray(columns[:, 0]) + + +def compute_partial_vdos( + velocities: NDArray, + masses: NDArray, + dt_fs: float, + groups: dict[str, dict[str, NDArray]], + *, + normalization: VdosNormalization = "unit", + remove_com: bool = True, + window: VdosWindow = None, +) -> tuple[NDArray[np.float64], dict[str, dict[str, NDArray[np.float64]]]]: + """Compute partial VDOS for many atom groups with one transform per atom. + + Each partial is exactly what :func:`compute_vdos_from_velocities` returns with ``indices`` set to the group + (same centre-of-mass treatment, window, normalisation and units), but every atom is transformed once, however many + groups it belongs to. ``groups`` has the layout returned by :func:`classify_vibrational_groups`: classify once, then + reuse the indices for any number of trajectories or blocks. Within one grouping that covers every atom once (e.g. + ``"element"``), the partials add up to the total VDOS computed with the same window and normalisation. + + Args: + velocities: Velocities of shape ``(n_frames, n_atoms, 3)`` in any unit. + masses: Atomic masses of shape ``(n_atoms,)`` in amu. + dt_fs: Time between consecutive frames in fs (the dump interval, not the MD timestep). + groups: ``{grouping: {label: indices}}`` with 0-based atom positions, e.g. the output of + :func:`classify_vibrational_groups`. Atoms may appear in several groupings. + normalization: ``"unit"``, ``"3N"`` or ``"none"``, as in :func:`compute_vdos_from_velocities`. + remove_com: Subtract the centre-of-mass velocity of the whole system from every frame. + window: ``"hann"``, ``"hamming"``, ``"blackmanharris"``, ``("gaussian", std)`` or ``None`` (default), as in + :func:`compute_vdos_from_velocities`. + + Returns: + A tuple ``(frequencies_thz, partial)``: the frequencies in THz and ``{grouping: {label: vdos}}`` with the + same keys as ``groups``, each a float64 array of length ``n_frames // 2 + 1``. + + Raises: + ValueError: As :func:`compute_vdos_from_velocities` (including an unknown ``window``), for any group's + indices, or if ``groups`` has no labels. + + Example: + ```pycon + >>> rng = np.random.default_rng(0) + >>> velocities = rng.normal(size=(100, 3, 3)) + >>> masses = np.array([28.085, 15.999, 15.999]) + >>> groups = {"element": {"Si": np.array([0]), "O": np.array([1, 2])}} + >>> frequencies_thz, partial = compute_partial_vdos(velocities, masses, 5.0, groups) + >>> _, total = compute_vdos_from_velocities(velocities, masses, 5.0) + >>> bool(np.allclose(partial["element"]["Si"] + partial["element"]["O"], total)) + True + + ``` + """ + keys, selections = _group_selections(groups) + frequencies_thz, columns = _vdos_columns( + velocities, masses, dt_fs, selections, normalization, remove_com=remove_com, window=window + ) + return frequencies_thz, _columns_by_group(groups, keys, columns) diff --git a/amorphouspy/src/tests/test_vibrational_pure.py b/amorphouspy/src/tests/test_vibrational_pure.py index bca1a6b4..7e014b25 100644 --- a/amorphouspy/src/tests/test_vibrational_pure.py +++ b/amorphouspy/src/tests/test_vibrational_pure.py @@ -1,16 +1,18 @@ """Tests for pure functions in amorphouspy.properties.vibrational.""" +import math import tracemalloc import warnings from pathlib import Path import numpy as np import pytest +import scipy.fft import scipy.linalg from amorphouspy.atoms.mass import get_atomic_mass -from amorphouspy.properties import vibrational from amorphouspy.properties.structural.qn import compute_qn from amorphouspy.properties.vibrational import ( + _common, classify_vibrational_groups, compute_debye_level, compute_harmonic_vdos, @@ -238,6 +240,19 @@ def _random_system(n_frames: int, n_atoms: int, seed: int) -> tuple[np.ndarray, return rng.normal(size=(n_frames, n_atoms, 3)), rng.uniform(1.0, 30.0, size=n_atoms) +def _count_calls(monkeypatch, module, name: str) -> list: + """Wrap ``module.name`` so that the positional arguments of every call are recorded; return the record.""" + calls = [] + original = getattr(module, name) + + def counted(*args, **kwargs): + calls.append(args) + return original(*args, **kwargs) + + monkeypatch.setattr(module, name, counted) + return calls + + def _centred_kinetic_sum(velocities: np.ndarray, masses: np.ndarray) -> float: """Time average of sum_i m_i |v_i - v_com|^2, computed directly.""" com = np.einsum("tia,i->ta", velocities, masses) / masses.sum() @@ -448,6 +463,8 @@ def _vdos_invalid_cases() -> list: nan_velocities = good.copy() nan_velocities[4, 1, 2] = np.nan translation = np.broadcast_to(np.array([0.1, 0.2, 0.3]), (10, 2, 3)) + first_frame_only = np.zeros((10, 2, 3)) # the periodic Hann window is exactly 0 at frame 0 + first_frame_only[0] = good[0] return [ pytest.param(good[:, :, 0], masses, DT_FS, {}, "shape", id="2d-velocities"), pytest.param(good[:, :, :2], masses, DT_FS, {}, "shape", id="two-components"), @@ -456,9 +473,15 @@ def _vdos_invalid_cases() -> list: pytest.param(good[:1], masses, DT_FS, {}, "At least 2 frames", id="one-frame"), pytest.param(good, masses, 0.0, {}, "dt_fs must be positive", id="dt-zero"), pytest.param(good, masses, np.nan, {}, "dt_fs must be positive", id="dt-nan"), + pytest.param(good, masses, None, {}, "dt_fs must be positive", id="dt-none"), pytest.param(good, np.array([M_SI, 0.0]), DT_FS, {}, "positive and finite", id="mass-zero"), pytest.param(good, np.array([-M_SI, M_O]), DT_FS, {}, "positive and finite", id="mass-negative"), pytest.param(nan_velocities, masses, DT_FS, {}, "NaN or inf", id="velocity-nan"), + pytest.param(good.astype(np.complex128), masses, DT_FS, {}, "real numeric", id="velocity-complex"), + pytest.param(good.astype(object), masses, DT_FS, {}, "real numeric", id="velocity-object"), + pytest.param( + first_frame_only, masses, DT_FS, {"window": "hann"}, "window removes all motion", id="window-removes-motion" + ), pytest.param(translation, masses, DT_FS, {}, "zero after removing", id="uniform-translation"), pytest.param(np.zeros((10, 2, 3)), masses, DT_FS, {}, "all velocities are zero", id="all-zero"), pytest.param(good, masses, DT_FS, {"normalization": "per-atom"}, "Unknown normalization", id="normalization"), @@ -591,12 +614,16 @@ def test_vdos_chunking_matches_single_chunk(monkeypatch, window, chunk_bytes, n_ """Total and partial results do not depend on how atoms are split into chunks, with and without a window.""" velocities, masses = _random_system(n_frames, 7, seed=27) groups = {"a": {"odd": np.array([1, 3, 5]), "first": np.array([0, 1, 2])}} - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 2**40) + monkeypatch.setattr(_common, "_CHUNK_BYTES", 2**40) _, reference = compute_vdos_from_velocities(velocities, masses, DT_FS, window=window) _, reference_partial = compute_partial_vdos(velocities, masses, DT_FS, groups, window=window) - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", chunk_bytes) + monkeypatch.setattr(_common, "_CHUNK_BYTES", chunk_bytes) + transforms = _count_calls(monkeypatch, scipy.fft, "rfft") _, vdos = compute_vdos_from_velocities(velocities, masses, DT_FS, window=window) _, partial = compute_partial_vdos(velocities, masses, DT_FS, groups, window=window) + # One transform per chunk: the 7 atoms of the total, then the 5 atoms in the groups. + atoms_per_chunk = max(1, chunk_bytes // (n_frames * 3 * velocities.itemsize)) + assert len(transforms) == math.ceil(7 / atoms_per_chunk) + math.ceil(5 / atoms_per_chunk) np.testing.assert_allclose(vdos, reference, rtol=1e-12) for label in groups["a"]: np.testing.assert_allclose(partial["a"][label], reference_partial["a"][label], rtol=1e-12) @@ -732,12 +759,16 @@ def test_vacf_chunking_matches_single_chunk(monkeypatch, chunk_bytes, remove_com """Total and partial VACFs do not depend on how atoms are split into chunks.""" velocities, masses = _random_system(50, 7, seed=38) groups = {"a": {"odd": np.array([1, 3, 5]), "first": np.array([0, 1, 2])}} - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 2**40) + monkeypatch.setattr(_common, "_CHUNK_BYTES", 2**40) _, reference = compute_vacf_from_velocities(velocities, masses, DT_FS, remove_com=remove_com) _, reference_partial = compute_partial_vacf(velocities, masses, DT_FS, groups, remove_com=remove_com) - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", chunk_bytes) + monkeypatch.setattr(_common, "_CHUNK_BYTES", chunk_bytes) + transforms = _count_calls(monkeypatch, scipy.fft, "rfft") _, vacf = compute_vacf_from_velocities(velocities, masses, DT_FS, remove_com=remove_com) _, partial = compute_partial_vacf(velocities, masses, DT_FS, groups, remove_com=remove_com) + # One transform per chunk, sized for the 2N = 100 padded frames: the 7 atoms of the total, then the 5 in the groups. + atoms_per_chunk = max(1, chunk_bytes // (100 * 3 * velocities.itemsize)) + assert len(transforms) == math.ceil(7 / atoms_per_chunk) + math.ceil(5 / atoms_per_chunk) np.testing.assert_allclose(vacf, reference, rtol=1e-12, atol=1e-14) for label in groups["a"]: np.testing.assert_allclose(partial["a"][label], reference_partial["a"][label], rtol=1e-12, atol=1e-14) @@ -786,8 +817,10 @@ def test_vacf_input_unchanged(dtype, remove_com): "masses-length", "one-frame", "dt-nan", + "dt-none", "mass-negative", "velocity-nan", + "velocity-complex", "uniform-translation", "all-zero", "indices-range", @@ -812,6 +845,7 @@ def _vacf_invalid_cases() -> list: pytest.param(good, masses, DT_FS, {"max_lag_frames": -1}, "max_lag_frames", id="max-lag-negative"), pytest.param(good, masses, DT_FS, {"max_lag_frames": 10}, r"in \[1, 9\]", id="max-lag-n-frames"), pytest.param(good, masses, DT_FS, {"max_lag_frames": 2.5}, "max_lag_frames", id="max-lag-float"), + pytest.param(good, masses, DT_FS, {"max_lag_frames": True}, "max_lag_frames", id="max-lag-bool"), ] @@ -933,6 +967,7 @@ def _debye_invalid_cases() -> list: b, g = SILICA_BULK_GPA, SILICA_SHEAR_GPA return [ pytest.param(silica, 0.0, g, {}, "bulk_modulus_gpa must be positive", id="bulk-zero"), + pytest.param(silica, b, None, {}, "shear_modulus_gpa must be positive", id="shear-none"), pytest.param(Atoms(cell=[10.0, 10.0, 10.0], pbc=True), b, g, {}, "no atoms", id="empty"), pytest.param(open_cell, b, g, {}, "periodic in all three", id="non-periodic"), pytest.param(Atoms("SiO2", pbc=True), b, g, {}, "positive volume", id="zero-volume"), @@ -1020,6 +1055,19 @@ def test_thermodynamics_debye_solid(): np.testing.assert_allclose(result["heat_capacity_kb_per_atom"], expected, rtol=1e-7) +@pytest.mark.parametrize("temperature", [5e-324, 1e-310, 1e-307]) +def test_thermodynamics_subnormal_temperature(temperature): + """H nu / (k_B T) overflows at a subnormal T; the T = 0 limits are returned, without NaN or a warning.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + result = compute_vibrational_thermodynamics(DEBYE_GRID_THZ, DEBYE_VDOS, temperature) + zpe = result["zero_point_energy_mev_per_atom"] + assert result["heat_capacity_kb_per_atom"][0] == 0.0 + assert result["entropy_kb_per_atom"][0] == 0.0 + assert result["internal_energy_mev_per_atom"][0] == zpe + assert result["free_energy_mev_per_atom"][0] == zpe + + def test_thermodynamics_limits_and_free_energy(): """T = 0 gives the exact limits, high T the classical 3 k_B, F = U - T S throughout, and nothing overflows.""" temps = np.array([0.0, 1e-3, 300.0, 1e6]) @@ -1101,7 +1149,11 @@ def _thermodynamics_invalid_cases() -> list: pytest.param(freqs[::-1], DEBYE_VDOS, 300.0, {}, "strictly increasing", id="unsorted"), pytest.param([-1.0, 0.0], [1.0, 1.0], 300.0, {}, "above 0 THz", id="no-positive-frequency"), pytest.param(freqs, DEBYE_VDOS, [-1.0, 300.0], {}, "non-negative", id="temperature-negative"), + pytest.param(freqs, DEBYE_VDOS, True, {}, "not booleans", id="temperature-bool"), + pytest.param(freqs, DEBYE_VDOS, [True, False], {}, "not booleans", id="temperature-bool-list"), pytest.param(freqs, DEBYE_VDOS, 300.0, {"lowest_frequency_thz": 0.0}, "positive and finite", id="lowest-zero"), + pytest.param(freqs, DEBYE_VDOS, 300.0, {"lowest_frequency_thz": "1"}, "positive and finite", id="lowest-str"), + pytest.param(freqs, DEBYE_VDOS, 300.0, {"lowest_frequency_thz": True}, "positive and finite", id="lowest-bool"), ] @@ -1214,7 +1266,7 @@ def _read_dynamical_matrix_invalid_cases(): @pytest.mark.parametrize(("write", "n_atoms", "kwargs", "error", "match"), _read_dynamical_matrix_invalid_cases()) def test_read_dynamical_matrix_invalid_raises(monkeypatch, tmp_path, write, n_atoms, kwargs, error, match): """Wrong sizes, non-finite values in a late row block, bad n_atoms or style, and a missing file raise.""" - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 1) # one row per chunk + monkeypatch.setattr(_common, "_CHUNK_BYTES", 1) # one row per chunk path = tmp_path / "dynmat" if write is not None: write(path) @@ -1304,7 +1356,7 @@ def test_diagonalize_asymmetry_is_measured_before_symmetrising(monkeypatch, orde symmetrised = (matrix + matrix.T) / 2 max_abs = np.abs(matrix).max() expected = np.abs(matrix - matrix.T).max() / max_abs - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 5 * n_dof * 8) # 5 rows per block, 5 blocks + monkeypatch.setattr(_common, "_CHUNK_BYTES", 5 * n_dof * 8) # 5 rows per block, 5 blocks received = [] eigh = scipy.linalg.eigh @@ -1355,7 +1407,7 @@ def test_diagonalize_overwrite_without_eigenvectors_does_not_copy(monkeypatch): matrix = _ring_matrix(300, 3.0, 28.0855) # n = 900, 6.5 MB # Real matrices are far above _CHUNK_BYTES; scale the blocks to 1/16 of the matrix so they stay small here too. # Expected peak: about 3 blocks (3/16) plus O(n) LAPACK workspace (~0.03), against >= 1 for any copy. - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", matrix.nbytes // 16) + monkeypatch.setattr(_common, "_CHUNK_BYTES", matrix.nbytes // 16) tracemalloc.start() try: diagonalize_dynamical_matrix(matrix, overwrite_matrix=True, eigenvectors=False) @@ -1393,7 +1445,7 @@ def _diagonalize_invalid_cases(): @pytest.mark.parametrize(("matrix", "kwargs", "match"), _diagonalize_invalid_cases()) def test_diagonalize_invalid_input_raises(monkeypatch, matrix, kwargs, match): """Bad shapes, dtypes, non-finite entries in a later block, masses, drivers and thresholds raise.""" - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 1) # one row per block + monkeypatch.setattr(_common, "_CHUNK_BYTES", 1) # one row per block with pytest.raises(ValueError, match=match): diagonalize_dynamical_matrix(matrix, **kwargs) @@ -1465,8 +1517,14 @@ def test_harmonic_vdos_chunks_give_same_result(monkeypatch): """One mode per block, for the weights and the Gaussians, gives the result of the default blocks.""" frequencies, vectors, groups = _spring_modes() default = compute_harmonic_vdos(frequencies, vectors, groups=groups, normalization="3N") - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 1) + monkeypatch.setattr(_common, "_CHUNK_BYTES", 1) + einsums, exps = _count_calls(monkeypatch, np, "einsum"), _count_calls(monkeypatch, np, "exp") chunked = compute_harmonic_vdos(frequencies, vectors, groups=groups, normalization="3N") + # One mode per block: a weight block per mode, and a block of Gaussians per mode with nu >= 0. + weight_blocks = sum(isinstance(call[0], str) and call[0] == "iak,iak->ik" for call in einsums) + gaussian_blocks = len(exps) + assert weight_blocks == frequencies.size + assert gaussian_blocks == np.count_nonzero(frequencies >= 0) np.testing.assert_allclose(chunked["vdos"]["total"], default["vdos"]["total"], rtol=1e-13, atol=1e-16) for grouping, labels in groups.items(): for label in labels: @@ -1508,6 +1566,8 @@ def _harmonic_invalid_cases(): pytest.param(f, np.zeros((6, 6)), {}, r"\(3N, 3N - 3\)", id="vectors-rows"), pytest.param(f, np.zeros((9, 5)), {}, r"\(3N, 3N - 3\)", id="vectors-columns"), pytest.param(f, None, {"broadening_thz": 0.0}, "positive and finite", id="broadening-zero"), + pytest.param(f, None, {"broadening_thz": None}, "positive and finite", id="broadening-none"), + pytest.param(f, None, {"broadening_thz": True}, "positive and finite", id="broadening-bool"), pytest.param(f, None, {"groups": groups}, "groups need eigenvectors", id="groups-without-vectors"), pytest.param(f, vectors, {"groups": {}}, "no labels", id="groups-empty"), pytest.param(f, None, {"normalization": "none"}, "Unknown normalization", id="normalization"), @@ -1583,9 +1643,15 @@ def test_participation_ratio_chunks_order_and_no_copy(monkeypatch): peak = tracemalloc.get_traced_memory()[1] tracemalloc.stop() assert peak < vectors.nbytes / 2 # the atom weights are a third - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 1) - for ordered in (vectors, np.ascontiguousarray(vectors)): # einsum differs by ulps between memory orders - np.testing.assert_allclose(compute_participation_ratio(ordered, masses), default, rtol=1e-13) + monkeypatch.setattr(_common, "_CHUNK_BYTES", 1) + einsums = _count_calls(monkeypatch, np, "einsum") + orders = (vectors, np.ascontiguousarray(vectors)) + chunked = [compute_participation_ratio(ordered, masses) for ordered in orders] + # One weight block per mode in each of the two calls. + weight_blocks = sum(isinstance(call[0], str) and call[0] == "iak,iak->ik" for call in einsums) + assert weight_blocks == len(orders) * vectors.shape[1] + for ratios in chunked: # einsum differs by ulps between memory orders + np.testing.assert_allclose(ratios, default, rtol=1e-13) def _participation_invalid_cases(): @@ -1607,6 +1673,6 @@ def _participation_invalid_cases(): @pytest.mark.parametrize(("vectors", "masses", "match"), _participation_invalid_cases()) def test_participation_ratio_invalid_raises(monkeypatch, vectors, masses, match): """Bad shapes, dtypes and masses, a zero column and NaN in a late block raise.""" - monkeypatch.setattr(vibrational, "_CHUNK_BYTES", 1) # one mode per block + monkeypatch.setattr(_common, "_CHUNK_BYTES", 1) # one mode per block with pytest.raises(ValueError, match=match): compute_participation_ratio(vectors, masses) diff --git a/amorphouspy/src/tests/test_vibrational_simulation.py b/amorphouspy/src/tests/test_vibrational_simulation.py index 9a6032db..20146068 100644 --- a/amorphouspy/src/tests/test_vibrational_simulation.py +++ b/amorphouspy/src/tests/test_vibrational_simulation.py @@ -6,6 +6,7 @@ """ import gc +import shutil import tempfile import warnings import weakref @@ -15,7 +16,6 @@ import numpy as np import pandas as pd import pytest -from amorphouspy.properties import vibrational from amorphouspy.properties.vibrational import ( classify_vibrational_groups, compute_harmonic_vdos, @@ -24,6 +24,7 @@ compute_participation_ratio, compute_vibrational_thermodynamics, diagonalize_dynamical_matrix, + harmonic_simulation, harmonic_vdos_simulation, read_dynamical_matrix, vdos_simulation, @@ -90,7 +91,7 @@ def _potential(): def _run(structure, generic, *, potential=None, side_effect=None, **kwargs): """Call vdos_simulation with the MD runner mocked; by default every stage returns the input structure.""" arguments = {"thermostat": "nose_hoover", "equilibration_steps": 50, **BLOCK, **GROUP_KWARGS, **kwargs} - with patch("amorphouspy.properties.vibrational._run_lammps_md", autospec=True) as mock_md: + with patch("amorphouspy.properties.vibrational.simulation._run_lammps_md", autospec=True) as mock_md: mock_md.return_value = (structure, {"generic": generic}) mock_md.side_effect = side_effect out = vdos_simulation(structure, _potential() if potential is None else potential, **arguments) @@ -359,11 +360,13 @@ def run_md(**kwargs): dumps_at_launch.append(len(list(tmp_path.glob("vdos_nve_block_*/*/dump.out")))) return fake(**kwargs) + checked = [] + def vacf_after_dump_check(*args, **kwargs): - assert (run_dirs[-1] / "dump.out").exists() + checked.append((run_dirs[-1] / "dump.out").exists()) return compute_partial_vacf(*args, **kwargs) - with patch("amorphouspy.properties.vibrational.compute_partial_vacf", side_effect=vacf_after_dump_check): + with patch("amorphouspy.properties.vibrational.simulation.compute_partial_vacf", side_effect=vacf_after_dump_check): _run( structure, None, @@ -373,6 +376,7 @@ def vacf_after_dump_check(*args, **kwargs): keep_trajectory=keep_trajectory, ) + assert checked == [True] * 3 # the patch took effect: each block's dump existed when its VACF was computed block_dirs = [run_dir.parent for run_dir in run_dirs[2:]] assert [d.parent for d in block_dirs] == [tmp_path] * 3 assert all(d.name.startswith(f"vdos_nve_block_{block:03d}_") for block, d in enumerate(block_dirs, start=1)) @@ -494,12 +498,15 @@ def test_vdos_simulation_nyquist_warning(): [ ({"potential": pd.DataFrame()}, "No matching potential"), ({"timestep": 0.0}, "timestep must be positive and finite"), + ({"timestep": None}, "timestep must be positive and finite"), + ({"temperature_sim": True}, "temperature_sim must be positive and finite"), ({"block_ps": -1.0}, "block_ps must be positive and finite"), ({"temperature_sim": float("nan")}, "temperature_sim must be positive and finite"), ({"dump_every": 0}, "dump_every must be a positive integer"), ({"dump_every": 2.5}, "dump_every must be a positive integer"), ({"dump_every": True}, "dump_every must be a positive integer"), ({"equilibration_steps": -1}, "equilibration_steps must not be negative"), + ({"equilibration_steps": 1.5}, "equilibration_steps must not be negative and must be an integer"), ({"normalization": "none"}, "Unknown normalization"), ({"window": "gaussian"}, "Unknown window 'gaussian'"), ({"timestep": 3.0}, "not a whole number of 3.0 fs timesteps"), @@ -514,12 +521,15 @@ def test_vdos_simulation_nyquist_warning(): ids=[ "potential-empty", "timestep-zero", + "timestep-none", + "temperature-bool", "block-negative", "temperature-nan", "dump-zero", "dump-float", "dump-bool", "equilibration-negative", + "equilibration-float", "normalization-none", "window-gaussian-without-std", "block-not-whole-steps", @@ -536,7 +546,7 @@ def test_vdos_simulation_invalid_inputs_raise(kwargs, match): """Invalid arguments raise before any MD stage is launched.""" arguments = {"potential": _potential(), "thermostat": "nose_hoover", **BLOCK, **GROUP_KWARGS, **kwargs} with ( - patch("amorphouspy.properties.vibrational._run_lammps_md", autospec=True) as mock_md, + patch("amorphouspy.properties.vibrational.simulation._run_lammps_md", autospec=True) as mock_md, pytest.raises(ValueError, match=match), ): vdos_simulation(_si2o7_dimer(), **arguments) @@ -601,7 +611,9 @@ def _run_harmonic(**kwargs): """Call harmonic_vdos_simulation on the dimer with the runner mocked; return result, mock, matrix and structure.""" minimised = _minimised_dimer() matrix = _dynamical_matrix(minimised.get_masses()) - with patch("amorphouspy.properties.vibrational._run_lammps_dynamical_matrix", autospec=True) as runner: + with patch( + "amorphouspy.properties.vibrational.harmonic_simulation._run_lammps_dynamical_matrix", autospec=True + ) as runner: runner.side_effect = _fake_dynamical_matrix_runner(minimised, matrix) out = harmonic_vdos_simulation(_si2o7_dimer(), _potential(), **{**GROUP_KWARGS, **kwargs}) return out, runner, matrix, minimised @@ -622,7 +634,7 @@ def _assert_same(actual, expected): def test_harmonic_vdos_simulation_matches_manual_chain(tmp_path): """The result is exactly read -> diagonalize -> VDOS -> participation ratio -> thermodynamics on the matrix.""" with patch.object( - vibrational, "diagonalize_dynamical_matrix", wraps=vibrational.diagonalize_dynamical_matrix + harmonic_simulation, "diagonalize_dynamical_matrix", wraps=harmonic_simulation.diagonalize_dynamical_matrix ) as diagonalize: out, runner, matrix, minimised = _run_harmonic(temperatures_k=HARMONIC_TEMPERATURES_K, keep_eigenvectors=True) @@ -690,7 +702,9 @@ def test_harmonic_vdos_simulation_atom_guard(): assert _run_harmonic(max_atoms=9)[1].call_count == 1 match = r"9 atoms, more than max_atoms=8.*9 N² x 8 bytes = 5.83e-06 GB.*2 matrices, 1.17e-05 GB. Raise max_atoms" with ( - patch("amorphouspy.properties.vibrational._run_lammps_dynamical_matrix", autospec=True) as runner, + patch( + "amorphouspy.properties.vibrational.harmonic_simulation._run_lammps_dynamical_matrix", autospec=True + ) as runner, pytest.raises(ValueError, match=match), ): harmonic_vdos_simulation(_si2o7_dimer(), _potential(), max_atoms=8, **GROUP_KWARGS) @@ -707,6 +721,7 @@ def test_harmonic_vdos_simulation_atom_guard(): ({"potential": pd.DataFrame()}, "No matching potential"), ({"displacement": 0.0}, "displacement must be positive and finite"), ({"displacement": float("nan")}, "displacement must be positive and finite"), + ({"displacement": None}, "displacement must be positive and finite"), ({"force_tolerance": -1e-6}, "force_tolerance must be finite and non-negative"), ({"force_tolerance": 0.0}, "cannot both be 0"), ({"max_iter": 0}, "max_iter must be a positive integer"), @@ -714,6 +729,7 @@ def test_harmonic_vdos_simulation_atom_guard(): ({"normalization": "none"}, "Unknown normalization"), ({"frequency_grid_thz": [2.0, 1.0]}, "frequency_grid_thz must be"), ({"temperatures_k": [300.0, -1.0]}, "temperatures_k must be"), + ({"temperatures_k": True}, "temperatures_k must be.*not booleans"), ({"driver": "evz"}, "Unknown driver"), ({"imaginary_threshold_thz": -0.01}, "imaginary_threshold_thz must be >= 0"), ({"keep_dynamical_matrix": True}, "keep_dynamical_matrix=True needs a tmp_working_directory"), @@ -726,6 +742,7 @@ def test_harmonic_vdos_simulation_atom_guard(): "potential-empty", "displacement-zero", "displacement-nan", + "displacement-none", "force-tolerance-negative", "force-tolerance-zero", "max-iter-zero", @@ -733,6 +750,7 @@ def test_harmonic_vdos_simulation_atom_guard(): "normalization-none", "grid-decreasing", "temperature-negative", + "temperature-bool", "driver", "threshold-negative", "keep-matrix-without-directory", @@ -742,7 +760,9 @@ def test_harmonic_vdos_simulation_invalid_inputs_raise(kwargs, match): """Invalid arguments raise before the LAMMPS runner is called.""" arguments = {"potential": _potential(), **GROUP_KWARGS, **kwargs} with ( - patch("amorphouspy.properties.vibrational._run_lammps_dynamical_matrix", autospec=True) as runner, + patch( + "amorphouspy.properties.vibrational.harmonic_simulation._run_lammps_dynamical_matrix", autospec=True + ) as runner, pytest.raises(ValueError, match=match), ): harmonic_vdos_simulation(_si2o7_dimer(), **arguments) @@ -773,6 +793,35 @@ def test_harmonic_vdos_simulation_matrix_file(directory, keep_dynamical_matrix, assert (tmp_path / "lammps_run" / "log.lammps").exists() +@pytest.mark.parametrize("directory", [False, True], ids=["system-temp", "tmp_working_directory"]) +def test_harmonic_vdos_simulation_checks_free_space(monkeypatch, directory, tmp_path): + """Too little free space where the matrix file goes raises before the runner; exactly enough space runs.""" + matrix_bytes = 9 * 9**2 * 8 + parent = str(tmp_path) if directory else tempfile.gettempdir() + kwargs = {"tmp_working_directory": tmp_path} if directory else {} + checked = [] + + def usage(free): + def disk_usage(path): + checked.append(str(path)) + return shutil._ntuple_diskusage(2 * free, free, free) # noqa: SLF001 + + return disk_usage + + monkeypatch.setattr(harmonic_simulation.shutil, "disk_usage", usage(matrix_bytes - 1)) + with ( + patch( + "amorphouspy.properties.vibrational.harmonic_simulation._run_lammps_dynamical_matrix", autospec=True + ) as runner, + pytest.raises(ValueError, match=r"9 N² x 8 bytes = 5.83e-06 GB, but .* has only 5.83e-06 GB free"), + ): + harmonic_vdos_simulation(_si2o7_dimer(), _potential(), **GROUP_KWARGS, **kwargs) + assert runner.call_count == 0 + monkeypatch.setattr(harmonic_simulation.shutil, "disk_usage", usage(matrix_bytes)) + assert _run_harmonic(**kwargs)[1].call_count == 1 + assert checked == [parent, parent] + + @pytest.mark.parametrize("keep_eigenvectors", [False, True], ids=["drop", "keep"]) def test_harmonic_vdos_simulation_eigenvectors(keep_eigenvectors): """The eigenvectors are returned only when kept; otherwise their buffer is freed and every other entry is equal.""" @@ -786,7 +835,7 @@ def spy(*args, **kwargs): buffers.append(weakref.ref(root)) return modes - with patch.object(vibrational, "diagonalize_dynamical_matrix", side_effect=spy): + with patch.object(harmonic_simulation, "diagonalize_dynamical_matrix", side_effect=spy): out, _, matrix, minimised = _run_harmonic(keep_eigenvectors=keep_eigenvectors) gc.collect() assert (buffers[0]() is not None) is keep_eigenvectors @@ -814,3 +863,23 @@ def test_harmonic_vdos_simulation_thermodynamics(): assert three_n[key] == value else: np.testing.assert_allclose(three_n[key], value, rtol=1e-12) + + +def test_harmonic_vdos_simulation_without_positive_mode_skips_thermodynamics(): + """With every kept mode imaginary, the result is still returned, with a warning and no thermodynamics.""" + minimised = _minimised_dimer() + matrix = -_dynamical_matrix(minimised.get_masses()) # translations stay at 0, every other mode turns imaginary + with ( + patch( + "amorphouspy.properties.vibrational.harmonic_simulation._run_lammps_dynamical_matrix", + autospec=True, + side_effect=_fake_dynamical_matrix_runner(minimised, matrix), + ), + pytest.warns(UserWarning, match="24 imaginary mode"), + pytest.warns(UserWarning, match="No mode has a positive frequency"), + ): + out = harmonic_vdos_simulation( + _si2o7_dimer(), _potential(), temperatures_k=HARMONIC_TEMPERATURES_K, **GROUP_KWARGS + ) + assert out["thermodynamics"] is None + assert out["n_imaginary_excluded"] == len(out["mode_frequencies_thz"]) diff --git a/notebooks/VDOSTutorial.ipynb b/notebooks/VDOSTutorial.ipynb index 19d5d216..f82a03b9 100644 --- a/notebooks/VDOSTutorial.ipynb +++ b/notebooks/VDOSTutorial.ipynb @@ -36,10 +36,10 @@ "id": "07c3b49e", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:20:34.909391Z", - "iopub.status.busy": "2026-11-08T23:20:34.909261Z", - "iopub.status.idle": "2026-11-08T23:20:36.640810Z", - "shell.execute_reply": "2026-11-08T23:20:36.640474Z" + "iopub.execute_input": "2026-11-10T11:35:33.520907Z", + "iopub.status.busy": "2026-11-10T11:35:33.520792Z", + "iopub.status.idle": "2026-11-10T11:35:36.304214Z", + "shell.execute_reply": "2026-11-10T11:35:36.303926Z" } }, "outputs": [], @@ -71,10 +71,10 @@ "id": "b5ba4c41", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:20:36.642529Z", - "iopub.status.busy": "2026-11-08T23:20:36.642366Z", - "iopub.status.idle": "2026-11-08T23:20:36.776412Z", - "shell.execute_reply": "2026-11-08T23:20:36.775980Z" + "iopub.execute_input": "2026-11-10T11:35:36.306008Z", + "iopub.status.busy": "2026-11-10T11:35:36.305840Z", + "iopub.status.idle": "2026-11-10T11:35:36.442643Z", + "shell.execute_reply": "2026-11-10T11:35:36.442352Z" } }, "outputs": [ @@ -133,10 +133,10 @@ "id": "70394342", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:20:36.777772Z", - "iopub.status.busy": "2026-11-08T23:20:36.777675Z", - "iopub.status.idle": "2026-11-08T23:22:12.669954Z", - "shell.execute_reply": "2026-11-08T23:22:12.669326Z" + "iopub.execute_input": "2026-11-10T11:35:36.443892Z", + "iopub.status.busy": "2026-11-10T11:35:36.443825Z", + "iopub.status.idle": "2026-11-10T11:37:11.490056Z", + "shell.execute_reply": "2026-11-10T11:37:11.489702Z" } }, "outputs": [ @@ -144,7 +144,7 @@ "name": "stderr", "output_type": "stream", "text": [ - "/Users/achrafatila/Documents/Workflows/amorphouspy/amorphouspy/src/amorphouspy/properties/vibrational.py:174: UserWarning: r_max=10.0000 Å exceeds half the smallest perpendicular cell height (8.2438 Å). r_max has been automatically adjusted to 8.0 Å (largest integer not exceeding the limit).\n", + "/Users/achrafatila/Documents/Workflows/amorphouspy/amorphouspy/src/amorphouspy/properties/vibrational/classification.py:102: UserWarning: r_max=10.0000 Å exceeds half the smallest perpendicular cell height (8.2438 Å). r_max has been automatically adjusted to 8.0 Å (largest integer not exceeding the limit).\n", " r, rdfs, _cumcn = compute_rdf(structure, r_max=10.0, n_bins=500)\n" ] }, @@ -199,10 +199,10 @@ "id": "b3da3816", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:12.671803Z", - "iopub.status.busy": "2026-11-08T23:22:12.671643Z", - "iopub.status.idle": "2026-11-08T23:22:13.050055Z", - "shell.execute_reply": "2026-11-08T23:22:13.049747Z" + "iopub.execute_input": "2026-11-10T11:37:11.491522Z", + "iopub.status.busy": "2026-11-10T11:37:11.491417Z", + "iopub.status.idle": "2026-11-10T11:37:11.861289Z", + "shell.execute_reply": "2026-11-10T11:37:11.861007Z" } }, "outputs": [ @@ -297,10 +297,10 @@ "id": "026b298f", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.052283Z", - "iopub.status.busy": "2026-11-08T23:22:13.052112Z", - "iopub.status.idle": "2026-11-08T23:22:13.256843Z", - "shell.execute_reply": "2026-11-08T23:22:13.256525Z" + "iopub.execute_input": "2026-11-10T11:37:11.862629Z", + "iopub.status.busy": "2026-11-10T11:37:11.862531Z", + "iopub.status.idle": "2026-11-10T11:37:12.034962Z", + "shell.execute_reply": "2026-11-10T11:37:12.034700Z" } }, "outputs": [ @@ -371,10 +371,10 @@ "id": "f86c0b2e", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.258863Z", - "iopub.status.busy": "2026-11-08T23:22:13.258763Z", - "iopub.status.idle": "2026-11-08T23:22:13.262608Z", - "shell.execute_reply": "2026-11-08T23:22:13.262222Z" + "iopub.execute_input": "2026-11-10T11:37:12.036628Z", + "iopub.status.busy": "2026-11-10T11:37:12.036534Z", + "iopub.status.idle": "2026-11-10T11:37:12.039756Z", + "shell.execute_reply": "2026-11-10T11:37:12.039509Z" } }, "outputs": [ @@ -424,10 +424,10 @@ "id": "44887e9e", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.263979Z", - "iopub.status.busy": "2026-11-08T23:22:13.263907Z", - "iopub.status.idle": "2026-11-08T23:22:13.486301Z", - "shell.execute_reply": "2026-11-08T23:22:13.486020Z" + "iopub.execute_input": "2026-11-10T11:37:12.040953Z", + "iopub.status.busy": "2026-11-10T11:37:12.040881Z", + "iopub.status.idle": "2026-11-10T11:37:12.240252Z", + "shell.execute_reply": "2026-11-10T11:37:12.239987Z" } }, "outputs": [ @@ -502,10 +502,10 @@ "id": "a442af43", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.488326Z", - "iopub.status.busy": "2026-11-08T23:22:13.488212Z", - "iopub.status.idle": "2026-11-08T23:22:13.568763Z", - "shell.execute_reply": "2026-11-08T23:22:13.568426Z" + "iopub.execute_input": "2026-11-10T11:37:12.242146Z", + "iopub.status.busy": "2026-11-10T11:37:12.242060Z", + "iopub.status.idle": "2026-11-10T11:37:12.319900Z", + "shell.execute_reply": "2026-11-10T11:37:12.319629Z" } }, "outputs": [ @@ -575,10 +575,10 @@ "id": "176a9466", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.570210Z", - "iopub.status.busy": "2026-11-08T23:22:13.570109Z", - "iopub.status.idle": "2026-11-08T23:22:13.682284Z", - "shell.execute_reply": "2026-11-08T23:22:13.681982Z" + "iopub.execute_input": "2026-11-10T11:37:12.321248Z", + "iopub.status.busy": "2026-11-10T11:37:12.321153Z", + "iopub.status.idle": "2026-11-10T11:37:12.432820Z", + "shell.execute_reply": "2026-11-10T11:37:12.432539Z" } }, "outputs": [ @@ -701,10 +701,10 @@ "id": "3e7772ba", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:22:13.683613Z", - "iopub.status.busy": "2026-11-08T23:22:13.683522Z", - "iopub.status.idle": "2026-11-08T23:23:48.606388Z", - "shell.execute_reply": "2026-11-08T23:23:48.605990Z" + "iopub.execute_input": "2026-11-10T11:37:12.434546Z", + "iopub.status.busy": "2026-11-10T11:37:12.434452Z", + "iopub.status.idle": "2026-11-10T11:38:45.063478Z", + "shell.execute_reply": "2026-11-10T11:38:45.063113Z" } }, "outputs": [ @@ -744,10 +744,10 @@ "id": "d098ad9c", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:23:48.607838Z", - "iopub.status.busy": "2026-11-08T23:23:48.607735Z", - "iopub.status.idle": "2026-11-08T23:23:48.752639Z", - "shell.execute_reply": "2026-11-08T23:23:48.752354Z" + "iopub.execute_input": "2026-11-10T11:38:45.064952Z", + "iopub.status.busy": "2026-11-10T11:38:45.064850Z", + "iopub.status.idle": "2026-11-10T11:38:45.212036Z", + "shell.execute_reply": "2026-11-10T11:38:45.211747Z" } }, "outputs": [ @@ -942,10 +942,10 @@ "id": "0ea2a4fc", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:23:48.754068Z", - "iopub.status.busy": "2026-11-08T23:23:48.753969Z", - "iopub.status.idle": "2026-11-08T23:23:48.890300Z", - "shell.execute_reply": "2026-11-08T23:23:48.890007Z" + "iopub.execute_input": "2026-11-10T11:38:45.213551Z", + "iopub.status.busy": "2026-11-10T11:38:45.213456Z", + "iopub.status.idle": "2026-11-10T11:38:45.348211Z", + "shell.execute_reply": "2026-11-10T11:38:45.347900Z" } }, "outputs": [ @@ -1079,10 +1079,10 @@ "id": "bbeb979e", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:23:48.891671Z", - "iopub.status.busy": "2026-11-08T23:23:48.891583Z", - "iopub.status.idle": "2026-11-08T23:23:57.557502Z", - "shell.execute_reply": "2026-11-08T23:23:57.557116Z" + "iopub.execute_input": "2026-11-10T11:38:45.349621Z", + "iopub.status.busy": "2026-11-10T11:38:45.349523Z", + "iopub.status.idle": "2026-11-10T11:38:53.911527Z", + "shell.execute_reply": "2026-11-10T11:38:53.911195Z" } }, "outputs": [ @@ -1168,10 +1168,10 @@ "id": "bc7f87fc", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:23:57.559045Z", - "iopub.status.busy": "2026-11-08T23:23:57.558949Z", - "iopub.status.idle": "2026-11-08T23:24:01.384249Z", - "shell.execute_reply": "2026-11-08T23:24:01.383850Z" + "iopub.execute_input": "2026-11-10T11:38:53.913052Z", + "iopub.status.busy": "2026-11-10T11:38:53.912932Z", + "iopub.status.idle": "2026-11-10T11:38:57.709985Z", + "shell.execute_reply": "2026-11-10T11:38:57.709591Z" } }, "outputs": [ @@ -1195,7 +1195,7 @@ "name": "stderr", "output_type": "stream", "text": [ - "/Users/achrafatila/Documents/Workflows/amorphouspy/amorphouspy/src/amorphouspy/properties/vibrational.py:174: UserWarning: r_max=10.0000 Å exceeds half the smallest perpendicular cell height (8.2438 Å). r_max has been automatically adjusted to 8.0 Å (largest integer not exceeding the limit).\n", + "/Users/achrafatila/Documents/Workflows/amorphouspy/amorphouspy/src/amorphouspy/properties/vibrational/classification.py:102: UserWarning: r_max=10.0000 Å exceeds half the smallest perpendicular cell height (8.2438 Å). r_max has been automatically adjusted to 8.0 Å (largest integer not exceeding the limit).\n", " r, rdfs, _cumcn = compute_rdf(structure, r_max=10.0, n_bins=500)\n" ] } @@ -1250,10 +1250,10 @@ "id": "1f4f2075", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:24:01.385716Z", - "iopub.status.busy": "2026-11-08T23:24:01.385610Z", - "iopub.status.idle": "2026-11-08T23:24:01.483923Z", - "shell.execute_reply": "2026-11-08T23:24:01.483654Z" + "iopub.execute_input": "2026-11-10T11:38:57.711501Z", + "iopub.status.busy": "2026-11-10T11:38:57.711393Z", + "iopub.status.idle": "2026-11-10T11:38:57.808507Z", + "shell.execute_reply": "2026-11-10T11:38:57.808228Z" } }, "outputs": [ @@ -1309,10 +1309,10 @@ "id": "e8ba14eb", "metadata": { "execution": { - "iopub.execute_input": "2026-11-08T23:24:01.485376Z", - "iopub.status.busy": "2026-11-08T23:24:01.485281Z", - "iopub.status.idle": "2026-11-08T23:24:01.562611Z", - "shell.execute_reply": "2026-11-08T23:24:01.562330Z" + "iopub.execute_input": "2026-11-10T11:38:57.809854Z", + "iopub.status.busy": "2026-11-10T11:38:57.809765Z", + "iopub.status.idle": "2026-11-10T11:38:57.886231Z", + "shell.execute_reply": "2026-11-10T11:38:57.885926Z" } }, "outputs": [