diff --git a/CMakeLists.txt b/CMakeLists.txt index 84cdfcc0..40f268b0 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -442,7 +442,7 @@ if(AARE_TESTS) endif() if(AARE_VERBOSE) target_compile_definitions(aare_core PUBLIC AARE_VERBOSE) - target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logDEBUG5) + target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logDEBUG) else() target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logWARNING) endif() @@ -457,6 +457,7 @@ set_target_properties(aare_core PROPERTIES ARCHIVE_OUTPUT_DIRECTORY if(AARE_TESTS) set(TestSources ${CMAKE_CURRENT_SOURCE_DIR}/tests/raw_file_helpers.hpp + ${CMAKE_CURRENT_SOURCE_DIR}/tests/jungfrau_file_helpers.hpp ${CMAKE_CURRENT_SOURCE_DIR}/src/algorithm.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/calibration.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/defs.test.cpp @@ -466,6 +467,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/fit/Fit.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Frame.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/DataSetAggregation.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Interpolation.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/RawMasterFile.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/NDArray.test.cpp diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index e874a003..ea4bccf9 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -20,7 +20,8 @@ add_executable(benchmarks) target_sources( benchmarks PRIVATE ndarray_benchmark.cpp ndview_benchmark.cpp calculateeta_benchmark.cpp - reduce_benchmark.cpp clusterfile_benchmark.cpp) + reduce_benchmark.cpp clusterfile_benchmark.cpp + DataSetAggregation_benchmark.cpp) # Link Google Benchmark and other necessary libraries target_link_libraries(benchmarks PRIVATE benchmark::benchmark aare_core diff --git a/benchmarks/DataSetAggregation_benchmark.cpp b/benchmarks/DataSetAggregation_benchmark.cpp new file mode 100644 index 00000000..bce3ec21 --- /dev/null +++ b/benchmarks/DataSetAggregation_benchmark.cpp @@ -0,0 +1,34 @@ +#include + +#include "aare/DataSetAggregation.hpp" +#include + +/* +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/" + "CS_M749_2026-05-19_HGOG1G2_000000.dat"; + + for (auto _ : st) { + aare::NDArray res = + aare::mean_over_dataset(file_path, 220, 10, 16); + + benchmark::DoNotOptimize(res); + } +} + +BENCHMARK(DatasetAggregation_MeanOverDataset); diff --git a/docs/src/DataSetAggregation.rst b/docs/src/DataSetAggregation.rst new file mode 100644 index 00000000..c7b09069 --- /dev/null +++ b/docs/src/DataSetAggregation.rst @@ -0,0 +1,6 @@ +DataSet Aggregation +=================== + +Operations to read file and directly perform aggregation over the dataset, e.g. mean over all frames per sample. + +.. doxygenfunction:: aare::mean_over_dataset \ No newline at end of file diff --git a/docs/src/index.rst b/docs/src/index.rst index 4f0151b7..a0de829d 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -58,6 +58,7 @@ AARE RawSubFile RawMasterFile VarClusterFinder + DataSetAggregation diff --git a/include/aare/DataSetAggregation.hpp b/include/aare/DataSetAggregation.hpp index 533cacac..42c3eecc 100644 --- a/include/aare/DataSetAggregation.hpp +++ b/include/aare/DataSetAggregation.hpp @@ -1,62 +1,110 @@ +#pragma once #include "aare/File.hpp" +#include #include #include #include -template -void mean_over_dataset(const std::filesystem::path &path, const int num_samples, - const int num_frames_per_sample, const int num_threads) { +namespace aare { +/** + * @brief Compute the mean over several frames per sample stored in a file + * @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 num_frames_per_sample The number of frames per sample. + * @param num_threads The number of threads to use for parallel computation. + * @return An NDArray containing the mean frame for each sample. + */ +template +NDArray mean_over_dataset(const std::filesystem::path &path, + const size_t num_samples, + const size_t num_frames_per_sample, + const int num_threads = 16) { File file(path); - NDArray mean_per_sample({file.rows, file.cols, num_samples}); + auto frame = file.read_frame(); - auto mean_over_samples = - [&](size_t start_sample, size_t end_sample) { - File file(path); + NDArray mean_per_sample({static_cast(file.rows()), + static_cast(file.cols()), + static_cast(num_samples)}); - file.seek(start_sample * num_frames_per_sample); - NDArray frames( - {num_frames_per_sample, file.rows, file.cols}); - for (size_t i = 0; ++i; i < chunk_size) { - file.read_into( - reinterpret_cast(frames.data()), - num_frames_per_sample); // TODO: maybe better performance - // if read one by one - e.g. for - // parallel - for (size_t frame = 0; frame < num_frames_per_sample; ++frame) { - for (size_t row = 0; row < file.rows; ++row) { - for (size_t col = 0; col < file.cols; ++col) { - mean_per_sample(row, col, i) += - frames(frame, row, col); - } + auto mean_over_samples = [&](size_t start_sample, size_t end_sample) { + File file(path); + + file.seek(start_sample * num_frames_per_sample); + NDArray frames( + {static_cast(num_frames_per_sample), + static_cast(file.rows()), + static_cast(file.cols())}); + + size_t rows = file.rows(); + size_t cols = file.cols(); + + std::vector sum(rows * + cols); // need to be double to avoid overflow + // for uint16_t and uint32_t + const double inv_n = 1.0 / static_cast(num_frames_per_sample); + + // TODO: maybe tile + for (size_t i = start_sample; i < end_sample; ++i) { + file.read_into(reinterpret_cast(frames.data()), + num_frames_per_sample); // TODO: maybe better + // performance if read one by + // one - e.g. for parallel + + std::fill(sum.begin(), sum.end(), 0.0); + + const FRAME_TYPE *src = + frames.data(); // using the pointer seems to be much faster than + // using the NDArray + + for (size_t f = 0; f < num_frames_per_sample; ++f) { + const size_t f_off = f * rows * cols; + for (size_t r = 0; r < rows; ++r) { + const size_t off = f_off + r * cols; + for (size_t c = 0; c < cols; ++c) { + sum[r * cols + c] += static_cast(src[off + c]); } } + } - mean_per_sample /= - num_frames_per_sample; // TODO: should it be during or after - // -> have to map to new type - }; - } + for (size_t r = 0; r < rows; ++r) { + for (size_t c = 0; c < cols; ++c) { + mean_per_sample(r, c, i) = + static_cast(sum[r * cols + c] * inv_n); + } + } + }; + }; - std::vector> - futures(num_threads); + std::vector> futures(num_threads); int chunk_size = num_samples / num_threads; - for (int i = 0; i < num_threads; ++i) { - int end_sample = std::min((i + 1) * chunk_size, num_samples); + for (int i = 0; i < num_threads - 1; ++i) { + int end_sample = + std::min((i + 1) * static_cast(chunk_size), num_samples); + futures[i] = std::async(std::launch::async, mean_over_samples, i * chunk_size, end_sample); } + int end_sample = num_samples; + futures[num_threads - 1] = + std::async(std::launch::async, mean_over_samples, + (num_threads - 1) * chunk_size, end_sample); + for (auto &f : futures) { try { f.get(); } catch (const std::exception &e) { - std::cerr << "Exception in thread: " << e.what() << std::endl; + throw std::runtime_error(std::string("Exception in thread: ") + + e.what()); } } return mean_per_sample; -} \ No newline at end of file +} + +} // namespace aare \ No newline at end of file diff --git a/python/src/bind_DataSetAggregation.hpp b/python/src/bind_DataSetAggregation.hpp new file mode 100644 index 00000000..08550055 --- /dev/null +++ b/python/src/bind_DataSetAggregation.hpp @@ -0,0 +1,39 @@ +#include "aare/DataSetAggregation.hpp" + +#include + +#include +#include + +namespace py = pybind11; + +using namespace aare; + +template +void bind_DataSetAggregation(pybind11::module_ &m) { + m.def( + "mean_over_dataset", + [](const std::filesystem::path &path, size_t num_samples, + size_t num_frames_per_sample, int num_threads) { + auto result = + new NDArray(mean_over_dataset( + path, num_samples, num_frames_per_sample, num_threads)); + return return_image_data(result); + }, + py::arg("path"), py::arg("num_samples"), + py::arg("num_frames_per_sample"), py::arg("num_threads") = 16, + R"pbdoc( + Compute the mean over several frames per sample stored in a file. + + Parameters: + ----------- + path (str): The path to the file containing the dataset. + num_samples (int): The number of samples in the dataset. + num_frames_per_sample (int): The number of frames per sample. + num_threads (int, optional): The number of threads to use for parallel computation. Defaults to 16. + + Returns: + -------- + np.ndarray: A numpy array containing the mean frame for each sample with shape (rows, cols, num_samples). + )pbdoc"); +} \ No newline at end of file diff --git a/python/src/module.cpp b/python/src/module.cpp index b83deaca..24f66f91 100644 --- a/python/src/module.cpp +++ b/python/src/module.cpp @@ -11,6 +11,7 @@ #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" @@ -178,4 +179,6 @@ PYBIND11_MODULE(_aare, m) { define_eta(m, "d"); define_eta(m, "i"); define_eta(m, "i16"); + + bind_DataSetAggregation(m); } diff --git a/src/DataSetAggregation.test.cpp b/src/DataSetAggregation.test.cpp new file mode 100644 index 00000000..6a4d2f54 --- /dev/null +++ b/src/DataSetAggregation.test.cpp @@ -0,0 +1,57 @@ +#include "aare/DataSetAggregation.hpp" + +#include "jungfrau_file_helpers.hpp" + +#include + +#include + +using namespace aare; + +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; + + TemporaryJungfrauFiles temp_files( + num_samples * num_frames_per_sample, [](size_t frame) { + uint16_t value = frame % num_frames_per_sample; + NDArray data({Jungfrau::nRows, Jungfrau::nCols}, + value); + return data; + }); + + const std::filesystem::path path = temp_files.file_path(); + + auto mean_result = mean_over_dataset( + path, num_samples, num_frames_per_sample, num_threads); + + // Check the shape of the result + REQUIRE(mean_result.shape(0) == Jungfrau::nRows); + REQUIRE(mean_result.shape(1) == Jungfrau::nCols); + REQUIRE(mean_result.shape(2) == num_samples); + + uint16_t mean_value = + (num_frames_per_sample - 1) / + 2; // ((num_frames_per_sample -1)*num_frames_per_sample) / (2 + // *num_frames_per_sample); // mean of + // 0,1,...,num_frames_per_sample-1 + + // Check that the mean values + for (ssize_t sample = 0; sample < num_samples; ++sample) { + for (ssize_t row = 0; row < mean_result.shape(0); ++row) { + for (ssize_t col = 0; col < mean_result.shape(1); ++col) { + if (mean_result(row, col, sample) != mean_value) { + std::cerr + << "Mismatch at sample: " << sample << ", row: " << row + << ", col: " << col << ". Expected: " << mean_value + << ", got: " << mean_result(row, col, sample) << "\n"; + } + CHECK(mean_result(row, col, sample) == mean_value); + } + } + } +} \ No newline at end of file diff --git a/tests/jungfrau_file_helpers.hpp b/tests/jungfrau_file_helpers.hpp new file mode 100644 index 00000000..f6d07972 --- /dev/null +++ b/tests/jungfrau_file_helpers.hpp @@ -0,0 +1,80 @@ +#include "aare/JungfrauDataFile.hpp" +#include "aare/NDArray.hpp" +#include +#include +#include +#include +#include + +class TemporaryJungfrauFiles { + public: + // TODO: could have an additional argument num files + + /** @brief Create a temporary Jungfrau data file with the given number of + * frames and a frame generator function. + * @param num_frames The number of frames to generate. + * @param frame_generator A function that takes a frame index and returns an + * NDArray representing the frame data. + */ + explicit TemporaryJungfrauFiles( + const size_t num_frames, + std::function(size_t)> frame_generator, + const size_t num_files = 1) { + const auto unique = + std::chrono::steady_clock::now().time_since_epoch().count(); + m_directory = std::filesystem::temp_directory_path() / + ("aare-raw-" + std::to_string(unique)); + + std::filesystem::create_directory(m_directory); + + // constexpr auto max_ofstream_size = + // std::numeric_limits::max(); // 562 MB + + size_t frames_per_file = num_frames / num_files; + + for (size_t file_index = 0; file_index < num_files; ++file_index) { + + auto my_file_path = file_path(file_index); + std::ofstream output(my_file_path, std::ios::binary); + output.exceptions(std::ios::failbit | std::ios::badbit); + + if (!output.is_open()) { + throw std::runtime_error("Failed to open output file\n"); + } + + size_t start_frame = file_index * frames_per_file; + size_t end_frame = (file_index == num_files - 1) + ? num_frames + : start_frame + frames_per_file; + + for (size_t frame = start_frame; frame < end_frame; ++frame) { + aare::JungfrauDataHeader header{}; + header.framenum = frame; + const auto frame_data = frame_generator(frame); + try { + output.write(reinterpret_cast(&header), + sizeof(header)); + output.write( + reinterpret_cast(frame_data.data()), + frame_data.total_bytes()); + } catch (const std::ios_base::failure &e) { + throw std::runtime_error(fmt::format( + "Write failed at frame {}: {}", frame, e.what())); + } + } + } + } + + TemporaryJungfrauFiles(const TemporaryJungfrauFiles &) = delete; + TemporaryJungfrauFiles &operator=(const TemporaryJungfrauFiles &) = delete; + ~TemporaryJungfrauFiles() { std::filesystem::remove_all(m_directory); } + + std::filesystem::path file_path(size_t file_index = 0) const { + return m_directory / + fmt::format("{}{:06}.dat", m_base_name, file_index); + } + + private: + std::filesystem::path m_directory; + const std::string m_base_name = "JungfrauTest_"; +}; \ No newline at end of file