diff --git a/CHANGELOG.rst b/CHANGELOG.rst index f8c59a4..7c406bb 100644 --- a/CHANGELOG.rst +++ b/CHANGELOG.rst @@ -9,6 +9,12 @@ CHANGELOG file - keep the format consistent (88 char width, Y/M/D date format) and do not use tabs but use spaces for formatting +Unreleased +---------- +Henrik Stooß + +- Add QENS module (#22) + v0.1.2 (2026/11/25) ------------------- Henrik Stooß diff --git a/docs/src/analysis-modules/qens.rst b/docs/src/analysis-modules/qens.rst new file mode 100644 index 0000000..6da7bd3 --- /dev/null +++ b/docs/src/analysis-modules/qens.rst @@ -0,0 +1,12 @@ +.. _Qens: + +Qens +#### + +.. autoclass:: scatterkit.Qens + :members: +run, save + :undoc-members: + :show-inheritance: + + +.. footbibliography:: diff --git a/docs/src/concepts-explanations/index.rst b/docs/src/concepts-explanations/index.rst index 93db519..848a8f6 100644 --- a/docs/src/concepts-explanations/index.rst +++ b/docs/src/concepts-explanations/index.rst @@ -9,3 +9,4 @@ This section provides the theory behind some of the most complex analysis module :maxdepth: 1 saxs + qens diff --git a/docs/src/concepts-explanations/qens.rst b/docs/src/concepts-explanations/qens.rst new file mode 100644 index 0000000..15fd05b --- /dev/null +++ b/docs/src/concepts-explanations/qens.rst @@ -0,0 +1,157 @@ +.. _qens-explanations: + +================================ +Quasi-elastic neutron scattering +================================ + +Where Small-Angle X-ray Scattering (SAXS, see :ref:`saxs-explanations`) probes static +structure through the elastic scattering of photons, Quasi-elastic Neutron Scattering +(QENS) probes *dynamics* through the small but non-zero energy transferred when neutrons +scatter off moving nuclei. Neutrons are particularly well-suited for this task: they +scatter from nuclei rather than electron clouds, they penetrate deeply into condensed +matter, and the energy of a thermal neutron is comparable to the energy of molecular +motions on the picosecond timescale, so the energy exchanged in a scattering event is +directly readable in the spectrum. + +QENS spectra contain information about diffusion, rotational motion, and the residence +times of molecules in local environments. In the time domain, this dynamical information +is encoded in the *intermediate scattering function* :math:`F(q, t)`, which is what +:class:`scatterkit.Qens` computes from a molecular dynamics trajectory. + +----------- +Experiments +----------- + +A QENS experiment is closely related to a SAXS experiment, with the key difference that +both the wave vector :math:`\boldsymbol q` *and* the energy transfer :math:`\hbar\omega` +of the scattered particle are resolved. A monochromatic neutron beam of wave vector +:math:`\boldsymbol k_i` impinges on the sample, and the energy and direction of the +scattered neutrons are measured. The setup is sketched below. + +.. image:: ../../static/qens-light.png + :alt: Setup of a QENS experiment with companion S(q, omega) spectrum + :class: only-light + +.. image:: ../../static/qens-dark.png + :alt: Setup of a QENS experiment with companion S(q, omega) spectrum + :class: only-dark + +The momentum and energy transferred to the sample are + +.. math:: + \hbar \boldsymbol q = \hbar (\boldsymbol k_s - \boldsymbol k_i) + \,, \qquad + \hbar \omega = \frac{\hbar^2}{2 m_n} (|\boldsymbol k_i|^2 - |\boldsymbol k_s|^2) \,, + +where :math:`m_n` is the neutron mass. Pure elastic scattering corresponds to +:math:`\omega = 0`; QENS is the regime of small but non-zero :math:`\omega`, where the +elastic line is broadened by the diffusive motion of the scatterers. + +The measured quantity is the *dynamic structure factor* :math:`S(\boldsymbol q, +\omega)`. By the Wiener-Khinchin theorem, it is the time-Fourier transform of the +intermediate scattering function + +.. math:: + S(\boldsymbol q, \omega) = + \frac{1}{2\pi} \int_{-\infty}^{\infty} + F(\boldsymbol q, t) e^{-i \omega t} \,\mathrm{d}t \,. + +Neutrons interact with nuclei through two channels with different coupling strengths, +which gives rise to two contributions: + +* the *coherent* part :math:`F(\boldsymbol q, t)` reports on collective density + fluctuations (pairs of atoms), +* the *incoherent* part :math:`F_s(\boldsymbol q, t)` reports on single-particle + motion. + +For elements with a large incoherent cross-section — hydrogen in particular — the QENS +spectrum is dominated by the incoherent channel, which makes it a direct probe of +self-diffusion. :class:`scatterkit.Qens` targets this regime. + +----------- +Simulations +----------- + +In molecular dynamics simulations the incoherent intermediate scattering function can be +computed directly from the trajectory: + +.. math:: + F_s(\boldsymbol q, t) = + \frac{1}{N} \left\langle \sum_{i=1}^{N} + \exp\!\big( i\, \boldsymbol q \cdot + [\boldsymbol r_i(t_0 + t) - \boldsymbol r_i(t_0)] \big) + \right\rangle_{t_0} \,, + +where the average is taken over time origins :math:`t_0` and :math:`\boldsymbol r_i(t)` +is the position of atom :math:`i` at time :math:`t`. The coherent counterpart includes +cross-terms :math:`i \neq j` and reduces to the static structure factor +:math:`S(\boldsymbol q)` (see :ref:`saxs-explanations`) at :math:`t = 0`. + +As in the static case, :math:`\boldsymbol q` is restricted by the periodic boundary +conditions to wave vectors of the form + +.. math:: + \boldsymbol q = 2 \pi (n_x / L_x, n_y / L_y, n_z / L_z) \,, \qquad + n_x, n_y, n_z \in \mathbb{Z} \,, + +with box lengths :math:`L_x, L_y, L_z`. For each requested :math:`q`-shell, +:class:`scatterkit.Qens` enumerates all lattice-compatible orientations of +:math:`\boldsymbol q` and powder-averages the resulting per-vector correlations into a +single :math:`F_s(q, t)` curve. This averaging recovers the isotropy that the discrete +:math:`q`-grid does not have for any individual vector. + +.. Note:: + :class:`scatterkit.Qens` currently supports only orthorhombic simulation cells. + Triclinic boxes would require the full reciprocal-lattice basis rather than the + axis-aligned grid above. + +Rather than storing the full trajectory of phase factors and then correlating in a +post-processing step, :class:`scatterkit.Qens` streams the per-atom phases +:math:`e^{i \boldsymbol q \cdot \boldsymbol r_i(t)}` into a *multi-tau* correlator +(:class:`multitau.MultiTauCorrelator`). The multi-tau scheme uses +geometrically spaced lag-time channels, so the function is sampled densely at short +times and coarsely at long times while the memory cost stays bounded by the number of +levels rather than by the trajectory length. This is the natural sampling for a +correlation function that decays roughly exponentially over many decades in time, as is +typical for diffusive motion. + +---------------------------------------------------- +Connection to the mean-squared displacement +---------------------------------------------------- + +For homogeneous, isotropic, and Gaussian-distributed displacements, + +.. math:: + P(\Delta \boldsymbol r, t) = + \left( \frac{3}{2 \pi \langle \Delta r^2(t) \rangle} \right)^{3/2} + \exp\!\left( - \frac{3 \,|\Delta \boldsymbol r|^2} + {2 \langle \Delta r^2(t) \rangle} \right) \,, + +the angular integral in the definition of :math:`F_s` can be carried out analytically +and yields the *Gaussian approximation* + +.. math:: + F_s(q, t) = \exp\!\left( - \frac{q^2 \langle \Delta r^2(t) \rangle}{6} \right) \,, + +where :math:`\langle \Delta r^2(t) \rangle = \langle |\boldsymbol r_i(t_0 + t) - +\boldsymbol r_i(t_0)|^2 \rangle` is the mean-squared displacement (MSD). The Gaussian +approximation is exact for free Brownian diffusion and for any harmonic system, and is +generally a good approximation at long times where the central-limit theorem applies. In +this regime :math:`\langle \Delta r^2(t) \rangle = 6 D t` and + +.. math:: + F_s(q, t) \approx \exp(- D q^2 t) \,, + +so the time-Fourier transform that yields the experimental dynamic structure factor is a +Lorentzian of half-width :math:`D q^2`. Fitting this width as a function of :math:`q` is +the standard way of extracting self-diffusion coefficients from QENS spectra. + +Deviations of the simulated :math:`F_s(q, t)` from a single exponential — or from the +Gaussian approximation — are themselves physically meaningful. They signal sub-diffusive +behaviour, jump diffusion, or coupling between translation and rotation. For a detailed +discussion of these regimes and of the relation between :math:`F(q, t)`, :math:`F_s(q, +t)`, and the van Hove correlation function, see :footcite:p:`hansen_theory_2006`. + +References +---------- +.. footbibliography:: diff --git a/docs/static/qens-dark.png b/docs/static/qens-dark.png new file mode 100644 index 0000000..ebd97b7 Binary files /dev/null and b/docs/static/qens-dark.png differ diff --git a/docs/static/qens-light.png b/docs/static/qens-light.png new file mode 100644 index 0000000..f355fae Binary files /dev/null and b/docs/static/qens-light.png differ diff --git a/pyproject.toml b/pyproject.toml index 86d12da..44c4359 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -57,7 +57,10 @@ maintainers = [ name = "scatterkit" readme = "README.rst" requires-python = ">=3.11" -dependencies = ["maicos==0.13"] +dependencies = [ + "maicos==0.13.1", + "multitau @ git+https://github.com/atomistic-lab/multitau.git", +] [project.optional-dependencies] examples = ["matplotlib"] diff --git a/src/scatterkit/__init__.py b/src/scatterkit/__init__.py index d021615..2982927 100644 --- a/src/scatterkit/__init__.py +++ b/src/scatterkit/__init__.py @@ -6,7 +6,8 @@ #: and `semantic versioning `_. from ._version import __version__ # noqa: F401 from .diporderstructurefactor import DiporderStructureFactor +from .qens import Qens from .rdfdiporder import RDFDiporder from .saxs import Saxs -__all__ = ["DiporderStructureFactor", "RDFDiporder", "Saxs"] +__all__ = ["DiporderStructureFactor", "Qens", "RDFDiporder", "Saxs"] diff --git a/src/scatterkit/qens.py b/src/scatterkit/qens.py new file mode 100644 index 0000000..58b1098 --- /dev/null +++ b/src/scatterkit/qens.py @@ -0,0 +1,345 @@ +# +# Copyright (c) 2025 Authors and contributors +# (see the AUTHORS.rst file for the full list of names) +# +# Released under the GNU Public Licence, v3 or any higher version +# SPDX-License-Identifier: GPL-3.0-or-later +r"""Module for computing the incoherent intermediate scattering function. + +Computes the self-part of the intermediate scattering function +:math:`F_s(q, t)` via streaming multi-tau correlation provided by +:class:`multitau.MultiTauCorrelator`. +""" + +import logging +import warnings + +import MDAnalysis as mda +import numpy as np +from maicos.core import AnalysisBase +from multitau import MultiTauCorrelator + +from .lib.util import render_docs + + +def _generate_q_vectors( + box_lengths: np.ndarray, + qmin: float, + qmax: float, + dq: float, + max_q_vectors: int | None = None, +) -> tuple[np.ndarray, list[np.ndarray]]: + """Generate q-vectors grouped into non-empty shells by magnitude. + + All q-vectors compatible with the simulation box that fall within the + requested q-range are generated deterministically from Miller indices. + An optional cap ``max_q_vectors`` can limit the number per shell for + performance; when set, vectors are selected by taking every n-th vector + (stride sampling) to preserve orientational coverage. + + Parameters + ---------- + box_lengths : numpy.ndarray + Diagonal box lengths (Lx, Ly, Lz) in Angstrom. + qmin : float + Minimum q magnitude (1/Angstrom). + qmax : float + Maximum q magnitude (1/Angstrom). + dq : float + Width of q-shells for binning (1/Angstrom). + max_q_vectors : int or None + Maximum number of q-vectors per shell. If ``None`` (default), all + vectors in each shell are used. When set, vectors are stride-sampled + to maintain uniform orientational coverage. + + Returns + ------- + q_bin_values : numpy.ndarray + Mean :math:`|q|` of the vectors actually used in each non-empty shell. + q_vectors_per_shell : list of numpy.ndarray + For each non-empty shell, an ``(n_selected, 3)`` array of q-vectors. + + """ + # Under PBC, only q = 2π n / L for integer Miller indices n = (h, k, l) + # are allowed. Enumerate every combination whose |q| can reach qmax. + q_factor = 2 * np.pi / box_lengths # (3,) + max_n = np.ceil(qmax / q_factor).astype(int) + + hh = np.arange(-max_n[0], max_n[0] + 1) + kk = np.arange(-max_n[1], max_n[1] + 1) + ll = np.arange(-max_n[2], max_n[2] + 1) + miller = np.array(np.meshgrid(hh, kk, ll, indexing="ij")).reshape(3, -1).T + miller = miller[np.any(miller != 0, axis=1)] # drop (0, 0, 0) + + q_vecs = miller * q_factor[np.newaxis, :] # (N, 3) + q_mags = np.linalg.norm(q_vecs, axis=1) + + mask = (q_mags >= qmin) & (q_mags <= qmax) + q_vecs = q_vecs[mask] + q_mags = q_mags[mask] + + n_shells = int(np.ceil((qmax - qmin) / dq)) + q_bin_edges = np.linspace(qmin, qmin + n_shells * dq, n_shells + 1) + shell_indices = np.digitize(q_mags, q_bin_edges) - 1 + + q_vectors_per_shell: list[np.ndarray] = [] + q_bin_values: list[float] = [] + for i_shell in range(n_shells): + in_shell = shell_indices == i_shell + if not in_shell.any(): + continue + vecs = q_vecs[in_shell] + mags = q_mags[in_shell] + + if max_q_vectors is not None and len(vecs) > max_q_vectors: + stride = len(vecs) // max_q_vectors + sel = np.arange(0, len(vecs), stride)[:max_q_vectors] + vecs = vecs[sel] + mags = mags[sel] + + q_vectors_per_shell.append(vecs) + q_bin_values.append(float(np.mean(mags))) + + return np.asarray(q_bin_values), q_vectors_per_shell + + +@render_docs +class Qens(AnalysisBase): + r"""Incoherent intermediate scattering function :math:`F_s(q, t)` via multi-tau. + + Computes the self-part of the intermediate scattering function + + .. math:: + + F_s(q, t) = \frac{1}{N} \left\langle \sum_{i=1}^{N} + \exp\!\big(i\,\boldsymbol{q} \cdot + [\boldsymbol{r}_i(t_0 + t) - \boldsymbol{r}_i(t_0)]\big) + \right\rangle_{t_0} + + by streaming the per-atom phase factors + :math:`e^{i\boldsymbol{q}\cdot\boldsymbol{r}_i(t)}` into a + :class:`multitau.MultiTauCorrelator`. The trajectory is processed in a + single pass with bounded memory; lag times are logarithmically spaced. + + For each q-shell, all q-vector orientations compatible with the simulation + box are used and averaged (powder averaging). Requires an orthorhombic + simulation cell. + + Parameters + ---------- + ${ATOMGROUP_PARAMETER} + ${Q_SPACE_PARAMETERS} + max_q_vectors : int or None + Maximum number of q-vectors per shell. If :py:obj:`None`, all + lattice-compatible vectors in each shell are used. Default is 6: + the powder-average variance budget is dominated by the per-atom + average (:math:`\propto 1/N`), so once N is large adding more + orientations gives rapidly diminishing returns while the + correlator memory scales linearly with the total q-vector count. + correlator_num_levels : int + Number of coarsening levels :math:`p` of the multi-tau correlator. + The highest resolvable lag is :math:`(m-1) \cdot 2^{p-1}` frames, + where :math:`m` is ``correlator_channels_per_level``. Levels that + are never reached by the trajectory contribute no data. + correlator_channels_per_level : int + Number of channels :math:`m` per level of the multi-tau correlator. + Must be even. Level 0 holds all :math:`m` lags; higher levels hold + the upper half :math:`m/2 \dots m-1` to avoid redundancy. + mem_warn_gb : float + Threshold (in GB) for emitting a :class:`UserWarning` about the + estimated peak memory of the streaming correlator. Defaults to + :py:obj:`8.0`. Set to :py:obj:`numpy.inf` to silence the warning. + ${BASE_CLASS_PARAMETERS} + ${OUTPUT_PARAMETER} + + Attributes + ---------- + results.lag_times : numpy.ndarray + Lag times in the same time unit as the trajectory. + results.q_values : numpy.ndarray + Scattering vector magnitudes for each non-empty q-shell. + results.F_s : numpy.ndarray + Incoherent intermediate scattering function, shape ``(n_q, n_tau)``. + + """ + + def __init__( + self, + atomgroup: mda.AtomGroup, + qmin: float = 0.2, + qmax: float = 2.0, + dq: float = 0.1, + max_q_vectors: int | None = 6, + refgroup: mda.AtomGroup | None = None, + unwrap: bool = True, + pack: bool = False, + jitter: float = 0.0, + concfreq: int = 0, + correlator_num_levels: int = 20, + correlator_channels_per_level: int = 16, + mem_warn_gb: float = 8.0, + output: str = "fs_qt.dat", + ) -> None: + self._locals = locals() + super().__init__( + atomgroup, + unwrap=unwrap, + pack=pack, + refgroup=refgroup, + jitter=jitter, + concfreq=concfreq, + wrap_compound="atoms", + ) + self.qmin = qmin + self.qmax = qmax + self.dq = dq + self.max_q_vectors = max_q_vectors + self.correlator_num_levels = correlator_num_levels + self.correlator_channels_per_level = correlator_channels_per_level + self.mem_warn_gb = mem_warn_gb + self.output = output + + def _prepare(self) -> None: + logging.info( + "Analysis of the incoherent intermediate scattering function F_s(q, t)." + ) + + # The Miller-index q-grid in `_generate_q_vectors` assumes axis-aligned + # cell vectors; a triclinic cell would need the full reciprocal basis. + cell = mda.lib.mdamath.triclinic_vectors(self._universe.dimensions) + if not np.allclose(cell - np.diag(np.diag(cell)), 0): + raise NotImplementedError( + "Qens currently supports only orthorhombic simulation cells." + ) + box = np.diag(cell) + + self._q_bin_values, self._q_vectors_per_shell = _generate_q_vectors( + box_lengths=box, + qmin=self.qmin, + qmax=self.qmax, + dq=self.dq, + max_q_vectors=self.max_q_vectors, + ) + + # `_all_q_vecs` is the flat (total_q, 3) view we feed into the + # correlator; `_shell_of_q[i]` records which shell row i came from so + # we can powder-average per-q correlations within each shell in + # `_conclude`. + if self._q_vectors_per_shell: + self._all_q_vecs = np.vstack(self._q_vectors_per_shell) + self._shell_of_q = np.concatenate( + [np.full(len(qv), i) for i, qv in enumerate(self._q_vectors_per_shell)] + ) + else: + self._all_q_vecs = np.empty((0, 3)) + self._shell_of_q = np.empty(0, dtype=int) + + logging.info( + f"Streaming {len(self._all_q_vecs)} q-vectors across " + f"{len(self._q_vectors_per_shell)} q-shells." + ) + + self._check_memory_budget() + + # Every (atom, q) pair gets its own autocorrelation, which is what + # makes this the self (incoherent) part of the scattering function. + self._correlator: MultiTauCorrelator | None = None + if len(self._all_q_vecs) > 0: + self._correlator = MultiTauCorrelator( + shape=(self.atomgroup.n_atoms, len(self._all_q_vecs)), + num_levels=self.correlator_num_levels, + channels_per_level=self.correlator_channels_per_level, + dtype=np.complex128, + ) + + def _check_memory_budget(self) -> None: + """Estimate streaming-correlator memory and warn if above threshold. + + The :class:`multitau.MultiTauCorrelator` holds a buffer and an + accumulator of shape ``(p, m, n_atoms, total_q)`` in complex128 (16 + bytes/element). On read, its ``correlation`` property materialises an + additional ``(n_lags, n_atoms, total_q)`` array of the same dtype. + """ + n_atoms = self.atomgroup.n_atoms + total_q = len(self._all_q_vecs) + if total_q == 0: + return + + p = self.correlator_num_levels + m = self.correlator_channels_per_level + n_lags = m + (p - 1) * (m // 2) + bytes_per_elem = 16 # complex128 + + buf_bytes = p * m * n_atoms * total_q * bytes_per_elem + out_bytes = n_lags * n_atoms * total_q * bytes_per_elem + peak_bytes = 2 * buf_bytes + out_bytes + peak_gb = peak_bytes / 1e9 + + logging.info( + "Estimated peak memory for streaming correlator: " + f"{peak_gb:.2f} GB " + f"(buffer+accumulator {2 * buf_bytes / 1e9:.2f} GB, " + f"correlation output {out_bytes / 1e9:.2f} GB) " + f"[n_atoms={n_atoms}, total_q={total_q}, p={p}, m={m}]." + ) + + if peak_gb > self.mem_warn_gb: + warnings.warn( + f"Qens streaming correlator estimated peak memory " + f"~{peak_gb:.1f} GB exceeds threshold " + f"({self.mem_warn_gb:.1f} GB). To reduce memory: lower " + f"`max_q_vectors` (currently " + f"{self.max_q_vectors!r}), coarsen `dq`, reduce " + f"`correlator_num_levels`, or raise `mem_warn_gb` to silence.", + UserWarning, + stacklevel=3, + ) + + def _single_frame(self) -> float: + # There is no per-frame scalar observable; NaN makes MAICoS skip its + # correlation-time analysis instead of warning about zero variance. + if self._correlator is None: + return np.nan + + positions = self.atomgroup.positions # (n_atoms, 3) + # phases[j, k] = exp(i q_k . r_j(t)), correlated element-wise. + self._correlator.add(np.exp(1j * (positions @ self._all_q_vecs.T))) + return np.nan + + def _conclude(self) -> None: + if self._correlator is None or self._correlator.n_frames < 2: + logging.warning("No correlation data collected.") + self.results.lag_times = np.array([]) + self.results.q_values = np.array([]) + self.results.F_s = np.array([]) + return + + # The correlation has shape (n_lags, n_atoms, total_q), complex. Mean + # over atoms then real part gives the per-q-vector F_s; we then + # powder-average within each shell. Upper levels the trajectory never + # reached have no pairs (NaN) and are dropped. + valid = self._correlator.counts > 0 + per_q = self._correlator.correlation.mean(axis=1).real[valid] + n_shells = len(self._q_vectors_per_shell) + F_s = np.zeros((n_shells, per_q.shape[0])) + for i_shell in range(n_shells): + F_s[i_shell] = per_q[:, self._shell_of_q == i_shell].mean(axis=1) + + # Lags are in units of frame intervals; convert to physical time via + # the actually-sampled dt (which already reflects any user-supplied + # stride). + dt = float(self.times[1] - self.times[0]) + self.results.lag_times = self._correlator.lags[valid] * dt + self.results.q_values = self._q_bin_values + self.results.F_s = F_s + + @render_docs + def save(self) -> None: + """${SAVE_METHOD_DESCRIPTION}""" # noqa: D415 + lag_times = self.results.lag_times + F_s = self.results.F_s # (n_q, n_tau) + + data = np.column_stack([lag_times, F_s.T]) + columns = ["t"] + [f"F_s(q={q:.3f})" for q in self.results.q_values] + + self.savetxt(self.output, data, columns=columns) diff --git a/tests/test_qens.py b/tests/test_qens.py new file mode 100644 index 0000000..c045861 --- /dev/null +++ b/tests/test_qens.py @@ -0,0 +1,149 @@ +# +# Copyright (c) 2025 Authors and contributors +# (see the AUTHORS.rst file for the full list of names) +# +# Released under the GNU Public Licence, v3 or any higher version +# SPDX-License-Identifier: GPL-3.0-or-later +"""Tests for the QENS module. + +Multi-tau correlator behaviour is covered by multitau's own test suite +(``tests/test_correlator.py``); this file exercises only the scatterkit +``Qens`` wrapper. +""" + +import sys +import warnings +from pathlib import Path + +import MDAnalysis as mda +import numpy as np +import pytest +from numpy.testing import assert_allclose + +sys.path.append(str(Path(__file__).parents[1])) + +from scatterkit import Qens + + +class TestQens: + """Tests for the Qens analysis class using trajectory data.""" + + @pytest.fixture + def ag_water_npt(self): + """Multi-frame water trajectory.""" + from data import WATER_TPR_NPT, WATER_TRR_NPT + + u = mda.Universe(WATER_TPR_NPT, WATER_TRR_NPT) + return u.select_atoms("name OW") + + @pytest.fixture + def ag_water_2f(self): + """Two-frame water trajectory.""" + from data import WATER_2F_TRR_NPT, WATER_TPR_NPT + + u = mda.Universe(WATER_TPR_NPT, WATER_2F_TRR_NPT) + return u.select_atoms("name OW") + + def test_smoke(self, ag_water_npt, monkeypatch, tmp_path): + """Smoke test: Qens runs without errors and produces output.""" + monkeypatch.chdir(tmp_path) + qens = Qens( + ag_water_npt, + qmin=0.5, + qmax=2.0, + dq=0.5, + correlator_num_levels=4, + correlator_channels_per_level=8, + output="fs.dat", + ).run() + + assert hasattr(qens.results, "lag_times") + assert hasattr(qens.results, "q_values") + assert hasattr(qens.results, "F_s") + assert len(qens.results.lag_times) > 0 + assert len(qens.results.q_values) > 0 + assert qens.results.F_s.shape[0] == len(qens.results.q_values) + assert qens.results.F_s.shape[1] == len(qens.results.lag_times) + + def test_save(self, ag_water_npt, monkeypatch, tmp_path): + """Test that save produces a loadable file.""" + monkeypatch.chdir(tmp_path) + qens = Qens( + ag_water_npt, + qmin=0.5, + qmax=2.0, + dq=0.5, + correlator_num_levels=4, + correlator_channels_per_level=8, + output="fs", + ).run() + qens.save() + + data = np.loadtxt("fs.dat") + assert data.shape[0] == len(qens.results.lag_times) + + def test_f_s_at_t0_is_one(self, ag_water_npt): + """F_s(q, t=0) is exactly 1 since |exp(i q.r)|^2 = 1.""" + qens = Qens( + ag_water_npt, + qmin=0.5, + qmax=1.5, + dq=0.5, + correlator_num_levels=4, + correlator_channels_per_level=8, + ).run() + + assert qens.results.lag_times[0] == 0 + assert_allclose(qens.results.F_s[:, 0], 1.0, rtol=1e-12) + + def test_matches_direct_computation(self, ag_water_npt): + """Level-0 lags equal a direct average over all time origins.""" + m = 8 + qens = Qens( + ag_water_npt, + qmin=0.5, + qmax=1.5, + dq=0.5, + correlator_num_levels=4, + correlator_channels_per_level=m, + ).run() + + positions = np.array([ag_water_npt.positions for _ in qens._trajectory]) + phases = np.exp(1j * (positions @ qens._all_q_vecs.T)) # (n_t, n_atoms, n_q) + expected = np.zeros((len(qens.results.q_values), m)) + for lag in range(m): + corr = np.conj(phases[: len(phases) - lag]) * phases[lag:] + per_q = corr.mean(axis=(0, 1)).real + for i_shell in range(len(qens.results.q_values)): + expected[i_shell, lag] = per_q[qens._shell_of_q == i_shell].mean() + + assert_allclose(qens.results.F_s[:, :m], expected, rtol=1e-12) + assert_allclose(qens.results.lag_times[:m], np.arange(m) * qens._trajectory.dt) + + def test_no_warnings(self, ag_water_npt): + """A regular run must not emit (e.g. correlation-time) warnings.""" + with warnings.catch_warnings(): + warnings.simplefilter("error") + Qens( + ag_water_npt, + qmin=0.5, + qmax=1.5, + dq=0.5, + correlator_num_levels=4, + correlator_channels_per_level=8, + ).run() + + def test_deterministic_reproducibility(self, ag_water_npt): + """Same parameters should give identical results (deterministic q-vectors).""" + kwargs = { + "qmin": 0.5, + "qmax": 1.5, + "dq": 0.5, + "correlator_num_levels": 4, + "correlator_channels_per_level": 8, + } + qens1 = Qens(ag_water_npt, **kwargs).run() + qens2 = Qens(ag_water_npt, **kwargs).run() + + assert_allclose(qens1.results.F_s, qens2.results.F_s) + assert_allclose(qens1.results.q_values, qens2.results.q_values)