Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ Change Log
*Added*

* Introduced Hillinger distance as an order option which obeys triangle inequality.
* Added a ``backend`` argument to ``PGOP`` (``{"scalar", "SIMD"}``, default
``"SIMD"``) selecting the kernel implementation at runtime (#171).

*Fixed*

Expand Down
16 changes: 16 additions & 0 deletions spatula/pgop.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
particle's neighborhood or its local bond orientation order diagram.
"""

import typing

import numpy as np

import spatula._spatula_nb
Expand All @@ -32,6 +34,7 @@ def __init__(
mode: str = "full",
compute_per_operator_values_for_final_orientation: bool = False,
metric: str = "BC",
backend: typing.Literal["scalar", "SIMD"] = "SIMD",
):
r"""Create a PGOP object.

Expand Down Expand Up @@ -84,6 +87,12 @@ def __init__(
disordered/no overlap.
- ``metric="HD"``: 0 means maximally ordered (zero distance), larger values
mean less ordered. Defaults to ``"BC"``.
backend : str, optional
The kernel backend used to evaluate the overlap sums. ``"SIMD"`` uses
ISPC-vectorized kernels with a fast approximate exponential for maximum
throughput, and should be used in most cases.. ``"scalar"`` uses scalar C++
loops evaluated with the standard library ``exp``, and can be used as a
reference implementation. Defaults to ``"SIMD"``.

"""
if isinstance(symmetries, str):
Expand All @@ -94,6 +103,12 @@ def __init__(
msg = f"Metric '{metric}' is not valid (valid params: {{'BC', 'HD'}})"
raise ValueError(msg)
self._metric = metric
if backend not in {"scalar", "SIMD"}:
msg = (
f"Backend '{backend}' is not valid (valid params: {{'scalar', 'SIMD'}})"
)
raise ValueError(msg)
self._backend = backend
# computing the PGOP
self._optimizer = optimizer
matrices = []
Expand All @@ -118,6 +133,7 @@ def __init__(
optimizer._cpp,
m_mode,
compute_per_operator_values_for_final_orientation,
backend,
)
self._order = None
self._rotations = None
Expand Down
14 changes: 8 additions & 6 deletions src/PGOP.cc
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ PGOP::PGOP(const std::vector<const float*> R_ij_data,
std::shared_ptr<optimize::Optimizer>& optimizer,
std::vector<size_t> group_sizes,
unsigned int mode,
bool compute_per_operator)
bool compute_per_operator,
Backend backend)
: m_n_symmetries(n_symmetries), m_Rij(R_ij_data), m_group_sizes(std::move(group_sizes)),
m_optimize(optimizer), m_mode(mode), m_compute_per_operator(compute_per_operator)
m_optimize(optimizer), m_mode(mode), m_compute_per_operator(compute_per_operator),
m_backend(backend)
{
const auto* no_optimization = dynamic_cast<const optimize::NoOptimization*>(m_optimize.get());
if (no_optimization == nullptr) {
Expand Down Expand Up @@ -209,14 +211,14 @@ double PGOP::compute_pgop(LocalNeighborhood& neighborhood, const std::span<const
{
if (m_mode == 0) {
if (neighborhood.constantSigmas()) {
return computes::compute_pgop_gaussian_fast(neighborhood, R_ij);
return computes::compute_pgop_gaussian_fast(neighborhood, R_ij, m_backend);
}
return computes::compute_pgop_gaussian(neighborhood, R_ij);
return computes::compute_pgop_gaussian(neighborhood, R_ij, m_backend);
} else {
if (neighborhood.constantSigmas()) {
return computes::compute_pgop_fisher_fast(neighborhood, R_ij);
return computes::compute_pgop_fisher_fast(neighborhood, R_ij, m_backend);
}
return computes::compute_pgop_fisher(neighborhood, R_ij);
return computes::compute_pgop_fisher(neighborhood, R_ij, m_backend);
}
}

Expand Down
6 changes: 5 additions & 1 deletion src/PGOP.h
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
#include <tuple>
#include <vector>

#include "computes.h"
#include "data/Quaternion.h"
#include "locality.h"
#include "optimize/Optimize.h"
Expand All @@ -29,7 +30,8 @@ class PGOP {
std::shared_ptr<optimize::Optimizer>& optimizer,
const std::vector<size_t> group_sizes,
unsigned int mode,
bool compute_per_operator);
bool compute_per_operator,
Backend backend = Backend::SIMD);

/**
* @brief Root function for computing PGOP for a set of points.
Expand Down Expand Up @@ -103,6 +105,8 @@ class PGOP {
unsigned int m_mode;
/// Whether to compute the PGOP for each operator.
bool m_compute_per_operator;
/// The kernel backend used for PGOP evaluation (scalar loops or ISPC SIMD).
Backend m_backend;
/// Whether operators are pre-rotated once for NoOptimization.
bool m_use_rotated_operators_for_noopt = false;
/// Cached operator matrices rotated into the fixed NoOptimization orientation.
Expand Down
68 changes: 48 additions & 20 deletions src/computes.h
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,31 @@
#include <cmath>
#include <span>

namespace spatula { namespace computes {
float compute_pgop_gaussian(LocalNeighborhood& neighborhood, const std::span<const float> R_ij)
namespace spatula {
/**
* @brief The kernel backend used to evaluate the PGOP overlap sums.
*
* The backend is a runtime choice; SIMD silently falls back to Scalar when
* spatula is built without ISPC support (SPATULA_HAS_ISPC undefined).
*/
enum class Backend {
/// Scalar C++ loops evaluated with std::exp.
Scalar,
/// ISPC vectorized kernels. Uses fast approximations of the exponential for
/// performance. Falls back to Scalar if ISPC is unavailable.
SIMD,
};

namespace computes {
inline float compute_pgop_gaussian(LocalNeighborhood& neighborhood,
const std::span<const float> R_ij,
[[maybe_unused]] Backend backend = Backend::SIMD)
{
#if defined(SPATULA_HAS_ISPC)
return compute_pgop_gaussian_ispc_wrapper(neighborhood, R_ij);
#else
if (backend == Backend::SIMD) {
return compute_pgop_gaussian_ispc_wrapper(neighborhood, R_ij);
}
#endif
const float* pos_x = neighborhood.rotated_pos_x.data();
const float* pos_y = neighborhood.rotated_pos_y.data();
const float* pos_z = neighborhood.rotated_pos_z.data();
Expand Down Expand Up @@ -58,14 +77,17 @@ float compute_pgop_gaussian(LocalNeighborhood& neighborhood, const std::span<con
// cast to double to avoid integer division
const auto normalization = static_cast<float>(n * R_ij.size()) / 9.0;
return overlap / normalization;
#endif
}

float compute_pgop_gaussian_fast(LocalNeighborhood& neighborhood, const std::span<const float> R_ij)
inline float compute_pgop_gaussian_fast(LocalNeighborhood& neighborhood,
const std::span<const float> R_ij,
[[maybe_unused]] Backend backend = Backend::SIMD)
{
#if defined(SPATULA_HAS_ISPC)
return compute_pgop_gaussian_fast_ispc_wrapper(neighborhood, R_ij);
#else
if (backend == Backend::SIMD) {
return compute_pgop_gaussian_fast_ispc_wrapper(neighborhood, R_ij);
}
#endif
const float* pos_x = neighborhood.rotated_pos_x.data();
const float* pos_y = neighborhood.rotated_pos_y.data();
const float* pos_z = neighborhood.rotated_pos_z.data();
Expand Down Expand Up @@ -98,21 +120,24 @@ float compute_pgop_gaussian_fast(LocalNeighborhood& neighborhood, const std::spa
min_dist_sq = std::min(min_dist_sq, dx * dx + dy * dy + dz * dz);
}

// Final calculation using the collapsed minimum
overlap += util::fast_exp_approx(-min_dist_sq * denom);
// Final calculation using the collapsed minimum.
overlap += std::exp(-min_dist_sq * denom);
}
}
// cast to double to avoid integer division
const auto normalization = static_cast<float>(n * R_ij.size()) / 9.0;
return overlap / normalization;
#endif
}

float compute_pgop_fisher(LocalNeighborhood& neighborhood, const std::span<const float> R_ij)
inline float compute_pgop_fisher(LocalNeighborhood& neighborhood,
const std::span<const float> R_ij,
[[maybe_unused]] Backend backend = Backend::SIMD)
{
#if defined(SPATULA_HAS_ISPC)
return compute_pgop_fisher_ispc_wrapper(neighborhood, R_ij);
#else
if (backend == Backend::SIMD) {
return compute_pgop_fisher_ispc_wrapper(neighborhood, R_ij);
}
#endif
const float* pos_x = neighborhood.rotated_pos_x.data();
const float* pos_y = neighborhood.rotated_pos_y.data();
const float* pos_z = neighborhood.rotated_pos_z.data();
Expand Down Expand Up @@ -149,14 +174,17 @@ float compute_pgop_fisher(LocalNeighborhood& neighborhood, const std::span<const
// cast to double to avoid integer division
const float normalization = static_cast<float>(n * R_ij.size()) / 9.0;
return overlap / normalization;
#endif
}

float compute_pgop_fisher_fast(LocalNeighborhood& neighborhood, const std::span<const float> R_ij)
inline float compute_pgop_fisher_fast(LocalNeighborhood& neighborhood,
const std::span<const float> R_ij,
[[maybe_unused]] Backend backend = Backend::SIMD)
{
#if defined(SPATULA_HAS_ISPC)
return compute_pgop_fisher_fast_ispc_wrapper(neighborhood, R_ij);
#else
if (backend == Backend::SIMD) {
return compute_pgop_fisher_fast_ispc_wrapper(neighborhood, R_ij);
}
#endif
const float* pos_x = neighborhood.rotated_pos_x.data();
const float* pos_y = neighborhood.rotated_pos_y.data();
const float* pos_z = neighborhood.rotated_pos_z.data();
Expand Down Expand Up @@ -198,6 +226,6 @@ float compute_pgop_fisher_fast(LocalNeighborhood& neighborhood, const std::span<
const float normalization = static_cast<float>(n * R_ij.size()) / 9.0;

return overlap / normalization;
#endif
}
}} // namespace spatula::computes
} // namespace computes
} // namespace spatula
22 changes: 19 additions & 3 deletions src/nanobind/export-pgop.h
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@
#include <nanobind/stl/list.h>
#include <nanobind/stl/shared_ptr.h>
#include <nanobind/stl/vector.h>
#include <stdexcept>
#include <string>
namespace nb = nanobind;
using namespace nb::literals;

Expand All @@ -25,7 +27,19 @@ void export_spatula(nb::module_& m)
const std::vector<nb::ndarray<float, nb::ndim<1>>>& R_ij_list,
std::shared_ptr<optimize::Optimizer>& optimizer,
unsigned int m_mode,
bool compute_per_operator) {
bool compute_per_operator,
const std::string& backend) {
// Validate the backend selection before doing any work.
Backend cpp_backend;
if (backend == "scalar") {
cpp_backend = Backend::Scalar;
} else if (backend == "SIMD") {
cpp_backend = Backend::SIMD;
} else {
throw std::invalid_argument(
"Backend '" + backend
+ "' is not valid (valid params: {\"scalar\", \"SIMD\"})");
}
// Save a vector of pointers to each group's data
const std::vector<const float*> ptrs = [&]() {
std::vector<const float*> v;
Expand All @@ -49,14 +63,16 @@ void export_spatula(nb::module_& m)
optimizer,
group_sizes,
m_mode,
compute_per_operator);
compute_per_operator,
cpp_backend);
},
// Keep argument 2 (symops) alive as long as arg 1 (self) is alive
nb::keep_alive<1, 2>(),
nb::arg("R_ij"),
nb::arg("optimizer"),
nb::arg("m_mode"),
nb::arg("compute_per_operator"))
nb::arg("compute_per_operator"),
nb::arg("backend") = "SIMD")
.def(
"compute",
[](PGOP* self,
Expand Down
Loading