From f2db33365eb1a48197052fed8b6cefb973e069d8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Sun, 4 Oct 2026 09:54:55 +0200 Subject: [PATCH 01/16] bindings for xy --- RELEASE.md | 8 ++++++++ python/aare/__init__.py | 1 + python/src/bind_Defs.hpp | 16 ++++++++++++++++ python/src/bind_RawFile.hpp | 9 ++++++++- python/src/raw_master_file.hpp | 18 ++++++++++++++++-- python/tests/test_RawFile.py | 16 +++++++++++++++- python/tests/test_xy.py | 26 ++++++++++++++++++++++++++ 7 files changed, 90 insertions(+), 4 deletions(-) create mode 100644 python/tests/test_xy.py diff --git a/RELEASE.md b/RELEASE.md index 88686f53..16f2322b 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,5 +1,13 @@ # Release notes +## Next + +### New Features: + +- Added the Python ``xy`` type with ``row`` and ``col`` fields, enabling access + to ``RawFile.geometry``, ``RawMasterFile.detector_layout``, and + ``RawMasterFile.udp_interfaces_per_module``. It unpacks as ``row, col``. + ## 2026.9.30 ### New Features: diff --git a/python/aare/__init__.py b/python/aare/__init__.py index 570176f9..ea3f4c39 100644 --- a/python/aare/__init__.py +++ b/python/aare/__init__.py @@ -25,6 +25,7 @@ from ._aare import Pedestal_d, Pedestal_f, ClusterFinder_Cluster3x3i, VarCluster from ._aare import DetectorType, FrameDiscardPolicy, ReadoutMode from ._aare import hitmap from ._aare import ROI +from ._aare import xy from ._aare import corner from ._aare import UDPPortPosition diff --git a/python/src/bind_Defs.hpp b/python/src/bind_Defs.hpp index c6592f24..e5f3cc3d 100644 --- a/python/src/bind_Defs.hpp +++ b/python/src/bind_Defs.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#include #include #include @@ -74,6 +75,21 @@ void define_defs_bindings(py::module &m) { self.ymin == other.ymin && self.ymax == other.ymax; }); + py::class_(m, "xy") + .def(py::init(), py::arg("row"), py::arg("col")) + .def_readwrite("row", &xy::row) + .def_readwrite("col", &xy::col) + .def("__repr__", + [](const xy &self) { + return fmt::format("xy(row={}, col={})", self.row, self.col); + }) + .def("__iter__", + [](const xy &self) { + return py::iter(py::make_tuple(self.row, self.col)); + }) + .def(py::self == py::self) + .def(py::self != py::self); + py::enum_(m, "DetectorType") .value("Jungfrau", DetectorType::Jungfrau) .value("Eiger", DetectorType::Eiger) diff --git a/python/src/bind_RawFile.hpp b/python/src/bind_RawFile.hpp index 2c4e20c8..11d1d31a 100644 --- a/python/src/bind_RawFile.hpp +++ b/python/src/bind_RawFile.hpp @@ -318,7 +318,14 @@ void define_raw_file_io_bindings(py::module &m) { Cols for the given ROI. )") .def_property_readonly("bitdepth", &RawFile::bitdepth) - .def_property_readonly("geometry", &RawFile::geometry) + .def_property_readonly("geometry", &RawFile::geometry, R"( + Number of modules along each axis of the detector. + + Returns + ------- + xy + Module rows and columns. + )") .def_property_readonly("detector_type", &RawFile::detector_type) .def_property_readonly("master", &RawFile::master) .def_property_readonly("n_modules", &RawFile::n_modules) diff --git a/python/src/raw_master_file.hpp b/python/src/raw_master_file.hpp index 40e942a9..d30762a4 100644 --- a/python/src/raw_master_file.hpp +++ b/python/src/raw_master_file.hpp @@ -67,9 +67,23 @@ void define_raw_master_file_bindings(py::module &m) { .def_property_readonly("total_frames_expected", &RawMasterFile::total_frames_expected) .def_property_readonly("detector_layout", - &RawMasterFile::detector_layout) + &RawMasterFile::detector_layout, R"( + Number of modules along each axis of the detector + + Returns + ---------- + xy + Module rows and columns + )") .def_property_readonly("udp_interfaces_per_module", - &RawMasterFile::udp_interfaces_per_module) + &RawMasterFile::udp_interfaces_per_module, R"( + Number of UDP interfaces along each axis of a module + + Returns + ---------- + xy + UDP interface rows and columns + )") .def_property_readonly("analog_samples", &RawMasterFile::analog_samples, R"( Number of analog samples diff --git a/python/tests/test_RawFile.py b/python/tests/test_RawFile.py index 1fb6c3f7..76988db9 100644 --- a/python/tests/test_RawFile.py +++ b/python/tests/test_RawFile.py @@ -1,7 +1,7 @@ # SPDX-License-Identifier: MPL-2.0 import pytest import json -from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition +from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition, xy import numpy as np @@ -237,6 +237,20 @@ def test_raw_frame_count_across_rois(small_raw_file, short_module): reader.read_roi(roi_index) +def test_raw_file_geometry(small_raw_file): + metadata = json.loads(small_raw_file.read_text()) + metadata["Geometry"] = {"x": 1, "y": 2} + small_raw_file.write_text(json.dumps(metadata)) + for index in range(2): + data = (small_raw_file.parent / f"run_d0_f{index}_0.raw").read_bytes() + (small_raw_file.parent / f"run_d1_f{index}_0.raw").write_bytes(data) + + reader = RawFile(small_raw_file) + assert reader.geometry == xy(row=2, col=1) + assert reader.master.detector_layout == xy(row=2, col=1) + assert reader.master.udp_interfaces_per_module == xy(row=1, col=1) + + @pytest.mark.parametrize("disabled_port", [0, 1]) def test_raw_frame_count_with_disabled_udp_port(small_raw_file, disabled_port): metadata = json.loads(small_raw_file.read_text()) diff --git a/python/tests/test_xy.py b/python/tests/test_xy.py new file mode 100644 index 00000000..efc9c7d2 --- /dev/null +++ b/python/tests/test_xy.py @@ -0,0 +1,26 @@ +# SPDX-License-Identifier: MPL-2.0 +from aare import xy + + +def test_xy_fields(): + layout = xy(row=2, col=3) + assert layout.row == 2 + assert layout.col == 3 + + layout.row = 4 + assert layout.row == 4 + + +def test_xy_unpacks_as_row_col(): + row, col = xy(2, 3) + assert (row, col) == (2, 3) + + +def test_xy_comparison(): + assert xy(2, 3) == xy(2, 3) + assert xy(2, 3) != xy(3, 2) + assert xy(2, 3) != (2, 3) + + +def test_xy_repr(): + assert repr(xy(2, 3)) == "xy(row=2, col=3)" From 4ac941a003acadfa027eb883700dff3018414267 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Mon, 5 Oct 2026 19:13:43 +0200 Subject: [PATCH 02/16] Add aare::ssize_t alias for MSVC (#398) - MSVC has no ssize_t, which made every translation unit fail on Windows. - Define aare::ssize_t in defs.hpp: the platform ssize_t on POSIX (so nothing changes there) and std::ptrdiff_t on MSVC. - Code inside the namespace picks it up unchanged; the few files that use ssize_t outside the namespace get a using-declaration. FilePtr.hpp now includes defs.hpp since it had no aare include. Closing #393 Co-authored-by: Claude Fable 5.1 --- benchmarks/fit_benchmark.cpp | 2 ++ benchmarks/ndarray_benchmark.cpp | 1 + include/aare/FilePtr.hpp | 1 + include/aare/defs.hpp | 17 +++++++++++++++++ python/src/bind_MultiThreadedFileReader.hpp | 1 + python/src/bind_calibration.hpp | 1 + python/src/fit.hpp | 1 + src/ClusterVector.test.cpp | 1 + src/MultiThreadedFileReader.test.cpp | 1 + src/NDArray.test.cpp | 1 + src/NDView.test.cpp | 1 + src/algorithm.test.cpp | 2 ++ src/decode.test.cpp | 1 + src/fit/Fit.test.cpp | 1 + .../PedestalTrackingPixelHistogram.test.cpp | 1 + src/hist/PixelHistogram.test.cpp | 1 + 16 files changed, 34 insertions(+) diff --git a/benchmarks/fit_benchmark.cpp b/benchmarks/fit_benchmark.cpp index 8e522f80..2a307002 100644 --- a/benchmarks/fit_benchmark.cpp +++ b/benchmarks/fit_benchmark.cpp @@ -10,6 +10,8 @@ #include #include +using aare::ssize_t; + struct TestCase { std::string name; double true_A; diff --git a/benchmarks/ndarray_benchmark.cpp b/benchmarks/ndarray_benchmark.cpp index b3a3f610..46e7138e 100644 --- a/benchmarks/ndarray_benchmark.cpp +++ b/benchmarks/ndarray_benchmark.cpp @@ -3,6 +3,7 @@ #include using aare::NDArray; +using aare::ssize_t; constexpr ssize_t size = 1024; class TwoArrays : public benchmark::Fixture { diff --git a/include/aare/FilePtr.hpp b/include/aare/FilePtr.hpp index 2e84b87c..d9753006 100644 --- a/include/aare/FilePtr.hpp +++ b/include/aare/FilePtr.hpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once +#include "aare/defs.hpp" #include #include diff --git a/include/aare/defs.hpp b/include/aare/defs.hpp index 174bfb6b..43cae3cb 100644 --- a/include/aare/defs.hpp +++ b/include/aare/defs.hpp @@ -5,6 +5,7 @@ #include #include +#include #include #include #include @@ -13,6 +14,10 @@ #include #include +#if !defined(_MSC_VER) +#include // ::ssize_t +#endif + /** * @brief LOCATION macro to get the current location in the code */ @@ -54,6 +59,18 @@ namespace aare { +/** + * Signed size and index type used throughout the library (shapes, strides, + * frame indices, ROI coordinates). On POSIX this is the platform's ssize_t, + * so nothing changes for existing code. MSVC has no ssize_t, so there it is + * std::ptrdiff_t, which is the same type as Py_ssize_t and NumPy's npy_intp. + */ +#if defined(_MSC_VER) +using ssize_t = std::ptrdiff_t; +#else +using ssize_t = ::ssize_t; +#endif + inline constexpr size_t bits_per_byte = 8; void assert_failed(const std::string &msg); diff --git a/python/src/bind_MultiThreadedFileReader.hpp b/python/src/bind_MultiThreadedFileReader.hpp index f63f79c8..0f39cb6c 100644 --- a/python/src/bind_MultiThreadedFileReader.hpp +++ b/python/src/bind_MultiThreadedFileReader.hpp @@ -16,6 +16,7 @@ #include namespace py = pybind11; +using aare::ssize_t; inline py::dtype multi_threaded_reader_numpy_dtype(const aare::Dtype &dtype) { using aare::Dtype; diff --git a/python/src/bind_calibration.hpp b/python/src/bind_calibration.hpp index 6efa87bc..cdb16b86 100644 --- a/python/src/bind_calibration.hpp +++ b/python/src/bind_calibration.hpp @@ -9,6 +9,7 @@ #include namespace py = pybind11; +using aare::ssize_t; template py::array_t diff --git a/python/src/fit.hpp b/python/src/fit.hpp index f26cc20c..b41b1596 100644 --- a/python/src/fit.hpp +++ b/python/src/fit.hpp @@ -11,6 +11,7 @@ namespace py = pybind11; using namespace pybind11::literals; +using aare::ssize_t; template py::object diff --git a/src/ClusterVector.test.cpp b/src/ClusterVector.test.cpp index 135719c1..7d5b3910 100644 --- a/src/ClusterVector.test.cpp +++ b/src/ClusterVector.test.cpp @@ -12,6 +12,7 @@ using aare::Cluster; using aare::ClusterVector; +using aare::ssize_t; using C1 = Cluster; TEST_CASE("A newly created ClusterVector is empty") { diff --git a/src/MultiThreadedFileReader.test.cpp b/src/MultiThreadedFileReader.test.cpp index 4896d788..c6fdcd90 100644 --- a/src/MultiThreadedFileReader.test.cpp +++ b/src/MultiThreadedFileReader.test.cpp @@ -22,6 +22,7 @@ using aare::File; using aare::FileConfig; using aare::Frame; using aare::NumpyFile; +using aare::ssize_t; using aare::experimental::MultiThreadedFileReader; namespace { diff --git a/src/NDArray.test.cpp b/src/NDArray.test.cpp index 872f22cd..56514102 100644 --- a/src/NDArray.test.cpp +++ b/src/NDArray.test.cpp @@ -9,6 +9,7 @@ using aare::NDArray; using aare::NDView; using aare::Shape; +using aare::ssize_t; TEST_CASE("Initial size is zero if no size is specified") { NDArray a; diff --git a/src/NDView.test.cpp b/src/NDView.test.cpp index 1a8c6a2b..59d231b3 100644 --- a/src/NDView.test.cpp +++ b/src/NDView.test.cpp @@ -11,6 +11,7 @@ using aare::NDView; using aare::num_elements; using aare::Shape; +using aare::ssize_t; static_assert(std::is_convertible_v, NDView>); static_assert(!std::is_convertible_v, NDView>); diff --git a/src/algorithm.test.cpp b/src/algorithm.test.cpp index e498c3b2..026fcacb 100644 --- a/src/algorithm.test.cpp +++ b/src/algorithm.test.cpp @@ -3,6 +3,8 @@ #include #include +using aare::ssize_t; + TEST_CASE("Find the closed index in a 1D array", "[algorithm]") { aare::NDArray arr({5}); for (ssize_t i = 0; i < arr.size(); i++) { diff --git a/src/decode.test.cpp b/src/decode.test.cpp index 09d6c61c..dec59e08 100644 --- a/src/decode.test.cpp +++ b/src/decode.test.cpp @@ -10,6 +10,7 @@ using Catch::Matchers::WithinAbs; #include using aare::BitOffset; +using aare::ssize_t; TEST_CASE("test_adc_sar_05_decode64to16") { uint64_t input = 0; diff --git a/src/fit/Fit.test.cpp b/src/fit/Fit.test.cpp index 992500e8..9c1c7311 100644 --- a/src/fit/Fit.test.cpp +++ b/src/fit/Fit.test.cpp @@ -17,6 +17,7 @@ using aare::Minimizer; using aare::NDArray; using aare::NDView; +using aare::ssize_t; using Catch::Approx; namespace { diff --git a/src/hist/PedestalTrackingPixelHistogram.test.cpp b/src/hist/PedestalTrackingPixelHistogram.test.cpp index 2c9f1590..b8d81df4 100644 --- a/src/hist/PedestalTrackingPixelHistogram.test.cpp +++ b/src/hist/PedestalTrackingPixelHistogram.test.cpp @@ -20,6 +20,7 @@ using aare::FileConfig; using aare::Frame; using aare::NumpyFile; using aare::PedestalTrackingPixelHistogram; +using aare::ssize_t; namespace { diff --git a/src/hist/PixelHistogram.test.cpp b/src/hist/PixelHistogram.test.cpp index 50b1fcec..25767257 100644 --- a/src/hist/PixelHistogram.test.cpp +++ b/src/hist/PixelHistogram.test.cpp @@ -18,6 +18,7 @@ using aare::NDArray; using aare::NDView; using aare::PixelHistogram; +using aare::ssize_t; namespace { // The synchronous fill() has been removed; fill_async() is the only entry From 3e90eb2539ea96f09c11934389e7d4ede1556d1c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Mon, 5 Oct 2026 19:13:44 +0200 Subject: [PATCH 03/16] Convert paths to strings explicitly (#400) On Windows std::filesystem::path holds wchar_t, so assigning a path component to a std::string or passing path::c_str() to fopen does not compile. Use path::string() at those sites, and drop a redundant path round trip in NumpyFile. closes #399 --- src/FilePtr.cpp | 4 ++-- src/JungfrauDataFile.cpp | 2 +- src/NumpyFile.cpp | 3 +-- src/RawMasterFile.cpp | 4 ++-- src/RawSubFile.cpp | 2 +- 5 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/FilePtr.cpp b/src/FilePtr.cpp index 45e65d46..f0e0844c 100644 --- a/src/FilePtr.cpp +++ b/src/FilePtr.cpp @@ -9,10 +9,10 @@ namespace aare { FilePtr::FilePtr(const std::filesystem::path &fname, const std::string &mode = "rb") { - fp_ = fopen(fname.c_str(), mode.c_str()); + fp_ = fopen(fname.string().c_str(), mode.c_str()); if (!fp_) throw std::runtime_error( - fmt::format("Could not open: {}", fname.c_str())); + fmt::format("Could not open: {}", fname.string())); } FilePtr::FilePtr(FilePtr &&other) { std::swap(fp_, other.fp_); } diff --git a/src/JungfrauDataFile.cpp b/src/JungfrauDataFile.cpp index 34820b8b..5c19cbc3 100644 --- a/src/JungfrauDataFile.cpp +++ b/src/JungfrauDataFile.cpp @@ -136,7 +136,7 @@ void JungfrauDataFile::find_frame_size(const std::filesystem::path &fname) { void JungfrauDataFile::parse_fname(const std::filesystem::path &fname) { m_path = fname.parent_path(); - m_base_name = fname.stem(); + m_base_name = fname.stem().string(); // find file index, then remove if from the base name if (auto pos = m_base_name.find_last_of('_'); pos != std::string::npos) { diff --git a/src/NumpyFile.cpp b/src/NumpyFile.cpp index 699fa08c..d70ae5bb 100644 --- a/src/NumpyFile.cpp +++ b/src/NumpyFile.cpp @@ -28,8 +28,7 @@ NumpyFile::NumpyFile(const std::filesystem::path &fname, throw std::runtime_error( fmt::format("Could not open: {} for reading", fname.string())); } - initial_header_len = aare::NumpyHelpers::write_header( - std::filesystem::path(fname.c_str()), m_header); + initial_header_len = aare::NumpyHelpers::write_header(fname, m_header); } m_pixels_per_frame = std::accumulate(m_header.shape.begin() + 1, m_header.shape.end(), 1, diff --git a/src/RawMasterFile.cpp b/src/RawMasterFile.cpp index e0880ba5..4259c899 100644 --- a/src/RawMasterFile.cpp +++ b/src/RawMasterFile.cpp @@ -11,8 +11,8 @@ namespace aare { RawFileNameComponents::RawFileNameComponents( const std::filesystem::path &fname) { m_base_path = fname.parent_path(); - m_base_name = fname.stem(); - m_ext = fname.extension(); + m_base_name = fname.stem().string(); + m_ext = fname.extension().string(); if (m_ext != ".json" && m_ext != ".raw") { throw std::runtime_error(LOCATION + diff --git a/src/RawSubFile.cpp b/src/RawSubFile.cpp index 7a42bbba..cd1a6fba 100644 --- a/src/RawSubFile.cpp +++ b/src/RawSubFile.cpp @@ -163,7 +163,7 @@ void RawSubFile::parse_fname(const std::filesystem::path &fname) { // f1 is the file index - thi is the one we need // 0 is the measurement index, will not change m_path = fname.parent_path(); - m_base_name = fname.filename(); + m_base_name = fname.filename().string(); // Regex to extract numbers after 'd' and 'f' std::regex pattern(R"(^(.*_d)(\d+)(_f)(\d+)(_\d+\.raw)$)"); From 060a0ec9e7dc14090a0fc48792de6e827acabd5e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Mon, 5 Oct 2026 19:13:44 +0200 Subject: [PATCH 04/16] Make the logger timestamp portable (#401) logger.hpp pulled in and used gettimeofday and localtime_r, which do not exist on MSVC. Build the timestamp from std::chrono instead and use localtime_s on MSVC. The output format is unchanged: - HH:MM:SS.mmm LEVEL: message. The unused __SHORT_FORM_OF_FILE__ helper now also strips backslash separators. Add logger tests that pin the timestamp and line format. closes #394 Co-authored-by: Claude Fable 5.1 --- CMakeLists.txt | 1 + include/aare/logger.hpp | 68 +++++++++++++++++++++++++++++------------ src/logger.test.cpp | 41 +++++++++++++++++++++++++ 3 files changed, 90 insertions(+), 20 deletions(-) create mode 100644 src/logger.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 8a1aa4eb..b4a501a8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -482,6 +482,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PixelHistogram.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/JungfrauDataFile.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/logger.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/MultiThreadedFileReader.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/NumpyFile.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/NumpyHelpers.test.cpp diff --git a/include/aare/logger.hpp b/include/aare/logger.hpp index 278d4d7d..6374aeea 100644 --- a/include/aare/logger.hpp +++ b/include/aare/logger.hpp @@ -2,9 +2,12 @@ #pragma once /*Utility to log to console*/ +#include +#include +#include #include #include -#include +#include namespace aare { @@ -55,12 +58,53 @@ enum TLogLevel { #define __AT__ \ std::string(__FILE__) + std::string("::") + std::string(__func__) + \ std::string("(): ") -#define __SHORT_FORM_OF_FILE__ \ - (strrchr(__FILE__, '/') ? strrchr(__FILE__, '/') + 1 : __FILE__) +#define __SHORT_FORM_OF_FILE__ aare::short_file_name(__FILE__) #define __SHORT_AT__ \ std::string(__SHORT_FORM_OF_FILE__) + std::string("::") + \ std::string(__func__) + std::string("(): ") +/** + * @brief Strip the directory part of a path, accepting both '/' and '\\' as + * separators so that __FILE__ is shortened the same way on every platform. + */ +inline const char *short_file_name(const char *path) noexcept { + const char *base = path; + for (const char *p = path; *p != '\0'; ++p) { + if (*p == '/' || *p == '\\') + base = p + 1; + } + return base; +} + +/** + * @brief Local wall-clock time as HH:MM:SS.mmm (strftime "%X" plus + * milliseconds), built from std::chrono so it works on every platform. + */ +inline std::string log_timestamp() { + using namespace std::chrono; + const auto now = system_clock::now(); + const time_t t = system_clock::to_time_t(now); + const auto ms = duration_cast(now.time_since_epoch()) % 1000; + + tm local{}; +#if defined(_MSC_VER) + localtime_s(&local, &t); +#else + localtime_r(&t, &local); +#endif + + constexpr size_t buffer_len = 12; + char buffer[buffer_len]; + if (strftime(buffer, buffer_len, "%X", &local) == 0) + buffer[0] = '\0'; + + constexpr size_t result_len = 100; + char result[result_len]; + snprintf(result, result_len, "%s.%03d", buffer, + static_cast(ms.count())); + return result; +} + class Logger { std::ostringstream os; TLogLevel m_level = AARE_LOG_LEVEL; @@ -111,23 +155,7 @@ class Logger { return os; } - static std::string Timestamp() { - constexpr size_t buffer_len = 12; - char buffer[buffer_len]; - time_t t; - ::time(&t); - tm r; - strftime(buffer, buffer_len, "%X", localtime_r(&t, &r)); - buffer[buffer_len - 1] = '\0'; - struct timeval tv; - gettimeofday(&tv, nullptr); - constexpr size_t result_len = 100; - char result[result_len]; - snprintf(result, result_len, "%s.%03ld", buffer, - static_cast(tv.tv_usec) / 1000); - result[result_len - 1] = '\0'; - return result; - } + static std::string Timestamp() { return log_timestamp(); } }; // TODO! Do we need to keep the runtime option? diff --git a/src/logger.test.cpp b/src/logger.test.cpp new file mode 100644 index 00000000..17218d96 --- /dev/null +++ b/src/logger.test.cpp @@ -0,0 +1,41 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/logger.hpp" + +#include +#include + +#include +#include +#include + +using Catch::Matchers::EndsWith; +using Catch::Matchers::Matches; +using Catch::Matchers::StartsWith; + +TEST_CASE("Log timestamp is HH:MM:SS.mmm", "[logger]") { + const std::string ts = aare::Logger::Timestamp(); + REQUIRE_THAT(ts, Matches(R"(\d{2}:\d{2}:\d{2}\.\d{3})")); +} + +TEST_CASE("short_file_name strips both kinds of directory separators", + "[logger]") { + REQUIRE(std::string(aare::short_file_name("/a/b/File.cpp")) == "File.cpp"); + REQUIRE(std::string(aare::short_file_name("C:\\a\\b\\File.cpp")) == + "File.cpp"); + REQUIRE(std::string(aare::short_file_name("File.cpp")) == "File.cpp"); +} + +TEST_CASE("LOG writes one coloured line with timestamp and level", "[logger]") { + std::ostringstream captured; + auto *previous = std::clog.rdbuf(captured.rdbuf()); + LOG(aare::logWARNING) << "hello " << 42; + std::clog.rdbuf(previous); + + const std::string line = captured.str(); + // - HH:MM:SS.mmm WARNING: hello 42\n + REQUIRE_THAT(line, StartsWith(std::string(YELLOW BOLD) + "- ")); + REQUIRE_THAT(line, Matches(std::string("\x1b\\[33m\x1b\\[1m- ") + + R"(\d{2}:\d{2}:\d{2}\.\d{3} WARNING: hello 42)" + + "\x1b\\[0m\n")); + REQUIRE_THAT(line, EndsWith(std::string(RESET) + "\n")); +} From 7e1b8a765d174a83ba33ade9d891f5bbd7f4c0be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Mon, 5 Oct 2026 19:13:45 +0200 Subject: [PATCH 05/16] Dev/win compile (#402) Collection of fixes to make aare build on Windows. Requires the previous PRs for compilation to succeed. - Replaced `or` keyword with || - updated cmake file - fix for 32 bit long in fseek closes #395 closes #396 --- CMakeLists.txt | 54 +++++++++++++++++++------------ include/aare/FilePtr.hpp | 20 +++++++++++- include/aare/NumpyFile.hpp | 3 +- python/src/bind_ClusterVector.hpp | 12 +++---- python/src/np_helper.hpp | 9 ++++-- src/ClusterVector.test.cpp | 6 ++-- src/FilePtr.cpp | 2 +- src/NumpyFile.cpp | 12 +++---- src/ROI.cpp | 4 +-- src/RawFile.cpp | 2 +- src/fit/Fit.cpp | 4 ++- src/fit/Fit.test.cpp | 2 +- 12 files changed, 85 insertions(+), 45 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b4a501a8..453414a4 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -254,18 +254,30 @@ target_compile_features(aare_compiler_flags INTERFACE cxx_std_17) # MSVC specific # # ############################################################################## if(MSVC) - add_compile_definitions(AARE_MSVC) - if(CMAKE_BUILD_TYPE STREQUAL "Release") - message(STATUS "Release build") - target_compile_options(aare_compiler_flags INTERFACE /O2) - else() - message(STATUS "Debug build") - target_compile_options(aare_compiler_flags - INTERFACE /Od /Zi /MDd /D_ITERATOR_DEBUG_LEVEL=2) - target_link_options(aare_compiler_flags INTERFACE /DEBUG:FULL) - endif() - target_compile_options(aare_compiler_flags INTERFACE /w # disable warnings + # CMake sets the per-configuration optimisation, debug-info and + # runtime-library flags itself, so only warnings and conformance here. + target_compile_options( + aare_compiler_flags + INTERFACE /W4 # -Wall -Wextra + /permissive- # standard conformance, like CMAKE_CXX_EXTENSIONS OFF + /utf-8 # sources are UTF-8 + /we4715 # not all control paths return a value, like + # -Werror=return-type + /wd4244 # narrowing conversions: -Wconversion is not enabled + /wd4267 # on gcc/clang either + /wd4068 # unknown pragma: the GCC diagnostic pragmas + /wd4324 # structure padded due to alignas: intended ) + target_compile_definitions(aare_compiler_flags + INTERFACE _CRT_SECURE_NO_WARNINGS) + + if(AARE_WARNINGS_AS_ERRORS) + target_compile_options(aare_compiler_flags INTERFACE /WX) + endif() + + if(AARE_ASAN) + message(WARNING "AARE_ASAN is not supported with MSVC. Ignoring.") + endif() else() # ############################################################################ @@ -318,22 +330,22 @@ else() endif() endif() + if(AARE_ASAN) + message(STATUS "AddressSanitizer enabled") + target_compile_options( + aare_compiler_flags INTERFACE -fsanitize=address,undefined,pointer-compare + -fno-omit-frame-pointer) + target_link_libraries( + aare_compiler_flags INTERFACE -fsanitize=address,undefined,pointer-compare + -fno-omit-frame-pointer) + endif() + endif() # GCC/Clang specific if(AARE_PYTHON_BINDINGS) add_subdirectory(python) endif() -if(AARE_ASAN) - message(STATUS "AddressSanitizer enabled") - target_compile_options( - aare_compiler_flags INTERFACE -fsanitize=address,undefined,pointer-compare - -fno-omit-frame-pointer) - target_link_libraries( - aare_compiler_flags INTERFACE -fsanitize=address,undefined,pointer-compare - -fno-omit-frame-pointer) -endif() - if(AARE_TESTS) enable_testing() add_subdirectory(tests) diff --git a/include/aare/FilePtr.hpp b/include/aare/FilePtr.hpp index d9753006..16ea198d 100644 --- a/include/aare/FilePtr.hpp +++ b/include/aare/FilePtr.hpp @@ -1,11 +1,29 @@ // SPDX-License-Identifier: MPL-2.0 #pragma once #include "aare/defs.hpp" +#include #include #include namespace aare { +// MSVC's long is 32 bits, so fseek/ftell stop working past 2 GB there +inline int fseek64(FILE *fp, int64_t offset, int whence) { +#ifdef _WIN32 + return _fseeki64(fp, offset, whence); +#else + return fseek(fp, static_cast(offset), whence); +#endif +} + +inline int64_t ftell64(FILE *fp) { +#ifdef _WIN32 + return _ftelli64(fp); +#else + return ftell(fp); +#endif +} + /** * \brief RAII wrapper for FILE pointer */ @@ -23,7 +41,7 @@ class FilePtr { FILE *get(); ssize_t tell(); void seek(ssize_t offset, int whence = SEEK_SET) { - if (fseek(fp_, offset, whence) != 0) + if (fseek64(fp_, offset, whence) != 0) throw std::runtime_error("Error seeking in file"); } std::string error_msg(); diff --git a/include/aare/NumpyFile.hpp b/include/aare/NumpyFile.hpp index caa68531..0d7a523d 100644 --- a/include/aare/NumpyFile.hpp +++ b/include/aare/NumpyFile.hpp @@ -2,6 +2,7 @@ #pragma once #include "aare/Dtype.hpp" #include "aare/FileInterface.hpp" +#include "aare/FilePtr.hpp" #include "aare/NumpyHelpers.hpp" #include "aare/defs.hpp" @@ -77,7 +78,7 @@ class NumpyFile : public FileInterface { */ template NDArray load() { NDArray arr(make_shape(m_header.shape)); - if (fseek(fp, static_cast(header_size), SEEK_SET)) { + if (fseek64(fp, header_size, SEEK_SET)) { throw std::runtime_error(LOCATION + "Error seeking to the start of the data"); } diff --git a/python/src/bind_ClusterVector.hpp b/python/src/bind_ClusterVector.hpp index 9b031e5d..c7b2932a 100644 --- a/python/src/bind_ClusterVector.hpp +++ b/python/src/bind_ClusterVector.hpp @@ -124,7 +124,7 @@ void define_ClusterVector(py::module &m, const std::string &typestr) { .def_property_readonly( "fmt", [typestr](ClusterVector &self) { - return fmt_format; + return fmt_format(); }, "PEP 3118 format string for one stored cluster.") @@ -145,11 +145,11 @@ void define_ClusterVector(py::module &m, const std::string &typestr) { .def_buffer( [typestr](ClusterVector &self) -> py::buffer_info { return py::buffer_info( - self.data(), /* Pointer to buffer */ - self.item_size(), /* Size of one scalar */ - fmt_format, /* Format descriptor */ - 1, /* Number of dimensions */ - {self.size()}, /* Buffer dimensions */ + self.data(), /* Pointer to buffer */ + self.item_size(), /* Size of one scalar */ + fmt_format(), /* Format descriptor */ + 1, /* Number of dimensions */ + {self.size()}, /* Buffer dimensions */ {self.item_size()} /* Strides (in bytes) for each index */ ); }); diff --git a/python/src/np_helper.hpp b/python/src/np_helper.hpp index d21aceff..83880470 100644 --- a/python/src/np_helper.hpp +++ b/python/src/np_helper.hpp @@ -112,8 +112,13 @@ struct fmt_format_trait> { } }; -template -auto fmt_format = fmt_format_trait::value(); +// Function-local static rather than a variable template: MSVC does not run +// the dynamic initializer of a variable template instantiated from inside +// another template, which left the format string empty. +template const std::string &fmt_format() { + static const std::string value = fmt_format_trait::value(); + return value; +} /** * Helper function to allocate image data given item size and shape diff --git a/src/ClusterVector.test.cpp b/src/ClusterVector.test.cpp index 7d5b3910..088f0059 100644 --- a/src/ClusterVector.test.cpp +++ b/src/ClusterVector.test.cpp @@ -181,7 +181,8 @@ TEST_CASE("Summing 3x1 clusters of int64") { Cluster c3 = {11, 12, {13, 14, 15}}; cv.push_back(c3); - REQUIRE(cv.capacity() == 4); + // growth factor is implementation defined (2x libstdc++, 1.5x MSVC) + REQUIRE(cv.capacity() >= 3); REQUIRE(cv.size() == 3); /* @@ -237,7 +238,8 @@ TEST_CASE("Push back more than initial capacity") { Cluster c3 = {11, 12, {13, 14, 15, 16}}; cv.push_back(c3); REQUIRE(cv.size() == 3); - REQUIRE(cv.capacity() == 4); + // growth factor is implementation defined (2x libstdc++, 1.5x MSVC) + REQUIRE(cv.capacity() >= 3); Cluster *ptr = reinterpret_cast *>(cv.data()); diff --git a/src/FilePtr.cpp b/src/FilePtr.cpp index f0e0844c..c6edfe62 100644 --- a/src/FilePtr.cpp +++ b/src/FilePtr.cpp @@ -27,7 +27,7 @@ FilePtr::operator bool() const noexcept { return fp_ != nullptr; } FILE *FilePtr::get() { return fp_; } ssize_t FilePtr::tell() { - auto pos = ftell(fp_); + auto pos = ftell64(fp_); if (pos == -1) throw std::runtime_error( fmt::format("Error getting file position: {}", error_msg())); diff --git a/src/NumpyFile.cpp b/src/NumpyFile.cpp index d70ae5bb..ad9cdf6f 100644 --- a/src/NumpyFile.cpp +++ b/src/NumpyFile.cpp @@ -45,7 +45,7 @@ void NumpyFile::write_impl(void *data, uint64_t size) { if (!(m_mode == "w" || m_mode == "a")) { throw std::invalid_argument("File not open for writing"); } - if (fseek(fp, 0, SEEK_END)) + if (fseek64(fp, 0, SEEK_END)) throw std::runtime_error("Could not seek to end of file"); size_t const rc = fwrite(data, size, 1, fp); if (rc != 1) { @@ -67,8 +67,8 @@ void NumpyFile::get_frame_into(size_t frame_number, std::byte *image_buf) { if (frame_number > m_header.shape[0]) { throw std::invalid_argument("Frame number out of range"); } - if (fseek(fp, header_size + frame_number * m_bytes_per_frame, - SEEK_SET)) // NOLINT + if (fseek64(fp, header_size + frame_number * m_bytes_per_frame, + SEEK_SET)) // NOLINT throw std::runtime_error("Could not seek to frame"); size_t const rc = fread(image_buf, m_bytes_per_frame, 1, fp); @@ -100,15 +100,15 @@ void NumpyFile::read_into(std::byte *image_buf, size_t n_frames) { NumpyFile::~NumpyFile() noexcept { if (m_mode == "w" || m_mode == "a") { // determine number of frames - if (fseek(fp, 0, SEEK_END)) { + if (fseek64(fp, 0, SEEK_END)) { std::cout << "Could not seek to end of file" << std::endl; } - size_t const file_size = ftell(fp); + size_t const file_size = ftell64(fp); size_t const data_size = file_size - initial_header_len; size_t const n_frames = data_size / m_bytes_per_frame; // update number of frames in header (first element of shape) m_header.shape[0] = n_frames; - if (fseek(fp, 0, SEEK_SET)) { + if (fseek64(fp, 0, SEEK_SET)) { std::cout << "Could not seek to beginning of file" << std::endl; } // create string stream to contain header diff --git a/src/ROI.cpp b/src/ROI.cpp index 7e91c49d..56882015 100644 --- a/src/ROI.cpp +++ b/src/ROI.cpp @@ -20,7 +20,7 @@ bool complete_ROI(const ROI &roi, const DetectorGeometry &geometry) { bool complete_ROI(const std::vector &rois, const DetectorGeometry &geometry) { - if (rois.empty() or rois.size() > 1) { + if (rois.empty() || rois.size() > 1) { return false; } else { return complete_ROI(rois[0], geometry); @@ -34,7 +34,7 @@ bool complete_ROI(const ROIGeometry &roi, const DetectorGeometry &geometry) { bool complete_ROI(const std::vector &rois, const DetectorGeometry &geometry) { - if (rois.empty() or rois.size() > 1) { + if (rois.empty() || rois.size() > 1) { return false; } else { return complete_ROI(rois[0], geometry); diff --git a/src/RawFile.cpp b/src/RawFile.cpp index 1e33bf83..e416a27e 100644 --- a/src/RawFile.cpp +++ b/src/RawFile.cpp @@ -302,7 +302,7 @@ void RawFile::open_subfiles(const size_t roi_index) { DetectorHeader RawFile::read_header(const std::filesystem::path &fname) { DetectorHeader h{}; - FILE *fp = fopen(fname.string().c_str(), "r"); + FILE *fp = fopen(fname.string().c_str(), "rb"); if (!fp) throw std::runtime_error(fmt::format( "Could not open file '{}' for frame index 0", fname.string())); diff --git a/src/fit/Fit.cpp b/src/fit/Fit.cpp index 8b34c177..05dfa5d8 100644 --- a/src/fit/Fit.cpp +++ b/src/fit/Fit.cpp @@ -268,7 +268,9 @@ void fit_3d(const FitModel &model, NDView x, NDView y, NDView y_err, NDView par_out, NDView err_out, NDView chi2_out, int n_threads) { - constexpr std::size_t npar = Model::npar; + // static so the lambda below can use it as an array size without + // capturing it, which MSVC otherwise rejects + static constexpr std::size_t npar = Model::npar; detail::check_fit_3d_shapes(x, y, y_err, par_out, err_out, chi2_out); const bool has_errors = (y_err.size() > 0); diff --git a/src/fit/Fit.test.cpp b/src/fit/Fit.test.cpp index 9c1c7311..1edadce6 100644 --- a/src/fit/Fit.test.cpp +++ b/src/fit/Fit.test.cpp @@ -1100,7 +1100,7 @@ TEST_CASE("Samples with a zero error are ignored even when NaN", "[fit]") { INFO("minimizer " << name(minimizer)); const double nan = std::numeric_limits::quiet_NaN(); - constexpr ssize_t n = 10; + static constexpr ssize_t n = 10; // static: used inside GENERATE's lambda NDArray x({n}); NDArray y({n}); NDArray y_err({n}, 1.0); From cdd8586f64eb2c07b5cb184a40e379f6919bc7df Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Tue, 6 Oct 2026 14:49:24 +0200 Subject: [PATCH 06/16] Fixed warnings on Windows (#407) Now builds clean on MSVC: cl version 19.51.36260 for x64, from Visual Studio 2026 Build Tools 18.10.3. Major items: - [[maybe_unused]] instead of gcc/clang specific pragmas - Removed names variables that weren't used - Cast + explicit uing64 --- CMakeLists.txt | 5 +++++ include/aare/to_string.hpp | 2 +- python/src/bind_Cluster.hpp | 5 ----- python/src/bind_ClusterCollector.hpp | 5 ----- python/src/bind_ClusterFile.hpp | 17 +++++------------ python/src/bind_ClusterFileSink.hpp | 5 ----- python/src/bind_ClusterFinder.hpp | 5 ----- python/src/bind_ClusterFinderMT.hpp | 8 ++------ python/src/bind_ClusterVector.hpp | 7 +------ python/src/file.hpp | 18 +++++++----------- python/src/jungfrau_data_file.hpp | 19 +++++++------------ python/src/raw_sub_file.hpp | 18 +++++++----------- src/JungfrauDataFile.cpp | 2 +- src/RawMasterFile.cpp | 18 +++++++++--------- src/decode.test.cpp | 4 ++-- 15 files changed, 47 insertions(+), 91 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 453414a4..9a6ba241 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -208,6 +208,11 @@ if(AARE_FETCH_FMT) CACHE BOOL "") FetchContent_MakeAvailable(fmt) set_property(TARGET fmt PROPERTY POSITION_INDEPENDENT_CODE ON) + if(MSVC) + # fmt 12.1.0 calls std::isalpha only to check that ADL finds it and drops + # the result, which MSVC's standard library marks [[nodiscard]] + target_compile_options(fmt PRIVATE /wd4834) + endif() else() find_package(fmt 8 REQUIRED) endif() diff --git a/include/aare/to_string.hpp b/include/aare/to_string.hpp index dbb0c09f..547ebc09 100644 --- a/include/aare/to_string.hpp +++ b/include/aare/to_string.hpp @@ -19,7 +19,7 @@ T string_to(const std::string &t, const std::string &unit) { double tval{0}; try { tval = std::stod(t); - } catch (const std::invalid_argument &e) { + } catch (const std::invalid_argument &) { throw std::runtime_error("Could not convert string to time"); } diff --git a/python/src/bind_Cluster.hpp b/python/src/bind_Cluster.hpp index afa9bfd1..49618bf2 100644 --- a/python/src/bind_Cluster.hpp +++ b/python/src/bind_Cluster.hpp @@ -13,9 +13,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_Cluster(py::module &m, const std::string &typestr) { @@ -140,5 +137,3 @@ void reduce_to_2x2(py::module &m) { row-major order. )doc"); } - -#pragma GCC diagnostic pop diff --git a/python/src/bind_ClusterCollector.hpp b/python/src/bind_ClusterCollector.hpp index 01dd03c2..fab91522 100644 --- a/python/src/bind_ClusterCollector.hpp +++ b/python/src/bind_ClusterCollector.hpp @@ -20,9 +20,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_ClusterCollector(py::module &m, const std::string &typestr) { @@ -42,5 +39,3 @@ void define_ClusterCollector(py::module &m, const std::string &typestr) { }, py::return_value_policy::take_ownership); } - -#pragma GCC diagnostic pop \ No newline at end of file diff --git a/python/src/bind_ClusterFile.hpp b/python/src/bind_ClusterFile.hpp index c8544e9d..75c5458d 100644 --- a/python/src/bind_ClusterFile.hpp +++ b/python/src/bind_ClusterFile.hpp @@ -13,11 +13,6 @@ #include #include -// Disable warnings for unused parameters, as we ignore some -// in the __exit__ method -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - namespace py = pybind11; using namespace ::aare; @@ -171,14 +166,12 @@ void define_ClusterFile(py::module &m, const std::string &typestr) { .def("__enter__", [](ClusterFile &self) { return &self; }) .def("__exit__", [](ClusterFile &self, - const std::optional &exc_type, - const std::optional &exc_value, - const std::optional &traceback) { - self.close(); - }) + [[maybe_unused]] const std::optional &exc_type, + [[maybe_unused]] const std::optional + &exc_value, + [[maybe_unused]] const std::optional + &traceback) { self.close(); }) .def("__iter__", [](ClusterFile &self) { return &self; }) .def("__next__", [](File &self) { return ChunkIterator(self.chunks()).next(); }); } - -#pragma GCC diagnostic pop diff --git a/python/src/bind_ClusterFileSink.hpp b/python/src/bind_ClusterFileSink.hpp index b366886a..50600fcb 100644 --- a/python/src/bind_ClusterFileSink.hpp +++ b/python/src/bind_ClusterFileSink.hpp @@ -17,9 +17,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_ClusterFileSink(py::module &m, const std::string &typestr) { @@ -34,5 +31,3 @@ void define_ClusterFileSink(py::module &m, const std::string &typestr) { const std::filesystem::path &>()) .def("stop", &ClusterFileSink::stop); } - -#pragma GCC diagnostic pop diff --git a/python/src/bind_ClusterFinder.hpp b/python/src/bind_ClusterFinder.hpp index 034b1b88..8872db29 100644 --- a/python/src/bind_ClusterFinder.hpp +++ b/python/src/bind_ClusterFinder.hpp @@ -20,9 +20,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_ClusterFinder(py::module &m, const std::string &typestr) { @@ -92,5 +89,3 @@ void define_ClusterFinder(py::module &m, const std::string &typestr) { }, py::arg("frame").noconvert(), py::arg("frame_number") = 0); } - -#pragma GCC diagnostic pop \ No newline at end of file diff --git a/python/src/bind_ClusterFinderMT.hpp b/python/src/bind_ClusterFinderMT.hpp index fdd4b580..7e662841 100644 --- a/python/src/bind_ClusterFinderMT.hpp +++ b/python/src/bind_ClusterFinderMT.hpp @@ -20,9 +20,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_ClusterFinderMT(py::module &m, const std::string &typestr) { @@ -55,7 +52,8 @@ void define_ClusterFinderMT(py::module &m, const std::string &typestr) { py::arg("frame").noconvert(), py::arg("frame_number") = 0) .def_property_readonly( "cluster_size", - [](ClusterFinderMT &self) { + []([[maybe_unused]] ClusterFinderMT + &self) { return py::make_tuple(ClusterSizeX, ClusterSizeY); }) .def("clear_pedestal", @@ -93,5 +91,3 @@ void define_ClusterFinderMT(py::module &m, const std::string &typestr) { py::arg("nSigma"), R"(sets the number of sigma for all cluster finders.)"); } - -#pragma GCC diagnostic pop \ No newline at end of file diff --git a/python/src/bind_ClusterVector.hpp b/python/src/bind_ClusterVector.hpp index c7b2932a..13ad5a6d 100644 --- a/python/src/bind_ClusterVector.hpp +++ b/python/src/bind_ClusterVector.hpp @@ -18,9 +18,6 @@ namespace py = pybind11; using namespace aare; -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - template void define_ClusterVector(py::module &m, const std::string &typestr) { @@ -123,7 +120,7 @@ void define_ClusterVector(py::module &m, const std::string &typestr) { "padding.") .def_property_readonly( "fmt", - [typestr](ClusterVector &self) { + [typestr]([[maybe_unused]] ClusterVector &self) { return fmt_format(); }, "PEP 3118 format string for one stored cluster.") @@ -228,5 +225,3 @@ void define_3x3_reduction(py::module &m) { )doc", py::arg("clustervector")); } - -#pragma GCC diagnostic pop diff --git a/python/src/file.hpp b/python/src/file.hpp index a493c910..030ba181 100644 --- a/python/src/file.hpp +++ b/python/src/file.hpp @@ -21,11 +21,6 @@ namespace py = pybind11; using namespace ::aare; -// Disable warnings for unused parameters, as we ignore some -// in the __exit__ method -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - void define_file_io_bindings(py::module &m) { PYBIND11_NUMPY_DTYPE(DetectorHeader, frameNumber, expLength, packetNumber, @@ -122,9 +117,12 @@ void define_file_io_bindings(py::module &m) { }) .def("__enter__", [](File &self) { return &self; }) .def("__exit__", - [](File &self, const std::optional &exc_type, - const std::optional &exc_value, - const std::optional &traceback) { + []([[maybe_unused]] File &self, + [[maybe_unused]] const std::optional &exc_type, + [[maybe_unused]] const std::optional + &exc_value, + [[maybe_unused]] const std::optional + &traceback) { // self.close(); }) .def("__iter__", [](File &self) { return &self; }) @@ -146,7 +144,7 @@ void define_file_io_bindings(py::module &m) { self.read_into( reinterpret_cast(image.mutable_data())); return image; - } catch (std::runtime_error &e) { + } catch (std::runtime_error &) { throw py::stop_iteration(); } }); @@ -160,6 +158,4 @@ void define_file_io_bindings(py::module &m) { .def_property_readonly("start", &ScanParameters::start) .def_property_readonly("stop", &ScanParameters::stop) .def_property_readonly("step", &ScanParameters::step); - -#pragma GCC diagnostic pop } \ No newline at end of file diff --git a/python/src/jungfrau_data_file.hpp b/python/src/jungfrau_data_file.hpp index 44ecd90c..1ff4ff9d 100644 --- a/python/src/jungfrau_data_file.hpp +++ b/python/src/jungfrau_data_file.hpp @@ -15,11 +15,6 @@ namespace py = pybind11; using namespace ::aare; -// Disable warnings for unused parameters, as we ignore some -// in the __exit__ method -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - auto read_dat_frame(JungfrauDataFile &self) { py::array_t header(1); py::array_t image({self.rows(), self.cols()}); @@ -94,20 +89,20 @@ void define_jungfrau_data_file_io_bindings(py::module &m) { )") .def("__enter__", [](JungfrauDataFile &self) { return &self; }) .def("__exit__", - [](JungfrauDataFile &self, - const std::optional &exc_type, - const std::optional &exc_value, - const std::optional &traceback) { + []([[maybe_unused]] JungfrauDataFile &self, + [[maybe_unused]] const std::optional &exc_type, + [[maybe_unused]] const std::optional + &exc_value, + [[maybe_unused]] const std::optional + &traceback) { // self.close(); }) .def("__iter__", [](JungfrauDataFile &self) { return &self; }) .def("__next__", [](JungfrauDataFile &self) { try { return read_dat_frame(self); - } catch (std::runtime_error &e) { + } catch (std::runtime_error &) { throw py::stop_iteration(); } }); } - -#pragma GCC diagnostic pop \ No newline at end of file diff --git a/python/src/raw_sub_file.hpp b/python/src/raw_sub_file.hpp index 5359c054..da858058 100644 --- a/python/src/raw_sub_file.hpp +++ b/python/src/raw_sub_file.hpp @@ -61,11 +61,6 @@ auto read_n_frames_from_RawSubFile(RawSubFile &self, size_t n_frames) { return py::make_tuple(header, image); } -// Disable warnings for unused parameters, as we ignore some -// in the __exit__ method -#pragma GCC diagnostic push -#pragma GCC diagnostic ignored "-Wunused-parameter" - void define_raw_sub_file_io_bindings(py::module &m) { py::class_(m, "RawSubFile") .def(py::init &exc_type, - const std::optional &exc_value, - const std::optional &traceback) {}) + []([[maybe_unused]] RawSubFile &self, + [[maybe_unused]] const std::optional &exc_type, + [[maybe_unused]] const std::optional + &exc_value, + [[maybe_unused]] const std::optional + &traceback) {}) .def("__iter__", [](RawSubFile &self) { return &self; }) .def("__next__", [](RawSubFile &self) { try { return read_frame_from_RawSubFile(self); - } catch (std::runtime_error &e) { + } catch (std::runtime_error &) { throw py::stop_iteration(); } }); } - -#pragma GCC diagnostic pop \ No newline at end of file diff --git a/src/JungfrauDataFile.cpp b/src/JungfrauDataFile.cpp index 5c19cbc3..6e77a0a6 100644 --- a/src/JungfrauDataFile.cpp +++ b/src/JungfrauDataFile.cpp @@ -221,7 +221,7 @@ JungfrauDataHeader JungfrauDataFile::read_header() { throw std::runtime_error(LOCATION + "Could not read header from file" + m_fp.error_msg()); } - m_fp.seek(-header_size, SEEK_CUR); + m_fp.seek(-static_cast(header_size), SEEK_CUR); return header; } diff --git a/src/RawMasterFile.cpp b/src/RawMasterFile.cpp index 4259c899..6e86de47 100644 --- a/src/RawMasterFile.cpp +++ b/src/RawMasterFile.cpp @@ -23,7 +23,7 @@ RawFileNameComponents::RawFileNameComponents( try { auto pos = m_base_name.rfind('_'); m_file_index = std::stoi(m_base_name.substr(pos + 1)); - } catch (const std::invalid_argument &e) { + } catch (const std::invalid_argument &) { throw std::runtime_error(LOCATION + "Could not parse file index"); } @@ -370,7 +370,7 @@ void RawMasterFile::parse_json(std::istream &is) { try { m_quad = j.at("Quad"); - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // keep the optional empty } // try{ @@ -384,7 +384,7 @@ void RawMasterFile::parse_json(std::istream &is) { if (digital_flag) { m_digital_samples = j.at("Digital Samples"); } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // keep the optional empty } try { @@ -393,7 +393,7 @@ void RawMasterFile::parse_json(std::istream &is) { if (m_transceiver_flag) { m_transceiver_samples = j.at("Transceiver Samples"); } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // keep the optional empty } try { @@ -414,7 +414,7 @@ void RawMasterFile::parse_json(std::istream &is) { m_scan_parameters .increment_stop(); // adjust for endpoint being included } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // not a scan } try { @@ -424,7 +424,7 @@ void RawMasterFile::parse_json(std::istream &is) { m_udp_port_types.value().push_back( string_to(elem)); } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // leave the optional empty } try { @@ -433,13 +433,13 @@ void RawMasterFile::parse_json(std::istream &is) { for (auto &elem : json_list_obj) { m_disabled_udp_ports.push_back(static_cast(elem)); } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { m_disabled_udp_ports .clear(); // empty list if not present in master file } try { m_udp_interfaces_per_module = {j.at("Number of UDP Interfaces"), 1}; - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { if (m_type == DetectorType::Eiger && m_quad == 1) m_udp_interfaces_per_module = {2, 1}; else if (m_type == DetectorType::Eiger) { @@ -485,7 +485,7 @@ void RawMasterFile::parse_json(std::istream &is) { } } - } catch (const json::out_of_range &e) { + } catch (const json::out_of_range &) { // fill ROI with full detector size if not present in master file m_rois.push_back( {0, m_detector_layout.col * static_cast(m_pixels_x), 0, diff --git a/src/decode.test.cpp b/src/decode.test.cpp index dec59e08..3fc3637f 100644 --- a/src/decode.test.cpp +++ b/src/decode.test.cpp @@ -25,7 +25,7 @@ TEST_CASE("test_adc_sar_05_decode64to16") { // test all bits by iteratting through the bitlist std::vector bitlist = {29, 19, 28, 18, 31, 21, 27, 20, 24, 23, 25, 22}; for (size_t i = 0; i < bitlist.size(); i++) { - input = 1UL << bitlist[i]; + input = 1ULL << bitlist[i]; output = aare::adc_sar_05_decode64to16(input); CHECK(output == (1 << i)); } @@ -95,7 +95,7 @@ TEST_CASE("Each byte buffer decoder maps to its own bit order") { }; for (const auto &c : cases) { - uint64_t word = (1UL << c.bit0) | (1UL << c.bit1); + uint64_t word = (1ULL << c.bit0) | (1ULL << c.bit1); std::vector buffer(8); std::memcpy(buffer.data(), &word, sizeof(word)); aare::NDView bytes(buffer.data(), {1, 8}); From fdc2d9499ff15b876515b861f69ec3c49069543e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Tue, 6 Oct 2026 14:49:25 +0200 Subject: [PATCH 07/16] Dev/win ci (#410) Added CI (wheels + native build for Windows) closes #397 --------- Co-authored-by: Tomas Celko --- .github/workflows/build_wheel.yml | 2 +- .github/workflows/build_windows.yml | 37 +++++++++++++++++++++++++++++ RELEASE.md | 3 +++ include/aare/Cluster.hpp | 6 ++--- include/aare/logger.hpp | 2 +- pyproject.toml | 3 +++ src/Dtype.cpp | 2 +- 7 files changed, 49 insertions(+), 6 deletions(-) create mode 100644 .github/workflows/build_windows.yml diff --git a/.github/workflows/build_wheel.yml b/.github/workflows/build_wheel.yml index 997a19d2..bc4f6683 100644 --- a/.github/workflows/build_wheel.yml +++ b/.github/workflows/build_wheel.yml @@ -17,7 +17,7 @@ jobs: runs-on: ${{ matrix.os }} strategy: matrix: - os: [ubuntu-latest,macos-latest] + os: [ubuntu-latest, macos-latest, windows-latest] steps: - uses: actions/checkout@v4 diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml new file mode 100644 index 00000000..5078cf5e --- /dev/null +++ b/.github/workflows/build_windows.yml @@ -0,0 +1,37 @@ +name: Build and test on Windows + +on: + workflow_dispatch: + push: + pull_request: + +jobs: + build: + runs-on: windows-latest + + steps: + - uses: actions/checkout@v6 + + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + + - name: Install Python dependencies + run: python -m pip install ninja numpy matplotlib pytest pytest-check boost-histogram + + # Puts cl.exe on the path so that CMake can use the Ninja generator + - uses: ilammy/msvc-dev-cmd@v1 + + - name: Configure + run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON + + - name: Build + run: cmake --build build + + - name: C++ unit tests + run: ctest --test-dir build --output-on-failure -j4 + + - name: Python unit tests + env: + PYTHONPATH: ${{ github.workspace }}\build + run: python -m pytest python/tests diff --git a/RELEASE.md b/RELEASE.md index 16f2322b..86d00ed2 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -7,6 +7,9 @@ - Added the Python ``xy`` type with ``row`` and ``col`` fields, enabling access to ``RawFile.geometry``, ``RawMasterFile.detector_layout``, and ``RawMasterFile.udp_interfaces_per_module``. It unpacks as ``row, col``. +- Added Windows wheels (``win_amd64``, Python 3.12 to 3.14) to the wheel + build, so releases publish them to PyPI alongside the Linux and macOS + wheels. ## 2026.9.30 diff --git a/include/aare/Cluster.hpp b/include/aare/Cluster.hpp index b08a2878..df67884c 100755 --- a/include/aare/Cluster.hpp +++ b/include/aare/Cluster.hpp @@ -83,7 +83,7 @@ struct Cluster { data[cluster_center_index - ClusterSizeX] + data[cluster_center_index - 1 - ClusterSizeX]; // subcluster top right from center - if (ClusterSizeX > 2) { + if constexpr (ClusterSizeX > 2) { sum_2x2_subcluster[1] = data[cluster_center_index] + data[cluster_center_index + 1] + @@ -91,7 +91,7 @@ struct Cluster { data[cluster_center_index - ClusterSizeX + 1]; } // subcluster bottom left from center - if (ClusterSizeY > 2) { + if constexpr (ClusterSizeY > 2) { sum_2x2_subcluster[2] = data[cluster_center_index] + data[cluster_center_index - 1] + @@ -99,7 +99,7 @@ struct Cluster { data[cluster_center_index + ClusterSizeX - 1]; } // subcluster bottom right from center - if (ClusterSizeX > 2 && ClusterSizeY > 2) { + if constexpr (ClusterSizeX > 2 && ClusterSizeY > 2) { sum_2x2_subcluster[3] = data[cluster_center_index] + data[cluster_center_index + 1] + diff --git a/include/aare/logger.hpp b/include/aare/logger.hpp index 6374aeea..b5504d73 100644 --- a/include/aare/logger.hpp +++ b/include/aare/logger.hpp @@ -160,7 +160,7 @@ class Logger { // TODO! Do we need to keep the runtime option? #define LOG(level) \ - if (level > AARE_LOG_LEVEL) \ + if constexpr (level > AARE_LOG_LEVEL) \ ; \ else if (level > aare::Logger::ReportingLevel()) \ ; \ diff --git a/pyproject.toml b/pyproject.toml index 6054356c..16636a01 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -28,6 +28,9 @@ build = "cp{312,313,314}-manylinux_x86_64" build = "cp{312,313,314}-macosx_*" archs = ["arm64"] +[tool.cibuildwheel.windows] +build = "cp{312,313,314}-win_amd64" + [tool.scikit-build] build.verbose = true diff --git a/src/Dtype.cpp b/src/Dtype.cpp index 08098874..9ad6d673 100644 --- a/src/Dtype.cpp +++ b/src/Dtype.cpp @@ -159,7 +159,7 @@ Dtype Dtype::from_bitdepth(uint8_t bitdepth) { std::string Dtype::to_string() const { char ec{}; - if (endian::native == endian::little) + if constexpr (endian::native == endian::little) ec = '<'; else ec = '>'; From bf0aa4a3bf67fc1af0dc76b4834c1e1de4b8f878 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Wed, 7 Oct 2026 12:04:54 +0200 Subject: [PATCH 08/16] Added missing header guards (#414) - Python extension. Originally left out since it didn't matter but good practice for future - to_string.hpp - this is the important one --- include/aare/to_string.hpp | 1 + python/src/bind_Cluster.hpp | 1 + python/src/bind_ClusterCollector.hpp | 1 + python/src/bind_ClusterFile.hpp | 1 + python/src/bind_ClusterFileSink.hpp | 1 + python/src/bind_ClusterFinder.hpp | 1 + python/src/bind_ClusterFinderMT.hpp | 1 + python/src/bind_ClusterVector.hpp | 1 + python/src/bind_Defs.hpp | 1 + python/src/bind_Eta.hpp | 1 + python/src/bind_FastPedestal.hpp | 1 + python/src/bind_Interpolator.hpp | 1 + python/src/bind_Pedestal.hpp | 1 + python/src/bind_PedestalTrackingPixelHistogram.hpp | 1 + python/src/bind_PixelHistogram.hpp | 1 + python/src/bind_PixelMap.hpp | 1 + python/src/bind_RawFile.hpp | 1 + python/src/bind_calibration.hpp | 1 + python/src/ctb_raw_file.hpp | 1 + python/src/file.hpp | 1 + python/src/fit.hpp | 1 + python/src/jungfrau_data_file.hpp | 1 + python/src/raw_master_file.hpp | 1 + python/src/raw_sub_file.hpp | 1 + python/src/var_cluster.hpp | 1 + tests/friend_test.hpp | 1 + tests/test_macros.hpp | 1 + 27 files changed, 27 insertions(+) diff --git a/include/aare/to_string.hpp b/include/aare/to_string.hpp index 547ebc09..1ca3332e 100644 --- a/include/aare/to_string.hpp +++ b/include/aare/to_string.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once /* *The file to_string.hpp contains conversion to and from string for various aare diff --git a/python/src/bind_Cluster.hpp b/python/src/bind_Cluster.hpp index 49618bf2..3e3e3c4f 100644 --- a/python/src/bind_Cluster.hpp +++ b/python/src/bind_Cluster.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/Cluster.hpp" #include diff --git a/python/src/bind_ClusterCollector.hpp b/python/src/bind_ClusterCollector.hpp index fab91522..815ca7e2 100644 --- a/python/src/bind_ClusterCollector.hpp +++ b/python/src/bind_ClusterCollector.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/ClusterCollector.hpp" #include "aare/ClusterFileSink.hpp" #include "aare/ClusterFinder.hpp" diff --git a/python/src/bind_ClusterFile.hpp b/python/src/bind_ClusterFile.hpp index 75c5458d..26af7813 100644 --- a/python/src/bind_ClusterFile.hpp +++ b/python/src/bind_ClusterFile.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CalculateEta.hpp" #include "aare/ClusterFile.hpp" #include "aare/defs.hpp" diff --git a/python/src/bind_ClusterFileSink.hpp b/python/src/bind_ClusterFileSink.hpp index 50600fcb..48820551 100644 --- a/python/src/bind_ClusterFileSink.hpp +++ b/python/src/bind_ClusterFileSink.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/ClusterCollector.hpp" #include "aare/ClusterFileSink.hpp" #include "aare/ClusterFinder.hpp" diff --git a/python/src/bind_ClusterFinder.hpp b/python/src/bind_ClusterFinder.hpp index 8872db29..e312bcb2 100644 --- a/python/src/bind_ClusterFinder.hpp +++ b/python/src/bind_ClusterFinder.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/ClusterCollector.hpp" #include "aare/ClusterFileSink.hpp" #include "aare/ClusterFinder.hpp" diff --git a/python/src/bind_ClusterFinderMT.hpp b/python/src/bind_ClusterFinderMT.hpp index 7e662841..d3a45962 100644 --- a/python/src/bind_ClusterFinderMT.hpp +++ b/python/src/bind_ClusterFinderMT.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/ClusterCollector.hpp" #include "aare/ClusterFileSink.hpp" #include "aare/ClusterFinder.hpp" diff --git a/python/src/bind_ClusterVector.hpp b/python/src/bind_ClusterVector.hpp index 13ad5a6d..9b4b779b 100644 --- a/python/src/bind_ClusterVector.hpp +++ b/python/src/bind_ClusterVector.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/ClusterCollector.hpp" #include "aare/ClusterFileSink.hpp" #include "aare/ClusterFinder.hpp" diff --git a/python/src/bind_Defs.hpp b/python/src/bind_Defs.hpp index e5f3cc3d..521d5529 100644 --- a/python/src/bind_Defs.hpp +++ b/python/src/bind_Defs.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include #include #include diff --git a/python/src/bind_Eta.hpp b/python/src/bind_Eta.hpp index e2b9302e..1f2dc32b 100644 --- a/python/src/bind_Eta.hpp +++ b/python/src/bind_Eta.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CalculateEta.hpp" #include "aare/to_string.hpp" diff --git a/python/src/bind_FastPedestal.hpp b/python/src/bind_FastPedestal.hpp index 5c278490..8bba55ea 100644 --- a/python/src/bind_FastPedestal.hpp +++ b/python/src/bind_FastPedestal.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/FastPedestal.hpp" #include "np_helper.hpp" diff --git a/python/src/bind_Interpolator.hpp b/python/src/bind_Interpolator.hpp index 3b7a015b..de391f3b 100644 --- a/python/src/bind_Interpolator.hpp +++ b/python/src/bind_Interpolator.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CalculateEta.hpp" #include "aare/Interpolator.hpp" #include "aare/NDArray.hpp" diff --git a/python/src/bind_Pedestal.hpp b/python/src/bind_Pedestal.hpp index 9e8af455..02b4d32f 100644 --- a/python/src/bind_Pedestal.hpp +++ b/python/src/bind_Pedestal.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/Pedestal.hpp" #include "np_helper.hpp" diff --git a/python/src/bind_PedestalTrackingPixelHistogram.hpp b/python/src/bind_PedestalTrackingPixelHistogram.hpp index 139b58a1..514ae263 100644 --- a/python/src/bind_PedestalTrackingPixelHistogram.hpp +++ b/python/src/bind_PedestalTrackingPixelHistogram.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/hist/PedestalTrackingPixelHistogram.hpp" #include "np_helper.hpp" diff --git a/python/src/bind_PixelHistogram.hpp b/python/src/bind_PixelHistogram.hpp index d3a1b462..b0c97e35 100644 --- a/python/src/bind_PixelHistogram.hpp +++ b/python/src/bind_PixelHistogram.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/hist/PixelHistogram.hpp" #include "np_helper.hpp" diff --git a/python/src/bind_PixelMap.hpp b/python/src/bind_PixelMap.hpp index 05d683e0..6aec76c3 100644 --- a/python/src/bind_PixelMap.hpp +++ b/python/src/bind_PixelMap.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/PixelMap.hpp" #include "np_helper.hpp" diff --git a/python/src/bind_RawFile.hpp b/python/src/bind_RawFile.hpp index 11d1d31a..27e6511c 100644 --- a/python/src/bind_RawFile.hpp +++ b/python/src/bind_RawFile.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" diff --git a/python/src/bind_calibration.hpp b/python/src/bind_calibration.hpp index cdb16b86..3cfc960e 100644 --- a/python/src/bind_calibration.hpp +++ b/python/src/bind_calibration.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/calibration.hpp" #include diff --git a/python/src/ctb_raw_file.hpp b/python/src/ctb_raw_file.hpp index b6338bdd..1808c01d 100644 --- a/python/src/ctb_raw_file.hpp +++ b/python/src/ctb_raw_file.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" diff --git a/python/src/file.hpp b/python/src/file.hpp index 030ba181..96960d91 100644 --- a/python/src/file.hpp +++ b/python/src/file.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" diff --git a/python/src/fit.hpp b/python/src/fit.hpp index b41b1596..617cd6ea 100644 --- a/python/src/fit.hpp +++ b/python/src/fit.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include #include #include diff --git a/python/src/jungfrau_data_file.hpp b/python/src/jungfrau_data_file.hpp index 1ff4ff9d..84f4e6f4 100644 --- a/python/src/jungfrau_data_file.hpp +++ b/python/src/jungfrau_data_file.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/JungfrauDataFile.hpp" #include "aare/defs.hpp" diff --git a/python/src/raw_master_file.hpp b/python/src/raw_master_file.hpp index d30762a4..5a0b049d 100644 --- a/python/src/raw_master_file.hpp +++ b/python/src/raw_master_file.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" diff --git a/python/src/raw_sub_file.hpp b/python/src/raw_sub_file.hpp index da858058..66ec7d8b 100644 --- a/python/src/raw_sub_file.hpp +++ b/python/src/raw_sub_file.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" diff --git a/python/src/var_cluster.hpp b/python/src/var_cluster.hpp index 1a3b674c..9734f406 100644 --- a/python/src/var_cluster.hpp +++ b/python/src/var_cluster.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include "aare/VarClusterFinder.hpp" #include "np_helper.hpp" diff --git a/tests/friend_test.hpp b/tests/friend_test.hpp index 2f2a4f3e..b06795d2 100644 --- a/tests/friend_test.hpp +++ b/tests/friend_test.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #define FRIEND_TEST(test_name) friend void test_name##_impl(); #define TEST_CASE_PRIVATE_FWD(test_name) \ diff --git a/tests/test_macros.hpp b/tests/test_macros.hpp index f6cc7dfd..4f4cab3d 100644 --- a/tests/test_macros.hpp +++ b/tests/test_macros.hpp @@ -1,4 +1,5 @@ // SPDX-License-Identifier: MPL-2.0 +#pragma once #include #include From 0eca8328d7bfc05567ee91b65be3f1ee6e08dcdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Fri, 9 Oct 2026 11:36:24 +0200 Subject: [PATCH 09/16] Dev/sccache (#415) - Use sccache: https://github.com/mozilla/sccache to speed up CI - Not huge benefits for Windows but mac and linux really improves --- .github/workflows/build_wheel.yml | 50 +++++++++++++++++++++++---- .github/workflows/build_windows.yml | 25 +++++++++++--- .github/workflows/build_with_docs.yml | 23 +++++++++--- conda-recipe/meta.yaml | 2 +- pyproject.toml | 10 ++++-- 5 files changed, 91 insertions(+), 19 deletions(-) diff --git a/.github/workflows/build_wheel.yml b/.github/workflows/build_wheel.yml index bc4f6683..d27abd6a 100644 --- a/.github/workflows/build_wheel.yml +++ b/.github/workflows/build_wheel.yml @@ -19,13 +19,51 @@ jobs: matrix: os: [ubuntu-latest, macos-latest, windows-latest] + env: + # Job level so that the build and the statistics step talk to the same + # sccache server configured for the GitHub Actions cache + SCCACHE_GHA_ENABLED: "true" + steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 + - uses: mozilla-actions/sccache-action@v0.0.11 + with: + version: "v0.18.0" + + # Without an MSVC environment scikit-build-core falls back to the Visual + # Studio generator on Windows, and MSBuild ignores the compiler launcher + - uses: TheMrMilchmann/setup-msvc-dev@v4.1.0 + if: runner.os == 'Windows' + with: + arch: x64 + + # Linux wheels build inside a manylinux container, which needs its own + # sccache binary and the cache credentials the action exported; its + # statistics are printed after each wheel since the host cannot see them. - name: Build wheels - run: pipx run cibuildwheel==3.4.0 + env: + CIBW_ENVIRONMENT_WINDOWS: CMAKE_GENERATOR=Ninja + CIBW_REPAIR_WHEEL_COMMAND_LINUX: >- + auditwheel repair -w {dest_dir} {wheel} && sccache --show-stats + CIBW_CONFIG_SETTINGS: >- + cmake.define.CMAKE_C_COMPILER_LAUNCHER=sccache + cmake.define.CMAKE_CXX_COMPILER_LAUNCHER=sccache + cmake.define.CMAKE_DISABLE_PRECOMPILE_HEADERS=ON + CIBW_ENVIRONMENT_PASS_LINUX: >- + SCCACHE_GHA_ENABLED ACTIONS_RESULTS_URL ACTIONS_RUNTIME_TOKEN + ACTIONS_CACHE_SERVICE_V2 + CIBW_BEFORE_ALL_LINUX: >- + curl -sSL https://github.com/mozilla/sccache/releases/download/v0.18.0/sccache-v0.18.0-x86_64-unknown-linux-musl.tar.gz + | tar -xz -C /usr/local/bin --strip-components=1 --wildcards '*/sccache' + && chmod +x /usr/local/bin/sccache + run: pipx run cibuildwheel==4.3.0 - - uses: actions/upload-artifact@v4 + - name: Compiler cache statistics + if: runner.os != 'Linux' + run: sccache --show-stats + + - uses: actions/upload-artifact@v7 with: name: cibw-wheels-${{ matrix.os }}-${{ strategy.job-index }} path: ./wheelhouse/*.whl @@ -34,12 +72,12 @@ jobs: name: Build source distribution runs-on: ubuntu-latest steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Build sdist run: pipx run build --sdist - - uses: actions/upload-artifact@v4 + - uses: actions/upload-artifact@v7 with: name: cibw-sdist path: dist/*.tar.gz @@ -54,7 +92,7 @@ jobs: # or, alternatively, upload to PyPI on every tag starting with 'v' (remove on: release above to use this) # if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') steps: - - uses: actions/download-artifact@v4 + - uses: actions/download-artifact@v8 with: # unpacks all CIBW artifacts into dist/ pattern: cibw-* diff --git a/.github/workflows/build_windows.yml b/.github/workflows/build_windows.yml index 5078cf5e..1a562f39 100644 --- a/.github/workflows/build_windows.yml +++ b/.github/workflows/build_windows.yml @@ -9,25 +9,42 @@ jobs: build: runs-on: windows-latest + env: + # sccache keeps compiled objects in the GitHub Actions cache, so later + # runs only recompile the translation units a change affects + SCCACHE_GHA_ENABLED: "true" + steps: - uses: actions/checkout@v6 - - uses: actions/setup-python@v5 + - uses: actions/setup-python@v7 with: python-version: "3.12" - name: Install Python dependencies run: python -m pip install ninja numpy matplotlib pytest pytest-check boost-histogram - # Puts cl.exe on the path so that CMake can use the Ninja generator - - uses: ilammy/msvc-dev-cmd@v1 + # Puts cl.exe on the path so that CMake can use the Ninja generator. + # Pinned to a release tag: the v4 ref of this action is a branch. + - uses: TheMrMilchmann/setup-msvc-dev@v4.1.0 + with: + arch: x64 + - uses: mozilla-actions/sccache-action@v0.0.11 + with: + version: "v0.18.0" + + # Precompiled headers are disabled: sccache cannot cache MSVC + # compilations that use one - name: Configure - run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON + run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON - name: Build run: cmake --build build + - name: Compiler cache statistics + run: sccache --show-stats + - name: C++ unit tests run: ctest --test-dir build --output-on-failure -j4 diff --git a/.github/workflows/build_with_docs.yml b/.github/workflows/build_with_docs.yml index bbae4f9b..9e2dc872 100644 --- a/.github/workflows/build_with_docs.yml +++ b/.github/workflows/build_with_docs.yml @@ -27,15 +27,19 @@ jobs: runs-on: ${{ matrix.platform }} + env: + # sccache keeps compiled objects in the GitHub Actions cache + SCCACHE_GHA_ENABLED: "true" + defaults: run: shell: "bash -l {0}" steps: - - uses: actions/checkout@v4 + - uses: actions/checkout@v7 - name: Get conda - uses: conda-incubator/setup-miniconda@v3 + uses: conda-incubator/setup-miniconda@v4 with: python-version: ${{ matrix.python-version }} environment-file: etc/dev-env.yml @@ -43,14 +47,23 @@ jobs: channels: conda-forge conda-remove-defaults: "true" + - uses: mozilla-actions/sccache-action@v0.0.11 + with: + version: "v0.18.0" + + # Precompiled headers are disabled because sccache does not cache + # compilations that use one - name: Build library and docs run: | mkdir build cd build - cmake .. -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DAARE_SYSTEM_LIBRARIES=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_DOCS=ON -DAARE_TESTS=ON -DAARE_WARNINGS_AS_ERRORS=ON + cmake .. -DCMAKE_BUILD_TYPE=${{env.BUILD_TYPE}} -DAARE_SYSTEM_LIBRARIES=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_DOCS=ON -DAARE_TESTS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON make -j 4 make docs + - name: Compiler cache statistics + run: sccache --show-stats + - name: C++ unit tests working-directory: ${{github.workspace}}/build run: ctest -C ${{env.BUILD_TYPE}} -j4 @@ -63,7 +76,7 @@ jobs: - name: Upload static files as artifact if: matrix.platform == 'ubuntu-latest' id: deployment - uses: actions/upload-pages-artifact@v3 + uses: actions/upload-pages-artifact@v5 with: path: build/docs/html/ deploy: @@ -76,7 +89,7 @@ jobs: steps: - name: Deploy to GitHub Pages id: deployment - uses: actions/deploy-pages@v4 + uses: actions/deploy-pages@v5 diff --git a/conda-recipe/meta.yaml b/conda-recipe/meta.yaml index d2d39b53..2e2264af 100644 --- a/conda-recipe/meta.yaml +++ b/conda-recipe/meta.yaml @@ -26,7 +26,7 @@ requirements: - python - pip - numpy >=2.1 - - scikit-build-core >=0.11 + - scikit-build-core >=1.0 - pybind11 >=3.0.3 - matplotlib # needed in host to solve the environment for run diff --git a/pyproject.toml b/pyproject.toml index 16636a01..e1176dcd 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,11 +1,12 @@ -[tool.scikit-build.metadata.version] +[[tool.dynamic-metadata]] +field = "version" provider = "scikit_build_core.metadata.regex" input = "VERSION" regex = '^(?P\d+(?:\.\d+)*(?:[\.\+\w]+)?)$' -result = "{version}" +result = "{version}" [build-system] -requires = ["scikit-build-core>=0.11", "pybind11", "numpy"] +requires = ["scikit-build-core>=1.0", "pybind11", "numpy"] build-backend = "scikit_build_core.build" [project] @@ -34,6 +35,9 @@ build = "cp{312,313,314}-win_amd64" [tool.scikit-build] build.verbose = true +# A fixed build directory keeps the absolute paths of the compiled sources +# stable between runs, which sccache needs for a cache hit +build-dir = "build/{wheel_tag}" cmake.build-type = "Release" install.components = ["python"] From f43e48cb901049c9adfb44ea5f9628f938aa69d7 Mon Sep 17 00:00:00 2001 From: AliceMazzoleni99 Date: Mon, 12 Oct 2026 17:21:25 +0200 Subject: [PATCH 10/16] added subview (#419) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - adds subview(ssize_t index) opeartor - returns subview with dropped dimension --------- Co-authored-by: Erik Fröjdh --- RELEASE.md | 1 + include/aare/NDView.hpp | 15 ++++++++++++ src/NDView.test.cpp | 53 +++++++++++++++++++++++++++-------------- 3 files changed, 51 insertions(+), 18 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index 86d00ed2..adb8405a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -10,6 +10,7 @@ - Added Windows wheels (``win_amd64``, Python 3.12 to 3.14) to the wheel build, so releases publish them to PyPI alongside the Linux and macOS wheels. +- added ``NDView::sub_view(index)`` operator returns a subview at index along dimension 0 ## 2026.9.30 diff --git a/include/aare/NDView.hpp b/include/aare/NDView.hpp index 715127c9..66ea7298 100644 --- a/include/aare/NDView.hpp +++ b/include/aare/NDView.hpp @@ -221,6 +221,21 @@ class NDView : public ArrayExpr, Ndim> { return NDView(buffer_ + first * strides_[0], new_shape); } + /** + * @brief Create a subview of a single index of the first dimension. + * This is useful for accessing a single frame in a batch of frames. + * @param index The index of the subview. + * @return A new NDView that is a subview of the current view. + * @throws std::runtime_error if the index is invalid. + */ + template 1) && D == Ndim, int> = 0> + NDView sub_view(const ssize_t index) const { + if (index < 0 || index >= shape_[0]) + throw std::runtime_error(LOCATION + "Invalid sub_view index"); + auto new_shape = drop_first_dim(shape_); + return NDView(buffer_ + index * strides_[0], new_shape); + } + private: template friend class NDView; diff --git a/src/NDView.test.cpp b/src/NDView.test.cpp index 59d231b3..808cb7a1 100644 --- a/src/NDView.test.cpp +++ b/src/NDView.test.cpp @@ -16,7 +16,7 @@ using aare::ssize_t; static_assert(std::is_convertible_v, NDView>); static_assert(!std::is_convertible_v, NDView>); -TEST_CASE("Calculate size from a shape") { +TEST_CASE("Calculate size from a shape", "[NDView]") { Shape<3> shape{2, 3, 4}; REQUIRE(num_elements(shape) == 24); @@ -34,7 +34,7 @@ TEST_CASE("Calculate size from a shape") { REQUIRE(num_elements(shape5) == 10485760000); } -TEST_CASE("Element reference 1D") { +TEST_CASE("Element reference 1D", "[NDView]") { std::vector vec; for (int i = 0; i != 10; ++i) { vec.push_back(i); @@ -47,7 +47,7 @@ TEST_CASE("Element reference 1D") { } } -TEST_CASE("Assign elements through () and []") { +TEST_CASE("Assign elements through () and []", "[NDView]") { std::vector vec; for (int i = 0; i != 10; ++i) { vec.push_back(i); @@ -80,7 +80,7 @@ TEST_CASE("Assign elements through () and []") { REQUIRE(data[9] == 9); } -TEST_CASE("Element reference 1D with a const NDView") { +TEST_CASE("Element reference 1D with a const NDView", "[NDView]") { std::vector vec; for (int i = 0; i != 10; ++i) { vec.push_back(i); @@ -93,7 +93,7 @@ TEST_CASE("Element reference 1D with a const NDView") { } } -TEST_CASE("Convert a mutable NDView to a const NDView") { +TEST_CASE("Convert a mutable NDView to a const NDView", "[NDView]") { std::vector vec{1, 2, 3, 4}; NDView mutable_view(vec.data(), Shape<2>{2, 2}); @@ -104,7 +104,7 @@ TEST_CASE("Convert a mutable NDView to a const NDView") { REQUIRE(const_view.strides() == mutable_view.strides()); } -TEST_CASE("Element reference 2D") { +TEST_CASE("Element reference 2D", "[NDView]") { std::vector vec(12); std::iota(vec.begin(), vec.end(), 0); @@ -120,7 +120,7 @@ TEST_CASE("Element reference 2D") { } } -TEST_CASE("Element reference 3D") { +TEST_CASE("Element reference 3D", "[NDView]") { std::vector vec; for (int i = 0; i != 24; ++i) { vec.push_back(i); @@ -139,7 +139,7 @@ TEST_CASE("Element reference 3D") { } } -TEST_CASE("Plus and minus with single value") { +TEST_CASE("Plus and minus with single value", "[NDView]") { std::vector vec(12); std::iota(vec.begin(), vec.end(), 0); NDView data(vec.data(), Shape<2>{3, 4}); @@ -161,7 +161,7 @@ TEST_CASE("Plus and minus with single value") { } } -TEST_CASE("Multiply and divide with single value") { +TEST_CASE("Multiply and divide with single value", "[NDView]") { std::vector vec; for (int i = 0; i != 12; ++i) { vec.push_back(i); @@ -185,7 +185,7 @@ TEST_CASE("Multiply and divide with single value") { } } -TEST_CASE("elementwise assign") { +TEST_CASE("elementwise assign", "[NDView]") { std::vector vec(25); NDView data(vec.data(), Shape<2>{5, 5}); @@ -195,7 +195,7 @@ TEST_CASE("elementwise assign") { } } -TEST_CASE("iterators") { +TEST_CASE("iterators", "[NDView]") { std::vector vec(12); std::iota(vec.begin(), vec.end(), 0); NDView data(vec.data(), Shape<1>{12}); @@ -220,7 +220,7 @@ TEST_CASE("iterators") { } } -TEST_CASE("divide with another NDView") { +TEST_CASE("divide with another NDView", "[NDView]") { std::vector vec0{9, 12, 3}; std::vector vec1{3, 2, 1}; std::vector result{3, 6, 3}; @@ -237,7 +237,7 @@ TEST_CASE("divide with another NDView") { } } -TEST_CASE("Retrieve shape") { +TEST_CASE("Retrieve shape", "[NDView]") { std::vector vec(12); std::iota(vec.begin(), vec.end(), 0); NDView data(vec.data(), Shape<2>{3, 4}); @@ -245,7 +245,7 @@ TEST_CASE("Retrieve shape") { REQUIRE(data.shape()[1] == 4); } -TEST_CASE("compare two views") { +TEST_CASE("compare two views", "[NDView]") { std::vector vec1(12); std::iota(vec1.begin(), vec1.end(), 0); NDView view1(vec1.data(), Shape<2>{3, 4}); @@ -257,7 +257,7 @@ TEST_CASE("compare two views") { REQUIRE((view1 == view2)); } -TEST_CASE("Compare two views with different size") { +TEST_CASE("Compare two views with different size", "[NDView]") { std::vector vec1(12); std::iota(vec1.begin(), vec1.end(), 0); NDView view1(vec1.data(), Shape<2>{3, 4}); @@ -269,7 +269,7 @@ TEST_CASE("Compare two views with different size") { REQUIRE_FALSE(view1 == view2); } -TEST_CASE("Compare two views with same size but different shape") { +TEST_CASE("Compare two views with same size but different shape", "[NDView]") { std::vector vec1(12); std::iota(vec1.begin(), vec1.end(), 0); NDView view1(vec1.data(), Shape<2>{3, 4}); @@ -281,7 +281,7 @@ TEST_CASE("Compare two views with same size but different shape") { REQUIRE_FALSE(view1 == view2); } -TEST_CASE("Create a view over a vector") { +TEST_CASE("Create a view over a vector", "[NDView]") { std::vector vec(12); std::iota(vec.begin(), vec.end(), 0); auto v = aare::make_view(vec); @@ -290,9 +290,26 @@ TEST_CASE("Create a view over a vector") { REQUIRE(v[11] == 11); } -TEST_CASE("NDView over byte") { +TEST_CASE("NDView over byte", "[NDView]") { std::vector buf(5); auto v = aare::make_view(buf); REQUIRE(v.shape()[0] == 5); REQUIRE(v[0] == std::byte{0}); } + +TEST_CASE("NDView subview", "[NDView]") { + std::vector vec(12); + std::iota(vec.begin(), vec.end(), 0); + NDView data(vec.data(), Shape<2>{3, 4}); + + auto subview = data.sub_view(1); + REQUIRE(subview.shape().size() == 1); + REQUIRE(subview.shape()[0] == 4); + CHECK(subview(0) == 4); + CHECK(subview(1) == 5); + CHECK(subview(2) == 6); + CHECK(subview(3) == 7); + + REQUIRE_THROWS_AS(data.sub_view(3), std::runtime_error); + REQUIRE_THROWS_AS(data.sub_view(-1), std::runtime_error); +} From 4408fe95b084ef87a808413d2d00d510e4d04d8a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Tue, 13 Oct 2026 15:00:45 +0200 Subject: [PATCH 11/16] Fixed failing tests due to updated bindings (#420) - New python bindings return a (1,n_bytes) array instead of a 1d array - Flatten on python side before transform --- RELEASE.md | 7 +++++++ python/aare/transform.py | 4 ++-- python/tests/test_Transformation.py | 31 +++++++++++++++++++++++++++++ 3 files changed, 40 insertions(+), 2 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index adb8405a..907c2668 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -12,6 +12,13 @@ wheels. - added ``NDView::sub_view(index)`` operator returns a subview at index along dimension 0 +### Bugfixes: + +- Fixed ``Matterhorn10Transform`` with 4 bit dynamic range and + ``Mythen302Transform`` failing with ``Expected 1D array, got 2D`` on frames + read through ``CtbRawFile``. The transforms now flatten the frame before + calling the decoders. + ## 2026.9.30 ### New Features: diff --git a/python/aare/transform.py b/python/aare/transform.py index 6d14231f..7739d69e 100644 --- a/python/aare/transform.py +++ b/python/aare/transform.py @@ -135,7 +135,7 @@ class Matterhorn10Transform: elif self.dynamic_range == 8: return np.take(data.view(np.uint8), self.pixel_map).reshape(self.num_counters, Matterhorn10.nRows, Matterhorn10.nCols) else: #dynamic range 4 - return np.take(_aare.expand4to8bit(data.view(np.uint8)), self.pixel_map).reshape(self.num_counters, Matterhorn10.nRows, Matterhorn10.nCols) + return np.take(_aare.expand4to8bit(data.view(np.uint8).reshape(-1)), self.pixel_map).reshape(self.num_counters, Matterhorn10.nRows, Matterhorn10.nCols) class Mythen302Transform: """ @@ -169,7 +169,7 @@ class Mythen302Transform: image : np.ndarray uint32 array of size 64, 3 """ - res = _aare.decode_my302(data, self.offset) + res = _aare.decode_my302(data.reshape(-1), self.offset) res = res.reshape( Mythen302Transform._n_channels, Mythen302Transform._n_counters ) diff --git a/python/tests/test_Transformation.py b/python/tests/test_Transformation.py index 0d91c10a..dad7d409 100644 --- a/python/tests/test_Transformation.py +++ b/python/tests/test_Transformation.py @@ -56,3 +56,34 @@ def test_matterhorn10_16bit_4counters(test_data_path): expected_data = np.tile(np.arange(255, -1, -1,dtype=np.uint16), (4, 256, 1)) # TODO: endianess issue ? assert np.all(frames == expected_data) + + +def test_matterhorn10_4bit_accepts_2d_frame(): + """CtbRawFile.read_frame returns a (1, n_bytes) array; the 4 bit path must accept it""" + n_bytes = (transform.Matterhorn10.nRows * transform.Matterhorn10.nCols * 4) // 8 + data = (np.arange(n_bytes) % 256).astype(np.uint8).reshape(1, n_bytes) + t = transform.Matterhorn10Transform(dynamic_range=4, num_counters=1) + + frames = t(data) + + assert frames.shape == (1, 256, 256) + assert frames.dtype == np.uint8 + + flat = data.reshape(-1) + nibbles = np.stack([flat & 0x0F, flat >> 4], axis=-1).reshape(-1) + expected = np.take(nibbles, t.pixel_map).reshape(1, 256, 256) + assert np.array_equal(frames, expected) + + +def test_mythen302_accepts_2d_frame(): + """CtbRawFile.read_frame returns a (1, n_bytes) array; Mythen302Transform must accept it""" + n_bytes = 64 * 3 * 3 + 2 # two extra bytes for the 4 bit offset + rng = np.random.default_rng(0) + data = rng.integers(0, 256, size=(1, n_bytes), dtype=np.uint8) + t = transform.Mythen302Transform(offset=4) + + res = t(data) + + assert res.shape == (64, 3) + assert res.dtype == np.uint32 + assert np.array_equal(res, t(data.reshape(-1))) From 5ccda7955d5fff9e0d2b3a4bc6d63383e998abf8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Tue, 13 Oct 2026 17:24:05 +0200 Subject: [PATCH 12/16] Assemble raw frames through one placement path (#421) First part of splitting up dev/gap. No gap pixels in here. - Extract the frame number sync loop into `RawFile::synchronized_frame_indices`. - Replace the two placement branches keyed on the detector layout with one loop. A part as wide as the ROI is read straight into the frame; a narrower part goes through a scratch buffer sized once at open, instead of a buffer allocated per frame. - The "x pos not 0" implementation error is gone, since the offset is computed for both paths. --- RELEASE.md | 5 + include/aare/RawFile.hpp | 14 +++ src/RawFile.cpp | 213 ++++++++++++++------------------------- 3 files changed, 97 insertions(+), 135 deletions(-) diff --git a/RELEASE.md b/RELEASE.md index 907c2668..cd35a69a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -12,6 +12,11 @@ wheels. - added ``NDView::sub_view(index)`` operator returns a subview at index along dimension 0 +### Other: + +- ``RawFile`` assembles multi-module frames through one placement path with + a scratch buffer allocated once at open, instead of allocating a module + buffer for every frame. ### Bugfixes: - Fixed ``Matterhorn10Transform`` with 4 bit dynamic range and diff --git a/include/aare/RawFile.hpp b/include/aare/RawFile.hpp index 4ef92962..e2666577 100644 --- a/include/aare/RawFile.hpp +++ b/include/aare/RawFile.hpp @@ -26,6 +26,10 @@ class RawFile : public FileInterface { std::vector>> m_subfiles; // [ROI][modules_per_ROI] + /// @brief Scratch space for one module part that is not contiguous in + /// the assembled frame. Sized at open to the largest part in any ROI. + std::vector m_part_buffer; + RawMasterFile m_master; size_t m_current_frame{}; @@ -154,6 +158,16 @@ class RawFile : public FileInterface { std::runtime_error frame_error(size_t frame_index, const std::string &message) const; + /** + * @brief Frame index to read from each module part of a ROI so that all + * parts hold the same detector frame number. Parts whose frame number + * lags are advanced; the index never moves backwards. + * @throws std::runtime_error if a part runs out of frames while + * synchronizing + */ + std::vector synchronized_frame_indices(size_t frame_index, + size_t roi_index); + /** * @brief read the frame at the given frame index into the image buffer * @param frame_index frame number to read diff --git a/src/RawFile.cpp b/src/RawFile.cpp index e416a27e..54adada6 100644 --- a/src/RawFile.cpp +++ b/src/RawFile.cpp @@ -9,6 +9,7 @@ #include "aare/logger.hpp" #include +#include #include #include @@ -49,13 +50,17 @@ RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode) std::optional min_frames; size_t max_frames = 0; + size_t max_part_bytes = 0; for (const auto &subfiles : m_subfiles) { for (const auto &subfile : subfiles) { const auto count = subfile->frames_in_file(); min_frames = min_frames ? std::min(*min_frames, count) : count; max_frames = std::max(max_frames, count); + max_part_bytes = + std::max(max_part_bytes, subfile->bytes_per_frame()); } } + m_part_buffer.resize(max_part_bytes); if (!min_frames) { throw std::runtime_error(fmt::format( "No raw subfiles selected by '{}'", fname.string())); @@ -338,6 +343,47 @@ Frame RawFile::get_frame(size_t frame_index, const size_t roi_index) { size_t RawFile::bytes_per_pixel() const { return m_master.bitdepth() / 8; } +std::vector RawFile::synchronized_frame_indices(size_t frame_index, + size_t roi_index) { + const auto &roi = m_master.roi_geometries().at(roi_index); + const size_t n_parts = roi.num_modules_in_roi(); + std::vector frame_indices(n_parts, frame_index); + if (n_parts == 1) { + return frame_indices; + } + + std::vector frame_numbers(n_parts); + for (size_t part_idx = 0; part_idx != n_parts; ++part_idx) { + frame_numbers[part_idx] = + m_subfiles[roi_index][part_idx]->frame_number(frame_index); + } + + while (!all_equal(frame_numbers)) { + // advance the part with the lowest frame number until all agree + const auto min_frame_idx = static_cast(std::distance( + frame_numbers.begin(), + std::min_element(frame_numbers.begin(), frame_numbers.end()))); + + frame_indices[min_frame_idx]++; + if (frame_indices[min_frame_idx] >= total_frames()) { + throw frame_error( + frame_index, + LOCATION + + fmt::format( + "Frame index {} out of range while synchronizing " + "module {} for ROI {}; last data file '{}'", + frame_indices[min_frame_idx], min_frame_idx, roi_index, + m_subfiles[roi_index][min_frame_idx] + ->current_path() + .string())); + } + frame_numbers[min_frame_idx] = + m_subfiles[roi_index][min_frame_idx]->frame_number( + frame_indices[min_frame_idx]); + } + return frame_indices; +} + void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer, const size_t roi_index, DetectorHeader *header) { LOG(logDEBUG) << "RawFile::get_frame_into(" << frame_index << ")"; @@ -349,148 +395,45 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer, "frames (indices are zero-based)", frame_index, total_frames())); } - std::vector frame_numbers( - m_master.roi_geometries().at(roi_index).num_modules_in_roi()); - std::vector frame_indices( - m_master.roi_geometries().at(roi_index).num_modules_in_roi(), - frame_index); - // sync the frame numbers + const auto &roi = m_master.roi_geometries().at(roi_index); + const auto frame_indices = + synchronized_frame_indices(frame_index, roi_index); - if (m_master.roi_geometries().at(roi_index).num_modules_in_roi() != - 1) { // if we have more than one module - for (size_t part_idx = 0; - part_idx != - m_master.roi_geometries().at(roi_index).num_modules_in_roi(); - ++part_idx) { - frame_numbers[part_idx] = - m_subfiles[roi_index][part_idx]->frame_number(frame_index); - } + const size_t bytes_per_pixel = m_master.bitdepth() / bits_per_byte; + const size_t roi_width = roi.pixels_x(); - // 1. if frame number vector is the same break - while (!all_equal(frame_numbers)) { + for (size_t part_idx = 0; part_idx != roi.num_modules_in_roi(); + ++part_idx) { + // origin and size of the part relative to the ROI + const auto &pos = m_master.geometry().get_module_geometries( + roi.module_indices_in_roi(part_idx)); + const auto width = static_cast(pos.width); + const auto height = static_cast(pos.height); + auto &subfile = *m_subfiles[roi_index][part_idx]; + subfile.seek(frame_indices[part_idx]); - // 2. find the index of the minimum frame number, - auto min_frame_idx = std::distance( - frame_numbers.begin(), - std::min_element(frame_numbers.begin(), frame_numbers.end())); + std::byte *dest = + frame_buffer + (static_cast(pos.origin_y) * roi_width + + static_cast(pos.origin_x)) * + bytes_per_pixel; - // 3. increase its index and update its respective frame - // number - frame_indices[min_frame_idx]++; - - // 4. if we can't increase its index => throw error - if (frame_indices[min_frame_idx] >= total_frames()) { - throw frame_error( - frame_index, - LOCATION + - fmt::format( - "Frame index {} out of range while synchronizing " - "module {} for ROI {}; last data file '{}'", - frame_indices[min_frame_idx], min_frame_idx, - roi_index, - m_subfiles[roi_index][min_frame_idx] - ->current_path() - .string())); - } - - frame_numbers[min_frame_idx] = - m_subfiles[roi_index][min_frame_idx]->frame_number( - frame_indices[min_frame_idx]); - } - } - - if (m_master.detector_layout().col == 1) { - // get the part from each subfile and copy it to the frame - for (size_t part_idx = 0; - part_idx != - m_master.roi_geometries().at(roi_index).num_modules_in_roi(); - ++part_idx) { - auto corrected_idx = frame_indices[part_idx]; - - // This is where we start writing - auto offset = - (m_master.geometry() - .get_module_geometries( - m_master.roi_geometries() - .at(roi_index) - .module_indices_in_roi(part_idx)) - .origin_y * - m_master.roi_geometries().at(roi_index).pixels_x() + - m_master.geometry() - .get_module_geometries( - m_master.roi_geometries() - .at(roi_index) - .module_indices_in_roi(part_idx)) - .origin_x) * - m_master.bitdepth() / 8; - - if (m_master.geometry() - .get_module_geometries(m_master.roi_geometries() - .at(roi_index) - .module_indices_in_roi(part_idx)) - .origin_x != 0) - throw frame_error( - frame_index, - LOCATION + - " Implementation error. x pos not 0."); // TODO: - // origin - // can still - // change if - // roi - // changes - // TODO! What if the files don't match? - m_subfiles[roi_index][part_idx]->seek(corrected_idx); - m_subfiles[roi_index][part_idx]->read_into(frame_buffer + offset, - header); - if (header) - ++header; - } - - } else { - // TODO! should we read row by row? - - // create a buffer large enough to hold a full module - auto bytes_per_part = - m_master.pixels_y() * m_master.pixels_x() * m_master.bitdepth() / - 8; // TODO! replace with image_size_in_bytes // TODO - // shouldnt it only be the module size? - check - - auto *part_buffer = new std::byte[bytes_per_part]; - - // TODO! if we have many submodules we should reorder them on - // the module level - - for (size_t part_idx = 0; - part_idx != - m_master.roi_geometries().at(roi_index).num_modules_in_roi(); - ++part_idx) { - auto pos = m_master.geometry().get_module_geometries( - m_master.roi_geometries().at(roi_index).module_indices_in_roi( - part_idx)); - auto corrected_idx = frame_indices[part_idx]; - - m_subfiles[roi_index][part_idx]->seek(corrected_idx); - m_subfiles[roi_index][part_idx]->read_into(part_buffer, header); - if (header) - ++header; - - for (size_t cur_row = 0; cur_row < static_cast(pos.height); - cur_row++) { - - auto irow = (pos.origin_y + cur_row); - auto icol = pos.origin_x; - auto dest = - (irow * m_master.roi_geometries().at(roi_index).pixels_x() + - icol); - dest = dest * m_master.bitdepth() / 8; - memcpy(frame_buffer + dest, - part_buffer + - cur_row * pos.width * m_master.bitdepth() / 8, - pos.width * m_master.bitdepth() / 8); + if (width == roi_width) { + // the part spans full rows of the ROI and is contiguous in the + // assembled frame + subfile.read_into(dest, header); + } else { + subfile.read_into(m_part_buffer.data(), header); + const size_t row_bytes = width * bytes_per_pixel; + const size_t roi_row_bytes = roi_width * bytes_per_pixel; + for (size_t row = 0; row < height; ++row) { + std::memcpy(dest + row * roi_row_bytes, + m_part_buffer.data() + row * row_bytes, row_bytes); } } - delete[] part_buffer; + if (header) { + ++header; + } } } From d1e432f8cabccf3693c7bb7b19fe53afac1d41d9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Thu, 15 Oct 2026 10:31:45 +0200 Subject: [PATCH 13/16] Add gap pixel insertion for images in memory (#423) Second part of splitting up dev/gap. Only the in-memory transform; no reader changes. - `GapPixels` and `ModuleGaps` configure 2 pixel gaps at the chip boundaries inside each Jungfrau or Eiger module and, only when module gaps are set, gaps between modules. Gap pixels get a fill value or, with `split_counts`, half of the neighbouring double size pixel. - `insert_gap_pixels` and `gapped_shape` apply the transform to an image in memory. Gap positions follow detector coordinates, so a ROI receives exactly the gaps that fall inside it. - Python bindings, tests and docs for the above. Chip and module sizes are fixed at 256 and 1024x512, so there is no detector type or quad argument: an Eiger quad is 512x512 and its only chip boundaries are at pixel 256. Reading raw files with gaps comes in the next PR. --- CMakeLists.txt | 3 + RELEASE.md | 7 + docs/src/GapPixels.rst | 101 +++++ docs/src/index.rst | 1 + docs/src/python/file/index.rst | 1 + docs/src/python/file/pyGapPixels.rst | 72 ++++ include/aare/GapPixels.hpp | 379 +++++++++++++++++ python/aare/__init__.py | 1 + python/src/bind_GapPixels.hpp | 174 ++++++++ python/src/module.cpp | 2 + python/tests/test_GapPixels.py | 130 ++++++ src/GapPixels.cpp | 104 +++++ src/GapPixels.test.cpp | 588 +++++++++++++++++++++++++++ 13 files changed, 1563 insertions(+) create mode 100644 docs/src/GapPixels.rst create mode 100644 docs/src/python/file/pyGapPixels.rst create mode 100644 include/aare/GapPixels.hpp create mode 100644 python/src/bind_GapPixels.hpp create mode 100644 python/tests/test_GapPixels.py create mode 100644 src/GapPixels.cpp create mode 100644 src/GapPixels.test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 9a6ba241..62a2a368 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -388,6 +388,7 @@ set(PUBLICHEADERS include/aare/ROI.hpp include/aare/ROIGeometry.hpp include/aare/DetectorGeometry.hpp + include/aare/GapPixels.hpp include/aare/JungfrauDataFile.hpp include/aare/logger.hpp include/aare/NDArray.hpp @@ -413,6 +414,7 @@ set(SourceFiles ${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ROIGeometry.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/GapPixels.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Dtype.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/File.cpp @@ -482,6 +484,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/GapPixels.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/RELEASE.md b/RELEASE.md index cd35a69a..0cd63bae 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -11,12 +11,19 @@ build, so releases publish them to PyPI alongside the Linux and macOS wheels. - added ``NDView::sub_view(index)`` operator returns a subview at index along dimension 0 +- Added ``GapPixels`` with ``insert_gap_pixels`` and ``gapped_shape`` to + insert gap pixels into Jungfrau and Eiger images in memory: 2 pixel gaps + at the chip boundaries inside each module and, only when ``ModuleGaps`` + is set, gaps between modules. Gap positions follow detector coordinates + before any ROI. Gap pixels receive a fill value or, with + ``split_counts``, half of the neighbouring double size pixel. ### Other: - ``RawFile`` assembles multi-module frames through one placement path with a scratch buffer allocated once at open, instead of allocating a module buffer for every frame. + ### Bugfixes: - Fixed ``Matterhorn10Transform`` with 4 bit dynamic range and diff --git a/docs/src/GapPixels.rst b/docs/src/GapPixels.rst new file mode 100644 index 00000000..0470878d --- /dev/null +++ b/docs/src/GapPixels.rst @@ -0,0 +1,101 @@ +GapPixels +============= + +Jungfrau and Eiger modules are built from 256x256 pixel chips. The pixels +at a chip edge are physically double size, so an image that places the +chips next to each other is distorted. Gap pixels restore the geometry by +inserting pixels at every chip boundary inside a module and, optionally, +gaps between modules. + +Gap positions are determined in detector coordinates before any ROI. +A ROI only receives the gaps that fall strictly inside it, so a ROI that +starts at column 256 has no gap on its left edge. + +Configuration +------------- + +``GapPixels`` holds the configuration. The chip size (256 pixels) and the +module size (1024x512 pixels) are fixed. An Eiger quad (512x512 pixels) +needs no special handling, since its only chip boundaries are at pixel 256. +Gaps of up to 1024 pixels are supported, far beyond the 2 to 10 pixels of +a real detector, and detector coordinates are limited to 2^28. + +================ ================ =========================================== +Field Default Meaning +================ ================ =========================================== +``chip_gap`` 2 Pixels inserted at each chip boundary + inside a module. Source column 255 expands + to the right and column 256 to the left. +``module_gaps`` unset ``ModuleGaps{x, y}`` inserted at module + boundaries. Unset means no pixels are + inserted between modules. + ``ModuleGaps{8, 36}`` matches the + slsDetectorPackage GUI. +``fill_value`` 0 Value written to gap pixels, converted to + the pixel type. Finite values wrap for + integer pixels; NaN, infinity and + magnitudes of 2^63 or more raise for + integer pixels. Module gaps always + receive this value. +``split_counts`` false Split the counts of the double size edge + pixels between the pixel and its gap pixel + instead of writing the fill value. +``seed`` unset Seed for the random assignment of integer + remainders in split mode. +================ ================ =========================================== + +Image sizes with the default configuration and with ``ModuleGaps{8, 36}``: + +====================================== ========== ========= =================== +Detector range Ungapped Defaults ``ModuleGaps{8,36}`` +====================================== ========== ========= =================== +One module, columns 1024 1030 1030 +Two modules side by side, columns 2048 2060 2068 +Two modules stacked, rows 1024 1028 1064 +ROI columns 100 to 400 300 302 302 +ROI columns 256 to 512 256 256 256 +====================================== ========== ========= =================== + +Split counts +------------ + +With ``split_counts`` every double size pixel at a chip boundary is halved +between itself and its gap pixel. Integer pixels put an odd remainder on +one side at random; floating point pixels are halved exactly. Columns are +split first and rows second, so a pixel at a chip corner ends up in four +parts with its total preserved. Module gaps are not split and keep the +fill value. Splitting only happens where a gap pixel is inserted, so an +edge pixel on a ROI border keeps its full value. Split mode requires a +chip gap of 2. + +Images in memory +---------------- + +``insert_gap_pixels`` inserts gap pixels into an image in memory, such as a +calibration map or a pedestal, and returns the gapped copy. The ROI gives +the detector coordinates of the image, so an image that covers part of the +detector receives exactly the gaps that fall inside it. + +.. code-block:: cpp + + #include "aare/GapPixels.hpp" + + aare::NDArray image = ...; // 512 x 1024 + auto gapped = aare::insert_gap_pixels( + image.view(), aare::ROI{0, 1024, 0, 512}, aare::GapPixels{}); + // gapped is 514 x 1030 + +``gapped_shape`` returns the shape of the gapped image of a ROI without +building it. + +.. doxygenstruct:: aare::ModuleGaps + :members: + :undoc-members: + +.. doxygenstruct:: aare::GapPixels + :members: + :undoc-members: + +.. doxygenfunction:: aare::gapped_shape + +.. doxygenfunction:: aare::insert_gap_pixels diff --git a/docs/src/index.rst b/docs/src/index.rst index 4f0151b7..c869d999 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -44,6 +44,7 @@ AARE NDView Frame File + GapPixels MultiThreadedFileReader Dtype Cluster diff --git a/docs/src/python/file/index.rst b/docs/src/python/file/index.rst index 0bcc4f9c..54e3fed2 100644 --- a/docs/src/python/file/index.rst +++ b/docs/src/python/file/index.rst @@ -8,6 +8,7 @@ File I/O pyClusterFile pyCtbRawFile pyFile + pyGapPixels pyJungfrauDataFile pyRawFile pyRawMasterFile diff --git a/docs/src/python/file/pyGapPixels.rst b/docs/src/python/file/pyGapPixels.rst new file mode 100644 index 00000000..020144c3 --- /dev/null +++ b/docs/src/python/file/pyGapPixels.rst @@ -0,0 +1,72 @@ +GapPixels +=================== + +.. py:currentmodule:: aare + +Jungfrau and Eiger modules are built from 256x256 pixel chips with double +size pixels at the chip edges. Gap pixels restore the geometry by inserting +pixels at every chip boundary inside a module and, optionally, gaps between +modules. +Gap positions are determined in detector coordinates before any ROI, so a +ROI only receives the gaps that fall strictly inside it. + +The chip size (256 pixels) and the module size (1024x512 pixels) are +fixed. An Eiger quad (512x512 pixels) needs no special handling, since its +only chip boundaries are at pixel 256. + +================ ================ =========================================== +Field Default Meaning +================ ================ =========================================== +``chip_gap`` 2 Pixels inserted at each chip boundary + inside a module. +``module_gaps`` None ``ModuleGaps(x, y)`` inserted at module + boundaries. None means no pixels are + inserted between modules. + ``ModuleGaps(8, 36)`` matches the + slsDetectorPackage GUI. +``fill_value`` 0 Value written to gap pixels, converted to + the pixel dtype. Module gaps always + receive this value. +``split_counts`` False Split the counts of the double size edge + pixels between the pixel and its gap + pixel. Integer remainders go to one side + at random. Requires a chip gap of 2. +``seed`` None Seed for the random remainders. +================ ================ =========================================== + +A single Jungfrau module of ``(512, 1024)`` pixels becomes ``(514, 1030)`` +with the defaults. Two stacked modules become ``(1028, 1030)`` with the +defaults and ``(1064, 1030)`` with ``ModuleGaps(8, 36)``. + +.. code-block:: python + + from aare import GapPixels, ModuleGaps, ROI, gapped_shape, insert_gap_pixels + + # defaults: chip gaps of 2 filled with 0, (512, 1024) -> (514, 1030) + gapped = insert_gap_pixels(image) + + # module gaps as in the slsDetectorPackage GUI, counts split at chip edges + gaps = GapPixels(module_gaps=ModuleGaps(8, 36), split_counts=True, seed=1) + gapped = insert_gap_pixels(image, gaps) + + # an image that covers columns 100 to 400 of the first ten rows + roi = ROI(100, 400, 0, 10) + gapped_shape(roi) # (10, 302) + part = insert_gap_pixels(image[:10, 100:400], gaps, roi=roi) + +``insert_gap_pixels`` accepts 2D ``uint8``, ``uint16``, ``uint32``, +``int32``, ``float32`` and ``float64`` arrays and returns a new array of the +same dtype. Pass ``roi`` when the image covers part of the detector. +``gapped_shape`` returns the shape of the gapped image of a ROI. + +.. autoclass:: GapPixels + :members: + :undoc-members: + +.. autoclass:: ModuleGaps + :members: + :undoc-members: + +.. autofunction:: insert_gap_pixels + +.. autofunction:: gapped_shape diff --git a/include/aare/GapPixels.hpp b/include/aare/GapPixels.hpp new file mode 100644 index 00000000..84b452f7 --- /dev/null +++ b/include/aare/GapPixels.hpp @@ -0,0 +1,379 @@ +// SPDX-License-Identifier: MPL-2.0 +#pragma once +#include "aare/NDArray.hpp" +#include "aare/NDView.hpp" +#include "aare/ROI.hpp" +#include "aare/defs.hpp" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace aare { + +/** + * @brief Pixels inserted at each boundary between modules. + */ +struct ModuleGaps { + ssize_t x{}; + ssize_t y{}; + + bool operator==(const ModuleGaps &other) const { + return x == other.x && y == other.y; + } + bool operator!=(const ModuleGaps &other) const { return !(*this == other); } +}; + +/** + * @brief Configuration for inserting gap pixels into Jungfrau and Eiger + * images. Chip and module sizes are fixed: 256x256 pixel chips in 1024x512 + * pixel modules. Gaps are inserted at the chip boundaries inside each module + * and, only when module_gaps is set, between modules. An Eiger quad is + * 512x512 pixels, so its only chip boundaries are at pixel 256 and the + * module width never comes into play. + * + * Gap positions are determined in detector coordinates before any ROI, so + * a ROI only receives the gaps that fall strictly inside it. + */ +struct GapPixels { + /// @brief Pixels inserted at each chip boundary inside a module, at + /// most 1024. Source column 255 expands to the right and column 256 to + /// the left. + ssize_t chip_gap{2}; + + /// @brief Pixels inserted at module boundaries, at most 1024 each. + /// Unset means no pixels are inserted between modules. + std::optional module_gaps{}; + + /// @brief Value written to gap pixels, converted to the pixel type. + /// Finite values wrap for integer pixel types; NaN, infinity and + /// magnitudes of 2^63 or more are rejected. Module gaps always receive + /// this value. + double fill_value{0}; + + /// @brief Split the counts of the double-size pixels at chip boundaries + /// between the pixel and its gap pixel instead of writing the fill + /// value. Integer remainders go to one side at random. Requires a chip + /// gap of 2. + bool split_counts{false}; + + /// @brief Seed for the random assignment of remainders. Unset means the + /// generator is seeded from the system. + std::optional seed{}; + + bool operator==(const GapPixels &other) const { + return chip_gap == other.chip_gap && module_gaps == other.module_gaps && + fill_value == other.fill_value && + split_counts == other.split_counts && seed == other.seed; + } + bool operator!=(const GapPixels &other) const { return !(*this == other); } +}; + +namespace detail { + +/** + * @brief Gap layout along one axis in ungapped detector coordinates. + */ +struct AxisGaps { + ssize_t chip{}; + ssize_t module{}; + ssize_t chip_gap{}; + ssize_t module_gap{}; + + /// @brief Gapped coordinate of an ungapped detector coordinate + ssize_t gapped(ssize_t coordinate) const { + const ssize_t chips_before = coordinate / chip; + const ssize_t modules_before = coordinate / module; + return coordinate + chip_gap * (chips_before - modules_before) + + module_gap * modules_before; + } + + /// @brief Gapped size of the detector range [min, max) + ssize_t extent(ssize_t min, ssize_t max) const { + return max <= min ? 0 : gapped(max - 1) - gapped(min) + 1; + } + + bool is_module_boundary(ssize_t boundary) const { + return boundary % module == 0; + } + + /// @brief Chip boundaries strictly inside [min, max). A boundary is the + /// detector coordinate of the first pixel of the chip after it. + std::vector inner_boundaries(ssize_t min, ssize_t max) const { + std::vector boundaries; + for (ssize_t boundary = (min / chip + 1) * chip; boundary < max; + boundary += chip) { + boundaries.push_back(boundary); + } + return boundaries; + } + + /// @brief Gapped column range [first, last] of the gap at a boundary, + /// relative to the gapped coordinate of `origin` + std::pair gap_range(ssize_t boundary, + ssize_t origin) const { + const ssize_t start = gapped(origin); + return {gapped(boundary - 1) + 1 - start, gapped(boundary) - 1 - start}; + } +}; + +struct GapLayout { + AxisGaps x; + AxisGaps y; +}; + +/** + * @brief Resolve the gap layout of a configuration + * @throws std::invalid_argument for an inconsistent configuration + */ +GapLayout gap_layout(const GapPixels &gaps); + +/// @brief Gapped shape {rows, cols} of a detector coordinate ROI +std::array gapped_shape(const ROI &roi, const GapLayout &layout); + +void validate_roi(const ROI &roi); +void validate_destination(const std::array &shape, const ROI &roi, + const GapLayout &layout); + +std::mt19937_64 make_generator(std::optional seed); + +/** + * @brief Convert the fill value to the pixel type + * + * Finite values wrap into integer pixel types. NaN, infinity and magnitudes + * of 2^63 or more have no integer representation and are rejected, since + * converting them would be undefined behaviour. + * @throws std::invalid_argument for a value without an integer + * representation when T is an integer type + */ +template T fill_as(double value) { + if constexpr (std::is_floating_point_v) { + return static_cast(value); + } else { + if (!(std::fabs(value) < 0x1p63)) { + throw std::invalid_argument( + LOCATION + fmt::format("Fill value {} cannot be converted to " + "an integer pixel type", + value)); + } + return static_cast(static_cast(value)); + } +} + +/** + * @brief Write `value` to every gap row and gap column inside the ROI + * @param destination gapped image of `roi` + * @param roi detector coordinates of the destination image + * @param layout resolved gap layout + * @param value value written to the gap pixels + */ +template +void fill_gap_pixels(NDView destination, const ROI &roi, + const GapLayout &layout, T value) { + validate_destination(destination.shape(), roi, layout); + const ssize_t rows = destination.shape(0); + const ssize_t cols = destination.shape(1); + + for (const auto boundary : layout.x.inner_boundaries(roi.xmin, roi.xmax)) { + const auto [first, last] = layout.x.gap_range(boundary, roi.xmin); + for (ssize_t row = 0; row < rows; ++row) { + for (ssize_t col = first; col <= last; ++col) { + destination(row, col) = value; + } + } + } + for (const auto boundary : layout.y.inner_boundaries(roi.ymin, roi.ymax)) { + const auto [first, last] = layout.y.gap_range(boundary, roi.ymin); + for (ssize_t row = first; row <= last; ++row) { + for (ssize_t col = 0; col < cols; ++col) { + destination(row, col) = value; + } + } + } +} + +/** + * @brief Copy a detector coordinate rectangle into its gapped position + * @param source ungapped pixels of `source_rect` + * @param source_rect detector coordinates of `source`, inside `roi` + * @param destination gapped image of `roi` + * @param roi detector coordinates of the destination image + * @param layout resolved gap layout + * @note Gap pixels are not written + */ +template +void copy_with_gaps(NDView source, const ROI &source_rect, + NDView destination, const ROI &roi, + const GapLayout &layout) { + validate_destination(destination.shape(), roi, layout); + validate_roi(source_rect); + if (source_rect.xmin < roi.xmin || source_rect.xmax > roi.xmax || + source_rect.ymin < roi.ymin || source_rect.ymax > roi.ymax) { + throw std::invalid_argument(LOCATION + + "Source rectangle extends outside the ROI"); + } + if (source.shape(0) != source_rect.height() || + source.shape(1) != source_rect.width()) { + throw std::invalid_argument( + LOCATION + "Source shape does not match the source rectangle"); + } + if (source.strides()[1] != 1 || destination.strides()[1] != 1) { + throw std::invalid_argument( + LOCATION + "Source and destination rows must be contiguous"); + } + if (source_rect.width() == 0 || source_rect.height() == 0) { + return; + } + + // contiguous column segments [begin, end) between chip boundaries + std::vector> segments; + ssize_t begin = source_rect.xmin; + for (const auto boundary : + layout.x.inner_boundaries(source_rect.xmin, source_rect.xmax)) { + segments.emplace_back(begin, boundary); + begin = boundary; + } + segments.emplace_back(begin, source_rect.xmax); + + const ssize_t x0 = layout.x.gapped(roi.xmin); + const ssize_t y0 = layout.y.gapped(roi.ymin); + for (ssize_t y = source_rect.ymin; y < source_rect.ymax; ++y) { + const T *source_row = &source(y - source_rect.ymin, 0); + T *destination_row = &destination(layout.y.gapped(y) - y0, 0); + for (const auto &[first, last] : segments) { + std::memcpy(destination_row + layout.x.gapped(first) - x0, + source_row + first - source_rect.xmin, + static_cast(last - first) * sizeof(T)); + } + } +} + +/** + * @brief Split the counts of the double-size pixels at every chip boundary + * inside the ROI between the pixel and its gap pixel. Columns are split + * first and rows second, so corner pixels end up in four parts with their + * total preserved. Module boundaries are left untouched. + * @param destination gapped image of `roi` after copy_with_gaps + * @param roi detector coordinates of the destination image + * @param layout resolved gap layout + * @param generator source of the random remainder assignment + */ +template +void split_edge_counts(NDView destination, const ROI &roi, + const GapLayout &layout, std::mt19937_64 &generator) { + validate_destination(destination.shape(), roi, layout); + if (layout.x.chip_gap != 2 || layout.y.chip_gap != 2) { + throw std::invalid_argument( + LOCATION + "Splitting counts requires a chip gap of 2"); + } + + auto halve = [&](T &pixel, T &gap) { + if constexpr (std::is_floating_point_v) { + const T half = pixel / 2; + pixel = half; + gap = half; + } else { + T low = pixel / 2; + T high = pixel - low; + if (low != high && (generator() & 1u)) { + std::swap(low, high); + } + pixel = low; + gap = high; + } + }; + + const ssize_t x0 = layout.x.gapped(roi.xmin); + const ssize_t y0 = layout.y.gapped(roi.ymin); + const ssize_t cols = destination.shape(1); + + // columns: every pixel row of every chip boundary that is not a module + // boundary + std::vector chip_columns; + for (const auto boundary : layout.x.inner_boundaries(roi.xmin, roi.xmax)) { + if (!layout.x.is_module_boundary(boundary)) { + chip_columns.push_back(boundary); + } + } + for (ssize_t y = roi.ymin; y < roi.ymax; ++y) { + const ssize_t row = layout.y.gapped(y) - y0; + for (const auto boundary : chip_columns) { + const ssize_t left = layout.x.gapped(boundary - 1) - x0; + const ssize_t right = layout.x.gapped(boundary) - x0; + halve(destination(row, left), destination(row, left + 1)); + halve(destination(row, right), destination(row, right - 1)); + } + } + + // rows: every gapped column except module gaps + std::vector module_gap_column(static_cast(cols), false); + for (const auto boundary : layout.x.inner_boundaries(roi.xmin, roi.xmax)) { + if (layout.x.is_module_boundary(boundary)) { + const auto [first, last] = layout.x.gap_range(boundary, roi.xmin); + for (ssize_t col = first; col <= last; ++col) { + module_gap_column[static_cast(col)] = true; + } + } + } + for (const auto boundary : layout.y.inner_boundaries(roi.ymin, roi.ymax)) { + if (layout.y.is_module_boundary(boundary)) { + continue; + } + const ssize_t top = layout.y.gapped(boundary - 1) - y0; + const ssize_t bottom = layout.y.gapped(boundary) - y0; + for (ssize_t col = 0; col < cols; ++col) { + if (module_gap_column[static_cast(col)]) { + continue; + } + halve(destination(top, col), destination(top + 1, col)); + halve(destination(bottom, col), destination(bottom - 1, col)); + } + } +} + +} // namespace detail + +/** + * @brief Shape {rows, cols} of the gapped image of a detector coordinate ROI + * @param roi detector coordinates of the image + * @param gaps gap configuration + * @throws std::invalid_argument for an invalid ROI or configuration + */ +std::array gapped_shape(const ROI &roi, const GapPixels &gaps = {}); + +/** + * @brief Insert gap pixels into an image + * @param source ungapped image of `roi` + * @param roi detector coordinates of `source` + * @param gaps gap configuration + * @return gapped image + * @throws std::invalid_argument for an invalid configuration, a fill value + * that cannot be converted to the pixel type or a source shape that does + * not match the ROI + */ +template +NDArray insert_gap_pixels(NDView source, const ROI &roi, + const GapPixels &gaps = {}) { + const auto layout = detail::gap_layout(gaps); + detail::validate_roi(roi); + const T fill = detail::fill_as(gaps.fill_value); + NDArray result(detail::gapped_shape(roi, layout)); + detail::fill_gap_pixels(result.view(), roi, layout, fill); + detail::copy_with_gaps(source, roi, result.view(), roi, layout); + if (gaps.split_counts) { + auto generator = detail::make_generator(gaps.seed); + detail::split_edge_counts(result.view(), roi, layout, generator); + } + return result; +} + +} // namespace aare diff --git a/python/aare/__init__.py b/python/aare/__init__.py index ea3f4c39..6394489c 100644 --- a/python/aare/__init__.py +++ b/python/aare/__init__.py @@ -25,6 +25,7 @@ from ._aare import Pedestal_d, Pedestal_f, ClusterFinder_Cluster3x3i, VarCluster from ._aare import DetectorType, FrameDiscardPolicy, ReadoutMode from ._aare import hitmap from ._aare import ROI +from ._aare import GapPixels, ModuleGaps, insert_gap_pixels, gapped_shape from ._aare import xy from ._aare import corner diff --git a/python/src/bind_GapPixels.hpp b/python/src/bind_GapPixels.hpp new file mode 100644 index 00000000..41874ca5 --- /dev/null +++ b/python/src/bind_GapPixels.hpp @@ -0,0 +1,174 @@ +// SPDX-License-Identifier: MPL-2.0 +#pragma once +#include "aare/GapPixels.hpp" +#include "aare/ROI.hpp" +#include "aare/defs.hpp" +#include "np_helper.hpp" + +#include +#include +#include +#include +#include +#include + +namespace py = pybind11; +using namespace ::aare; + +namespace { + +template +py::array insert_gap_pixels_typed(const py::array &image, const ROI &roi, + const GapPixels &gaps) { + py::array_t typed(image); + auto source = make_const_view_2d(typed); + auto *result = new NDArray(insert_gap_pixels(source, roi, gaps)); + return return_image_data(result); +} + +} // namespace + +void define_gap_pixels_bindings(py::module &m) { + py::class_(m, "ModuleGaps", R"( + Pixels inserted at each boundary between modules. + )") + .def(py::init<>()) + .def(py::init(), py::arg("x"), py::arg("y")) + .def_readwrite("x", &ModuleGaps::x) + .def_readwrite("y", &ModuleGaps::y) + .def(py::self == py::self) + .def(py::self != py::self) + .def("__repr__", [](const ModuleGaps &self) { + return fmt::format("ModuleGaps(x={}, y={})", self.x, self.y); + }); + + py::class_(m, "GapPixels", R"( + Configuration for inserting gap pixels into Jungfrau and Eiger + images. Chip and module sizes are fixed: 256x256 pixel chips in + 1024x512 pixel modules. + + Parameters + ---------- + chip_gap : int + Pixels inserted at each chip boundary inside a module, at most + 1024. Source column 255 expands to the right and column 256 to + the left. + module_gaps : ModuleGaps, optional + Pixels inserted at module boundaries, at most 1024 each. None + means no pixels are inserted between modules. + fill_value : float + Value written to gap pixels, converted to the pixel type. Finite + values wrap for integer images; NaN, infinity and magnitudes of + 2**63 or more raise ValueError for integer images. Module gaps + always receive this value. + split_counts : bool + Split the counts of the double-size pixels at chip boundaries + between the pixel and its gap pixel. Integer remainders go to + one side at random. Requires a chip gap of 2. + seed : int, optional + Seed for the random assignment of remainders. + )") + .def( + py::init([](ssize_t chip_gap, std::optional module_gaps, + double fill_value, bool split_counts, + std::optional seed) { + GapPixels gaps; + gaps.chip_gap = chip_gap; + gaps.module_gaps = module_gaps; + gaps.fill_value = fill_value; + gaps.split_counts = split_counts; + gaps.seed = seed; + return gaps; + }), + py::arg("chip_gap") = 2, py::arg("module_gaps") = py::none(), + py::arg("fill_value") = 0.0, py::arg("split_counts") = false, + py::arg("seed") = py::none()) + .def_readwrite("chip_gap", &GapPixels::chip_gap) + .def_readwrite("module_gaps", &GapPixels::module_gaps) + .def_readwrite("fill_value", &GapPixels::fill_value) + .def_readwrite("split_counts", &GapPixels::split_counts) + .def_readwrite("seed", &GapPixels::seed) + .def(py::self == py::self) + .def(py::self != py::self) + .def("__repr__", [](const GapPixels &self) { + return fmt::format( + "GapPixels(chip_gap={}, module_gaps={}, fill_value={}, " + "split_counts={}, seed={})", + self.chip_gap, + self.module_gaps + ? fmt::format("ModuleGaps(x={}, y={})", self.module_gaps->x, + self.module_gaps->y) + : "None", + self.fill_value, self.split_counts ? "True" : "False", + self.seed ? fmt::format("{}", *self.seed) : "None"); + }); + + m.def( + "gapped_shape", + [](const ROI &roi, const GapPixels &gaps) { + const auto shape = gapped_shape(roi, gaps); + return py::make_tuple(shape[0], shape[1]); + }, + py::arg("roi"), py::arg("gaps") = GapPixels{}, R"( + Shape (rows, cols) of the gapped image of a detector coordinate ROI. + + Parameters + ---------- + roi : ROI + Detector coordinates of the image. + gaps : GapPixels + Gap configuration. + )"); + + m.def( + "insert_gap_pixels", + [](const py::array &image, const GapPixels &gaps, + std::optional roi) -> py::array { + if (image.ndim() != 2) { + throw py::value_error( + fmt::format("Expected a 2D image, got {}D", image.ndim())); + } + const ROI rect = + roi.value_or(ROI{0, image.shape(1), 0, image.shape(0)}); + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + if (py::isinstance>(image)) { + return insert_gap_pixels_typed(image, rect, gaps); + } + throw py::type_error( + "Unsupported dtype, expected uint8, uint16, uint32, int32, " + "float32 or float64"); + }, + py::arg("image"), py::arg("gaps") = GapPixels{}, + py::arg("roi") = py::none(), R"( + Insert gap pixels into a 2D image. + + Parameters + ---------- + image : numpy.ndarray + Ungapped image of ``roi``. + gaps : GapPixels + Gap configuration. + roi : ROI, optional + Detector coordinates of the image. Defaults to the full image + starting at pixel (0, 0). + + Returns + ------- + numpy.ndarray + New array with the same dtype as ``image``. + )"); +} diff --git a/python/src/module.cpp b/python/src/module.cpp index b83deaca..0df7fe8d 100644 --- a/python/src/module.cpp +++ b/python/src/module.cpp @@ -14,6 +14,7 @@ #include "bind_Defs.hpp" #include "bind_Eta.hpp" #include "bind_FastPedestal.hpp" +#include "bind_GapPixels.hpp" #include "bind_Interpolator.hpp" #include "bind_MultiThreadedFileReader.hpp" #include "bind_Pedestal.hpp" @@ -156,6 +157,7 @@ PYBIND11_MODULE(_aare, m) { register_calculate_3x3eta(m); define_defs_bindings(m); + define_gap_pixels_bindings(m); using Sum_index_pair_d = Sum_index_pair; PYBIND11_NUMPY_DTYPE(Sum_index_pair_d, sum, index); diff --git a/python/tests/test_GapPixels.py b/python/tests/test_GapPixels.py new file mode 100644 index 00000000..9fde15eb --- /dev/null +++ b/python/tests/test_GapPixels.py @@ -0,0 +1,130 @@ +# SPDX-License-Identifier: MPL-2.0 +import numpy as np +import pytest + +from aare import GapPixels, ModuleGaps, ROI, gapped_shape, insert_gap_pixels + + +def reference(image, boundaries_x, boundaries_y, fill=0): + """Insert gap columns and rows with numpy: boundaries map a source index to + the number of pixels inserted before it.""" + cols = [index for index, count in boundaries_x for _ in range(count)] + rows = [index for index, count in boundaries_y for _ in range(count)] + result = np.insert(image, cols, fill, axis=1) + return np.insert(result, rows, fill, axis=0) + + +def test_configuration_defaults_and_equality(): + gaps = GapPixels() + assert gaps.chip_gap == 2 + assert gaps.module_gaps is None + assert gaps.fill_value == 0 + assert gaps.split_counts is False + assert gaps.seed is None + assert gaps == GapPixels() + assert gaps != GapPixels(fill_value=1) + + gaps = GapPixels(chip_gap=4, module_gaps=ModuleGaps(8, 36), fill_value=-1, split_counts=False, seed=5) + assert gaps.module_gaps == ModuleGaps(x=8, y=36) + assert gaps.seed == 5 + assert "ModuleGaps(x=8, y=36)" in repr(gaps) + gaps.module_gaps = None + assert gaps.module_gaps is None + + +def test_gapped_shape(): + assert gapped_shape(ROI(0, 1024, 0, 512)) == (514, 1030) + assert gapped_shape(ROI(0, 1024, 0, 1024)) == (1028, 1030) + assert gapped_shape(ROI(0, 1024, 0, 1024), GapPixels(module_gaps=ModuleGaps(8, 36))) == (1064, 1030) + assert gapped_shape(ROI(0, 512, 0, 512)) == (514, 514) # Eiger quad + assert gapped_shape(ROI(256, 512, 0, 256)) == (256, 256) + assert gapped_shape(ROI(255, 257, 0, 1)) == (1, 4) + + +@pytest.mark.parametrize("dtype", [np.uint8, np.uint16, np.uint32, np.int32, np.float32, np.float64]) +def test_insert_gap_pixels_matches_numpy(dtype): + rng = np.random.default_rng(1) + image = rng.integers(0, 200, size=(512, 1024)).astype(dtype) + result = insert_gap_pixels(image, GapPixels(fill_value=3)) + expected = reference(image, [(256, 2), (512, 2), (768, 2)], [(256, 2)], fill=3) + assert result.dtype == image.dtype + assert result.shape == (514, 1030) + assert (result == expected).all() + + +def test_insert_gap_pixels_without_module_gaps(): + # two stacked modules: chip gaps at rows 256 and 768, none at the module + # boundary at row 512 + image = np.arange(1024 * 1024, dtype=np.uint32).reshape(1024, 1024) + result = insert_gap_pixels(image) + expected = reference(image, [(256, 2), (512, 2), (768, 2)], [(256, 2), (768, 2)]) + assert result.shape == (1028, 1030) + assert (result == expected).all() + + +def test_insert_gap_pixels_with_module_gaps(): + image = np.arange(1024 * 1024, dtype=np.uint32).reshape(1024, 1024) + gaps = GapPixels(module_gaps=ModuleGaps(8, 36), fill_value=9) + result = insert_gap_pixels(image, gaps) + expected = reference(image, [(256, 2), (512, 2), (768, 2)], [(256, 2), (512, 36), (768, 2)], fill=9) + assert result.shape == (1064, 1030) + assert (result == expected).all() + + +def test_insert_gap_pixels_in_roi(): + image = np.array([[11, 22]], dtype=np.uint16) + result = insert_gap_pixels(image, roi=ROI(255, 257, 10, 11)) + assert result.tolist() == [[11, 0, 0, 22]] + + # a gap on the ROI border is not inserted + image = np.arange(8, dtype=np.uint16).reshape(2, 4) + result = insert_gap_pixels(image, roi=ROI(256, 260, 0, 2)) + assert (result == image).all() + + +def test_insert_gap_pixels_split_counts(): + rng = np.random.default_rng(2) + image = rng.integers(0, 1000, size=(512, 1024)).astype(np.uint32) + gaps = GapPixels(split_counts=True, seed=3) + first = insert_gap_pixels(image, gaps) + second = insert_gap_pixels(image, gaps) + assert first.sum() == image.sum() + assert (first == second).all() + # edge pixel and its gap pixel hold floor and ceil of the half; row 255 + # is excluded because it is split again vertically + pair = np.stack([first[:255, 255], first[:255, 256]]) + assert (pair.sum(axis=0) == image[:255, 255]).all() + assert (pair.max(axis=0) == (image[:255, 255] + 1) // 2).all() + + halves = insert_gap_pixels(np.full((2, 2), 3.0), gaps, roi=ROI(255, 257, 255, 257)) + assert (halves == 0.75).all() + + +def test_insert_gap_pixels_rejects_bad_input(): + image = np.zeros((400, 400), dtype=np.uint16) + with pytest.raises(ValueError): + insert_gap_pixels(image, roi=ROI(0, 401, 0, 400)) + with pytest.raises(ValueError): + insert_gap_pixels(np.zeros((2, 2, 2), dtype=np.uint16)) + with pytest.raises(TypeError): + insert_gap_pixels(np.zeros((2, 2), dtype=np.int64)) + with pytest.raises(ValueError): + insert_gap_pixels(image, GapPixels(split_counts=True, chip_gap=4)) + with pytest.raises(ValueError): + insert_gap_pixels(image, GapPixels(fill_value=float("nan"))) + with pytest.raises(ValueError): + insert_gap_pixels(image, GapPixels(fill_value=1e20)) + with pytest.raises(ValueError): + insert_gap_pixels(image, GapPixels(chip_gap=6148914691236517205)) + with pytest.raises(ValueError): + insert_gap_pixels(image, GapPixels(module_gaps=ModuleGaps(8, 2000))) + with pytest.raises(ValueError): + insert_gap_pixels(image, roi=ROI(2**40, 2**40 + 400, 0, 400)) + + +def test_insert_gap_pixels_nan_fill_for_float_images(): + image = np.ones((2, 2), dtype=np.float32) + result = insert_gap_pixels(image, GapPixels(fill_value=float("nan")), roi=ROI(255, 257, 0, 2)) + assert result.shape == (2, 4) + assert np.isnan(result[:, 1:3]).all() + assert (result[:, [0, 3]] == 1).all() diff --git a/src/GapPixels.cpp b/src/GapPixels.cpp new file mode 100644 index 00000000..109b6981 --- /dev/null +++ b/src/GapPixels.cpp @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/GapPixels.hpp" + +#include + +#include + +namespace aare { +namespace detail { + +namespace { + +constexpr ssize_t chip = 256; +constexpr ssize_t module_x = 1024; +constexpr ssize_t module_y = 512; + +// Gap sizes and detector coordinates are bounded so that gapped coordinates +// and gapped image sizes cannot overflow ssize_t. A gapped coordinate is at +// most (1 + 2 * max_gap / chip) times the detector coordinate, and the image +// size is the product of two such extents. +constexpr ssize_t max_gap = 1024; +constexpr ssize_t max_coordinate = ssize_t{1} << 28; +constexpr ssize_t max_extent = max_coordinate * (1 + 2 * max_gap / chip); +static_assert(max_extent <= std::numeric_limits::max() / max_extent, + "gapped image sizes must fit in ssize_t"); + +} // namespace + +GapLayout gap_layout(const GapPixels &gaps) { + if (gaps.chip_gap < 0) { + throw std::invalid_argument(LOCATION + "Chip gap must not be negative"); + } + const ModuleGaps module_gaps = gaps.module_gaps.value_or(ModuleGaps{}); + if (module_gaps.x < 0 || module_gaps.y < 0) { + throw std::invalid_argument(LOCATION + + "Module gaps must not be negative"); + } + if (gaps.chip_gap > max_gap) { + throw std::invalid_argument( + LOCATION + + fmt::format("Chip gap must not exceed {} pixels", max_gap)); + } + if (module_gaps.x > max_gap || module_gaps.y > max_gap) { + throw std::invalid_argument( + LOCATION + + fmt::format("Module gaps must not exceed {} pixels", max_gap)); + } + if (gaps.split_counts && gaps.chip_gap != 2) { + throw std::invalid_argument( + LOCATION + "Splitting counts requires a chip gap of 2"); + } + return {{chip, module_x, gaps.chip_gap, module_gaps.x}, + {chip, module_y, gaps.chip_gap, module_gaps.y}}; +} + +std::array gapped_shape(const ROI &roi, const GapLayout &layout) { + return {layout.y.extent(roi.ymin, roi.ymax), + layout.x.extent(roi.xmin, roi.xmax)}; +} + +void validate_roi(const ROI &roi) { + if (roi.xmin < 0 || roi.ymin < 0 || roi.xmax < roi.xmin || + roi.ymax < roi.ymin) { + throw std::invalid_argument( + LOCATION + fmt::format("Invalid ROI x [{}, {}) y [{}, {})", + roi.xmin, roi.xmax, roi.ymin, roi.ymax)); + } + if (roi.xmax > max_coordinate || roi.ymax > max_coordinate) { + throw std::invalid_argument( + LOCATION + + fmt::format("ROI coordinates must not exceed {}", max_coordinate)); + } +} + +void validate_destination(const std::array &shape, const ROI &roi, + const GapLayout &layout) { + validate_roi(roi); + const auto expected = gapped_shape(roi, layout); + if (shape != expected) { + throw std::invalid_argument( + LOCATION + + fmt::format("Destination shape ({}, {}) does not match the gapped " + "ROI shape ({}, {})", + shape[0], shape[1], expected[0], expected[1])); + } +} + +std::mt19937_64 make_generator(std::optional seed) { + if (seed) { + return std::mt19937_64(*seed); + } + std::random_device device; + return std::mt19937_64((static_cast(device()) << 32) ^ device()); +} + +} // namespace detail + +std::array gapped_shape(const ROI &roi, const GapPixels &gaps) { + const auto layout = detail::gap_layout(gaps); + detail::validate_roi(roi); + return detail::gapped_shape(roi, layout); +} + +} // namespace aare diff --git a/src/GapPixels.test.cpp b/src/GapPixels.test.cpp new file mode 100644 index 00000000..ae792319 --- /dev/null +++ b/src/GapPixels.test.cpp @@ -0,0 +1,588 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/GapPixels.hpp" + +#include +#include +#include + +#include +#include +#include + +using namespace aare; + +namespace { + +// chip 2, module 4, chip gap 1, module gap 3: boundaries at 2 (chip), 4 +// (module), 6 (chip) for an 8 pixel axis +const detail::AxisGaps tiny_axis{2, 4, 1, 3}; + +template NDArray pattern(ssize_t rows, ssize_t cols) { + NDArray image({rows, cols}); + for (ssize_t row = 0; row < rows; ++row) { + for (ssize_t col = 0; col < cols; ++col) { + image(row, col) = static_cast((row * cols + col) % 60000 + 1); + } + } + return image; +} + +template double total(NDView image) { + double sum = 0; + for (ssize_t row = 0; row < image.shape(0); ++row) { + for (ssize_t col = 0; col < image.shape(1); ++col) { + sum += static_cast(image(row, col)); + } + } + return sum; +} + +} // namespace + +TEST_CASE("Axis gap map inserts chip and module gaps", "[GapPixels]") { + const detail::AxisGaps &axis = tiny_axis; + CHECK(axis.gapped(0) == 0); + CHECK(axis.gapped(1) == 1); + CHECK(axis.gapped(2) == 3); + CHECK(axis.gapped(3) == 4); + CHECK(axis.gapped(4) == 8); + CHECK(axis.gapped(5) == 9); + CHECK(axis.gapped(6) == 11); + CHECK(axis.gapped(7) == 12); + + CHECK(axis.extent(0, 8) == 13); + CHECK(axis.extent(0, 2) == 2); + CHECK(axis.extent(2, 4) == 2); + CHECK(axis.extent(1, 3) == 3); + CHECK(axis.extent(3, 5) == 5); + CHECK(axis.extent(4, 4) == 0); + CHECK(axis.extent(5, 4) == 0); + + CHECK(axis.inner_boundaries(0, 8) == std::vector{2, 4, 6}); + CHECK(axis.inner_boundaries(1, 3) == std::vector{2}); + CHECK(axis.inner_boundaries(2, 4).empty()); + CHECK(axis.inner_boundaries(2, 5) == std::vector{4}); + CHECK(axis.inner_boundaries(0, 0).empty()); + + CHECK(axis.is_module_boundary(4)); + CHECK_FALSE(axis.is_module_boundary(2)); + CHECK(axis.gap_range(2, 0) == std::pair{2, 2}); + CHECK(axis.gap_range(4, 0) == std::pair{5, 7}); + CHECK(axis.gap_range(4, 3) == std::pair{1, 3}); +} + +TEST_CASE("Gap layout follows the configuration", "[GapPixels]") { + SECTION("Jungfrau defaults") { + const auto layout = detail::gap_layout(GapPixels{}); + CHECK(layout.x.chip == 256); + CHECK(layout.x.module == 1024); + CHECK(layout.x.chip_gap == 2); + CHECK(layout.x.module_gap == 0); + CHECK(layout.y.chip == 256); + CHECK(layout.y.module == 512); + CHECK(layout.y.chip_gap == 2); + CHECK(layout.y.module_gap == 0); + } + SECTION("explicit gaps") { + GapPixels gaps; + gaps.chip_gap = 4; + gaps.module_gaps = ModuleGaps{8, 36}; + const auto layout = detail::gap_layout(gaps); + CHECK(layout.x.chip_gap == 4); + CHECK(layout.y.chip_gap == 4); + CHECK(layout.x.module_gap == 8); + CHECK(layout.y.module_gap == 36); + } + SECTION("invalid configuration throws") { + GapPixels gaps; + gaps.chip_gap = -1; + CHECK_THROWS_AS(detail::gap_layout(gaps), std::invalid_argument); + gaps = GapPixels{}; + gaps.module_gaps = ModuleGaps{-8, 36}; + CHECK_THROWS_AS(detail::gap_layout(gaps), std::invalid_argument); + gaps = GapPixels{}; + gaps.split_counts = true; + gaps.chip_gap = 4; + CHECK_THROWS_AS(detail::gap_layout(gaps), std::invalid_argument); + } + SECTION("gaps are limited to 1024 pixels") { + GapPixels gaps; + gaps.chip_gap = 1024; + gaps.module_gaps = ModuleGaps{1024, 1024}; + CHECK_NOTHROW(detail::gap_layout(gaps)); + gaps.chip_gap = 1025; + CHECK_THROWS_AS(detail::gap_layout(gaps), std::invalid_argument); + gaps.chip_gap = 2; + gaps.module_gaps = ModuleGaps{8, 1025}; + CHECK_THROWS_AS(detail::gap_layout(gaps), std::invalid_argument); + } +} + +TEST_CASE("Gapped shape of detector ROIs", "[GapPixels]") { + GapPixels module_8_36; + module_8_36.module_gaps = ModuleGaps{8, 36}; + using Shape = std::array; + + CHECK(gapped_shape(ROI{0, 1024, 0, 512}) == Shape{514, 1030}); + CHECK(gapped_shape(ROI{0, 1024, 0, 512}, module_8_36) == Shape{514, 1030}); + CHECK(gapped_shape(ROI{0, 2048, 0, 512}) == Shape{514, 2060}); + CHECK(gapped_shape(ROI{0, 2048, 0, 512}, module_8_36) == Shape{514, 2068}); + CHECK(gapped_shape(ROI{0, 1024, 0, 1024}) == Shape{1028, 1030}); + CHECK(gapped_shape(ROI{0, 1024, 0, 1024}, module_8_36) == + Shape{1064, 1030}); + // an Eiger quad + CHECK(gapped_shape(ROI{0, 512, 0, 512}) == Shape{514, 514}); + + SECTION("ROI borders exclude gaps") { + CHECK(gapped_shape(ROI{100, 400, 0, 10}) == Shape{10, 302}); + CHECK(gapped_shape(ROI{256, 512, 0, 1}) == Shape{1, 256}); + CHECK(gapped_shape(ROI{255, 257, 0, 1}) == Shape{1, 4}); + CHECK(gapped_shape(ROI{200, 301, 300, 601}) == Shape{301, 103}); + CHECK(gapped_shape(ROI{200, 301, 300, 601}, module_8_36) == + Shape{337, 103}); + CHECK(gapped_shape(ROI{512, 768, 0, 256}) == Shape{256, 256}); + } + SECTION("invalid ROI throws") { + CHECK_THROWS_AS(gapped_shape(ROI{-1, 10, 0, 10}), + std::invalid_argument); + CHECK_THROWS_AS(gapped_shape(ROI{10, 5, 0, 10}), std::invalid_argument); + } + SECTION("coordinates are limited to 2^28") { + const ssize_t limit = ssize_t{1} << 28; + CHECK(gapped_shape(ROI{limit - 1, limit, 0, 1}) == Shape{1, 1}); + CHECK_THROWS_AS(gapped_shape(ROI{limit, limit + 1, 0, 1}), + std::invalid_argument); + CHECK_THROWS_AS(gapped_shape(ROI{0, 1, limit, limit + 1}), + std::invalid_argument); + } +} + +TEST_CASE("Copy and fill with a tiny layout", "[GapPixels]") { + const detail::GapLayout layout{tiny_axis, tiny_axis}; + // 4 rows (one chip boundary at 2) by 8 columns (chip, module, chip) + const ROI roi{0, 8, 0, 4}; + auto source = pattern(4, 8); + const auto shape = detail::gapped_shape(roi, layout); + REQUIRE(shape == std::array{5, 13}); + + NDArray destination(shape, uint16_t{7}); + detail::fill_gap_pixels(destination.view(), roi, layout, uint16_t{99}); + + SECTION("whole ROI") { + detail::copy_with_gaps(NDView(source.view()), roi, + destination.view(), roi, layout); + for (ssize_t row = 0; row < shape[0]; ++row) { + for (ssize_t col = 0; col < shape[1]; ++col) { + CAPTURE(row, col); + const bool gap_row = row == 2; + const bool gap_col = + col == 2 || (col >= 5 && col <= 7) || col == 10; + if (gap_row || gap_col) { + CHECK(destination(row, col) == 99); + } + } + } + for (ssize_t row = 0; row < 4; ++row) { + for (ssize_t col = 0; col < 8; ++col) { + CAPTURE(row, col); + CHECK(destination(layout.y.gapped(row), layout.x.gapped(col)) == + source(row, col)); + } + } + } + SECTION("two rectangles cover the ROI") { + const ROI left{0, 3, 0, 4}; + const ROI right{3, 8, 0, 4}; + NDArray left_pixels({4, 3}); + NDArray right_pixels({4, 5}); + for (ssize_t row = 0; row < 4; ++row) { + for (ssize_t col = 0; col < 8; ++col) { + if (col < 3) { + left_pixels(row, col) = source(row, col); + } else { + right_pixels(row, col - 3) = source(row, col); + } + } + } + detail::copy_with_gaps(NDView(left_pixels.view()), + left, destination.view(), roi, layout); + detail::copy_with_gaps(NDView(right_pixels.view()), + right, destination.view(), roi, layout); + for (ssize_t row = 0; row < 4; ++row) { + for (ssize_t col = 0; col < 8; ++col) { + CAPTURE(row, col); + CHECK(destination(layout.y.gapped(row), layout.x.gapped(col)) == + source(row, col)); + } + } + CHECK(destination(0, 2) == 99); + CHECK(destination(2, 0) == 99); + } + SECTION("mismatched shapes throw") { + NDArray wrong({5, 12}); + CHECK_THROWS_AS( + detail::fill_gap_pixels(wrong.view(), roi, layout, uint16_t{0}), + std::invalid_argument); + CHECK_THROWS_AS( + detail::copy_with_gaps(NDView(source.view()), + roi, wrong.view(), roi, layout), + std::invalid_argument); + CHECK_THROWS_AS(detail::copy_with_gaps( + NDView(source.view()), + ROI{0, 9, 0, 4}, destination.view(), roi, layout), + std::invalid_argument); + CHECK_THROWS_AS(detail::copy_with_gaps( + NDView(source.view()), + ROI{0, 7, 0, 4}, destination.view(), roi, layout), + std::invalid_argument); + } +} + +TEST_CASE("Gaps and coordinates that overflow the gapped shape are rejected", + "[GapPixels]") { + // chip_gap * 3 wrapped around in 64 bit arithmetic and reported a 1x1023 + // image for this source, so gap filling wrote past the allocation + auto source = pattern(1, 1024); + GapPixels gaps; + gaps.chip_gap = 6148914691236517205; + const ROI roi{0, 1024, 0, 1}; + CHECK_THROWS_AS(gapped_shape(roi, gaps), std::invalid_argument); + CHECK_THROWS_AS( + insert_gap_pixels(NDView(source.view()), roi, gaps), + std::invalid_argument); + + const ssize_t far = ssize_t{1} << 62; + const ROI far_roi{far, far + 1024, 0, 1}; + CHECK_THROWS_AS(gapped_shape(far_roi), std::invalid_argument); + CHECK_THROWS_AS( + insert_gap_pixels(NDView(source.view()), far_roi), + std::invalid_argument); +} + +TEST_CASE("insert_gap_pixels on a Jungfrau module", "[GapPixels]") { + const ROI roi{0, 1024, 0, 512}; + auto source = pattern(512, 1024); + GapPixels gaps; + gaps.fill_value = 5; + auto result = + insert_gap_pixels(NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{514, 1030}); + + const auto layout = detail::gap_layout(gaps); + for (ssize_t row = 0; row < 512; ++row) { + for (ssize_t col = 0; col < 1024; ++col) { + if (result(layout.y.gapped(row), layout.x.gapped(col)) != + source(row, col)) { + CAPTURE(row, col); + REQUIRE(result(layout.y.gapped(row), layout.x.gapped(col)) == + source(row, col)); + } + } + } + for (ssize_t col : {256, 257, 514, 515, 772, 773}) { + for (ssize_t row = 0; row < 514; ++row) { + if (result(row, col) != 5) { + CAPTURE(row, col); + REQUIRE(result(row, col) == 5); + } + } + } + for (ssize_t row : {256, 257}) { + for (ssize_t col = 0; col < 1030; ++col) { + if (result(row, col) != 5) { + CAPTURE(row, col); + REQUIRE(result(row, col) == 5); + } + } + } + CHECK(total(NDView(result.view())) == + total(NDView(source.view())) + + 5.0 * (514 * 1030 - 512 * 1024)); +} + +TEST_CASE("insert_gap_pixels on ROIs", "[GapPixels]") { + SECTION("gap inside the ROI") { + const ROI roi{255, 257, 10, 11}; + NDArray source({1, 2}); + source(0, 0) = 11; + source(0, 1) = 22; + auto result = + insert_gap_pixels(NDView(source.view()), roi); + REQUIRE(result.shape() == std::array{1, 4}); + CHECK(result(0, 0) == 11); + CHECK(result(0, 1) == 0); + CHECK(result(0, 2) == 0); + CHECK(result(0, 3) == 22); + } + SECTION("gap on the ROI border is not inserted") { + const ROI roi{256, 260, 0, 2}; + auto source = pattern(2, 4); + auto result = + insert_gap_pixels(NDView(source.view()), roi); + REQUIRE(result.shape() == std::array{2, 4}); + for (ssize_t row = 0; row < 2; ++row) { + for (ssize_t col = 0; col < 4; ++col) { + CHECK(result(row, col) == source(row, col)); + } + } + } + SECTION("module boundary inside the ROI") { + GapPixels gaps; + gaps.module_gaps = ModuleGaps{8, 36}; + gaps.fill_value = -1; // wraps for unsigned types + const ROI roi{200, 301, 300, 601}; + auto source = pattern(301, 101); + auto result = insert_gap_pixels( + NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{337, 103}); + // chip gap at column 256 -> gapped columns 56, 57 + CHECK(result(0, 55) == source(0, 55)); + CHECK(result(0, 56) == 65535); + CHECK(result(0, 57) == 65535); + CHECK(result(0, 58) == source(0, 56)); + // module gap at row 512 -> gapped rows 212 .. 247 + CHECK(result(211, 0) == source(211, 0)); + CHECK(result(212, 0) == 65535); + CHECK(result(247, 0) == 65535); + CHECK(result(248, 0) == source(212, 0)); + } + SECTION("source shape must match the ROI") { + auto source = pattern(2, 4); + CHECK_THROWS_AS( + insert_gap_pixels(NDView(source.view()), + ROI{0, 5, 0, 2}), + std::invalid_argument); + } + SECTION("floating point images") { + const ROI roi{255, 257, 0, 1}; + NDArray source({1, 2}); + source(0, 0) = 1.5; + source(0, 1) = 2.5; + GapPixels gaps; + gaps.fill_value = 0.25; + auto result = insert_gap_pixels(NDView(source.view()), + roi, gaps); + CHECK(result(0, 0) == 1.5); + CHECK(result(0, 1) == 0.25); + CHECK(result(0, 2) == 0.25); + CHECK(result(0, 3) == 2.5); + } + SECTION("fill values without an integer representation throw") { + const ROI roi{255, 257, 0, 1}; + auto source = pattern(1, 2); + GapPixels gaps; + for (const double value : + {std::numeric_limits::quiet_NaN(), + std::numeric_limits::infinity(), + -std::numeric_limits::infinity(), 1e20, -1e20, 0x1p63}) { + gaps.fill_value = value; + CHECK_THROWS_AS( + insert_gap_pixels(NDView(source.view()), roi, + gaps), + std::invalid_argument); + } + + // the same values are valid for floating point images + gaps.fill_value = std::numeric_limits::quiet_NaN(); + auto floats = pattern(1, 2); + auto result = + insert_gap_pixels(NDView(floats.view()), roi, gaps); + CHECK(std::isnan(result(0, 1))); + CHECK(std::isnan(result(0, 2))); + } +} + +TEST_CASE("Module boundaries receive no gap unless module gaps are set", + "[GapPixels]") { + // rows 510..513 of two stacked modules hold the module boundary at 512 + const ROI roi{0, 2, 510, 514}; + auto source = pattern(4, 2); + GapPixels gaps; + gaps.fill_value = 9; + SECTION("fill value") {} + SECTION("split counts") { + gaps.split_counts = true; + gaps.seed = 1; + } + auto result = + insert_gap_pixels(NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{4, 2}); + CHECK(result == source); + + gaps.module_gaps = ModuleGaps{0, 3}; + auto with_gap = + insert_gap_pixels(NDView(source.view()), roi, gaps); + REQUIRE(with_gap.shape() == std::array{7, 2}); + for (ssize_t row = 2; row < 5; ++row) { + CHECK(with_gap(row, 0) == 9); + CHECK(with_gap(row, 1) == 9); + } + CHECK(with_gap(1, 0) == source(1, 0)); + CHECK(with_gap(5, 0) == source(2, 0)); +} + +TEST_CASE("Split counts between edge pixels and their gaps", "[GapPixels]") { + GapPixels gaps; + gaps.split_counts = true; + gaps.seed = 42; + + SECTION("one boundary, integer counts") { + // columns 254..258 and rows 0..1: one chip boundary at 256 + const ROI roi{254, 258, 0, 2}; + NDArray source({2, 4}); + source(0, 0) = 10; + source(0, 1) = 7; // odd, splits 3 + 4 in random order + source(0, 2) = 9; + source(0, 3) = 12; + source(1, 0) = 1; + source(1, 1) = 8; + source(1, 2) = 2; + source(1, 3) = 3; + auto result = insert_gap_pixels( + NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{2, 6}); + for (ssize_t row = 0; row < 2; ++row) { + CAPTURE(row); + CHECK(result(row, 0) == source(row, 0)); + CHECK(result(row, 5) == source(row, 3)); + // left edge pixel and its gap pixel to the right + CHECK(result(row, 1) + result(row, 2) == source(row, 1)); + CHECK(std::max(result(row, 1), result(row, 2)) == + (source(row, 1) + 1) / 2); + // right edge pixel and its gap pixel to the left + CHECK(result(row, 3) + result(row, 4) == source(row, 2)); + CHECK(std::max(result(row, 3), result(row, 4)) == + (source(row, 2) + 1) / 2); + } + CHECK(result(0, 1) + result(0, 2) == 7); + CHECK(result(1, 1) == 4); + CHECK(result(1, 2) == 4); + CHECK(result(1, 3) == 1); + CHECK(result(1, 4) == 1); + } + SECTION("corner pixels split four ways") { + const ROI roi{255, 257, 255, 257}; + NDArray source({2, 2}); + source(0, 0) = 9; + source(0, 1) = 8; + source(1, 0) = 4; + source(1, 1) = 1; + auto result = insert_gap_pixels( + NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{4, 4}); + auto quad_sum = [&](ssize_t row, ssize_t col) { + return result(row, col) + result(row, col + 1) + + result(row + 1, col) + result(row + 1, col + 1); + }; + CHECK(quad_sum(0, 0) == 9); + CHECK(quad_sum(0, 2) == 8); + CHECK(quad_sum(2, 0) == 4); + CHECK(quad_sum(2, 2) == 1); + CHECK(result(0, 2) + result(0, 3) == 4); + CHECK(result(1, 2) + result(1, 3) == 4); + CHECK(result(2, 0) == 1); + CHECK(result(2, 1) == 1); + CHECK(result(3, 0) == 1); + CHECK(result(3, 1) == 1); + CHECK(total(NDView(result.view())) == 22); + } + SECTION("floating point halves exactly") { + const ROI roi{255, 257, 255, 257}; + NDArray source({2, 2}, 1.0); + source(0, 0) = 3.0; + auto result = insert_gap_pixels(NDView(source.view()), + roi, gaps); + for (ssize_t row = 0; row < 2; ++row) { + for (ssize_t col = 0; col < 2; ++col) { + CHECK(result(row, col) == 0.75); + } + } + CHECK(result(0, 2) == 0.25); + CHECK(result(3, 3) == 0.25); + } + SECTION("totals, remainders and reproducibility on a module") { + const ROI roi{0, 1024, 0, 512}; + NDArray source({512, 1024}); + for (ssize_t row = 0; row < 512; ++row) { + for (ssize_t col = 0; col < 1024; ++col) { + source(row, col) = + static_cast((row * 7 + col * 13) % 1000 + 1); + } + } + auto first = insert_gap_pixels(NDView(source.view()), + roi, gaps); + auto second = insert_gap_pixels( + NDView(source.view()), roi, gaps); + REQUIRE(first.shape() == std::array{514, 1030}); + CHECK(total(NDView(first.view())) == + total(NDView(source.view()))); + CHECK(first == second); + + // remainders of odd left edge pixels should land on either side + // about equally often + size_t odd = 0; + size_t kept_high = 0; + for (ssize_t row = 0; row < 512; ++row) { + if (row == 255 || row == 256) { + continue; // rows that are split again vertically + } + for (ssize_t boundary : {256, 512, 768}) { + const auto value = source(row, boundary - 1); + if (value % 2 == 0) { + continue; + } + ++odd; + const ssize_t gapped_row = row < 256 ? row : row + 2; + // gapped column of the left edge pixel, source column boundary + // - 1 + const ssize_t left = boundary - 1 + 2 * (boundary / 256 - 1); + if (first(gapped_row, left) > first(gapped_row, left + 1)) { + ++kept_high; + } + } + } + REQUIRE(odd > 500); + const double fraction = static_cast(kept_high) / odd; + CHECK(fraction > 0.4); + CHECK(fraction < 0.6); + + GapPixels other = gaps; + other.seed = 43; + auto third = insert_gap_pixels(NDView(source.view()), + roi, other); + CHECK(third != first); + } + SECTION("module gaps keep the fill value") { + GapPixels module_gaps = gaps; + module_gaps.module_gaps = ModuleGaps{8, 36}; + module_gaps.fill_value = 3; + const ROI roi{0, 1024, 0, 1024}; + NDArray source({1024, 1024}, uint16_t{7}); + auto result = insert_gap_pixels( + NDView(source.view()), roi, module_gaps); + REQUIRE(result.shape() == std::array{1064, 1030}); + for (ssize_t row = 514; row < 550; ++row) { + for (ssize_t col = 0; col < 1030; ++col) { + if (result(row, col) != 3) { + CAPTURE(row, col); + REQUIRE(result(row, col) == 3); + } + } + } + // the edge pixels next to the module gap are not split + CHECK(result(513, 0) == 7); + CHECK(result(550, 0) == 7); + // chip gaps are split: 7 -> 3 + 4 + CHECK(result(0, 255) + result(0, 256) == 7); + CHECK(total(NDView(result.view())) == + 7.0 * 1024 * 1024 + 3.0 * 36 * 1030); + } + SECTION("no split at a ROI border") { + const ROI roi{256, 260, 0, 1}; + NDArray source({1, 4}, uint16_t{9}); + auto result = insert_gap_pixels( + NDView(source.view()), roi, gaps); + REQUIRE(result.shape() == std::array{1, 4}); + CHECK(result(0, 0) == 9); + } +} From 7abbf3cbb5a945374d11adf80089050ae55b10e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Erik=20Fr=C3=B6jdh?= Date: Mon, 26 Oct 2026 14:39:13 +0100 Subject: [PATCH 14/16] Read raw files with gap pixels (#426) Third part of splitting up dev/gap. The multithreaded reader comes in the next PR. - `RawFile` takes an optional `GapPixels`. Frames are assembled with the gaps inserted: fill the gap lines, scatter each module part through the scratch buffer into its gapped position, and split the chip edge counts if configured. `rows()`, `cols()`, `pixels_per_frame()` and `bytes_per_frame()` include the gaps, for the full frame and for each ROI. Only Jungfrau and Eiger are supported. - Python `RawFile` accepts `gap_pixels` as a bool or a `GapPixels`, exposes it as a property, and takes frame shapes from `rows()` and `cols()`. - The generic `File` is unchanged: it does not know the detector geometry of `.npy` and `.dat` files, so gap pixels stay a `RawFile` option. Use `RawFile`, or apply `insert_gap_pixels` to frames from `File`. - Tests: generalized raw file helper with arbitrary module layouts, module layout assembly tests (these cover #421, which went in without tests), synthetic gap tests, a split-counts oracle against `insert_gap_pixels`, unsupported detector rejection, and data-backed recorded-file and two-ROI cases. - A raw file benchmark with no-gaps, fill-value and split-counts cases. - Docs and release note. --- RELEASE.md | 4 + benchmarks/CMakeLists.txt | 2 +- benchmarks/rawfile_benchmark.cpp | 112 +++++++++ docs/src/GapPixels.rst | 21 ++ docs/src/RawFile.rst | 8 + docs/src/python/file/pyGapPixels.rst | 24 +- docs/src/python/file/pyRawFile.rst | 6 + include/aare/RawFile.hpp | 36 ++- python/aare/RawFile.py | 14 +- python/src/bind_RawFile.hpp | 43 +++- python/tests/test_RawFile.py | 158 ++++++++++++ src/RawFile.cpp | 133 +++++++++- src/RawFile.test.cpp | 353 ++++++++++++++++++++++++++- tests/raw_file_helpers.hpp | 77 +++++- 14 files changed, 955 insertions(+), 36 deletions(-) create mode 100644 benchmarks/rawfile_benchmark.cpp diff --git a/RELEASE.md b/RELEASE.md index 0cd63bae..e8b90b5f 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -17,6 +17,10 @@ is set, gaps between modules. Gap positions follow detector coordinates before any ROI. Gap pixels receive a fill value or, with ``split_counts``, half of the neighbouring double size pixel. +- ``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 + the gaps, for the full frame and for each ROI. ### Other: diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index e874a003..f89b57d3 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -20,7 +20,7 @@ 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 rawfile_benchmark.cpp) # Link Google Benchmark and other necessary libraries target_link_libraries(benchmarks PRIVATE benchmark::benchmark aare_core diff --git a/benchmarks/rawfile_benchmark.cpp b/benchmarks/rawfile_benchmark.cpp new file mode 100644 index 00000000..cecd5183 --- /dev/null +++ b/benchmarks/rawfile_benchmark.cpp @@ -0,0 +1,112 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/GapPixels.hpp" +#include "aare/RawFile.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +/// One Jungfrau module, 512x1024 pixels at 16 bit, with every frame in a +/// single data file written to the temporary directory. +class RawFileFixture : public benchmark::Fixture { + protected: + static constexpr size_t rows = 512; + static constexpr size_t cols = 1024; + static constexpr size_t frame_count = 32; + std::filesystem::path m_directory; + + public: + void SetUp(const benchmark::State &) override { + const auto stamp = + std::chrono::steady_clock::now().time_since_epoch().count(); + m_directory = std::filesystem::temp_directory_path() / + ("aare-rawfile-benchmark-" + std::to_string(stamp)); + std::filesystem::create_directory(m_directory); + const nlohmann::json metadata = { + {"Version", 7.2}, + {"Detector Type", "Jungfrau"}, + {"Timing Mode", "auto"}, + {"Geometry", {{"x", 1}, {"y", 1}}}, + {"Image Size in bytes", rows * cols * sizeof(uint16_t)}, + {"Pixels", {{"x", cols}, {"y", rows}}}, + {"Max Frames Per File", frame_count}, + {"Total Frames", frame_count}, + {"Frames in File", frame_count}, + {"Frame Padding", 1}, + {"Frame Discard Policy", "nodiscard"}}; + std::ofstream(master()) << metadata; + + std::vector pixels(rows * cols); + for (size_t i = 0; i < pixels.size(); ++i) { + pixels[i] = static_cast(i % 1000 + 1); + } + std::ofstream data(m_directory / "run_d0_f0_0.raw", std::ios::binary); + for (size_t frame = 0; frame < frame_count; ++frame) { + aare::DetectorHeader header{}; + header.frameNumber = frame + 1; + data.write(reinterpret_cast(&header), sizeof(header)); + data.write( + reinterpret_cast(pixels.data()), + static_cast(pixels.size() * sizeof(uint16_t))); + } + } + + void TearDown(const benchmark::State &) override { + std::error_code error; + std::filesystem::remove_all(m_directory, error); + } + + std::filesystem::path master() const { + return m_directory / "run_master_0.json"; + } + + /// Read every frame of the file into one buffer per iteration + void read_all(benchmark::State &state, + std::optional gaps) const { + aare::RawFile file(master(), "r", gaps); + std::vector buffer(file.bytes_per_frame() * frame_count); + for (auto _ : state) { + file.seek(0); + file.read_into(buffer.data(), frame_count); + benchmark::DoNotOptimize(buffer.data()); + benchmark::ClobberMemory(); + } + state.SetItemsProcessed(static_cast(state.iterations()) * + static_cast(frame_count)); + state.SetBytesProcessed(static_cast(state.iterations()) * + static_cast(buffer.size())); + } +}; + +BENCHMARK_DEFINE_F(RawFileFixture, NoGaps)(benchmark::State &state) { + read_all(state, std::nullopt); +} + +BENCHMARK_DEFINE_F(RawFileFixture, GapsFillValue)(benchmark::State &state) { + read_all(state, aare::GapPixels{}); +} + +BENCHMARK_DEFINE_F(RawFileFixture, GapsSplitCounts)(benchmark::State &state) { + aare::GapPixels gaps; + gaps.split_counts = true; + gaps.seed = 1; + read_all(state, gaps); +} + +BENCHMARK_REGISTER_F(RawFileFixture, NoGaps)->Unit(benchmark::kMillisecond); +BENCHMARK_REGISTER_F(RawFileFixture, GapsFillValue) + ->Unit(benchmark::kMillisecond); +BENCHMARK_REGISTER_F(RawFileFixture, GapsSplitCounts) + ->Unit(benchmark::kMillisecond); + +} // namespace diff --git a/docs/src/GapPixels.rst b/docs/src/GapPixels.rst index 0470878d..f5169e7a 100644 --- a/docs/src/GapPixels.rst +++ b/docs/src/GapPixels.rst @@ -17,6 +17,7 @@ Configuration ``GapPixels`` holds the configuration. The chip size (256 pixels) and the module size (1024x512 pixels) are fixed. An Eiger quad (512x512 pixels) needs no special handling, since its only chip boundaries are at pixel 256. +``RawFile`` rejects other detector types with ``std::invalid_argument``. Gaps of up to 1024 pixels are supported, far beyond the 2 to 10 pixels of a real detector, and detector coordinates are limited to 2^28. @@ -68,6 +69,26 @@ fill value. Splitting only happens where a gap pixel is inserted, so an edge pixel on a ROI border keeps its full value. Split mode requires a chip gap of 2. +Reading files +------------- + +Pass a ``GapPixels`` to :cpp:class:`aare::RawFile`. Frame sizes, +``rows()``, ``cols()`` and ``bytes_per_frame()`` then include the gaps. +Module data is scattered into the gapped frame while it is assembled, so no +extra frame sized buffer is needed. Headers are unchanged. The generic +:cpp:class:`aare::File` does not insert gap pixels; use ``RawFile`` or +apply ``insert_gap_pixels`` to the frames it returns. + +.. code-block:: cpp + + #include "aare/GapPixels.hpp" + #include "aare/RawFile.hpp" + + aare::GapPixels gaps; + gaps.module_gaps = aare::ModuleGaps{8, 36}; + aare::RawFile file("run_master_0.json", "r", gaps); + auto frame = file.read_frame(); // 1064 x 1030 for two stacked modules + Images in memory ---------------- diff --git a/docs/src/RawFile.rst b/docs/src/RawFile.rst index 8ecd30e9..db10ae78 100644 --- a/docs/src/RawFile.rst +++ b/docs/src/RawFile.rst @@ -42,6 +42,14 @@ The top-level frame bounds error states the number of frames in the file and that indices are zero-based. +Pass a :doc:`GapPixels ` configuration as the third constructor +argument to insert gap pixels while frames are assembled. ``rows()``, +``cols()``, ``pixels_per_frame()``, ``bytes_per_frame()`` and every returned +frame then include the gaps, for the full frame and for each ROI. The option +is only supported for Jungfrau and Eiger and throws +``std::invalid_argument`` for other detector types. Headers and frame +numbers are unchanged. + .. doxygenclass:: aare::RawFile :members: :undoc-members: diff --git a/docs/src/python/file/pyGapPixels.rst b/docs/src/python/file/pyGapPixels.rst index 020144c3..58e344a3 100644 --- a/docs/src/python/file/pyGapPixels.rst +++ b/docs/src/python/file/pyGapPixels.rst @@ -46,7 +46,7 @@ defaults and ``(1064, 1030)`` with ``ModuleGaps(8, 36)``. gapped = insert_gap_pixels(image) # module gaps as in the slsDetectorPackage GUI, counts split at chip edges - gaps = GapPixels(module_gaps=ModuleGaps(8, 36), split_counts=True, seed=1) + gaps = GapPixels(module_gaps=ModuleGaps(8, 36), split_counts=True) gapped = insert_gap_pixels(image, gaps) # an image that covers columns 100 to 400 of the first ten rows @@ -59,6 +59,28 @@ defaults and ``(1064, 1030)`` with ``ModuleGaps(8, 36)``. same dtype. Pass ``roi`` when the image covers part of the detector. ``gapped_shape`` returns the shape of the gapped image of a ROI. +Reading files +------------- + +``RawFile`` takes ``gap_pixels``: ``True`` for the defaults or a +``GapPixels``. Frame shapes, ``rows`` and ``cols`` then include the gaps. +Only Jungfrau and Eiger raw files are supported; other detector types raise +``ValueError``. The generic ``File`` does not insert gap pixels; use +``RawFile`` or apply ``insert_gap_pixels`` to the frames it returns. + +.. code-block:: python + + from aare import GapPixels, ModuleGaps, RawFile + + # defaults: chip gaps of 2 filled with 0 + with RawFile("run_master_0.json", gap_pixels=True) as f: + header, image = f.read_frame() + + # module gaps as in the slsDetectorPackage GUI + gaps = GapPixels(module_gaps=ModuleGaps(8, 36), split_counts=False) + with RawFile("run_master_0.json", gap_pixels=gaps) as f: + header, image = f.read_frame() + .. autoclass:: GapPixels :members: :undoc-members: diff --git a/docs/src/python/file/pyRawFile.rst b/docs/src/python/file/pyRawFile.rst index a128d2fe..480560e2 100644 --- a/docs/src/python/file/pyRawFile.rst +++ b/docs/src/python/file/pyRawFile.rst @@ -40,6 +40,12 @@ For a file containing five frames, the valid indices are 0 through 4. Attempting to read index 5 raises an error stating: ``Frame index 5 is out of range: file contains 5 frames (indices are zero-based)``. +``gap_pixels`` inserts :doc:`gap pixels ` while frames are +assembled. Pass ``True`` for the defaults or a ``GapPixels``. ``rows()``, +``cols()`` and every returned frame then include the gaps, for the full frame +and for each ROI. Only Jungfrau and Eiger are supported; other detector +types raise ``ValueError``. Headers are unchanged. + .. autoclass:: RawFile :members: :undoc-members: diff --git a/include/aare/RawFile.hpp b/include/aare/RawFile.hpp index e2666577..3314c8cf 100644 --- a/include/aare/RawFile.hpp +++ b/include/aare/RawFile.hpp @@ -2,6 +2,7 @@ #pragma once #include "aare/FileInterface.hpp" #include "aare/Frame.hpp" +#include "aare/GapPixels.hpp" #include "aare/NDArray.hpp" //for pixel map #include "aare/ROIGeometry.hpp" #include "aare/RawMasterFile.hpp" @@ -11,7 +12,9 @@ #include "../tests/friend_test.hpp" #endif +#include #include +#include namespace aare { @@ -38,15 +41,32 @@ class RawFile : public FileInterface { /// @brief Minimum frame count across the selected raw subfile series. size_t m_frames_in_file{}; + /// @brief Gap pixel configuration, empty when reading without gaps + std::optional m_gap_pixels; + detail::GapLayout m_gap_layout{}; + std::mt19937_64 m_generator; + + /// @brief Detector coordinates of each ROI, in roi_geometries() order + std::vector m_roi_rects; + /// @brief {rows, cols} of the assembled frame of each ROI, including + /// gap pixels when enabled + std::vector> m_roi_shapes; + public: /** * @brief RawFile constructor * @param fname path to the master file (.json) * @param mode file mode (only "r" is supported at the moment) + * @param gap_pixels insert gap pixels into every assembled frame. Frame + * sizes, rows() and cols() then include the gaps. Only supported for + * Jungfrau and Eiger. * @throws std::runtime_error if frame padding is disabled and the frame * discard policy is not DiscardPartial. + * @throws std::invalid_argument if gap pixels are requested for another + * detector type or the gap configuration is invalid */ - RawFile(const std::filesystem::path &fname, const std::string &mode = "r"); + RawFile(const std::filesystem::path &fname, const std::string &mode = "r", + std::optional gap_pixels = std::nullopt); virtual ~RawFile() override = default; Frame read_frame() override; @@ -106,6 +126,10 @@ class RawFile : public FileInterface { */ size_t pixels_per_frame(const size_t roi_index); size_t bytes_per_pixel() const; + + /// @brief Gap pixel configuration, empty when reading without gaps + const std::optional &gap_pixels() const { return m_gap_pixels; } + void seek(size_t frame_index) override; size_t tell() override; /// @brief Minimum actual frame count across all subfiles and ROIs. @@ -168,6 +192,16 @@ class RawFile : public FileInterface { std::vector synchronized_frame_indices(size_t frame_index, size_t roi_index); + /** + * @brief Assemble a frame with gap pixels: fill the gap lines, scatter + * every module part through the scratch buffer and, if configured, + * split the counts of the chip edge pixels. + */ + template + void assemble_with_gaps(std::byte *frame_buffer, size_t roi_index, + const std::vector &frame_indices, + DetectorHeader *header); + /** * @brief read the frame at the given frame index into the image buffer * @param frame_index frame number to read diff --git a/python/aare/RawFile.py b/python/aare/RawFile.py index 253fcc53..56eccf46 100644 --- a/python/aare/RawFile.py +++ b/python/aare/RawFile.py @@ -4,8 +4,18 @@ import numpy as np from .ScanParameters import ScanParameters class RawFile(_aare.RawFile): - def __init__(self, fname, chunk_size = 1): - super().__init__(fname) + def __init__(self, fname, chunk_size = 1, gap_pixels = False): + """Open a raw file for reading. + + Args: + fname: Master file (.json or .raw). + chunk_size: Frames returned per iteration step. + gap_pixels: Insert gap pixels into every frame. True uses the + default GapPixels configuration, or pass a GapPixels. Frame + shapes then include the gaps. Only Jungfrau and Eiger are + supported. + """ + super().__init__(fname, gap_pixels) self._chunk_size = chunk_size diff --git a/python/src/bind_RawFile.hpp b/python/src/bind_RawFile.hpp index 27e6511c..f3b2d672 100644 --- a/python/src/bind_RawFile.hpp +++ b/python/src/bind_RawFile.hpp @@ -3,6 +3,7 @@ #include "aare/CtbRawFile.hpp" #include "aare/File.hpp" #include "aare/Frame.hpp" +#include "aare/GapPixels.hpp" #include "aare/RawFile.hpp" #include "aare/RawMasterFile.hpp" #include "aare/RawSubFile.hpp" @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -34,7 +36,33 @@ std::runtime_error raw_file_read_error(RawFile &file, void define_raw_file_io_bindings(py::module &m) { py::class_(m, "RawFile") - .def(py::init()) + .def(py::init([](const std::filesystem::path &fname, + const GapPixels &gap_pixels) { + return std::make_unique(fname, "r", gap_pixels); + }), + py::arg("fname"), py::arg("gap_pixels")) + .def(py::init([](const std::filesystem::path &fname, bool gap_pixels) { + return std::make_unique( + fname, "r", + gap_pixels ? std::optional(GapPixels{}) + : std::nullopt); + }), + py::arg("fname"), py::arg("gap_pixels") = false, R"( + Open a raw file for reading. + + Parameters + ---------- + fname : path + Master file (.json or .raw). + gap_pixels : bool or GapPixels + Insert gap pixels into every frame. True uses the default + GapPixels configuration. Frame shapes, rows() and cols() + then include the gaps. Only Jungfrau and Eiger are + supported. + )") + .def_property_readonly("gap_pixels", &RawFile::gap_pixels, R"( + Gap pixel configuration, or None when reading without gaps. + )") .def("read_frame", [](RawFile &self) { if (self.n_modules_in_roi().size() > 1) { @@ -118,8 +146,8 @@ void define_raw_file_io_bindings(py::module &m) { std::vector shape; shape.reserve(2); - shape.push_back(self.roi_geometries(roi_index).pixels_y()); - shape.push_back(self.roi_geometries(roi_index).pixels_x()); + shape.push_back(self.rows(roi_index)); + shape.push_back(self.cols(roi_index)); py::array image = allocate_image_data(self.bytes_per_pixel(), shape); @@ -177,8 +205,8 @@ void define_raw_file_io_bindings(py::module &m) { for (size_t r = 0; r < number_of_ROIs; r++) { std::vector shape; shape.reserve(2); - shape.push_back(self.roi_geometries(r).pixels_y()); - shape.push_back(self.roi_geometries(r).pixels_x()); + shape.push_back(self.rows(r)); + shape.push_back(self.cols(r)); images[r] = allocate_image_data(self.bytes_per_pixel(), shape); @@ -229,9 +257,8 @@ void define_raw_file_io_bindings(py::module &m) { if (n_frames == 0) { throw raw_file_read_error(self, "No frames left in file"); } - std::vector shape{ - n_frames, self.roi_geometries(roi_index).pixels_y(), - self.roi_geometries(roi_index).pixels_x()}; + std::vector shape{n_frames, self.rows(roi_index), + self.cols(roi_index)}; // return headers from all subfiles auto n_mod = self.n_modules_in_roi()[roi_index]; diff --git a/python/tests/test_RawFile.py b/python/tests/test_RawFile.py index 76988db9..d104a3c3 100644 --- a/python/tests/test_RawFile.py +++ b/python/tests/test_RawFile.py @@ -2,6 +2,7 @@ import pytest import json from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition, xy +from aare import GapPixels, ModuleGaps, insert_gap_pixels import numpy as np @@ -28,6 +29,46 @@ def small_raw_file(tmp_path): return master_path +MODULE_ROWS = 2 +MODULE_COLS = 3 + + +def write_module_layout(directory, layout_rows, layout_cols, frames=2, + module_rows=MODULE_ROWS, module_cols=MODULE_COLS, + detector_type="Jungfrau"): + """Write a raw file series with modules in the given layout. + + Modules are numbered as DetectorGeometry orders them, down each column + first, and every module holds distinct values so misplacement is visible. + Returns the master path and the expected image of frame 0. + """ + master_path = directory / "run_master_0.json" + master_path.write_text(json.dumps({ + "Version": 7.2, + "Detector Type": detector_type, + "Timing Mode": "auto", + "Geometry": {"x": layout_cols, "y": layout_rows}, + "Image Size in bytes": module_rows * module_cols * 2, + "Pixels": {"x": module_cols, "y": module_rows}, + "Max Frames Per File": 1, + "Total Frames": frames, + "Frames in File": frames, + "Frame Padding": 1, + "Frame Discard Policy": "nodiscard", + })) + expected = np.zeros((module_rows * layout_rows, module_cols * layout_cols), dtype=np.uint16) + for module in range(layout_rows * layout_cols): + module_row, module_col = module % layout_rows, module // layout_rows + pixels = ((np.arange(module_rows * module_cols, dtype=np.uint32) + module * 10 + 1) % 65536).astype(np.uint16) + expected[module_row * module_rows:(module_row + 1) * module_rows, + module_col * module_cols:(module_col + 1) * module_cols] = pixels.reshape(module_rows, module_cols) + for index in range(frames): + data_path = directory / f"run_d{module}_f{index}_0.raw" + # 112 byte detector header followed by the module pixels + data_path.write_bytes(bytes(112) + pixels.tobytes()) + return master_path, expected + + @pytest.mark.parametrize("reader_type", [RawFile, File]) @pytest.mark.parametrize("legacy_master", [False, True]) @pytest.mark.parametrize("padding, policy, supported", [ @@ -453,3 +494,120 @@ def test_read_eiger_udp_port_disabled(test_data_path): assert len(rois) == 2 assert rois[0] == ROI(0, 512, 0, 512) assert rois[1] == ROI(1024, 1536, 0, 512) + + +@pytest.mark.parametrize("layout", [(1, 1), (2, 1), (1, 2), (2, 2), (3, 2)]) +@pytest.mark.parametrize("reader_type", [RawFile, File]) +def test_raw_file_assembles_module_layout(tmp_path, layout, reader_type): + layout_rows, layout_cols = layout + master_path, expected = write_module_layout(tmp_path, layout_rows, layout_cols) + + with reader_type(master_path) as reader: + # RawFile binds rows/cols as methods (ROI overloads), File as properties + rows = reader.rows() if reader_type is RawFile else reader.rows + cols = reader.cols() if reader_type is RawFile else reader.cols + assert (rows, cols) == expected.shape + result = reader.read_frame() + image = result[1] if reader_type is RawFile else result + assert image.shape == expected.shape + assert (image == expected).all() + + reader.seek(0) + result = reader.read_n(2) + images = result[1] if reader_type is RawFile else result + assert images.shape == (2,) + expected.shape + assert (images == expected).all() + + +@pytest.mark.parametrize("layout", [(1, 1), (2, 1), (1, 2)]) +def test_raw_file_gap_pixels(tmp_path, layout): + layout_rows, layout_cols = layout + master_path, expected = write_module_layout(tmp_path, layout_rows, layout_cols, + module_rows=512, module_cols=1024) + gaps = GapPixels(fill_value=5) + with RawFile(master_path, gap_pixels=gaps) as reader: + assert reader.gap_pixels == gaps + # one chip boundary per module row, three per module column and no + # gap between modules + assert (reader.rows(), reader.cols()) == ((512 + 2) * layout_rows, (1024 + 6) * layout_cols) + header, image = reader.read_frame() + assert header.size == layout_rows * layout_cols + assert (image == insert_gap_pixels(expected, gaps)).all() + reader.seek(0) + _, images = reader.read_n(2) + assert images.shape == (2, reader.rows(), reader.cols()) + assert (images[1] == image).all() + + with RawFile(master_path) as reader: + assert reader.gap_pixels is None + assert (reader.rows(), reader.cols()) == expected.shape + + with RawFile(master_path, gap_pixels=True) as reader: + assert reader.gap_pixels == GapPixels() + assert (reader.rows(), reader.cols()) == insert_gap_pixels(expected).shape + _, image = reader.read_frame() + assert (image == insert_gap_pixels(expected)).all() + + module_gaps = GapPixels(module_gaps=ModuleGaps(8, 36)) + with RawFile(master_path, gap_pixels=module_gaps) as reader: + assert (reader.rows(), reader.cols()) == insert_gap_pixels(expected, module_gaps).shape + _, image = reader.read_frame() + assert (image == insert_gap_pixels(expected, module_gaps)).all() + + +def test_raw_file_gap_pixels_split_counts(tmp_path): + # one Eiger module: four 256x512 ports in a 2x2 layout. Splitting is + # rejected on raw Jungfrau data. The plain read is the reference since + # Eiger ports are row flipped on reading. + master_path, _ = write_module_layout(tmp_path, 2, 2, module_rows=256, module_cols=512, + detector_type="Eiger") + gaps = GapPixels(split_counts=True, seed=11) + with RawFile(master_path) as reader: + _, plain = reader.read_frame() + with RawFile(master_path, gap_pixels=gaps) as reader: + _, image = reader.read_frame() + assert (image == insert_gap_pixels(plain, gaps)).all() + assert image.sum() == plain.sum() + + +def test_raw_file_gap_pixels_split_counts_rejected_for_jungfrau(tmp_path): + master_path, _ = write_module_layout(tmp_path, 1, 1, module_rows=512, module_cols=1024) + RawFile(master_path, gap_pixels=GapPixels()) + with pytest.raises(ValueError): + RawFile(master_path, gap_pixels=GapPixels(split_counts=True)) + + +def test_raw_file_gap_pixels_unsupported_detector(tmp_path): + master_path, _ = write_module_layout(tmp_path, 1, 1, detector_type="Moench") + RawFile(master_path) + with pytest.raises(ValueError): + RawFile(master_path, gap_pixels=True) + + +@pytest.mark.withdata +def test_raw_file_gap_pixels_recorded_jungfrau(test_data_path): + path = test_data_path / "raw/jungfrau/jungfrau_single_master_0.json" + gaps = GapPixels(fill_value=3) + with RawFile(path, gap_pixels=gaps) as gapped, RawFile(path) as plain: + assert (gapped.rows(), gapped.cols()) == (514, 1030) + _, image = gapped.read_frame() + _, reference = plain.read_frame() + assert image.shape == (514, 1030) + assert (image == insert_gap_pixels(reference, gaps)).all() + + +@pytest.mark.withdata +def test_raw_file_gap_pixels_recorded_rois(test_data_path): + path = test_data_path / "raw/ROITestData/MultipleROIs/run_master_0.json" + with RawFile(path, gap_pixels=True) as gapped, RawFile(path) as plain: + assert gapped.num_rois == 2 + _, images = gapped.read_rois() + _, references = plain.read_rois() + rois = plain.master.rois + assert images[0].shape == (303, 103) + assert images[1].shape == (101, 103) + for image, reference, roi in zip(images, references, rois): + assert (image == insert_gap_pixels(reference, roi=roi)).all() + gapped.seek(0) + _, frames = gapped.read_n_with_roi(2, roi_index=1) + assert frames.shape == (2, 101, 103) diff --git a/src/RawFile.cpp b/src/RawFile.cpp index 54adada6..34c336a2 100644 --- a/src/RawFile.cpp +++ b/src/RawFile.cpp @@ -24,7 +24,8 @@ std::runtime_error RawFile::frame_error(size_t frame_index, frame_index, m_master.master_fname().string(), message)); } -RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode) +RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode, + std::optional gap_pixels) : m_master(fname) { m_mode = mode; @@ -61,6 +62,60 @@ RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode) } } m_part_buffer.resize(max_part_bytes); + + m_roi_rects = m_master.rois(); + if (m_roi_rects.size() != num_rois) { + throw std::runtime_error( + LOCATION + "ROI count differs from ROI geometry count"); + } + m_roi_shapes.reserve(num_rois); + if (gap_pixels) { + const auto detector = m_master.detector_type(); + if (detector != DetectorType::Jungfrau && + detector != DetectorType::Eiger) { + throw std::invalid_argument( + LOCATION + "Gap pixels are only supported for Jungfrau " + "and Eiger detectors"); + } + if (gap_pixels->split_counts && + detector == DetectorType::Jungfrau) { + throw std::invalid_argument( + LOCATION + "split_counts cannot be used on raw Jungfrau " + "data: it would split the gain bits. Convert " + "to energy and use insert_gap_pixels"); + } + // bit depth and fill value are known at open, reject them here + // rather than on the first read + switch (m_master.bitdepth()) { + case 8: + detail::fill_as(gap_pixels->fill_value); + break; + case 16: + detail::fill_as(gap_pixels->fill_value); + break; + case 32: + detail::fill_as(gap_pixels->fill_value); + break; + default: + throw std::invalid_argument( + LOCATION + + fmt::format("Gap pixels are not supported for a bit " + "depth of {}", + m_master.bitdepth())); + } + m_gap_pixels = gap_pixels; + m_gap_layout = detail::gap_layout(*gap_pixels); + m_generator = detail::make_generator(gap_pixels->seed); + for (const auto &rect : m_roi_rects) { + m_roi_shapes.push_back( + detail::gapped_shape(rect, m_gap_layout)); + } + } else { + for (const auto &roi : m_master.roi_geometries()) { + m_roi_shapes.push_back({static_cast(roi.pixels_y()), + static_cast(roi.pixels_x())}); + } + } if (!min_frames) { throw std::runtime_error(fmt::format( "No raw subfiles selected by '{}'", fname.string())); @@ -202,9 +257,7 @@ size_t RawFile::bytes_per_frame() { } size_t RawFile::bytes_per_frame(const size_t roi_index) { - return m_master.roi_geometries().at(roi_index).pixels_x() * - m_master.roi_geometries().at(roi_index).pixels_y() * - m_master.bitdepth() / bits_per_byte; + return pixels_per_frame(roi_index) * m_master.bitdepth() / bits_per_byte; } size_t RawFile::pixels_per_frame() { @@ -217,8 +270,7 @@ size_t RawFile::pixels_per_frame() { } size_t RawFile::pixels_per_frame(const size_t roi_index) { - return m_master.roi_geometries().at(roi_index).pixels_x() * - m_master.roi_geometries().at(roi_index).pixels_y(); + return rows(roi_index) * cols(roi_index); } DetectorType RawFile::detector_type() const { return m_master.detector_type(); } @@ -249,7 +301,7 @@ size_t RawFile::rows() const { return rows(0); } size_t RawFile::rows(const size_t roi_index) const { - return m_master.roi_geometries().at(roi_index).pixels_y(); + return static_cast(m_roi_shapes.at(roi_index)[0]); } size_t RawFile::cols() const { if (m_master.roi_geometries().size() > 1) { @@ -260,7 +312,7 @@ size_t RawFile::cols() const { return cols(0); } size_t RawFile::cols(const size_t roi_index) const { - return m_master.roi_geometries().at(roi_index).pixels_x(); + return static_cast(m_roi_shapes.at(roi_index)[1]); } size_t RawFile::bitdepth() const { return m_master.bitdepth(); } @@ -333,8 +385,8 @@ DetectorHeader RawFile::read_header(const std::filesystem::path &fname) { RawMasterFile RawFile::master() const { return m_master; } Frame RawFile::get_frame(size_t frame_index, const size_t roi_index) { - auto f = Frame(m_master.roi_geometries().at(roi_index).pixels_y(), - m_master.roi_geometries().at(roi_index).pixels_x(), + auto f = Frame(static_cast(rows(roi_index)), + static_cast(cols(roi_index)), Dtype::from_bitdepth(m_master.bitdepth())); std::byte *frame_buffer = f.data(); get_frame_into(frame_index, frame_buffer, roi_index); @@ -400,6 +452,30 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer, const auto frame_indices = synchronized_frame_indices(frame_index, roi_index); + if (m_gap_pixels) { + switch (m_master.bitdepth()) { + case 8: + assemble_with_gaps(frame_buffer, roi_index, frame_indices, + header); + break; + case 16: + assemble_with_gaps(frame_buffer, roi_index, frame_indices, + header); + break; + case 32: + assemble_with_gaps(frame_buffer, roi_index, frame_indices, + header); + break; + default: + throw frame_error(frame_index, + LOCATION + + fmt::format("Gap pixels are not supported " + "for a bit depth of {}", + m_master.bitdepth())); + } + return; + } + const size_t bytes_per_pixel = m_master.bitdepth() / bits_per_byte; const size_t roi_width = roi.pixels_x(); @@ -437,6 +513,43 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer, } } +template +void RawFile::assemble_with_gaps(std::byte *frame_buffer, size_t roi_index, + const std::vector &frame_indices, + DetectorHeader *header) { + const auto &roi = m_master.roi_geometries().at(roi_index); + const ROI &rect = m_roi_rects.at(roi_index); + NDView destination(reinterpret_cast(frame_buffer), + m_roi_shapes.at(roi_index)); + detail::fill_gap_pixels(destination, rect, m_gap_layout, + detail::fill_as(m_gap_pixels->fill_value)); + + for (size_t part_idx = 0; part_idx != roi.num_modules_in_roi(); + ++part_idx) { + const auto &pos = m_master.geometry().get_module_geometries( + roi.module_indices_in_roi(part_idx)); + auto &subfile = *m_subfiles[roi_index][part_idx]; + subfile.seek(frame_indices[part_idx]); + subfile.read_into(m_part_buffer.data(), header); + if (header) { + ++header; + } + // detector coordinates of the part + const ROI part_rect{ + rect.xmin + pos.origin_x, rect.xmin + pos.origin_x + pos.width, + rect.ymin + pos.origin_y, rect.ymin + pos.origin_y + pos.height}; + NDView source( + reinterpret_cast(m_part_buffer.data()), + {pos.height, pos.width}); + detail::copy_with_gaps(source, part_rect, destination, rect, + m_gap_layout); + } + + if (m_gap_pixels->split_counts) { + detail::split_edge_counts(destination, rect, m_gap_layout, m_generator); + } +} + std::vector RawFile::read_n(size_t n_frames) { // TODO: implement this in a more efficient way if (num_rois() > 1) { diff --git a/src/RawFile.test.cpp b/src/RawFile.test.cpp index ee0b9e24..a4d67ec9 100644 --- a/src/RawFile.test.cpp +++ b/src/RawFile.test.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: MPL-2.0 #include "aare/RawFile.hpp" #include "aare/File.hpp" +#include "aare/GapPixels.hpp" #include "aare/RawMasterFile.hpp" //needed for ROI #include @@ -222,6 +223,354 @@ TEST_CASE("RawFile frame count comes from the complete subfile series", REQUIRE_NOTHROW(reader.read_frame(1)); } +TEST_CASE("RawFile assembles every module layout", "[RawFile][geometry]") { + const auto [layout_rows, layout_cols] = GENERATE(table({ + {1, 1}, + {2, 1}, + {1, 2}, + {2, 2}, + {3, 2}, + })); + CAPTURE(layout_rows, layout_cols); + TemporaryRawFiles files(xy{layout_rows, layout_cols}); + const size_t rows = TemporaryRawFiles::module_rows * layout_rows; + const size_t cols = TemporaryRawFiles::module_cols * layout_cols; + + auto check = [&](NDView image) { + REQUIRE(image.shape(0) == static_cast(rows)); + REQUIRE(image.shape(1) == static_cast(cols)); + for (size_t row = 0; row < rows; ++row) { + for (size_t col = 0; col < cols; ++col) { + CAPTURE(row, col); + REQUIRE(image(row, col) == files.expected(row, col)); + } + } + }; + + RawFile file(files.master_path()); + REQUIRE(file.rows() == rows); + REQUIRE(file.cols() == cols); + REQUIRE(file.n_modules() == files.n_modules()); + REQUIRE(file.bytes_per_frame() == rows * cols * sizeof(uint16_t)); + + SECTION("read_frame") { + auto frame = file.read_frame(); + check(frame.view()); + } + SECTION("read_into with headers") { + NDArray image( + {static_cast(rows), static_cast(cols)}); + std::vector headers(files.n_modules()); + file.seek(1); + file.read_into(reinterpret_cast(image.data()), + headers.data()); + check(image.view()); + for (size_t module = 0; module < files.n_modules(); ++module) { + CAPTURE(module); + REQUIRE(headers[module].frameNumber == 101); + REQUIRE(headers[module].row == module % layout_rows); + REQUIRE(headers[module].column == module / layout_rows); + } + } + SECTION("read_n") { + auto frames = file.read_n(2); + REQUIRE(frames.size() == 2); + for (auto &frame : frames) { + check(frame.view()); + } + } + SECTION("generic File") { + File reader(files.master_path()); + auto frame = reader.read_frame(1); + check(frame.view()); + } +} + +namespace { + +/// Compare a frame read with gap pixels against the free function applied +/// to the same frame read without gaps. +template +bool matches_gap_oracle(Frame &gapped, Frame &plain, const ROI &roi, + const GapPixels &gaps) { + auto expected = + insert_gap_pixels(NDView(plain.view()), roi, gaps); + auto actual = gapped.view(); + if (expected.shape() != actual.shape()) { + UNSCOPED_INFO("shape " << actual.shape(0) << "x" << actual.shape(1) + << " expected " << expected.shape(0) << "x" + << expected.shape(1)); + return false; + } + for (ssize_t row = 0; row < expected.shape(0); ++row) { + for (ssize_t col = 0; col < expected.shape(1); ++col) { + if (expected(row, col) != actual(row, col)) { + UNSCOPED_INFO("pixel (" << row << ", " << col << ") " + << actual(row, col) << " expected " + << expected(row, col)); + return false; + } + } + } + return true; +} + +bool matches_gap_oracle(Frame &gapped, Frame &plain, const ROI &roi, + const GapPixels &gaps) { + switch (plain.bitdepth()) { + case 8: + return matches_gap_oracle(gapped, plain, roi, gaps); + case 16: + return matches_gap_oracle(gapped, plain, roi, gaps); + case 32: + return matches_gap_oracle(gapped, plain, roi, gaps); + default: + return false; + } +} + +} // namespace + +TEST_CASE("RawFile inserts gap pixels into synthetic Jungfrau modules", + "[RawFile][GapPixels]") { + const auto [layout_rows, layout_cols] = GENERATE(table({ + {1, 1}, + {2, 1}, + {1, 2}, + })); + CAPTURE(layout_rows, layout_cols); + TemporaryRawFiles files(xy{layout_rows, layout_cols}, xy{512, 1024}); + const ROI detector{0, static_cast(files.cols()), 0, + static_cast(files.rows())}; + + GapPixels gaps; + SECTION("defaults") {} + SECTION("module gaps and fill value") { + gaps.module_gaps = ModuleGaps{8, 36}; + gaps.fill_value = 7; + } + const auto layout = detail::gap_layout(gaps); + const auto shape = detail::gapped_shape(detector, layout); + const auto fill = static_cast(gaps.fill_value); + + RawFile file(files.master_path(), "r", gaps); + REQUIRE(file.gap_pixels() == gaps); + REQUIRE(file.rows() == static_cast(shape[0])); + REQUIRE(file.cols() == static_cast(shape[1])); + REQUIRE(file.pixels_per_frame() == + static_cast(shape[0] * shape[1])); + REQUIRE(file.bytes_per_frame() == file.pixels_per_frame() * 2); + + std::vector headers(files.n_modules()); + NDArray image(shape); + file.read_into(reinterpret_cast(image.data()), headers.data()); + for (const auto &header : headers) { + REQUIRE(header.frameNumber == 100); + } + + for (size_t row = 0; row < files.rows(); ++row) { + for (size_t col = 0; col < files.cols(); ++col) { + const auto value = + image(layout.y.gapped(static_cast(row)), + layout.x.gapped(static_cast(col))); + if (value != files.expected(row, col)) { + CAPTURE(row, col); + REQUIRE(value == files.expected(row, col)); + } + } + } + for (const auto boundary : + layout.x.inner_boundaries(detector.xmin, detector.xmax)) { + const auto [first, last] = layout.x.gap_range(boundary, 0); + for (ssize_t col = first; col <= last; ++col) { + for (ssize_t row = 0; row < shape[0]; ++row) { + if (image(row, col) != fill) { + CAPTURE(row, col); + REQUIRE(image(row, col) == fill); + } + } + } + } + for (const auto boundary : + layout.y.inner_boundaries(detector.ymin, detector.ymax)) { + const auto [first, last] = layout.y.gap_range(boundary, 0); + for (ssize_t row = first; row <= last; ++row) { + for (ssize_t col = 0; col < shape[1]; ++col) { + if (image(row, col) != fill) { + CAPTURE(row, col); + REQUIRE(image(row, col) == fill); + } + } + } + } + + auto frame = file.read_frame(); + REQUIRE(frame.rows() == static_cast(shape[0])); + REQUIRE(frame.cols() == static_cast(shape[1])); + REQUIRE(frame.view() == image.view()); +} + +TEST_CASE("RawFile splits counts like the free function", + "[RawFile][GapPixels]") { + // one Eiger module: four 256x512 ports in a 2x2 layout. Splitting is + // rejected on raw Jungfrau data, so the synthetic file is Eiger. + TemporaryRawFiles files(xy{2, 2}, xy{256, 512}); + auto metadata = nlohmann::json::parse(std::ifstream(files.master_path())); + metadata["Detector Type"] = "Eiger"; + std::ofstream(files.master_path()) << metadata; + GapPixels gaps; + gaps.split_counts = true; + gaps.seed = 7; + RawFile gapped(files.master_path(), "r", gaps); + RawFile plain(files.master_path()); + auto gapped_frame = gapped.read_frame(); + auto plain_frame = plain.read_frame(); + const ROI detector{0, 1024, 0, 512}; + REQUIRE(matches_gap_oracle(gapped_frame, plain_frame, detector, gaps)); + + // the next frame continues the generator, so the oracle for frame 1 is + // the free function applied after the same number of draws + auto frames = gapped.read_n(1); + auto second_plain = plain.read_frame(); + auto expected = insert_gap_pixels( + NDView(second_plain.view()), detector, + gaps); + double gapped_total = 0; + double expected_total = 0; + auto view = frames[0].view(); + for (ssize_t row = 0; row < expected.shape(0); ++row) { + for (ssize_t col = 0; col < expected.shape(1); ++col) { + gapped_total += view(row, col); + expected_total += expected(row, col); + } + } + REQUIRE(gapped_total == expected_total); +} + +TEST_CASE("RawFile rejects split counts on raw Jungfrau data", + "[RawFile][GapPixels]") { + TemporaryRawFiles files(xy{1, 1}, xy{512, 1024}); + GapPixels gaps; + gaps.split_counts = true; + REQUIRE_NOTHROW(RawFile(files.master_path(), "r", GapPixels{})); + REQUIRE_THROWS_AS(RawFile(files.master_path(), "r", gaps), + std::invalid_argument); +} + +TEST_CASE("RawFile rejects gap pixels for unsupported detectors", + "[RawFile][GapPixels]") { + TemporaryRawFiles files; + auto metadata = nlohmann::json::parse(std::ifstream(files.master_path())); + metadata["Detector Type"] = "Moench"; + std::ofstream(files.master_path()) << metadata; + REQUIRE_NOTHROW(RawFile(files.master_path())); + REQUIRE_THROWS_AS(RawFile(files.master_path(), "r", GapPixels{}), + std::invalid_argument); +} + +TEST_CASE("Gap pixels on recorded Jungfrau and Eiger files", + "[.with-data][RawFile][GapPixels]") { + struct Case { + const char *path; + std::array shape; + std::optional module_gaps; + }; + const auto test = GENERATE(values({ + {"raw/jungfrau/jungfrau_single_master_0.json", {514, 1030}, {}}, + {"raw/jungfrau/jungfrau_double_master_0.json", {514, 1030}, {}}, + {"raw/eiger/Lab6_20500eV_2deg_20240629_master_7.json", {514, 1030}, {}}, + {"raw/eiger/eiger_500k_16bit_master_0.json", {514, 1030}, {}}, + {"raw/eiger_quad_data/" + "W13_vrpreampscan_m21C_300V_800eV_vthre2000_master_0.json", + {514, 514}, + {}}, + {"raw/virtual/920/jungfrau/two_modules_master_0.json", + {1028, 1030}, + {}}, + {"raw/virtual/920/jungfrau/two_modules_master_0.json", + {1064, 1030}, + ModuleGaps{8, 36}}, + {"raw/ROITestData/MultipleChipROI/run_master_2.json", {301, 103}, {}}, + {"raw/ROITestData/MultipleChipROI/run_master_2.json", + {337, 103}, + ModuleGaps{8, 36}}, + {"raw/virtual/920/jungfrau/" + "single_module_roi_512_767_0_255_master_0.json", + {256, 256}, + {}}, + })); + CAPTURE(test.path); + const auto fpath = test_data_path() / test.path; + REQUIRE(std::filesystem::exists(fpath)); + + GapPixels gaps; + gaps.module_gaps = test.module_gaps; + gaps.fill_value = 3; + RawFile gapped(fpath, "r", gaps); + RawFile plain(fpath); + REQUIRE(gapped.rows() == static_cast(test.shape[0])); + REQUIRE(gapped.cols() == static_cast(test.shape[1])); + REQUIRE(gapped.bytes_per_frame() == + gapped.pixels_per_frame() * gapped.bytes_per_pixel()); + + auto gapped_frame = gapped.read_frame(); + auto plain_frame = plain.read_frame(); + REQUIRE(gapped_frame.rows() == static_cast(test.shape[0])); + REQUIRE(gapped_frame.cols() == static_cast(test.shape[1])); + REQUIRE(matches_gap_oracle(gapped_frame, plain_frame, plain.master().roi(), + gaps)); +} + +TEST_CASE("Split counts on a recorded Eiger file", + "[.with-data][RawFile][GapPixels]") { + const auto fpath = + test_data_path() / "raw/eiger/eiger_500k_16bit_master_0.json"; + GapPixels gaps; + gaps.split_counts = true; + gaps.seed = 2024; + RawFile gapped(fpath, "r", gaps); + RawFile plain(fpath); + auto gapped_frame = gapped.read_frame(); + auto plain_frame = plain.read_frame(); + REQUIRE(matches_gap_oracle(gapped_frame, plain_frame, plain.master().roi(), + gaps)); +} + +TEST_CASE("Split counts are rejected on a recorded Jungfrau file", + "[.with-data][RawFile][GapPixels]") { + const auto fpath = + test_data_path() / "raw/jungfrau/jungfrau_single_master_0.json"; + GapPixels gaps; + gaps.split_counts = true; + REQUIRE_THROWS_AS(RawFile(fpath, "r", gaps), std::invalid_argument); +} + +TEST_CASE("Gap pixels on a file with two ROIs", + "[.with-data][RawFile][GapPixels]") { + const auto fpath = + test_data_path() / "raw/ROITestData/MultipleROIs/run_master_0.json"; + GapPixels gaps; + RawFile gapped(fpath, "r", gaps); + RawFile plain(fpath); + REQUIRE(gapped.num_rois() == 2); + // x 200..300 holds the chip boundary at 256; y 100..400 holds the one at + // 256 while y 600..700 holds none + REQUIRE(gapped.rows(0) == 303); + REQUIRE(gapped.cols(0) == 103); + REQUIRE(gapped.rows(1) == 101); + REQUIRE(gapped.cols(1) == 103); + + auto gapped_frames = gapped.read_rois(); + auto plain_frames = plain.read_rois(); + const auto rois = plain.master().rois(); + REQUIRE(gapped_frames.size() == 2); + for (size_t index = 0; index < 2; ++index) { + CAPTURE(index); + REQUIRE(matches_gap_oracle(gapped_frames[index], plain_frames[index], + rois[index], gaps)); + } +} + TEST_CASE("Read number of frames from a jungfrau raw file", "[.with-data][RawFile]") { @@ -535,7 +884,7 @@ TEST_CASE("Open multi module file with ROI", } TEST_CASE("Open multi module file with ROI spanning over multiple modules", - "[.width-data][read_rois][RawFile]") { + "[.with-data][read_rois][RawFile]") { auto fpath = test_data_path() / "raw/ROITestData/MultipleChipROI/run_master_2.json"; @@ -557,7 +906,7 @@ TEST_CASE("Open multi module file with ROI spanning over multiple modules", } TEST_CASE("Open multi module file with two ROIs", - "[.width-data][read_rois][RawFile]") { + "[.with-data][read_rois][RawFile]") { auto fpath = test_data_path() / "raw/ROITestData/MultipleROIs/run_master_0.json"; diff --git a/tests/raw_file_helpers.hpp b/tests/raw_file_helpers.hpp index b1a9b17c..4b8733e0 100644 --- a/tests/raw_file_helpers.hpp +++ b/tests/raw_file_helpers.hpp @@ -8,44 +8,99 @@ #include #include #include +#include +/** + * @brief Throwaway raw file series with a 2x3 pixel Jungfrau "module" per + * data file. Modules are laid out as DetectorGeometry orders them (module + * index runs down each column first) and every module holds distinct pixel + * values so that misplaced modules are detected. + */ class TemporaryRawFiles { std::filesystem::path m_directory; + aare::xy m_layout; + aare::xy m_module_size; public: - explicit TemporaryRawFiles(size_t modules = 1) { + static constexpr size_t module_rows = 2; + static constexpr size_t module_cols = 3; + static constexpr size_t frames = 2; + + /// Value written to pixel index `pixel` (row major) of module `module` + static uint16_t pixel_value(size_t module, size_t pixel) { + return static_cast((module * 10 + pixel + 1) % 65536); + } + + /// Modules stacked in one column + explicit TemporaryRawFiles(size_t modules = 1) + : TemporaryRawFiles(aare::xy{static_cast(modules), 1}) {} + + /// Modules of `module_size` pixels arranged in `layout.row` rows and + /// `layout.col` columns. The default module is 2x3 pixels; pass + /// {512, 1024} for a full Jungfrau module. + explicit TemporaryRawFiles(aare::xy layout, + aare::xy module_size = {module_rows, + module_cols}) + : m_layout(layout), m_module_size(module_size) { 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); + const size_t pixels_per_module = module_size.row * module_size.col; const nlohmann::json metadata = { {"Version", 7.2}, {"Detector Type", "Jungfrau"}, {"Timing Mode", "auto"}, - {"Geometry", {{"x", 1}, {"y", modules}}}, - {"Image Size in bytes", 12}, - {"Pixels", {{"x", 3}, {"y", 2}}}, + {"Geometry", {{"x", layout.col}, {"y", layout.row}}}, + {"Image Size in bytes", pixels_per_module * 2}, + {"Pixels", {{"x", module_size.col}, {"y", module_size.row}}}, {"Max Frames Per File", 1}, - {"Total Frames", 2}, - {"Frames in File", 2}, + {"Total Frames", frames}, + {"Frames in File", frames}, {"Frame Padding", 1}, {"Frame Discard Policy", "nodiscard"}}; std::ofstream(master_path()) << metadata; - for (size_t module = 0; module < modules; ++module) { - for (size_t file = 0; file < 2; ++file) { + std::vector pixels(pixels_per_module); + for (size_t module = 0; module < n_modules(); ++module) { + for (size_t pixel = 0; pixel < pixels_per_module; ++pixel) { + pixels[pixel] = pixel_value(module, pixel); + } + for (size_t file = 0; file < frames; ++file) { std::ofstream output(data_path(module, file), std::ios::binary); aare::DetectorHeader header{}; header.frameNumber = 100 + file; - const uint16_t pixels[6] = {1, 2, 3, 4, 5, 6}; + header.row = static_cast(module % layout.row); + header.column = static_cast(module / layout.row); output.write(reinterpret_cast(&header), sizeof(header)); - output.write(reinterpret_cast(pixels), - sizeof(pixels)); + output.write(reinterpret_cast(pixels.data()), + static_cast(pixels.size() * + sizeof(uint16_t))); } } } + aare::xy layout() const { return m_layout; } + aare::xy module_size() const { return m_module_size; } + size_t n_modules() const { return m_layout.row * m_layout.col; } + size_t rows() const { return m_module_size.row * m_layout.row; } + size_t cols() const { return m_module_size.col * m_layout.col; } + + /// Module index (data file number) of the module at a layout position + size_t module_index(size_t module_row, size_t module_col) const { + return module_col * m_layout.row + module_row; + } + + /// Expected value of pixel (row, col) in the assembled image + uint16_t expected(size_t row, size_t col) const { + const size_t module = + module_index(row / m_module_size.row, col / m_module_size.col); + const size_t pixel = (row % m_module_size.row) * m_module_size.col + + col % m_module_size.col; + return pixel_value(module, pixel); + } + TemporaryRawFiles(const TemporaryRawFiles &) = delete; TemporaryRawFiles &operator=(const TemporaryRawFiles &) = delete; ~TemporaryRawFiles() { std::filesystem::remove_all(m_directory); } From 56e880638ec4fa0996f1c6f2ce9ecec51602aa6f Mon Sep 17 00:00:00 2001 From: AliceMazzoleni99 Date: Tue, 3 Nov 2026 09:51:26 +0100 Subject: [PATCH 15/16] handle overloads (#433) Pybind11 merges all docstrings of overloaded functions into one docstring. Sphinx rendering usually complains about these merged docstrings e.g unexpected Section titles. Added a custom sphinx extension that overwrites the standard pybind11 method and function document handler. The handler splits the pybind generated docstring and adds for each overload its own method header. --- docs/CMakeLists.txt | 29 ++----- docs/{conf.py.in => conf.py} | 9 ++- docs/pybind_overloads.py | 144 +++++++++++++++++++++++++++++++++++ 3 files changed, 154 insertions(+), 28 deletions(-) rename docs/{conf.py.in => conf.py} (88%) create mode 100644 docs/pybind_overloads.py diff --git a/docs/CMakeLists.txt b/docs/CMakeLists.txt index d83b6f29..c26075a9 100644 --- a/docs/CMakeLists.txt +++ b/docs/CMakeLists.txt @@ -11,32 +11,13 @@ configure_file(${DOXYGEN_IN} ${DOXYGEN_OUT} @ONLY) set(SPHINX_SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/src) set(SPHINX_BUILD ${CMAKE_CURRENT_BINARY_DIR}) -file( - GLOB_RECURSE SPHINX_SOURCE_FILES CONFIGURE_DEPENDS - RELATIVE "${CMAKE_CURRENT_SOURCE_DIR}/src" - "${CMAKE_CURRENT_SOURCE_DIR}/src/*.rst") - -foreach(relpath IN LISTS SPHINX_SOURCE_FILES) - set(src "${CMAKE_CURRENT_SOURCE_DIR}/src/${relpath}") - set(dst "${SPHINX_BUILD}/src/${relpath}") - - message(STATUS "Copying ${src} to ${dst}") - configure_file("${src}" "${dst}" COPYONLY) -endforeach() - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/conf.py.in" - "${SPHINX_BUILD}/conf.py" @ONLY) - -file(COPY "${CMAKE_CURRENT_SOURCE_DIR}/figures" DESTINATION "${SPHINX_BUILD}") - -configure_file("${CMAKE_CURRENT_SOURCE_DIR}/static/extra.css" - "${SPHINX_BUILD}/static/css/extra.css" @ONLY) - add_custom_target( docs COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT} COMMAND - ${SPHINX_EXECUTABLE} -W -a -b html - -Dbreathe_projects.aare=${CMAKE_CURRENT_BINARY_DIR}/xml -c "${SPHINX_BUILD}" - ${SPHINX_BUILD}/src ${SPHINX_BUILD}/html + ${CMAKE_COMMAND} -E env "PYTHONPATH=${CMAKE_BINARY_DIR}" # find aare module + ${SPHINX_EXECUTABLE} -W -a -b html -Dversion=${PROJECT_VERSION} + -Drelease=${PROJECT_VERSION} + -Dbreathe_projects.aare=${CMAKE_CURRENT_BINARY_DIR}/xml -c + "${CMAKE_CURRENT_SOURCE_DIR}" ${SPHINX_SOURCE} ${SPHINX_BUILD}/html COMMENT "Generating documentation with Sphinx") diff --git a/docs/conf.py.in b/docs/conf.py similarity index 88% rename from docs/conf.py.in rename to docs/conf.py index 1e0b5a71..88e035bf 100644 --- a/docs/conf.py.in +++ b/docs/conf.py @@ -13,9 +13,8 @@ # import os import sys -sys.path.insert(0, os.path.abspath('..')) +sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) # finds pybind_overloads.py -print(sys.path) # -- Project information ----------------------------------------------------- @@ -23,6 +22,7 @@ project = 'aare' copyright = '2024, CPS Detector Group' author = 'CPS Detector Group' version = '@PROJECT_VERSION@' +release = '@PROJECT_VERSION@' # -- General configuration --------------------------------------------------- @@ -32,10 +32,12 @@ version = '@PROJECT_VERSION@' extensions = ['breathe', 'sphinx.ext.autodoc', 'sphinx.ext.napoleon', + 'pybind_overloads', ] breathe_default_project = "aare" napoleon_use_ivar = True +napoleon_numpy_docstring = True # Add any paths that contain templates here, relative to this directory. @@ -59,6 +61,5 @@ html_theme = "furo" # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['static'] - def setup(app): - app.add_css_file('css/extra.css') # may also be an URL \ No newline at end of file + app.add_css_file('extra.css') # relative to _static/; may also be an URL \ No newline at end of file diff --git a/docs/pybind_overloads.py b/docs/pybind_overloads.py new file mode 100644 index 00000000..68a2bd6f --- /dev/null +++ b/docs/pybind_overloads.py @@ -0,0 +1,144 @@ +# SPDX-License-Identifier: MPL-2.0 +"""Sphinx extension that documents pybind11 overloads as separate entries. + +pybind11 merges the docstrings of all overloads of a function into one:: + + name(*args, **kwargs) + Overloaded function. + + 1. name(self: pkg.Cls, a: int) -> int + + docstring of overload 1 + + 2. name(self: pkg.Cls, a: float) -> float + + docstring of overload 2 + +This extension replaces autodoc's function and method documenters so that +every overload is rendered as its own entry, with its own signature and +docstring, as if it were a separate function:: + + name(a: int) -> int + docstring of overload 1 + + name(a: float) -> float + docstring of overload 2 + +Every overload body goes through ``autodoc-process-docstring`` on its own, so +napoleon renders the ``Parameters``/``Returns`` sections of each overload. + +Works for any overloaded function, method, operator or ``__call__``. +""" + +import re +import textwrap + +from sphinx.ext.autodoc import FunctionDocumenter, MethodDocumenter +from sphinx.util.docstrings import prepare_docstring + +OVERLOAD_MARKER = "Overloaded function." + +# "1. name(args) -> ret"; args may contain nested parentheses (default values), +# so match greedily up to the last ")" before an optional "-> ret". +_HEADER_RE = re.compile( + r"^(?P\d+)\.\s+(?P[\w.]+)\((?P.*)\)\s*(?:->\s*(?P.+?))?\s*$" +) +# Leading "self" / "self: pkg.Cls" argument of a bound method +_SELF_RE = re.compile(r"^\s*self(?:\s*:\s*[^,]+)?\s*(?:,\s*|$)") +# Fully qualified dotted names, e.g. aare._aare.ROI or numpy.typing.NDArray +#_QUALIFIED_RE = re.compile(r"\b(?:[A-Za-z_]\w*\.)+([A-Za-z_]\w*)") + + +def _split_overloads(lines): + """Return [(header_match, body_lines), ...] or None if not overloaded.""" + try: + start = next(i for i, l in enumerate(lines) if l.strip() == OVERLOAD_MARKER) + except StopIteration: + return None + + # Everything before the marker must be blank or the "name(*args, **kwargs)" line + if any(l.strip() and not l.strip().endswith("(*args, **kwargs)") for l in lines[:start]): + return None + + overloads = [] + func_name = None + for line in lines[start + 1:]: + m = _HEADER_RE.match(line) + # Only accept "N. name(" at column 0 with the expected index and the same + # name, so numbered lists inside a docstring are not mistaken for headers. + if (m and int(m["idx"]) == len(overloads) + 1 + and func_name in (None, m["name"])): + func_name = m["name"] + overloads.append((m, [])) + elif overloads: + overloads[-1][1].append(line) + + return overloads or None + + +class PybindOverloadMixin: + """Render each pybind11 overload as a separate directive. + + The first overload uses the directive autodoc generates anyway; the others + are appended as sibling directives (with ``:no-index:`` to avoid duplicate + object warnings) after the first overload's content. + """ + + _overloads = None + _current = 0 + + def format_signature(self, **kwargs): + doc = getattr(self.object, "__doc__", None) + self._overloads = _split_overloads(prepare_docstring(doc)) if isinstance(doc, str) else None + if not self._overloads: + return super().format_signature(**kwargs) + return self._overload_signature(0) + + def get_doc(self): + if not self._overloads: + return super().get_doc() + body = self._overloads[self._current][1] + return [prepare_docstring(textwrap.dedent("\n".join(body)))] + + def add_content(self, more_content): + super().add_content(more_content) + if not self._overloads or self._current: + return + + sourcename = self.get_sourcename() + content_indent = self.indent + outer_indent = content_indent[: len(content_indent) - len(self.content_indent)] + for i in range(1, len(self._overloads)): + self._current = i + self.indent = outer_indent + self.add_line("", sourcename) + self.add_directive_header(self._overload_signature(i)) + if not (self.options.no_index or self.options.noindex): + self.add_line(" :no-index:", sourcename) + self.add_line("", sourcename) + self.indent = content_indent + super().add_content(None) + self._current = 0 + + def _overload_signature(self, i): + header = self._overloads[i][0] + sig = f"({_SELF_RE.sub('', header['args'], count=1)})" + if header["ret"]: + sig += f" -> {header['ret']}" + return sig + + +class PybindFunctionDocumenter(PybindOverloadMixin, FunctionDocumenter): + pass + + +class PybindMethodDocumenter(PybindOverloadMixin, MethodDocumenter): + pass + + +def setup(app): + app.setup_extension("sphinx.ext.autodoc") + #app.add_config_value("pybind_overloads_short_names", False, "env") # not sure if needed + app.add_autodocumenter(PybindFunctionDocumenter, override=True) # overwrites existing pybind autodoc function documenter + app.add_autodocumenter(PybindMethodDocumenter, override=True) + return {"parallel_read_safe": True, "parallel_write_safe": True} # extension metadata From 288152716b5619c71a2199625ab8197a51eb0150 Mon Sep 17 00:00:00 2001 From: AliceMazzoleni99 Date: Tue, 3 Nov 2026 10:35:08 +0100 Subject: [PATCH 16/16] Dev/jungfraucalibration (#427) stuff needed for JungfrauCalibration: - added fit boundaries to fit function (needed to only fit a certain range, faster than iterating over it in python) - added Jungfrau Geometry definitions - added mean_over_dataset (takes the mean over some aqcuisitions in a file - added read_current_source (reads current_source data from Jungfrau and averages) - added configurable option to fit elastic scattering in fit modules - added bad channel mask to PedestalTrackingHistogram --- CMakeLists.txt | 10 +- RELEASE.md | 6 +- benchmarks/CMakeLists.txt | 9 +- benchmarks/DataSetAggregation_benchmark.cpp | 34 +++ docs/src/DataSetAggregation.rst | 74 +++++++ docs/src/index.rst | 2 + docs/src/pyDataSetAggregation.rst | 74 +++++++ include/aare/DataSetAggregation.hpp | 193 ++++++++++++++++++ include/aare/Fit.hpp | 8 +- include/aare/Models.hpp | 46 +++-- include/aare/MultiThreadedFileReader.hpp | 7 +- include/aare/defs.hpp | 5 + .../hist/PedestalTrackingPixelHistogram.hpp | 12 +- include/aare/utils/RingBufferPool.hpp | 139 +++++++++++++ python/aare/__init__.py | 2 + python/benchmarks/mean_over_dataset.py | 50 +++++ python/benchmarks/read_current_source.py | 62 ++++++ python/src/bind_DataSetAggregation.hpp | 78 +++++++ python/src/bind_Defs.hpp | 3 + .../bind_PedestalTrackingPixelHistogram.hpp | 55 ++++- python/src/fit.hpp | 126 +++++++++--- python/src/module.cpp | 5 + python/tests/conftest.py | 26 +++ python/tests/test_DataSetAggregation.py | 56 +++++ src/DataSetAggregation.cpp | 184 +++++++++++++++++ src/DataSetAggregation.test.cpp | 113 ++++++++++ src/MultiThreadedFileReader.cpp | 14 +- src/fit/Fit.cpp | 42 +++- src/fit/FitHelpers.hpp | 12 +- src/hist/PedestalTrackingPixelHistogram.cpp | 63 +++++- src/utils/RingBufferPool.test.cpp | 127 ++++++++++++ tests/jungfrau_file_helpers.hpp | 80 ++++++++ 32 files changed, 1645 insertions(+), 72 deletions(-) create mode 100644 benchmarks/DataSetAggregation_benchmark.cpp create mode 100644 docs/src/DataSetAggregation.rst create mode 100644 docs/src/pyDataSetAggregation.rst create mode 100644 include/aare/DataSetAggregation.hpp create mode 100644 include/aare/utils/RingBufferPool.hpp create mode 100644 python/benchmarks/mean_over_dataset.py create mode 100644 python/benchmarks/read_current_source.py create mode 100644 python/src/bind_DataSetAggregation.hpp create mode 100644 python/tests/test_DataSetAggregation.py create mode 100644 src/DataSetAggregation.cpp create mode 100644 src/DataSetAggregation.test.cpp create mode 100644 src/utils/RingBufferPool.test.cpp create mode 100644 tests/jungfrau_file_helpers.hpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 62a2a368..74197f9f 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -388,6 +388,7 @@ set(PUBLICHEADERS include/aare/ROI.hpp include/aare/ROIGeometry.hpp include/aare/DetectorGeometry.hpp + include/aare/DataSetAggregation.hpp include/aare/GapPixels.hpp include/aare/JungfrauDataFile.hpp include/aare/logger.hpp @@ -404,7 +405,8 @@ set(PUBLICHEADERS include/aare/to_string.hpp include/aare/utils/task.hpp include/aare/utils/ifstream_helpers.hpp - include/aare/utils/math_helpers.hpp) + include/aare/utils/math_helpers.hpp + include/aare/utils/RingBufferPool.hpp) set(SourceFiles ${CMAKE_CURRENT_SOURCE_DIR}/src/calibration.cpp @@ -416,6 +418,7 @@ set(SourceFiles ${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/GapPixels.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/DataSetAggregation.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Dtype.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/File.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/FilePtr.cpp @@ -460,7 +463,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() @@ -475,6 +478,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 @@ -484,6 +488,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/GapPixels.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/Interpolation.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/RawMasterFile.test.cpp @@ -510,6 +515,7 @@ if(AARE_TESTS) ${CMAKE_CURRENT_SOURCE_DIR}/src/RawSubFile.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/task.test.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/src/utils/RingBufferPool.test.cpp ${CMAKE_CURRENT_SOURCE_DIR}/src/to_string.test.cpp) target_sources(tests PRIVATE ${TestSources}) endif() diff --git a/RELEASE.md b/RELEASE.md index e8b90b5f..d5a2f81a 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -1,6 +1,6 @@ # Release notes -## Next +## Next: ### New Features: @@ -17,6 +17,10 @@ is set, gaps between modules. Gap positions follow detector coordinates 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 ``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 diff --git a/benchmarks/CMakeLists.txt b/benchmarks/CMakeLists.txt index f89b57d3..b81cb4ed 100644 --- a/benchmarks/CMakeLists.txt +++ b/benchmarks/CMakeLists.txt @@ -19,8 +19,13 @@ add_executable(benchmarks) target_sources( benchmarks - PRIVATE ndarray_benchmark.cpp ndview_benchmark.cpp calculateeta_benchmark.cpp - reduce_benchmark.cpp clusterfile_benchmark.cpp rawfile_benchmark.cpp) + PRIVATE ndarray_benchmark.cpp + ndview_benchmark.cpp + calculateeta_benchmark.cpp + reduce_benchmark.cpp + clusterfile_benchmark.cpp + DataSetAggregation_benchmark.cpp + rawfile_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..5e1e64f1 --- /dev/null +++ b/benchmarks/DataSetAggregation_benchmark.cpp @@ -0,0 +1,34 @@ +#include + +#include "aare/DataSetAggregation.hpp" +#include + +static void DatasetAggregation_MeanOverDataset(benchmark::State &st) { + const std::filesystem::path file_path = + "/mnt/sls_det_storage/jungfrau_calib/data/Module_749_Calib/" + "BP_M749_2026-05-19_HGOG1G2_000000.dat"; + + for (auto _ : st) { + aare::NDArray res = + aare::block_mean(file_path, 220, 100); + + benchmark::DoNotOptimize(res); + } +} + +static void DatasetAggregation_MeanCurrentSource(benchmark::State &st) { + const std::filesystem::path file_path = + "/mnt/sls_det_storage/jungfrau_calib/data/Module_749_Calib/" + "CS_M749_2026-05-19_HGOG1G2_000000.dat"; + + for (auto _ : st) { + aare::NDArray res = aare::mean_current_source( + file_path, 10, 97, 12, 8, + 10 * 3 * 64); // 10 frames * 3 samples * 64 columns + + benchmark::DoNotOptimize(res); + } +} + +BENCHMARK(DatasetAggregation_MeanOverDataset); +BENCHMARK(DatasetAggregation_MeanCurrentSource); \ No newline at end of file diff --git a/docs/src/DataSetAggregation.rst b/docs/src/DataSetAggregation.rst new file mode 100644 index 00000000..fb4ada4f --- /dev/null +++ b/docs/src/DataSetAggregation.rst @@ -0,0 +1,74 @@ +DataSet Aggregation +=================== + +Operations to read file and directly perform aggregation over the dataset, e.g. mean over all frames per sample. + +Both functions open the file themselves, read it in parallel and return a single 3D array. + +The result has shape ``(rows, cols, num_samples)``, i.e. the sample index is the **last** axis. +``result(r, c, i)`` is the value of pixel ``(r, c)`` for sample ``i``. + +Mean over a dataset +------------------- + +:cpp:func:`aare::block_mean` averages a fixed number of consecutive frames for each sample. +The frames in the file are expected to be grouped by sample: + +.. code-block:: text + + | sample 0 | sample 1 | ... | + | frame 0 ... frame (n - 1) | frame 0 ... frame (n - 1) | ... | + + n = num_frames_per_sample + +* The file must contain exactly ``num_samples * num_frames_per_sample`` frames, otherwise a + ``std::runtime_error`` is thrown. +* The template parameter ``FRAME_TYPE`` must match the pixel type stored in the file + (e.g. ``uint16_t``); it is also the type of the returned array. +* ``num_threads`` must be at least 1, otherwise a ``std::invalid_argument`` is thrown. + +.. code-block:: cpp + + #include "aare/DataSetAggregation.hpp" + + // 10 samples (e.g. exposure times) with 1000 frames each + auto mean = aare::block_mean("path/to/master_0.json", 10, 1000); + // mean.shape() == {rows, cols, 10} + +.. doxygenfunction:: aare::block_mean + +Mean of current source data +--------------------------- + +:cpp:func:`aare::mean_current_source` reads a Jungfrau data file recorded during a current source scan. In such a scan only every 64th +column is illuminated in each frame. Consecutive frames step through the 64 columns of a +subcolumn group, so frame ``k`` (counted from the start of the sample) illuminates column +``k % 64`` in each group of 64 columns: + +.. code-block:: text + + frame: 0 1 2 ... 63 64 65 ... + illuminated col: 0 1 2 ... 63 0 1 ... (+ 64 * s for every group s) + +For every pixel only the frames in which its column is illuminated are used. Each sample therefore +spans ``mean_over_num_frames * 64`` frames, and every pixel is averaged over +``mean_over_num_frames`` values. + +* The modules in the top half of the detector (rows ``>= rows / 2``) are mounted flipped, so for + these rows the column index within a group is mirrored, i.e. frame ``k`` illuminates column + ``63 - (k % 64)``. +* ``file_offset`` skips the given number of frames at the start of the file. The file must contain + exactly ``file_offset + num_samples * mean_over_num_frames * 64`` frames, otherwise a + ``std::runtime_error`` is thrown. +* Frames are read in chunks of 16 frames (~16 MiB for a 512x1024 detector). +* ``num_threads`` must be at least 1, otherwise a ``std::invalid_argument`` is thrown. + +.. code-block:: cpp + + #include "aare/DataSetAggregation.hpp" + + // 5 current source settings, 100 frames per column -> 6400 frames per sample + auto cs = aare::mean_current_source("path/to/data_000000.dat", 5, 100); + // cs.shape() == {rows, cols, 5} + +.. doxygenfunction:: aare::mean_current_source diff --git a/docs/src/index.rst b/docs/src/index.rst index c869d999..caddb522 100644 --- a/docs/src/index.rst +++ b/docs/src/index.rst @@ -32,6 +32,7 @@ AARE python/histogram/index python/pedestal/index pyFit + pyDataSetAggregation @@ -59,6 +60,7 @@ AARE RawSubFile RawMasterFile VarClusterFinder + DataSetAggregation diff --git a/docs/src/pyDataSetAggregation.rst b/docs/src/pyDataSetAggregation.rst new file mode 100644 index 00000000..8b673512 --- /dev/null +++ b/docs/src/pyDataSetAggregation.rst @@ -0,0 +1,74 @@ +DataSet Aggregation +=================== + +Operations to read file and directly perform aggregation over the dataset, e.g. mean over all frames per sample. + +Both functions open the file themselves, read it in parallel and return a single 3D array. + +The result has shape ``(rows, cols, num_samples)``, i.e. the sample index is the **last** axis. +``result(r, c, i)`` is the value of pixel ``(r, c)`` for sample ``i``. + +Mean over a dataset +------------------- + +``aare.block_mean`` averages a fixed number of consecutive frames for each sample. +The frames in the file are expected to be grouped by sample: + +.. note:: + This function is only bound for ``np.uint16``. + +.. code-block:: text + + | sample 0 | sample 1 | ... | + | frame 0 ... frame (n - 1) | frame 0 ... frame (n - 1) | ... | + + n = num_frames_per_sample + +* The file must contain exactly ``num_samples * num_frames_per_sample`` frames, otherwise a + ``RuntimeError`` is thrown. +* ``num_threads`` must be at least 1, otherwise a ``ValueError`` is thrown. + +.. code-block:: python + + from aare import block_mean + + # 10 samples (e.g. exposure times) with 1000 frames each + mean = block_mean("path/to/master_0.json", 10, 1000) + # mean.shape() == {rows, cols, 10} + +.. py:currentmodule:: aare + +.. autofunction:: block_mean + +``aare.mean_current_source`` reads a Jungfrau data file recorded during a current source scan. In such a scan only every 64th +column is illuminated in each frame. Consecutive frames step through the 64 columns of a +subcolumn group, so frame ``k`` (counted from the start of the sample) illuminates column +``k % 64`` in each group of 64 columns: + +.. code-block:: text + + frame: 0 1 2 ... 63 64 65 ... + illuminated col: 0 1 2 ... 63 0 1 ... (+ 64 * s for every group s) + +For every pixel only the frames in which its column is illuminated are used. Each sample therefore +spans ``mean_over_num_frames * 64`` frames, and every pixel is averaged over +``mean_over_num_frames`` values. + +* The modules in the top half of the detector (rows ``>= rows / 2``) are mounted flipped, so for + these rows the column index within a group is mirrored, i.e. frame ``k`` illuminates column + ``63 - (k % 64)``. +* ``file_offset`` skips the given number of frames at the start of the file. The file must contain + exactly ``file_offset + num_samples * mean_over_num_frames * 64`` frames, otherwise a + ``RuntimeError`` is thrown. +* Frames are read in chunks of 16 frames (~16 MiB for a 512x1024 detector). +* ``num_threads`` must be at least 1, otherwise a ``ValueError`` is thrown. + +.. code-block:: python + + from aare import mean_current_source + + # 5 current source settings, 100 frames per column -> 6400 frames per sample + cs = mean_current_source("path/to/data_000000.dat", 5, 100) + # cs.shape() == {rows, cols, 5} + +.. autofunction:: mean_current_source \ No newline at end of file diff --git a/include/aare/DataSetAggregation.hpp b/include/aare/DataSetAggregation.hpp new file mode 100644 index 00000000..53d30af9 --- /dev/null +++ b/include/aare/DataSetAggregation.hpp @@ -0,0 +1,193 @@ +#pragma once +#include "aare/File.hpp" +#include "aare/MultiThreadedFileReader.hpp" +#include "aare/utils/RingBufferPool.hpp" +#include "aare/utils/math_helpers.hpp" +#include +#include +#include +#include +#include + +namespace aare { + +/** + * @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_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 +NDArray 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; + size_t total_num_frames = 0; + + { + File meta_file(path); + rows = meta_file.rows(); + cols = meta_file.cols(); + total_num_frames = meta_file.total_frames(); + } + + NDArray mean_per_sample({static_cast(rows), + static_cast(cols), + static_cast(num_samples)}); + + 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"); + + if (total_num_frames != num_samples * mean_over_num_frames) { + throw std::runtime_error( + fmt::format("Frames mismatch: Expected {} frames got {}", + num_samples * mean_over_num_frames, total_num_frames)); + } + + const double inv_n = 1.0 / static_cast(mean_over_num_frames); + + constexpr size_t num_buffers = + 4; // TODO: random for now reading much slower - small buffer is enough + + RingBufferPool> buffers( + num_buffers, num_processing_threads, + [&mean_over_num_frames, &rows, &cols] { + return NDArray(std::array{ + static_cast(mean_over_num_frames), + static_cast(rows), static_cast(cols)}); + }); + + auto reader = [&]() { + try { + // one wave of the reader covers exactly one sample + experimental::MultiThreadedFileReader file_reader( + path, num_reader_threads, + ceil_div(mean_over_num_frames, num_reader_threads)); + + for (size_t i = 0; i < num_samples; ++i) { + NDArray *buffer = buffers.acquire_write(i); + if (!buffer) + throw std::runtime_error( + "Failed to acquire buffer for writing"); + + file_reader.read_into( + reinterpret_cast(buffer->data()), + mean_over_num_frames); + + buffers.commit_write(i); + } + } catch (...) { + buffers.abort(); // wake up the other threads so they can exit + throw; + } + }; + + auto worker = [&](size_t row_begin, size_t row_end) { + try { + const size_t shard_size = (row_end - row_begin) * cols; + // need to be double to avoid overflow for uint16_t and uint32_t + std::vector sum(shard_size); + + for (size_t i = 0; i < num_samples; ++i) { + const NDArray *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 = 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) { + sum[k] += static_cast(frame[k]); + } + } + + // buffer slot is no longer needed, write output after + // release + buffers.release_read(i); + + 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[local_row * cols + c] * inv_n; + } + } + } + } catch (...) { + buffers.abort(); // wake up the other threads so they can exit + throw; + } + }; + + std::vector> futures; + futures.reserve(num_processing_threads + 1); + + futures.push_back(std::async(std::launch::async, reader)); + + 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)); + } + + for (auto &f : futures) { + try { + f.get(); + } catch (const std::exception &e) { + throw std::runtime_error(std::string("Exception in thread: ") + + e.what()); + } + } + + return mean_per_sample; +} + +/** + * @brief Compute the mean current source data from a Jungfrau detector file + * Spawns num_processing_threads + num_reader_threads + 1 threads in total. + * @param path The path to the Jungfrau detector file. + * @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_processing_threads The number of threads to use for parallel + computation. (default 12) + * @param num_reader_threads The number of threads to use for reading data. + (default 8) + * @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) + + */ +NDArray mean_current_source(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 file_offset = 0); + +} // namespace aare diff --git a/include/aare/Fit.hpp b/include/aare/Fit.hpp index cc7edce1..cd9c44e6 100644 --- a/include/aare/Fit.hpp +++ b/include/aare/Fit.hpp @@ -4,6 +4,8 @@ #include "aare/FitModel.hpp" #include "aare/NDArray.hpp" +#include + namespace aare { // --------------------------------------------------------------------------- @@ -62,11 +64,15 @@ NDArray fit_pixel(const FitModel &model, NDView x, * @param chi2_out Output chi-squared / objective values, shape `(rows, * cols)`. * @param n_threads Number of threads used to split rows. + * @param fit_range Optional view of shape `(rows, cols, 2)` with the start + * and end indices of the scan points to fit for each pixel. If not provided, + * the full range is used. */ template void fit_3d(const FitModel &model, NDView x, NDView y, NDView y_err, NDView par_out, NDView err_out, - NDView chi2_out, int n_threads); + NDView chi2_out, int n_threads, + std::optional> fit_range = std::nullopt); } // namespace aare diff --git a/include/aare/Models.hpp b/include/aare/Models.hpp index da908f14..34b3d8d2 100644 --- a/include/aare/Models.hpp +++ b/include/aare/Models.hpp @@ -880,8 +880,17 @@ struct GaussianChargeSharing { return par[3] > 0.0; } - static std::array estimate_par(NDView x, - NDView y) { + /** + * @brief Data-driven initial parameter estimates. + * @param x Independent variable values + * @param y Dependent variable values + * @param elastic_scattering If true, take into account elastic scattering + * effects + * @return Initial parameter estimates + */ + static std::array + estimate_par(NDView x, NDView y, + const bool elastic_scattering = true) { const ssize_t n = y.size(); const auto max_it = std::max_element(y.begin(), y.end()); @@ -889,7 +898,9 @@ struct GaussianChargeSharing { const double x_range = std::max(x[n - 1] - x[0], 1e-9); - const ssize_t tail = std::min(std::max(n / 10, 2), n); + const ssize_t tail = std::min( + std::max(n / 10, 2), + n); // TODO: why hardcoded to 10 % - doesnt it depend on x range?? double left_mean = 0.0; double right_mean = 0.0; @@ -898,18 +909,22 @@ struct GaussianChargeSharing { left_mean += y[i]; left_mean /= tail; - for (ssize_t i = n - tail; i < n; ++i) - right_mean += y[i]; - right_mean /= tail; + if (elastic_scattering) { + for (ssize_t i = n - tail; i < n; ++i) + right_mean += y[i]; + right_mean /= tail; + } const double p0 = right_mean; const double p1 = 0.0; - const double mu = x[i_max]; - const double N = std::max(*max_it - right_mean, 1e-9); + const double mu = x[i_max]; + const double N = + std::max(*max_it - right_mean, 1e-9); // amplitude K_\alpha // Left plateau excess is roughly N*C. - const double C = (left_mean - right_mean) / N; + const double C = + (left_mean - right_mean) / N; // charge-sharing amplitude ratio double sigma = 0.1 * x_range; const double half = right_mean + 0.5 * ((*max_it) - right_mean); @@ -1206,9 +1221,16 @@ struct GaussianChargeSharingKb { return par[3] > 0.0; } - static std::array estimate_par(NDView x, - NDView y) { - const auto base = GaussianChargeSharing::estimate_par(x, y); + /** + * @brief Data-driven initial parameter estimates. + * @param elastic_scattering If true, take into account elastic scattering + * effects + */ + static std::array + estimate_par(NDView x, NDView y, + const bool elastic_scattering = true) { + const auto base = + GaussianChargeSharing::estimate_par(x, y, elastic_scattering); const double p0 = base[0]; const double p1 = base[1]; diff --git a/include/aare/MultiThreadedFileReader.hpp b/include/aare/MultiThreadedFileReader.hpp index d7a930b8..b4542bdc 100644 --- a/include/aare/MultiThreadedFileReader.hpp +++ b/include/aare/MultiThreadedFileReader.hpp @@ -40,12 +40,17 @@ class MultiThreadedFileReader { /** * @brief Read one chunk per active worker into a caller-owned buffer. * + * @param destination Pointer to the buffer where the data will be written. + * @param frames_to_read Optional number of frames to read. If not provided, + * the reader will read the next available frames. + * * The buffer must hold at least next_read_bytes() bytes. The reader's * position advances by the returned number of frames. At the end of the * configured range this function returns zero and does not access the * destination. */ - size_t read_into(std::byte *destination); + size_t read_into(std::byte *destination, + std::optional frames_to_read = std::nullopt); /** @brief Read the next wave of chunks into an owned byte buffer. */ std::vector read(); diff --git a/include/aare/defs.hpp b/include/aare/defs.hpp index 43cae3cb..9c94e5f6 100644 --- a/include/aare/defs.hpp +++ b/include/aare/defs.hpp @@ -173,6 +173,11 @@ struct Moench05 { constexpr static std::array adcNumbers = {5, 9, 1}; }; +struct Jungfrau { + constexpr static size_t nRows = 512; + constexpr static size_t nCols = 1024; +}; + enum ReadoutMode : uint8_t { ANALOG_ONLY = 0, DIGITAL_ONLY = 1, diff --git a/include/aare/hist/PedestalTrackingPixelHistogram.hpp b/include/aare/hist/PedestalTrackingPixelHistogram.hpp index 2025d053..1220498b 100644 --- a/include/aare/hist/PedestalTrackingPixelHistogram.hpp +++ b/include/aare/hist/PedestalTrackingPixelHistogram.hpp @@ -15,6 +15,7 @@ #include #include #include +#include #include #include @@ -49,6 +50,7 @@ class PedestalTrackingPixelHistogram { std::vector> partial_pedestals_; std::vector> partial_std_; // cached for pedestal // tracking + std::vector> partial_masks_{}; // Thread pool members std::vector workers_; @@ -101,16 +103,16 @@ class PedestalTrackingPixelHistogram { void fill_with_threshold_batch_(std::vector> &batch); public: - PedestalTrackingPixelHistogram(int rows, int cols, int n_bins, - AxisType xmin, AxisType xmax, - int n_threads = 1, - std::size_t max_pending = 16, - AxisType n_sigma = 1.0); + PedestalTrackingPixelHistogram( + int rows, int cols, int n_bins, AxisType xmin, AxisType xmax, + int n_threads = 1, std::size_t max_pending = 16, AxisType n_sigma = 1.0, + std::optional> mask = std::nullopt); ~PedestalTrackingPixelHistogram(); void push_pedestal_no_update(const NDView &frame); void update_mean(); NDArray pedestal_mean() const; + NDArray pedestal_std() const; void fill_async(NDArray &&image); diff --git a/include/aare/utils/RingBufferPool.hpp b/include/aare/utils/RingBufferPool.hpp new file mode 100644 index 00000000..b05009b8 --- /dev/null +++ b/include/aare/utils/RingBufferPool.hpp @@ -0,0 +1,139 @@ +#include +#include +#include +#include +#include +#include +#include + +namespace aare { +/** + * @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 class RingBufferPool { + 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 + RingBufferPool(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( + "RingBufferPool 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 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 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 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 lock(m_mtx); + if (m_item_in_slot[slot] != i) + throw std::logic_error( + "release_read called for item not in slot"); + 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 lock(m_mtx); + m_abort = true; + } + m_cv_loaded.notify_all(); + m_cv_free.notify_all(); + } + + private: + size_t m_num_consumers; + std::vector m_buffers; + + static constexpr size_t no_item = std::numeric_limits::max(); + + // per slot: + /// @brief Index of the item currently committed to the slot. + std::vector m_item_in_slot; // store the item - boolean flag need to + // set back to false -> + std::vector 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}; +}; + +} // namespace aare \ No newline at end of file diff --git a/python/aare/__init__.py b/python/aare/__init__.py index 6394489c..f1c27352 100644 --- a/python/aare/__init__.py +++ b/python/aare/__init__.py @@ -73,3 +73,5 @@ from ._aare import ( PixelHistogram_u32, PixelHistogram_u64, ) + +from ._aare import block_mean, mean_current_source diff --git a/python/benchmarks/mean_over_dataset.py b/python/benchmarks/mean_over_dataset.py new file mode 100644 index 00000000..7a600191 --- /dev/null +++ b/python/benchmarks/mean_over_dataset.py @@ -0,0 +1,50 @@ +from pathlib import Path + +from aare import JungfrauDataFile + +import timeit + +import numpy as np + +def read_backplane_pulsing_signals(backplane_pulsing_data : Path, num_signals : int = 220, num_acquisitions_per_signal : int = 10) -> np.ndarray: + """ + Read the backplane pulsing signals from the raw data file and average over the number of acquisitions. + + Params: + backplane_pulsing_data : Path + The path to the raw data file containing the backplane pulsing signals. + num_signals : int, optional + The number of backplane pulsing signals to read. Default is 220. + num_acquisitions_per_signal : int, optional + The number of acquisitions per signal. Default is 10. + """ + + backplane_pulsing_file = JungfrauDataFile(backplane_pulsing_data) #MultiThreadedFileReader(backplane_pulsing_data, ) # + + nrows, ncols = backplane_pulsing_file.rows, backplane_pulsing_file.cols + + backplane_pulsing_signals = np.empty(shape=(nrows, ncols, num_signals), dtype=np.uint16) # TODO should we use float? - copy in fit - maybe better for mean - not aligned with detector + # parallelizing over signals is harder - not sure if file_reading gets faster - cant use parallel file reading class either + for signal_idx in range(num_signals): + _ , ADU_values = backplane_pulsing_file.read_n(num_acquisitions_per_signal) # TODO: use parallel file reader + # TODO doesnt fit into L3 cache - and update mean on the go in c++ + + # maybe a bit unorthodox but could use seperate PedestalTrackingHistogram and process_pedestal_file for each signal and parallel file reading - also copy not neccessary + backplane_pulsing_signals[:, :, signal_idx] = np.mean(ADU_values, axis=0) # mean over acquisitions -> bad striding + + backplane_pulsing_signals = backplane_pulsing_signals.transpose(1, 2, 0).copy() # transpose to (rows, cols, signals) and copy to avoid striding issues + + return backplane_pulsing_signals + +num_calls = 10 + +my_file = Path("/home/mazzol_a/Documents/temp_jungfrau/" + "BP_M749_2026-05-19_HGOG1G2_000000.dat") + +time = timeit.timeit( + lambda: read_backplane_pulsing_signals(my_file, num_signals=220, num_acquisitions_per_signal=10), + number=num_calls +) + + +print(f"Per call: {time / num_calls:.6f} s") \ No newline at end of file diff --git a/python/benchmarks/read_current_source.py b/python/benchmarks/read_current_source.py new file mode 100644 index 00000000..613c02c5 --- /dev/null +++ b/python/benchmarks/read_current_source.py @@ -0,0 +1,62 @@ +from pathlib import Path +from aare import JungfrauDataFile +import timeit +import numpy as np + +def read_current_source_data(current_source_data : Path, num_samples, num_acq_per_exposure : int = 10) -> np.ndarray: + """ + Read the current source data from the raw data file and average over the number of acquisitions per exposure time. + + Parameters + ---------- + current_source_data : Path + The path to the raw data file containing the current source data. + exposure_times : np.ndarray + The exposure times to read. + num_acq_per_exposure : int, optional + The number of acquisitions per exposure time. Default is 10. + output_file : Path, optional + The path to the file where the averaged current source data will be saved. If None, the data is not saved. Default is None. + Returns + ------- + np.ndarray + A 3D array containing the averaged current source data for each exposure time. The shape of the array is (rows, cols, num_exposure_times) + """ + + num_exposure_times = num_samples + columns_per_subcolumn : int = 64 # number of columns per subcolumn - 64 for Jungfrau 1M - Jungfrau has 4 subcolumns per module a 64 columns + + cs_file = JungfrauDataFile(current_source_data) + + if ((num_exposure_times + 3) * num_acq_per_exposure * columns_per_subcolumn != cs_file.total_frames): + raise ValueError(f"The number of frames in the current source data file does not match the expected number of frames. Expected: {(num_exposure_times + 3) * num_acq_per_exposure * columns_per_subcolumn}, got: {cs_file.total_frames}") + + mean_cs = np.zeros((cs_file.rows, cs_file.cols, num_exposure_times), dtype=np.float64) # TODO: use mean and np.uint16 + + cs_file.seek(3*num_acq_per_exposure*columns_per_subcolumn) # skip first 3 frames used to check gain switching + + for i in range(num_exposure_times): + for _ in range(num_acq_per_exposure): + for k in range(columns_per_subcolumn): + _, frame = cs_file.read_frame() + mean_cs[:256, k:-1:columns_per_subcolumn, i] += frame[:256, k:-1:columns_per_subcolumn] + # flipped for top modules + flipped_k = columns_per_subcolumn - 1 - k + mean_cs[256:, flipped_k:-1:columns_per_subcolumn, i] += frame[256:, flipped_k:-1:columns_per_subcolumn] + + mean_cs[:, :, i] /= num_acq_per_exposure + + return mean_cs.astype(np.uint16).copy() + +num_calls = 10 + +my_file = Path("/home/mazzol_a/Documents/temp_jungfrau/" + "CS_M749_2026-05-19_HGOG1G2_000000.dat") + +time = timeit.timeit( + lambda: read_current_source_data(my_file, 97, num_acq_per_exposure=10), + number=num_calls +) + + +print(f"Per call: {time / num_calls:.6f} s") \ 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..a12f2fb4 --- /dev/null +++ b/python/src/bind_DataSetAggregation.hpp @@ -0,0 +1,78 @@ +#include "aare/DataSetAggregation.hpp" + +#include + +#include +#include + +namespace py = pybind11; + +using namespace aare; + +template +void bind_DataSetAggregation(pybind11::module_ &m) { + m.def( + "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, + const size_t num_reader_threads) { + auto result = new NDArray(block_mean( + path, num_samples, mean_over_num_frames, num_processing_threads, + num_reader_threads)); + return return_image_data(result); + }, + 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_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). + )pbdoc"); +} + +void bind_read_current_source(pybind11::module_ &m) { + m.def( + "mean_current_source", + [](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, + const size_t file_offset) { + auto result = new NDArray(mean_current_source( + path, num_samples, mean_over_num_frames, num_processing_threads, + num_reader_threads, file_offset)); + return return_image_data(result); + }, + 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, py::arg("file_offset") = 0, + R"pbdoc( + Compute the mean over several frames per sample stored in a file for each current source. + 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 sources/samples in the dataset. + mean_over_num_frames (int): The number of frames per sample to take mean over. + num_processing_threads (int, optional): The number of threads to use for parallel computation. One thread reads, the others each process a shard of rows. Defaults to 12. + num_reader_threads (int, optional): The number of file workers the reader thread uses to load the frames. Defaults to 8. + file_offset (int, optional): The offset in the file to start reading from. Defaults to 0. + + Returns: + -------- + np.ndarray: A numpy array containing the mean frame stored as np.float64 for each current source with shape (rows, cols, num_sources). + )pbdoc"); +} \ No newline at end of file diff --git a/python/src/bind_Defs.hpp b/python/src/bind_Defs.hpp index 521d5529..489ca052 100644 --- a/python/src/bind_Defs.hpp +++ b/python/src/bind_Defs.hpp @@ -31,6 +31,9 @@ void define_defs_bindings(py::module &m) { moench05.attr("nCols") = Moench05::nCols; moench05.attr("adcNumbers") = Moench05::adcNumbers; + auto jungfrau = py::class_(m, "Jungfrau"); + jungfrau.attr("nRows") = Jungfrau::nRows; + jungfrau.attr("nCols") = Jungfrau::nCols; py::class_(m, "ROI") .def(py::init<>()) .def(py::init(), py::arg("xmin"), diff --git a/python/src/bind_PedestalTrackingPixelHistogram.hpp b/python/src/bind_PedestalTrackingPixelHistogram.hpp index 514ae263..1d650b26 100644 --- a/python/src/bind_PedestalTrackingPixelHistogram.hpp +++ b/python/src/bind_PedestalTrackingPixelHistogram.hpp @@ -16,9 +16,22 @@ void define_pedestal_tracking_pixel_histogram_bindings(py::module &m) { m, "PedestalTrackingPixelHistogram", "A pixel-wise histogram of frame - pedestal residuals, with a " "per-pixel running pedestal estimate sharded across worker threads") - .def( - py::init(), - R"( + .def(py::init( + [](int rows, int cols, int n_bins, double xmin, double xmax, + int n_threads, std::size_t max_pending, double n_sigma, + std::optional> mask) { + if (mask.has_value()) { + auto view = make_view_2d(mask.value()); + return new PedestalTrackingPixelHistogram( + rows, cols, n_bins, xmin, xmax, n_threads, + max_pending, n_sigma, view); + } else { + return new PedestalTrackingPixelHistogram( + rows, cols, n_bins, xmin, xmax, n_threads, + max_pending, n_sigma); + } + }), + R"( Initialize a PedestalTrackingPixelHistogram. Args: @@ -43,10 +56,16 @@ void define_pedestal_tracking_pixel_histogram_bindings(py::module &m) { ``0.0`` to disable the pedestal update and get histogram-only async behaviour (default: 1.0). Also exposed live via the ``n_sigma`` property. + mask: Optional 2D boolean array (shape: rows x cols) that + indicates bad pixels. True values indicate bad pixels + that will be skipped during pedestal tracking and + histogramming. If not provided, all pixels are treated + as good. )", - py::kw_only(), py::arg("rows"), py::arg("cols"), py::arg("n_bins"), - py::arg("xmin"), py::arg("xmax"), py::arg("n_threads") = 1, - py::arg("max_pending") = std::size_t{16}, py::arg("n_sigma") = 1.0) + py::kw_only(), py::arg("rows"), py::arg("cols"), py::arg("n_bins"), + py::arg("xmin"), py::arg("xmax"), py::arg("n_threads") = 1, + py::arg("max_pending") = std::size_t{16}, py::arg("n_sigma") = 1.0, + py::arg("mask") = std::nullopt) .def( "push_pedestal_no_update", @@ -101,6 +120,30 @@ void define_pedestal_tracking_pixel_histogram_bindings(py::module &m) { containing the current cached pedestal mean. )") + .def( + "pedestal_std", + [](const PedestalTrackingPixelHistogram &self) { + // pedestal_std() flushes + locks + memcpys; do all of + // that without the GIL, only reacquire to wrap into a + // numpy array. + NDArray *ptr = + nullptr; + { + py::gil_scoped_release release; + ptr = new NDArray(self.pedestal_std()); + } + return return_image_data(ptr); + }, + R"( + Snapshot the per-pixel pedestal std stitched together + from all shards. + + Returns: + A 2D numpy array (rows x cols, dtype: float64) + containing the current cached pedestal std. + )") + .def( "fill_async", [](PedestalTrackingPixelHistogram &self, diff --git a/python/src/fit.hpp b/python/src/fit.hpp index 617cd6ea..4d6e3835 100644 --- a/python/src/fit.hpp +++ b/python/src/fit.hpp @@ -19,17 +19,20 @@ py::object fit_dispatch(const aare::FitModel &model, py::array_t x, py::array_t y, - py::object y_err_obj, int n_threads); + py::object y_err_obj, int n_threads, + std::optional> fit_range = std::nullopt); template void bind_fit_model(py::module &m, const char *name) { using FM = aare::FitModel; - py::class_(m, name) - .def(py::init(), - py::arg("strategy") = 0, py::arg("max_calls") = 100, - py::arg("tolerance") = 0.5, py::arg("compute_errors") = false, - py::arg("minimizer") = aare::Minimizer::Migrad, - R"doc( + + auto cls = py::class_(m, name); + + cls.def(py::init(), + py::arg("strategy") = 0, py::arg("max_calls") = 100, + py::arg("tolerance") = 0.5, py::arg("compute_errors") = false, + py::arg("minimizer") = aare::Minimizer::Migrad, + R"doc( Fit configuration for this model. Parameters @@ -117,8 +120,11 @@ template void bind_fit_model(py::module &m, const char *name) { [](const FM &self, py::array_t x, py::array_t y, - py::object y_err_obj, int n_threads) -> py::object { - return fit_dispatch(self, x, y, y_err_obj, n_threads); + py::object y_err_obj, int n_threads, + std::optional> fit_range = + std::nullopt) -> py::object { + return fit_dispatch(self, x, y, y_err_obj, n_threads, + fit_range); }, R"doc( Fit this model to 1D or 3D data using Minuit2. @@ -138,9 +144,50 @@ template void bind_fit_model(py::module &m, const char *name) { Per-point uncertainties. None for unweighted fit. n_threads : int Number of threads for 3D parallel loop. + fit_range : array_like, shape (rows, cols, 2), optional + Start and end indices of the scan points to fit for each pixel. If not provided, the full range is used. )doc", py::arg("x"), py::arg("y"), py::arg("y_err") = py::none(), - py::arg("n_threads") = 4); + py::arg("n_threads") = 4, py::arg("fit_range") = py::none()); + + if constexpr (std::is_same_v or + std::is_same_v) { + cls.def( + "estimate_par", + [](const FM & /*self*/, + py::array_t x, + py::array_t y, + const bool elastic_scattering) { + auto x_view = make_view_1d(x); + auto y_view = make_view_1d(y); + + return Model::estimate_par(x_view, y_view, elastic_scattering); + }, + py::arg("x"), py::arg("y"), py::arg("elastic_scattering") = true, + R"doc( + Estimate starting parameters from 1D data. + Parameters + ---------- + elastic_scattering : bool + If true, take into account elastic scattering + effects. + )doc"); + } else { + cls.def( + "estimate_par", + [](const FM & /*self*/, + py::array_t x, + py::array_t + y) { + auto x_view = make_view_1d(x); + auto y_view = make_view_1d(y); + + return Model::estimate_par(x_view, y_view); + }, + py::arg("x"), py::arg("y"), R"doc( + Estimate starting parameters from 1D data. + )doc"); + } } template @@ -187,7 +234,8 @@ py::object fit_dispatch(const aare::FitModel &model, py::array_t x, py::array_t y, - py::object y_err_obj, int n_threads) { + py::object y_err_obj, int n_threads, + std::optional> fit_range) { constexpr std::size_t npar = Model::npar; if (y.ndim() == 3) { @@ -198,6 +246,11 @@ fit_dispatch(const aare::FitModel &model, auto x_view = make_view_1d(x); auto y_view = make_view_3d(y); + const auto fit_range_view = + fit_range.has_value() + ? std::optional(make_view_3d(fit_range.value())) + : std::nullopt; + if (!y_err_obj.is_none()) { auto y_err = py::cast< py::array_t>( @@ -207,9 +260,13 @@ fit_dispatch(const aare::FitModel &model, new NDArray({y.shape(0), y.shape(1), npar}, 0.0); auto y_view_err = make_view_3d(y_err); - aare::fit_3d(model, x_view, y_view, y_view_err, - par_out->view(), err_out->view(), - chi2_out->view(), n_threads); + { + py::gil_scoped_release release; // release GIL for parallel loop + aare::fit_3d(model, x_view, y_view, y_view_err, + par_out->view(), err_out->view(), + chi2_out->view(), n_threads, + fit_range_view); + } if (model.compute_errors()) { return py::dict("par"_a = return_image_data(par_out), @@ -231,7 +288,8 @@ fit_dispatch(const aare::FitModel &model, aare::fit_3d(model, x_view, y_view, dummy_err, par_out->view(), err_out->view(), - chi2_out->view(), n_threads); + chi2_out->view(), n_threads, + fit_range_view); return py::dict("par"_a = return_image_data(par_out), "par_err"_a = return_image_data(err_out), @@ -240,9 +298,12 @@ fit_dispatch(const aare::FitModel &model, NDView dummy_err_out{}; - aare::fit_3d(model, x_view, y_view, dummy_err, - par_out->view(), dummy_err_out, - chi2_out->view(), n_threads); + { + py::gil_scoped_release release; // release GIL for parallel loop + aare::fit_3d( + model, x_view, y_view, dummy_err, par_out->view(), + dummy_err_out, chi2_out->view(), n_threads, fit_range_view); + } return py::dict("par"_a = return_image_data(par_out), "chi2"_a = return_image_data(chi2_out)); @@ -253,15 +314,28 @@ fit_dispatch(const aare::FitModel &model, auto x_view = make_view_1d(x); auto y_view = make_view_1d(y); + if (fit_range.has_value()) { + throw std::runtime_error( + "fit_range is only supported for 3D data. Directly pass the " + "clipped data to fit() for 1D data."); + } + if (!y_err_obj.is_none()) { auto y_err = py::cast< py::array_t>( y_err_obj); auto y_view_err = make_view_1d(y_err); - result = aare::fit_pixel(model, x_view, y_view, y_view_err); + { + py::gil_scoped_release release; // release GIL for parallel loop + result = + aare::fit_pixel(model, x_view, y_view, y_view_err); + } } else { - result = aare::fit_pixel(model, x_view, y_view); + { + py::gil_scoped_release release; // release GIL for parallel loop + result = aare::fit_pixel(model, x_view, y_view); + } } return pack_1d_result_dict(result, model.compute_errors()); @@ -276,13 +350,15 @@ py::object dispatch_any_model( py::object model_obj, py::array_t x, py::array_t y, - py::object y_err_obj, int n_threads) { + py::object y_err_obj, int n_threads, + std::optional> fit_range = std::nullopt) { using namespace aare::model; #define AARE_DISPATCH_MODEL(Model) \ if (py::isinstance>(model_obj)) { \ const auto &mdl = model_obj.cast &>(); \ - return fit_dispatch(mdl, x, y, y_err_obj, n_threads); \ + return fit_dispatch(mdl, x, y, y_err_obj, n_threads, \ + fit_range); \ } AARE_DISPATCH_MODEL(Pol1) @@ -371,7 +447,7 @@ void define_fit_bindings(py::module &m) { R"( Fit a model to 1D or 3D data with the minimizer selected by the model's ``minimizer`` property. - + Parameters ---------- model : object @@ -387,7 +463,7 @@ void define_fit_bindings(py::module &m) { Per-point uncertainties. Same shape as y. None → unweighted fit. n_threads : int Number of threads for the 3D parallel loop. - + Returns ------- dict diff --git a/python/src/module.cpp b/python/src/module.cpp index 0df7fe8d..9f14a72c 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" @@ -180,4 +181,8 @@ PYBIND11_MODULE(_aare, m) { define_eta(m, "d"); define_eta(m, "i"); define_eta(m, "i16"); + + bind_DataSetAggregation(m); + + bind_read_current_source(m); } diff --git a/python/tests/conftest.py b/python/tests/conftest.py index cdd14f86..f4c66c57 100644 --- a/python/tests/conftest.py +++ b/python/tests/conftest.py @@ -2,6 +2,7 @@ import os from pathlib import Path import pytest +import numpy as np @@ -33,3 +34,28 @@ def test_data_path(): return Path(env_value) +@pytest.fixture +def create_temporary_jungfrau_files(tmp_path): + """Factory fixture: writes a Jungfrau raw file set into tmp_path and returns the path of the first file.""" + + JungfrauDataHeader = np.dtype([("framenum", np.uint64), ("bunchid", np.uint64)]) + + def _create(num_frames, frame_generator, num_files=1): + master_path = tmp_path / "aare-raw" + master_path.mkdir(exist_ok=True) + + frames_per_file = num_frames // num_files + + for file_index in range(num_files): + start_frame = file_index * frames_per_file + end_frame = num_frames if file_index == num_files - 1 else start_frame + frames_per_file + + with open(master_path / f"JungfrauTest_{file_index:06}.dat", "wb") as f: + for frame in range(start_frame, end_frame): + # header + f.write(np.array([(frame, 0)], dtype=JungfrauDataHeader).tobytes()) + f.write(np.ascontiguousarray(frame_generator(frame), dtype=np.uint16).tobytes()) + + return master_path / "JungfrauTest_000000.dat" + + return _create diff --git a/python/tests/test_DataSetAggregation.py b/python/tests/test_DataSetAggregation.py new file mode 100644 index 00000000..70c716ca --- /dev/null +++ b/python/tests/test_DataSetAggregation.py @@ -0,0 +1,56 @@ +# SPDX-License-Identifier: MPL-2.0 +import numpy as np +import pytest + +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 = 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_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) + + # mean of 0,1,...,num_frames_per_sample-1 + mean_value = (num_frames_per_sample - 1) / 2 + np.testing.assert_allclose(result, mean_value) + + +def test_mean_current_source(create_temporary_jungfrau_files): + """ test mean_current_source """ + + rows, cols = 256, 256 + columns_per_subcolumn = 64 + mean_over_num_frames = 3 + num_samples = 5 + file_offset = 2 * columns_per_subcolumn + frames_per_sample = mean_over_num_frames * columns_per_subcolumn + num_frames = num_samples * frames_per_sample + file_offset + + col_values = np.tile(np.arange(cols, dtype=np.uint16), (rows, 1)) + + def frame_generator(frame): + frame_idx = ((frame - file_offset) // columns_per_subcolumn) % mean_over_num_frames + return col_values + frame_idx + + # spread over several files to cross file boundaries mid sample + file_system = create_temporary_jungfrau_files(num_frames, frame_generator, num_files=3) + + result = mean_current_source(file_system, num_samples = num_samples, mean_over_num_frames = mean_over_num_frames, num_processing_threads = 4, num_reader_threads = 3, file_offset = file_offset) + + assert result.shape == (rows, cols, num_samples) + + # mean of c + 0, c + 1, ..., c + mean_over_num_frames-1 + sum_mean_over_frames = mean_over_num_frames * (mean_over_num_frames - 1) / 2 + expected = (col_values * mean_over_num_frames + sum_mean_over_frames) / mean_over_num_frames + np.testing.assert_allclose(result, np.repeat(expected[:, :, np.newaxis], num_samples, axis=2)) diff --git a/src/DataSetAggregation.cpp b/src/DataSetAggregation.cpp new file mode 100644 index 00000000..470f3e75 --- /dev/null +++ b/src/DataSetAggregation.cpp @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/DataSetAggregation.hpp" +#include "aare/JungfrauDataFile.hpp" +#include "aare/MultiThreadedFileReader.hpp" +#include "aare/utils/math_helpers.hpp" + +#include +#include +#include +#include +#include + +namespace aare { + +// TODO: maybe O_DIRECT rea dis better to avoid the page cache + +NDArray mean_current_source(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, + size_t file_offset) { + + constexpr size_t columns_per_subcolumn = 64; + + size_t num_rows = 0; + size_t num_cols = 0; + size_t total_num_frames = 0; + { + JungfrauDataFile meta_file(path); + num_rows = meta_file.rows(); + num_cols = meta_file.cols(); + total_num_frames = meta_file.total_frames(); + } + + const size_t half_rows = num_rows / 2; + const size_t num_subcolumns = num_cols / columns_per_subcolumn; + const size_t frames_per_sample = + mean_over_num_frames * columns_per_subcolumn; + + if (total_num_frames != frames_per_sample * num_samples + file_offset) { + throw std::runtime_error(fmt::format( + "Frames mismatch: Expected {} frames got {}", + frames_per_sample * num_samples + file_offset, total_num_frames)); + } + 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"); + + const double inv_mean_over_num_frames = + 1.0 / static_cast(mean_over_num_frames); + + NDArray cs_data({static_cast(num_rows), + static_cast(num_cols), + static_cast(num_samples)}, + 0); + + constexpr size_t num_buffers = 4; // TODO: random for now reading much + // slower - small buffer is enough + + RingBufferPool> buffers( + num_buffers, num_processing_threads, + [&num_rows, &num_cols, &frames_per_sample] { + return NDArray( + std::array{static_cast(frames_per_sample), + static_cast(num_rows), + static_cast(num_cols)}); + }); + + auto reader = [&]() { + try { + // one wave of the reader covers exactly one batch + experimental::MultiThreadedFileReader file_reader( + path, static_cast(num_reader_threads), + ceil_div(frames_per_sample, + static_cast(num_reader_threads))); + + file_reader.seek(file_offset); + + for (size_t b = 0; b < num_samples; ++b) { + NDArray *buffer = buffers.acquire_write(b); + if (!buffer) + throw std::runtime_error( + "Failed to acquire buffer for writing"); + + file_reader.read_into( + reinterpret_cast(buffer->data()), + frames_per_sample); + + buffers.commit_write(b); + } + } catch (...) { + buffers.abort(); // wake up the other threads so they can exit + throw; + } + }; + + auto worker = [&](const size_t row_begin, const size_t row_end) { + try { + const size_t shard_size = (row_end - row_begin) * num_cols; + // uint64_t to avoid overflow for uint16_t + std::vector sum(shard_size, 0); + + for (size_t sample = 0; sample < num_samples; ++sample) { + const NDArray *buffer = + buffers.acquire_read(sample); + if (!buffer) + throw std::runtime_error( + "Failed to acquire buffer for reading"); + + for (size_t f = 0; f < frames_per_sample; ++f) { + // each frame illuminates every 64th column + const size_t illum_col_idx = f % columns_per_subcolumn; + + const uint16_t *data = + buffer->data() + f * num_rows * num_cols; + + for (size_t r = row_begin; r < row_end; ++r) { + // top half modules are flipped + const size_t col_in_subcolumn = + r < half_rows + ? illum_col_idx + : columns_per_subcolumn - 1 - illum_col_idx; + const size_t column_offset = + r * num_cols + col_in_subcolumn; + const size_t local_offset = + column_offset - row_begin * num_cols; + for (size_t s = 0; s < num_subcolumns; ++s) { + const size_t step = s * columns_per_subcolumn; + sum[local_offset + step] += + data[column_offset + step]; + } + } + } + + // buffer slot is no longer needed, write output after release + buffers.release_read(sample); + + for (size_t r = row_begin; r < row_end; ++r) { + const size_t local_row_offset = (r - row_begin) * num_cols; + for (size_t c = 0; c < num_cols; ++c) { + cs_data(r, c, sample) = + static_cast(sum[local_row_offset + c]) * + inv_mean_over_num_frames; + } + } + std::fill(sum.begin(), sum.end(), 0); + } + } catch (...) { + buffers.abort(); // wake up the other threads so they can exit + throw; + } + }; + + std::vector> futures; + futures.reserve(num_processing_threads + 1); + + // reader thread + futures.push_back(std::async(std::launch::async, reader)); + + const size_t rows_per_worker = num_rows / num_processing_threads; + for (size_t w = 0; w < num_processing_threads; ++w) { + const size_t row_end = (w == num_processing_threads - 1) + ? num_rows + : (w + 1) * rows_per_worker; + futures.push_back(std::async(std::launch::async, worker, + w * rows_per_worker, row_end)); + } + + for (auto &f : futures) { + try { + f.get(); + } catch (const std::exception &e) { + throw std::runtime_error(std::string("Exception in thread: ") + + e.what()); + } + } + + return cs_data; +} + +} // namespace aare diff --git a/src/DataSetAggregation.test.cpp b/src/DataSetAggregation.test.cpp new file mode 100644 index 00000000..d33b33ba --- /dev/null +++ b/src/DataSetAggregation.test.cpp @@ -0,0 +1,113 @@ +#include "aare/DataSetAggregation.hpp" + +#include "jungfrau_file_helpers.hpp" + +#include +#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 = 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) { + 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 = + block_mean(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); + REQUIRE(mean_result.shape(1) == Jungfrau::nCols); + REQUIRE(mean_result.shape(2) == num_samples); + + double mean_value = + (num_frames_per_sample - 1) / + 2.0; // ((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) == + Catch::Approx(mean_value)); + } + } + } +} + +TEST_CASE("mean_current_source", "[DataSetAggregation]") { + + constexpr size_t rows = 256; + constexpr size_t cols = 256; + constexpr size_t columns_per_subcolumn = 64; + constexpr size_t mean_over_num_frames = 3; + constexpr size_t num_samples = 5; + constexpr size_t file_offset = 2 * columns_per_subcolumn; + constexpr size_t frames_per_sample = + mean_over_num_frames * columns_per_subcolumn; + constexpr size_t num_frames = num_samples * frames_per_sample + file_offset; + + // spread over several files to cross file boundaries mid sample + TemporaryJungfrauFiles temp_files( + num_frames, + [&](size_t frame) { + NDArray data({rows, cols}); + int frame_idx = ((frame - file_offset) / columns_per_subcolumn) % + mean_over_num_frames; + + for (size_t r = 0; r < rows; ++r) + for (size_t c = 0; c < cols; ++c) + data(r, c) = c + frame_idx; + return data; + }, + 3); + + auto result = mean_current_source(temp_files.file_path(), num_samples, + mean_over_num_frames, 4, 3, file_offset); + + REQUIRE(result.shape(0) == rows); + REQUIRE(result.shape(1) == cols); + REQUIRE(result.shape(2) == num_samples); + + size_t sum_mean_over_frames = (mean_over_num_frames) * + (mean_over_num_frames - 1) / + 2; // sum of 0,1,...,mean_over_num_frames-1 + + for (size_t r = 0; r < rows; ++r) { + for (size_t c = 0; c < cols; ++c) { + for (size_t sample = 0; sample < num_samples; ++sample) { + + CHECK( + result(r, c, sample) == + Catch::Approx(static_cast(c * mean_over_num_frames + + sum_mean_over_frames) / + mean_over_num_frames)); + } + } + } +} diff --git a/src/MultiThreadedFileReader.cpp b/src/MultiThreadedFileReader.cpp index 6810e9bf..ace48998 100644 --- a/src/MultiThreadedFileReader.cpp +++ b/src/MultiThreadedFileReader.cpp @@ -85,9 +85,19 @@ void MultiThreadedFileReader::ensure_open() const { } } -size_t MultiThreadedFileReader::read_into(std::byte *destination) { +size_t +MultiThreadedFileReader::read_into(std::byte *destination, + std::optional frames_to_read_) { ensure_open(); - const size_t frames_to_read = next_read_frames(); + const size_t next_frames_to_read = next_read_frames(); + const size_t frames_to_read = frames_to_read_.value_or(next_frames_to_read); + + if (frames_to_read > next_frames_to_read) { + throw std::invalid_argument( + fmt::format("MultiThreadedFileReader cannot read more frames than " + "available: requested {}, available {}", + frames_to_read, next_frames_to_read)); + } if (frames_to_read == 0) { return 0; } diff --git a/src/fit/Fit.cpp b/src/fit/Fit.cpp index 05dfa5d8..4f0ff8f5 100644 --- a/src/fit/Fit.cpp +++ b/src/fit/Fit.cpp @@ -267,11 +267,14 @@ template void fit_3d(const FitModel &model, NDView x, NDView y, NDView y_err, NDView par_out, NDView err_out, - NDView chi2_out, int n_threads) { + NDView chi2_out, int n_threads, + std::optional> fit_range) { + // static so the lambda below can use it as an array size without // capturing it, which MSVC otherwise rejects static constexpr std::size_t npar = Model::npar; - detail::check_fit_3d_shapes(x, y, y_err, par_out, err_out, chi2_out); + detail::check_fit_3d_shapes(x, y, y_err, par_out, err_out, chi2_out, + fit_range); const bool has_errors = (y_err.size() > 0); const bool want_par_errors = (err_out.size() > 0) && model.compute_errors(); @@ -282,14 +285,31 @@ void fit_3d(const FitModel &model, NDView x, std::array err{}; for (ssize_t row = first_row; row < last_row; row++) { for (ssize_t col = 0; col < y.shape(1); col++) { - NDView values(&y(row, col, 0), {y.shape(2)}); + const size_t start_range = + fit_range ? (*fit_range)(row, col, 0) : 0; + const ssize_t num_y_samples = + fit_range ? (*fit_range)(row, col, 1) - start_range + : y.shape(2); + + if (start_range + num_y_samples > + static_cast(y.shape(2))) + throw std::runtime_error(fmt::format( + "fit_3d: fit_range out of bounds for (row={}, col={}, " + "start_range={}, num_y_samples={}, num samples={})", + row, col, start_range, num_y_samples, y.shape(2))); + + NDView values(&y(row, col, start_range), + {num_y_samples}); NDView errors = - has_errors ? NDView(&y_err(row, col, 0), - {y_err.shape(2)}) - : NDView{}; + has_errors + ? NDView(&y_err(row, col, start_range), + {num_y_samples}) + : NDView{}; + + NDView x_clipped(&x(start_range), {num_y_samples}); double chi2 = 0.0; - fitter.fit(model, x, values, errors, par.data(), + fitter.fit(model, x_clipped, values, errors, par.data(), want_par_errors ? err.data() : nullptr, chi2); for (std::size_t k = 0; k < npar; ++k) @@ -319,10 +339,10 @@ void fit_3d(const FitModel &model, NDView x, NDView); \ template NDArray fit_pixel( \ const FitModel &, NDView, NDView); \ - template void fit_3d(const FitModel &, NDView, \ - NDView, NDView, \ - NDView, NDView, \ - NDView, int); + template void fit_3d( \ + const FitModel &, NDView, NDView, \ + NDView, NDView, NDView, \ + NDView, int, std::optional>); AARE_INSTANTIATE_FIT(model::Gaussian) AARE_INSTANTIATE_FIT(model::GaussianErfcPlateau) diff --git a/src/fit/FitHelpers.hpp b/src/fit/FitHelpers.hpp index a82599cf..bc46b588 100644 --- a/src/fit/FitHelpers.hpp +++ b/src/fit/FitHelpers.hpp @@ -49,8 +49,8 @@ inline void check_fit_pixel_shapes(NDView x, NDView y, template void check_fit_3d_shapes(NDView x, NDView y, NDView y_err, NDView par_out, - NDView err_out, - NDView chi2_out) { + NDView err_out, NDView chi2_out, + std::optional> fit_range) { constexpr auto npar = static_cast(Model::npar); if (x.size() != y.shape(2)) @@ -63,6 +63,14 @@ void check_fit_3d_shapes(NDView x, NDView y, if (chi2_out.shape(0) != y.shape(0) || chi2_out.shape(1) != y.shape(1)) throw std::runtime_error("chi2_out must have shape [rows, cols]."); + if (fit_range.has_value()) { + const auto &fr = fit_range.value(); + if (fr.shape(0) != y.shape(0) || fr.shape(1) != y.shape(1) || + fr.shape(2) != 2) + throw std::runtime_error( + "fit_range must have shape [rows, cols, 2]."); + } + const bool err_out_matches = err_out.shape(0) == y.shape(0) && err_out.shape(1) == y.shape(1) && err_out.shape(2) == npar; diff --git a/src/hist/PedestalTrackingPixelHistogram.cpp b/src/hist/PedestalTrackingPixelHistogram.cpp index b97b5ad9..a2d5f649 100644 --- a/src/hist/PedestalTrackingPixelHistogram.cpp +++ b/src/hist/PedestalTrackingPixelHistogram.cpp @@ -20,7 +20,8 @@ namespace aare { PedestalTrackingPixelHistogram::PedestalTrackingPixelHistogram( int rows, int cols, int n_bins, AxisType xmin, AxisType xmax, int n_threads, - std::size_t max_pending, AxisType n_sigma) + std::size_t max_pending, AxisType n_sigma, + std::optional> mask) : rows_(rows), cols_(cols), n_threads_(n_threads), xmin_(xmin), xmax_(xmax), current_work_kind_(WorkKind::FillWithThreshold), current_image_(nullptr), current_images_(nullptr), completed_threads_(0), stop_workers_(false), @@ -62,6 +63,16 @@ PedestalTrackingPixelHistogram::PedestalTrackingPixelHistogram( partial_hists_.reserve(n_threads_); partial_pedestals_.reserve(n_threads_); partial_std_.reserve(n_threads_); + + if (mask.has_value()) { + if (mask->shape(0) != rows_ || mask->shape(1) != cols_) { + throw std::invalid_argument( + "PedestalTrackingPixelHistogram mask shape does not match " + "constructor shape"); + } + partial_masks_.reserve(n_threads_); + } + for (int i = 0; i < n_threads_; ++i) { const auto local_rows = row_count(i); partial_hists_.emplace_back(local_rows, cols, n_bins, xmin_, xmax_); @@ -70,6 +81,13 @@ PedestalTrackingPixelHistogram::PedestalTrackingPixelHistogram( partial_std_.emplace_back(NDArray( {static_cast(local_rows), static_cast(cols)}, 0.0)); + + if (mask.has_value()) { + partial_masks_.emplace_back( + NDView(mask->begin() + row_start(i) * cols_, + {static_cast(local_rows), + static_cast(cols)})); + } } // Spawn worker threads @@ -206,10 +224,14 @@ void PedestalTrackingPixelHistogram::worker_loop(int thread_id) { auto &my_pedestal = partial_pedestals_[thread_id]; auto &my_hist = partial_hists_[thread_id]; + const bool has_mask = !partial_masks_.empty(); + switch (kind) { case WorkKind::PushPedestal: { auto frame = image->sub_view(first_row, first_row + local_rows); - my_pedestal.add_init_frame(frame); + my_pedestal.add_init_frame( + frame); // dont bother adding bad pixels in pedestal - not + // needed for calculation break; } case WorkKind::UpdateMean: { @@ -265,6 +287,12 @@ void PedestalTrackingPixelHistogram::worker_loop(int thread_id) { for (std::size_t local_pixel = tile_begin; local_pixel < tile_end; ++local_pixel, ++input) { const FrameType raw = *input; + + if (has_mask && + partial_masks_[thread_id](local_pixel)) { + continue; // Skip masked pixels entirely + } + const AxisType val = static_cast(raw) - my_pedestal.mean_unchecked( @@ -372,6 +400,37 @@ PedestalTrackingPixelHistogram::pedestal_mean() const { return data; } +NDArray +PedestalTrackingPixelHistogram::pedestal_std() const { + // Drain in-flight async fills and serialise with all other fan-outs + // (Fill / PushPedestal / UpdateMean). m_std is overwritten wholesale + // by Pedestal::update_mean, so without the lock we could read torn + // rows mid-update. + flush(); + std::lock_guard lock(fill_mutex_); + + NDArray data( + {static_cast(rows_), static_cast(cols_)}); + + // Each partial pedestal stores its slice of m_std in C-order + // [local_rows x cols], identical in layout to the corresponding + // [first_row .. first_row + local_rows)[col] slice of `data`, so + // we can copy each shard with a single memcpy. + const size_t row_stride = static_cast(cols_); + for (int t = 0; t < n_threads_; ++t) { + const auto first_row = static_cast(row_start(t)); + const auto local_rows = static_cast(row_count(t)); + if (local_rows == 0) + continue; + + const auto view = partial_std_[t].view(); + std::memcpy(data.data() + first_row * row_stride, view.data(), + local_rows * row_stride * sizeof(AxisType)); + } + + return data; +} + void PedestalTrackingPixelHistogram::fill_with_threshold_batch_( std::vector> &batch) { // Called only by the coordinator thread on images already shape-checked diff --git a/src/utils/RingBufferPool.test.cpp b/src/utils/RingBufferPool.test.cpp new file mode 100644 index 00000000..cdc15975 --- /dev/null +++ b/src/utils/RingBufferPool.test.cpp @@ -0,0 +1,127 @@ +// SPDX-License-Identifier: MPL-2.0 +#include "aare/utils/RingBufferPool.hpp" + +#include + +TEST_CASE("RingBufferPool cant overwrite before all consumers release", + "[RingBufferPool]") { + constexpr size_t pool_size = 8; + constexpr size_t num_consumers = 3; + + // Create a RingBufferPool with integers initialized to 0 + aare::RingBufferPool ring_buffer(pool_size, num_consumers, + []() { return 0; }); + + // Test acquiring and committing writes + for (size_t i = 0; i < pool_size; ++i) { + int *buffer = ring_buffer.acquire_write(i); + REQUIRE(buffer != nullptr); + *buffer = static_cast(i); + ring_buffer.commit_write(i); + } + + // Test acquiring reads + for (size_t i = 0; i < pool_size; ++i) { + const int *buffer = ring_buffer.acquire_read(i); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(i)); + ring_buffer.release_read(i); + } + + const size_t next_buffer = pool_size; // This will wrap around to slot 0 + const size_t slot_to_write = next_buffer % pool_size; + // Producer cannot acquire a write slot until all consumers have released it + std::thread producer_thread([&ring_buffer]() { + int *buffer = ring_buffer.acquire_write(next_buffer); + REQUIRE(buffer != nullptr); + *buffer = static_cast(next_buffer); + ring_buffer.commit_write(next_buffer); + }); + + // Remaining consumers read the items + for (size_t i = 1; i < num_consumers; ++i) { + const int *buffer = ring_buffer.acquire_read(slot_to_write); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(0)); + ring_buffer.release_read(slot_to_write); + } + + producer_thread.join(); + + // written correctly + { + const int *buffer = ring_buffer.acquire_read(next_buffer); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(next_buffer)); + } + for (size_t i = 1; i < pool_size; ++i) { + const int *buffer = ring_buffer.acquire_read(i); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == static_cast(i)); + ring_buffer.release_read(i); + } + + // Test aborting the pool + ring_buffer.abort(); + int *buffer_after_abort = ring_buffer.acquire_write(6); + REQUIRE(buffer_after_abort == nullptr); +} + +TEST_CASE("cant read if not written", "[RingBufferPool]") { + constexpr size_t pool_size = 2; + constexpr size_t num_consumers = 2; + + aare::RingBufferPool ring_buffer(pool_size, num_consumers, + []() { return 0; }); + + const int value_first_slot = 50; + const int value_second_slot = 10; + + { + int *buffer = ring_buffer.acquire_write(0); + *buffer = value_first_slot; + ring_buffer.commit_write(0); + } + + { + const int *buffer = ring_buffer.acquire_read(0); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == value_first_slot); + ring_buffer.release_read(0); + } + bool could_read = false; + + std::thread consumer_thread([&ring_buffer, &could_read]() { + // Try to acquire read for an item that hasn't been written yet + const int *buffer = ring_buffer.acquire_read(1); + could_read = (buffer != nullptr); + REQUIRE(*buffer == value_second_slot); + }); + + { + const int *buffer = ring_buffer.acquire_read(0); + REQUIRE(buffer != nullptr); + REQUIRE(*buffer == value_first_slot); + ring_buffer.release_read(0); + } + + REQUIRE(could_read == false); + + { + int *buffer = ring_buffer.acquire_write(0); + REQUIRE(buffer != nullptr); + *buffer = value_first_slot; + ring_buffer.commit_write(0); + } + REQUIRE(could_read == false); + + { + int *buffer = ring_buffer.acquire_write(1); + REQUIRE(buffer != nullptr); + *buffer = value_second_slot; + ring_buffer.commit_write(1); + } + consumer_thread.join(); + + REQUIRE(could_read == true); +} \ 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