mirror of
https://github.com/slsdetectorgroup/aare.git
synced 2026-11-30 14:37:49 +01:00
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
This commit is contained in:
1 parent
22d19d4f45
commit
c7ccacbe92
11 files changed
+734
-42
No files matched your search
@@ -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
|
||||
|
||||
+24
@@ -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.
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
@@ -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 <typename ClusterType,
|
||||
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
|
||||
class ClusterCollector {
|
||||
@@ -21,19 +34,23 @@ class ClusterCollector {
|
||||
|
||||
SourceQueue *m_source;
|
||||
std::atomic<bool> m_stop_requested{false};
|
||||
std::atomic<bool> m_stopped{true};
|
||||
std::thread m_thread;
|
||||
std::mutex m_clusters_mutex; // guards m_clusters
|
||||
std::vector<ClusterVector<ClusterType>> m_clusters;
|
||||
|
||||
void process() {
|
||||
m_stopped.store(false, std::memory_order_release);
|
||||
fmt::print("ClusterCollector started\n");
|
||||
Backoff backoff;
|
||||
while (true) {
|
||||
if (ClusterVector<ClusterType> *clusters = m_source->frontPtr();
|
||||
clusters != nullptr) {
|
||||
backoff.reset();
|
||||
m_clusters.push_back(std::move(*clusters));
|
||||
{
|
||||
std::lock_guard<std::mutex> 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 <typename Finder,
|
||||
@@ -64,16 +78,54 @@ class ClusterCollector {
|
||||
explicit ClusterCollector(Finder *source)
|
||||
: ClusterCollector(source->sink()) {}
|
||||
|
||||
void stop() {
|
||||
m_stop_requested.store(true, std::memory_order_release);
|
||||
if (m_thread.joinable())
|
||||
m_thread.join();
|
||||
}
|
||||
std::vector<ClusterVector<ClusterType>> 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<ClusterVector<ClusterType>> steal_clusters() {
|
||||
std::vector<ClusterVector<ClusterType>> clusters;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_clusters_mutex);
|
||||
clusters.swap(m_clusters);
|
||||
}
|
||||
return clusters;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,28 +1,46 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
|
||||
#include <fmt/format.h>
|
||||
|
||||
#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 ClusterType,
|
||||
typename = std::enable_if_t<is_cluster_v<ClusterType>>,
|
||||
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
|
||||
class ClusterFileSink {
|
||||
ProducerConsumerQueue<ClusterVector<ClusterType>> *m_source;
|
||||
using SourceQueue = ProducerConsumerQueue<ClusterVector<ClusterType>>;
|
||||
|
||||
SourceQueue *m_source;
|
||||
std::atomic<bool> m_stop_requested{false};
|
||||
std::atomic<bool> 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<ClusterType> *clusters = m_source->frontPtr();
|
||||
@@ -44,24 +62,52 @@ class ClusterFileSink {
|
||||
}
|
||||
}
|
||||
LOG(logDEBUG) << "ClusterFileSink stopped";
|
||||
m_stopped = true;
|
||||
}
|
||||
|
||||
public:
|
||||
ClusterFileSink(ClusterFinderMT<ClusterType, uint16_t, double> *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<ClusterType, uint16_t, double> *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
|
||||
} // namespace aare
|
||||
@@ -91,6 +91,9 @@ class ClusterFinderMT {
|
||||
private:
|
||||
std::atomic<bool> m_stop_requested{false};
|
||||
std::atomic<bool> 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<bool> 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) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -29,8 +29,14 @@ void define_ClusterCollector(py::module &m, const std::string &typestr) {
|
||||
using ClusterType = Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>;
|
||||
|
||||
py::class_<ClusterCollector<ClusterType>>(m, class_name.c_str())
|
||||
.def(py::init<ClusterFinderMT<ClusterType, uint16_t, pd_type> *>())
|
||||
.def("stop", &ClusterCollector<ClusterType>::stop)
|
||||
// The collector thread reads the sink of the finder
|
||||
.def(py::init<ClusterFinderMT<ClusterType, uint16_t, pd_type> *>(),
|
||||
py::keep_alive<1, 2>())
|
||||
.def("start", &ClusterCollector<ClusterType>::start,
|
||||
"Start the collector thread. Does nothing if it is running.")
|
||||
.def("stop", &ClusterCollector<ClusterType>::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<ClusterType> &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.");
|
||||
}
|
||||
@@ -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_<ClusterFileSink<ClusterType>>(m, class_name.c_str())
|
||||
// The sink thread reads the sink queue of the finder
|
||||
.def(py::init<ClusterFinderMT<ClusterType, uint16_t, double> *,
|
||||
const std::filesystem::path &>())
|
||||
.def("stop", &ClusterFileSink<ClusterType>::stop);
|
||||
const std::filesystem::path &>(),
|
||||
py::keep_alive<1, 2>())
|
||||
.def("stop", &ClusterFileSink<ClusterType>::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.");
|
||||
}
|
||||
@@ -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))
|
||||
@@ -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 <algorithm>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
using namespace aare;
|
||||
|
||||
namespace {
|
||||
|
||||
using SinkCluster = Cluster<int32_t, 3, 3>;
|
||||
using SinkQueue = ProducerConsumerQueue<ClusterVector<SinkCluster>>;
|
||||
|
||||
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<SinkCluster> make_frame(int32_t frame_number, size_t n_clusters) {
|
||||
ClusterVector<SinkCluster> clusters(n_clusters, frame_number);
|
||||
for (size_t i = 0; i < n_clusters; ++i) {
|
||||
SinkCluster cluster{};
|
||||
cluster.x = static_cast<uint16_t>(frame_number);
|
||||
cluster.y = static_cast<uint16_t>(i);
|
||||
std::fill(std::begin(cluster.data), std::end(cluster.data),
|
||||
frame_number * 10 + static_cast<int32_t>(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<SinkCluster> 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<size_t>(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<size_t>(i % 3))));
|
||||
}
|
||||
|
||||
ClusterFileSink<SinkCluster> 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<SinkCluster> sink(&source, file.path());
|
||||
|
||||
for (int32_t i = 0; i < 40; ++i) {
|
||||
auto frame = make_frame(1 + i, static_cast<size_t>(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<SinkCluster> sink(&source, file.path());
|
||||
for (int32_t i = 0; i < 5; ++i) {
|
||||
REQUIRE(
|
||||
source.write(make_frame(1 + i, static_cast<size_t>(i % 3))));
|
||||
}
|
||||
}
|
||||
CHECK(source.isEmpty());
|
||||
check_file(file.path(), 1, 5);
|
||||
|
||||
static_assert(!std::is_copy_constructible_v<ClusterFileSink<SinkCluster>>);
|
||||
static_assert(!std::is_move_constructible_v<ClusterFileSink<SinkCluster>>);
|
||||
}
|
||||
|
||||
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<SinkCluster>(&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<SinkCluster> finder(image_size, 5, 200, 3, 16,
|
||||
min_pedestal_samples);
|
||||
ClusterFileSink<SinkCluster> sink(&finder, file.path());
|
||||
|
||||
NDArray<uint16_t, 2> low(image_size, 98);
|
||||
NDArray<uint16_t, 2> high(image_size, 102);
|
||||
NDArray<uint16_t, 2> 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<uint64_t>(i));
|
||||
}
|
||||
finder.stop();
|
||||
sink.stop();
|
||||
|
||||
ClusterFile<SinkCluster> reader(file.path());
|
||||
std::vector<int32_t> 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<size_t>(n_frames));
|
||||
for (int32_t i = 0; i < n_frames; ++i) {
|
||||
CHECK(frame_numbers[static_cast<size_t>(i)] == i);
|
||||
}
|
||||
}
|
||||
@@ -7,9 +7,14 @@
|
||||
|
||||
#include "test_config.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include <type_traits>
|
||||
#include <vector>
|
||||
|
||||
using namespace aare;
|
||||
|
||||
@@ -223,3 +228,184 @@ TEST_CASE("cluster collector drains queued clusters when stopped") {
|
||||
CHECK(clusters[i].frame_number() == static_cast<int32_t>(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("clusters can be stolen from a running cluster collector") {
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
ProducerConsumerQueue<ClusterVector<ClusterType>> source(8);
|
||||
ClusterCollector<ClusterType> 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<ClusterType>(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<int32_t>(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<int32_t, 3, 3>;
|
||||
|
||||
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<ClusterType> cf(image_size, 5, 200, n_threads, 16,
|
||||
min_pedestal_samples);
|
||||
ClusterCollector<ClusterType> collector(&cf);
|
||||
|
||||
NDArray<uint16_t, 2> low(image_size, 98);
|
||||
NDArray<uint16_t, 2> high(image_size, 102);
|
||||
NDArray<uint16_t, 2> 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<int32_t> 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<int32_t>(frame_number) -
|
||||
static_cast<int32_t>(frames_per_round);
|
||||
for (size_t i = 0; i < frame_numbers.size(); ++i) {
|
||||
CHECK(frame_numbers[i] == first + static_cast<int32_t>(i));
|
||||
}
|
||||
}
|
||||
|
||||
cf.stop();
|
||||
collector.stop();
|
||||
CHECK(collector.steal_clusters().empty());
|
||||
}
|
||||
|
||||
TEST_CASE("cluster collector can be started again after a stop") {
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
ProducerConsumerQueue<ClusterVector<ClusterType>> source(8);
|
||||
ClusterCollector<ClusterType> collector(&source);
|
||||
collector.start(); // running: does nothing
|
||||
|
||||
REQUIRE(source.write(ClusterVector<ClusterType>(4, 1)));
|
||||
collector.stop();
|
||||
collector.stop(); // stopped: does nothing
|
||||
CHECK(source.isEmpty());
|
||||
|
||||
// Nothing is taken from the queue while stopped
|
||||
REQUIRE(source.write(ClusterVector<ClusterType>(4, 2)));
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(5));
|
||||
CHECK_FALSE(source.isEmpty());
|
||||
|
||||
collector.start();
|
||||
REQUIRE(source.write(ClusterVector<ClusterType>(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<int32_t>(i + 1));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("cluster collector stops its thread when destroyed") {
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
ProducerConsumerQueue<ClusterVector<ClusterType>> source(8);
|
||||
{
|
||||
ClusterCollector<ClusterType> collector(&source);
|
||||
REQUIRE(source.write(ClusterVector<ClusterType>(4, 1)));
|
||||
}
|
||||
// The destructor waits for the queue to be empty, as stop() does
|
||||
CHECK(source.isEmpty());
|
||||
|
||||
static_assert(!std::is_copy_constructible_v<ClusterCollector<ClusterType>>);
|
||||
static_assert(!std::is_move_constructible_v<ClusterCollector<ClusterType>>);
|
||||
}
|
||||
|
||||
TEST_CASE("running cluster finder can be destroyed") {
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
const Shape<2> image_size{10, 10};
|
||||
NDArray<uint16_t, 2> frame(image_size, 100);
|
||||
|
||||
{
|
||||
ClusterFinderMT<ClusterType> cf(image_size);
|
||||
}
|
||||
{
|
||||
ClusterFinderMT<ClusterType> 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<ClusterType> cf(image_size);
|
||||
cf.stop();
|
||||
cf.stop();
|
||||
}
|
||||
{
|
||||
ClusterFinderMT<ClusterType> cf(image_size);
|
||||
cf.start(); // running: does nothing
|
||||
cf.stop();
|
||||
cf.start();
|
||||
}
|
||||
|
||||
static_assert(!std::is_copy_constructible_v<ClusterFinderMT<ClusterType>>);
|
||||
static_assert(!std::is_move_constructible_v<ClusterFinderMT<ClusterType>>);
|
||||
}
|
||||
|
||||
TEST_CASE("cluster finder with a full sink can be destroyed") {
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
const size_t n_threads = 3;
|
||||
const Shape<2> image_size{10, 10};
|
||||
NDArray<uint16_t, 2> frame(image_size, 100);
|
||||
|
||||
ClusterFinderMT<ClusterType> 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();
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user