From d7f04ad9501148cdb564abb59e7f214e3b05323d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Thu, 5 Nov 2026 12:09:55 +0100 Subject: [PATCH 1/2] rework of the VarClusterFinder (#432) Updated VarClusterFinder: - Dropped support for a 2 pass CCL now only flood fill - Stack implementation to allow for large clusters - Supports arbitrary masking --- CMakeLists.txt | 1 + RELEASE.md | 49 ++ benchmarks/CMakeLists.txt | 3 +- benchmarks/varclusterfinder_benchmark.cpp | 81 ++ docs/src/VarClusterFinder.rst | 8 +- .../src/python/cluster/pyVarClusterFinder.rst | 103 ++- include/aare/VarClusterFinder.hpp | 721 ++++++++++-------- include/aare/defs.hpp | 12 + python/aare/__init__.py | 3 +- python/src/var_cluster.hpp | 247 ++++-- python/tests/test_VarClusterFinder.py | 333 ++++++++ src/VarClusterFinder.test.cpp | 573 ++++++++++++++ 12 files changed, 1766 insertions(+), 368 deletions(-) create mode 100644 benchmarks/varclusterfinder_benchmark.cpp create mode 100644 python/tests/test_VarClusterFinder.py create mode 100644 src/VarClusterFinder.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 74197f9f..84d65e3c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -515,6 +515,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/RawSubFile.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/task.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/VarClusterFinder.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/RingBufferPool.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/to_string.test.cpp) target_sources(tests PRIVATE ${TestSources}) diff --git a/RELEASE.md b/RELEASE.md index d5a2f81a..74b65aa2 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -4,6 +4,15 @@ ### New Features: +- ``VarClusterFinder`` can exclude pixels with a mask (``set_mask`` and + ``clear_mask`` in C++, the ``mask`` property in Python, ``None`` to + remove it): a masked pixel never seeds a cluster and is never added to + one, clusters grow around it, and it shows as -1 in ``labeled``. +- ``VarClusterFinder`` can grow clusters with a fixed neighbour threshold + below the seed threshold (``set_neighbour_threshold`` in C++, the + ``neighbour_threshold`` property in Python, ``None`` to follow the seed + threshold), as the noise map mode does with its two factors. The seed + ``threshold`` can be changed after construction. - Added the Python ``xy`` type with ``row`` and ``col`` fields, enabling access to ``RawFile.geometry``, ``RawMasterFile.detector_layout``, and ``RawMasterFile.udp_interfaces_per_module``. It unpacks as ``row, col``. @@ -26,14 +35,54 @@ assembled. ``rows()``, ``cols()`` and every returned frame then include the gaps, for the full frame and for each ROI. +### API Changes: + +- ``VarClusterFinder`` keeps only the flood fill. ``find_clusters_X`` is now + ``find_clusters``; the connected component labelling path (the previous + ``find_clusters`` and ``single_pass``) and the Python ``hits`` method, a + duplicate of ``steal_hits``, are removed. The input image is no longer + modified unless erasing is enabled (``set_erase_clusters`` in C++, the + ``erase_clusters`` property in Python, replacing + ``set_empty_surroundingPixels``), which now zeroes both the cluster + pixels and their sub-threshold neighbours. + Hits are stored in an offset layout instead of one 624 byte record per + cluster: ``steal_hits`` returns a ``Hits`` structure (``VarClusterHits`` + in Python) with one 32 byte record per cluster (``size``, ``row``, + ``col``, ``energy``, ``max``, ``offset``) and flat ``rows``, ``cols`` and + ``values`` arrays holding every cluster pixel, so the 50 pixel limit is + gone. Hits are returned in scan order. The threshold factors are + ``set_seed_factor`` and ``set_neighbour_factor`` in C++ and the + ``seed_factor`` and ``neighbour_factor`` properties in Python; they take + floating point values for every pixel type, where the factor and its + product with the noise used to be truncated to the pixel type, and the + seed factor is configurable instead of being fixed to 5. + The noise map setters are ``set_noise_map`` and ``clear_noise_map`` in + C++; in Python the noise map is the ``noise_map`` property, ``None`` to + return to the fixed threshold, and ``labeled`` is a property instead of + a method. ``set_numberOfNeighbours`` is ``set_connectivity`` in C++ and + the ``connectivity`` property in Python. + ### Other: - ``RawFile`` assembles multi-module frames through one placement path with a scratch buffer allocated once at open, instead of allocating a module buffer for every frame. +- ``VarClusterFinder`` is several times faster than the previous flood fill, + on empty frames and on frames with thousands of clusters alike; see + ``benchmarks/varclusterfinder_benchmark.cpp``. ### Bugfixes: +- Fixed ``VarClusterFinder`` crashing with a stack overflow on large + connected areas above threshold, for example a frame with an invalid + pedestal. The fill is now iterative. +- Fixed ``VarClusterFinder.set_noiseMap`` keeping a reference to the + temporary array created when the noise map was not a C-contiguous + float64 array. The map is now copied. +- ``VarClusterFinder`` now rejects images and noise maps whose shape does + not match the finder instead of reading out of bounds, and records the + maximum pixel correctly with a negative threshold. + - Fixed ``Matterhorn10Transform`` with 4 bit dynamic range and ``Mythen302Transform`` failing with ``Expected 1D array, got 2D`` on frames read through ``CtbRawFile``. The transforms now flatten the frame before diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index b81cb4ed..76732411 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -25,7 +25,8 @@ target_sources( reduce_benchmark.cpp clusterfile_benchmark.cpp DataSetAggregation_benchmark.cpp - rawfile_benchmark.cpp) + rawfile_benchmark.cpp + varclusterfinder_benchmark.cpp) # Link Google Benchmark and other necessary libraries target_link_libraries(benchmarks PRIVATE benchmark::benchmark aare_core diff --git a/benchmarks/varclusterfinder_benchmark.cpp b/benchmarks/varclusterfinder_benchmark.cpp new file mode 100644 index 00000000..dac0c765 --- /dev/null +++ b/benchmarks/varclusterfinder_benchmark.cpp @@ -0,0 +1,81 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/NDArray.hpp" +#include "aare/VarClusterFinder.hpp" +#include +#include + +using namespace aare; + +namespace { + +constexpr ssize_t kRows = 512; +constexpr ssize_t kCols = 1024; +constexpr double kNoiseSigma = 1.0; +constexpr double kFixedThreshold = 10.0; + +// Gaussian background with 3x3 photon clusters (100 in the centre, 20 in +// the eight neighbours) at random positions. Positions may overlap, which +// is fine for timing purposes as long as the same seed is used. +NDArray make_frame(int n_clusters, unsigned seed) { + NDArray frame({kRows, kCols}); + std::mt19937 gen(seed); + std::normal_distribution noise(0.0, kNoiseSigma); + for (auto &v : frame) + v = noise(gen); + + std::uniform_int_distribution row(1, kRows - 2); + std::uniform_int_distribution col(1, kCols - 2); + for (int n = 0; n < n_clusters; ++n) { + const auto r = row(gen); + const auto c = col(gen); + for (ssize_t dr = -1; dr <= 1; ++dr) + for (ssize_t dc = -1; dc <= 1; ++dc) + frame(r + dr, c + dc) += (dr == 0 && dc == 0) ? 100.0 : 20.0; + } + return frame; +} + +// The finder may modify the frame in place, so each iteration starts from a +// pristine copy that is restored outside the timed region. +void run(benchmark::State &state, VarClusterFinder &finder) { + const auto pristine = make_frame(static_cast(state.range(0)), 42); + NDArray frame(pristine); + size_t n_hits = 0; + for (auto _ : state) { + state.PauseTiming(); + std::copy(pristine.begin(), pristine.end(), frame.begin()); + state.ResumeTiming(); + finder.find_clusters(frame.view()); + auto hits = finder.steal_hits(); + n_hits = hits.size(); + benchmark::DoNotOptimize(hits.hits.data()); + } + state.counters["hits"] = static_cast(n_hits); + state.counters["pixels/s"] = + benchmark::Counter(static_cast(kRows * kCols), + benchmark::Counter::kIsIterationInvariantRate); +} + +} // namespace + +static void BM_VarClusterFinder_FixedThreshold(benchmark::State &state) { + VarClusterFinder finder({kRows, kCols}, kFixedThreshold); + run(state, finder); +} +BENCHMARK(BM_VarClusterFinder_FixedThreshold) + ->Arg(100) + ->Arg(1000) + ->Arg(10000) + ->Unit(benchmark::kMicrosecond); + +static void BM_VarClusterFinder_NoiseMap(benchmark::State &state) { + VarClusterFinder finder({kRows, kCols}, kFixedThreshold); + NDArray noise({kRows, kCols}, kNoiseSigma); + finder.set_noise_map(noise.view()); + run(state, finder); +} +BENCHMARK(BM_VarClusterFinder_NoiseMap) + ->Arg(100) + ->Arg(1000) + ->Arg(10000) + ->Unit(benchmark::kMicrosecond); diff --git a/docs/src/VarClusterFinder.rst b/docs/src/VarClusterFinder.rst index be2e5cb6..83dfe44d 100644 --- a/docs/src/VarClusterFinder.rst +++ b/docs/src/VarClusterFinder.rst @@ -1,7 +1,13 @@ VarClusterFinder ==================== +Finds clusters of variable size by flood filling connected pixels above a +threshold. The seed and neighbour thresholds are either one fixed value or +per-pixel multiples of a noise map. Each cluster is reported as a ``Hit`` +with its size, summed energy and maximum pixel; the coordinates and values +of every cluster pixel are stored in the flat arrays of ``Hits``. See the +Python page for a description of the algorithm and the output. .. doxygenclass:: aare::VarClusterFinder :members: - :undoc-members: \ No newline at end of file + :undoc-members: diff --git a/docs/src/python/cluster/pyVarClusterFinder.rst b/docs/src/python/cluster/pyVarClusterFinder.rst index c9f4f2e6..2d4ce4c7 100644 --- a/docs/src/python/cluster/pyVarClusterFinder.rst +++ b/docs/src/python/cluster/pyVarClusterFinder.rst @@ -1,10 +1,111 @@ VarClusterFinder =================== +Finds clusters of variable size by flood filling connected pixels above a +threshold. Use it when the cluster shape is not known in advance, for +example for charge spread over more than 3x3 pixels or for tracks. For +fixed size photon clusters ``ClusterFinder`` is the faster choice. + +The image is scanned row by row. A pixel above the seed threshold starts a +cluster, which then grows into every 4 or 8 connected neighbour +(``connectivity``, default 8) above the neighbour threshold. Without a noise map the thresholds are fixed values: +``threshold``, given to the constructor, for seeds and +``neighbour_threshold`` for neighbours, which follows ``threshold`` until +it is set and again after assigning ``None``. With ``noise_map`` set the +thresholds are per pixel: ``seed_factor`` times the noise for seeds and +``neighbour_factor`` times the noise for neighbours, both 5 by default. +Assign ``None`` to ``noise_map`` to return to the fixed thresholds. + +**Usage** + +.. code:: python + + import numpy as np + from aare import VarClusterFinder + + cf = VarClusterFinder((512, 1024), threshold=50.0) + for frame in frames: # float64, pedestal subtracted + cf.find_clusters(frame) + hits = cf.steal_hits() # VarClusterHits + energies = hits.hits["energy"] # one record per cluster + rows, cols, values = hits.pixels(0) # pixels of the first cluster + + # Grow clusters into pixels above a lower threshold than the seeds + cf.neighbour_threshold = 20.0 + + # Thresholds in units of the per pixel noise instead of fixed values + cf.noise_map = noise # same shape as the frames, copied + cf.seed_factor = 5 + cf.neighbour_factor = 2 + + cf.mask = bad_pixels # bool array, True on excluded pixels + +**Hits** + +``steal_hits`` returns all clusters found since the last call as a +``VarClusterHits`` with four NumPy arrays that are views into it: + +- ``hits``: structured array with one record per cluster: ``size``, the + number of pixels (int32); ``row``, ``col``, the position of the maximum + pixel (int16); ``energy``, the sum over all pixels (float64); ``max``, + the value of the maximum pixel (float64); ``offset``, the index of the + cluster's first pixel in the arrays below (int64). +- ``rows``, ``cols`` (int16) and ``values`` (float64): one entry per + cluster pixel. The pixels of ``hits[i]`` are the slice + ``offset:offset + size``, in fill order starting with the seed, and + ``pixels(i)`` returns the three slices. + +Every pixel of every cluster is stored, whatever its size. The layout +suits vectorised per cluster sums, for example +``np.add.reduceat(hits.values, hits.hits["offset"])`` for the energies, +and it maps directly onto ragged array libraries such as Awkward. Hits are +returned in the order in which their seeds were found, row by row, and +accumulate across frames until ``steal_hits`` or ``clear_hits`` is called. + +``labeled`` is the label image of the last frame, returned as a copy: 0 +outside clusters and the 1-based index of the cluster within that frame +otherwise. + +**Mask** + +``mask`` is a boolean array of the image shape, ``True`` on the pixels to +exclude, or ``None``. A masked pixel never seeds a cluster and is never +added to one, so clusters grow around it as they do around the image +border, and it is never modified. Masked pixels are -1 in ``labeled``. +The array is copied on assignment; assign ``None`` to remove the mask. + +Clusters next to a masked pixel or to the image border have lost part of +their charge. The finder keeps them; to find them afterwards, dilate the +mask by one pixel, treat the border as masked and reduce per cluster: + +.. code:: python + + pad = np.pad(mask, 1, constant_values=True) + near = np.zeros_like(mask) + for dr in (0, 1, 2): + for dc in (0, 1, 2): + near |= pad[dr : dr + mask.shape[0], dc : dc + mask.shape[1]] + touches = np.logical_or.reduceat(near[hits.rows, hits.cols], hits.hits["offset"]) + clean = hits.hits[~touches] + +**Input image** + +``find_clusters`` takes a C-contiguous float64 array of the shape given to +the constructor and leaves it untouched. With ``erase_clusters = True`` the +clusters are erased from the frame as the fill visits them: every cluster +pixel is set to zero, and so are the sub-threshold neighbours around it, +because charge that leaked below threshold would otherwise bias a pedestal +updated from the erased frame. A zeroed pixel compares as zero for the rest +of the frame, which only matters for negative thresholds. + .. py:currentmodule:: aare .. autoclass:: VarClusterFinder :members: :undoc-members: :show-inheritance: - :inherited-members: \ No newline at end of file + :inherited-members: + +.. autoclass:: VarClusterHits + :members: + :undoc-members: diff --git a/include/aare/VarClusterFinder.hpp b/include/aare/VarClusterFinder.hpp index b3d583c1..22a3f495 100644 --- a/include/aare/VarClusterFinder.hpp +++ b/include/aare/VarClusterFinder.hpp @@ -1,336 +1,447 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once +#include "aare/NDArray.hpp" +#include "aare/NDView.hpp" +#include "aare/defs.hpp" + #include -#include -#include +#include +#include +#include +#include +#include +#include +#include #include -#include "aare/NDArray.hpp" - -const int MAX_CLUSTER_SIZE = 50; namespace aare { +/** + * @brief Find clusters of variable size by flood filling connected pixels + * above a threshold. + * + * The image is scanned in row-major order. A pixel above the seed threshold + * that does not already belong to a cluster starts a new cluster, which then + * grows into every 4- or 8-connected neighbour above the neighbour threshold. + * Without a noise map the thresholds are fixed values: the threshold given + * to the constructor for seeds and, once set_neighbour_threshold() is used, + * a separate one for neighbours. With a noise map they are per-pixel + * multiples of the noise: the seed factor times the noise for seeds and the + * neighbour factor times the noise for neighbours, both 5 by default. The + * factors are floating point for every pixel type, see Factor. + * + * The clusters are collected in a Hits structure: one Hit per cluster with + * the pixel count, the summed energy and the position and value of the + * maximum pixel, plus flat arrays with the coordinates and values of every + * cluster pixel. The pixels of a hit are a contiguous slice of those arrays + * in fill order, starting with the seed. Hits are appended in the order + * their seeds are encountered and accumulate across frames until + * steal_hits() or clear_hits() is called. + * + * Pixels can be excluded with set_mask(): a masked pixel never seeds a + * cluster and is never added to one, so clusters grow around it as they + * do around the image border. Masked pixels are never modified and show + * up as -1 in labeled(). + * + * The input image is left untouched unless set_erase_clusters(true) is set, + * in which case every cluster pixel, and also every sub-threshold neighbour + * the fill examined around it, is set to zero as it is visited. The ring is + * included so that a pedestal updated from the erased frame sees no charge + * that leaked out of the cluster. A zeroed pixel compares as zero for the + * rest of the frame, which only matters for negative thresholds. + * + * @tparam T Pixel type of the image and the noise map. + */ template class VarClusterFinder { public: + /** + * @brief One cluster found by find_clusters(). Its pixels are the + * entries [offset, offset + size) of the pixel arrays in Hits. + */ struct Hit { - int16_t size{}; - int16_t row{}; - int16_t col{}; - uint16_t reserved{}; // for alignment - T energy{}; - T max{}; - - // std::vector rows{}; - // std::vector cols{}; - int16_t rows[MAX_CLUSTER_SIZE] = {0}; - int16_t cols[MAX_CLUSTER_SIZE] = {0}; - double enes[MAX_CLUSTER_SIZE] = {0}; + int32_t size{}; ///< Number of pixels in the cluster + int16_t row{}; ///< Row of the maximum pixel + int16_t col{}; ///< Column of the maximum pixel + T energy{}; ///< Sum over all pixels in the cluster + T max{}; ///< Value of the maximum pixel + int64_t offset{}; ///< Index of the first pixel in Hits::rows etc. }; + /** + * @brief Clusters found by find_clusters(): one Hit per cluster and + * one entry per cluster pixel in rows, cols and values. + */ + struct Hits { + std::vector hits; ///< One record per cluster + std::vector rows; ///< Row of every cluster pixel + std::vector cols; ///< Column of every cluster pixel + std::vector values; ///< Value of every cluster pixel + + /** @brief Number of clusters. */ + size_t size() const { return hits.size(); } + bool empty() const { return hits.empty(); } + /** @brief Number of cluster pixels over all clusters. */ + size_t n_pixels() const { return rows.size(); } + void clear() { + hits.clear(); + rows.clear(); + cols.clear(); + values.clear(); + } + void reserve(size_t n_hits, size_t n_pixels) { + hits.reserve(n_hits); + rows.reserve(n_pixels); + cols.reserve(n_pixels); + values.reserve(n_pixels); + } + }; + + /** + * @brief Type of the threshold factors and of the thresholds derived + * from the noise map: the pixel type for floating point images, double + * for integer images so that fractional factors are not truncated and + * the product with the noise cannot overflow the pixel type. + */ + using Factor = std::conditional_t, T, double>; + private: - const std::array shape_; - NDView original_; - NDArray labeled_; - NDArray peripheral_labeled_; - NDArray binary_; // over threshold flag + struct FixedThreshold { + T seed_value; + T neighbour_value; + T seed(ssize_t) const { return seed_value; } + T neighbour(ssize_t) const { return neighbour_value; } + }; + + struct NoiseThreshold { + const T *noise; + Factor seed_factor; + Factor neighbour_factor; + Factor seed(ssize_t i) const { return seed_factor * noise[i]; } + Factor neighbour(ssize_t i) const { + return neighbour_factor * noise[i]; + } + }; + + static constexpr size_t initial_hit_capacity = 2000; + static constexpr size_t initial_pixel_capacity = 8 * initial_hit_capacity; + + Shape<2> shape_; T threshold_; - NDView noiseMap; - bool use_noise_map = false; - int peripheralThresholdFactor_ = 5; - int current_label; - const std::array di{ - {0, -1, -1, -1}}; // row ### 8-neighbour by scaning from left to right - const std::array dj{ - {-1, -1, 0, 1}}; // col ### 8-neighbour by scaning from top to bottom - const std::array di_{{0, 0, -1, 1, -1, 1, -1, 1}}; // row - const std::array dj_{{-1, 1, 0, 0, 1, -1, -1, 1}}; // col - std::map child; // heirachy: key: child; val: parent - int numberOfNeighbours = 8; // 4 or 8 - bool empty_surroundingPixels = - true; // whether to set peripheral pixels to 0, to avoid potential - // influence for pedestal updating - std::unordered_map h_size; - std::vector hits; - // std::vector> row - int check_neighbours(int i, int j); + std::optional neighbour_threshold_; // follows threshold_ when unset + std::optional> noise_map_; + // Label image template: -1 on masked pixels, 0 elsewhere + std::optional> masked_labels_; + Factor seed_factor_ = 5; + Factor neighbour_factor_ = 5; + int connectivity_ = 8; + bool erase_clusters_ = false; + NDArray labels_; + Hits hits_; public: + /** + * @brief Construct a finder for images of the given shape. + * @param shape Image shape as (rows, columns); each at most 32767. + * @param threshold Fixed seed threshold, also used for neighbours until + * set_neighbour_threshold() is called; ignored while a noise map is set. + * @throws std::runtime_error if the shape is empty or does not fit the + * 16 bit coordinates of Hit. + */ VarClusterFinder(Shape<2> shape, T threshold) - : shape_(shape), labeled_(shape, 0), peripheral_labeled_(shape, 0), - binary_(shape), threshold_(threshold) { - hits.reserve(2000); - } - - NDArray labeled() { return labeled_; } - - void set_noiseMap(NDView noise_map) { - noiseMap = noise_map; - use_noise_map = true; - } - void set_peripheralThresholdFactor(int factor) { - peripheralThresholdFactor_ = factor; - } - void set_numberOfNeighbours(int num) { - if (num == 4 || num == 8) - numberOfNeighbours = num; - else + : shape_(shape), threshold_(threshold), labels_(shape, 0) { + constexpr ssize_t max_coord = std::numeric_limits::max(); + if (shape[0] < 1 || shape[1] < 1 || shape[0] > max_coord || + shape[1] > max_coord) throw std::runtime_error( - LOCATION + "number of neighbours should be either 4 or 8"); + LOCATION + + fmt::format("image shape ({}, {}) must be between (1, 1) and " + "({}, {})", + shape[0], shape[1], max_coord, max_coord)); + hits_.reserve(initial_hit_capacity, initial_pixel_capacity); } - void set_empty_surroundingPixels(bool empty) { - empty_surroundingPixels = empty; - } - void find_clusters(NDView img); - void find_clusters_X(NDView img); - void rec_FillHit(int clusterIndex, int i, int j); - void single_pass(NDView img); - void first_pass(); - void second_pass(); - void store_clusters(); - std::vector steal_hits() { - std::vector tmp; - std::swap(tmp, hits); + /** + * @brief Return a copy of the label image of the last processed frame. + * + * Pixels outside clusters are 0; cluster pixels hold the 1-based index + * of their cluster within that frame, in the order the hits were added; + * masked pixels are -1. + */ + NDArray labeled() const { return labels_; } + + /** + * @brief Use per-pixel thresholds derived from a noise map instead of + * the fixed threshold. The map is copied. + * @throws std::runtime_error if the shape does not match. + */ + void set_noise_map(NDView noise_map) { + check_shape(noise_map.shape(), "noise map"); + noise_map_.emplace(noise_map); + } + + /** @brief Drop the noise map and use the fixed threshold again. */ + void clear_noise_map() { noise_map_.reset(); } + + /** @brief The noise map, or nothing while the fixed threshold is used. */ + const std::optional> &noise_map() const { return noise_map_; } + + /** + * @brief Exclude the pixels where mask is true: they never seed a + * cluster, are never added to one and are never modified. The mask is + * copied. + * @throws std::runtime_error if the shape does not match. + */ + void set_mask(NDView mask) { + check_shape(mask.shape(), "mask"); + NDArray labels(shape_, 0); + const bool *masked = mask.data(); + int32_t *out = labels.data(); + for (ssize_t i = 0; i < shape_[0] * shape_[1]; ++i) + out[i] = masked[i] ? -1 : 0; + masked_labels_.emplace(std::move(labels)); + } + + /** @brief Remove the mask. */ + void clear_mask() { masked_labels_.reset(); } + + /** @brief The mask as a boolean image, or nothing when no mask is set. */ + std::optional> mask() const { + if (!masked_labels_) + return std::nullopt; + NDArray out(shape_, false); + const int32_t *in = masked_labels_->data(); + bool *masked = out.data(); + for (ssize_t i = 0; i < shape_[0] * shape_[1]; ++i) + masked[i] = in[i] < 0; + return out; + } + + /** @brief Fixed seed threshold, used without a noise map. */ + void set_threshold(T threshold) { threshold_ = threshold; } + /** @brief The fixed seed threshold. */ + T threshold() const { return threshold_; } + + /** + * @brief Fixed neighbour threshold, used without a noise map. Until it + * is set, and again after clear_neighbour_threshold(), neighbours use + * the seed threshold. + */ + void set_neighbour_threshold(T threshold) { + neighbour_threshold_ = threshold; + } + /** @brief Let neighbours use the seed threshold again. */ + void clear_neighbour_threshold() { neighbour_threshold_.reset(); } + /** @brief The neighbour threshold in effect without a noise map. */ + T neighbour_threshold() const { + return neighbour_threshold_.value_or(threshold_); + } + + /** + * @brief Seed threshold in units of the noise map (default 5), floating + * point for every pixel type. + */ + void set_seed_factor(Factor factor) { seed_factor_ = factor; } + /** @brief The seed threshold factor. */ + Factor seed_factor() const { return seed_factor_; } + + /** + * @brief Neighbour threshold in units of the noise map (default 5), + * floating point for every pixel type. + */ + void set_neighbour_factor(Factor factor) { neighbour_factor_ = factor; } + /** @brief The neighbour threshold factor. */ + Factor neighbour_factor() const { return neighbour_factor_; } + + /** + * @brief Grow clusters through 4 or 8 connected neighbours (default 8). + * @throws std::runtime_error for any other value. + */ + void set_connectivity(int connectivity) { + if (connectivity != 4 && connectivity != 8) + throw std::runtime_error(LOCATION + + "connectivity should be either 4 or 8"); + connectivity_ = connectivity; + } + /** @brief The connectivity, 4 or 8. */ + int connectivity() const { return connectivity_; } + + /** + * @brief Erase the clusters from the input image while processing a + * frame (default off): every cluster pixel and the sub-threshold + * neighbours around it are set to zero, so that a pedestal updated from + * the frame afterwards is not biased by the clusters. + */ + void set_erase_clusters(bool erase) { erase_clusters_ = erase; } + /** @brief Whether clusters are erased from the input image. */ + bool erase_clusters() const { return erase_clusters_; } + + /** + * @brief Find the clusters in one frame and append them to the hits. + * @param img Image of the shape given to the constructor. + * @throws std::runtime_error if the shape does not match. + */ + void find_clusters(NDView img) { + check_shape(img.shape(), "image"); + if (noise_map_) + find_clusters_impl(img, + NoiseThreshold{noise_map_->data(), seed_factor_, + neighbour_factor_}); + else + find_clusters_impl( + img, FixedThreshold{threshold_, neighbour_threshold()}); + } + + /** @brief Move out all accumulated hits and reset the finder. */ + Hits steal_hits() { + Hits tmp; + std::swap(tmp, hits_); + hits_.reserve(initial_hit_capacity, initial_pixel_capacity); return tmp; - }; - void clear_hits() { hits.clear(); }; + } - void print_connections() { - fmt::print("Connections:\n"); - for (auto it = child.begin(); it != child.end(); ++it) { - fmt::print("{} -> {}\n", it->first, it->second); - } - } - size_t total_clusters() const { - // TODO! fix for stealing - return hits.size(); - } + /** @brief Discard all accumulated hits. */ + void clear_hits() { hits_.clear(); } + + /** @brief Number of hits currently held by the finder. */ + size_t total_clusters() const { return hits_.size(); } private: - void add_link(int from, int to) { - // we want to add key from -> value to - // fmt::print("add_link({},{})\n", from, to); - auto it = child.find(from); - if (it == child.end()) { - child[from] = to; - } else { - // found need to disambiguate - if (it->second == to) - return; - else { - if (it->second > to) { - // child[from] = to; - auto old = it->second; - it->second = to; - add_link(old, to); - } else { - // found value is smaller than what we want to link - add_link(to, it->second); - } + void check_shape(const Shape<2> &shape, const char *what) const { + if (shape != shape_) + throw std::runtime_error( + LOCATION + + fmt::format("{} shape ({}, {}) does not match the finder " + "shape ({}, {})", + what, shape[0], shape[1], shape_[0], shape_[1])); + } + + template + void find_clusters_impl(NDView img, const Threshold &thr) { + const ssize_t n_pixels = shape_[0] * shape_[1]; + const ssize_t n_cols = shape_[1]; + T *const pixels = img.data(); + int32_t *const labels = labels_.data(); + if (masked_labels_) + std::copy_n(masked_labels_->data(), n_pixels, labels); + else + std::fill_n(labels, n_pixels, 0); + + int32_t label = 0; + auto seed_range = [&](ssize_t begin, ssize_t end) { + for (ssize_t idx = begin; idx < end; ++idx) { + if (!(pixels[idx] > thr.seed(idx)) || labels[idx] != 0) + continue; + ++label; + fill(pixels, labels, thr, label, + static_cast(idx / n_cols), + static_cast(idx % n_cols)); + } + }; + + // Most pixels are below threshold. A vectorisable check per block + // skips them without entering the per-pixel loop. The flag is an int + // rather than a bool because gcc does not vectorise a bool + // OR-reduction. + constexpr ssize_t block = 32; + ssize_t start = 0; + for (; start + block <= n_pixels; start += block) { + int any = 0; + for (ssize_t k = 0; k < block; ++k) + any |= pixels[start + k] > thr.seed(start + k); + if (any) + seed_range(start, start + block); + } + seed_range(start, n_pixels); + } + + // Out of line so that the register pressure of the fill does not spill + // the counters of the scan loop above. + template + NEVER_INLINE void fill(T *pixels, int32_t *labels, const Threshold &thr, + int32_t label, int32_t seed_row, int32_t seed_col) { + const int32_t n_rows = static_cast(shape_[0]); + const int32_t n_cols = static_cast(shape_[1]); + const bool diagonals = connectivity_ == 8; + + Hit &hit = hits_.hits.emplace_back(); + hit.offset = static_cast(hits_.rows.size()); + accept(pixels, labels, label, hit, + static_cast(seed_row) * n_cols + seed_col, seed_row, + seed_col); + + // The pixel arrays double as the work queue: every accepted pixel + // is appended to them, and its neighbours are visited once the + // queue reaches it. + for (size_t q = static_cast(hit.offset); q < hits_.rows.size(); + ++q) { + const int32_t row = hits_.rows[q]; + const int32_t col = hits_.cols[q]; + const ssize_t idx = static_cast(row) * n_cols + col; + const bool up = row > 0; + const bool down = row < n_rows - 1; + const bool left = col > 0; + const bool right = col < n_cols - 1; + if (left) + visit(pixels, labels, thr, label, hit, idx - 1, row, col - 1); + if (right) + visit(pixels, labels, thr, label, hit, idx + 1, row, col + 1); + if (up) + visit(pixels, labels, thr, label, hit, idx - n_cols, row - 1, + col); + if (down) + visit(pixels, labels, thr, label, hit, idx + n_cols, row + 1, + col); + if (diagonals) { + if (up && right) + visit(pixels, labels, thr, label, hit, idx - n_cols + 1, + row - 1, col + 1); + if (down && left) + visit(pixels, labels, thr, label, hit, idx + n_cols - 1, + row + 1, col - 1); + if (up && left) + visit(pixels, labels, thr, label, hit, idx - n_cols - 1, + row - 1, col - 1); + if (down && right) + visit(pixels, labels, thr, label, hit, idx + n_cols + 1, + row + 1, col + 1); } } } + + // Forced inline: gcc otherwise calls these out of line from the eight + // neighbour sites in fill. + template + ALWAYS_INLINE void visit(T *pixels, int32_t *labels, const Threshold &thr, + int32_t label, Hit &hit, ssize_t idx, int32_t r, + int32_t c) { + if (labels[idx] != 0) + return; + if (pixels[idx] > thr.neighbour(idx)) + accept(pixels, labels, label, hit, idx, r, c); + else if (erase_clusters_) + pixels[idx] = T{}; + } + + // Add a pixel to the cluster: label it, append it to the pixel arrays + // and update the hit record. + ALWAYS_INLINE void accept(T *pixels, int32_t *labels, int32_t label, + Hit &hit, ssize_t idx, int32_t row, int32_t col) { + const T value = pixels[idx]; + labels[idx] = label; + hits_.rows.push_back(static_cast(row)); + hits_.cols.push_back(static_cast(col)); + hits_.values.push_back(value); + if (hit.size == 0 || value > hit.max) { + hit.max = value; + hit.row = static_cast(row); + hit.col = static_cast(col); + } + ++hit.size; + hit.energy += value; + if (erase_clusters_) + pixels[idx] = T{}; + } }; -template int VarClusterFinder::check_neighbours(int i, int j) { - std::vector neighbour_labels; - - for (int k = 0; k < 4; ++k) { - const auto row = i + di[k]; - const auto col = j + dj[k]; - if (row >= 0 && col >= 0 && row < shape_[0] && col < shape_[1]) { - auto tmp = labeled_(i + di[k], j + dj[k]); - if (tmp != 0) - neighbour_labels.push_back(tmp); - } - } - - if (neighbour_labels.size() == 0) { - return 0; - } else { - - // need to sort and add to union field - std::sort(neighbour_labels.rbegin(), neighbour_labels.rend()); - auto first = neighbour_labels.begin(); - auto last = std::unique(first, neighbour_labels.end()); - if (last - first == 1) - return *neighbour_labels.begin(); - - for (auto current = first; current != last - 1; ++current) { - auto next = current + 1; - add_link(*current, *next); - } - return neighbour_labels.back(); // already sorted - } -} - -template -void VarClusterFinder::find_clusters(NDView img) { - original_ = img; - labeled_ = 0; - peripheral_labeled_ = 0; - current_label = 0; - child.clear(); - first_pass(); - // print_connections(); - second_pass(); - store_clusters(); -} - -template -void VarClusterFinder::find_clusters_X(NDView img) { - original_ = img; - int clusterIndex = 0; - for (int i = 0; i < shape_[0]; ++i) { - for (int j = 0; j < shape_[1]; ++j) { - if (use_noise_map) - threshold_ = 5 * noiseMap(i, j); - if (original_(i, j) > threshold_) { - // printf("========== Cluster index: %d\n", clusterIndex); - rec_FillHit(clusterIndex, i, j); - clusterIndex++; - } - } - } - for (const auto &h : h_size) - hits.push_back(h.second); - h_size.clear(); -} - -template -void VarClusterFinder::rec_FillHit(int clusterIndex, int i, int j) { - // printf("original_(%d, %d)=%f\n", i, j, original_(i,j)); - // printf("h_size[%d].size=%d\n", clusterIndex, h_size[clusterIndex].size); - if (h_size[clusterIndex].size < MAX_CLUSTER_SIZE) { - h_size[clusterIndex].rows[h_size[clusterIndex].size] = i; - h_size[clusterIndex].cols[h_size[clusterIndex].size] = j; - h_size[clusterIndex].enes[h_size[clusterIndex].size] = original_(i, j); - } - h_size[clusterIndex].size += 1; - h_size[clusterIndex].energy += original_(i, j); - if (h_size[clusterIndex].max < original_(i, j)) { - h_size[clusterIndex].row = i; - h_size[clusterIndex].col = j; - h_size[clusterIndex].max = original_(i, j); - } - original_(i, j) = 0; - - for (int k = 0; k < numberOfNeighbours; ++k) { // - const auto row = i + di_[k]; - const auto col = j + dj_[k]; - if (row >= 0 && col >= 0 && row < shape_[0] && col < shape_[1]) { - if (use_noise_map) - threshold_ = peripheralThresholdFactor_ * noiseMap(row, col); - if (original_(row, col) > threshold_) { - rec_FillHit(clusterIndex, row, col); - } else { - // if (h_size[clusterIndex].size < MAX_CLUSTER_SIZE){ - // h_size[clusterIndex].size += 1; - // h_size[clusterIndex].rows[h_size[clusterIndex].size] = - // row; h_size[clusterIndex].cols[h_size[clusterIndex].size] - // = col; - // h_size[clusterIndex].enes[h_size[clusterIndex].size] = - // original_(row, col); - // }// ? weather to include peripheral pixels - if (empty_surroundingPixels) { - original_(row, col) = - 0; // remove peripheral pixels, to avoid potential - // influence for pedestal updating - } - } - } - } -} - -template void VarClusterFinder::single_pass(NDView img) { - original_ = img; - labeled_ = 0; - current_label = 0; - child.clear(); - first_pass(); - // print_connections(); - // second_pass(); - // store_clusters(); -} - -template void VarClusterFinder::first_pass() { - - for (ssize_t i = 0; i < original_.size(); ++i) { - if (use_noise_map) - threshold_ = 5 * noiseMap[i]; - binary_[i] = (original_[i] > threshold_); - } - - for (int i = 0; i < shape_[0]; ++i) { - for (int j = 0; j < shape_[1]; ++j) { - - // do we have something to process? - if (binary_(i, j)) { - auto tmp = check_neighbours(i, j); - if (tmp != 0) { - labeled_(i, j) = tmp; - } else { - labeled_(i, j) = ++current_label; - } - } - } - } -} - -template void VarClusterFinder::second_pass() { - - for (ssize_t i = 0; i != labeled_.size(); ++i) { - auto cl = labeled_(i); - if (cl != 0) { - auto it = child.find(cl); - while (it != child.end()) { - cl = it->second; - it = child.find(cl); - // do this once before doing the second pass? - // all values point to the final one... - } - labeled_(i) = cl; - } - } -} - -template void VarClusterFinder::store_clusters() { - - // Accumulate hit information in a map - // Do we always have monotonic increasing - // labels? Then vector? - // here the translation is label -> Hit - std::unordered_map h_map; - for (int i = 0; i < shape_[0]; ++i) { - for (int j = 0; j < shape_[1]; ++j) { - if (labeled_(i, j) != 0 || false - // (i-1 >= 0 and labeled_(i-1, j) != 0) or // another circle of - // peripheral pixels (j-1 >= 0 and labeled_(i, j-1) != 0) or - // (i+1 < shape_[0] and labeled_(i+1, j) != 0) or - // (j+1 < shape_[1] and labeled_(i, j+1) != 0) - ) { - Hit &record = h_map[labeled_(i, j)]; - if (record.size < MAX_CLUSTER_SIZE) { - record.rows[record.size] = i; - record.cols[record.size] = j; - record.enes[record.size] = original_(i, j); - } else { - continue; - } - record.size += 1; - record.energy += original_(i, j); - - if (record.max < original_(i, j)) { - record.row = i; - record.col = j; - record.max = original_(i, j); - } - } - } - } - - for (const auto &h : h_map) - hits.push_back(h.second); -} } // namespace aare diff --git a/include/aare/defs.hpp b/include/aare/defs.hpp index 9c94e5f6..ed19ecb0 100644 --- a/include/aare/defs.hpp +++ b/include/aare/defs.hpp @@ -57,6 +57,18 @@ #define ALWAYS_INLINE STRONG_INLINE #endif +/** + * NEVER_INLINE keeps a rarely taken, register-hungry function out of the + * hot loop that calls it, so that the loop itself stays tight. + */ +#if defined(__GNUC__) +#define NEVER_INLINE __attribute__((noinline)) +#elif defined(_MSC_VER) +#define NEVER_INLINE __declspec(noinline) +#else +#define NEVER_INLINE +#endif + namespace aare { /** diff --git a/python/aare/__init__.py b/python/aare/__init__.py index f1c27352..e6f2f44b 100644 --- a/python/aare/__init__.py +++ b/python/aare/__init__.py @@ -14,6 +14,7 @@ from ._aare import ( Pedestal_i16, ClusterFinder_Cluster3x3i, VarClusterFinder, + VarClusterHits, ) from ._aare import ( File, @@ -21,7 +22,6 @@ from ._aare import ( RawMasterFile, RawSubFile, ) -from ._aare import Pedestal_d, Pedestal_f, ClusterFinder_Cluster3x3i, VarClusterFinder from ._aare import DetectorType, FrameDiscardPolicy, ReadoutMode from ._aare import hitmap from ._aare import ROI @@ -62,7 +62,6 @@ from .calibration import * from ._aare import apply_calibration, count_switching_pixels from ._aare import calculate_pedestal, calculate_pedestal_float, calculate_pedestal_g0, calculate_pedestal_g0_float -from ._aare import VarClusterFinder from ._aare import ( PedestalTrackingPixelHistogram, PixelHistogram, diff --git a/python/src/var_cluster.hpp b/python/src/var_cluster.hpp index 9734f406..9aade712 100644 --- a/python/src/var_cluster.hpp +++ b/python/src/var_cluster.hpp @@ -7,70 +7,201 @@ #include #include #include +#include namespace py = pybind11; using namespace ::aare; -void define_var_cluster_finder_bindings(py::module &m) { - PYBIND11_NUMPY_DTYPE(VarClusterFinder::Hit, size, row, col, - reserved, energy, max, rows, cols, enes); +namespace { - py::class_>(m, "VarClusterFinder") - .def(py::init, double>()) - .def("labeled", - [](VarClusterFinder &self) { - auto *ptr = new NDArray(self.labeled()); - return return_image_data(ptr); - }) - .def( - "set_noiseMap", // conversions ok - [](VarClusterFinder &self, - py::array_t - noise_map) { - auto noise_map_span = make_view_2d(noise_map); - self.set_noiseMap(noise_map_span); +// A numpy view of [first, first + count) of a vector owned by the Python +// object `owner`, which the view keeps alive. No data is copied. +template +py::array_t view_vector(std::vector &vec, py::handle owner, + size_t first = 0, size_t count = SIZE_MAX) { + if (count == SIZE_MAX) + count = vec.size() - first; + return py::array_t({static_cast(count)}, + {static_cast(sizeof(T))}, vec.data() + first, + owner); +} + +} // namespace + +void define_var_cluster_finder_bindings(py::module &m) { + using Finder = VarClusterFinder; + using Hits = Finder::Hits; + PYBIND11_NUMPY_DTYPE(Finder::Hit, size, row, col, energy, max, offset); + + py::class_(m, "VarClusterHits", + R"(Clusters returned by VarClusterFinder.steal_hits(). + +``hits`` is a structured array with one record per cluster: ``size``, +``row`` and ``col`` of the maximum pixel, ``energy``, ``max`` and +``offset``. ``rows``, ``cols`` and ``values`` hold one entry per cluster +pixel; the pixels of ``hits[i]`` are the slice ``offset:offset + size`` of +those arrays, in fill order starting with the seed. All arrays are views +into this object and stay valid as long as any of them is referenced.)") + .def("__len__", &Hits::size, "Number of clusters.") + .def_property_readonly( + "hits", + [](py::object self) { + return view_vector(self.cast().hits, self); }, - py::arg("noise_map")) - .def("set_numberOfNeighbours", - &VarClusterFinder::set_numberOfNeighbours) - .def("set_empty_surroundingPixels", - &VarClusterFinder::set_empty_surroundingPixels) - .def("set_peripheralThresholdFactor", - &VarClusterFinder::set_peripheralThresholdFactor) + "Structured array with one record per cluster.") + .def_property_readonly( + "rows", + [](py::object self) { + return view_vector(self.cast().rows, self); + }, + "Row of every cluster pixel (int16).") + .def_property_readonly( + "cols", + [](py::object self) { + return view_vector(self.cast().cols, self); + }, + "Column of every cluster pixel (int16).") + .def_property_readonly( + "values", + [](py::object self) { + return view_vector(self.cast().values, self); + }, + "Value of every cluster pixel (float64).") + .def( + "pixels", + [](py::object self, ssize_t i) { + auto &h = self.cast(); + const ssize_t n = static_cast(h.size()); + if (i < 0) + i += n; + if (i < 0 || i >= n) + throw py::index_error(fmt::format( + "hit index {} out of range for {} hits", i, n)); + const auto &hit = h.hits[static_cast(i)]; + const auto first = static_cast(hit.offset); + const auto count = static_cast(hit.size); + return py::make_tuple( + view_vector(h.rows, self, first, count), + view_vector(h.cols, self, first, count), + view_vector(h.values, self, first, count)); + }, + py::arg("i"), + "Rows, columns and values of the pixels of cluster i, as views."); + + py::class_(m, "VarClusterFinder", + R"(Find clusters of variable size by flood filling +connected pixels above a threshold. + +A pixel above the seed threshold starts a cluster that grows into every +4 or 8 connected neighbour above the neighbour threshold. Without a noise +map the thresholds are the fixed ``threshold`` for seeds and +``neighbour_threshold`` for neighbours. With ``noise_map`` set they are +per pixel multiples of the noise, ``seed_factor`` and ``neighbour_factor``.)") + .def(py::init, double>(), py::arg("shape"), + py::arg("threshold")) + .def_property_readonly( + "labeled", + [](const Finder &self) { + auto *ptr = new NDArray(self.labeled()); + return return_image_data(ptr); + }, + "Label image of the last frame, as a copy: 0 outside clusters, " + "the 1-based index of the cluster within that frame on cluster " + "pixels and -1 on masked pixels.") + .def_property( + "noise_map", + [](const Finder &self) -> py::object { + const auto &map = self.noise_map(); + if (!map) + return py::none(); + return return_image_data(new NDArray(*map)); + }, + [](Finder &self, py::object value) { + if (value.is_none()) { + self.clear_noise_map(); + return; + } + auto map = py::array_t::ensure(value); + if (!map) + throw py::type_error("noise_map must be an array of the " + "image shape or None"); + self.set_noise_map(make_const_view_2d(map)); + }, + "Per pixel noise of the image shape, or None. When set, the seed " + "and neighbour thresholds are the threshold factors times the " + "noise instead of the fixed threshold. The array is copied on " + "assignment; assign None to return to the fixed threshold.") + .def_property( + "mask", + [](const Finder &self) -> py::object { + auto mask = self.mask(); + if (!mask) + return py::none(); + return return_image_data( + new NDArray(std::move(*mask))); + }, + [](Finder &self, py::object value) { + if (value.is_none()) { + self.clear_mask(); + return; + } + auto mask = + py::array_t::ensure(value); + if (!mask) + throw py::type_error( + "mask must be an array of the image shape or None"); + self.set_mask(make_const_view_2d(mask)); + }, + "Boolean array of the image shape, True on the pixels to " + "exclude, or None. A masked pixel never seeds a cluster, is never " + "added to one and is never modified; it is -1 in labeled. The " + "array is copied on assignment; assign None to remove the mask.") + .def_property("threshold", &Finder::threshold, &Finder::set_threshold, + "Fixed seed threshold, used without a noise map.") + .def_property( + "neighbour_threshold", + [](const Finder &self) { return self.neighbour_threshold(); }, + [](Finder &self, std::optional value) { + if (value) + self.set_neighbour_threshold(*value); + else + self.clear_neighbour_threshold(); + }, + "Fixed neighbour threshold, used without a noise map. Reads as " + "the value in effect; assign None to follow the seed threshold " + "again (the default).") + .def_property("seed_factor", &Finder::seed_factor, + &Finder::set_seed_factor, + "Seed threshold in units of the noise map (default 5).") + .def_property( + "neighbour_factor", &Finder::neighbour_factor, + &Finder::set_neighbour_factor, + "Neighbour threshold in units of the noise map (default 5).") + .def_property( + "connectivity", &Finder::connectivity, &Finder::set_connectivity, + "Grow clusters through 4 or 8 connected neighbours (default 8).") + .def_property( + "erase_clusters", &Finder::erase_clusters, + &Finder::set_erase_clusters, + "Erase the clusters from the input image while processing a " + "frame (default False): every cluster pixel and the sub-threshold " + "neighbours around it are set to zero, so that a pedestal updated " + "from the frame afterwards is not biased by the clusters.") .def( "find_clusters", - [](VarClusterFinder &self, py::array_t img) { - auto view = make_view_2d(img); - self.find_clusters(view); + [](Finder &self, py::array_t img) { + self.find_clusters(make_view_2d(img)); }, - py::arg("img").noconvert()) - .def( - "find_clusters_X", - [](VarClusterFinder &self, py::array_t img) { - auto img_span = make_view_2d(img); - self.find_clusters_X(img_span); - }, - py::arg("img").noconvert()) - .def( - "single_pass", - [](VarClusterFinder &self, py::array_t img) { - auto img_span = make_view_2d(img); - self.single_pass(img_span); - }, - py::arg("img").noconvert()) - .def("hits", - [](VarClusterFinder &self) { - auto ptr = new std::vector::Hit>( - self.steal_hits()); - return return_vector(ptr); - }) - .def("clear_hits", - [](VarClusterFinder &self) { self.clear_hits(); }) - .def("steal_hits", - [](VarClusterFinder &self) { - auto ptr = new std::vector::Hit>( - self.steal_hits()); - return return_vector(ptr); - }) - .def("total_clusters", &VarClusterFinder::total_clusters); -} \ No newline at end of file + py::arg("img").noconvert(), + "Find the clusters in one float64 frame and append them to the " + "hits.") + .def("clear_hits", &Finder::clear_hits, "Discard all accumulated hits.") + .def("steal_hits", &Finder::steal_hits, + "Return all accumulated hits as a VarClusterHits and reset the " + "finder.") + .def("total_clusters", &Finder::total_clusters, + "Number of hits currently held by the finder."); +} diff --git a/python/tests/test_VarClusterFinder.py b/python/tests/test_VarClusterFinder.py new file mode 100644 index 00000000..fd475f37 --- /dev/null +++ b/python/tests/test_VarClusterFinder.py @@ -0,0 +1,333 @@ +# SPDX-License-Identifier: MPL-2.0 +import gc + +import numpy as np +import pytest + +from aare import VarClusterFinder, VarClusterHits + + +def frame_with_cluster(shape=(8, 8), row=3, col=4): + img = np.zeros(shape, dtype=np.float64) + img[row - 1 : row + 2, col - 1 : col + 2] = 20.0 + img[row, col] = 100.0 + return img + + +def test_single_cluster_fixed_threshold(): + img = frame_with_cluster() + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(img) + hits = cf.steal_hits() + + assert isinstance(hits, VarClusterHits) + assert len(hits) == 1 + hit = hits.hits[0] + assert hit["size"] == 9 + assert hit["offset"] == 0 + assert hit["row"] == 3 + assert hit["col"] == 4 + assert hit["max"] == 100.0 + assert hit["energy"] == pytest.approx(260.0) + + assert hits.rows.shape == (9,) + assert hits.cols.shape == (9,) + assert hits.values.shape == (9,) + stored = {(int(r), int(c)) for r, c in zip(hits.rows, hits.cols)} + assert stored == {(r, c) for r in range(2, 5) for c in range(3, 6)} + assert hits.values.sum() == pytest.approx(260.0) + # The seed comes first + assert (hits.rows[0], hits.cols[0]) == (2, 3) + + +def test_hit_dtype_and_array_types(): + cf = VarClusterFinder((8, 8), 10.0) + hits = cf.steal_hits() + assert hits.hits.dtype.names == ("size", "row", "col", "energy", "max", "offset") + assert hits.hits.dtype["size"] == np.int32 + assert hits.hits.dtype["row"] == np.int16 + assert hits.hits.dtype["energy"] == np.float64 + assert hits.hits.dtype["offset"] == np.int64 + assert hits.hits.dtype.itemsize == 32 + assert hits.rows.dtype == np.int16 + assert hits.cols.dtype == np.int16 + assert hits.values.dtype == np.float64 + + +def test_pixels_of_each_hit(): + img = frame_with_cluster() + img[7, 0] = 50.0 + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(img) + hits = cf.steal_hits() + + assert len(hits) == 2 + assert hits.hits["offset"].tolist() == [0, 9] + rows, cols, values = hits.pixels(0) + assert rows.shape == (9,) + assert values.sum() == pytest.approx(260.0) + rows, cols, values = hits.pixels(1) + assert (rows.tolist(), cols.tolist(), values.tolist()) == ([7], [0], [50.0]) + rows, cols, values = hits.pixels(-1) + assert rows.tolist() == [7] + with pytest.raises(IndexError): + hits.pixels(2) + with pytest.raises(IndexError): + hits.pixels(-3) + + # Vectorised per hit sums through the offsets + energies = np.add.reduceat(hits.values, hits.hits["offset"]) + assert energies == pytest.approx(hits.hits["energy"]) + + +def test_arrays_keep_the_hits_alive(): + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(frame_with_cluster()) + hits = cf.steal_hits() + values = hits.values + records = hits.hits + del hits + gc.collect() + _ = np.ones(10000) # reuse freed memory, if any + assert values.sum() == pytest.approx(260.0) + assert records[0]["size"] == 9 + + +def test_steal_hits_empties_the_finder(): + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(frame_with_cluster()) + assert cf.total_clusters() == 1 + assert len(cf.steal_hits()) == 1 + assert cf.total_clusters() == 0 + empty = cf.steal_hits() + assert len(empty) == 0 + assert empty.rows.shape == (0,) + + +def test_hits_accumulate_across_frames(): + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(frame_with_cluster()) + cf.find_clusters(frame_with_cluster()) + hits = cf.steal_hits() + assert len(hits) == 2 + assert hits.hits["offset"].tolist() == [0, 9] + assert hits.values.shape == (18,) + + +def test_input_is_not_modified_by_default(): + img = frame_with_cluster() + original = img.copy() + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(img) + assert np.array_equal(img, original) + + +def test_erase_clusters_zeroes_cluster_and_ring(): + img = frame_with_cluster() + 1.0 + cf = VarClusterFinder((8, 8), 10.0) + assert cf.erase_clusters is False + cf.erase_clusters = True + assert cf.erase_clusters is True + cf.find_clusters(img) + expected = np.ones((8, 8)) + expected[1:6, 2:7] = 0.0 + assert np.array_equal(img, expected) + + +def test_labeled_image(): + img = frame_with_cluster() + img[7, 0] = 50.0 + cf = VarClusterFinder((8, 8), 10.0) + cf.find_clusters(img) + labels = cf.labeled + assert labels.dtype == np.int32 + assert labels.shape == (8, 8) + assert labels[3, 4] == 1 + assert labels[2, 3] == 1 + assert labels[7, 0] == 2 + assert labels[0, 0] == 0 + + +def test_noise_map_from_float32_and_non_contiguous_arrays(): + # Regression test: the finder used to keep a view into the temporary + # array created by the conversion. + img = frame_with_cluster() + img[4, 5] = 3.0 # neighbour between 2 and 5 sigma + cf = VarClusterFinder((8, 8), 1000.0) + noise = np.ones((8, 16), dtype=np.float32)[:, ::2] + assert not noise.flags.c_contiguous + cf.noise_map = noise + del noise + gc.collect() + _ = np.ones((8, 8), dtype=np.float64) * 1e6 # reuse freed memory, if any + + cf.neighbour_factor = 2 + cf.find_clusters(img) + hits = cf.steal_hits() + assert len(hits) == 1 + assert hits.hits[0]["size"] == 9 + + +def test_noise_map_property_round_trip(): + img = frame_with_cluster() + cf = VarClusterFinder((8, 8), 1000.0) + assert cf.noise_map is None + cf.noise_map = np.ones((8, 8), dtype=np.float32) # cast and copied + assert cf.noise_map.dtype == np.float64 + assert np.array_equal(cf.noise_map, np.ones((8, 8))) + cf.find_clusters(img) + assert len(cf.steal_hits()) == 1 + cf.noise_map = None + assert cf.noise_map is None + cf.find_clusters(img) # fixed threshold 1000: nothing + assert len(cf.steal_hits()) == 0 + with pytest.raises(ValueError): + cf.noise_map = [1.0, 2.0] # not a 2D array + + +def test_seed_threshold_factor(): + img = np.zeros((8, 8)) + img[1, 1] = 4.0 + cf = VarClusterFinder((8, 8), 1000.0) + cf.noise_map = np.ones((8, 8)) + cf.find_clusters(img) + assert len(cf.steal_hits()) == 0 + cf.seed_factor = 3.5 + cf.find_clusters(img) + assert len(cf.steal_hits()) == 1 + + +def test_shape_mismatch_raises(): + cf = VarClusterFinder((8, 8), 10.0) + with pytest.raises(RuntimeError): + cf.find_clusters(np.zeros((8, 9))) + with pytest.raises(RuntimeError): + cf.noise_map = np.ones((9, 8)) + + +def test_only_float64_frames_are_accepted(): + cf = VarClusterFinder((8, 8), 10.0) + with pytest.raises(TypeError): + cf.find_clusters(frame_with_cluster().astype(np.float32)) + with pytest.raises(ValueError): + cf.find_clusters(np.zeros((8, 16))[:, ::2]) + + +def test_large_blob_stores_every_pixel(): + img = np.full((512, 1024), 100.0) + cf = VarClusterFinder((512, 1024), 10.0) + cf.find_clusters(img) + hits = cf.steal_hits() + assert len(hits) == 1 + assert hits.hits[0]["size"] == 512 * 1024 + assert hits.values.shape == (512 * 1024,) + assert hits.values.sum() == pytest.approx(100.0 * 512 * 1024) + + +def test_mask_excludes_pixels_from_seeding_and_growing(): + img = frame_with_cluster() + img[7, 0] = 50.0 + mask = np.zeros((8, 8), dtype=bool) + mask[3, 4] = True + mask[7, 0] = True + cf = VarClusterFinder((8, 8), 10.0) + cf.mask = mask + cf.find_clusters(img) + hits = cf.steal_hits() + assert len(hits) == 1 + assert hits.hits[0]["size"] == 8 + assert hits.hits[0]["energy"] == pytest.approx(160.0) + labels = cf.labeled + assert labels[3, 4] == -1 + assert labels[7, 0] == -1 + assert labels[2, 3] == 1 + cf.mask = None + cf.find_clusters(img) + assert len(cf.steal_hits()) == 2 + + +def test_mask_property_round_trip_and_checks(): + cf = VarClusterFinder((8, 8), 10.0) + assert cf.mask is None + mask = np.zeros((8, 8), dtype=np.uint8) + mask[1, 2] = 1 + cf.mask = mask # integer arrays are cast to bool + assert cf.mask.dtype == bool + assert np.array_equal(cf.mask, mask.astype(bool)) + cf.mask = None + assert cf.mask is None + with pytest.raises(RuntimeError): + cf.mask = np.zeros((8, 9), dtype=bool) + with pytest.raises(ValueError): + cf.mask = [True, False] # not a 2D array + + +def test_clusters_touching_the_mask_can_be_found_afterwards(): + # The recipe from the docs: dilate the mask by one pixel, treat the + # image border as masked and reduce per cluster. + img = frame_with_cluster(row=3, col=4) + img[6, 6] = 40.0 # single pixel away from the mask and the border + mask = np.zeros((8, 8), dtype=bool) + mask[3, 6] = True # next to the cluster's right column + cf = VarClusterFinder((8, 8), 10.0) + cf.mask = mask + cf.find_clusters(img) + hits = cf.steal_hits() + + pad = np.pad(mask, 1, constant_values=True) + near = np.zeros_like(mask) + for dr in (0, 1, 2): + for dc in (0, 1, 2): + near |= pad[dr : dr + mask.shape[0], dc : dc + mask.shape[1]] + touches = np.logical_or.reduceat(near[hits.rows, hits.cols], hits.hits["offset"]) + assert touches.tolist() == [True, False] + assert hits.hits[~touches]["energy"].tolist() == [40.0] + + +def test_fixed_thresholds_for_seeds_and_neighbours(): + img = np.zeros((8, 8)) + img[1:6, 1:6] = 8.0 + img[2:5, 2:5] = 20.0 + img[3, 3] = 100.0 + cf = VarClusterFinder((8, 8), 50.0) + assert cf.threshold == 50.0 + assert cf.neighbour_threshold == 50.0 + assert (cf.seed_factor, cf.neighbour_factor) == (5.0, 5.0) + + def size_of_first_hit(): + cf.find_clusters(img) + hits = cf.steal_hits() + assert len(hits) == 1 + return hits.hits[0]["size"] + + assert size_of_first_hit() == 1 + cf.neighbour_threshold = 10.0 + assert cf.neighbour_threshold == 10.0 + assert size_of_first_hit() == 9 + cf.neighbour_threshold = 5.0 + assert size_of_first_hit() == 25 + cf.neighbour_threshold = None + assert cf.neighbour_threshold == 50.0 + assert size_of_first_hit() == 1 + cf.threshold = 15.0 + assert cf.neighbour_threshold == 15.0 + assert size_of_first_hit() == 9 + with pytest.raises(TypeError): + cf.neighbour_threshold = "low" + + +def test_connectivity_property(): + img = np.zeros((8, 8)) + img[2, 2] = 50.0 + img[3, 3] = 40.0 # diagonal neighbour only + cf = VarClusterFinder((8, 8), 10.0) + assert cf.connectivity == 8 + cf.find_clusters(img) + assert len(cf.steal_hits()) == 1 + cf.connectivity = 4 + assert cf.connectivity == 4 + cf.find_clusters(img) + assert len(cf.steal_hits()) == 2 + with pytest.raises(RuntimeError): + cf.connectivity = 6 + assert cf.connectivity == 4 diff --git a/src/VarClusterFinder.test.cpp b/src/VarClusterFinder.test.cpp new file mode 100644 index 00000000..88365c7f --- /dev/null +++ b/src/VarClusterFinder.test.cpp @@ -0,0 +1,573 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/VarClusterFinder.hpp" +#include +#include +#include +#include +#include +#include + +using namespace aare; +using Finder = VarClusterFinder; +using Hits = Finder::Hits; + +namespace { + +template +std::set> pixels_of(const H &hits, size_t i) { + const auto &hit = hits.hits[i]; + std::set> pixels; + for (int64_t k = hit.offset; k < hit.offset + hit.size; ++k) + pixels.emplace(hits.rows[k], hits.cols[k]); + return pixels; +} + +// Centre value 100 surrounded by 20 in the eight neighbours, clipped at the +// image border. +void add_cluster(NDArray &img, int row, int col) { + for (int dr = -1; dr <= 1; ++dr) + for (int dc = -1; dc <= 1; ++dc) { + const int r = row + dr; + const int c = col + dc; + if (r < 0 || c < 0 || r >= img.shape(0) || c >= img.shape(1)) + continue; + img(r, c) += (dr == 0 && dc == 0) ? 100.0 : 20.0; + } +} + +} // namespace + +TEST_CASE("A single 3x3 cluster above a fixed threshold", "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 3, 4); + + Finder finder({8, 8}, 10.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 1); + REQUIRE(hits.n_pixels() == 9); + const auto &hit = hits.hits[0]; + CHECK(hit.size == 9); + CHECK(hit.offset == 0); + CHECK(hit.row == 3); + CHECK(hit.col == 4); + CHECK(hit.max == 100.0); + CHECK_THAT(hit.energy, Catch::Matchers::WithinAbs(260.0, 1e-12)); + + // The seed is the first pixel in scan order + CHECK(hits.rows[0] == 2); + CHECK(hits.cols[0] == 3); + + std::set> expected; + for (int r = 2; r <= 4; ++r) + for (int c = 3; c <= 5; ++c) + expected.emplace(r, c); + CHECK(pixels_of(hits, 0) == expected); + + // Stored pixel values match the stored coordinates + for (size_t i = 0; i < hits.n_pixels(); ++i) { + const double expected_value = + (hits.rows[i] == 3 && hits.cols[i] == 4) ? 100.0 : 20.0; + CHECK(hits.values[i] == expected_value); + } +} + +TEST_CASE("A cluster in the image corner is clipped", "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 0, 0); + + Finder finder({8, 8}, 10.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 4); + CHECK(hits.hits[0].row == 0); + CHECK(hits.hits[0].col == 0); + CHECK_THAT(hits.hits[0].energy, Catch::Matchers::WithinAbs(160.0, 1e-12)); +} + +TEST_CASE("Separated clusters give separate hits in scan order", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 6, 1); + add_cluster(img, 1, 6); + add_cluster(img, 1, 1); + + Finder finder({8, 8}, 10.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 3); + CHECK(hits.hits[0].row == 1); + CHECK(hits.hits[0].col == 1); + CHECK(hits.hits[1].row == 1); + CHECK(hits.hits[1].col == 6); + CHECK(hits.hits[2].row == 6); + CHECK(hits.hits[2].col == 1); + for (const auto &hit : hits.hits) + CHECK(hit.size == 9); + + // The pixel slices are contiguous and in hit order + CHECK(hits.hits[0].offset == 0); + CHECK(hits.hits[1].offset == 9); + CHECK(hits.hits[2].offset == 18); + CHECK(hits.n_pixels() == 27); + for (size_t i = 0; i < 3; ++i) { + const auto pixels = pixels_of(hits, i); + CHECK(pixels.size() == 9); + for (const auto &[r, c] : pixels) { + CHECK(std::abs(r - hits.hits[i].row) <= 1); + CHECK(std::abs(c - hits.hits[i].col) <= 1); + } + } + + auto labels = finder.labeled(); + CHECK(labels(1, 1) == 1); + CHECK(labels(0, 0) == 1); + CHECK(labels(2, 7) == 2); + CHECK(labels(7, 2) == 3); + CHECK(labels(4, 4) == 0); + CHECK(labels(0, 3) == 0); +} + +TEST_CASE("Diagonal neighbours join with 8 but not with 4 connectivity", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + img(2, 2) = 50.0; + img(3, 3) = 40.0; + + Finder finder({8, 8}, 10.0); + + SECTION("8 neighbours (default)") { + CHECK(finder.connectivity() == 8); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 2); + CHECK(hits.hits[0].row == 2); + CHECK(hits.hits[0].col == 2); + CHECK(hits.hits[0].max == 50.0); + CHECK(hits.hits[0].energy == 90.0); + } + SECTION("4 neighbours") { + finder.set_connectivity(4); + CHECK(finder.connectivity() == 4); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 2); + CHECK(hits.hits[0].size == 1); + CHECK(hits.hits[0].energy == 50.0); + CHECK(hits.hits[1].size == 1); + CHECK(hits.hits[1].offset == 1); + CHECK(hits.hits[1].energy == 40.0); + } + SECTION("Only 4 and 8 neighbours are accepted") { + CHECK_THROWS_AS(finder.set_connectivity(6), std::runtime_error); + CHECK_THROWS_AS(finder.set_connectivity(0), std::runtime_error); + CHECK(finder.connectivity() == 8); + } +} + +TEST_CASE("Noise map thresholds: seeds and neighbours use their own factors", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + img(4, 4) = 10.0; // seed: above 5 sigma + img(4, 5) = 3.0; // neighbour: between 2 and 5 sigma + img(1, 1) = 4.0; // isolated, below 5 sigma: never a seed by default + NDArray noise({8, 8}, 1.0); + + Finder finder({8, 8}, 1000.0); // fixed threshold must not be used + finder.set_noise_map(noise.view()); + + SECTION("Default peripheral factor 5 excludes the 3 sigma neighbour") { + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 1); + CHECK(hits.hits[0].energy == 10.0); + } + SECTION("Neighbour factor 2 includes the 3 sigma neighbour") { + finder.set_neighbour_factor(2); + CHECK(finder.neighbour_factor() == 2); + CHECK(finder.seed_factor() == 5); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 2); + CHECK(hits.hits[0].energy == 13.0); + CHECK(hits.hits[0].row == 4); + CHECK(hits.hits[0].col == 4); + } + SECTION("Seed factor 3.5 makes the isolated 4 sigma pixel a seed") { + finder.set_seed_factor(3.5); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 2); + CHECK(hits.hits[0].row == 1); + CHECK(hits.hits[0].col == 1); + CHECK(hits.hits[0].energy == 4.0); + CHECK(hits.hits[1].energy == 10.0); + } + SECTION("The noise map is copied") { + REQUIRE(finder.noise_map().has_value()); + CHECK(*finder.noise_map() == noise); + noise = 1000.0; + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 1); + CHECK_FALSE(*finder.noise_map() == noise); + } + SECTION("clear_noise_map returns to the fixed threshold") { + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 1); + finder.clear_noise_map(); + finder.find_clusters(img.view()); // fixed threshold 1000: no hits + CHECK(finder.total_clusters() == 1); + finder.set_noise_map(noise.view()); + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 2); + } + SECTION("A noise map of the wrong shape is rejected") { + NDArray wrong({8, 9}, 1.0); + CHECK_THROWS_AS(finder.set_noise_map(wrong.view()), std::runtime_error); + } +} + +TEST_CASE("Noise factors are floating point for integer images", + "[varcluster]") { + SECTION("A fractional seed factor is not truncated") { + // Noise 2 and seed factor 2.5 give a threshold of 5: the pixel of + // value 5 is not above it, the pixel of value 6 is. A factor + // truncated to 2 would accept both. + NDArray img({4, 4}, 0); + img(1, 1) = 5; + img(2, 3) = 6; + NDArray noise({4, 4}, 2); + VarClusterFinder finder({4, 4}, 1); + finder.set_noise_map(noise.view()); + finder.set_seed_factor(2.5); + CHECK(finder.seed_factor() == 2.5); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].row == 2); + CHECK(hits.hits[0].col == 3); + CHECK(hits.hits[0].max == 6); + } + SECTION("A fractional neighbour factor is not truncated") { + // Noise 2 and neighbour factor 1.5 give a threshold of 3: the + // neighbour of value 4 joins the cluster, the one of value 3 does + // not. A factor truncated to 1 would take both. + NDArray img({4, 4}, 0); + img(1, 1) = 20; + img(1, 2) = 3; + img(2, 1) = 4; + NDArray noise({4, 4}, 2); + VarClusterFinder finder({4, 4}, 1); + finder.set_noise_map(noise.view()); + finder.set_neighbour_factor(1.5); + CHECK(finder.neighbour_factor() == 1.5); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 2); + CHECK(pixels_of(hits, 0) == + std::set>{{1, 1}, {2, 1}}); + CHECK(hits.hits[0].energy == 24); + } + SECTION("The threshold does not wrap around in a narrow pixel type") { + // 5 times a noise of 20000 is 100000, which does not fit uint16_t. + // Wrapped to the pixel type it would be 34464, below the pixel. + NDArray img({4, 4}, 0); + img(1, 1) = 40000; + VarClusterFinder finder({4, 4}, 1); + NDArray noise({4, 4}, 20000); + finder.set_noise_map(noise.view()); + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 0); + NDArray small_noise({4, 4}, 2000); // threshold 10000 + finder.set_noise_map(small_noise.view()); + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 1); + } +} + +TEST_CASE("Large clusters store every pixel", "[varcluster]") { + NDArray img({10, 10}, 100.0); + img(7, 2) = 300.0; + + Finder finder({10, 10}, 10.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 100); + CHECK(hits.n_pixels() == 100); + CHECK_THAT(hits.hits[0].energy, Catch::Matchers::WithinAbs(10200.0, 1e-9)); + CHECK(hits.hits[0].max == 300.0); + CHECK(hits.hits[0].row == 7); + CHECK(hits.hits[0].col == 2); + CHECK(pixels_of(hits, 0).size() == 100); +} + +TEST_CASE("A whole module above threshold is one cluster", "[varcluster]") { + // Regression test: the recursive fill overflowed the stack here. + const Shape<2> shape{512, 1024}; + NDArray img(shape, 100.0); + + Finder finder(shape, 10.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 512 * 1024); + CHECK(hits.n_pixels() == 512 * 1024); + CHECK_THAT(hits.hits[0].energy, + Catch::Matchers::WithinRel(100.0 * 512 * 1024, 1e-12)); + auto labels = finder.labeled(); + CHECK(std::all_of(labels.begin(), labels.end(), + [](int32_t l) { return l == 1; })); +} + +TEST_CASE("Negative thresholds record the maximum correctly", "[varcluster]") { + NDArray img({8, 8}, -100.0); + for (int r = 2; r <= 4; ++r) + for (int c = 2; c <= 4; ++c) + img(r, c) = -30.0; + img(3, 3) = -10.0; + + Finder finder({8, 8}, -50.0); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 9); + CHECK(hits.hits[0].max == -10.0); + CHECK(hits.hits[0].row == 3); + CHECK(hits.hits[0].col == 3); + CHECK_THAT(hits.hits[0].energy, Catch::Matchers::WithinAbs(-250.0, 1e-12)); +} + +TEST_CASE("Image shape must match the finder", "[varcluster]") { + Finder finder({8, 8}, 10.0); + NDArray wrong({8, 9}, 0.0); + CHECK_THROWS_AS(finder.find_clusters(wrong.view()), std::runtime_error); + NDArray right({8, 8}, 0.0); + CHECK_NOTHROW(finder.find_clusters(right.view())); +} + +TEST_CASE("Shapes that do not fit 16 bit coordinates are rejected", + "[varcluster]") { + CHECK_THROWS_AS(Finder({0, 8}, 10.0), std::runtime_error); + CHECK_THROWS_AS(Finder({8, 40000}, 10.0), std::runtime_error); + CHECK_NOTHROW(Finder({1, 32767}, 10.0)); +} + +TEST_CASE("steal_hits empties the finder and total_clusters counts held hits", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 3, 3); + + Finder finder({8, 8}, 10.0); + CHECK(finder.total_clusters() == 0); + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 1); + auto hits = finder.steal_hits(); + CHECK(hits.size() == 1); + CHECK(finder.total_clusters() == 0); + auto empty = finder.steal_hits(); + CHECK(empty.empty()); + CHECK(empty.n_pixels() == 0); +} + +TEST_CASE("Hits accumulate over frames until cleared", "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 3, 3); + + Finder finder({8, 8}, 10.0); + finder.find_clusters(img.view()); + finder.find_clusters(img.view()); + CHECK(finder.total_clusters() == 2); + + // The second frame's pixels follow the first frame's in the arrays + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 2); + CHECK(hits.hits[0].offset == 0); + CHECK(hits.hits[1].offset == 9); + CHECK(hits.n_pixels() == 18); + CHECK(pixels_of(hits, 0) == pixels_of(hits, 1)); + + finder.find_clusters(img.view()); + finder.clear_hits(); + CHECK(finder.total_clusters() == 0); + CHECK(finder.steal_hits().n_pixels() == 0); +} + +TEST_CASE("The input is left untouched unless erase_clusters is enabled", + "[varcluster]") { + NDArray img({8, 8}, 1.0); + add_cluster(img, 3, 3); + const NDArray original(img); + + Finder finder({8, 8}, 10.0); + + SECTION("Default: no modification") { + CHECK_FALSE(finder.erase_clusters()); + finder.find_clusters(img.view()); + CHECK(img == original); + } + SECTION("Enabled: cluster pixels and the sub-threshold ring are zeroed") { + finder.set_erase_clusters(true); + CHECK(finder.erase_clusters()); + finder.find_clusters(img.view()); + for (int r = 0; r < 8; ++r) + for (int c = 0; c < 8; ++c) { + const bool touched = r >= 1 && r <= 5 && c >= 1 && c <= 5; + CHECK(img(r, c) == (touched ? 0.0 : 1.0)); + } + CHECK(finder.total_clusters() == 1); + } + SECTION("Zeroing does not change the hits of clusters sharing a ring") { + // The ring of the first cluster is zeroed before the second cluster + // is filled; with a non-negative threshold that cannot change it. + NDArray two({8, 12}, 1.0); + add_cluster(two, 3, 3); + add_cluster(two, 3, 7); + NDArray copy(two); + + Finder plain({8, 12}, 10.0); + plain.find_clusters(two.view()); + Finder zeroing({8, 12}, 10.0); + zeroing.set_erase_clusters(true); + zeroing.find_clusters(copy.view()); + + const auto a = plain.steal_hits(); + const auto b = zeroing.steal_hits(); + REQUIRE(a.size() == 2); + REQUIRE(b.size() == 2); + for (size_t i = 0; i < a.size(); ++i) { + CHECK(a.hits[i].size == b.hits[i].size); + CHECK(a.hits[i].energy == b.hits[i].energy); + CHECK(a.hits[i].row == b.hits[i].row); + CHECK(a.hits[i].col == b.hits[i].col); + CHECK(pixels_of(a, i) == pixels_of(b, i)); + } + CHECK(copy(3, 5) == 0.0); + } +} + +TEST_CASE("Masked pixels never seed and are never added to a cluster", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + add_cluster(img, 3, 4); + img(7, 0) = 50.0; // hot pixel + NDArray mask({8, 8}, false); + mask(3, 4) = true; // the cluster centre + mask(7, 0) = true; + + Finder finder({8, 8}, 10.0); + finder.set_mask(mask.view()); + + SECTION("The cluster grows around the masked centre") { + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + CHECK(hits.hits[0].size == 8); + CHECK(hits.hits[0].max == 20.0); + CHECK_THAT(hits.hits[0].energy, + Catch::Matchers::WithinAbs(160.0, 1e-12)); + CHECK(pixels_of(hits, 0).count({3, 4}) == 0); + auto labels = finder.labeled(); + CHECK(labels(3, 4) == -1); + CHECK(labels(7, 0) == -1); + CHECK(labels(2, 3) == 1); + CHECK(labels(0, 0) == 0); + } + SECTION("Masked pixels are not zeroed") { + finder.set_erase_clusters(true); + finder.find_clusters(img.view()); + CHECK(img(3, 4) == 100.0); + CHECK(img(7, 0) == 50.0); + CHECK(img(2, 3) == 0.0); + } + SECTION("A masked pixel splits a cluster") { + NDArray line({8, 8}, 0.0); + line(2, 2) = line(3, 2) = line(4, 2) = 30.0; + NDArray middle({8, 8}, false); + middle(3, 2) = true; + Finder split({8, 8}, 10.0); + split.find_clusters(line.view()); + CHECK(split.total_clusters() == 1); + split.clear_hits(); + split.set_mask(middle.view()); + split.find_clusters(line.view()); + CHECK(split.total_clusters() == 2); + } + SECTION("clear_mask restores the full image") { + finder.clear_mask(); + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 2); + CHECK(hits.hits[0].size == 9); + CHECK(hits.hits[0].max == 100.0); + CHECK(finder.labeled()(7, 0) == 2); + } + SECTION("A mask of the wrong shape is rejected") { + NDArray wrong({8, 9}, false); + CHECK_THROWS_AS(finder.set_mask(wrong.view()), std::runtime_error); + } +} + +TEST_CASE("mask() returns the current mask", "[varcluster]") { + Finder finder({8, 8}, 10.0); + CHECK_FALSE(finder.mask().has_value()); + NDArray mask({8, 8}, false); + mask(1, 2) = true; + finder.set_mask(mask.view()); + REQUIRE(finder.mask().has_value()); + CHECK(*finder.mask() == mask); + finder.clear_mask(); + CHECK_FALSE(finder.mask().has_value()); +} + +TEST_CASE("A fixed neighbour threshold grows clusters below the seed " + "threshold", + "[varcluster]") { + NDArray img({8, 8}, 0.0); + for (int r = 1; r <= 5; ++r) + for (int c = 1; c <= 5; ++c) + img(r, c) = 8.0; + for (int r = 2; r <= 4; ++r) + for (int c = 2; c <= 4; ++c) + img(r, c) = 20.0; + img(3, 3) = 100.0; + + Finder finder({8, 8}, 50.0); + CHECK(finder.threshold() == 50.0); + CHECK(finder.neighbour_threshold() == 50.0); + + auto size_of_first_hit = [&]() { + finder.find_clusters(img.view()); + auto hits = finder.steal_hits(); + REQUIRE(hits.size() == 1); + return hits.hits[0].size; + }; + CHECK(size_of_first_hit() == 1); + + finder.set_neighbour_threshold(10.0); + CHECK(finder.neighbour_threshold() == 10.0); + CHECK(size_of_first_hit() == 9); + + finder.set_neighbour_threshold(5.0); + CHECK(size_of_first_hit() == 25); + + finder.clear_neighbour_threshold(); + CHECK(finder.neighbour_threshold() == 50.0); + CHECK(size_of_first_hit() == 1); + + // The neighbour threshold follows the seed threshold while unset + finder.set_threshold(15.0); + CHECK(finder.neighbour_threshold() == 15.0); + CHECK(size_of_first_hit() == 9); +} From 4c6f88c905eae63cc3215eb101bcc048b635dad9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Fri, 6 Nov 2026 12:39:06 +0100 Subject: [PATCH 2/2] Dev/build time (#413) - Make zmq opt in since nothing uses it at the moment - Turn on unity builds for Minuit2, libzmq and Catch2. Specially for Minuit2 this seems to make a difference - Split python extension into multiple translation units - Drop LTO on the python ext. Saves 22s of link time (22-->0.1s on my laptop) --- .github/workflows/build_windows.yml | 2 +- .github/workflows/build_with_docs.yml | 7 +- AGENTS.md | 42 ++++- CMakeLists.txt | 126 ++++++++----- RELEASE.md | 25 +++ benchmarks/CMakeLists.txt | 2 +- docs/src/Installation.rst | 8 + docs/src/Requirements.rst | 2 +- pyproject.toml | 3 + python/CMakeLists.txt | 83 +++++++- python/src/bind_ClusterFileSink.hpp | 1 + .../{ctb_raw_file.hpp => bind_CtbRawFile.cpp} | 2 +- ...gation.hpp => bind_DataSetAggregation.cpp} | 12 +- python/src/{bind_Defs.hpp => bind_Defs.cpp} | 5 +- python/src/bind_Eta.cpp | 31 +++ python/src/bind_Eta.hpp | 2 +- ...FastPedestal.hpp => bind_FastPedestal.cpp} | 9 +- python/src/{file.hpp => bind_File.cpp} | 4 +- python/src/{fit.hpp => bind_Fit.cpp} | 4 +- ...{bind_GapPixels.hpp => bind_GapPixels.cpp} | 2 +- ...Interpolator.hpp => bind_Interpolator.cpp} | 4 +- ...ata_file.hpp => bind_JungfrauDataFile.cpp} | 2 +- ...r.hpp => bind_MultiThreadedFileReader.cpp} | 4 +- .../{bind_Pedestal.hpp => bind_Pedestal.cpp} | 8 +- ...> bind_PedestalTrackingPixelHistogram.cpp} | 3 +- ...lHistogram.hpp => bind_PixelHistogram.cpp} | 2 +- .../{bind_PixelMap.hpp => bind_PixelMap.cpp} | 4 +- .../{bind_RawFile.hpp => bind_RawFile.cpp} | 2 +- ...master_file.hpp => bind_RawMasterFile.cpp} | 2 +- .../{raw_sub_file.hpp => bind_RawSubFile.cpp} | 2 +- ..._cluster.hpp => bind_VarClusterFinder.cpp} | 2 +- ...d_calibration.hpp => bind_calibration.cpp} | 7 +- python/src/bind_cluster_2x2.cpp | 10 + python/src/bind_cluster_3x3.cpp | 28 +++ python/src/bind_cluster_5x5.cpp | 28 +++ python/src/bind_cluster_7x7.cpp | 28 +++ python/src/bind_cluster_9x9.cpp | 28 +++ python/src/bind_cluster_common.hpp | 38 ++++ .../{bind_testing.hpp => bind_testing.cpp} | 2 +- python/src/bindings.hpp | 79 ++++++++ python/src/module.cpp | 177 +++--------------- python/src/np_helper.hpp | 6 +- tests/CMakeLists.txt | 25 +++ 43 files changed, 619 insertions(+), 244 deletions(-) rename python/src/{ctb_raw_file.hpp => bind_CtbRawFile.cpp} (99%) rename python/src/{bind_DataSetAggregation.hpp => bind_DataSetAggregation.cpp} (93%) rename python/src/{bind_Defs.hpp => bind_Defs.cpp} (98%) create mode 100644 python/src/bind_Eta.cpp rename python/src/{bind_FastPedestal.hpp => bind_FastPedestal.cpp} (95%) rename python/src/{file.hpp => bind_File.cpp} (99%) rename python/src/{fit.hpp => bind_Fit.cpp} (99%) rename python/src/{bind_GapPixels.hpp => bind_GapPixels.cpp} (99%) rename python/src/{bind_Interpolator.hpp => bind_Interpolator.cpp} (99%) rename python/src/{jungfrau_data_file.hpp => bind_JungfrauDataFile.cpp} (99%) rename python/src/{bind_MultiThreadedFileReader.hpp => bind_MultiThreadedFileReader.cpp} (98%) rename python/src/{bind_Pedestal.hpp => bind_Pedestal.cpp} (95%) rename python/src/{bind_PedestalTrackingPixelHistogram.hpp => bind_PedestalTrackingPixelHistogram.cpp} (99%) rename python/src/{bind_PixelHistogram.hpp => bind_PixelHistogram.cpp} (99%) rename python/src/{bind_PixelMap.hpp => bind_PixelMap.cpp} (98%) rename python/src/{bind_RawFile.hpp => bind_RawFile.cpp} (99%) rename python/src/{raw_master_file.hpp => bind_RawMasterFile.cpp} (99%) rename python/src/{raw_sub_file.hpp => bind_RawSubFile.cpp} (99%) rename python/src/{var_cluster.hpp => bind_VarClusterFinder.cpp} (99%) rename python/src/{bind_calibration.hpp => bind_calibration.cpp} (98%) create mode 100644 python/src/bind_cluster_2x2.cpp create mode 100644 python/src/bind_cluster_3x3.cpp create mode 100644 python/src/bind_cluster_5x5.cpp create mode 100644 python/src/bind_cluster_7x7.cpp create mode 100644 python/src/bind_cluster_9x9.cpp create mode 100644 python/src/bind_cluster_common.hpp rename python/src/{bind_testing.hpp => bind_testing.cpp} (98%) create mode 100644 python/src/bindings.hpp diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml index 1a562f39..cc8303e0 100644 --- a/.github/workflows/build_windows.yml +++ b/.github/workflows/build_windows.yml @@ -37,7 +37,7 @@ jobs: # Precompiled headers are disabled: sccache cannot cache MSVC # compilations that use one - name: Configure - run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON + run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_PYTHON_UNITY_BUILD=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON - name: Build run: cmake --build build diff --git a/.github/workflows/build_with_docs.yml b/.github/workflows/build_with_docs.yml index 9e2dc872..8dbec646 100644 --- a/.github/workflows/build_with_docs.yml +++ b/.github/workflows/build_with_docs.yml @@ -52,12 +52,15 @@ jobs: version: "v0.18.0" # Precompiled headers are disabled because sccache does not cache - # compilations that use one + # compilations that use one. The python bindings are compiled as one + # translation unit per file (AARE_PYTHON_UNITY_BUILD=OFF, the local + # default) so every unit is checked to compile on its own; the + # packaging jobs build the grouped units instead. - name: Build library and docs run: | mkdir build cd build - cmake .. -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DAARE_SYSTEM_LIBRARIES=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_DOCS=ON -DAARE_TESTS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON + cmake .. -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DAARE_SYSTEM_LIBRARIES=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_PYTHON_UNITY_BUILD=OFF -DAARE_DOCS=ON -DAARE_TESTS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON make -j 4 make docs diff --git a/AGENTS.md b/AGENTS.md index 5646aaae..dfd5f687 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -49,10 +49,16 @@ cmake --build build -j4 Useful optional settings include `AARE_DOCS`, `AARE_BENCHMARKS`, `AARE_ASAN`, `AARE_WARNINGS_AS_ERRORS`, `AARE_VERBOSE` (raises the compile-time log -level), and `AARE_TUNE_LOCAL` (`-march=native`, not portable). Reconfigure an -existing build directory instead of creating alternate in-tree build layouts -unless isolation is needed; `build/CMakeCache.txt` records the options and -interpreter it was configured with. +level), `AARE_TUNE_LOCAL` (`-march=native`, not portable), `AARE_ZMQ` +(fetches or finds ZeroMQ and defines `aare::zmq`; nothing links it yet), and +`AARE_PYTHON_UNITY_BUILD` (compiles the python bindings as one translation +unit per binding area instead of one per class; less total compiler time, +less parallelism; `pip install` and the packaging CI jobs turn it on, the +`build_with_docs` job keeps it off so every unit is checked to compile on +its own). +Reconfigure an existing build directory instead of creating alternate +in-tree build layouts unless isolation is needed; `build/CMakeCache.txt` +records the options and interpreter it was configured with. `-Werror=return-type` is always enabled. New code should also compile cleanly under the project's `-Wall -Wextra -pedantic -Wshadow -Wold-style-cast @@ -169,13 +175,28 @@ agree; run them when changing any solver. ### Python layer -- `python/src/module.cpp` registers everything. Templated classes are - instantiated per value type and cluster size through the - `DEFINE_CLUSTER_BINDINGS` and `DEFINE_BINDINGS_CLUSTERFINDER` macros, +- `python/src/module.cpp` only calls the registration entry points declared + in `bindings.hpp`, in a fixed order (overload docstrings follow it). Each + `bind_.cpp` is one translation unit with the bindings of one class + or function group (`bind_RawFile.cpp`, `bind_Fit.cpp`, + `bind_calibration.cpp`, ...) and defines the entry point it declares in + `bindings.hpp`. Headers hold only templates that several units + instantiate: the `bind_Cluster*.hpp` set and `bind_Eta.hpp`, included + through `bind_cluster_common.hpp` by one `bind_cluster_NxN.cpp` per + cluster size and by `bind_Eta.cpp`. Templated classes are instantiated + per value type and cluster size through the `DEFINE_CLUSTER_BINDINGS` and + `DEFINE_BINDINGS_CLUSTERFINDER` macros in `bind_cluster_common.hpp`, producing names such as `ClusterFinder_Cluster3x3i`, `Pedestal_d`, and `FastPedestal_i16`. Supported cluster sizes are 2x2, 3x3, 5x5, 7x7, and 9x9; value types are `i`, `f`, `d`, and `i16` (3x3 only). - `module_config.hpp` fixes the module-wide pedestal type (`pd_type`). + `module_config.hpp` fixes the module-wide pedestal type (`pd_type`). A + shared header must include everything it uses itself, including the + pybind11 casters (`pybind11/stl.h`, `pybind11/stl/filesystem.h`) for the + types its bindings take or return, and non-template functions it defines + must be `inline`. `python/CMakeLists.txt` lists the units in groups + (`io`, `core`, `hist`, `pedestal`, `fit`); with `AARE_PYTHON_UNITY_BUILD` + the units of a group are concatenated into one, so file-scope names + (helpers, anonymous namespaces, macros) must not clash within a group. - `python/aare/factory.py` maps NumPy dtypes to those suffixes. The facades in `python/aare/*.py` are thin factory functions or subclasses that select the right binding and add Pythonic conveniences (iteration, context @@ -223,7 +244,10 @@ A Python-facing feature can require coordinated changes in several layers: 1. Update the C++ public API and implementation. 2. Add or update its binding in `python/src/`. -3. Register new bindings in `python/src/module.cpp`. +3. Register new bindings: put them in the matching `python/src/bind_*.cpp` + or add a new unit to its group in `python/CMakeLists.txt`, declare the + entry point in `python/src/bindings.hpp`, and call it from + `python/src/module.cpp`. 4. Update the facade or public exports in `python/aare/`. 5. If adding a Python module, add it to `PYTHON_FILES` in `python/CMakeLists.txt` so it is copied and installed. diff --git a/CMakeLists.txt b/CMakeLists.txt index 84d65e3c..8595562f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -43,6 +43,10 @@ set(CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) # General options option(AARE_PYTHON_BINDINGS "Build python bindings" OFF) +option( + AARE_PYTHON_UNITY_BUILD + "Compile the python bindings as one translation unit per binding area instead of one per class: less total compiler time, fewer units to build in parallel" + OFF) option(AARE_TESTS "Build tests" OFF) option(AARE_BENCHMARKS "Build benchmarks" OFF) option(AARE_EXAMPLES "Build examples" OFF) @@ -65,6 +69,10 @@ option(AARE_FETCH_FMT "Use FetchContent to download fmt" ON) option(AARE_FETCH_PYBIND11 "Use FetchContent to download pybind11" ON) option(AARE_FETCH_CATCH "Use FetchContent to download catch2" ON) option(AARE_FETCH_JSON "Use FetchContent to download nlohmann::json" ON) +option( + AARE_ZMQ + "Fetch or find ZeroMQ. Nothing uses it yet; kept for upcoming streaming support" + OFF) option(AARE_FETCH_ZMQ "Use FetchContent to download libzmq" ON) option(AARE_FETCH_MINUIT2 "Use FetchContent to download Minuit2" ON) @@ -107,6 +115,7 @@ if(AARE_FETCH_MINUIT2) Minuit2 GIT_REPOSITORY https://github.com/GooFit/Minuit2.git GIT_TAG v6-40-02 + GIT_SHALLOW TRUE UPDATE_DISCONNECTED 1) # Disable Minuit2 extras we don't need set(minuit2_mpi @@ -124,6 +133,10 @@ if(AARE_FETCH_MINUIT2) FetchContent_MakeAvailable(Minuit2) set_property(TARGET Minuit2Math PROPERTY POSITION_INDEPENDENT_CODE ON) + # Minuit2 is ~60 small files; compiling them in batches is several times + # faster + set_target_properties(Minuit2 Minuit2Math + PROPERTIES UNITY_BUILD ON UNITY_BUILD_BATCH_SIZE 16) set_property(TARGET Minuit2 PROPERTY POSITION_INDEPENDENT_CODE ON) add_library(aare::Minuit2 ALIAS Minuit2) @@ -144,53 +157,75 @@ else() endif() endif() -if(AARE_FETCH_ZMQ) - # Fetchcontent_Declare is deprecated need to find a way to update this for now - # setting the policy to old is enough - if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.30") - cmake_policy(SET CMP0169 OLD) - endif() - set(ZMQ_PATCH_COMMAND - git apply ${CMAKE_CURRENT_SOURCE_DIR}/patches/libzmq_cmake_version.patch) - FetchContent_Declare( - libzmq - GIT_REPOSITORY https://github.com/zeromq/libzmq.git - GIT_TAG v4.3.5 - PATCH_COMMAND ${ZMQ_PATCH_COMMAND} - UPDATE_DISCONNECTED 1) - # Disable unwanted options from libzmq - set(BUILD_TESTS - OFF - CACHE BOOL "Switch off libzmq test build") - set(BUILD_SHARED - OFF - CACHE BOOL "Switch off libzmq shared libs") - set(WITH_PERF_TOOL - OFF - CACHE BOOL "") - set(ENABLE_CPACK - OFF - CACHE BOOL "") - set(ENABLE_CLANG - OFF - CACHE BOOL "") - set(ENABLE_CURVE - OFF - CACHE BOOL "") - set(ENABLE_DRAFTS - OFF - CACHE BOOL "") +# ZeroMQ is not linked anywhere at the moment, so it is only fetched and +# configured on request (saves ~8 s per configure and a 25 MB clone). Enable it +# with -DAARE_ZMQ=ON and link aare::zmq where it is needed. +if(AARE_ZMQ) + if(AARE_FETCH_ZMQ) + # Fetchcontent_Declare is deprecated need to find a way to update this for + # now setting the policy to old is enough + if(${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.30") + cmake_policy(SET CMP0169 OLD) + endif() + set(ZMQ_PATCH_COMMAND + git apply + ${CMAKE_CURRENT_SOURCE_DIR}/patches/libzmq_cmake_version.patch) + FetchContent_Declare( + libzmq + GIT_REPOSITORY https://github.com/zeromq/libzmq.git + GIT_TAG v4.3.5 + GIT_SHALLOW TRUE + PATCH_COMMAND ${ZMQ_PATCH_COMMAND} + UPDATE_DISCONNECTED 1) + # Disable unwanted options from libzmq + set(BUILD_TESTS + OFF + CACHE BOOL "Switch off libzmq test build") + set(BUILD_SHARED + OFF + CACHE BOOL "Switch off libzmq shared libs") + set(WITH_PERF_TOOL + OFF + CACHE BOOL "") + set(ENABLE_CPACK + OFF + CACHE BOOL "") + set(ENABLE_CLANG + OFF + CACHE BOOL "") + set(ENABLE_CURVE + OFF + CACHE BOOL "") + set(ENABLE_DRAFTS + OFF + CACHE BOOL "") - # TODO! Verify that this is what we want to do in aare Using GetProperties and - # Populate to be able to exclude zmq from install (not possible with - # FetchContent_MakeAvailable(libzmq)) - FetchContent_GetProperties(libzmq) - if(NOT libzmq_POPULATED) - FetchContent_Populate(libzmq) - add_subdirectory(${libzmq_SOURCE_DIR} ${libzmq_BINARY_DIR} EXCLUDE_FROM_ALL) + # TODO! Verify that this is what we want to do in aare Using GetProperties + # and Populate to be able to exclude zmq from install (not possible with + # FetchContent_MakeAvailable(libzmq)) + FetchContent_GetProperties(libzmq) + if(NOT libzmq_POPULATED) + FetchContent_Populate(libzmq) + add_subdirectory(${libzmq_SOURCE_DIR} ${libzmq_BINARY_DIR} + EXCLUDE_FROM_ALL) + # libzmq compiles its sources into the OBJECT library "objects" (on + # Windows directly into libzmq-static); batch them like Minuit2 + foreach(_zmq_target objects libzmq-static) + if(TARGET ${_zmq_target}) + set_target_properties( + ${_zmq_target} PROPERTIES UNITY_BUILD ON UNITY_BUILD_BATCH_SIZE 16) + endif() + endforeach() + endif() + else() + find_package(ZeroMQ 4 REQUIRED) endif() -else() - find_package(ZeroMQ 4 REQUIRED) + if(TARGET libzmq-static) + add_library(aare::zmq ALIAS libzmq-static) + else() + add_library(aare::zmq ALIAS libzmq) + endif() + message(STATUS "ZeroMQ enabled (AARE_ZMQ=ON), link aare::zmq to use it") endif() if(AARE_FETCH_FMT) @@ -201,6 +236,7 @@ if(AARE_FETCH_FMT) fmt GIT_REPOSITORY https://github.com/fmtlib/fmt.git GIT_TAG 12.1.0 + GIT_SHALLOW TRUE GIT_PROGRESS TRUE USES_TERMINAL_DOWNLOAD TRUE) set(FMT_INSTALL diff --git a/RELEASE.md b/RELEASE.md index 74b65aa2..34e36555 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -88,6 +88,31 @@ read through ``CtbRawFile``. The transforms now flatten the frame before calling the decoders. +### Build: + +- libzmq is only fetched or searched for with ``-DAARE_ZMQ=ON`` (default + OFF) and is then available as ``aare::zmq``. Nothing in aare links it yet, + and skipping it removes about 8 s from every CMake configure. +- Minuit2, Catch2, and libzmq when enabled, are compiled as unity builds + (about 4-5x less compile time), and the fetched dependencies are shallow + clones, which makes a first configure faster and the build directory + smaller. +- The Python extension is compiled from one translation unit per bound + class or function group instead of a single file, so the bindings build + in parallel and editing one binding recompiles only its unit. + ``-DAARE_PYTHON_UNITY_BUILD=ON`` (used by ``pip install`` and the + packaging CI jobs) + combines the units of each binding area into one, which needs less total + compiler time on machines with few cores. The module's contents and + registration order are unchanged. +- The Python extension is no longer link-time optimized by default. The hot + loops are header templates compiled at ``-O3`` inside the extension and + LTO cannot reach the static ``aare_core``, so it only added a 20 s + single-threaded link and made the binary 15 % smaller. LTO follows the + standard CMake property now: + ``set_property(TARGET _aare PROPERTY INTERPROCEDURAL_OPTIMIZATION ON)`` or + ``-DCMAKE_INTERPROCEDURAL_OPTIMIZATION=ON`` restores it. + ## 2026.9.30 ### New Features: diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index 76732411..3b4f2f10 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -6,7 +6,7 @@ FetchContent_Declare( benchmark GIT_REPOSITORY https://github.com/google/benchmark.git GIT_TAG v1.8.3 # Change to the latest version if needed -) + GIT_SHALLOW TRUE) # Ensure Google Benchmark is built correctly set(BENCHMARK_ENABLE_TESTING diff --git a/docs/src/Installation.rst b/docs/src/Installation.rst index 2cd8c681..eb64a216 100644 --- a/docs/src/Installation.rst +++ b/docs/src/Installation.rst @@ -109,6 +109,14 @@ Build the Python bindings. Default option is off. If you have a newer system Python compared to the one in your virtual environment, you might have to pass -DPython_FIND_VIRTUALENV=ONLY to cmake. +**AARE_PYTHON_UNITY_BUILD "Compile the python bindings as one translation unit per binding area" OFF** + +Compile the Python bindings as one translation unit per binding area (file readers, +pedestals, clusters of one size, ...) instead of one per bound class. The build then +needs less total compiler time but has fewer units to compile in parallel, which is +faster on machines with few cores. Default option is off; ``pip install`` and the packaging +CI jobs turn it on. + **AARE_TESTS "Build tests" OFF** Build unit tests. Default option is off. diff --git a/docs/src/Requirements.rst b/docs/src/Requirements.rst index 7c44dbdc..c75dfdf1 100644 --- a/docs/src/Requirements.rst +++ b/docs/src/Requirements.rst @@ -17,7 +17,7 @@ To simplify deployment we build and statically link a few libraries. - Minuit2 - nlohmann_json - pybind11 -- ZeroMQ +- ZeroMQ (only with ``-DAARE_ZMQ=ON``; nothing uses it yet) **Extra dependencies for building documentation** diff --git a/pyproject.toml b/pyproject.toml index e1176dcd..4e557c4e 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -43,6 +43,9 @@ install.components = ["python"] [tool.scikit-build.cmake.define] AARE_PYTHON_BINDINGS = "ON" +# A pip build is compiled once and never incrementally, so fewer, larger +# translation units only save compiler time +AARE_PYTHON_UNITY_BUILD = "ON" AARE_INSTALL_PYTHONEXT = "ON" diff --git a/python/CMakeLists.txt b/python/CMakeLists.txt index 7f4db4c0..410564b7 100644 --- a/python/CMakeLists.txt +++ b/python/CMakeLists.txt @@ -11,22 +11,97 @@ if(AARE_FETCH_PYBIND11) FetchContent_Declare( pybind11 GIT_REPOSITORY https://github.com/pybind/pybind11 - GIT_TAG v3.0.3) + GIT_TAG v3.0.3 + GIT_SHALLOW TRUE) FetchContent_MakeAvailable(pybind11) else() find_package(pybind11 3.0.3 REQUIRED) endif() -# Add the compiled python extension +# The compiled python extension. Each bind_*.cpp holds the bindings of one class +# or function group and is its own translation unit, so the units compile in +# parallel and an edit recompiles only its file. The templated cluster bindings +# are instantiated per cluster size in bind_cluster_NxN.cpp; src/module.cpp +# registers everything in a fixed order. +# +# AARE_PYTHON_UNITY_BUILD combines the units of each group below into one. That +# trades parallelism and per-file rebuilds for less total compiler time, which +# is what counts on machines with few cores; pip builds and the packaging CI +# jobs turn it on. The build_with_docs CI job keeps it off, so every unit is +# also checked to compile on its own. +# +# Without NO_EXTRAS pybind11 links pybind11::lto, which forces full LTO on the +# extension regardless of the target's INTERPROCEDURAL_OPTIMIZATION property. +# LTO cannot reach aare_core (a plain static library) and the templated hot +# paths are already compiled at -O3 inside the extension, so it only adds a long +# single-threaded link step. With NO_EXTRAS the standard target property decides +# (off by default); the other extras are re-added below. +set(_aare_py_io + src/bind_File.cpp + src/bind_RawFile.cpp + src/bind_RawSubFile.cpp + src/bind_RawMasterFile.cpp + src/bind_CtbRawFile.cpp + src/bind_JungfrauDataFile.cpp + src/bind_MultiThreadedFileReader.cpp + src/bind_DataSetAggregation.cpp) +set(_aare_py_core src/bind_Defs.cpp src/bind_GapPixels.cpp + src/bind_PixelMap.cpp src/bind_testing.cpp) +set(_aare_py_hist src/bind_PixelHistogram.cpp + src/bind_PedestalTrackingPixelHistogram.cpp) +set(_aare_py_pedestal src/bind_Pedestal.cpp src/bind_FastPedestal.cpp + src/bind_calibration.cpp) +set(_aare_py_fit src/bind_Fit.cpp src/bind_Interpolator.cpp) +set(_aare_py_groups io core hist pedestal fit) + pybind11_add_module( _aare # name of the module - src/module.cpp # source file -) + NO_EXTRAS + src/module.cpp + # the cluster units take longest, listing them first schedules them first + src/bind_cluster_3x3.cpp + src/bind_cluster_9x9.cpp + src/bind_cluster_7x7.cpp + src/bind_cluster_5x5.cpp + src/bind_cluster_2x2.cpp + ${_aare_py_io} + ${_aare_py_core} + ${_aare_py_hist} + ${_aare_py_pedestal} + ${_aare_py_fit} + src/bind_Eta.cpp + src/bind_VarClusterFinder.cpp) + +if(AARE_PYTHON_UNITY_BUILD) + if(CMAKE_VERSION VERSION_LESS 3.18) + message( + WARNING + "AARE_PYTHON_UNITY_BUILD needs CMake 3.18 or newer; compiling the python bindings as individual translation units" + ) + else() + set_target_properties(_aare PROPERTIES UNITY_BUILD ON UNITY_BUILD_MODE + GROUP) + foreach(group IN LISTS _aare_py_groups) + set_source_files_properties(${_aare_py_${group}} PROPERTIES UNITY_GROUP + ${group}) + endforeach() + endif() +endif() set_target_properties(_aare PROPERTIES LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}) target_link_libraries(_aare PRIVATE aare_core aare_compiler_flags) +# The pybind11_add_module extras that NO_EXTRAS skipped, LTO excepted +if(MSVC) + target_link_libraries(_aare PRIVATE pybind11::windows_extras) # /bigobj, /MP +elseif(CMAKE_BUILD_TYPE) + string(TOUPPER "${CMAKE_BUILD_TYPE}" _aare_build_type) + if(NOT _aare_build_type MATCHES "DEBUG|RELWITHDEBINFO|NONE") + pybind11_strip(_aare) # strip symbols from optimized builds + endif() +endif() + target_include_directories( _aare SYSTEM PRIVATE $) diff --git a/python/src/bind_ClusterFileSink.hpp b/python/src/bind_ClusterFileSink.hpp index 48820551..b6892b1c 100644 --- a/python/src/bind_ClusterFileSink.hpp +++ b/python/src/bind_ClusterFileSink.hpp @@ -13,6 +13,7 @@ #include #include #include +#include #include namespace py = pybind11; diff --git a/python/src/ctb_raw_file.hpp b/python/src/bind_CtbRawFile.cpp similarity index 99% rename from python/src/ctb_raw_file.hpp rename to python/src/bind_CtbRawFile.cpp index 1808c01d..368f587f 100644 --- a/python/src/ctb_raw_file.hpp +++ b/python/src/bind_CtbRawFile.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" diff --git a/python/src/bind_DataSetAggregation.hpp b/python/src/bind_DataSetAggregation.cpp similarity index 93% rename from python/src/bind_DataSetAggregation.hpp rename to python/src/bind_DataSetAggregation.cpp index a12f2fb4..6e352c9c 100644 --- a/python/src/bind_DataSetAggregation.hpp +++ b/python/src/bind_DataSetAggregation.cpp @@ -1,6 +1,11 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + #include "aare/DataSetAggregation.hpp" +#include "np_helper.hpp" #include +#include #include #include @@ -75,4 +80,9 @@ void bind_read_current_source(pybind11::module_ &m) { -------- np.ndarray: A numpy array containing the mean frame stored as np.float64 for each current source with shape (rows, cols, num_sources). )pbdoc"); -} \ No newline at end of file +} + +void bind_dataset_aggregation(py::module &m) { + bind_DataSetAggregation(m); + bind_read_current_source(m); +} diff --git a/python/src/bind_Defs.hpp b/python/src/bind_Defs.cpp similarity index 98% rename from python/src/bind_Defs.hpp rename to python/src/bind_Defs.cpp index 489ca052..dcdd2800 100644 --- a/python/src/bind_Defs.hpp +++ b/python/src/bind_Defs.cpp @@ -1,11 +1,14 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include #include #include +#include "aare/ROI.hpp" #include "aare/defs.hpp" +#include + namespace py = pybind11; using namespace aare; diff --git a/python/src/bind_Eta.cpp b/python/src/bind_Eta.cpp new file mode 100644 index 00000000..707ac960 --- /dev/null +++ b/python/src/bind_Eta.cpp @@ -0,0 +1,31 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_Eta.hpp" + +#include +#include + +void bind_eta_types(py::module &m) { + using Sum_index_pair_d = Sum_index_pair; + PYBIND11_NUMPY_DTYPE(Sum_index_pair_d, sum, index); + using Sum_index_pair_f = Sum_index_pair; + PYBIND11_NUMPY_DTYPE(Sum_index_pair_f, sum, index); + using Sum_index_pair_i = Sum_index_pair; + PYBIND11_NUMPY_DTYPE(Sum_index_pair_i, sum, index); + + using eta_d = Eta2; + PYBIND11_NUMPY_DTYPE(eta_d, x, y, c, sum); + using eta_i = Eta2; + PYBIND11_NUMPY_DTYPE(eta_i, x, y, c, sum); + using eta_f = Eta2; + PYBIND11_NUMPY_DTYPE(eta_f, x, y, c, sum); + using eta_i16 = Eta2; + PYBIND11_NUMPY_DTYPE(eta_i16, x, y, c, sum); + + define_corner_enum(m); + define_eta(m, "f"); + define_eta(m, "d"); + define_eta(m, "i"); + define_eta(m, "i16"); +} diff --git a/python/src/bind_Eta.hpp b/python/src/bind_Eta.hpp index 1f2dc32b..868e7d37 100644 --- a/python/src/bind_Eta.hpp +++ b/python/src/bind_Eta.hpp @@ -29,7 +29,7 @@ void define_eta(py::module &m, const std::string &typestr) { }); } -void define_corner_enum(py::module &m) { +inline void define_corner_enum(py::module &m) { py::enum_(m, "corner", "enum.Enum") .value("cTopLeft", corner::cTopLeft) .value("cTopRight", corner::cTopRight) diff --git a/python/src/bind_FastPedestal.hpp b/python/src/bind_FastPedestal.cpp similarity index 95% rename from python/src/bind_FastPedestal.hpp rename to python/src/bind_FastPedestal.cpp index 8bba55ea..46574f9f 100644 --- a/python/src/bind_FastPedestal.hpp +++ b/python/src/bind_FastPedestal.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/FastPedestal.hpp" #include "np_helper.hpp" @@ -8,6 +8,7 @@ #include #include #include +#include namespace py = pybind11; @@ -134,3 +135,9 @@ void define_fast_pedestal_bindings(py::module &m, const std::string &name) { "the next n_samples for initialization, then apply every remaining " "frame as a steady-state update."); } + +void bind_fast_pedestals(py::module &m) { + define_fast_pedestal_bindings(m, "FastPedestal_d"); + define_fast_pedestal_bindings(m, "FastPedestal_f"); + define_fast_pedestal_bindings(m, "FastPedestal_i16"); +} diff --git a/python/src/file.hpp b/python/src/bind_File.cpp similarity index 99% rename from python/src/file.hpp rename to python/src/bind_File.cpp index 96960d91..09d6de03 100644 --- a/python/src/file.hpp +++ b/python/src/bind_File.cpp @@ -1,5 +1,4 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" @@ -7,6 +6,7 @@ #include "aare/RawFile.hpp" #include "aare/RawMasterFile.hpp" #include "aare/RawSubFile.hpp" +#include "bindings.hpp" #include "aare/defs.hpp" @@ -159,4 +159,4 @@ void define_file_io_bindings(py::module &m) { .def_property_readonly("start", &ScanParameters::start) .def_property_readonly("stop", &ScanParameters::stop) .def_property_readonly("step", &ScanParameters::step); -} \ No newline at end of file +} diff --git a/python/src/fit.hpp b/python/src/bind_Fit.cpp similarity index 99% rename from python/src/fit.hpp rename to python/src/bind_Fit.cpp index 4d6e3835..0e762604 100644 --- a/python/src/fit.hpp +++ b/python/src/bind_Fit.cpp @@ -1,7 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" +#include "np_helper.hpp" #include #include +#include #include #include #include diff --git a/python/src/bind_GapPixels.hpp b/python/src/bind_GapPixels.cpp similarity index 99% rename from python/src/bind_GapPixels.hpp rename to python/src/bind_GapPixels.cpp index 41874ca5..caaa751a 100644 --- a/python/src/bind_GapPixels.hpp +++ b/python/src/bind_GapPixels.cpp @@ -1,8 +1,8 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/GapPixels.hpp" #include "aare/ROI.hpp" #include "aare/defs.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include diff --git a/python/src/bind_Interpolator.hpp b/python/src/bind_Interpolator.cpp similarity index 99% rename from python/src/bind_Interpolator.hpp rename to python/src/bind_Interpolator.cpp index de391f3b..524f1c6a 100644 --- a/python/src/bind_Interpolator.hpp +++ b/python/src/bind_Interpolator.cpp @@ -1,9 +1,9 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/CalculateEta.hpp" #include "aare/Interpolator.hpp" #include "aare/NDArray.hpp" #include "aare/NDView.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include #include @@ -209,4 +209,4 @@ void define_interpolation_bindings(py::module &m) { par : array_like The parameters of the Gaussian function. The first element is the amplitude, the second element is the mean, and the third element is the standard deviation. )"); -} \ No newline at end of file +} diff --git a/python/src/jungfrau_data_file.hpp b/python/src/bind_JungfrauDataFile.cpp similarity index 99% rename from python/src/jungfrau_data_file.hpp rename to python/src/bind_JungfrauDataFile.cpp index 84f4e6f4..41ab9743 100644 --- a/python/src/jungfrau_data_file.hpp +++ b/python/src/bind_JungfrauDataFile.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/JungfrauDataFile.hpp" #include "aare/defs.hpp" diff --git a/python/src/bind_MultiThreadedFileReader.hpp b/python/src/bind_MultiThreadedFileReader.cpp similarity index 98% rename from python/src/bind_MultiThreadedFileReader.hpp rename to python/src/bind_MultiThreadedFileReader.cpp index 0f39cb6c..2de55c7d 100644 --- a/python/src/bind_MultiThreadedFileReader.hpp +++ b/python/src/bind_MultiThreadedFileReader.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/MultiThreadedFileReader.hpp" @@ -71,7 +71,7 @@ multi_threaded_reader_read(aare::experimental::MultiThreadedFileReader &reader, return image; } -inline void define_multi_threaded_file_reader_bindings(py::module_ &m) { +void define_multi_threaded_file_reader_bindings(py::module_ &m) { using aare::experimental::MultiThreadedFileReader; auto reader = diff --git a/python/src/bind_Pedestal.hpp b/python/src/bind_Pedestal.cpp similarity index 95% rename from python/src/bind_Pedestal.hpp rename to python/src/bind_Pedestal.cpp index 02b4d32f..479ba084 100644 --- a/python/src/bind_Pedestal.hpp +++ b/python/src/bind_Pedestal.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/Pedestal.hpp" #include "np_helper.hpp" @@ -120,3 +120,9 @@ void define_pedestal_bindings(py::module &m, const std::string &name) { true); }); } + +void bind_pedestals(py::module &m) { + define_pedestal_bindings(m, "Pedestal_d"); + define_pedestal_bindings(m, "Pedestal_f"); + define_pedestal_bindings(m, "Pedestal_i16"); +} diff --git a/python/src/bind_PedestalTrackingPixelHistogram.hpp b/python/src/bind_PedestalTrackingPixelHistogram.cpp similarity index 99% rename from python/src/bind_PedestalTrackingPixelHistogram.hpp rename to python/src/bind_PedestalTrackingPixelHistogram.cpp index 1d650b26..4b8cf925 100644 --- a/python/src/bind_PedestalTrackingPixelHistogram.hpp +++ b/python/src/bind_PedestalTrackingPixelHistogram.cpp @@ -1,12 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/hist/PedestalTrackingPixelHistogram.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include #include #include #include +#include namespace py = pybind11; using namespace ::aare; diff --git a/python/src/bind_PixelHistogram.hpp b/python/src/bind_PixelHistogram.cpp similarity index 99% rename from python/src/bind_PixelHistogram.hpp rename to python/src/bind_PixelHistogram.cpp index b0c97e35..c013cd9c 100644 --- a/python/src/bind_PixelHistogram.hpp +++ b/python/src/bind_PixelHistogram.cpp @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/hist/PixelHistogram.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include diff --git a/python/src/bind_PixelMap.hpp b/python/src/bind_PixelMap.cpp similarity index 98% rename from python/src/bind_PixelMap.hpp rename to python/src/bind_PixelMap.cpp index 6aec76c3..a4fb15c1 100644 --- a/python/src/bind_PixelMap.hpp +++ b/python/src/bind_PixelMap.cpp @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/PixelMap.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include @@ -65,4 +65,4 @@ void define_pixel_map_bindings(py::module &m) { py::arg("dynamic_range") = 16, py::arg("n_counters") = 1, R"( Generate pixel map for Matterhorn02 detector)"); -} \ No newline at end of file +} diff --git a/python/src/bind_RawFile.hpp b/python/src/bind_RawFile.cpp similarity index 99% rename from python/src/bind_RawFile.hpp rename to python/src/bind_RawFile.cpp index f3b2d672..fbdea295 100644 --- a/python/src/bind_RawFile.hpp +++ b/python/src/bind_RawFile.cpp @@ -1,5 +1,4 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" @@ -7,6 +6,7 @@ #include "aare/RawFile.hpp" #include "aare/RawMasterFile.hpp" #include "aare/RawSubFile.hpp" +#include "bindings.hpp" #include "aare/defs.hpp" #include "np_helper.hpp" diff --git a/python/src/raw_master_file.hpp b/python/src/bind_RawMasterFile.cpp similarity index 99% rename from python/src/raw_master_file.hpp rename to python/src/bind_RawMasterFile.cpp index 5a0b049d..9043a300 100644 --- a/python/src/raw_master_file.hpp +++ b/python/src/bind_RawMasterFile.cpp @@ -1,5 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once +#include "bindings.hpp" #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" diff --git a/python/src/raw_sub_file.hpp b/python/src/bind_RawSubFile.cpp similarity index 99% rename from python/src/raw_sub_file.hpp rename to python/src/bind_RawSubFile.cpp index 66ec7d8b..25885bcd 100644 --- a/python/src/raw_sub_file.hpp +++ b/python/src/bind_RawSubFile.cpp @@ -1,11 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" #include "aare/RawFile.hpp" #include "aare/RawMasterFile.hpp" #include "aare/RawSubFile.hpp" +#include "bindings.hpp" #include "aare/defs.hpp" diff --git a/python/src/var_cluster.hpp b/python/src/bind_VarClusterFinder.cpp similarity index 99% rename from python/src/var_cluster.hpp rename to python/src/bind_VarClusterFinder.cpp index 9aade712..980df083 100644 --- a/python/src/var_cluster.hpp +++ b/python/src/bind_VarClusterFinder.cpp @@ -1,6 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/VarClusterFinder.hpp" +#include "bindings.hpp" #include "np_helper.hpp" #include diff --git a/python/src/bind_calibration.hpp b/python/src/bind_calibration.cpp similarity index 98% rename from python/src/bind_calibration.hpp rename to python/src/bind_calibration.cpp index 3cfc960e..c93d77f0 100644 --- a/python/src/bind_calibration.hpp +++ b/python/src/bind_calibration.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 -#pragma once #include "aare/calibration.hpp" +#include "bindings.hpp" +#include "np_helper.hpp" #include #include @@ -10,7 +11,7 @@ #include namespace py = pybind11; -using aare::ssize_t; +using namespace aare; template py::array_t @@ -164,4 +165,4 @@ void bind_calibration(py::module &m) { The number of threads to use for the calculation. )", py::arg("raw_data").noconvert(), py::arg("n_threads") = 4); -} \ No newline at end of file +} diff --git a/python/src/bind_cluster_2x2.cpp b/python/src/bind_cluster_2x2.cpp new file mode 100644 index 00000000..e7f93a3a --- /dev/null +++ b/python/src/bind_cluster_2x2.cpp @@ -0,0 +1,10 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_cluster_common.hpp" + +void bind_cluster_types_2x2(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int, 2, 2, uint16_t, i); + DEFINE_CLUSTER_BINDINGS(double, 2, 2, uint16_t, d); + DEFINE_CLUSTER_BINDINGS(float, 2, 2, uint16_t, f); +} diff --git a/python/src/bind_cluster_3x3.cpp b/python/src/bind_cluster_3x3.cpp new file mode 100644 index 00000000..d59eac31 --- /dev/null +++ b/python/src/bind_cluster_3x3.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_cluster_common.hpp" + +void bind_cluster_types_3x3(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int, 3, 3, uint16_t, i); + DEFINE_CLUSTER_BINDINGS(double, 3, 3, uint16_t, d); + DEFINE_CLUSTER_BINDINGS(float, 3, 3, uint16_t, f); +} + +void bind_cluster_types_3x3_i16(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int16_t, 3, 3, uint16_t, i16); +} + +void bind_cluster_finders_3x3(py::module &m) { + DEFINE_BINDINGS_CLUSTERFINDER(int, 3, 3, uint16_t, i); + DEFINE_BINDINGS_CLUSTERFINDER(double, 3, 3, uint16_t, d); + DEFINE_BINDINGS_CLUSTERFINDER(float, 3, 3, uint16_t, f); + DEFINE_BINDINGS_CLUSTERFINDER(int16_t, 3, 3, uint16_t, i16); +} + +void bind_eta_3x3(py::module &m) { + register_calculate_3x3eta(m); + register_calculate_3x3eta(m); + register_calculate_3x3eta(m); + register_calculate_3x3eta(m); +} diff --git a/python/src/bind_cluster_5x5.cpp b/python/src/bind_cluster_5x5.cpp new file mode 100644 index 00000000..29adec8a --- /dev/null +++ b/python/src/bind_cluster_5x5.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_cluster_common.hpp" + +void bind_cluster_types_5x5(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int, 5, 5, uint16_t, i); + DEFINE_CLUSTER_BINDINGS(double, 5, 5, uint16_t, d); + DEFINE_CLUSTER_BINDINGS(float, 5, 5, uint16_t, f); +} + +void bind_cluster_finders_5x5(py::module &m) { + DEFINE_BINDINGS_CLUSTERFINDER(int, 5, 5, uint16_t, i); + DEFINE_BINDINGS_CLUSTERFINDER(double, 5, 5, uint16_t, d); + DEFINE_BINDINGS_CLUSTERFINDER(float, 5, 5, uint16_t, f); +} + +void bind_cluster_vector_reductions_5x5(py::module &m) { + define_3x3_reduction(m); + define_3x3_reduction(m); + define_3x3_reduction(m); +} + +void bind_cluster_reductions_5x5(py::module &m) { + reduce_to_3x3(m); + reduce_to_3x3(m); + reduce_to_3x3(m); +} diff --git a/python/src/bind_cluster_7x7.cpp b/python/src/bind_cluster_7x7.cpp new file mode 100644 index 00000000..3bd2fc4b --- /dev/null +++ b/python/src/bind_cluster_7x7.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_cluster_common.hpp" + +void bind_cluster_types_7x7(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int, 7, 7, uint16_t, i); + DEFINE_CLUSTER_BINDINGS(double, 7, 7, uint16_t, d); + DEFINE_CLUSTER_BINDINGS(float, 7, 7, uint16_t, f); +} + +void bind_cluster_finders_7x7(py::module &m) { + DEFINE_BINDINGS_CLUSTERFINDER(int, 7, 7, uint16_t, i); + DEFINE_BINDINGS_CLUSTERFINDER(double, 7, 7, uint16_t, d); + DEFINE_BINDINGS_CLUSTERFINDER(float, 7, 7, uint16_t, f); +} + +void bind_cluster_vector_reductions_7x7(py::module &m) { + define_3x3_reduction(m); + define_3x3_reduction(m); + define_3x3_reduction(m); +} + +void bind_cluster_reductions_7x7(py::module &m) { + reduce_to_3x3(m); + reduce_to_3x3(m); + reduce_to_3x3(m); +} diff --git a/python/src/bind_cluster_9x9.cpp b/python/src/bind_cluster_9x9.cpp new file mode 100644 index 00000000..6ffc5b6a --- /dev/null +++ b/python/src/bind_cluster_9x9.cpp @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "bindings.hpp" + +#include "bind_cluster_common.hpp" + +void bind_cluster_types_9x9(py::module &m) { + DEFINE_CLUSTER_BINDINGS(int, 9, 9, uint16_t, i); + DEFINE_CLUSTER_BINDINGS(double, 9, 9, uint16_t, d); + DEFINE_CLUSTER_BINDINGS(float, 9, 9, uint16_t, f); +} + +void bind_cluster_finders_9x9(py::module &m) { + DEFINE_BINDINGS_CLUSTERFINDER(int, 9, 9, uint16_t, i); + DEFINE_BINDINGS_CLUSTERFINDER(double, 9, 9, uint16_t, d); + DEFINE_BINDINGS_CLUSTERFINDER(float, 9, 9, uint16_t, f); +} + +void bind_cluster_vector_reductions_9x9(py::module &m) { + define_3x3_reduction(m); + define_3x3_reduction(m); + define_3x3_reduction(m); +} + +void bind_cluster_reductions_9x9(py::module &m) { + reduce_to_3x3(m); + reduce_to_3x3(m); + reduce_to_3x3(m); +} diff --git a/python/src/bind_cluster_common.hpp b/python/src/bind_cluster_common.hpp new file mode 100644 index 00000000..809a58b8 --- /dev/null +++ b/python/src/bind_cluster_common.hpp @@ -0,0 +1,38 @@ +// SPDX-License-Identifier: MPL-2.0 +// Shared by the per-cluster-size translation units bind_cluster_NxN.cpp. +#pragma once + +#include "module_config.hpp" + +#include "bind_Cluster.hpp" +#include "bind_ClusterCollector.hpp" +#include "bind_ClusterFile.hpp" +#include "bind_ClusterFileSink.hpp" +#include "bind_ClusterFinder.hpp" +#include "bind_ClusterFinderMT.hpp" +#include "bind_ClusterVector.hpp" +#include "bind_Eta.hpp" + +/* MACRO that defines Cluster bindings for a specific size and type + +T - Storage type of the cluster data (int, float, double) +N - Number of rows in the cluster +M - Number of columns in the cluster +U - Type of the pixel data (e.g., uint16_t) +TYPE_CODE - A character representing the type code (e.g., 'i' for int, 'd' for +double, 'f' for float) + +*/ +#define DEFINE_CLUSTER_BINDINGS(T, N, M, U, TYPE_CODE) \ + define_ClusterFile(m, "Cluster" #N "x" #M #TYPE_CODE); \ + define_ClusterVector(m, "Cluster" #N "x" #M #TYPE_CODE); \ + define_Cluster(m, #N "x" #M #TYPE_CODE); \ + register_calculate_2x2eta(m); \ + define_2x2_reduction(m); \ + reduce_to_2x2(m); + +#define DEFINE_BINDINGS_CLUSTERFINDER(T, N, M, U, TYPE_CODE) \ + define_ClusterFinder(m, "Cluster" #N "x" #M #TYPE_CODE); \ + define_ClusterFinderMT(m, "Cluster" #N "x" #M #TYPE_CODE); \ + define_ClusterFileSink(m, "Cluster" #N "x" #M #TYPE_CODE); \ + define_ClusterCollector(m, "Cluster" #N "x" #M #TYPE_CODE); diff --git a/python/src/bind_testing.hpp b/python/src/bind_testing.cpp similarity index 98% rename from python/src/bind_testing.hpp rename to python/src/bind_testing.cpp index 2a4e8760..1e8199a8 100644 --- a/python/src/bind_testing.hpp +++ b/python/src/bind_testing.cpp @@ -1,7 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 // Probes used by the python test-suite to exercise the helpers in // np_helper.hpp. Internal, no API guarantees. -#pragma once +#include "bindings.hpp" #include "aare/NDArray.hpp" #include "aare/NDView.hpp" diff --git a/python/src/bindings.hpp b/python/src/bindings.hpp new file mode 100644 index 00000000..c4cad924 --- /dev/null +++ b/python/src/bindings.hpp @@ -0,0 +1,79 @@ +// SPDX-License-Identifier: MPL-2.0 +// Entry points of the binding translation units. Each bind_*.cpp defines the +// entry points listed under its name; module.cpp calls them in a fixed order. +// The templated cluster and eta bindings are shared headers (bind_Cluster*.hpp, +// bind_Eta.hpp) instantiated per size in bind_cluster_NxN.cpp. +#pragma once + +#include +#include + +namespace py = pybind11; + +// bind_File.cpp +void define_file_io_bindings(py::module &m); +// bind_RawFile.cpp +void define_raw_file_io_bindings(py::module &m); +// bind_RawSubFile.cpp +void define_raw_sub_file_io_bindings(py::module &m); +// bind_RawMasterFile.cpp +void define_raw_master_file_bindings(py::module &m); +// bind_CtbRawFile.cpp +void define_ctb_raw_file_io_bindings(py::module &m); +// bind_JungfrauDataFile.cpp +void define_jungfrau_data_file_io_bindings(py::module &m); +// bind_MultiThreadedFileReader.cpp +void define_multi_threaded_file_reader_bindings(py::module &m); +// bind_DataSetAggregation.cpp +void bind_dataset_aggregation(py::module &m); + +// bind_Defs.cpp +void define_defs_bindings(py::module &m); +// bind_GapPixels.cpp +void define_gap_pixels_bindings(py::module &m); +// bind_PixelMap.cpp +void define_pixel_map_bindings(py::module &m); +// bind_testing.cpp +void define_testing_bindings(py::module &m); + +// bind_PixelHistogram.cpp +void define_pixel_histogram_bindings(py::module &m); +// bind_PedestalTrackingPixelHistogram.cpp +void define_pedestal_tracking_pixel_histogram_bindings(py::module &m); + +// bind_Pedestal.cpp +void bind_pedestals(py::module &m); +// bind_FastPedestal.cpp +void bind_fast_pedestals(py::module &m); +// bind_calibration.cpp +void bind_calibration(py::module &m); + +// bind_Fit.cpp +void define_fit_bindings(py::module &m); +// bind_Interpolator.cpp +void define_interpolation_bindings(py::module &m); + +// bind_VarClusterFinder.cpp +void define_var_cluster_finder_bindings(py::module &m); + +// bind_Eta.cpp +void bind_eta_types(py::module &m); + +// bind_cluster_NxN.cpp +void bind_cluster_types_3x3(py::module &m); +void bind_cluster_types_3x3_i16(py::module &m); +void bind_cluster_types_2x2(py::module &m); +void bind_cluster_types_5x5(py::module &m); +void bind_cluster_types_7x7(py::module &m); +void bind_cluster_types_9x9(py::module &m); +void bind_cluster_finders_3x3(py::module &m); +void bind_cluster_finders_5x5(py::module &m); +void bind_cluster_finders_7x7(py::module &m); +void bind_cluster_finders_9x9(py::module &m); +void bind_cluster_vector_reductions_5x5(py::module &m); +void bind_cluster_vector_reductions_7x7(py::module &m); +void bind_cluster_vector_reductions_9x9(py::module &m); +void bind_cluster_reductions_5x5(py::module &m); +void bind_cluster_reductions_7x7(py::module &m); +void bind_cluster_reductions_9x9(py::module &m); +void bind_eta_3x3(py::module &m); diff --git a/python/src/module.cpp b/python/src/module.cpp index 9f14a72c..22d483e6 100644 --- a/python/src/module.cpp +++ b/python/src/module.cpp @@ -1,70 +1,11 @@ // SPDX-License-Identifier: MPL-2.0 -// Files with bindings to the different classes +// Module registration. Each bind_*.cpp defines the bindings of one class or +// function group and declares its entry point in bindings.hpp. The call order +// below is kept: overload docstrings follow it. -#include "module_config.hpp" +#include "bindings.hpp" -// New style file naming -#include "bind_Cluster.hpp" -#include "bind_ClusterCollector.hpp" -#include "bind_ClusterFile.hpp" -#include "bind_ClusterFileSink.hpp" -#include "bind_ClusterFinder.hpp" -#include "bind_ClusterFinderMT.hpp" -#include "bind_ClusterVector.hpp" -#include "bind_DataSetAggregation.hpp" -#include "bind_Defs.hpp" -#include "bind_Eta.hpp" -#include "bind_FastPedestal.hpp" -#include "bind_GapPixels.hpp" -#include "bind_Interpolator.hpp" -#include "bind_MultiThreadedFileReader.hpp" -#include "bind_Pedestal.hpp" -#include "bind_PedestalTrackingPixelHistogram.hpp" -#include "bind_PixelHistogram.hpp" -#include "bind_PixelMap.hpp" -#include "bind_RawFile.hpp" -#include "bind_calibration.hpp" -#include "bind_testing.hpp" - -// TODO! migrate the other names -#include "ctb_raw_file.hpp" -#include "file.hpp" -#include "fit.hpp" -#include "jungfrau_data_file.hpp" -#include "raw_master_file.hpp" -#include "raw_sub_file.hpp" -#include "var_cluster.hpp" - -// Pybind stuff -#include #include -#include - -namespace py = pybind11; - -/* MACRO that defines Cluster bindings for a specific size and type - -T - Storage type of the cluster data (int, float, double) -N - Number of rows in the cluster -M - Number of columns in the cluster -U - Type of the pixel data (e.g., uint16_t) -TYPE_CODE - A character representing the type code (e.g., 'i' for int, 'd' for -double, 'f' for float) - -*/ -#define DEFINE_CLUSTER_BINDINGS(T, N, M, U, TYPE_CODE) \ - define_ClusterFile(m, "Cluster" #N "x" #M #TYPE_CODE); \ - define_ClusterVector(m, "Cluster" #N "x" #M #TYPE_CODE); \ - define_Cluster(m, #N "x" #M #TYPE_CODE); \ - register_calculate_2x2eta(m); \ - define_2x2_reduction(m); \ - reduce_to_2x2(m); - -#define DEFINE_BINDINGS_CLUSTERFINDER(T, N, M, U, TYPE_CODE) \ - define_ClusterFinder(m, "Cluster" #N "x" #M #TYPE_CODE); \ - define_ClusterFinderMT(m, "Cluster" #N "x" #M #TYPE_CODE); \ - define_ClusterFileSink(m, "Cluster" #N "x" #M #TYPE_CODE); \ - define_ClusterCollector(m, "Cluster" #N "x" #M #TYPE_CODE); PYBIND11_MODULE(_aare, m) { auto experimental = m.def_submodule( @@ -80,12 +21,8 @@ PYBIND11_MODULE(_aare, m) { define_pixel_map_bindings(m); define_pixel_histogram_bindings(m); define_pedestal_tracking_pixel_histogram_bindings(m); - define_pedestal_bindings(m, "Pedestal_d"); - define_pedestal_bindings(m, "Pedestal_f"); - define_pedestal_bindings(m, "Pedestal_i16"); - define_fast_pedestal_bindings(m, "FastPedestal_d"); - define_fast_pedestal_bindings(m, "FastPedestal_f"); - define_fast_pedestal_bindings(m, "FastPedestal_i16"); + bind_pedestals(m); + bind_fast_pedestals(m); define_fit_bindings(m); define_interpolation_bindings(m); define_jungfrau_data_file_io_bindings(m); @@ -93,96 +30,32 @@ PYBIND11_MODULE(_aare, m) { bind_calibration(m); define_testing_bindings(m); - DEFINE_CLUSTER_BINDINGS(int, 3, 3, uint16_t, i); - DEFINE_CLUSTER_BINDINGS(double, 3, 3, uint16_t, d); - DEFINE_CLUSTER_BINDINGS(float, 3, 3, uint16_t, f); + bind_cluster_types_3x3(m); + bind_cluster_types_2x2(m); + bind_cluster_types_5x5(m); + bind_cluster_types_7x7(m); + bind_cluster_types_9x9(m); + bind_cluster_types_3x3_i16(m); - DEFINE_CLUSTER_BINDINGS(int, 2, 2, uint16_t, i); - DEFINE_CLUSTER_BINDINGS(double, 2, 2, uint16_t, d); - DEFINE_CLUSTER_BINDINGS(float, 2, 2, uint16_t, f); + bind_cluster_finders_3x3(m); + bind_cluster_finders_5x5(m); + bind_cluster_finders_7x7(m); + bind_cluster_finders_9x9(m); - DEFINE_CLUSTER_BINDINGS(int, 5, 5, uint16_t, i); - DEFINE_CLUSTER_BINDINGS(double, 5, 5, uint16_t, d); - DEFINE_CLUSTER_BINDINGS(float, 5, 5, uint16_t, f); + bind_cluster_vector_reductions_5x5(m); + bind_cluster_vector_reductions_7x7(m); + bind_cluster_vector_reductions_9x9(m); - DEFINE_CLUSTER_BINDINGS(int, 7, 7, uint16_t, i); - DEFINE_CLUSTER_BINDINGS(double, 7, 7, uint16_t, d); - DEFINE_CLUSTER_BINDINGS(float, 7, 7, uint16_t, f); + bind_cluster_reductions_5x5(m); + bind_cluster_reductions_7x7(m); + bind_cluster_reductions_9x9(m); - DEFINE_CLUSTER_BINDINGS(int, 9, 9, uint16_t, i); - DEFINE_CLUSTER_BINDINGS(double, 9, 9, uint16_t, d); - DEFINE_CLUSTER_BINDINGS(float, 9, 9, uint16_t, f); - - DEFINE_CLUSTER_BINDINGS(int16_t, 3, 3, uint16_t, i16); - - DEFINE_BINDINGS_CLUSTERFINDER(int, 3, 3, uint16_t, i); - DEFINE_BINDINGS_CLUSTERFINDER(double, 3, 3, uint16_t, d); - DEFINE_BINDINGS_CLUSTERFINDER(float, 3, 3, uint16_t, f); - DEFINE_BINDINGS_CLUSTERFINDER(int16_t, 3, 3, uint16_t, i16); - - DEFINE_BINDINGS_CLUSTERFINDER(int, 5, 5, uint16_t, i); - DEFINE_BINDINGS_CLUSTERFINDER(double, 5, 5, uint16_t, d); - DEFINE_BINDINGS_CLUSTERFINDER(float, 5, 5, uint16_t, f); - - DEFINE_BINDINGS_CLUSTERFINDER(int, 7, 7, uint16_t, i); - DEFINE_BINDINGS_CLUSTERFINDER(double, 7, 7, uint16_t, d); - DEFINE_BINDINGS_CLUSTERFINDER(float, 7, 7, uint16_t, f); - - DEFINE_BINDINGS_CLUSTERFINDER(int, 9, 9, uint16_t, i); - DEFINE_BINDINGS_CLUSTERFINDER(double, 9, 9, uint16_t, d); - DEFINE_BINDINGS_CLUSTERFINDER(float, 9, 9, uint16_t, f); - - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - define_3x3_reduction(m); - - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - reduce_to_3x3(m); - - register_calculate_3x3eta(m); - register_calculate_3x3eta(m); - register_calculate_3x3eta(m); - register_calculate_3x3eta(m); + bind_eta_3x3(m); define_defs_bindings(m); define_gap_pixels_bindings(m); - using Sum_index_pair_d = Sum_index_pair; - PYBIND11_NUMPY_DTYPE(Sum_index_pair_d, sum, index); - using Sum_index_pair_f = Sum_index_pair; - PYBIND11_NUMPY_DTYPE(Sum_index_pair_f, sum, index); - using Sum_index_pair_i = Sum_index_pair; - PYBIND11_NUMPY_DTYPE(Sum_index_pair_i, sum, index); + bind_eta_types(m); - using eta_d = Eta2; - PYBIND11_NUMPY_DTYPE(eta_d, x, y, c, sum); - using eta_i = Eta2; - PYBIND11_NUMPY_DTYPE(eta_i, x, y, c, sum); - using eta_f = Eta2; - PYBIND11_NUMPY_DTYPE(eta_f, x, y, c, sum); - using eta_i16 = Eta2; - PYBIND11_NUMPY_DTYPE(eta_i16, x, y, c, sum); - - define_corner_enum(m); - define_eta(m, "f"); - define_eta(m, "d"); - define_eta(m, "i"); - define_eta(m, "i16"); - - bind_DataSetAggregation(m); - - bind_read_current_source(m); + bind_dataset_aggregation(m); } diff --git a/python/src/np_helper.hpp b/python/src/np_helper.hpp index 83880470..6beb7318 100644 --- a/python/src/np_helper.hpp +++ b/python/src/np_helper.hpp @@ -1,11 +1,13 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once +#include #include #include #include #include +#include "aare/Cluster.hpp" #include "aare/Frame.hpp" #include "aare/NDArray.hpp" #include "aare/NDView.hpp" @@ -124,8 +126,8 @@ template const std::string &fmt_format() { * Helper function to allocate image data given item size and shape * used when we want to fill a numpy array and return to python */ -py::array allocate_image_data(size_t item_size, - const std::vector &shape) { +inline py::array allocate_image_data(size_t item_size, + const std::vector &shape) { py::array image_data; if (item_size == 1) { image_data = py::array_t(shape); diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index eb90112c..d9cbbd25 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -8,6 +8,9 @@ if(AARE_FETCH_CATCH) GIT_REPOSITORY https://github.com/catchorg/Catch2.git GIT_TAG v3.5.3) FetchContent_MakeAvailable(Catch2) + # Catch2 is ~100 small files; a unity build compiles them in a few batches + set_target_properties(Catch2 Catch2WithMain + PROPERTIES UNITY_BUILD ON UNITY_BUILD_BATCH_SIZE 16) else() # Otherwise look for installed catch2 find_package(Catch2 3 REQUIRED) @@ -24,6 +27,28 @@ set_target_properties( tests PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR} OUTPUT_NAME run_tests) +# Headers nearly every test includes, parsed once instead of per test file. Keep +# this list to the test framework and ubiquitous aare headers: anything listed +# here is available in every test without an #include. +target_precompile_headers( + tests + PRIVATE + + + + + + + + + + + "${PROJECT_SOURCE_DIR}/include/aare/NDArray.hpp" + "${PROJECT_SOURCE_DIR}/include/aare/NDView.hpp" + "${PROJECT_SOURCE_DIR}/include/aare/defs.hpp" + "${PROJECT_SOURCE_DIR}/include/aare/Frame.hpp" + "${PROJECT_SOURCE_DIR}/include/aare/Dtype.hpp") + include(CTest) include(Catch) catch_discover_tests(tests)