diff --git a/CMakeLists.txt b/CMakeLists.txt index 7127220..cdf954f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -81,6 +81,10 @@ if(DEFINED _srreal_saved_suffixes) endforeach() endif() +# Needs nvcc to build; without a CUDA device the CPU kernels are used. +option(SRREAL_CUDA "Build the CUDA calculation kernels" OFF) +set(LIBDIFFPY_CUDA ${SRREAL_CUDA}) + # Embed libdiffpy as an OBJECT library: every object is linked, so its static # factory/serialization registrars are kept. set(LIBDIFFPY_BUILD_OBJECT_LIB ON) diff --git a/README.rst b/README.rst index 04c5ae4..98e6793 100644 --- a/README.rst +++ b/README.rst @@ -128,6 +128,14 @@ libdiffpy download. GitHub's automatically generated source archives omit submodule contents; use a recursive clone or a packaged sdist instead. A C++23 compiler, Boost.Serialization, GSL, and the Python build dependencies must still be installed separately, including for an offline build. +CMake builds the SIMD kernels when it finds xsimd 14 or newer. + +To enable the optional CUDA kernels in a source build, install the CUDA +toolkit with ``nvcc`` and run :: + + pip install . -C cmake.define.SRREAL_CUDA=ON + +Set ``CUDACXX`` if ``nvcc`` is not in the ``PATH``. Getting Started --------------- @@ -148,6 +156,11 @@ directory :: pip install -e . +The default build type is Release. For example, to test a debug CUDA build :: + + python -m pip install -e ".[test]" -C cmake.build-type=Debug -C cmake.define.SRREAL_CUDA=ON + python -m pytest + To ensure code quality and to prevent accidental commits into the default branch, please set up the use of our pre-commit hooks. diff --git a/docs/source/api/diffpy.srreal.rst b/docs/source/api/diffpy.srreal.rst index 82b2528..d0c21bc 100644 --- a/docs/source/api/diffpy.srreal.rst +++ b/docs/source/api/diffpy.srreal.rst @@ -54,6 +54,15 @@ diffpy.srreal.bvscalculator module :undoc-members: :show-inheritance: +diffpy.srreal.calculationkernel module +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +.. automodule:: diffpy.srreal.calculationkernel + +.. autofunction:: diffpy.srreal.calculationkernel.availableCalculationKernels() +.. autofunction:: diffpy.srreal.calculationkernel.getCalculationKernel() +.. autofunction:: diffpy.srreal.calculationkernel.setCalculationKernel(name) + diffpy.srreal.eventticker module ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/extern/libdiffpy b/extern/libdiffpy index e7b105e..994aaf2 160000 --- a/extern/libdiffpy +++ b/extern/libdiffpy @@ -1 +1 @@ -Subproject commit e7b105e492cd25e7c0b1a72cc1ec93f83267b07d +Subproject commit 994aaf25e6a62d7e547eb471d5a0716714606366 diff --git a/news/cuda.rst b/news/cuda.rst new file mode 100644 index 0000000..690e92c --- /dev/null +++ b/news/cuda.rst @@ -0,0 +1,38 @@ +**Added:** + +* The ``diffpy.srreal.calculationkernel`` module selects the kernel of PDF + and Debye calculations. +* Optional ``cuda`` and ``cuda-mixed`` kernels, included in the Windows and + Linux x86-64 wheels (which also run without a GPU) and enabled in source + builds with ``SRREAL_CUDA=ON``. +* ``AtomicStructureAdapter.getAtomArrays`` and ``setAtomArrays`` read and + replace all atom data in bulk. + +**Changed:** + +* Full PDF and Debye calculations use multithreaded, batched CPU sums, with + SIMD kernels when built with xsimd (always in wheels). +* ``OPTIMIZED`` can choose a full calculation when it costs less than updating + changed atoms. ``evaluatortypeused`` then reports ``"BASIC"``. +* Conversion of ``diffpy.structure`` and ``pyobjcryst`` structures is faster. + +**Deprecated:** + +* + +**Removed:** + +* + +**Fixed:** + +* ``DebyePDFCalculator`` uses each site's own occupancy when several sites + share an element. +* ``CrystalStructureAdapter.getEquivalentAtoms`` now checks the index against + the number of sites, fixing incorrect exceptions and a possible crash. +* ``OPTIMIZED`` recalculates when a change of adapter class changes the + structure, for example when a cluster becomes periodic. + +**Security:** + +* diff --git a/pyproject.toml b/pyproject.toml index c98f744..bd5f837 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -67,31 +67,64 @@ skip = ["*-musllinux_*"] test-extras = ["test"] test-command = "pytest {project}/tests" +[tool.cibuildwheel.config-settings] +"cmake.define.SRREAL_STATIC_DEPS" = "ON" +"cmake.define.VCPKG_MANIFEST_INSTALL" = "OFF" +"cmake.define.CMAKE_REQUIRE_FIND_PACKAGE_xsimd" = "ON" + [tool.cibuildwheel.linux] archs = ["x86_64"] -config-settings = { "cmake.define.SRREAL_STATIC_DEPS" = "ON", "cmake.define.SRREAL_DEPS_LICENSE_DIR" = "/opt/srreal-deps/licenses", "cmake.define.CMAKE_TOOLCHAIN_FILE" = "/opt/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake", "cmake.define.VCPKG_INSTALLED_DIR" = "/opt/srreal-deps/installed", "cmake.define.VCPKG_MANIFEST_INSTALL" = "OFF" } +environment = { CUDACXX = "/usr/local/cuda-13.5/bin/nvcc" } +test-environment = { CUDA_VISIBLE_DEVICES = "-1" } +inherit.config-settings = "append" + +[tool.cibuildwheel.linux.config-settings] +"cmake.define.SRREAL_CUDA" = "ON" +"cmake.define.SRREAL_DEPS_LICENSE_DIR" = "/opt/srreal-deps/licenses" +"cmake.define.CMAKE_TOOLCHAIN_FILE" = "/opt/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake" +"cmake.define.VCPKG_INSTALLED_DIR" = "/opt/srreal-deps/installed" [tool.cibuildwheel.macos] archs = ["native"] # Keep in sync with VCPKG_OSX_DEPLOYMENT_TARGET in tools/vcpkg-triplets. environment = { MACOSX_DEPLOYMENT_TARGET = "11.0" } -config-settings = { "cmake.define.SRREAL_STATIC_DEPS" = "ON", "cmake.define.SRREAL_DEPS_LICENSE_DIR" = "/tmp/srreal-deps/licenses", "cmake.define.CMAKE_TOOLCHAIN_FILE" = "/tmp/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake", "cmake.define.VCPKG_INSTALLED_DIR" = "/tmp/srreal-deps/installed", "cmake.define.VCPKG_MANIFEST_INSTALL" = "OFF" } +inherit.config-settings = "append" + +[tool.cibuildwheel.macos.config-settings] +"cmake.define.SRREAL_DEPS_LICENSE_DIR" = "/tmp/srreal-deps/licenses" +"cmake.define.CMAKE_TOOLCHAIN_FILE" = "/tmp/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake" +"cmake.define.VCPKG_INSTALLED_DIR" = "/tmp/srreal-deps/installed" # No Windows ARM64 wheels. [tool.cibuildwheel.windows] archs = ["AMD64"] -before-all = "powershell -NoProfile -ExecutionPolicy Bypass -File {project}/tools/install-vcpkg-deps.ps1 C:/srreal-deps srreal-x64-windows" -config-settings = { "cmake.define.SRREAL_STATIC_DEPS" = "ON", "cmake.define.SRREAL_DEPS_LICENSE_DIR" = "C:/srreal-deps/licenses", "cmake.define.CMAKE_TOOLCHAIN_FILE" = "C:/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake", "cmake.define.VCPKG_INSTALLED_DIR" = "C:/srreal-deps/installed", "cmake.define.VCPKG_MANIFEST_INSTALL" = "OFF", "cmake.define.VCPKG_TARGET_TRIPLET" = "srreal-x64-windows" } +environment = { CUDA_PATH_V13_5 = "C:/Program Files/NVIDIA GPU Computing Toolkit/CUDA/v13.5" } +test-environment = { CUDA_VISIBLE_DEVICES = "-1" } +before-all = [ + "pwsh -NoProfile -ExecutionPolicy Bypass -File {project}/tools/install-wheel-cuda.ps1 C:/srreal-deps", + "powershell -NoProfile -ExecutionPolicy Bypass -File {project}/tools/install-vcpkg-deps.ps1 C:/srreal-deps srreal-x64-windows", +] +inherit.config-settings = "append" before-build = "pip install delvewheel" # Other diffpy distributions also install diffpy/__init__.py. Keep the DLL # loader in diffpy.srreal and use the runtime matching the build toolset. repair-wheel-command = "delvewheel repair --namespace-pkg diffpy --add-path C:/srreal-deps/redist -w {dest_dir} {wheel}" +[tool.cibuildwheel.windows.config-settings] +"cmake.define.SRREAL_CUDA" = "ON" +"cmake.define.SRREAL_DEPS_LICENSE_DIR" = "C:/srreal-deps/licenses" +"cmake.define.CMAKE_TOOLCHAIN_FILE" = "C:/srreal-deps/vcpkg/scripts/buildsystems/vcpkg.cmake" +"cmake.define.VCPKG_INSTALLED_DIR" = "C:/srreal-deps/installed" +"cmake.define.VCPKG_TARGET_TRIPLET" = "srreal-x64-windows" + # One vcpkg triplet per architecture; see tools/vcpkg-triplets. [[tool.cibuildwheel.overrides]] select = "*-manylinux_x86_64" inherit.config-settings = "append" -before-all = "bash {project}/tools/install-vcpkg-deps.sh /opt/srreal-deps srreal-x64-linux" +before-all = [ + "bash {project}/tools/install-wheel-cuda.sh /opt/srreal-deps", + "bash {project}/tools/install-vcpkg-deps.sh /opt/srreal-deps srreal-x64-linux", +] config-settings = { "cmake.define.VCPKG_TARGET_TRIPLET" = "srreal-x64-linux" } [[tool.cibuildwheel.overrides]] diff --git a/requirements/conda.txt b/requirements/conda.txt index 0ea911d..783430c 100644 --- a/requirements/conda.txt +++ b/requirements/conda.txt @@ -1,5 +1,6 @@ libboost-devel gsl +xsimd>=14 diffpy.structure periodictable nanobind>=3.1,<4 diff --git a/src/diffpy/srreal/_objcrystconverters.py b/src/diffpy/srreal/_objcrystconverters.py index 6890abd..4c570dd 100644 --- a/src/diffpy/srreal/_objcrystconverters.py +++ b/src/diffpy/srreal/_objcrystconverters.py @@ -9,7 +9,6 @@ import numpy as np from diffpy.srreal.srreal_ext import ( - Atom, AtomicStructureAdapter, CrystalStructureAdapter, ) @@ -23,18 +22,20 @@ def _check_type(obj, name): raise TypeError(f"Expected a pyobjcryst {name} object.") -def _atom_from_scattering_power(sp): - atom = Atom() - atom.atomtype = sp.GetSymbol() - atom.anisotropy = not sp.IsIsotropic() - if atom.anisotropy: - bij = np.array( - [[sp.GetBij(i, j) for j in range(1, 4)] for i in range(1, 4)] - ) - else: - bij = np.eye(3) * sp.GetBiso() - atom.uij_cartn = bij / (8 * np.pi**2) - return atom +def _power_arrays(powers): + """Return atom types, anisotropy flags and U tensors of scattering + powers, in pyobjcryst coordinates.""" + n = len(powers) + atomtypes = [sp.GetSymbol() for sp in powers] + anisotropy = np.fromiter((not sp.IsIsotropic() for sp in powers), bool, n) + biso = np.fromiter((sp.GetBiso() for sp in powers), float, n) + bij = np.zeros((n, 3, 3)) + for k in range(3): + bij[:, k, k] = biso + for i in np.flatnonzero(anisotropy): + sp = powers[i] + bij[i] = [[sp.GetBij(j, k) for k in (1, 2, 3)] for j in (1, 2, 3)] + return atomtypes, anisotropy, bij / (8 * np.pi**2) def convertObjCrystMolecule(molecule): @@ -42,42 +43,62 @@ def convertObjCrystMolecule(molecule): dummies.""" _check_type(molecule, "Molecule") adapter = AtomicStructureAdapter() - adapter.reserve(molecule.GetNbComponent()) + powers, xyz, occupancy = [], [], [] for i in range(molecule.GetNbComponent()): source = molecule.GetAtom(i) if source.IsDummy(): continue - atom = _atom_from_scattering_power(source.GetScatteringPower()) - atom.xyz_cartn = [source.X, source.Y, source.Z] - atom.occupancy = source.Occupancy - adapter.append(atom) + powers.append(source.GetScatteringPower()) + xyz.append((source.X, source.Y, source.Z)) + occupancy.append(source.Occupancy) + atomtypes, anisotropy, uij = _power_arrays(powers) + adapter.setAtomArrays(atomtypes, xyz, occupancy, anisotropy, uij) return adapter +def _crystal_components(crystal): + """Read the asymmetric unit in crystal order.""" + from pyobjcryst._pyobjcryst import Crystal + + for name in ( + "GetScatteringComponentList", + "GetNbScatterer", + "GetScatterer", + ): + method = getattr(crystal, name) + if getattr(method, "__self__", None) is not crystal or getattr( + method, "__func__", None + ) is not getattr(Crystal, name): + return crystal.GetScatteringComponentList() + return [ + component + for i in range(crystal.GetNbScatterer()) + for component in crystal.GetScatterer(i).GetScatteringComponentList() + ] + + def convertObjCrystCrystal(crystal): """Copy the asymmetric unit and complete space-group symmetry operations.""" _check_type(crystal, "Crystal") + # The master clock does not track all changes to the crystal's children. adapter = CrystalStructureAdapter() lattice = [crystal.GetLatticePar(i) for i in range(6)] lattice[3:] = np.degrees(lattice[3:]) adapter.setLatPar(*lattice) - components = crystal.GetScatteringComponentList() - adapter.reserve(len(components)) - for source in components: + powers, xyz, occupancy = [], [], [] + for source in _crystal_components(crystal): sp = source.mpScattPow if sp is None: continue - atom = _atom_from_scattering_power(sp) - atom.xyz_cartn = [source.mX, source.mY, source.mZ] - atom.occupancy = source.mOccupancy - # Isotropic U is already Cartesian. Only anisotropic U follows the - # lattice transformation; coordinates always need that transformation. - uij = atom.uij_cartn.copy() - adapter.toCartesian(atom) - if not atom.anisotropy: - atom.uij_cartn = uij - adapter.append(atom) + powers.append(sp) + xyz.append((source.mX, source.mY, source.mZ)) + occupancy.append(source.mOccupancy) + atomtypes, anisotropy, uij = _power_arrays(powers) + # isotropic U is already Cartesian + adapter._setLatticeAtomArrays( + atomtypes, xyz, occupancy, anisotropy, uij, isotropic_cartesian=True + ) sg = crystal.GetSpaceGroup() operations = [ @@ -90,7 +111,5 @@ def convertObjCrystCrystal(crystal): operations += [(-r, inversion - t) for r, t in operations] if len(operations) != sg.GetNbSymmetrics(): raise ValueError("Inconsistent pyobjcryst space-group operations.") - for rotation, translation in operations: - adapter.addSymOp(rotation, translation) - adapter.updateSymmetryPositions() + adapter._setSymOps([r for r, t in operations], [t for r, t in operations]) return adapter diff --git a/src/diffpy/srreal/calculationkernel.py b/src/diffpy/srreal/calculationkernel.py new file mode 100644 index 0000000..5cc4444 --- /dev/null +++ b/src/diffpy/srreal/calculationkernel.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python +############################################################################## +# +# (c) 2026 The Trustees of Columbia University in the City of New York. +# All rights reserved. +# +# File coded by: Billinge Group members and community contributors. +# +# See GitHub contributions for a more detailed list of contributors. +# https://github.com/diffpy/diffpy.srreal/graphs/contributors +# +# See LICENSE.rst for license information. +# +############################################################################## +"""Selection of the kernel that sums the contributions of atom pairs. + +PDFCalculator and DebyePDFCalculator send full pair sums to the selected +kernel, by default the best one the CPU supports. For refinements with +'cuda-mixed', use larger finite-difference steps and verify the fit in +double precision. +""" + +# exported items +__all__ = [ + "availableCalculationKernels", + "getCalculationKernel", + "setCalculationKernel", +] + +from diffpy.srreal.srreal_ext import ( + availableCalculationKernels, + getCalculationKernel, + setCalculationKernel, +) + +# End of file diff --git a/src/diffpy/srreal/structureconverters.py b/src/diffpy/srreal/structureconverters.py index b8c36eb..934c029 100644 --- a/src/diffpy/srreal/structureconverters.py +++ b/src/diffpy/srreal/structureconverters.py @@ -15,6 +15,10 @@ """Converters from other structure representations in Python to diffpy.srreal StructureAdapter classes.""" +import sys + +import numpy + from diffpy.srreal.srreal_ext import ( AtomicStructureAdapter, PeriodicStructureAdapter, @@ -77,6 +81,39 @@ def _fetchDiffPyStructureData(adpt, stru): """ from diffpy.srreal.srreal_ext import Atom as AdapterAtom + # Batch isotropic tensors only when the atoms use standard properties, + # the structure's lattice, and coordinates and occupancies in native form. + lattice = stru.lattice + standard_atom = getattr(sys.modules.get("diffpy.structure"), "Atom", None) + if ( + len(stru) > 1 + and all( + type(a) is standard_atom + and a.lattice is lattice + and type(a.occupancy) is float + and type(a.xyz) is numpy.ndarray + and a.xyz.shape == (3,) + for a in stru + ) + and not all(a.anisotropy for a in stru) + ): + atomtypes = [a.element for a in stru] + xyz = [a.xyz for a in stru] + occupancy = [a.occupancy for a in stru] + anisotropy = [a.anisotropy for a in stru] + uiso = [0.0 if f else a.Uisoequiv for a, f in zip(stru, anisotropy)] + uij = numpy.multiply.outer(uiso, lattice.isotropicunit) + if any(anisotropy): + uij[anisotropy] = [a.U for a, f in zip(stru, anisotropy) if f] + if hasattr(adpt, "setLatPar"): + adpt.setLatPar(*lattice.cell_parms()) + adpt._setLatticeAtomArrays( + atomtypes, xyz, occupancy, anisotropy, uij + ) + else: + adpt.setAtomArrays(atomtypes, xyz, occupancy, anisotropy, uij) + return + # copy atoms adpt.clear() adpt.reserve(len(stru)) diff --git a/src/extensions/srreal_converters.cpp b/src/extensions/srreal_converters.cpp index d0dd48d..08322f2 100644 --- a/src/extensions/srreal_converters.cpp +++ b/src/extensions/srreal_converters.cpp @@ -151,6 +151,13 @@ NumPyOutput createNumPyDoubleArray(size_t dim, const size_t* sz) } +NumPyOutput createNumPyBoolArray(size_t size) +{ + nb::object array = newNumPyArray(1, &size, "bool", sizeof(bool)); + return {array, nb::cast::array)>(array, false)}; +} + + NumPyOutput createNumPyDoubleArrayLike(const NumPyDoubleInput& array) { std::vector shape(array.ndim()); diff --git a/src/extensions/srreal_converters.hpp b/src/extensions/srreal_converters.hpp index 1e9f798..3772e3e 100644 --- a/src/extensions/srreal_converters.hpp +++ b/src/extensions/srreal_converters.hpp @@ -249,6 +249,7 @@ struct NumPyOutput /// helper for creating numpy array of doubles NumPyOutput createNumPyDoubleArray(size_t dim, const size_t* sz); +NumPyOutput createNumPyBoolArray(size_t size); /// helper for creating numpy array of the same shape as the argument diff --git a/src/extensions/srreal_ext.cpp b/src/extensions/srreal_ext.cpp index 1c8282a..e971363 100644 --- a/src/extensions/srreal_ext.cpp +++ b/src/extensions/srreal_ext.cpp @@ -45,6 +45,7 @@ void wrap_PDFCalculators(nb::module_& m); void wrap_BondCalculator(nb::module_& m); void wrap_AtomRadiiTable(nb::module_& m); void wrap_OverlapCalculator(nb::module_& m); +void wrap_CalculationKernel(nb::module_& m); } // namespace srrealmodule @@ -75,6 +76,7 @@ NB_MODULE(srreal_ext, m) wrap_BondCalculator(m); wrap_AtomRadiiTable(m); wrap_OverlapCalculator(m); + wrap_CalculationKernel(m); // load Python modules that tweak the wrapped classes nb::module_ srreal = nb::module_::import_("diffpy.srreal"); if (!nb::hasattr(srreal, "_final_imports")) diff --git a/src/extensions/wrap_AtomicStructureAdapter.cpp b/src/extensions/wrap_AtomicStructureAdapter.cpp index 0d7f1ea..927a19c 100644 --- a/src/extensions/wrap_AtomicStructureAdapter.cpp +++ b/src/extensions/wrap_AtomicStructureAdapter.cpp @@ -19,6 +19,14 @@ * *****************************************************************************/ +#include +#include +#include +#include +#include +#include +#include + #include #include "srreal_trampoline.hpp" #include @@ -118,6 +126,45 @@ const char* doc_AtomicStructureAdapter_clear = "\ Remove all atoms from the structure.\n\ "; +const char* doc_AtomicStructureAdapter_getAtomArrays = "\ +Return the data of all atoms as arrays.\n\ +\n\ +Return a tuple (atomtypes, xyz_cartn, occupancy, anisotropy, uij_cartn)\n\ +with a list of N type strings and NumPy arrays of the shapes (N, 3), (N,),\n\ +(N,) and (N, 3, 3). The arrays are copies of the atom data.\n\ +"; + +const char* doc_AtomicStructureAdapter_setAtomArrays = "\ +Replace all atoms with the atoms given as arrays.\n\ +\n\ +atomtypes -- sequence of N type strings\n\ +xyz_cartn -- Cartesian coordinates, shape (N, 3)\n\ +occupancy -- occupancies, shape (N,)\n\ +anisotropy -- flags of anisotropic displacements, shape (N,)\n\ +uij_cartn -- Cartesian displacement parameters, shape (N, 3, 3)\n\ +\n\ +No return value. Atom objects obtained from this adapter before are\n\ +detached from it.\n\ +"; + +const char* doc_PeriodicStructureAdapter_setLatticeAtomArrays = "\ +Replace all atoms with the atoms given as arrays in lattice coordinates.\n\ +\n\ +The arguments are those of setAtomArrays in lattice coordinates, which\n\ +are converted by toCartesian.\n\ +\n\ +isotropic_cartesian -- when True, keep isotropic displacements as given.\n\ +"; + +const char* doc_CrystalStructureAdapter_setSymOps = "\ +Replace the symmetry operations with those given as arrays.\n\ +\n\ +rotations -- rotation matrices in fractional coordinates, shape (N, 3, 3)\n\ +translations -- translation vectors in fractional coordinates, shape (N, 3)\n\ +\n\ +No return value. Unchanged operations keep the symmetry positions.\n\ +"; + const char* doc_AtomicStructureAdapter_reserve = "\ Reserve memory for a specified number of atoms.\n\ Although not required, calling this method can save memory and\n\ @@ -631,6 +678,116 @@ void atomadapter_reserve(AtomicStructureAdapter& adpt, int sz) adpt.reserve(sz); } +// Atom data of the whole adapter as arrays + +/// Throw ValueError unless the array has the given shape. +template +void ensure_array_shape(nb::handle input, const Array& array, + std::initializer_list shape, const char* name) +{ + // An empty sequence such as [] has no explicit trailing dimensions. + if (std::ranges::equal(std::span(array.shape_ptr(), array.ndim()), shape) || + (*shape.begin() == 0 && array.ndim() == 1 && array.shape(0) == 0 && + !nb::hasattr(input, "shape"))) + return; + std::string emsg = name; + emsg += " must have the shape ("; + const char* sep = ""; + for (size_t sz : shape) + { + emsg += sep + std::to_string(sz); + sep = ", "; + } + emsg += (shape.size() == 1) ? ",)." : ")."; + throw std::invalid_argument(emsg); +} + + +/// Atoms from the arrays of setAtomArrays. +std::vector atoms_from_arrays(nb::object atomtypes, nb::object xyz, + nb::object occupancy, nb::object anisotropy, nb::object uij) +{ + if (nb::isinstance(atomtypes) || nb::isinstance(atomtypes)) + throw nb::type_error("atomtypes must be a sequence of type strings."); + std::vector atoms; + for (nb::handle atomtype : atomtypes) + { + atoms.emplace_back(); + atoms.back().atomtype = nb::cast(atomtype); + } + const size_t n = atoms.size(); + NumPyDoubleInput axyz = extractNumPyDoubleArray(xyz); + NumPyDoubleInput aocc = extractNumPyDoubleArray(occupancy); + NumPyDoubleInput auij = extractNumPyDoubleArray(uij); + using BoolInput = nb::ndarray; + nb::object flags = nb::module_::import_("numpy").attr("asarray")( + anisotropy, nb::arg("dtype") = "bool", nb::arg("order") = "C"); + auto aaniso = nb::cast(flags, false); + ensure_array_shape(xyz, axyz, {n, 3}, "xyz_cartn"); + ensure_array_shape(occupancy, aocc, {n}, "occupancy"); + ensure_array_shape(anisotropy, aaniso, {n}, "anisotropy"); + ensure_array_shape(uij, auij, {n, 3, 3}, "uij_cartn"); + const double* pxyz = axyz.data(); + const double* pocc = aocc.data(); + // NumPy permits any nonzero byte in a boolean array. + const auto paniso = std::as_bytes(std::span(aaniso.data(), n)); + const double* puij = auij.data(); + for (size_t i = 0; i < n; ++i, pxyz += 3, puij += 9) + { + Atom& a = atoms[i]; + a.xyz_cartn = R3::Vector(pxyz[0], pxyz[1], pxyz[2]); + a.occupancy = pocc[i]; + a.anisotropy = paniso[i] != std::byte{}; + std::copy_n(puij, a.uij_cartn.data().size(), a.uij_cartn.data().begin()); + } + return atoms; +} + + +void assign_atoms(AtomicStructureAdapter& adpt, std::vector&& atoms) +{ + replace_atom_references(adpt, 0, adpt.size(), atoms.size()); + adpt.assign(std::move(atoms)); +} + + +void atomadapter_setatomarrays(AtomicStructureAdapter& adpt, + nb::object atomtypes, nb::object xyz, nb::object occupancy, + nb::object anisotropy, nb::object uij) +{ + assign_atoms(adpt, + atoms_from_arrays(atomtypes, xyz, occupancy, anisotropy, uij)); +} + + +nb::tuple atomadapter_getatomarrays(const AtomicStructureAdapter& adpt) +{ + const size_t n = adpt.size(); + const size_t ndim = static_cast(R3::Ndim); + const size_t szxyz[2] = {n, ndim}; + const size_t szuij[3] = {n, ndim, ndim}; + nb::list atomtypes; + auto anisotropy = createNumPyBoolArray(n); + bool* flags = anisotropy.array.data(); + NumPyOutput xyz = createNumPyDoubleArray(2, szxyz); + NumPyOutput occupancy = createNumPyDoubleArray(1, &n); + NumPyOutput uij = createNumPyDoubleArray(3, szuij); + double* pxyz = xyz.array.data(); + double* pocc = occupancy.array.data(); + double* puij = uij.array.data(); + for (const Atom& a : adpt) + { + atomtypes.append(a.atomtype); + *flags++ = a.anisotropy; + pxyz = std::copy(a.xyz_cartn.begin(), a.xyz_cartn.end(), pxyz); + *(pocc++) = a.occupancy; + puij = std::ranges::copy(a.uij_cartn.data(), puij).out; + } + return nb::make_tuple( + atomtypes, xyz.object, occupancy.object, anisotropy.object, uij.object); +} + // Wrapper helpers for class PeriodicStructureAdapter typedef MakeWrapper PeriodicStructureAdapterWrap; @@ -644,6 +801,21 @@ nb::tuple periodicadapter_getlatpar(const PeriodicStructureAdapter& adpt) return rv; } +void periodicadapter_setlatticeatomarrays(PeriodicStructureAdapter& adpt, + nb::object atomtypes, nb::object xyz, nb::object occupancy, + nb::object anisotropy, nb::object uij, bool isotropic_cartesian) +{ + std::vector atoms = + atoms_from_arrays(atomtypes, xyz, occupancy, anisotropy, uij); + for (Atom& a : atoms) + { + const R3::Matrix ucartesian = a.uij_cartn; + adpt.toCartesian(a); + if (isotropic_cartesian && !a.anisotropy) a.uij_cartn = ucartesian; + } + assign_atoms(adpt, std::move(atoms)); +} + // Wrapper helpers for class CrystalStructureAdapter typedef MakeWrapper CrystalStructureAdapterWrap; @@ -666,6 +838,36 @@ void crystaladapter_addsymop(CrystalStructureAdapter& adpt, } +void crystaladapter_setsymops(CrystalStructureAdapter& adpt, + nb::object rotations, nb::object translations) +{ + NumPyDoubleInput ar = extractNumPyDoubleArray(rotations); + NumPyDoubleInput at = extractNumPyDoubleArray(translations); + const size_t n = (ar.ndim() > 0) ? ar.shape(0) : 0; + ensure_array_shape(rotations, ar, {n, 3, 3}, "rotations"); + ensure_array_shape(translations, at, {n, 3}, "translations"); + std::vector ops(n); + const double* pr = ar.data(); + const double* pt = at.data(); + for (SymOpRotTrans& op : ops) + { + std::copy_n(pr, op.R.data().size(), op.R.data().begin()); + std::copy_n(pt, op.t.size(), op.t.begin()); + pr += op.R.data().size(); + pt += op.t.size(); + } + // Keep the expanded symmetry positions for unchanged operations. + bool same = (int(n) == adpt.countSymOps()); + for (size_t i = 0; same && i < n; ++i) + { + same = (ops[i] == adpt.getSymOp(i)); + } + if (same) return; + adpt.clearSymOps(); + for (const SymOpRotTrans& op : ops) adpt.addSymOp(op); +} + + nb::tuple crystaladapter_getsymop(const CrystalStructureAdapter& adpt, int idx) { @@ -687,7 +889,7 @@ nb::list atoms_aslist(const Range& atoms) nb::object crystaladapter_getequivalentatoms( const CrystalStructureAdapter& adpt, int idx) { - ensure_index_bounds(idx, 0, adpt.countSymOps()); + ensure_index_bounds(idx, 0, adpt.countSites()); return atoms_aslist(adpt.getEquivalentAtoms(idx)); } @@ -829,6 +1031,13 @@ void wrap_AtomicStructureAdapter(nb::module_& m) doc_AtomicStructureAdapter_clear) .def("reserve", atomadapter_reserve, nb::arg("sz"), doc_AtomicStructureAdapter_reserve) + .def("getAtomArrays", atomadapter_getatomarrays, + doc_AtomicStructureAdapter_getAtomArrays) + .def("setAtomArrays", atomadapter_setatomarrays, + nb::arg("atomtypes"), nb::arg("xyz_cartn"), + nb::arg("occupancy"), nb::arg("anisotropy"), + nb::arg("uij_cartn"), + doc_AtomicStructureAdapter_setAtomArrays) ; StructureAdapterPickleSuite::bind(adapter_class); @@ -868,6 +1077,11 @@ void wrap_AtomicStructureAdapter(nb::module_& m) adpt.toFractional(atom.value()); }, nb::arg("atom"), doc_PeriodicStructureAdapter_toFractional) + .def("_setLatticeAtomArrays", periodicadapter_setlatticeatomarrays, + nb::arg("atomtypes"), nb::arg("xyz"), + nb::arg("occupancy"), nb::arg("anisotropy"), + nb::arg("uij"), nb::arg("isotropic_cartesian") = false, + doc_PeriodicStructureAdapter_setLatticeAtomArrays) ; StructureAdapterPickleSuite::bind(periodic_class); @@ -905,6 +1119,9 @@ void wrap_AtomicStructureAdapter(nb::module_& m) doc_CrystalStructureAdapter_addSymOp) .def("getSymOp", crystaladapter_getsymop, nb::arg("index"), doc_CrystalStructureAdapter_getSymOp) + .def("_setSymOps", crystaladapter_setsymops, + nb::arg("rotations"), nb::arg("translations"), + doc_CrystalStructureAdapter_setSymOps) .def("getEquivalentAtoms", crystaladapter_getequivalentatoms, nb::arg("index"), doc_CrystalStructureAdapter_getEquivalentAtoms) diff --git a/src/extensions/wrap_CalculationKernel.cpp b/src/extensions/wrap_CalculationKernel.cpp new file mode 100644 index 0000000..ec60051 --- /dev/null +++ b/src/extensions/wrap_CalculationKernel.cpp @@ -0,0 +1,68 @@ +/***************************************************************************** +* +* diffpy.srreal Complex Modeling Initiative +* (c) 2026 The Trustees of Columbia University +* in the City of New York. All rights reserved. +* +* See AUTHORS.rst for a list of people who contributed. +* See LICENSE.rst for license information. +* +****************************************************************************** +* +* Bindings to the selection of the calculation kernel in libdiffpy. +* +*****************************************************************************/ + +#include +#include +#include + +#include + +namespace nb = nanobind; + +namespace srrealmodule { +namespace nswrap_CalculationKernel { + +// docstrings ---------------------------------------------------------------- + +const char* doc_availableCalculationKernels = "\ +Return the kernels this machine can run, CPU kernels first in order of\n\ +preference. CUDA builds add 'cuda' and 'cuda-mixed' on compatible\n\ +devices; these fall back to the CPU for masked sums, custom peak\n\ +profiles and per-bond evaluations.\n\ +"; + +const char* doc_getCalculationKernel = "\ +Return the name of the calculation kernel in use.\n\ +"; + +const char* doc_setCalculationKernel = "\ +Use the named calculation kernel in all calculators.\n\ +\n\ +name -- one of the names from availableCalculationKernels\n\ +\n\ +Raise ValueError when the kernel is not available. Do not call this\n\ +while a calculator evaluates in another thread.\n\ +"; + +} // namespace nswrap_CalculationKernel + +// Wrapper definition -------------------------------------------------------- + +void wrap_CalculationKernel(nb::module_& m) +{ + using namespace nswrap_CalculationKernel; + using namespace diffpy::srreal; + + m.def("availableCalculationKernels", availableCalculationKernels, + doc_availableCalculationKernels); + m.def("getCalculationKernel", getCalculationKernel, + doc_getCalculationKernel); + m.def("setCalculationKernel", setCalculationKernel, + nb::arg("name"), doc_setCalculationKernel); +} + +} // namespace srrealmodule + +// End of file diff --git a/src/extensions/wrap_PDFCalculators.cpp b/src/extensions/wrap_PDFCalculators.cpp index 9235c71..97fcedc 100644 --- a/src/extensions/wrap_PDFCalculators.cpp +++ b/src/extensions/wrap_PDFCalculators.cpp @@ -398,11 +398,11 @@ nb::tuple getstate_super(nb::object obj) { obj.attr("clearEnvelopes")(); needs_restore = true; - assert(nb::len(obj.attr("envelopes")) == 0); + assert(nb::len(nb::getattr(obj, "envelopes")) == 0); nb::tuple super_state = Super::getstate(obj); obj.attr("envelopes") = envlps; needs_restore = false; - assert(nb::len(obj.attr("envelopes")) == nb::len(envlps)); + assert(nb::len(nb::getattr(obj, "envelopes")) == nb::len(envlps)); return nb::make_tuple(super_state); } catch (...) @@ -433,7 +433,7 @@ void setstate_common(T& calc, nb::object obj, nb::tuple state, size_t& pos) { assign_pointer_state(calc.getPeakWidthModel(), state[pos++]); assign_pointer_state(calc.getScatteringFactorTable(), state[pos++]); - assert(nb::len(obj.attr("envelopes")) == 0); + assert(nb::len(nb::getattr(obj, "envelopes")) == 0); obj.attr("envelopes") = nb::borrow(state[pos++]); } diff --git a/src/extensions/wrap_PairQuantity.cpp b/src/extensions/wrap_PairQuantity.cpp index 823cad4..cfa047f 100644 --- a/src/extensions/wrap_PairQuantity.cpp +++ b/src/extensions/wrap_PairQuantity.cpp @@ -125,7 +125,8 @@ const char* doc_BasePairQuantity_evaluatortypeused = "\ String type of evaluation procedure used in the last calculation.\n\ \n\ Possible values are 'BASIC', 'OPTIMIZED', 'CHECK', and 'NONE'\n\ -when calculator that has not been used yet.\n\ +when calculator that has not been used yet. 'OPTIMIZED' reports 'BASIC'\n\ +when it recalculated from scratch, for example because that was cheaper.\n\ "; const char* doc_BasePairQuantity_maskAllPairs = "\ diff --git a/tests/test_allpairs.py b/tests/test_allpairs.py new file mode 100644 index 0000000..25fb90c --- /dev/null +++ b/tests/test_allpairs.py @@ -0,0 +1,194 @@ +#!/usr/bin/env python +"""Unit tests for the batched pair sums of PDFCalculator and +DebyePDFCalculator, compared to pair-by-pair sums with a Python peak +width model.""" + +import pickle + +import numpy +import pytest +from testutils import ( + DerivedPeriodicStructureAdapter, + _maxNormDiff, + loadCrystalStructureAdapter, + loadDiffPyStructure, +) + +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.srreal.peakwidthmodel import PeakWidthModel +from diffpy.srreal.structureadapter import ( + AtomicStructureAdapter, + createStructureAdapter, + nometa, +) + +CALCULATORS = [PDFCalculator, DebyePDFCalculator] + + +class ScaledWidth(PeakWidthModel): + """Peak widths of another model times a factor.""" + + def __init__(self, model, factor=1): + PeakWidthModel.__init__(self) + self.model = model + self.factor = factor + return + + def type(self): + return "scaledwidth" + + def create(self): + return ScaledWidth(self.model.create(), self.factor) + + def clone(self): + return ScaledWidth(self.model.clone(), self.factor) + + def calculate(self, bnds): + return self.factor * self.model.calculate(bnds) + + def maxWidth(self, stru, rmin, rmax): + return self.factor * self.model.maxWidth(stru, rmin, rmax) + + +def pair_by_pair(calc): + """Return a copy of calc that adds its pairs one by one.""" + rv = calc.copy() + rv.peakwidthmodel = ScaledWidth(calc.peakwidthmodel) + return rv + + +@pytest.fixture(scope="module") +def rutile(): + return loadDiffPyStructure("rutile.cif") + + +@pytest.mark.parametrize("calculator", CALCULATORS) +def test_structures(calculator, rutile): + """Check the results for every kind of structure object.""" + calc = calculator(rmax=9) + onebyone = pair_by_pair(calc) + adapter = createStructureAdapter(rutile) + structures = [ + rutile, + adapter, + nometa(rutile), + loadCrystalStructureAdapter("rutile.cif"), + ] + for stru in structures: + r, g = calc(stru) + r, g1 = onebyone(stru) + assert numpy.any(g) + assert _maxNormDiff(g1, g) < 1e-12 + # An adapter class defined in Python gives its bonds itself. + derived = DerivedPeriodicStructureAdapter() + derived.setLatPar(*adapter.getLatPar()) + derived.setAtomArrays(*adapter.getAtomArrays()) + r, g = calc(derived) + r, g1 = onebyone(derived) + assert _maxNormDiff(g1, g) < 1e-12 + r, gadapter = calc(adapter) + assert _maxNormDiff(gadapter, g) < 1e-12 + return + + +@pytest.mark.parametrize("calculator", CALCULATORS) +def test_python_peak_width_model(calculator, rutile): + calc = calculator(rmax=9, peakwidthmodel="constant") + calc.peakwidthmodel.width = 0.2 + _, g = calc(rutile) + wide = calc.copy() + wide.peakwidthmodel.width = 0.4 + r, gwide = wide(rutile) + assert not numpy.allclose(g, gwide) + calc.peakwidthmodel = ScaledWidth(calc.peakwidthmodel, 2) + r, gdouble = calc(rutile) + assert _maxNormDiff(gwide, gdouble) < 1e-12 + return + + +@pytest.mark.parametrize("calculator", CALCULATORS) +def test_masks(calculator, rutile): + calc = calculator(rmax=9) + r, gall = calc(rutile) + calc.setTypeMask("Ti", "O", False) + r, g = calc(rutile) + r, g1 = pair_by_pair(calc)(rutile) + assert _maxNormDiff(g1, g) < 1e-12 + assert not numpy.allclose(g, gall) + return + + +def test_nearly_equal_distances_straddle_cropped_peak_boundary(): + # One dimer contributes at 2.10 angstroms and the other is cropped. + xyz = [[0, 0, 0], [2, 0, 0], [0, 30, 0], [numpy.nextafter(2, 3), 30, 0]] + stru = AtomicStructureAdapter() + stru.setAtomArrays( + ["H"] * 4, xyz, numpy.ones(4), numpy.zeros(4), numpy.zeros((4, 3, 3)) + ) + calc = PDFCalculator(rmax=5, rstep=0.01, maxextension=0) + calc.peakwidthmodel = "constant" + calc.peakwidthmodel.width = 0.2 + calc.peakprofile = "croppedgaussian" + calc.peakprecision = 0.5 + reference = pair_by_pair(calc) + reference(stru) + calc(stru) + assert reference.rdf[210] > 0 + numpy.testing.assert_allclose( + calc.rdf, reference.rdf, rtol=1e-12, atol=1e-14 + ) + + +def test_fast_updates(): + """Check the evaluation used after the change of one atom.""" + ni = loadDiffPyStructure("Ni.stru") + calc = PDFCalculator(rmax=9) + # The four atoms of Ni take less work when added all at once. + for c, used in ((calc, "BASIC"), (pair_by_pair(calc), "OPTIMIZED")): + basic = c.copy() + basic.evaluatortype = "BASIC" + c(ni) + moved = ni.copy() + moved[1].xyz[0] += 0.01 + r, g = c(moved) + assert used == c.evaluatortypeused + r, gb = basic(moved) + assert numpy.allclose(gb, g, rtol=0, atol=1e-10) + return + + +@pytest.mark.parametrize("calculator", CALCULATORS) +def test_copies(calculator, rutile): + calc = calculator(rmax=9) + r, g = calc(rutile) + for other in (calc.copy(), pickle.loads(pickle.dumps(calc))): + assert numpy.array_equal(g, other.pdf) + other.evaluatortype = "BASIC" + r, g1 = other(rutile) + assert numpy.array_equal(g, g1) + return + + +@pytest.mark.parametrize("calculator", CALCULATORS) +def test_large_cpu_batch(calculator): + # Unequal occupancies and mixed atom types exercise the Debye cutoff. + # The cluster has enough pairs to cross batch and worker boundaries. + n = 377 + rng = numpy.random.default_rng(151) + atoms = AtomicStructureAdapter() + atoms.setAtomArrays( + ["Ni", "O"] * (n // 2) + ["Ni"], + rng.uniform(0, 12, (n, 3)), + rng.choice([0.4, 0.7, 1.0], n), + numpy.zeros(n), + numpy.tile(numpy.eye(3) * 0.005, (n, 1, 1)), + ) + calc = calculator(rmax=14, qmax=18) + calc.evaluatortype = "BASIC" + calc.setTypeMask("Ni", "O", False) + _, reference = pair_by_pair(calc)(atoms) + _, batch = calc(atoms) + batch = batch.copy() + assert numpy.any(reference) + assert _maxNormDiff(reference, batch) < 1e-12 + numpy.testing.assert_array_equal(calc(atoms)[1], batch) diff --git a/tests/test_atomarrays.py b/tests/test_atomarrays.py new file mode 100644 index 0000000..719e505 --- /dev/null +++ b/tests/test_atomarrays.py @@ -0,0 +1,468 @@ +#!/usr/bin/env python +"""Unit tests for the atom data of structure adapters as arrays.""" + +import gc +import weakref + +import numpy +import pytest +from testutils import loadDiffPyStructure + +from diffpy.srreal.structureadapter import ( + Atom, + AtomicStructureAdapter, + CrystalStructureAdapter, + PeriodicStructureAdapter, + createStructureAdapter, +) +from diffpy.structure import Atom as StructureAtom +from diffpy.structure import Lattice, Structure + +TRICLINIC = (4.1, 5.2, 6.3, 81.0, 97.0, 115.0) +ADAPTERS = [ + AtomicStructureAdapter, + PeriodicStructureAdapter, + CrystalStructureAdapter, +] + + +def make_arrays(n=7): + """Return arrays of n atoms, every third one anisotropic.""" + rng = numpy.random.default_rng(n) + atomtypes = [("C", "Ti4+", "O2-")[i % 3] for i in range(n)] + xyz = rng.uniform(-1.0, 2.0, (n, 3)) + occupancy = rng.uniform(0.1, 1.0, n) + anisotropy = numpy.arange(n) % 3 == 1 + uiso = rng.uniform(0.002, 0.02, n) + uij = uiso[:, None, None] * numpy.eye(3) + for i in numpy.flatnonzero(anisotropy): + m = rng.uniform(-0.03, 0.03, (3, 3)) + uij[i] = 0.5 * (m + m.T) + 0.1 * numpy.eye(3) + return atomtypes, xyz, occupancy, anisotropy, uij + + +def append_atoms(adpt, arrays, lattice=False, isotropic_cartesian=False): + """Fill the adapter atom by atom, as the converters once did.""" + for atomtype, xyz, occupancy, anisotropy, uij in zip(*arrays): + atom = Atom() + atom.atomtype = atomtype + atom.xyz_cartn = xyz + atom.occupancy = occupancy + atom.anisotropy = anisotropy + atom.uij_cartn = uij + if lattice: + adpt.toCartesian(atom) + if isotropic_cartesian and not anisotropy: + atom.uij_cartn = uij + adpt.append(atom) + return adpt + + +@pytest.mark.parametrize("cls", ADAPTERS) +def test_set_atom_arrays(cls): + arrays = make_arrays() + expected = append_atoms(cls(), arrays) + adpt = cls() + adpt.setAtomArrays(*arrays) + assert expected == adpt + assert 7 == adpt.countSites() + # the adapter copies the arrays + arrays[1][:] = 0.0 + assert expected == adpt + # other sequences give the same atoms + atomtypes, xyz, occupancy, anisotropy, uij = make_arrays() + adpt.setAtomArrays( + tuple(atomtypes), + xyz.tolist(), + list(occupancy), + [bool(f) for f in anisotropy], + numpy.asfortranarray(uij), + ) + assert expected == adpt + # new arrays replace all atoms + adpt.setAtomArrays(*make_arrays(3)) + assert append_atoms(cls(), make_arrays(3)) == adpt + adpt.setAtomArrays(*make_arrays(0)) + assert cls() == adpt + adpt.setAtomArrays([], [], [], [], []) + assert cls() == adpt + return + + +@pytest.mark.parametrize("cls", ADAPTERS) +def test_get_atom_arrays(cls): + arrays = make_arrays() + adpt = append_atoms(cls(), arrays) + atomtypes, xyz, occupancy, anisotropy, uij = adpt.getAtomArrays() + assert arrays[0] == atomtypes + assert numpy.array_equal(arrays[1], xyz) + assert numpy.array_equal(arrays[2], occupancy) + assert numpy.array_equal(arrays[3], anisotropy) + assert bool == anisotropy.dtype + assert numpy.array_equal(arrays[4], uij) + assert (7, 3) == xyz.shape + assert (7, 3, 3) == uij.shape + # the arrays are copies + xyz[:] = 0.0 + assert numpy.array_equal(arrays[1], adpt.getAtomArrays()[1]) + # an empty adapter has empty arrays of the same dimensions + atomtypes, xyz, occupancy, anisotropy, uij = cls().getAtomArrays() + assert [] == atomtypes + assert (0, 3) == xyz.shape + assert (0,) == occupancy.shape + assert (0,) == anisotropy.shape + assert (0, 3, 3) == uij.shape + return + + +def test_atom_array_boolean_storage(): + atomtypes, xyz, occ, _, uij = make_arrays(3) + adpt = AtomicStructureAdapter() + # Nonzero bytes in a read-only NumPy bool view represent True. + flags = numpy.array([0, 2, 255], dtype=numpy.uint8).view(bool) + flags.setflags(write=False) + for view in (flags, flags[::-1]): + adpt.setAtomArrays(atomtypes, xyz, occ, view, uij) + out = adpt.getAtomArrays()[3] + assert out.flags.owndata + numpy.testing.assert_array_equal(out, view) + numpy.testing.assert_array_equal(out.view(numpy.uint8), view != 0) + + +def test_set_atom_arrays_invalid(): + adpt = AtomicStructureAdapter() + adpt.setAtomArrays(*make_arrays()) + expected = adpt.clone() + atomtypes, xyz, occupancy, anisotropy, uij = make_arrays() + invalid = [ + (atomtypes[:-1], xyz, occupancy, anisotropy, uij), + (atomtypes, xyz[:-1], occupancy, anisotropy, uij), + (atomtypes, xyz[:, :2], occupancy, anisotropy, uij), + (atomtypes, xyz.ravel(), occupancy, anisotropy, uij), + (atomtypes, xyz, occupancy[:-1], anisotropy, uij), + (atomtypes, xyz, occupancy[:, None], anisotropy, uij), + (atomtypes, xyz, occupancy, anisotropy[1:], uij), + (atomtypes, xyz, occupancy, anisotropy, uij[:-1]), + (atomtypes, xyz, occupancy, anisotropy, uij[:, :, :2]), + (atomtypes, xyz, occupancy, anisotropy, uij.reshape(-1, 9)), + ] + for arrays in invalid: + with pytest.raises(ValueError): + adpt.setAtomArrays(*arrays) + with pytest.raises(TypeError): + adpt.setAtomArrays([1] * 7, xyz, occupancy, anisotropy, uij) + with pytest.raises(TypeError): + adpt.setAtomArrays(atomtypes, xyz, occupancy, anisotropy) + # a failed call leaves the atoms as they were + assert expected == adpt + return + + +def test_set_atom_arrays_rejects_string(): + adpt = AtomicStructureAdapter() + arrays = make_arrays(2) + with pytest.raises(TypeError, match="atomtypes"): + adpt.setAtomArrays("Ni", *arrays[1:]) + assert adpt.countSites() == 0 + + +@pytest.mark.parametrize( + "index, shape", + [(1, (0, 5)), (2, (1, 0)), (3, (0, 1)), (4, (0, 3, 2)), (4, (0,))], +) +def test_set_atom_arrays_rejects_misshaped_empty_arrays(index, shape): + adpt = AtomicStructureAdapter() + adpt.setAtomArrays(*make_arrays(2)) + expected = adpt.clone() + arrays = list(make_arrays(0)) + arrays[index] = numpy.zeros(shape) + with pytest.raises(ValueError): + adpt.setAtomArrays(*arrays) + assert adpt == expected + + +def test_set_atom_arrays_detaches_atoms(): + adpt = AtomicStructureAdapter() + adpt.setAtomArrays(*make_arrays()) + first = adpt[0] + xyz_view = first.xyz_cartn + xyz0 = xyz_view.copy() + adpt.setAtomArrays(*make_arrays(3)) + numpy.testing.assert_array_equal(xyz_view, xyz0) + xyz_view[:] = 17.0 + assert not numpy.shares_memory(xyz_view, adpt[0].xyz_cartn) + # the atom keeps its values and no longer changes the adapter + assert numpy.array_equal(xyz0, first.xyz_cartn) + first.occupancy = 0.123 + assert 0.123 != adpt[0].occupancy + assert 3 == len(adpt) + return + + +@pytest.mark.parametrize("cls", ADAPTERS[1:]) +def test_set_lattice_atom_arrays(cls): + arrays = make_arrays() + expected = cls() + expected.setLatPar(*TRICLINIC) + append_atoms(expected, arrays, lattice=True) + adpt = cls() + adpt.setLatPar(*TRICLINIC) + adpt._setLatticeAtomArrays(*arrays) + assert expected == adpt + assert not numpy.allclose(arrays[4], adpt.getAtomArrays()[4]) + # Cartesian isotropic tensors stay as given, anisotropic ones change + expected = cls() + expected.setLatPar(*TRICLINIC) + append_atoms(expected, arrays, lattice=True, isotropic_cartesian=True) + adpt._setLatticeAtomArrays(*arrays, isotropic_cartesian=True) + assert expected == adpt + uij = adpt.getAtomArrays()[4] + anisotropy = arrays[3] + assert numpy.array_equal(arrays[4][~anisotropy], uij[~anisotropy]) + assert not numpy.allclose(arrays[4][anisotropy], uij[anisotropy]) + return + + +def test_set_symops(): + adpt = CrystalStructureAdapter() + adpt.setLatPar(*TRICLINIC) + adpt._setLatticeAtomArrays(*make_arrays()) + rotations = numpy.array([numpy.eye(3), -numpy.eye(3)]) + translations = numpy.array([[0.0, 0.0, 0.0], [0.5, 0.0, 0.5]]) + adpt._setSymOps(rotations, translations) + assert 2 == adpt.countSymOps() + for i in range(2): + R, t = adpt.getSymOp(i) + assert numpy.array_equal(rotations[i], R) + assert numpy.array_equal(translations[i], t) + expected = CrystalStructureAdapter() + expected.setLatPar(*TRICLINIC) + expected._setLatticeAtomArrays(*make_arrays()) + for R, t in zip(rotations, translations): + expected.addSymOp(R, t) + assert expected == adpt + assert 2 == adpt.siteMultiplicity(0) + # the same operations again keep the adapter as it is + adpt._setSymOps(rotations, translations) + assert expected == adpt + adpt._setSymOps(rotations[:1], translations[:1]) + assert 1 == adpt.countSymOps() + assert 1 == adpt.siteMultiplicity(0) + with pytest.raises(ValueError): + adpt._setSymOps(rotations, translations[:1]) + with pytest.raises(ValueError): + adpt._setSymOps(rotations[:, :2], translations) + assert 1 == adpt.countSymOps() + return + + +def test_set_atom_arrays_refreshes_equivalent_atoms(): + adpt = CrystalStructureAdapter() + rotations = [numpy.eye(3), -numpy.eye(3)] + translations = numpy.zeros((2, 3)) + adpt._setSymOps(rotations, translations) + atomtypes, xyz, occupancy, anisotropy, uij = make_arrays(1) + xyz[0] = [0, 0, 0] + adpt.setAtomArrays(atomtypes, xyz, occupancy, anisotropy, uij) + assert len(adpt.getEquivalentAtoms(0)) == 1 + + xyz[0] = [0.1, 0.2, 0.3] + adpt.setAtomArrays(atomtypes, xyz, occupancy, anisotropy, uij) + adpt._setSymOps(rotations, translations) + equivalents = adpt.getEquivalentAtoms(0) + numpy.testing.assert_allclose( + [a.xyz_cartn for a in equivalents], [xyz[0], 1 - xyz[0]] + ) + + +def reference_adapter(stru): + """Convert a diffpy.structure object atom by atom.""" + periodic = (1, 1, 1, 90, 90, 90) != stru.lattice.cell_parms() + adpt = PeriodicStructureAdapter() if periodic else AtomicStructureAdapter() + if periodic: + adpt.setLatPar(*stru.lattice.cell_parms()) + for a in stru: + atom = Atom() + atom.atomtype = a.element + atom.occupancy = a.occupancy + atom.anisotropy = a.anisotropy + atom.xyz_cartn = a.xyz + atom.uij_cartn = a.U + if periodic: + adpt.toCartesian(atom) + adpt.append(atom) + return adpt + + +def check_same_atoms(expected, adpt): + """Check that the adapters have the same atoms to the last bit.""" + assert type(expected) is type(adpt) + assert expected == adpt + for x0, x1 in zip(expected.getAtomArrays(), adpt.getAtomArrays()): + assert numpy.array_equal(x0, x1) + return + + +@pytest.mark.parametrize( + "filename", + ["Ni.stru", "TiO2_rutile-fit.stru", "C60bucky.stru", "silicon.cif"], +) +def test_diffpy_structure_files(filename): + stru = loadDiffPyStructure(filename) + adpt = createStructureAdapter(stru) + check_same_atoms(reference_adapter(stru), adpt) + if hasattr(adpt, "getLatPar"): + assert stru.lattice.cell_parms() == adpt.getLatPar() + return + + +@pytest.mark.parametrize("cell", [TRICLINIC, (1, 1, 1, 90, 90, 90)]) +def test_diffpy_structure_mixed_displacements(cell): + stru = Structure(lattice=Lattice(*cell)) + stru.append(StructureAtom("Na", [0.1, 0.2, 0.3], Uisoequiv=0.004)) + stru.append( + StructureAtom( + "Cl", + [0.6, 0.5, 0.9], + occupancy=0.7, + anisotropy=True, + U=[[0.01, 0.002, 0.0], [0.002, 0.02, -0.003], [0.0, -0.003, 0.03]], + ) + ) + stru.append(StructureAtom("Na", [0.4, 0.8, 0.2])) + stru.append(StructureAtom("Cl", [0.3, 0.1, 0.7], Uisoequiv=0.011)) + adpt = createStructureAdapter(stru) + check_same_atoms(reference_adapter(stru), adpt) + assert [False, True, False, False] == list(adpt.getAtomArrays()[3]) + # isotropic atoms have Uisoequiv on the diagonal + uij = adpt.getAtomArrays()[4] + assert numpy.allclose(0.004 * numpy.eye(3), uij[0], rtol=0, atol=1e-17) + assert numpy.array_equal(numpy.zeros((3, 3)), uij[2]) + # all atoms anisotropic, and none + for a in stru: + a.anisotropy = True + check_same_atoms(reference_adapter(stru), createStructureAdapter(stru)) + check_same_atoms( + reference_adapter(stru[:0]), createStructureAdapter(stru[:0]) + ) + return + + +@pytest.mark.parametrize( + "cell", + [(1, 1, 1, 90, 90, 90), (4, 5, 6, 90, 90, 90)], + ids=["atomic", "periodic"], +) +def test_diffpy_structure_shared_atom_lattice(cell): + stru = Structure(lattice=Lattice(*cell)) + stru.append(StructureAtom("Na", [0.1, 0.2, 0.3], Uisoequiv=0.02)) + stru.append(StructureAtom("Cl", [0.4, 0.5, 0.6], Uisoequiv=0.01)) + subset = stru[:1] + subset.lattice = Lattice(*TRICLINIC) + assert stru[0].lattice is subset.lattice + check_same_atoms(reference_adapter(stru), createStructureAdapter(stru)) + + +@pytest.mark.parametrize("occupancy", [None, "0.7"]) +def test_diffpy_structure_invalid_occupancy(occupancy): + stru = Structure([StructureAtom("Ni"), StructureAtom("O")]) + stru[1].occupancy = occupancy + with pytest.raises(TypeError): + createStructureAdapter(stru) + + +@pytest.mark.parametrize("xyz", [0.25, [0.25]]) +def test_diffpy_structure_broadcast_coordinates(xyz): + stru = Structure([StructureAtom("Ni"), StructureAtom("O", [1, 2, 3])]) + stru[0].xyz = xyz + check_same_atoms(reference_adapter(stru), createStructureAdapter(stru)) + + +def test_diffpy_structure_atom_u_override(): + class DisorderedAtom(StructureAtom): + @property + def U(self): + return super().U + 0.02 * self.lattice.isotropicunit + + stru = Structure([StructureAtom("Ni", Uisoequiv=0.01)]) + stru.append(DisorderedAtom("O", Uisoequiv=0.01), copy=False) + check_same_atoms(reference_adapter(stru), createStructureAdapter(stru)) + + +def test_converter_accepts_unhashable_class(): + class Unhashable(type): + __hash__ = None + + class MyStructure(Structure, metaclass=Unhashable): + pass + + stru = MyStructure([StructureAtom("C")]) + assert createStructureAdapter(stru).countSites() == 1 + + +def test_converter_releases_dynamic_class(): + class MyStructure(Structure): + pass + + ref = weakref.ref(MyStructure) + createStructureAdapter(MyStructure()) + del MyStructure + gc.collect() + assert ref() is None + + +def test_converter_of_new_type(): + """Check that a converter registered later is used at once.""" + from diffpy.srreal.structureadapter import ( + RegisterStructureAdapter, + _adapter_converters_registry, + ) + + class MyStructure(Structure): + pass + + stru = MyStructure(loadDiffPyStructure("Ni.stru")) + assert 4 == createStructureAdapter(stru).countSites() + fqname = str(MyStructure).split("'")[1] + try: + RegisterStructureAdapter(fqname, lambda s: AtomicStructureAdapter()) + assert 0 == createStructureAdapter(stru).countSites() + finally: + del _adapter_converters_registry[fqname] + return + + +@pytest.mark.parametrize("cls", ADAPTERS) +def test_fast_updates_of_python_adapter_class(cls): + """Check that a class derived in Python keeps the fast updates. + + The calculator keeps a copy of the last structure, which is of the + built-in class. + """ + from diffpy.srreal.pdfcalculator import PDFCalculator + + class DerivedAdapter(cls): + pass + + def make(shift): + adpt = DerivedAdapter() + if hasattr(adpt, "setLatPar"): + adpt.setLatPar(11.0, 12.0, 13.0, 90, 90, 90) + atomtypes, xyz, occupancy, anisotropy, uij = make_arrays() + xyz[3, 0] += shift + adpt.setAtomArrays(atomtypes, xyz, occupancy, anisotropy, uij) + if hasattr(adpt, "addSymOp"): + adpt.addSymOp(numpy.eye(3), numpy.zeros(3)) + return adpt + + calc = PDFCalculator(rmax=8) + basic = PDFCalculator(rmax=8, evaluatortype="BASIC") + r, g0 = calc(make(0.0)) + assert "BASIC" == calc.evaluatortypeused + for shift in (0.0, 0.2): + r, g = calc(make(shift)) + assert "OPTIMIZED" == calc.evaluatortypeused + r, gb = basic(make(shift)) + assert numpy.allclose(gb, g, rtol=0, atol=1e-10) + assert not numpy.allclose(g0, g) + return diff --git a/tests/test_calculationkernel.py b/tests/test_calculationkernel.py new file mode 100644 index 0000000..e93e0f3 --- /dev/null +++ b/tests/test_calculationkernel.py @@ -0,0 +1,187 @@ +#!/usr/bin/env python +"""Unit tests for diffpy.srreal.calculationkernel.""" + +import os +import pickle + +import numpy +import pytest +from testutils import _maxNormDiff, loadDiffPyStructure + +from diffpy.srreal.calculationkernel import ( + availableCalculationKernels, + getCalculationKernel, + setCalculationKernel, +) +from diffpy.srreal.pdfcalculator import DebyePDFCalculator, PDFCalculator +from diffpy.srreal.structureadapter import AtomicStructureAdapter + +CUDA_KERNELS = ["cuda", "cuda-mixed"] + + +@pytest.fixture +def restore_kernel(): + """Leave the tests with the kernel that was active before them.""" + name = getCalculationKernel() + yield name + setCalculationKernel(name) + return + + +@pytest.fixture +def cuda_device(restore_kernel): + names = availableCalculationKernels() + if "cuda" not in names: + pytest.skip("CUDA kernels unavailable") + setCalculationKernel(names[0]) + + +def test_available(restore_kernel): + names = availableCalculationKernels() + assert len(names) == len(set(names)) + # CPU kernels come first, CUDA kernels are never the default. + cpunames = [n for n in names if n not in CUDA_KERNELS] + assert "scalar" == cpunames[-1] + assert names == cpunames + CUDA_KERNELS or names == cpunames + known = {"avx512", "avx2", "sse2", "neon", "scalar"} + assert known.issuperset(cpunames) + assert restore_kernel in names + return + + +def test_set_kernel(restore_kernel): + for name in availableCalculationKernels(): + setCalculationKernel(name) + assert name == getCalculationKernel() + return + + +def test_set_unavailable_kernel(restore_kernel): + with pytest.raises(ValueError, match="scalar"): + setCalculationKernel("invalid") + with pytest.raises(ValueError): + setCalculationKernel("") + with pytest.raises(TypeError): + setCalculationKernel(None) + assert restore_kernel == getCalculationKernel() + return + + +def test_cpu_calculation(restore_kernel): + stru = loadDiffPyStructure("TiO2_rutile-fit.stru") + calc = PDFCalculator(rmax=12, evaluatortype="BASIC") + setCalculationKernel("scalar") + reference = calc(stru)[1].copy() + assert numpy.max(numpy.abs(reference)) > 0.1 + setCalculationKernel(availableCalculationKernels()[0]) + assert _maxNormDiff(reference, calc(stru)[1]) < 1e-10 + + +def test_cropped_peak_on_absolute_grid(restore_kernel): + # A single dimer gives an RDF of (r / distance) times its peak profile. + distance, width = 2.0, 0.12 + atoms = AtomicStructureAdapter() + atoms.setAtomArrays( + ["Ni", "Ni"], + [[0, 0, 0], [distance, 0, 0]], + [1, 1], + [False, False], + numpy.zeros((2, 3, 3)), + ) + calc = PDFCalculator( + rmin=1.8, + rmax=2.2, + rstep=0.01, + maxextension=0, + peakwidthmodel="constant", + peakprofile="croppedgaussian", + peakprecision=0.5, + ) + calc.peakwidthmodel.width = width + for kernel in availableCalculationKernels(): + setCalculationKernel(kernel) + r, _ = calc(atoms) + expected = [ + x / distance * calc.peakprofile(x - distance, width) for x in r + ] + rtol = 1e-6 if kernel == "cuda-mixed" else 1e-12 + numpy.testing.assert_allclose( + calc.rdf, expected, rtol=rtol, atol=0, err_msg=kernel + ) + + +def test_cuda_missing(restore_kernel): + names = availableCalculationKernels() + if "cuda" in names and os.environ.get("CUDA_VISIBLE_DEVICES") != "-1": + pytest.skip("CUDA kernels available") + for name in CUDA_KERNELS: + assert name not in names + with pytest.raises(ValueError, match=f"'{name}' is not available: .+"): + setCalculationKernel(name) + assert restore_kernel == getCalculationKernel() + return + + +@pytest.mark.parametrize("cls", [PDFCalculator, DebyePDFCalculator]) +def test_cuda(cuda_device, cls): + rutile = loadDiffPyStructure("rutile.cif") + cpu = cls(rmax=9) + r, g = cpu(rutile) + setCalculationKernel("cuda") + calc = cls(rmax=9) + r, gcuda = calc(rutile) + assert _maxNormDiff(g, gcuda) < 1e-11 + assert _maxNormDiff(cpu.value, calc.value) < 1e-12 + # the sums in single precision are other ones + setCalculationKernel("cuda-mixed") + mixed = cls(rmax=9) + r, gmixed = mixed(rutile) + assert 0 < _maxNormDiff(cpu.value, mixed.value) < 1e-5 + assert _maxNormDiff(g, gmixed) < 1e-4 + + +@pytest.mark.parametrize("cls", [PDFCalculator, DebyePDFCalculator]) +def test_pickled_mixed_precision(cuda_device, cls): + stru = loadDiffPyStructure("rutile.cif") + setCalculationKernel("cuda-mixed") + calc = cls(rmax=9) + _, mixed = calc(stru) + restored = pickle.loads(pickle.dumps(calc)) + + setCalculationKernel("cuda") + _, expected = cls(rmax=9)(stru) + assert not numpy.array_equal(mixed, expected) + numpy.testing.assert_array_equal(restored(stru)[1], expected) + + +def test_cuda_in_refinement(cuda_device): + """Check refinements with numerical derivatives on the device.""" + least_squares = pytest.importorskip("scipy.optimize").least_squares + stru = loadDiffPyStructure("Ni.stru") + ptrue = numpy.array([3.53, 0.006, 0.8, 2.5]) + + def pdf(calc, p): + a, uiso, scale, delta2 = p + stru.lattice.set_latt_parms(a, a, a, 90, 90, 90) + stru.Uisoequiv = uiso + calc.scale = scale + calc.delta2 = delta2 + return calc(stru)[1] + + gobs = pdf(PDFCalculator(rmin=1.5, rmax=9), ptrue) + # The default step, 1.5e-8 of a parameter, changes the peaks by less + # than the rounding errors of the mixed precision. + for kernel, step, tolerance in ( + ("cuda", None, 1e-7), + ("cuda-mixed", 1e-4, 1e-5), + ): + setCalculationKernel(kernel) + calc = PDFCalculator(rmin=1.5, rmax=9) + fit = least_squares( + lambda p: pdf(calc, p) - gobs, + [3.52, 0.005, 1.0, 1.5], + x_scale="jac", + diff_step=step, + ) + assert numpy.allclose(fit.x, ptrue, rtol=tolerance) + return diff --git a/tests/test_objcrystconverters.py b/tests/test_objcrystconverters.py index cf8e96e..147a865 100644 --- a/tests/test_objcrystconverters.py +++ b/tests/test_objcrystconverters.py @@ -3,11 +3,16 @@ import subprocess import sys +from concurrent.futures import ThreadPoolExecutor, wait +from threading import Event import numpy as np import pytest -from diffpy.srreal.structureadapter import createStructureAdapter +from diffpy.srreal.structureadapter import ( + CrystalStructureAdapter, + createStructureAdapter, +) from diffpy.srreal.structureconverters import ( convertObjCrystCrystal, convertObjCrystMolecule, @@ -77,8 +82,27 @@ def test_molecule_coordinates_occupancy_anisotropy_and_dummy(objcryst): adapter[0].uij_cartn, np.array([[0.4, 0.01, 0.02], [0.01, 0.5, 0.03], [0.02, 0.03, 0.6]]) / (8 * np.pi**2), + rtol=0, + atol=1e-16, ) + oxygen = objcryst.ScatteringPowerAtom("O", "O") + oxygen.SetBiso(0.7) + crystal.AddScatteringPower(oxygen) + molecule.AddAtom(-1, 0.5, 2, oxygen, "O1") + molecule.AddAtom(4, 5, 6, sp, "C2") + molecule.GetAtom(3).Occupancy = 0.25 + adapter = convertObjCrystMolecule(molecule) + atomtypes, xyz, occupancy, anisotropy, uij = adapter.getAtomArrays() + assert ["C", "O", "C"] == atomtypes + np.testing.assert_array_equal([[1, 2, 3], [-1, 0.5, 2], [4, 5, 6]], xyz) + np.testing.assert_array_equal([0.5, 1, 0.25], occupancy) + np.testing.assert_array_equal([True, False, True], anisotropy) + np.testing.assert_allclose( + uij[1], np.eye(3) * 0.7 / (8 * np.pi**2), rtol=0, atol=1e-16 + ) + assert 0 == len(convertObjCrystMolecule(objcryst.Molecule(crystal, "m"))) + def test_wrong_structure_type(objcryst): with pytest.raises(TypeError): @@ -101,3 +125,311 @@ def test_structureadapter_can_be_imported_first(): capture_output=True, text=True, ) + + +def reference_crystal_adapter(crystal): + """Convert a crystal atom by atom from its list of components.""" + from diffpy.srreal.structureadapter import Atom + + adapter = CrystalStructureAdapter() + lattice = [crystal.GetLatticePar(i) for i in range(6)] + lattice[3:] = np.degrees(lattice[3:]) + adapter.setLatPar(*lattice) + for source in crystal.GetScatteringComponentList(): + sp = source.mpScattPow + if sp is None: + continue + atom = Atom() + atom.atomtype = sp.GetSymbol() + atom.anisotropy = not sp.IsIsotropic() + if atom.anisotropy: + bij = np.array( + [[sp.GetBij(i, j) for j in range(1, 4)] for i in range(1, 4)] + ) + else: + bij = np.eye(3) * sp.GetBiso() + uij = bij / (8 * np.pi**2) + atom.uij_cartn = uij + atom.xyz_cartn = [source.mX, source.mY, source.mZ] + atom.occupancy = source.mOccupancy + adapter.toCartesian(atom) + if not atom.anisotropy: + atom.uij_cartn = uij + adapter.append(atom) + sg = crystal.GetSpaceGroup() + # For each operation f(x) = R x + t, f(0) gives its translation + # and f(e_i) - f(0) gives column i of its rotation. + translations = sg.GetAllSymmetrics(0, 0, 0) + rotations = np.stack( + [sg.GetAllSymmetrics(*axis) - translations for axis in np.eye(3)], + axis=-1, + ) + for rotation, translation in zip(rotations, translations): + adapter.addSymOp(rotation, translation) + return adapter + + +def make_crystal(objcryst, spacegroup="P n m a"): + """Return a crystal with isotropic, anisotropic, partial atoms.""" + crystal = objcryst.Crystal(5.3, 7.7, 5.4, spacegroup) + spca = objcryst.ScatteringPowerAtom("Ca", "Ca") + spca.SetBiso(0.6) + spti = objcryst.ScatteringPowerAtom("Ti", "Ti") + spti.B11, spti.B22, spti.B33 = 0.4, 0.5, 0.6 + spti.B12, spti.B13, spti.B23 = 0.01, 0.02, 0.03 + spo = objcryst.ScatteringPowerAtom("O", "O") + spo.SetBiso(0.9) + for sp in (spca, spti, spo): + crystal.AddScatteringPower(sp) + crystal.AddScatterer(objcryst.Atom(0.03, 0.25, 0.99, "Ca1", spca)) + crystal.AddScatterer(objcryst.Atom(0.0, 0.0, 0.5, "Ti1", spti)) + crystal.AddScatterer(objcryst.Atom(0.48, 0.25, 0.07, "O1", spo)) + crystal.AddScatterer(objcryst.Atom(0.29, 0.04, 0.71, "O2", spo, 0.8)) + return crystal + + +def check_as_reference(crystal): + """Check the converted crystal and its symmetry positions.""" + adapter = createStructureAdapter(crystal) + expected = reference_crystal_adapter(crystal) + assert expected.countSites() == adapter.countSites() + assert expected.countSymOps() == adapter.countSymOps() + assert expected.getLatPar() == adapter.getLatPar() + a0, a1 = expected.getAtomArrays(), adapter.getAtomArrays() + assert a0[0] == a1[0] + np.testing.assert_allclose(a0[1], a1[1], rtol=0, atol=1e-13) + np.testing.assert_array_equal(a0[2], a1[2]) + np.testing.assert_array_equal(a0[3], a1[3]) + np.testing.assert_allclose(a0[4], a1[4], rtol=0, atol=1e-15) + for i in range(expected.countSymOps()): + for x0, x1 in zip(expected.getSymOp(i), adapter.getSymOp(i)): + np.testing.assert_array_equal(x0, x1) + for i in range(expected.countSites()): + e0 = expected.getEquivalentAtoms(i) + e1 = adapter.getEquivalentAtoms(i) + assert len(e0) == len(e1) + for atom0, atom1 in zip(e0, e1): + np.testing.assert_allclose( + atom0.xyz_cartn, atom1.xyz_cartn, rtol=0, atol=1e-13 + ) + np.testing.assert_allclose( + atom0.uij_cartn, atom1.uij_cartn, rtol=0, atol=1e-15 + ) + return adapter + + +@pytest.mark.parametrize("spacegroup", ["P1", "P n m a", "F m -3 m"]) +def test_crystal_as_atom_by_atom(objcryst, spacegroup): + check_as_reference(make_crystal(objcryst, spacegroup)) + + +def test_crystal_without_occupancy_correction(objcryst): + """Check that the crystal keeps its setting of the correction of + occupancies, which the conversion does not use.""" + crystal = make_crystal(objcryst) + assert crystal.GetUseDynPopCorr() + check_as_reference(crystal) + crystal.GetScatterer(3).X = 0.31 + check_as_reference(crystal) + assert crystal.GetUseDynPopCorr() + + +def test_crystal_changes_after_conversion(objcryst): + """Check repeated conversion of one crystal after each change.""" + crystal = make_crystal(objcryst) + first = check_as_reference(crystal) + again = createStructureAdapter(crystal) + assert first == again + assert first is not again + # a changed copy does not show in the next conversion + again[0].xyz_cartn = [1.0, 2.0, 3.0] + again.setLatPar(4, 5, 6, 90, 90, 90) + assert first == check_as_reference(crystal) + ca, ti, o1, o2 = (crystal.GetScatterer(i) for i in range(4)) + spti = ti.GetScatteringPower() + spo = o1.GetScatteringPower() + changes = [ + lambda: setattr(o2, "X", 0.33), + lambda: setattr(ca, "Occupancy", 0.5), + lambda: spo.SetBiso(1.4), + lambda: setattr(spti, "B11", 0.7), + lambda: setattr(spti, "B23", -0.02), + lambda: setattr(crystal, "a", 5.5), + lambda: setattr(crystal, "c", 5.2), + # to a special position and away from it + lambda: setattr(o2, "Y", 0.25), + lambda: setattr(o2, "Y", 0.1), + lambda: crystal.ChangeSpaceGroup("P 21/c"), + lambda: crystal.GetSpaceGroup().ChangeSpaceGroup("P -1"), + lambda: crystal.RemoveScatterer(o1), + lambda: crystal.AddScatterer( + objcryst.Atom(0.1, 0.6, 0.2, "O3", spo, 0.4) + ), + ] + last = first + for change in changes: + change() + adapter = check_as_reference(crystal) + assert last != adapter + # an unchanged crystal converts to an equal adapter + assert adapter == createStructureAdapter(crystal) + last = adapter + + +def test_renamed_sphere_changes_atom_type(objcryst): + crystal = objcryst.Crystal(5, 5, 5, "P1") + power = objcryst.ScatteringPowerSphere("C", 1) + crystal.AddScatteringPower(power) + atom = objcryst.Atom(0.1, 0.2, 0.3, "site", power) + crystal.AddScatterer(atom) + original = createStructureAdapter(crystal) + power.SetName("Ni") + assert createStructureAdapter(crystal)[0].atomtype == "Ni" + assert original[0].atomtype == "C" + + +def test_refinement_parameter_with_independent_clock(objcryst): + from pyobjcryst.refinableobj import RefinableObjClock + + clock = RefinableObjClock() + crystal = make_crystal(objcryst, "P1") + power = crystal.GetScatterer(0).GetScatteringPower() + biso = power.GetPar("Biso") + biso.AssignClock(clock) + original = createStructureAdapter(crystal) + biso.SetValue(2.4) + updated = createStructureAdapter(crystal) + assert updated[0].uij_cartn[0, 0] == pytest.approx(2.4 / (8 * np.pi**2)) + assert original[0].uij_cartn[0, 0] == pytest.approx(0.6 / (8 * np.pi**2)) + + +def test_change_symbol_and_remove_power_in_use(objcryst): + crystal = make_crystal(objcryst, "P1") + power = crystal.GetScatterer(0).GetScatteringPower() + original = createStructureAdapter(crystal) + power.SetSymbol("Mg") + assert createStructureAdapter(crystal)[0].atomtype == "Mg" + crystal.RemoveScatteringPower(power) + power.SetBiso(1.7) + atom = createStructureAdapter(crystal)[0] + assert atom.atomtype == "Mg" + assert atom.uij_cartn[0, 0] == pytest.approx(1.7 / (8 * np.pi**2)) + assert original[0].atomtype == "Ca" + + +def test_concurrent_crystal_snapshots(objcryst, monkeypatch): + crystal = make_crystal(objcryst, "P1") + original = createStructureAdapter(crystal) + site = crystal.GetScatterer(0) + site.Occupancy = 0.25 + read_first = Event() + resume = Event() + set_symops = CrystalStructureAdapter._setSymOps + + def set_symops_after_read(adapter, rotations, translations): + # All source reads are complete before the main thread changes it. + if len(rotations) == 1: + read_first.set() + resume.wait() + set_symops(adapter, rotations, translations) + + monkeypatch.setattr( + CrystalStructureAdapter, "_setSymOps", set_symops_after_read + ) + with ThreadPoolExecutor(max_workers=2) as pool: + first = pool.submit(createStructureAdapter, crystal) + try: + assert read_first.wait(timeout=5) + site.Occupancy = 0.75 + crystal.ChangeSpaceGroup("P -1") + second = pool.submit(createStructureAdapter, crystal) + # A converter that serializes calls can finish after resume. + wait([second], timeout=1) + finally: + resume.set() + first, second = first.result(), second.result() + assert (first[0].occupancy, first.countSymOps()) == (0.25, 1) + assert (second[0].occupancy, second.countSymOps()) == (0.75, 2) + assert original[0].occupancy == 1 + + +@pytest.mark.parametrize("previously_registered", [False, True]) +def test_molecule_with_unregistered_power(objcryst, previously_registered): + from pyobjcryst.crystal import Crystal + + crystal = Crystal(5, 5, 5, "P1") + molecule = objcryst.Molecule(crystal, "molecule") + crystal.AddScatterer(molecule) + registered = objcryst.ScatteringPowerAtom("C", "C") + other = objcryst.ScatteringPowerAtom("C", "C") + crystal.AddScatteringPower(registered) + crystal.AddScatteringPower(objcryst.ScatteringPowerAtom("O", "O")) + if previously_registered: + crystal.AddScatteringPower(other) + crystal.RemoveScatteringPower(other) + molecule.AddAtom(0, 0, 0, registered, "C1") + molecule.AddAtom(1, 0, 0, other, "C2") + other.SetBiso(1) + first = createStructureAdapter(crystal) + other.SetBiso(3) + second = createStructureAdapter(crystal) + assert first[1].uij_cartn[0, 0] == pytest.approx(1 / (8 * np.pi**2)) + assert second[1].uij_cartn[0, 0] == pytest.approx(3 / (8 * np.pi**2)) + + +def test_crystal_component_list_override(objcryst): + class SelectedSiteCrystal(objcryst.Crystal): + selected = 0 + + def GetScatteringComponentList(self): + scatterer = self.GetScatterer(self.selected) + return iter(scatterer.GetScatteringComponentList()) + + crystal = SelectedSiteCrystal(5, 5, 5, "P1") + for i, symbol in enumerate(("C", "O")): + power = objcryst.ScatteringPowerAtom(symbol, symbol) + crystal.AddScatteringPower(power) + crystal.AddScatterer(objcryst.Atom(0.2 * i, 0, 0, symbol, power)) + for i, symbol in enumerate(("C", "O")): + crystal.selected = i + assert createStructureAdapter(crystal).getAtomArrays()[0] == [symbol] + + +def test_crystal_lattice_override_after_conversion(objcryst): + class ScaledCrystal(objcryst.Crystal): + scale = 1.0 + + def GetLatticePar(self, index): + value = super().GetLatticePar(index) + return value * self.scale if index < 3 else value + + crystal = ScaledCrystal(5, 5, 5, "P1") + first = createStructureAdapter(crystal) + crystal.scale = 1.2 + assert createStructureAdapter(crystal).getLatPar()[0] == 6 + assert first.getLatPar()[0] == 5 + + +def test_crystal_component_order_with_scatterer_override(objcryst): + class ReversedCrystal(objcryst.Crystal): + def GetScatterer(self, index): + return super().GetScatterer(self.GetNbScatterer() - 1 - index) + + crystal = ReversedCrystal(5, 5, 5, "P1") + for i, symbol in enumerate(("C", "O")): + power = objcryst.ScatteringPowerAtom(symbol, symbol) + crystal.AddScatteringPower(power) + crystal.AddScatterer(objcryst.Atom(0.2 * i, 0, 0, symbol, power)) + assert createStructureAdapter(crystal).getAtomArrays()[0] == ["C", "O"] + + +def test_crystals_converted_in_turn(objcryst): + crystals = [make_crystal(objcryst, sg) for sg in ("P1", "P n m a")] + for i in range(3): + for crystal in crystals: + crystal.GetScatterer(0).X += 0.01 + check_as_reference(crystal) + # the adapter of a deleted crystal is not used for another one + del crystals[:], crystal + for sg in ("P -1", "P1", "P m m m"): + check_as_reference(make_crystal(objcryst, sg)) diff --git a/tests/test_parallel.py b/tests/test_parallel.py index dae110b..318aa1b 100644 --- a/tests/test_parallel.py +++ b/tests/test_parallel.py @@ -6,7 +6,7 @@ import unittest import numpy -from testutils import loadDiffPyStructure +from testutils import _maxNormDiff, loadDiffPyStructure from diffpy.srreal.parallel import createParallelCalculator @@ -67,7 +67,7 @@ def test_parallel_pdf(self): ppdfc1 = createParallelCalculator(PDFCalculator(), 3, map) r1, g1 = ppdfc1(self.cdse) self.assertTrue(numpy.array_equal(r0, r1)) - self.assertTrue(numpy.allclose(g0, g1)) + self.assertLess(_maxNormDiff(g0, g1), 1e-12) ppdfc2 = createParallelCalculator( PDFCalculator(), self.ncpu, self.pool.imap_unordered ) diff --git a/tests/test_structureadapter.py b/tests/test_structureadapter.py index 895f965..5397c23 100644 --- a/tests/test_structureadapter.py +++ b/tests/test_structureadapter.py @@ -422,6 +422,26 @@ def test_getEquivalentAtoms(self): self.assertEqual(2, len(eqatoms1)) self.assertTrue(all(a.atomtype == "Cd" for a in eqatoms0)) self.assertTrue(all(a.atomtype == "Se" for a in eqatoms1)) + self.assertRaises(IndexError, cdse.getEquivalentAtoms, 2) + self.assertRaises(IndexError, cdse.getEquivalentAtoms, -1) + return + + def test_getEquivalentAtoms_more_sites_than_symops(self): + """Check getEquivalentAtoms for every site of a P1 structure.""" + adpt = CrystalStructureAdapter() + adpt.setLatPar(4, 5, 6, 90, 90, 90) + adpt.addSymOp(numpy.identity(3), numpy.zeros(3)) + a = Atom() + for i, atomtype in enumerate(["Na", "Cl", "O"]): + a.atomtype = atomtype + a.xyz_cartn = (0.5 * i, 0.1, 0.2) + adpt.append(a) + self.assertEqual(1, adpt.countSymOps()) + for i, atomtype in enumerate(["Na", "Cl", "O"]): + eqatoms = adpt.getEquivalentAtoms(i) + self.assertEqual(1, len(eqatoms)) + self.assertEqual(atomtype, eqatoms[0].atomtype) + self.assertRaises(IndexError, adpt.getEquivalentAtoms, 3) return diff --git a/tests/testutils.py b/tests/testutils.py index f2b1484..94f5790 100644 --- a/tests/testutils.py +++ b/tests/testutils.py @@ -64,12 +64,9 @@ def pickle_with_attr(obj, **attr): def _maxNormDiff(yobs, ycalc): - """Returned maximum difference normalized by RMS of the yobs.""" - yobsa = numpy.array(yobs) - obsmax = numpy.max(numpy.fabs(yobsa)) or 1 - ynmdiff = (yobsa - ycalc) / obsmax - rv = max(numpy.fabs(ynmdiff)) - return rv + """Maximum absolute difference, scaled by max(abs(yobs)) or 1.""" + scale = numpy.max(numpy.abs(yobs)) or 1 + return numpy.max(numpy.abs(numpy.asarray(yobs) - ycalc)) / scale # helper class for testing overloading of StructureAdapter diff --git a/tools/install-vcpkg-deps.ps1 b/tools/install-vcpkg-deps.ps1 index 39bbe84..8df12f2 100644 --- a/tools/install-vcpkg-deps.ps1 +++ b/tools/install-vcpkg-deps.ps1 @@ -52,6 +52,7 @@ Invoke-Checked $vcpkg install ` $share = Join-Path $Prefix "installed\$Triplet\share" $licenses = Join-Path $Prefix "licenses" -New-Item -ItemType Directory -Force -Path (Join-Path $licenses "boost"), (Join-Path $licenses "gsl") | Out-Null +New-Item -ItemType Directory -Force -Path (Join-Path $licenses "boost"), (Join-Path $licenses "gsl"), (Join-Path $licenses "xsimd") | Out-Null Copy-Item (Join-Path $share "boost-serialization\copyright") (Join-Path $licenses "boost\LICENSE_1_0.txt") Copy-Item (Join-Path $share "gsl\copyright") (Join-Path $licenses "gsl\COPYING") +Copy-Item (Join-Path $share "xsimd\copyright") (Join-Path $licenses "xsimd\LICENSE") diff --git a/tools/install-vcpkg-deps.sh b/tools/install-vcpkg-deps.sh index 2f9127a..1ef5378 100755 --- a/tools/install-vcpkg-deps.sh +++ b/tools/install-vcpkg-deps.sh @@ -1,5 +1,6 @@ #!/usr/bin/env bash -# Install static Boost.Serialization and GSL with vcpkg for PyPI wheels. +# Install static Boost.Serialization and GSL and the xsimd headers with vcpkg +# for PyPI wheels. # # Usage: tools/install-vcpkg-deps.sh PREFIX TRIPLET # @@ -35,6 +36,7 @@ fi --triplet="$TRIPLET" share="$PREFIX/installed/$TRIPLET/share" -mkdir -p "$PREFIX/licenses/boost" "$PREFIX/licenses/gsl" +mkdir -p "$PREFIX/licenses/boost" "$PREFIX/licenses/gsl" "$PREFIX/licenses/xsimd" cp "$share/boost-serialization/copyright" "$PREFIX/licenses/boost/LICENSE_1_0.txt" cp "$share/gsl/copyright" "$PREFIX/licenses/gsl/COPYING" +cp "$share/xsimd/copyright" "$PREFIX/licenses/xsimd/LICENSE" diff --git a/tools/install-wheel-cuda.ps1 b/tools/install-wheel-cuda.ps1 new file mode 100644 index 0000000..83fc0ca --- /dev/null +++ b/tools/install-wheel-cuda.ps1 @@ -0,0 +1,21 @@ +# Install the compiler, static runtime and CUDA build rules for MSBuild. +param([Parameter(Mandatory = $true)] [string] $Prefix) +$ErrorActionPreference = "Stop" +$ProgressPreference = "SilentlyContinue" + +$url = "https://developer.download.nvidia.com/compute/cuda/13.5.0/network_installers/cuda_13.5.0_windows_x86_64_network.exe" +$sha256 = "a03530c404b881bb2b34d23de3fd6a74e819ed9d4fd5633f428c30cf85f012e3" +$installer = Join-Path $env:TEMP "cuda_13.5.0_windows_x86_64_network.exe" +Invoke-WebRequest -UseBasicParsing -Uri $url -OutFile $installer +if ((Get-FileHash $installer -Algorithm SHA256).Hash -ne $sha256) { + throw "CUDA installer checksum mismatch." +} +$components = @( + "-s", "nvcc_13.5", "nvvm_13.5", "crt_13.5", "cudart_13.5", "cccl_13.5", + "visual_studio_integration_13.5" +) +$setup = Start-Process -FilePath $installer -ArgumentList $components -Wait -PassThru +if ($setup.ExitCode -ne 0) { throw "CUDA installer exited with code $($setup.ExitCode)." } + +$licenseDir = New-Item -ItemType Directory -Force -Path (Join-Path $Prefix "licenses/cuda") +Copy-Item (Join-Path $env:CUDA_PATH_V13_5 "EULA.txt") $licenseDir diff --git a/tools/install-wheel-cuda.sh b/tools/install-wheel-cuda.sh new file mode 100755 index 0000000..61d8e83 --- /dev/null +++ b/tools/install-wheel-cuda.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env bash +# Install the CUDA compiler and static runtime inside the manylinux image. +set -euo pipefail + +prefix="${1:?usage: $0 PREFIX}" +rhel="rhel$(rpm -E '%{rhel}')" +repo="https://developer.download.nvidia.com/compute/cuda/repos/$rhel/x86_64" +curl -fsSL --retry 3 "$repo/cuda-$rhel.repo" -o /etc/yum.repos.d/cuda.repo +dnf install -y --setopt=install_weak_deps=False cuda-nvcc-13-5 cuda-cudart-devel-13-5 +install -Dm644 /usr/local/cuda-13.5/EULA.txt "$prefix/licenses/cuda/EULA.txt" diff --git a/vcpkg.json b/vcpkg.json index f8ddd73..0c05031 100644 --- a/vcpkg.json +++ b/vcpkg.json @@ -1,12 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", "name": "diffpy-srreal", - "description": "Static Boost.Serialization and GSL for the diffpy.srreal PyPI wheels.", - "dependencies": [ - "boost-container-hash", - "boost-serialization", - "boost-ublas", - "gsl" - ], + "description": "Static Boost.Serialization and GSL, and the xsimd headers, for the diffpy.srreal PyPI wheels.", + "dependencies": ["boost-serialization", "gsl", "xsimd"], "builtin-baseline": "9e593bb18ea69cc5095e012465dcd675a822ed0d" }