From c7ccacbe92956b04e075a067261e2eea579f02f6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Tue, 17 Nov 2026 21:01:26 +0100 Subject: [PATCH] Steal clusters without stopping cluster collector (#438) - Added missing destructor - Added missing start (technically not needed but gives symmetry with stop) - Cluster vector is now protected by a mutex and can be stolen without stopping the collector. Recommended pattern: ```python cf = ClusterFinderMT(...) sink = ClusterCollector(cf) for i in range(N): ... cf.find_clusters(frame) cf.sync() clusters = sink.steal_clusters() #find more clusters ``` Additions: - Destructor for ClusterFileSink - Destructor for ClusterFinderMT --- CMakeLists.txt | 1 + RELEASE.md | 24 ++++ include/aare/ClusterCollector.hpp | 88 ++++++++++--- include/aare/ClusterFileSink.hpp | 70 ++++++++-- include/aare/ClusterFinderMT.hpp | 46 ++++++- python/aare/ClusterFinder.py | 9 +- python/src/bind_ClusterCollector.hpp | 16 ++- python/src/bind_ClusterFileSink.hpp | 9 +- python/tests/test_ClusterFinderMT.py | 148 +++++++++++++++++++++ src/ClusterFileSink.test.cpp | 179 ++++++++++++++++++++++++++ src/ClusterFinderMT.test.cpp | 186 +++++++++++++++++++++++++++ 11 files changed, 734 insertions(+), 42 deletions(-) create mode 100644 python/tests/test_ClusterFinderMT.py create mode 100644 src/ClusterFileSink.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 62baa10f..b8616a89 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -542,6 +542,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/Cluster.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/CalculateEta.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFile.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFileSink.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFinderMT.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ProducerConsumerQueue.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Pedestal.test.cpp diff --git a/RELEASE.md b/RELEASE.md index 1747f6b3..e1a81973 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -37,6 +37,12 @@ ### API Changes: +- ``ClusterCollector.steal_clusters()`` can be called while the collector + is running and no longer raises on a collector that is not stopped. It + returns the clusters collected since the last call; call ``sync()`` on the + ``ClusterFinderMT`` first to get those of every frame given to it so far. +- ``ClusterCollector`` has ``start()``, which starts the collector thread + again after ``stop()``. Both do nothing when there is nothing to do. - ``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 @@ -73,6 +79,24 @@ ### Bugfixes: +- Destroying a running ``ClusterFinderMT`` no longer terminates the program. + The destructor stops the threads without waiting for the frames and + clusters still in the queues, so it also returns when nothing empties the + sink; call ``stop()`` first to have every frame processed. ``start()`` + and ``stop()`` do nothing on a finder that is already running or stopped, + instead of terminating or raising. +- ``ClusterFileSink`` opens its file before it starts its thread. Clusters + that were already in the sink queue of the finder could be dropped + instead of written. +- ``ClusterFileSink`` raises if the file cannot be opened, instead of + silently discarding all clusters. +- Destroying a ``ClusterFileSink`` without calling ``stop()`` no longer + terminates the program: the destructor stops the thread and closes the + file. Calling ``stop()`` twice no longer raises. In Python the sink keeps + its ``ClusterFinderMT`` alive. +- Destroying a ``ClusterCollector`` without calling ``stop()`` no longer + terminates the program: the destructor stops the collector thread. In + Python the collector keeps its ``ClusterFinderMT`` alive. - 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. diff --git a/include/aare/ClusterCollector.hpp b/include/aare/ClusterCollector.hpp index aa4e334c..b2655ee4 100644 --- a/include/aare/ClusterCollector.hpp +++ b/include/aare/ClusterCollector.hpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once #include +#include #include #include #include @@ -14,6 +15,18 @@ namespace aare { +/** + * @brief Takes the clusters out of a sink queue, such as the one of a + * ClusterFinderMT, on its own thread and keeps them in memory. + * + * The thread is started by the constructor and stopped by stop() or the + * destructor, and can be started again with start(). The clusters collected + * so far can be taken with steal_clusters() at any time, also while the + * collector is running. start() and stop() must not be called from several + * threads at once. + * + * The queue must outlive the collector. + */ template >> class ClusterCollector { @@ -21,19 +34,23 @@ class ClusterCollector { SourceQueue *m_source; std::atomic m_stop_requested{false}; - std::atomic m_stopped{true}; std::thread m_thread; + std::mutex m_clusters_mutex; // guards m_clusters std::vector> m_clusters; void process() { - m_stopped.store(false, std::memory_order_release); fmt::print("ClusterCollector started\n"); Backoff backoff; while (true) { if (ClusterVector *clusters = m_source->frontPtr(); clusters != nullptr) { backoff.reset(); - m_clusters.push_back(std::move(*clusters)); + { + std::lock_guard lock(m_clusters_mutex); + m_clusters.push_back(std::move(*clusters)); + } + // Removed from the queue only once it can be stolen, so an + // empty queue means that nothing is on its way m_source->popFront(); continue; } @@ -44,16 +61,13 @@ class ClusterCollector { backoff.pause(); } fmt::print("ClusterCollector stopped\n"); - m_stopped.store(true, std::memory_order_release); } public: explicit ClusterCollector(SourceQueue *source) : m_source(source) { - m_thread = - std::thread(&ClusterCollector::process, - this); // only one process does that so why isnt it - // automatically written to m_cluster in collect - // - instead of writing first to m_sink? + // only one process does that so why isnt it automatically written to + // m_cluster in collect - instead of writing first to m_sink? + start(); } template sink()) {} - void stop() { - m_stop_requested.store(true, std::memory_order_release); - if (m_thread.joinable()) - m_thread.join(); - } - std::vector> steal_clusters() { - if (!m_stopped.load(std::memory_order_acquire)) { - throw std::runtime_error("ClusterCollector is still running"); + /// Stops the collector thread, see stop() + ~ClusterCollector() { stop(); } + + // The thread holds a pointer to this object + ClusterCollector(const ClusterCollector &) = delete; + ClusterCollector &operator=(const ClusterCollector &) = delete; + + /** + * @brief Start the collector thread. Does nothing if it is running. + * + * Clusters collected before stop() that have not been stolen are kept. + */ + void start() { + if (m_thread.joinable()) { + return; } - return std::move(m_clusters); + m_stop_requested.store(false, std::memory_order_release); + m_thread = std::thread(&ClusterCollector::process, this); + } + + /** + * @brief Stop the collector thread once the queue is empty. Does nothing + * if it is stopped. + */ + void stop() { + if (!m_thread.joinable()) { + return; + } + m_stop_requested.store(true, std::memory_order_release); + m_thread.join(); + } + + /** + * @brief Take the clusters collected since the last call, one + * ClusterVector per frame. + * + * Can be called while the collector is running. Clusters that are still + * on their way are not included: to get those of every frame given to + * a ClusterFinderMT so far, call its sync() first, from the thread that + * gives it the frames. + */ + std::vector> steal_clusters() { + std::vector> clusters; + { + std::lock_guard lock(m_clusters_mutex); + clusters.swap(m_clusters); + } + return clusters; } }; diff --git a/include/aare/ClusterFileSink.hpp b/include/aare/ClusterFileSink.hpp index 4abd7415..82e32b2a 100644 --- a/include/aare/ClusterFileSink.hpp +++ b/include/aare/ClusterFileSink.hpp @@ -1,28 +1,46 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once #include +#include +#include #include +#include +#include #include +#include + #include "aare/ClusterFinderMT.hpp" #include "aare/ClusterVector.hpp" #include "aare/ProducerConsumerQueue.hpp" +#include "aare/logger.hpp" namespace aare { +/** + * @brief Takes the clusters out of a sink queue, such as the one of a + * ClusterFinderMT, on its own thread and writes them to a binary cluster + * file that ClusterFile reads. + * + * The thread is started by the constructor and stopped by stop() or the + * destructor, which also close the file. A stopped sink cannot be started + * again. + * + * The queue must outlive the sink. + */ template >, typename = std::enable_if_t::value>> class ClusterFileSink { - ProducerConsumerQueue> *m_source; + using SourceQueue = ProducerConsumerQueue>; + + SourceQueue *m_source; std::atomic m_stop_requested{false}; - std::atomic m_stopped{true}; std::chrono::milliseconds m_default_wait{1}; - std::thread m_thread; std::ofstream m_file; + std::thread m_thread; void process() { - m_stopped = false; LOG(logDEBUG) << "ClusterFileSink started"; while (!m_stop_requested || !m_source->isEmpty()) { if (ClusterVector *clusters = m_source->frontPtr(); @@ -44,24 +62,52 @@ class ClusterFileSink { } } LOG(logDEBUG) << "ClusterFileSink stopped"; - m_stopped = true; } public: - ClusterFileSink(ClusterFinderMT *source, - const std::filesystem::path &fname) { + /** + * @brief Open the file, replacing an existing one, and start writing the + * clusters of the queue to it. + * @throws std::runtime_error if the file cannot be opened. + */ + ClusterFileSink(SourceQueue *source, const std::filesystem::path &fname) + : m_source(source) { LOG(logDEBUG) << "ClusterFileSink: " - << "source: " << source->sink() - << ", file: " << fname.string(); - m_source = source->sink(); - m_thread = std::thread(&ClusterFileSink::process, this); + << "source: " << source << ", file: " << fname.string(); + // The file is open before the thread starts: the queue can already + // hold clusters, which the thread writes at once m_file.open(fname, std::ios::binary); + if (!m_file.is_open()) { + throw std::runtime_error( + fmt::format("Could not open: {} for writing", fname.string())); + } + m_thread = std::thread(&ClusterFileSink::process, this); } + + /// As for a queue, with the sink queue of the cluster finder + ClusterFileSink(ClusterFinderMT *source, + const std::filesystem::path &fname) + : ClusterFileSink(source->sink(), fname) {} + + /// Stops the thread and closes the file, see stop() + ~ClusterFileSink() { stop(); } + + // The thread holds a pointer to this object + ClusterFileSink(const ClusterFileSink &) = delete; + ClusterFileSink &operator=(const ClusterFileSink &) = delete; + + /** + * @brief Stop the thread once the queue is empty and close the file. + * Does nothing if the sink is stopped. + */ void stop() { + if (!m_thread.joinable()) { + return; + } m_stop_requested = true; m_thread.join(); m_file.close(); } }; -} // namespace aare \ No newline at end of file +} // namespace aare diff --git a/include/aare/ClusterFinderMT.hpp b/include/aare/ClusterFinderMT.hpp index f5e19844..6920444d 100644 --- a/include/aare/ClusterFinderMT.hpp +++ b/include/aare/ClusterFinderMT.hpp @@ -91,6 +91,9 @@ class ClusterFinderMT { private: std::atomic m_stop_requested{false}; std::atomic m_processing_threads_stopped{true}; + // Set by the destructor only: the threads leave their frames and + // clusters where they are instead of waiting for room in the queues + std::atomic m_discard_requested{false}; /** * @brief Function called by the processing threads. It reads the frames @@ -102,7 +105,7 @@ class ClusterFinderMT { auto *pool = m_frame_pools[thread_id].get(); Backoff backoff; - while (!m_stop_requested || !q->isEmpty()) { + while (!m_discard_requested && (!m_stop_requested || !q->isEmpty())) { if (FrameRef *ref = q->frontPtr(); ref != nullptr) { backoff.reset(); auto view = (*pool)[ref->slot].view(); @@ -115,6 +118,9 @@ class ClusterFinderMT { auto clusters = cf->steal_clusters(true); while (!m_output_queues[thread_id]->write( std::move(clusters))) { + if (m_discard_requested) { + return; + } backoff.pause(); } break; @@ -155,12 +161,16 @@ class ClusterFinderMT { */ void collect() { Backoff backoff; - while (!m_stop_requested || !output_queues_are_empty() || - !m_processing_threads_stopped) { + while (!m_discard_requested && + (!m_stop_requested || !output_queues_are_empty() || + !m_processing_threads_stopped)) { bool moved_any = false; for (auto &queue : m_output_queues) { if (auto *front = queue->frontPtr(); front != nullptr) { while (!m_sink.write(std::move(*front))) { + if (m_discard_requested) { + return; + } backoff.pause(); } queue->popFront(); @@ -223,6 +233,25 @@ class ClusterFinderMT { start(); } + /** + * @brief Stop the threads without waiting for the frames and clusters + * that are still in the queues. + * + * Nothing can take the clusters from the sink once the finder is gone, + * and waiting for room in a sink that nobody empties would never end. + * Call stop() first, with something emptying the sink, to have every + * frame processed. Whatever takes clusters from the sink must be + * stopped or destroyed before the finder. + */ + ~ClusterFinderMT() { + m_discard_requested = true; + stop(); + } + + // The threads hold a pointer to this object + ClusterFinderMT(const ClusterFinderMT &) = delete; + ClusterFinderMT &operator=(const ClusterFinderMT &) = delete; + /** * @brief Return the sink queue where all the clusters are collected * @warning You need to empty this queue otherwise the cluster finder will @@ -233,9 +262,12 @@ class ClusterFinderMT { } /** - * @brief Start all processing threads + * @brief Start all processing threads. Does nothing if they are running. */ void start() { + if (!m_processing_threads_stopped) { + return; + } m_processing_threads_stopped = false; m_stop_requested = false; @@ -248,9 +280,13 @@ class ClusterFinderMT { } /** - * @brief Stop all processing threads + * @brief Stop all processing threads once they have finished the frames + * they were given. Does nothing if they are stopped. */ void stop() { + if (m_processing_threads_stopped) { + return; + } m_stop_requested = true; for (auto &thread : m_threads) { diff --git a/python/aare/ClusterFinder.py b/python/aare/ClusterFinder.py index d612fcb9..6f22001f 100644 --- a/python/aare/ClusterFinder.py +++ b/python/aare/ClusterFinder.py @@ -80,8 +80,13 @@ def ClusterCollector(clusterfindermt, dtype=np.int32): def ClusterFileSink(clusterfindermt, cluster_file, dtype=np.int32): """ - Factory function to create a ClusterCollector object. Provides a cleaner syntax for - the templated ClusterCollector in C++. + Factory function to create a ClusterFileSink object, which writes the + clusters of a ClusterFinderMT to a binary cluster file. Provides a cleaner + syntax for the templated ClusterFileSink in C++. + + The file is replaced if it exists and is complete once ``stop()`` has + returned or the sink is deleted. Raises ``RuntimeError`` if the file + cannot be opened. """ cls = _get_class("ClusterFileSink", clusterfindermt.cluster_size, dtype) diff --git a/python/src/bind_ClusterCollector.hpp b/python/src/bind_ClusterCollector.hpp index 815ca7e2..651bb8ba 100644 --- a/python/src/bind_ClusterCollector.hpp +++ b/python/src/bind_ClusterCollector.hpp @@ -29,8 +29,14 @@ void define_ClusterCollector(py::module &m, const std::string &typestr) { using ClusterType = Cluster; py::class_>(m, class_name.c_str()) - .def(py::init *>()) - .def("stop", &ClusterCollector::stop) + // The collector thread reads the sink of the finder + .def(py::init *>(), + py::keep_alive<1, 2>()) + .def("start", &ClusterCollector::start, + "Start the collector thread. Does nothing if it is running.") + .def("stop", &ClusterCollector::stop, + "Stop the collector thread once all clusters in the sink of " + "the finder are collected. Does nothing if it is stopped.") .def( "steal_clusters", [](ClusterCollector &self) { @@ -38,5 +44,9 @@ void define_ClusterCollector(py::module &m, const std::string &typestr) { self.steal_clusters()); return v; // TODO change!!! }, - py::return_value_policy::take_ownership); + py::return_value_policy::take_ownership, + "Take the clusters collected since the last call, one " + "ClusterVector per frame. Can be called while the collector is " + "running; call sync() on the finder first to get the clusters " + "of every frame given to it so far."); } diff --git a/python/src/bind_ClusterFileSink.hpp b/python/src/bind_ClusterFileSink.hpp index b6892b1c..5b79b81d 100644 --- a/python/src/bind_ClusterFileSink.hpp +++ b/python/src/bind_ClusterFileSink.hpp @@ -29,7 +29,12 @@ void define_ClusterFileSink(py::module &m, const std::string &typestr) { // TODO! adapt to set pedestal type (needs templating of ClusterFileSink) // or maybe access through base class? py::class_>(m, class_name.c_str()) + // The sink thread reads the sink queue of the finder .def(py::init *, - const std::filesystem::path &>()) - .def("stop", &ClusterFileSink::stop); + const std::filesystem::path &>(), + py::keep_alive<1, 2>()) + .def("stop", &ClusterFileSink::stop, + "Stop the sink thread once all clusters in the sink queue of " + "the finder are written, and close the file. Does nothing if " + "the sink is stopped."); } diff --git a/python/tests/test_ClusterFinderMT.py b/python/tests/test_ClusterFinderMT.py new file mode 100644 index 00000000..c26b15fe --- /dev/null +++ b/python/tests/test_ClusterFinderMT.py @@ -0,0 +1,148 @@ +# SPDX-License-Identifier: MPL-2.0 + +import numpy as np +import pytest + +from aare import ClusterCollector, ClusterFile, ClusterFileSink, ClusterFinderMT + +SHAPE = (10, 12) +N_SAMPLES = 8 +N_THREADS = 3 + + +def _finder_with_pedestal(): + finder = ClusterFinderMT( + SHAPE, n_sigma=5, n_threads=N_THREADS, min_pedestal_samples=N_SAMPLES + ) + for i in range(N_SAMPLES): + value = 903 if i % 2 else 907 + finder.push_pedestal_frame(np.full(SHAPE, value, dtype=np.uint16)) + return finder + + +def _find(finder, frame_numbers): + frame = np.full(SHAPE, 905, dtype=np.uint16) + frame[4, 5] += 300 + for frame_number in frame_numbers: + finder.find_clusters(frame, frame_number) + + +def _frame_numbers(cluster_vectors): + return sorted(clusters.frame_number for clusters in cluster_vectors) + + +def test_clusters_can_be_stolen_from_a_running_collector(): + finder = _finder_with_pedestal() + collector = ClusterCollector(finder) + + # After sync() the collector has one ClusterVector for each data frame + _find(finder, range(12)) + finder.sync() + assert _frame_numbers(collector.steal_clusters()) == list(range(12)) + + # Stolen clusters are gone, later ones are still collected + _find(finder, range(12, 20)) + finder.sync() + assert _frame_numbers(collector.steal_clusters()) == list(range(12, 20)) + + finder.stop() + collector.stop() + assert len(collector.steal_clusters()) == 0 + + +def test_collector_can_be_started_again(): + finder = _finder_with_pedestal() + collector = ClusterCollector(finder) + + _find(finder, range(4)) + finder.sync() + collector.stop() + collector.stop() + + collector.start() + collector.start() + _find(finder, range(4, 8)) + finder.sync() + assert _frame_numbers(collector.steal_clusters()) == list(range(8)) + + finder.stop() + collector.stop() + + +def test_collector_can_be_dropped_without_stop(): + finder = _finder_with_pedestal() + collector = ClusterCollector(finder) + _find(finder, range(4)) + finder.sync() + # The collector keeps the finder alive and stops its own thread + del finder + del collector + + +def _frame_numbers_in(path): + with ClusterFile(path) as file: + frame_numbers = [] + while (clusters := file.read_frame()) is not None: + frame_numbers.append(clusters.frame_number) + return sorted(frame_numbers) + + +def test_file_sink_writes_the_clusters_of_all_frames(tmp_path): + path = tmp_path / "clusters.clust" + finder = _finder_with_pedestal() + sink = ClusterFileSink(finder, path) + _find(finder, range(20)) + finder.stop() + sink.stop() + sink.stop() + assert _frame_numbers_in(path) == list(range(20)) + + +def test_file_sink_writes_clusters_found_before_it_was_created(tmp_path): + path = tmp_path / "clusters.clust" + finder = _finder_with_pedestal() + _find(finder, range(20)) + finder.stop() + sink = ClusterFileSink(finder, path) + sink.stop() + assert _frame_numbers_in(path) == list(range(20)) + + +def test_file_sink_can_be_dropped_without_stop(tmp_path): + path = tmp_path / "clusters.clust" + finder = _finder_with_pedestal() + sink = ClusterFileSink(finder, path) + _find(finder, range(20)) + finder.sync() + # The sink keeps the finder alive, stops its own thread and closes the + # file + del finder + del sink + assert _frame_numbers_in(path) == list(range(20)) + + +def test_file_sink_raises_if_the_file_cannot_be_opened(tmp_path): + finder = _finder_with_pedestal() + with pytest.raises(RuntimeError, match="Could not open"): + ClusterFileSink(finder, tmp_path / "missing" / "clusters.clust") + finder.stop() + + +def test_running_finder_can_be_dropped(): + finder = _finder_with_pedestal() + _find(finder, range(20)) + del finder + + +def test_finder_start_and_stop_can_be_repeated(): + finder = _finder_with_pedestal() + collector = ClusterCollector(finder) + finder.start() + _find(finder, range(4)) + finder.stop() + finder.stop() + finder.start() + _find(finder, range(4, 8)) + finder.stop() + collector.stop() + assert _frame_numbers(collector.steal_clusters()) == list(range(8)) diff --git a/src/ClusterFileSink.test.cpp b/src/ClusterFileSink.test.cpp new file mode 100644 index 00000000..c46541f7 --- /dev/null +++ b/src/ClusterFileSink.test.cpp @@ -0,0 +1,179 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/ClusterFileSink.hpp" +#include "aare/Cluster.hpp" +#include "aare/ClusterFile.hpp" +#include "aare/ClusterFinderMT.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace aare; + +namespace { + +using SinkCluster = Cluster; +using SinkQueue = ProducerConsumerQueue>; + +class TemporarySinkFile { + std::filesystem::path m_path; + + public: + TemporarySinkFile() { + const auto unique = + std::chrono::steady_clock::now().time_since_epoch().count(); + m_path = + std::filesystem::temp_directory_path() / + ("aare-cluster-file-sink-" + std::to_string(unique) + ".clust"); + } + TemporarySinkFile(const TemporarySinkFile &) = delete; + TemporarySinkFile &operator=(const TemporarySinkFile &) = delete; + ~TemporarySinkFile() { + std::error_code error; + std::filesystem::remove(m_path, error); + } + const std::filesystem::path &path() const { return m_path; } +}; + +// Frame with n_clusters clusters whose values are given by the frame number +ClusterVector make_frame(int32_t frame_number, size_t n_clusters) { + ClusterVector clusters(n_clusters, frame_number); + for (size_t i = 0; i < n_clusters; ++i) { + SinkCluster cluster{}; + cluster.x = static_cast(frame_number); + cluster.y = static_cast(i); + std::fill(std::begin(cluster.data), std::end(cluster.data), + frame_number * 10 + static_cast(i)); + clusters.push_back(cluster); + } + return clusters; +} + +// Frame i of the file must be make_frame(first + i, i % 3) +void check_file(const std::filesystem::path &path, int32_t first, + int32_t n_frames) { + ClusterFile file(path); + for (int32_t i = 0; i < n_frames; ++i) { + const auto read = file.read_frame(); + REQUIRE(read.has_value()); + const auto expected = make_frame(first + i, static_cast(i % 3)); + CHECK(read->frame_number() == expected.frame_number()); + REQUIRE(read->size() == expected.size()); + for (size_t j = 0; j < expected.size(); ++j) { + CHECK((*read)[j].x == expected[j].x); + CHECK((*read)[j].y == expected[j].y); + CHECK(std::equal(std::begin((*read)[j].data), + std::end((*read)[j].data), + std::begin(expected[j].data))); + } + } + CHECK_FALSE(file.read_frame().has_value()); +} + +} // namespace + +TEST_CASE("cluster file sink writes the clusters queued before it started") { + TemporarySinkFile file; + SinkQueue source(8); + for (int32_t i = 0; i < 5; ++i) { + REQUIRE(source.write(make_frame(1 + i, static_cast(i % 3)))); + } + + ClusterFileSink sink(&source, file.path()); + sink.stop(); + + CHECK(source.isEmpty()); + check_file(file.path(), 1, 5); +} + +TEST_CASE("cluster file sink writes the clusters queued while it runs") { + TemporarySinkFile file; + SinkQueue source(8); + ClusterFileSink sink(&source, file.path()); + + for (int32_t i = 0; i < 40; ++i) { + auto frame = make_frame(1 + i, static_cast(i % 3)); + while (!source.write(std::move(frame))) { + std::this_thread::yield(); + } + } + sink.stop(); + sink.stop(); // stopped: does nothing + + check_file(file.path(), 1, 40); +} + +TEST_CASE("cluster file sink stops and closes the file when destroyed") { + TemporarySinkFile file; + SinkQueue source(8); + { + ClusterFileSink sink(&source, file.path()); + for (int32_t i = 0; i < 5; ++i) { + REQUIRE( + source.write(make_frame(1 + i, static_cast(i % 3)))); + } + } + CHECK(source.isEmpty()); + check_file(file.path(), 1, 5); + + static_assert(!std::is_copy_constructible_v>); + static_assert(!std::is_move_constructible_v>); +} + +TEST_CASE("cluster file sink throws if the file cannot be opened") { + TemporarySinkFile file; + SinkQueue source(8); + REQUIRE(source.write(make_frame(1, 1))); + + // The file name is used as a directory that does not exist + CHECK_THROWS_AS( + ClusterFileSink(&source, file.path() / "clusters.clust"), + std::runtime_error); + // Nothing was taken from the queue + CHECK_FALSE(source.isEmpty()); +} + +TEST_CASE("cluster file sink writes the clusters of a cluster finder") { + TemporarySinkFile file; + const size_t min_pedestal_samples = 4; + const Shape<2> image_size{10, 10}; + const int32_t n_frames = 30; + + ClusterFinderMT finder(image_size, 5, 200, 3, 16, + min_pedestal_samples); + ClusterFileSink sink(&finder, file.path()); + + NDArray low(image_size, 98); + NDArray high(image_size, 102); + NDArray hit(image_size, 100); + hit(5, 5) = 130; + for (size_t i = 0; i < min_pedestal_samples / 2; ++i) { + finder.push_pedestal_frame(low.view()); + finder.push_pedestal_frame(high.view()); + } + for (int32_t i = 0; i < n_frames; ++i) { + finder.find_clusters(hit.view(), static_cast(i)); + } + finder.stop(); + sink.stop(); + + ClusterFile reader(file.path()); + std::vector frame_numbers; + while (auto frame = reader.read_frame()) { + REQUIRE(frame->size() == 1); + CHECK((*frame)[0].x == 5); + CHECK((*frame)[0].y == 5); + frame_numbers.push_back(frame->frame_number()); + } + std::sort(frame_numbers.begin(), frame_numbers.end()); + REQUIRE(frame_numbers.size() == static_cast(n_frames)); + for (int32_t i = 0; i < n_frames; ++i) { + CHECK(frame_numbers[static_cast(i)] == i); + } +} diff --git a/src/ClusterFinderMT.test.cpp b/src/ClusterFinderMT.test.cpp index 6973d0df..ef0426ff 100644 --- a/src/ClusterFinderMT.test.cpp +++ b/src/ClusterFinderMT.test.cpp @@ -7,9 +7,14 @@ #include "test_config.hpp" +#include #include +#include #include #include +#include +#include +#include using namespace aare; @@ -223,3 +228,184 @@ TEST_CASE("cluster collector drains queued clusters when stopped") { CHECK(clusters[i].frame_number() == static_cast(i + 1)); } } + +TEST_CASE("clusters can be stolen from a running cluster collector") { + using ClusterType = Cluster; + ProducerConsumerQueue> source(8); + ClusterCollector collector(&source); + + const auto write_frames = [&source](uint64_t first, uint64_t last) { + for (uint64_t frame_number = first; frame_number <= last; + ++frame_number) { + REQUIRE(source.write(ClusterVector(4, frame_number))); + } + while (!source.isEmpty()) { + std::this_thread::yield(); + } + }; + + CHECK(collector.steal_clusters().empty()); + + write_frames(1, 3); + auto clusters = collector.steal_clusters(); + REQUIRE(clusters.size() == 3); + for (size_t i = 0; i < clusters.size(); ++i) { + CHECK(clusters[i].frame_number() == static_cast(i + 1)); + } + + // Stolen clusters are gone, later ones are still collected + write_frames(4, 5); + clusters = collector.steal_clusters(); + REQUIRE(clusters.size() == 2); + CHECK(clusters[0].frame_number() == 4); + CHECK(clusters[1].frame_number() == 5); + + collector.stop(); + CHECK(collector.steal_clusters().empty()); +} + +TEST_CASE("sync gives a running collector the clusters of all frames") { + using ClusterType = Cluster; + + const size_t n_threads = 3; + const size_t min_pedestal_samples = 4; + const size_t frames_per_round = 50; + const Shape<2> image_size{10, 10}; + + ClusterFinderMT cf(image_size, 5, 200, n_threads, 16, + min_pedestal_samples); + ClusterCollector collector(&cf); + + NDArray low(image_size, 98); + NDArray high(image_size, 102); + NDArray hit(image_size, 100); + hit(5, 5) = 130; + + for (size_t i = 0; i < min_pedestal_samples / 2; ++i) { + cf.push_pedestal_frame(low.view()); + cf.push_pedestal_frame(high.view()); + } + + uint64_t frame_number = 0; + for (int round = 0; round < 3; ++round) { + for (size_t i = 0; i < frames_per_round; ++i) { + cf.find_clusters(hit.view(), frame_number++); + } + cf.sync(); + + auto clusters = collector.steal_clusters(); + REQUIRE(clusters.size() == frames_per_round); + std::vector frame_numbers; + for (const auto &frame_clusters : clusters) { + CHECK(frame_clusters.size() == 1); + frame_numbers.push_back(frame_clusters.frame_number()); + } + std::sort(frame_numbers.begin(), frame_numbers.end()); + const auto first = static_cast(frame_number) - + static_cast(frames_per_round); + for (size_t i = 0; i < frame_numbers.size(); ++i) { + CHECK(frame_numbers[i] == first + static_cast(i)); + } + } + + cf.stop(); + collector.stop(); + CHECK(collector.steal_clusters().empty()); +} + +TEST_CASE("cluster collector can be started again after a stop") { + using ClusterType = Cluster; + ProducerConsumerQueue> source(8); + ClusterCollector collector(&source); + collector.start(); // running: does nothing + + REQUIRE(source.write(ClusterVector(4, 1))); + collector.stop(); + collector.stop(); // stopped: does nothing + CHECK(source.isEmpty()); + + // Nothing is taken from the queue while stopped + REQUIRE(source.write(ClusterVector(4, 2))); + std::this_thread::sleep_for(std::chrono::milliseconds(5)); + CHECK_FALSE(source.isEmpty()); + + collector.start(); + REQUIRE(source.write(ClusterVector(4, 3))); + collector.stop(); + + // Clusters from before the stop are kept + auto clusters = collector.steal_clusters(); + REQUIRE(clusters.size() == 3); + for (size_t i = 0; i < clusters.size(); ++i) { + CHECK(clusters[i].frame_number() == static_cast(i + 1)); + } +} + +TEST_CASE("cluster collector stops its thread when destroyed") { + using ClusterType = Cluster; + ProducerConsumerQueue> source(8); + { + ClusterCollector collector(&source); + REQUIRE(source.write(ClusterVector(4, 1))); + } + // The destructor waits for the queue to be empty, as stop() does + CHECK(source.isEmpty()); + + static_assert(!std::is_copy_constructible_v>); + static_assert(!std::is_move_constructible_v>); +} + +TEST_CASE("running cluster finder can be destroyed") { + using ClusterType = Cluster; + const Shape<2> image_size{10, 10}; + NDArray frame(image_size, 100); + + { + ClusterFinderMT cf(image_size); + } + { + ClusterFinderMT cf(image_size, 5, 16, 3, 16, 2); + cf.push_pedestal_frame(frame.view()); + cf.push_pedestal_frame(frame.view()); + cf.find_clusters(frame.view()); + } + { + // Stopped: the destructor has nothing to do + ClusterFinderMT cf(image_size); + cf.stop(); + cf.stop(); + } + { + ClusterFinderMT cf(image_size); + cf.start(); // running: does nothing + cf.stop(); + cf.start(); + } + + static_assert(!std::is_copy_constructible_v>); + static_assert(!std::is_move_constructible_v>); +} + +TEST_CASE("cluster finder with a full sink can be destroyed") { + using ClusterType = Cluster; + const size_t n_threads = 3; + const Shape<2> image_size{10, 10}; + NDArray frame(image_size, 100); + + ClusterFinderMT cf(image_size, 5, 16, n_threads, 16, 2); + cf.push_pedestal_frame(frame.view()); + cf.push_pedestal_frame(frame.view()); + + // Nothing empties the sink, so it fills up, then the queues of the + // threads, and the threads wait for room. With 1000 cluster vectors in + // the sink and 200 in the queue of each thread, these frames leave + // every thread waiting without blocking find_clusters(). stop() would + // wait forever, the destructor must not. + const size_t n_frames = 1000 + n_threads * 200 + n_threads * 4; + for (size_t i = 0; i < n_frames; ++i) { + cf.find_clusters(frame.view(), i); + } + while (!cf.sink()->isFull()) { + std::this_thread::yield(); + } +}