Clustering
C++20 header-only: DBSCAN, HDBSCAN, k-means.
Loading...
Searching...
No Matches
centroid_shift.h
Go to the documentation of this file.
1#pragma once
2
3#include <cstddef>
4#include <type_traits>
5
10
11namespace clustering::math {
12
27template <class T>
29 const NDArray<T, 2, Layout::Contig> &cNew, NDArray<T, 1> &outShiftSq,
30 Pool pool) {
31 static_assert(std::is_same_v<T, float> || std::is_same_v<T, double>,
32 "centroidShift<T> requires T to be float or double");
33
35 CLUSTERING_ALWAYS_ASSERT(cOld.dim(0) == cNew.dim(0));
36 CLUSTERING_ALWAYS_ASSERT(cOld.dim(1) == cNew.dim(1));
37 CLUSTERING_ALWAYS_ASSERT(outShiftSq.dim(0) == cOld.dim(0));
38
39 const std::size_t k = cOld.dim(0);
40 if (k == 0) {
41 return;
42 }
43
44 auto runRowRange = [&](std::size_t lo, std::size_t hi) noexcept {
45 for (std::size_t c = lo; c < hi; ++c) {
46 outShiftSq(c) = detail::sqEuclideanRow<T, Layout::Contig, Layout::Contig>(cOld, c, cNew, c);
47 }
48 };
49
50 if (pool.shouldParallelize(k, 4, 2)) {
51 pool.parallelForBlocks(std::size_t{0}, k, std::size_t{0},
52 [&](std::size_t lo, std::size_t hi) { runRowRange(lo, hi); });
53 } else {
54 runRowRange(0, k);
55 }
56}
57
58} // namespace clustering::math
#define CLUSTERING_ALWAYS_ASSERT(cond)
Release-active assertion: evaluates cond in every build configuration.
Represents a multidimensional array (NDArray) of a fixed number of dimensions N and element type T.
Definition ndarray.h:136
size_t dim(std::size_t index) const noexcept
Returns the size of a specific dimension of the NDArray.
Definition ndarray.h:462
bool isMutable() const noexcept
Reports whether writes through operator(), Accessor, or flatIndex are allowed.
Definition ndarray.h:489
T sqEuclideanRow(const NDArray< T, 2, LX > &X, std::size_t i, const NDArray< T, 2, LY > &Y, std::size_t j) noexcept
Definition pairwise.h:134
void centroidShift(const NDArray< T, 2, Layout::Contig > &cOld, const NDArray< T, 2, Layout::Contig > &cNew, NDArray< T, 1 > &outShiftSq, Pool pool)
Per-row squared shift between two centroid matrices of identical shape.
Thin compile-time-templated wrapper around the underlying OwnedPool.
Definition thread.h:109
void parallelForBlocks(std::size_t first, std::size_t last, std::size_t numBlocks, Body body)
Run body in parallel over [first, last) partitioned into numBlocks blocks.
Definition thread.h:239
bool shouldParallelize(std::size_t totalWork, std::size_t minChunk, std::size_t minTasksPerWorker=2) const noexcept
Decide whether totalWork warrants parallel dispatch.
Definition thread.h:147