refactored to use a BufferPool

This commit is contained in:
mazzol_a committed 2026-10-27 22:13:44 +01:00
1 parent 9738c6c19f
commit fe37c0a9e9
6 files changed
+208 -128

No files matched your search

+3 -1
View File
@@ -18,7 +18,9 @@
before any ROI. Gap pixels receive a fill value or, with
``split_counts``, half of the neighbouring double size pixel.
- Added ``mean_current_source`` to read current source Jungfrau data and evarge the values over several acquisitions.
- Added ``mean_over_dataset`` to calculate the mean over several acquisitions in a Datasets.
- Added ``block_mean`` to calculate the mean over several blocked acquisitions in a datasets.
- Added ``MultiThreadedFileReader::read_into(destination, n_frames)`` to read an
exact number of frames in C++.
- ``RawFile`` takes a ``GapPixels`` configuration, in Python the
``gap_pixels`` argument, and inserts gap pixels while frames are
assembled. ``rows()``, ``cols()`` and every returned frame then include
+3 -18
View File
@@ -3,29 +3,14 @@
#include "aare/DataSetAggregation.hpp"
#include <filesystem>
/*
constexpr ssize_t size = 1024;
class JungfrauTestDataSet : public benchmark::Fixture {
public:
std::filesystem::path file_path =
std::filesystem::path("/home/mazzol_a/Documents/temp_jungfrau/"
"CS_M749_2026-05-19_HGOG1G2_000000.dat");
void SetUp(::benchmark::State &state) {}
// void TearDown(::benchmark::State& state) {
// }
};
*/
static void DatasetAggregation_MeanOverDataset(benchmark::State &st) {
const std::filesystem::path file_path =
"/home/mazzol_a/Documents/temp_jungfrau/"
"/mnt/sls_det_storage/jungfrau_calib/data/Module_749_Calib/"
"BP_M749_2026-05-19_HGOG1G2_000000.dat";
for (auto _ : st) {
aare::NDArray<uint16_t, 3> res =
aare::block_mean<uint16_t>(file_path, 220, 100, 16);
aare::block_mean<uint16_t>(file_path, 220, 100);
benchmark::DoNotOptimize(res);
}
@@ -33,7 +18,7 @@ static void DatasetAggregation_MeanOverDataset(benchmark::State &st) {
static void DatasetAggregation_MeanCurrentSource(benchmark::State &st) {
const std::filesystem::path file_path =
"/home/mazzol_a/Documents/temp_jungfrau/"
"/mnt/sls_det_storage/jungfrau_calib/data/Module_749_Calib/"
"CS_M749_2026-05-19_HGOG1G2_000000.dat";
for (auto _ : st) {
+177 -92
View File
@@ -14,25 +14,152 @@
namespace aare {
/**
* @brief Compute the block mean over several frames per sample stored in a file
* @brief Ring buffer of slots shared between one producer and a fixed number
* of consumers. Item i is stored in slot i % size(). The producer can only
* overwrite a slot once all consumers released the item stored in it, and a
* consumer can only read item i once the producer committed it.
* Calling abort() wakes up all waiting threads.
*/
template <typename ItemType> class BufferPool {
public:
/**
* @param size number of slots in the pool
* @param num_consumers number of consumers that read every item
* @param initializer callable returning the initial ItemType of a slot
*/
template <typename Func>
BufferPool(size_t size, size_t num_consumers, Func initializer)
: m_num_consumers(num_consumers), m_item_in_slot(size, no_item),
m_pending_consumers(size, 0) {
if (size == 0)
throw std::invalid_argument("BufferPool size must be at least 1");
m_buffers.reserve(size);
for (size_t i = 0; i < size; ++i) {
m_buffers.emplace_back(initializer());
}
}
/// @brief Get the number of slots in the buffer pool.
/// @return The number of slots in the buffer pool.
size_t size() const { return m_buffers.size(); }
/**
* @brief Block until the slot of item i is free (e.g. all consumers have
* read it) to be written.
* @return the buffer to write item i into or nullptr if aborted
*/
ItemType *acquire_write(size_t i) {
const size_t slot = i % size();
std::unique_lock<std::mutex> lock(m_mtx);
m_cv_free.wait(
lock, [&] { return m_abort || m_pending_consumers[slot] == 0; });
if (m_abort)
return nullptr;
return &m_buffers[slot];
}
/**
* @brief Mark item i as written and wake up the consumers.
*/
void commit_write(size_t i) {
const size_t slot = i % size();
{
std::lock_guard<std::mutex> lock(m_mtx);
m_item_in_slot[slot] = i;
m_pending_consumers[slot] = m_num_consumers;
}
m_cv_loaded.notify_all();
}
/**
* @brief Block until item i has been written.
* @return the buffer holding item i or nullptr if aborted
*/
const ItemType *acquire_read(size_t i) {
const size_t slot = i % size();
std::unique_lock<std::mutex> lock(m_mtx);
m_cv_loaded.wait(lock,
[&] { return m_abort || m_item_in_slot[slot] == i; });
if (m_abort)
return nullptr;
return &m_buffers[slot];
}
/**
* @brief Signal that this consumer no longer needs item i. Once all
* consumers released it the slot can be reused by the producer.
*/
void release_read(size_t i) {
const size_t slot = i % size();
bool slot_free = false;
{
std::lock_guard<std::mutex> lock(m_mtx);
slot_free = --m_pending_consumers[slot] == 0;
}
if (slot_free)
m_cv_free.notify_one();
}
/**
* @brief Wake up all waiting threads, acquire_* returns nullptr from now
* on.
*/
void abort() {
{
std::lock_guard<std::mutex> lock(m_mtx);
m_abort = true;
}
m_cv_loaded.notify_all();
m_cv_free.notify_all();
}
private:
size_t m_num_consumers;
std::vector<ItemType> m_buffers;
static constexpr size_t no_item = std::numeric_limits<size_t>::max();
// per slot:
/// @brief Index of the item currently committed to the slot.
std::vector<size_t> m_item_in_slot; // store the item - boolean flag need to
// set back to false ->
std::vector<size_t> m_pending_consumers;
std::mutex m_mtx;
/// @brief Condition variable to notify consumers that an item has been
/// loaded.
std::condition_variable m_cv_loaded;
/// @brief Condition variable to notify producers that a slot is free to
/// overwrite.
std::condition_variable m_cv_free;
/// @brief Flag to indicate if the buffer pool should be aborted.
bool m_abort{false};
};
/**
* @brief Compute the block mean over several frames per sample stored in a
* file. Function spawns num_processing_threads + num_reader_threads + 1 threads
* in total.
* @tparam FRAME_TYPE The type of the frames in the dataset.
* @param path The path to the file containing the dataset.
* @param num_samples The number of samples in the dataset.
* @param mean_over_num_frames The number of frames per sample to take mean
* over.
* @param num_threads The number of threads to use for parallel computation.
* One thread reads the frames, the remaining threads each process a shard of
* rows.
* @param num_reader_threads The number of file workers the reader thread uses
* to load the frames of one sample in parallel.
* @param num_processing_threads The number of threads to use for parallel
* computation. One thread reads the frames, the remaining threads each process
* a shard of rows. (default 12)
* @param num_reader_threads The number of file workers the reader thread
* uses to load the frames of one sample in parallel. (default 8)
* @return An NDArray containing the mean frame stored as double for each
* sample.
*/
template <typename FRAME_TYPE>
NDArray<double, 3>
block_mean(const std::filesystem::path &path, const size_t num_samples,
const size_t mean_over_num_frames, const int num_threads = 12,
const size_t num_reader_threads = 8) {
NDArray<double, 3> block_mean(const std::filesystem::path &path,
const size_t num_samples,
const size_t mean_over_num_frames,
const size_t num_processing_threads = 12,
const size_t num_reader_threads = 8) {
size_t rows = 0;
size_t cols = 0;
@@ -49,8 +176,9 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
static_cast<ssize_t>(cols),
static_cast<ssize_t>(num_samples)});
if (num_threads < 1)
throw std::invalid_argument("num_threads must be at least 1");
if (num_processing_threads < 1)
throw std::invalid_argument(
"num_processing_threads must be at least 1");
if (num_reader_threads < 1)
throw std::invalid_argument("num_reader_threads must be at least 1");
@@ -62,42 +190,16 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
const double inv_n = 1.0 / static_cast<double>(mean_over_num_frames);
// One reader thread loads all frames of a sample into a ring buffer slot,
// splitting the read over num_reader_threads file workers, while the
// worker threads each compute the mean for their own shard of rows.
// Reading the next samples overlaps with processing the current one.
constexpr size_t num_buffers = 3;
constexpr size_t num_buffers =
4; // TODO: random for now reading much slower - small buffer is enough
const size_t num_workers =
std::min(std::max<size_t>(1, static_cast<size_t>(num_threads) - 1),
std::max<size_t>(1, rows));
std::vector<NDArray<FRAME_TYPE, 3>> buffers;
buffers.reserve(num_buffers);
for (size_t b = 0; b < num_buffers; ++b) {
buffers.emplace_back(std::array<ssize_t, 3>{
static_cast<ssize_t>(mean_over_num_frames),
static_cast<ssize_t>(rows), static_cast<ssize_t>(cols)});
}
// per slot: sample currently loaded and number of workers still using it
constexpr size_t no_sample = std::numeric_limits<size_t>::max();
std::vector<size_t> loaded_sample(num_buffers, no_sample);
std::vector<size_t> pending_workers(num_buffers, 0);
bool abort = false;
std::mutex mtx;
std::condition_variable cv_loaded;
std::condition_variable cv_free;
auto set_abort = [&]() {
{
std::lock_guard<std::mutex> lock(mtx);
abort = true;
}
cv_loaded.notify_all();
cv_free.notify_all();
};
BufferPool<NDArray<FRAME_TYPE, 3>> buffers(
num_buffers, num_processing_threads,
[&mean_over_num_frames, &rows, &cols] {
return NDArray<FRAME_TYPE, 3>(std::array<ssize_t, 3>{
static_cast<ssize_t>(mean_over_num_frames),
static_cast<ssize_t>(rows), static_cast<ssize_t>(cols)});
});
auto reader = [&]() {
try {
@@ -107,29 +209,19 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
ceil_div(mean_over_num_frames, num_reader_threads));
for (size_t i = 0; i < num_samples; ++i) {
const size_t slot = i % num_buffers;
{
std::unique_lock<std::mutex> lock(mtx);
cv_free.wait(lock, [&] {
return abort || pending_workers[slot] == 0;
});
if (abort)
return;
}
NDArray<FRAME_TYPE, 3> *buffer = buffers.acquire_write(i);
if (!buffer)
throw std::runtime_error(
"Failed to acquire buffer for writing");
file_reader.read_into(
reinterpret_cast<std::byte *>(buffers[slot].data()),
reinterpret_cast<std::byte *>(buffer->data()),
mean_over_num_frames);
{
std::lock_guard<std::mutex> lock(mtx);
loaded_sample[slot] = i;
pending_workers[slot] = num_workers;
}
cv_loaded.notify_all();
buffers.commit_write(i);
}
} catch (...) {
set_abort();
buffers.abort(); // wake up the other threads so they can exit
throw;
}
};
@@ -141,19 +233,14 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
std::vector<double> sum(shard_size);
for (size_t i = 0; i < num_samples; ++i) {
const size_t slot = i % num_buffers;
{
std::unique_lock<std::mutex> lock(mtx);
cv_loaded.wait(lock, [&] {
return abort || loaded_sample[slot] == i;
});
if (abort)
return;
}
const NDArray<FRAME_TYPE, 3> *buffer = buffers.acquire_read(i);
if (!buffer)
throw std::runtime_error(
"Failed to acquire buffer for reading");
std::fill(sum.begin(), sum.end(), 0.0);
const FRAME_TYPE *src = buffers[slot].data() + row_begin * cols;
const FRAME_TYPE *src = buffer->data() + row_begin * cols;
for (size_t f = 0; f < mean_over_num_frames; ++f) {
const FRAME_TYPE *frame = src + f * rows * cols;
for (size_t k = 0; k < shard_size; ++k) {
@@ -161,37 +248,34 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
}
}
bool slot_free = false;
{
std::lock_guard<std::mutex> lock(mtx);
slot_free = --pending_workers[slot] == 0;
}
if (slot_free)
cv_free.notify_one();
// buffer slot is no longer needed, write output after
// release
buffers.release_read(i);
// buffer slot is no longer needed, write output after release
for (size_t r = row_begin; r < row_end; ++r) {
size_t local_row = r - row_begin;
for (size_t c = 0; c < cols; ++c) {
mean_per_sample(r, c, i) =
sum[(r - row_begin) * cols + c] * inv_n;
sum[local_row * cols + c] * inv_n;
}
}
}
} catch (...) {
set_abort();
buffers.abort(); // wake up the other threads so they can exit
throw;
}
};
std::vector<std::future<void>> futures;
futures.reserve(num_workers + 1);
futures.reserve(num_processing_threads + 1);
futures.push_back(std::async(std::launch::async, reader));
const size_t rows_per_worker = rows / num_workers;
for (size_t w = 0; w < num_workers; ++w) {
size_t row_end =
(w == num_workers - 1) ? rows : (w + 1) * rows_per_worker;
const size_t rows_per_worker = rows / num_processing_threads;
for (size_t w = 0; w < num_processing_threads; ++w) {
size_t row_end = (w == num_processing_threads - 1)
? rows
: (w + 1) * rows_per_worker;
futures.push_back(std::async(std::launch::async, worker,
w * rows_per_worker, row_end));
}
@@ -211,13 +295,14 @@ block_mean(const std::filesystem::path &path, const size_t num_samples,
/**
* @brief Compute the mean current source data from a Jungfrau detector file
* @param path The path to the Jungfrau detector file.
* @param num_samples The number of samples in the dataset e.g. exposure times
* @param num_samples The number of samples in the dataset e.g. exposure
times
* @param mean_over_num_frames The number of frames to mean over for each
sample.
* @param num_threads The number of threads to use for parallel computation.
* @param file_offset The offset in the file to start reading from.
* @return An NDArray containing the mean current source data stored as double
for each sample. (rows, cols, num_samples)
* @return An NDArray containing the mean current source data stored as
double for each sample. (rows, cols, num_samples)
*/
NDArray<double, 3> mean_current_source(const std::filesystem::path &path,
+13 -8
View File
@@ -13,24 +13,29 @@ template <typename FRAME_TYPE>
void bind_DataSetAggregation(pybind11::module_ &m) {
m.def(
"block_mean",
[](const std::filesystem::path &path, size_t num_samples,
size_t mean_over_num_frames, int num_threads) {
[](const std::filesystem::path &path, const size_t num_samples,
const size_t mean_over_num_frames,
const size_t num_processing_threads,
const size_t num_reader_threads) {
auto result = new NDArray<double, 3>(block_mean<FRAME_TYPE>(
path, num_samples, mean_over_num_frames, num_threads));
path, num_samples, mean_over_num_frames, num_processing_threads,
num_reader_threads));
return return_image_data(result);
},
py::arg("path"), py::arg("num_samples"),
py::arg("mean_over_num_frames"), py::arg("num_threads") = 16,
py::arg("path"), py::kw_only(), py::arg("num_samples"),
py::arg("mean_over_num_frames"), py::arg("num_processing_threads") = 12,
py::arg("num_reader_threads") = 8,
R"pbdoc(
Compute the block mean over several frames per sample stored in a file.
Function spawns num_processing_threads + num_reader_threads + 1 threads in total.
Parameters:
-----------
path (str): The path to the file containing the dataset.
num_samples (int): The number of samples in the dataset.
mean_over_num_frames (int): The number of frames per sample to take mean over.
num_threads (int, optional): The number of threads to use for parallel computation. Defaults to 16.
num_processing_threads (int, optional): The number of threads to use for parallel computation. One thread reads, the others compute the mean. Defaults to 12.
num_reader_threads (int, optional): The number of file workers the reader thread uses to load each sample. Defaults to 8.
Returns:
--------
np.ndarray: A numpy array containing the mean frame stored as np.float64 for each sample with shape (rows, cols, num_samples).
@@ -47,7 +52,7 @@ void bind_read_current_source(pybind11::module_ &m) {
num_threads, file_offset));
return return_image_data(result);
},
py::arg("path"), py::arg("num_samples"),
py::arg("path"), py::kw_only(), py::arg("num_samples"),
py::arg("mean_over_num_frames"), py::arg("num_threads") = 16,
py::arg("file_offset") = 0,
R"pbdoc(
+5 -4
View File
@@ -7,16 +7,17 @@ from aare import block_mean, mean_current_source
def test_block_mean(create_temporary_jungfrau_files):
""" test block_mean """
rows, cols = 256, 256
num_samples = 100
num_frames_per_sample = 10
num_threads = 16
num_samples = 10
num_frames_per_sample = 100
num_processing_threads = 12
num_reader_threads = 8
file_system = create_temporary_jungfrau_files(
num_samples * num_frames_per_sample,
lambda frame: np.full((rows, cols), frame % num_frames_per_sample, dtype=np.uint16),
)
result = block_mean(file_system, num_samples, num_frames_per_sample, num_threads)
result = block_mean(file_system, num_samples = num_samples, mean_over_num_frames = num_frames_per_sample, num_processing_threads = num_processing_threads, num_reader_threads = num_reader_threads)
assert result.shape == (rows, cols, num_samples)
+7 -5
View File
@@ -13,9 +13,10 @@ TEST_CASE("mean_over_dataset", "[DataSetAggregation]") {
// Create a temporary Jungfrau data file with 2200 frames, each frame is a
const int num_samples = 100;
const int num_frames_per_sample = 10;
const int num_threads = 16;
const int num_samples = 10;
const int num_frames_per_sample = 100;
const int num_processing_threads = 12;
const int num_reader_threads = 8;
TemporaryJungfrauFiles temp_files(
num_samples * num_frames_per_sample, [](size_t frame) {
@@ -27,8 +28,9 @@ TEST_CASE("mean_over_dataset", "[DataSetAggregation]") {
const std::filesystem::path path = temp_files.file_path();
auto mean_result = block_mean<uint16_t>(path, num_samples,
num_frames_per_sample, num_threads);
auto mean_result =
block_mean<uint16_t>(path, num_samples, num_frames_per_sample,
num_processing_threads, num_reader_threads);
// Check the shape of the result
REQUIRE(mean_result.shape(0) == Jungfrau::nRows);