mirror of
https://github.com/slsdetectorgroup/aare.git
synced 2026-12-01 19:08:10 +01:00
Merge remote-tracking branch 'origin/main' into feature/cuda_clusterfinder
This commit is contained in:
commit
198aa63715
110 files changed
+5015
-474
No files matched your search
@@ -17,15 +17,53 @@ jobs:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ubuntu-latest,macos-latest]
|
||||
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-*
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
name: Build and test on Windows
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
pull_request:
|
||||
|
||||
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@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.
|
||||
# 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 -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
|
||||
|
||||
- name: Python unit tests
|
||||
env:
|
||||
PYTHONPATH: ${{ github.workspace }}\build
|
||||
run: python -m pytest python/tests
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
+50
-23
@@ -233,6 +233,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()
|
||||
@@ -279,18 +284,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()
|
||||
# ############################################################################
|
||||
@@ -346,22 +363,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)
|
||||
@@ -399,6 +416,8 @@ 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
|
||||
include/aare/NDArray.hpp
|
||||
@@ -414,7 +433,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)
|
||||
|
||||
if(AARE_CUDA)
|
||||
list(
|
||||
@@ -435,7 +455,9 @@ 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/DataSetAggregation.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Dtype.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/File.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/FilePtr.cpp
|
||||
@@ -480,7 +502,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()
|
||||
@@ -506,6 +528,7 @@ endif()
|
||||
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
|
||||
@@ -515,6 +538,8 @@ 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
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/NDArray.test.cpp
|
||||
@@ -532,6 +557,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
|
||||
@@ -539,6 +565,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()
|
||||
|
||||
+39
@@ -1,5 +1,44 @@
|
||||
# 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``.
|
||||
- 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
|
||||
- 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.
|
||||
- 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
|
||||
the gaps, for the full frame and for each ROI.
|
||||
|
||||
### 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
|
||||
``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:
|
||||
|
||||
@@ -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)
|
||||
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
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
#include "aare/DataSetAggregation.hpp"
|
||||
#include <filesystem>
|
||||
|
||||
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<uint16_t, 3> res =
|
||||
aare::block_mean<uint16_t>(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<uint16_t, 3> 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);
|
||||
@@ -10,6 +10,8 @@
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
using aare::ssize_t;
|
||||
|
||||
struct TestCase {
|
||||
std::string name;
|
||||
double true_A;
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#include <benchmark/benchmark.h>
|
||||
|
||||
using aare::NDArray;
|
||||
using aare::ssize_t;
|
||||
|
||||
constexpr ssize_t size = 1024;
|
||||
class TwoArrays : public benchmark::Fixture {
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/GapPixels.hpp"
|
||||
#include "aare/RawFile.hpp"
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
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<uint16_t> pixels(rows * cols);
|
||||
for (size_t i = 0; i < pixels.size(); ++i) {
|
||||
pixels[i] = static_cast<uint16_t>(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<const char *>(&header), sizeof(header));
|
||||
data.write(
|
||||
reinterpret_cast<const char *>(pixels.data()),
|
||||
static_cast<std::streamsize>(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<aare::GapPixels> gaps) const {
|
||||
aare::RawFile file(master(), "r", gaps);
|
||||
std::vector<std::byte> 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<int64_t>(state.iterations()) *
|
||||
static_cast<int64_t>(frame_count));
|
||||
state.SetBytesProcessed(static_cast<int64_t>(state.iterations()) *
|
||||
static_cast<int64_t>(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
|
||||
@@ -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
|
||||
|
||||
|
||||
+5
-24
@@ -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")
|
||||
@@ -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
|
||||
|
||||
# CUDA execution-space and pointer qualifiers are not C++, so Sphinx's C++
|
||||
# domain cannot parse declarations such as the __global__ kernels in
|
||||
@@ -72,6 +74,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
|
||||
app.add_css_file('extra.css') # relative to _static/; may also be an URL
|
||||
@@ -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<idx>\d+)\.\s+(?P<name>[\w.]+)\((?P<args>.*)\)\s*(?:->\s*(?P<ret>.+?))?\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
|
||||
@@ -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<uint16_t>("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
|
||||
@@ -0,0 +1,122 @@
|
||||
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.
|
||||
``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.
|
||||
|
||||
================ ================ ===========================================
|
||||
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.
|
||||
|
||||
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
|
||||
----------------
|
||||
|
||||
``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<double, 2> image = ...; // 512 x 1024
|
||||
auto gapped = aare::insert_gap_pixels<double>(
|
||||
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
|
||||
@@ -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 <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:
|
||||
|
||||
@@ -32,6 +32,7 @@ AARE
|
||||
python/histogram/index
|
||||
python/pedestal/index
|
||||
pyFit
|
||||
pyDataSetAggregation
|
||||
|
||||
|
||||
|
||||
@@ -44,6 +45,7 @@ AARE
|
||||
NDView
|
||||
Frame
|
||||
File
|
||||
GapPixels
|
||||
MultiThreadedFileReader
|
||||
Dtype
|
||||
Cluster
|
||||
@@ -59,6 +61,7 @@ AARE
|
||||
RawSubFile
|
||||
RawMasterFile
|
||||
VarClusterFinder
|
||||
DataSetAggregation
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -8,6 +8,7 @@ File I/O
|
||||
pyClusterFile
|
||||
pyCtbRawFile
|
||||
pyFile
|
||||
pyGapPixels
|
||||
pyJungfrauDataFile
|
||||
pyRawFile
|
||||
pyRawMasterFile
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
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)
|
||||
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.
|
||||
|
||||
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:
|
||||
|
||||
.. autoclass:: ModuleGaps
|
||||
:members:
|
||||
:undoc-members:
|
||||
|
||||
.. autofunction:: insert_gap_pixels
|
||||
|
||||
.. autofunction:: gapped_shape
|
||||
@@ -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 <pyGapPixels>` 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:
|
||||
|
||||
@@ -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] +
|
||||
|
||||
@@ -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 <algorithm>
|
||||
#include <array>
|
||||
#include <filesystem>
|
||||
#include <future>
|
||||
#include <vector>
|
||||
|
||||
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 <typename FRAME_TYPE>
|
||||
NDArray<double, 3> block_mean(const std::filesystem::path &path,
|
||||
const size_t num_samples,
|
||||
const size_t mean_over_num_frames,
|
||||
const 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<double, 3> mean_per_sample({static_cast<ssize_t>(rows),
|
||||
static_cast<ssize_t>(cols),
|
||||
static_cast<ssize_t>(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<double>(mean_over_num_frames);
|
||||
|
||||
constexpr size_t num_buffers =
|
||||
4; // TODO: random for now reading much slower - small buffer is enough
|
||||
|
||||
RingBufferPool<NDArray<FRAME_TYPE, 3>> buffers(
|
||||
num_buffers, num_processing_threads,
|
||||
[&mean_over_num_frames, &rows, &cols] {
|
||||
return NDArray<FRAME_TYPE, 3>(std::array<ssize_t, 3>{
|
||||
static_cast<ssize_t>(mean_over_num_frames),
|
||||
static_cast<ssize_t>(rows), static_cast<ssize_t>(cols)});
|
||||
});
|
||||
|
||||
auto reader = [&]() {
|
||||
try {
|
||||
// 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<FRAME_TYPE, 3> *buffer = buffers.acquire_write(i);
|
||||
if (!buffer)
|
||||
throw std::runtime_error(
|
||||
"Failed to acquire buffer for writing");
|
||||
|
||||
file_reader.read_into(
|
||||
reinterpret_cast<std::byte *>(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<double> sum(shard_size);
|
||||
|
||||
for (size_t i = 0; i < num_samples; ++i) {
|
||||
const NDArray<FRAME_TYPE, 3> *buffer = buffers.acquire_read(i);
|
||||
if (!buffer)
|
||||
throw std::runtime_error(
|
||||
"Failed to acquire buffer for reading");
|
||||
|
||||
std::fill(sum.begin(), sum.end(), 0.0);
|
||||
|
||||
const FRAME_TYPE *src = 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<double>(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<std::future<void>> 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<double, 3> 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
|
||||
@@ -1,10 +1,29 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/defs.hpp"
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <filesystem>
|
||||
|
||||
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<long>(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
|
||||
*/
|
||||
@@ -22,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();
|
||||
|
||||
@@ -4,6 +4,8 @@
|
||||
#include "aare/FitModel.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
|
||||
#include <optional>
|
||||
|
||||
namespace aare {
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -62,11 +64,15 @@ NDArray<double, 1> fit_pixel(const FitModel<Model> &model, NDView<double, 1> 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 <typename Model>
|
||||
void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
|
||||
NDView<double, 3> y, NDView<double, 3> y_err,
|
||||
NDView<double, 3> par_out, NDView<double, 3> err_out,
|
||||
NDView<double, 2> chi2_out, int n_threads);
|
||||
NDView<double, 2> chi2_out, int n_threads,
|
||||
std::optional<const NDView<size_t, 3>> fit_range = std::nullopt);
|
||||
|
||||
} // namespace aare
|
||||
@@ -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 <fmt/format.h>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
#include <stdexcept>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<ModuleGaps> 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<uint64_t> 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<ssize_t> inner_boundaries(ssize_t min, ssize_t max) const {
|
||||
std::vector<ssize_t> 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<ssize_t, ssize_t> 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<ssize_t, 2> gapped_shape(const ROI &roi, const GapLayout &layout);
|
||||
|
||||
void validate_roi(const ROI &roi);
|
||||
void validate_destination(const std::array<ssize_t, 2> &shape, const ROI &roi,
|
||||
const GapLayout &layout);
|
||||
|
||||
std::mt19937_64 make_generator(std::optional<uint64_t> 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 <typename T> T fill_as(double value) {
|
||||
if constexpr (std::is_floating_point_v<T>) {
|
||||
return static_cast<T>(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<T>(static_cast<int64_t>(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 <typename T>
|
||||
void fill_gap_pixels(NDView<T, 2> 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 <typename T>
|
||||
void copy_with_gaps(NDView<const T, 2> source, const ROI &source_rect,
|
||||
NDView<T, 2> 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<std::pair<ssize_t, ssize_t>> 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<size_t>(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 <typename T>
|
||||
void split_edge_counts(NDView<T, 2> 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<T>) {
|
||||
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<ssize_t> 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<bool> module_gap_column(static_cast<size_t>(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<size_t>(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<size_t>(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<ssize_t, 2> 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 <typename T>
|
||||
NDArray<T, 2> insert_gap_pixels(NDView<const T, 2> source, const ROI &roi,
|
||||
const GapPixels &gaps = {}) {
|
||||
const auto layout = detail::gap_layout(gaps);
|
||||
detail::validate_roi(roi);
|
||||
const T fill = detail::fill_as<T>(gaps.fill_value);
|
||||
NDArray<T, 2> 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
|
||||
+34
-12
@@ -880,8 +880,17 @@ struct GaussianChargeSharing {
|
||||
return par[3] > 0.0;
|
||||
}
|
||||
|
||||
static std::array<double, npar> estimate_par(NDView<double, 1> x,
|
||||
NDView<double, 1> 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<double, npar>
|
||||
estimate_par(NDView<double, 1> x, NDView<double, 1> 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<ssize_t>(std::max<ssize_t>(n / 10, 2), n);
|
||||
const ssize_t tail = std::min<ssize_t>(
|
||||
std::max<ssize_t>(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<double, npar> estimate_par(NDView<double, 1> x,
|
||||
NDView<double, 1> 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<double, npar>
|
||||
estimate_par(NDView<double, 1> x, NDView<double, 1> 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];
|
||||
|
||||
@@ -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<size_t> frames_to_read = std::nullopt);
|
||||
|
||||
/** @brief Read the next wave of chunks into an owned byte buffer. */
|
||||
std::vector<std::byte> read();
|
||||
|
||||
@@ -221,6 +221,21 @@ class NDView : public ArrayExpr<NDView<T, Ndim>, 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 <int D = Ndim, std::enable_if_t<(D > 1) && D == Ndim, int> = 0>
|
||||
NDView<T, D - 1> 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<T, D - 1>(buffer_ + index * strides_[0], new_shape);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename, ssize_t> friend class NDView;
|
||||
|
||||
|
||||
@@ -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 <typename T, size_t NDim> NDArray<T, NDim> load() {
|
||||
NDArray<T, NDim> arr(make_shape<NDim>(m_header.shape));
|
||||
if (fseek(fp, static_cast<long>(header_size), SEEK_SET)) {
|
||||
if (fseek64(fp, header_size, SEEK_SET)) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Error seeking to the start of the data");
|
||||
}
|
||||
|
||||
@@ -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 <array>
|
||||
#include <optional>
|
||||
#include <random>
|
||||
|
||||
namespace aare {
|
||||
|
||||
@@ -26,6 +29,10 @@ class RawFile : public FileInterface {
|
||||
std::vector<std::vector<std::unique_ptr<RawSubFile>>>
|
||||
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<std::byte> m_part_buffer;
|
||||
|
||||
RawMasterFile m_master;
|
||||
size_t m_current_frame{};
|
||||
|
||||
@@ -34,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<GapPixels> 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<ROI> m_roi_rects;
|
||||
/// @brief {rows, cols} of the assembled frame of each ROI, including
|
||||
/// gap pixels when enabled
|
||||
std::vector<std::array<ssize_t, 2>> 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<GapPixels> gap_pixels = std::nullopt);
|
||||
virtual ~RawFile() override = default;
|
||||
|
||||
Frame read_frame() override;
|
||||
@@ -102,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<GapPixels> &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.
|
||||
@@ -154,6 +182,26 @@ 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<size_t> 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 <typename T>
|
||||
void assemble_with_gaps(std::byte *frame_buffer, size_t roi_index,
|
||||
const std::vector<size_t> &frame_indices,
|
||||
DetectorHeader *header);
|
||||
|
||||
/**
|
||||
* @brief read the frame at the given frame index into the image buffer
|
||||
* @param frame_index frame number to read
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <stdexcept>
|
||||
@@ -13,6 +14,10 @@
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
#if !defined(_MSC_VER)
|
||||
#include <sys/types.h> // ::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);
|
||||
@@ -156,6 +173,11 @@ struct Moench05 {
|
||||
constexpr static std::array<int, 3> 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,
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include <filesystem>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
@@ -49,6 +50,7 @@ class PedestalTrackingPixelHistogram {
|
||||
std::vector<FastPedestal<AxisType>> partial_pedestals_;
|
||||
std::vector<NDArray<AxisType, 2>> partial_std_; // cached for pedestal
|
||||
// tracking
|
||||
std::vector<NDArray<bool, 2>> partial_masks_{};
|
||||
|
||||
// Thread pool members
|
||||
std::vector<std::thread> workers_;
|
||||
@@ -101,16 +103,16 @@ class PedestalTrackingPixelHistogram {
|
||||
void fill_with_threshold_batch_(std::vector<NDArray<FrameType, 2>> &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<const NDView<bool, 2>> mask = std::nullopt);
|
||||
~PedestalTrackingPixelHistogram();
|
||||
|
||||
void push_pedestal_no_update(const NDView<FrameType, 2> &frame);
|
||||
void update_mean();
|
||||
NDArray<AxisType, 2> pedestal_mean() const;
|
||||
NDArray<AxisType, 2> pedestal_std() const;
|
||||
|
||||
void fill_async(NDArray<FrameType, 2> &&image);
|
||||
|
||||
|
||||
+49
-21
@@ -2,9 +2,12 @@
|
||||
#pragma once
|
||||
/*Utility to log to console*/
|
||||
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <ctime>
|
||||
#include <iostream>
|
||||
#include <sstream>
|
||||
#include <sys/time.h>
|
||||
#include <string>
|
||||
|
||||
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<milliseconds>(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<int>(ms.count()));
|
||||
return result;
|
||||
}
|
||||
|
||||
class Logger {
|
||||
std::ostringstream os;
|
||||
TLogLevel m_level = AARE_LOG_LEVEL;
|
||||
@@ -111,28 +155,12 @@ 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<long>(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?
|
||||
#define LOG(level) \
|
||||
if (level > AARE_LOG_LEVEL) \
|
||||
if constexpr (level > AARE_LOG_LEVEL) \
|
||||
; \
|
||||
else if (level > aare::Logger::ReportingLevel()) \
|
||||
; \
|
||||
|
||||
@@ -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
|
||||
@@ -19,7 +20,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");
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
#include <condition_variable>
|
||||
#include <limits>
|
||||
#include <mutex>
|
||||
#include <stddef.h>
|
||||
#include <stdexcept>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
|
||||
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 <typename ItemType> 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 <typename Func>
|
||||
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<std::mutex> lock(m_mtx);
|
||||
m_cv_free.wait(
|
||||
lock, [&] { return m_abort || m_pending_consumers[slot] == 0; });
|
||||
if (m_abort)
|
||||
return nullptr;
|
||||
return &m_buffers[slot];
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Mark item i as written and wake up the consumers.
|
||||
*/
|
||||
void commit_write(size_t i) {
|
||||
const size_t slot = i % size();
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mtx);
|
||||
m_item_in_slot[slot] = i;
|
||||
m_pending_consumers[slot] = m_num_consumers;
|
||||
}
|
||||
m_cv_loaded.notify_all();
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Block until item i has been written.
|
||||
* @return the buffer holding item i or nullptr if aborted
|
||||
*/
|
||||
const ItemType *acquire_read(size_t i) {
|
||||
const size_t slot = i % size();
|
||||
std::unique_lock<std::mutex> lock(m_mtx);
|
||||
m_cv_loaded.wait(lock,
|
||||
[&] { return m_abort || m_item_in_slot[slot] == i; });
|
||||
if (m_abort)
|
||||
return nullptr;
|
||||
return &m_buffers[slot];
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Signal that this consumer no longer needs item i. Once all
|
||||
* consumers released it the slot can be reused by the producer.
|
||||
*/
|
||||
void release_read(size_t i) {
|
||||
const size_t slot = i % size();
|
||||
bool slot_free = false;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(m_mtx);
|
||||
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<std::mutex> lock(m_mtx);
|
||||
m_abort = true;
|
||||
}
|
||||
m_cv_loaded.notify_all();
|
||||
m_cv_free.notify_all();
|
||||
}
|
||||
|
||||
private:
|
||||
size_t m_num_consumers;
|
||||
std::vector<ItemType> m_buffers;
|
||||
|
||||
static constexpr size_t no_item = std::numeric_limits<size_t>::max();
|
||||
|
||||
// per slot:
|
||||
/// @brief Index of the item currently committed to the slot.
|
||||
std::vector<size_t> m_item_in_slot; // store the item - boolean flag need to
|
||||
// set back to false ->
|
||||
std::vector<size_t> m_pending_consumers;
|
||||
|
||||
std::mutex m_mtx;
|
||||
/// @brief Condition variable to notify consumers that an item has been
|
||||
/// loaded.
|
||||
std::condition_variable m_cv_loaded;
|
||||
/// @brief Condition variable to notify producers that a slot is free to
|
||||
/// overwrite.
|
||||
std::condition_variable m_cv_free;
|
||||
|
||||
/// @brief Flag to indicate if the buffer pool should be aborted.
|
||||
bool m_abort{false};
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
+10
-3
@@ -1,11 +1,12 @@
|
||||
[tool.scikit-build.metadata.version]
|
||||
[[tool.dynamic-metadata]]
|
||||
field = "version"
|
||||
provider = "scikit_build_core.metadata.regex"
|
||||
input = "VERSION"
|
||||
regex = '^(?P<version>\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]
|
||||
@@ -28,9 +29,15 @@ 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
|
||||
# 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"]
|
||||
|
||||
|
||||
+12
-2
@@ -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
|
||||
|
||||
|
||||
|
||||
@@ -42,6 +42,8 @@ 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
|
||||
|
||||
from ._aare import UDPPortPosition
|
||||
@@ -89,3 +91,5 @@ from ._aare import (
|
||||
PixelHistogram_u32,
|
||||
PixelHistogram_u64,
|
||||
)
|
||||
|
||||
from ._aare import block_mean, mean_current_source
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -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")
|
||||
@@ -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")
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -13,9 +14,6 @@ namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename Type, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType>
|
||||
void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
@@ -140,5 +138,3 @@ void reduce_to_2x2(py::module &m) {
|
||||
row-major order.
|
||||
)doc");
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
@@ -20,9 +21,6 @@ namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterCollector(py::module &m, const std::string &typestr) {
|
||||
@@ -42,5 +40,3 @@ void define_ClusterCollector(py::module &m, const std::string &typestr) {
|
||||
},
|
||||
py::return_value_policy::take_ownership);
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/ClusterFile.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
@@ -13,11 +14,6 @@
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
// 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 +167,12 @@ void define_ClusterFile(py::module &m, const std::string &typestr) {
|
||||
.def("__enter__", [](ClusterFile<ClusterType> &self) { return &self; })
|
||||
.def("__exit__",
|
||||
[](ClusterFile<ClusterType> &self,
|
||||
const std::optional<pybind11::type> &exc_type,
|
||||
const std::optional<pybind11::object> &exc_value,
|
||||
const std::optional<pybind11::object> &traceback) {
|
||||
self.close();
|
||||
})
|
||||
[[maybe_unused]] const std::optional<pybind11::type> &exc_type,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&exc_value,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&traceback) { self.close(); })
|
||||
.def("__iter__", [](ClusterFile<ClusterType> &self) { return &self; })
|
||||
.def("__next__",
|
||||
[](File &self) { return ChunkIterator(self.chunks()).next(); });
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
@@ -17,9 +18,6 @@
|
||||
namespace py = pybind11;
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterFileSink(py::module &m, const std::string &typestr) {
|
||||
@@ -34,5 +32,3 @@ void define_ClusterFileSink(py::module &m, const std::string &typestr) {
|
||||
const std::filesystem::path &>())
|
||||
.def("stop", &ClusterFileSink<ClusterType>::stop);
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
@@ -20,9 +21,6 @@ namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterFinder(py::module &m, const std::string &typestr) {
|
||||
@@ -92,5 +90,3 @@ void define_ClusterFinder(py::module &m, const std::string &typestr) {
|
||||
},
|
||||
py::arg("frame").noconvert(), py::arg("frame_number") = 0);
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
@@ -20,9 +21,6 @@ namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterFinderMT(py::module &m, const std::string &typestr) {
|
||||
@@ -55,7 +53,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<ClusterType, uint16_t, pd_type> &self) {
|
||||
[]([[maybe_unused]] ClusterFinderMT<ClusterType, uint16_t, pd_type>
|
||||
&self) {
|
||||
return py::make_tuple(ClusterSizeX, ClusterSizeY);
|
||||
})
|
||||
.def("clear_pedestal",
|
||||
@@ -93,5 +92,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
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
@@ -18,9 +19,6 @@ namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
#pragma GCC diagnostic push
|
||||
#pragma GCC diagnostic ignored "-Wunused-parameter"
|
||||
|
||||
template <typename Type, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
@@ -123,8 +121,8 @@ void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
"padding.")
|
||||
.def_property_readonly(
|
||||
"fmt",
|
||||
[typestr](ClusterVector<ClusterType> &self) {
|
||||
return fmt_format<ClusterType>;
|
||||
[typestr]([[maybe_unused]] ClusterVector<ClusterType> &self) {
|
||||
return fmt_format<ClusterType>();
|
||||
},
|
||||
"PEP 3118 format string for one stored cluster.")
|
||||
|
||||
@@ -145,11 +143,11 @@ void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
.def_buffer(
|
||||
[typestr](ClusterVector<ClusterType> &self) -> py::buffer_info {
|
||||
return py::buffer_info(
|
||||
self.data(), /* Pointer to buffer */
|
||||
self.item_size(), /* Size of one scalar */
|
||||
fmt_format<ClusterType>, /* Format descriptor */
|
||||
1, /* Number of dimensions */
|
||||
{self.size()}, /* Buffer dimensions */
|
||||
self.data(), /* Pointer to buffer */
|
||||
self.item_size(), /* Size of one scalar */
|
||||
fmt_format<ClusterType>(), /* Format descriptor */
|
||||
1, /* Number of dimensions */
|
||||
{self.size()}, /* Buffer dimensions */
|
||||
{self.item_size()} /* Strides (in bytes) for each index */
|
||||
);
|
||||
});
|
||||
@@ -228,5 +226,3 @@ void define_3x3_reduction(py::module &m) {
|
||||
)doc",
|
||||
py::arg("clustervector"));
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -0,0 +1,78 @@
|
||||
#include "aare/DataSetAggregation.hpp"
|
||||
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
using namespace aare;
|
||||
|
||||
template <typename FRAME_TYPE>
|
||||
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<double, 3>(block_mean<FRAME_TYPE>(
|
||||
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<double, 3>(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");
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <pybind11/operators.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
@@ -29,6 +31,9 @@ void define_defs_bindings(py::module &m) {
|
||||
moench05.attr("nCols") = Moench05::nCols;
|
||||
moench05.attr("adcNumbers") = Moench05::adcNumbers;
|
||||
|
||||
auto jungfrau = py::class_<Jungfrau>(m, "Jungfrau");
|
||||
jungfrau.attr("nRows") = Jungfrau::nRows;
|
||||
jungfrau.attr("nCols") = Jungfrau::nCols;
|
||||
py::class_<ROI>(m, "ROI")
|
||||
.def(py::init<>())
|
||||
.def(py::init<ssize_t, ssize_t, ssize_t, ssize_t>(), py::arg("xmin"),
|
||||
@@ -74,6 +79,21 @@ void define_defs_bindings(py::module &m) {
|
||||
self.ymin == other.ymin && self.ymax == other.ymax;
|
||||
});
|
||||
|
||||
py::class_<xy>(m, "xy")
|
||||
.def(py::init<uint32_t, uint32_t>(), 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_<DetectorType>(m, "DetectorType")
|
||||
.value("Jungfrau", DetectorType::Jungfrau)
|
||||
.value("Eiger", DetectorType::Eiger)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/to_string.hpp"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/FastPedestal.hpp"
|
||||
#include "np_helper.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 <fmt/format.h>
|
||||
#include <optional>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/operators.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
using namespace ::aare;
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename T>
|
||||
py::array insert_gap_pixels_typed(const py::array &image, const ROI &roi,
|
||||
const GapPixels &gaps) {
|
||||
py::array_t<T, py::array::c_style | py::array::forcecast> typed(image);
|
||||
auto source = make_const_view_2d(typed);
|
||||
auto *result = new NDArray<T, 2>(insert_gap_pixels<T>(source, roi, gaps));
|
||||
return return_image_data(result);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
void define_gap_pixels_bindings(py::module &m) {
|
||||
py::class_<ModuleGaps>(m, "ModuleGaps", R"(
|
||||
Pixels inserted at each boundary between modules.
|
||||
)")
|
||||
.def(py::init<>())
|
||||
.def(py::init<ssize_t, ssize_t>(), 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_<GapPixels>(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<ModuleGaps> module_gaps,
|
||||
double fill_value, bool split_counts,
|
||||
std::optional<uint64_t> 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> 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<py::array_t<uint8_t>>(image)) {
|
||||
return insert_gap_pixels_typed<uint8_t>(image, rect, gaps);
|
||||
}
|
||||
if (py::isinstance<py::array_t<uint16_t>>(image)) {
|
||||
return insert_gap_pixels_typed<uint16_t>(image, rect, gaps);
|
||||
}
|
||||
if (py::isinstance<py::array_t<uint32_t>>(image)) {
|
||||
return insert_gap_pixels_typed<uint32_t>(image, rect, gaps);
|
||||
}
|
||||
if (py::isinstance<py::array_t<int32_t>>(image)) {
|
||||
return insert_gap_pixels_typed<int32_t>(image, rect, gaps);
|
||||
}
|
||||
if (py::isinstance<py::array_t<float>>(image)) {
|
||||
return insert_gap_pixels_typed<float>(image, rect, gaps);
|
||||
}
|
||||
if (py::isinstance<py::array_t<double>>(image)) {
|
||||
return insert_gap_pixels_typed<double>(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``.
|
||||
)");
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/Interpolator.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
|
||||
@@ -16,6 +16,7 @@
|
||||
#include <pybind11/stl/filesystem.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
using aare::ssize_t;
|
||||
|
||||
inline py::dtype multi_threaded_reader_numpy_dtype(const aare::Dtype &dtype) {
|
||||
using aare::Dtype;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/hist/PedestalTrackingPixelHistogram.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
@@ -15,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<int, int, int, double, double, int, std::size_t, double>(),
|
||||
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<py::array_t<bool, py::array::c_style>> 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:
|
||||
@@ -42,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",
|
||||
@@ -100,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<PedestalTrackingPixelHistogram::AxisType, 2> *ptr =
|
||||
nullptr;
|
||||
{
|
||||
py::gil_scoped_release release;
|
||||
ptr = new NDArray<PedestalTrackingPixelHistogram::AxisType,
|
||||
2>(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,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/hist/PixelHistogram.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/PixelMap.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#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"
|
||||
@@ -12,6 +14,7 @@
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <memory>
|
||||
#include <pybind11/iostream.h>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
@@ -33,7 +36,33 @@ std::runtime_error raw_file_read_error(RawFile &file,
|
||||
|
||||
void define_raw_file_io_bindings(py::module &m) {
|
||||
py::class_<RawFile>(m, "RawFile")
|
||||
.def(py::init<const std::filesystem::path &>())
|
||||
.def(py::init([](const std::filesystem::path &fname,
|
||||
const GapPixels &gap_pixels) {
|
||||
return std::make_unique<RawFile>(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<RawFile>(
|
||||
fname, "r",
|
||||
gap_pixels ? std::optional<GapPixels>(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) {
|
||||
@@ -117,8 +146,8 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
|
||||
std::vector<size_t> 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);
|
||||
@@ -176,8 +205,8 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
for (size_t r = 0; r < number_of_ROIs; r++) {
|
||||
std::vector<size_t> 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);
|
||||
@@ -228,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<size_t> shape{
|
||||
n_frames, self.roi_geometries(roi_index).pixels_y(),
|
||||
self.roi_geometries(roi_index).pixels_x()};
|
||||
std::vector<size_t> 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];
|
||||
@@ -318,7 +346,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)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/calibration.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -9,6 +10,7 @@
|
||||
#include <pybind11/stl_bind.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
using aare::ssize_t;
|
||||
|
||||
template <typename DataType>
|
||||
py::array_t<DataType>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
|
||||
+8
-11
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
@@ -21,11 +22,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 +118,12 @@ void define_file_io_bindings(py::module &m) {
|
||||
})
|
||||
.def("__enter__", [](File &self) { return &self; })
|
||||
.def("__exit__",
|
||||
[](File &self, const std::optional<pybind11::type> &exc_type,
|
||||
const std::optional<pybind11::object> &exc_value,
|
||||
const std::optional<pybind11::object> &traceback) {
|
||||
[]([[maybe_unused]] File &self,
|
||||
[[maybe_unused]] const std::optional<pybind11::type> &exc_type,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&exc_value,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&traceback) {
|
||||
// self.close();
|
||||
})
|
||||
.def("__iter__", [](File &self) { return &self; })
|
||||
@@ -146,7 +145,7 @@ void define_file_io_bindings(py::module &m) {
|
||||
self.read_into(
|
||||
reinterpret_cast<std::byte *>(image.mutable_data()));
|
||||
return image;
|
||||
} catch (std::runtime_error &e) {
|
||||
} catch (std::runtime_error &) {
|
||||
throw py::stop_iteration();
|
||||
}
|
||||
});
|
||||
@@ -160,6 +159,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
|
||||
}
|
||||
+103
-25
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <pybind11/pybind11.h>
|
||||
@@ -11,23 +12,27 @@
|
||||
|
||||
namespace py = pybind11;
|
||||
using namespace pybind11::literals;
|
||||
using aare::ssize_t;
|
||||
|
||||
template <typename Model>
|
||||
py::object
|
||||
fit_dispatch(const aare::FitModel<Model> &model,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> y,
|
||||
py::object y_err_obj, int n_threads);
|
||||
py::object y_err_obj, int n_threads,
|
||||
std::optional<py::array_t<size_t>> fit_range = std::nullopt);
|
||||
|
||||
template <typename Model> void bind_fit_model(py::module &m, const char *name) {
|
||||
using FM = aare::FitModel<Model>;
|
||||
py::class_<FM>(m, name)
|
||||
.def(py::init<unsigned int, unsigned int, double, bool,
|
||||
aare::Minimizer>(),
|
||||
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_<FM>(m, name);
|
||||
|
||||
cls.def(py::init<unsigned int, unsigned int, double, bool,
|
||||
aare::Minimizer>(),
|
||||
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
|
||||
@@ -115,8 +120,11 @@ template <typename Model> void bind_fit_model(py::module &m, const char *name) {
|
||||
[](const FM &self,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> y,
|
||||
py::object y_err_obj, int n_threads) -> py::object {
|
||||
return fit_dispatch<Model>(self, x, y, y_err_obj, n_threads);
|
||||
py::object y_err_obj, int n_threads,
|
||||
std::optional<py::array_t<size_t>> fit_range =
|
||||
std::nullopt) -> py::object {
|
||||
return fit_dispatch<Model>(self, x, y, y_err_obj, n_threads,
|
||||
fit_range);
|
||||
},
|
||||
R"doc(
|
||||
Fit this model to 1D or 3D data using Minuit2.
|
||||
@@ -136,9 +144,50 @@ template <typename Model> 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<Model, model::GaussianChargeSharing> or
|
||||
std::is_same_v<Model, model::GaussianChargeSharingKb>) {
|
||||
cls.def(
|
||||
"estimate_par",
|
||||
[](const FM & /*self*/,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> 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<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast>
|
||||
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 <typename Model>
|
||||
@@ -185,7 +234,8 @@ py::object
|
||||
fit_dispatch(const aare::FitModel<Model> &model,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> y,
|
||||
py::object y_err_obj, int n_threads) {
|
||||
py::object y_err_obj, int n_threads,
|
||||
std::optional<py::array_t<size_t>> fit_range) {
|
||||
constexpr std::size_t npar = Model::npar;
|
||||
|
||||
if (y.ndim() == 3) {
|
||||
@@ -196,6 +246,11 @@ fit_dispatch(const aare::FitModel<Model> &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<double, py::array::c_style | py::array::forcecast>>(
|
||||
@@ -205,9 +260,13 @@ fit_dispatch(const aare::FitModel<Model> &model,
|
||||
new NDArray<double, 3>({y.shape(0), y.shape(1), npar}, 0.0);
|
||||
auto y_view_err = make_view_3d(y_err);
|
||||
|
||||
aare::fit_3d<Model>(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>(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),
|
||||
@@ -229,7 +288,8 @@ fit_dispatch(const aare::FitModel<Model> &model,
|
||||
|
||||
aare::fit_3d<Model>(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),
|
||||
@@ -238,9 +298,12 @@ fit_dispatch(const aare::FitModel<Model> &model,
|
||||
|
||||
NDView<double, 3> dummy_err_out{};
|
||||
|
||||
aare::fit_3d<Model>(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>(
|
||||
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));
|
||||
@@ -251,15 +314,28 @@ fit_dispatch(const aare::FitModel<Model> &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<double, py::array::c_style | py::array::forcecast>>(
|
||||
y_err_obj);
|
||||
|
||||
auto y_view_err = make_view_1d(y_err);
|
||||
result = aare::fit_pixel<Model>(model, x_view, y_view, y_view_err);
|
||||
{
|
||||
py::gil_scoped_release release; // release GIL for parallel loop
|
||||
result =
|
||||
aare::fit_pixel<Model>(model, x_view, y_view, y_view_err);
|
||||
}
|
||||
} else {
|
||||
result = aare::fit_pixel<Model>(model, x_view, y_view);
|
||||
{
|
||||
py::gil_scoped_release release; // release GIL for parallel loop
|
||||
result = aare::fit_pixel<Model>(model, x_view, y_view);
|
||||
}
|
||||
}
|
||||
|
||||
return pack_1d_result_dict<Model>(result, model.compute_errors());
|
||||
@@ -274,13 +350,15 @@ py::object dispatch_any_model(
|
||||
py::object model_obj,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> x,
|
||||
py::array_t<double, py::array::c_style | py::array::forcecast> y,
|
||||
py::object y_err_obj, int n_threads) {
|
||||
py::object y_err_obj, int n_threads,
|
||||
std::optional<py::array_t<size_t>> fit_range = std::nullopt) {
|
||||
using namespace aare::model;
|
||||
|
||||
#define AARE_DISPATCH_MODEL(Model) \
|
||||
if (py::isinstance<aare::FitModel<Model>>(model_obj)) { \
|
||||
const auto &mdl = model_obj.cast<const aare::FitModel<Model> &>(); \
|
||||
return fit_dispatch<Model>(mdl, x, y, y_err_obj, n_threads); \
|
||||
return fit_dispatch<Model>(mdl, x, y, y_err_obj, n_threads, \
|
||||
fit_range); \
|
||||
}
|
||||
|
||||
AARE_DISPATCH_MODEL(Pol1)
|
||||
@@ -369,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
|
||||
@@ -385,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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/JungfrauDataFile.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
@@ -15,11 +16,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<JungfrauDataHeader> header(1);
|
||||
py::array_t<uint16_t> image({self.rows(), self.cols()});
|
||||
@@ -94,20 +90,20 @@ void define_jungfrau_data_file_io_bindings(py::module &m) {
|
||||
)")
|
||||
.def("__enter__", [](JungfrauDataFile &self) { return &self; })
|
||||
.def("__exit__",
|
||||
[](JungfrauDataFile &self,
|
||||
const std::optional<pybind11::type> &exc_type,
|
||||
const std::optional<pybind11::object> &exc_value,
|
||||
const std::optional<pybind11::object> &traceback) {
|
||||
[]([[maybe_unused]] JungfrauDataFile &self,
|
||||
[[maybe_unused]] const std::optional<pybind11::type> &exc_type,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&exc_value,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&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
|
||||
@@ -12,9 +12,11 @@
|
||||
#include "bind_ClusterFinderFrozen.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"
|
||||
#include "bind_GapPixels.hpp"
|
||||
#include "bind_Interpolator.hpp"
|
||||
#include "bind_MultiThreadedFileReader.hpp"
|
||||
#include "bind_Pedestal.hpp"
|
||||
@@ -158,6 +160,7 @@ PYBIND11_MODULE(_aare, m) {
|
||||
register_calculate_3x3eta<int16_t, 3, 3, uint16_t>(m);
|
||||
|
||||
define_defs_bindings(m);
|
||||
define_gap_pixels_bindings(m);
|
||||
|
||||
using Sum_index_pair_d = Sum_index_pair<double, corner>;
|
||||
PYBIND11_NUMPY_DTYPE(Sum_index_pair_d, sum, index);
|
||||
@@ -180,4 +183,8 @@ PYBIND11_MODULE(_aare, m) {
|
||||
define_eta<double>(m, "d");
|
||||
define_eta<int>(m, "i");
|
||||
define_eta<int16_t>(m, "i16");
|
||||
|
||||
bind_DataSetAggregation<uint16_t>(m);
|
||||
|
||||
bind_read_current_source(m);
|
||||
}
|
||||
@@ -112,8 +112,13 @@ struct fmt_format_trait<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
}
|
||||
};
|
||||
|
||||
template <typename ClusterType>
|
||||
auto fmt_format = fmt_format_trait<ClusterType>::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 <typename ClusterType> const std::string &fmt_format() {
|
||||
static const std::string value = fmt_format_trait<ClusterType>::value();
|
||||
return value;
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper function to allocate image data given item size and shape
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
@@ -67,9 +68,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
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
@@ -61,11 +62,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_<RawSubFile>(m, "RawSubFile")
|
||||
.def(py::init<const std::filesystem::path &, DetectorType, size_t,
|
||||
@@ -89,17 +85,18 @@ void define_raw_sub_file_io_bindings(py::module &m) {
|
||||
})
|
||||
.def("__enter__", [](RawSubFile &self) { return &self; })
|
||||
.def("__exit__",
|
||||
[](RawSubFile &self, const std::optional<pybind11::type> &exc_type,
|
||||
const std::optional<pybind11::object> &exc_value,
|
||||
const std::optional<pybind11::object> &traceback) {})
|
||||
[]([[maybe_unused]] RawSubFile &self,
|
||||
[[maybe_unused]] const std::optional<pybind11::type> &exc_type,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&exc_value,
|
||||
[[maybe_unused]] const std::optional<pybind11::object>
|
||||
&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
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/VarClusterFinder.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
|
||||
@@ -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
|
||||
@@ -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))
|
||||
@@ -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()
|
||||
@@ -1,7 +1,8 @@
|
||||
# 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
|
||||
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", [
|
||||
@@ -237,6 +278,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())
|
||||
@@ -439,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)
|
||||
@@ -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)))
|
||||
@@ -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)"
|
||||
@@ -12,6 +12,7 @@
|
||||
|
||||
using aare::Cluster;
|
||||
using aare::ClusterVector;
|
||||
using aare::ssize_t;
|
||||
using C1 = Cluster<int32_t, 2, 2>;
|
||||
|
||||
TEST_CASE("A newly created ClusterVector is empty") {
|
||||
@@ -180,7 +181,8 @@ TEST_CASE("Summing 3x1 clusters of int64") {
|
||||
|
||||
Cluster<int32_t, 3, 1> 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);
|
||||
|
||||
/*
|
||||
@@ -236,7 +238,8 @@ TEST_CASE("Push back more than initial capacity") {
|
||||
Cluster<int32_t, 2, 2> 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<int32_t, 2, 2> *ptr =
|
||||
reinterpret_cast<Cluster<int32_t, 2, 2> *>(cv.data());
|
||||
|
||||
@@ -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 <cstdint>
|
||||
#include <fmt/format.h>
|
||||
#include <future>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace aare {
|
||||
|
||||
// TODO: maybe O_DIRECT rea dis better to avoid the page cache
|
||||
|
||||
NDArray<double, 3> 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<double>(mean_over_num_frames);
|
||||
|
||||
NDArray<double, 3> cs_data({static_cast<ssize_t>(num_rows),
|
||||
static_cast<ssize_t>(num_cols),
|
||||
static_cast<ssize_t>(num_samples)},
|
||||
0);
|
||||
|
||||
constexpr size_t num_buffers = 4; // TODO: random for now reading much
|
||||
// slower - small buffer is enough
|
||||
|
||||
RingBufferPool<NDArray<uint16_t, 3>> buffers(
|
||||
num_buffers, num_processing_threads,
|
||||
[&num_rows, &num_cols, &frames_per_sample] {
|
||||
return NDArray<uint16_t, 3>(
|
||||
std::array<ssize_t, 3>{static_cast<ssize_t>(frames_per_sample),
|
||||
static_cast<ssize_t>(num_rows),
|
||||
static_cast<ssize_t>(num_cols)});
|
||||
});
|
||||
|
||||
auto reader = [&]() {
|
||||
try {
|
||||
// one wave of the reader covers exactly one batch
|
||||
experimental::MultiThreadedFileReader file_reader(
|
||||
path, static_cast<size_t>(num_reader_threads),
|
||||
ceil_div(frames_per_sample,
|
||||
static_cast<size_t>(num_reader_threads)));
|
||||
|
||||
file_reader.seek(file_offset);
|
||||
|
||||
for (size_t b = 0; b < num_samples; ++b) {
|
||||
NDArray<uint16_t, 3> *buffer = buffers.acquire_write(b);
|
||||
if (!buffer)
|
||||
throw std::runtime_error(
|
||||
"Failed to acquire buffer for writing");
|
||||
|
||||
file_reader.read_into(
|
||||
reinterpret_cast<std::byte *>(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<uint64_t> sum(shard_size, 0);
|
||||
|
||||
for (size_t sample = 0; sample < num_samples; ++sample) {
|
||||
const NDArray<uint16_t, 3> *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<double>(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<std::future<void>> 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
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "aare/DataSetAggregation.hpp"
|
||||
|
||||
#include "jungfrau_file_helpers.hpp"
|
||||
|
||||
#include <catch2/catch_approx.hpp>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include <iostream>
|
||||
|
||||
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<uint16_t, 2> data({Jungfrau::nRows, Jungfrau::nCols},
|
||||
value);
|
||||
return data;
|
||||
});
|
||||
|
||||
const std::filesystem::path path = temp_files.file_path();
|
||||
|
||||
auto mean_result =
|
||||
block_mean<uint16_t>(path, num_samples, num_frames_per_sample,
|
||||
num_processing_threads, num_reader_threads);
|
||||
|
||||
// Check the shape of the result
|
||||
REQUIRE(mean_result.shape(0) == Jungfrau::nRows);
|
||||
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<uint16_t, 2> 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<double>(c * mean_over_num_frames +
|
||||
sum_mean_over_frames) /
|
||||
mean_over_num_frames));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -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 = '>';
|
||||
|
||||
+3
-3
@@ -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_); }
|
||||
@@ -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()));
|
||||
|
||||
@@ -0,0 +1,104 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/GapPixels.hpp"
|
||||
|
||||
#include <fmt/format.h>
|
||||
|
||||
#include <limits>
|
||||
|
||||
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<ssize_t>::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<ssize_t, 2> 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<ssize_t, 2> &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<uint64_t> seed) {
|
||||
if (seed) {
|
||||
return std::mt19937_64(*seed);
|
||||
}
|
||||
std::random_device device;
|
||||
return std::mt19937_64((static_cast<uint64_t>(device()) << 32) ^ device());
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
std::array<ssize_t, 2> 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
|
||||
@@ -0,0 +1,588 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/GapPixels.hpp"
|
||||
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/generators/catch_generators.hpp>
|
||||
#include <catch2/matchers/catch_matchers_string.hpp>
|
||||
|
||||
#include <cmath>
|
||||
#include <limits>
|
||||
#include <numeric>
|
||||
|
||||
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 <typename T> NDArray<T, 2> pattern(ssize_t rows, ssize_t cols) {
|
||||
NDArray<T, 2> image({rows, cols});
|
||||
for (ssize_t row = 0; row < rows; ++row) {
|
||||
for (ssize_t col = 0; col < cols; ++col) {
|
||||
image(row, col) = static_cast<T>((row * cols + col) % 60000 + 1);
|
||||
}
|
||||
}
|
||||
return image;
|
||||
}
|
||||
|
||||
template <typename T> double total(NDView<T, 2> 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<double>(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<ssize_t>{2, 4, 6});
|
||||
CHECK(axis.inner_boundaries(1, 3) == std::vector<ssize_t>{2});
|
||||
CHECK(axis.inner_boundaries(2, 4).empty());
|
||||
CHECK(axis.inner_boundaries(2, 5) == std::vector<ssize_t>{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<ssize_t, ssize_t>{2, 2});
|
||||
CHECK(axis.gap_range(4, 0) == std::pair<ssize_t, ssize_t>{5, 7});
|
||||
CHECK(axis.gap_range(4, 3) == std::pair<ssize_t, ssize_t>{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<ssize_t, 2>;
|
||||
|
||||
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<uint16_t>(4, 8);
|
||||
const auto shape = detail::gapped_shape(roi, layout);
|
||||
REQUIRE(shape == std::array<ssize_t, 2>{5, 13});
|
||||
|
||||
NDArray<uint16_t, 2> destination(shape, uint16_t{7});
|
||||
detail::fill_gap_pixels(destination.view(), roi, layout, uint16_t{99});
|
||||
|
||||
SECTION("whole ROI") {
|
||||
detail::copy_with_gaps(NDView<const uint16_t, 2>(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<uint16_t, 2> left_pixels({4, 3});
|
||||
NDArray<uint16_t, 2> 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<const uint16_t, 2>(left_pixels.view()),
|
||||
left, destination.view(), roi, layout);
|
||||
detail::copy_with_gaps(NDView<const uint16_t, 2>(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<uint16_t, 2> 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<const uint16_t, 2>(source.view()),
|
||||
roi, wrong.view(), roi, layout),
|
||||
std::invalid_argument);
|
||||
CHECK_THROWS_AS(detail::copy_with_gaps(
|
||||
NDView<const uint16_t, 2>(source.view()),
|
||||
ROI{0, 9, 0, 4}, destination.view(), roi, layout),
|
||||
std::invalid_argument);
|
||||
CHECK_THROWS_AS(detail::copy_with_gaps(
|
||||
NDView<const uint16_t, 2>(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<uint16_t>(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<const uint16_t, 2>(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<const uint16_t, 2>(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<uint16_t>(512, 1024);
|
||||
GapPixels gaps;
|
||||
gaps.fill_value = 5;
|
||||
auto result =
|
||||
insert_gap_pixels(NDView<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<const uint16_t, 2>(result.view())) ==
|
||||
total(NDView<const uint16_t, 2>(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<uint32_t, 2> source({1, 2});
|
||||
source(0, 0) = 11;
|
||||
source(0, 1) = 22;
|
||||
auto result =
|
||||
insert_gap_pixels(NDView<const uint32_t, 2>(source.view()), roi);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<uint8_t>(2, 4);
|
||||
auto result =
|
||||
insert_gap_pixels(NDView<const uint8_t, 2>(source.view()), roi);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<uint16_t>(301, 101);
|
||||
auto result = insert_gap_pixels(
|
||||
NDView<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<uint16_t>(2, 4);
|
||||
CHECK_THROWS_AS(
|
||||
insert_gap_pixels(NDView<const uint16_t, 2>(source.view()),
|
||||
ROI{0, 5, 0, 2}),
|
||||
std::invalid_argument);
|
||||
}
|
||||
SECTION("floating point images") {
|
||||
const ROI roi{255, 257, 0, 1};
|
||||
NDArray<double, 2> 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<const double, 2>(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<uint16_t>(1, 2);
|
||||
GapPixels gaps;
|
||||
for (const double value :
|
||||
{std::numeric_limits<double>::quiet_NaN(),
|
||||
std::numeric_limits<double>::infinity(),
|
||||
-std::numeric_limits<double>::infinity(), 1e20, -1e20, 0x1p63}) {
|
||||
gaps.fill_value = value;
|
||||
CHECK_THROWS_AS(
|
||||
insert_gap_pixels(NDView<const uint16_t, 2>(source.view()), roi,
|
||||
gaps),
|
||||
std::invalid_argument);
|
||||
}
|
||||
|
||||
// the same values are valid for floating point images
|
||||
gaps.fill_value = std::numeric_limits<double>::quiet_NaN();
|
||||
auto floats = pattern<float>(1, 2);
|
||||
auto result =
|
||||
insert_gap_pixels(NDView<const float, 2>(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<uint16_t>(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<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{4, 2});
|
||||
CHECK(result == source);
|
||||
|
||||
gaps.module_gaps = ModuleGaps{0, 3};
|
||||
auto with_gap =
|
||||
insert_gap_pixels(NDView<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(with_gap.shape() == std::array<ssize_t, 2>{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<uint32_t, 2> 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<const uint32_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<uint16_t, 2> 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<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<const uint16_t, 2>(result.view())) == 22);
|
||||
}
|
||||
SECTION("floating point halves exactly") {
|
||||
const ROI roi{255, 257, 255, 257};
|
||||
NDArray<double, 2> source({2, 2}, 1.0);
|
||||
source(0, 0) = 3.0;
|
||||
auto result = insert_gap_pixels(NDView<const double, 2>(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<uint32_t, 2> source({512, 1024});
|
||||
for (ssize_t row = 0; row < 512; ++row) {
|
||||
for (ssize_t col = 0; col < 1024; ++col) {
|
||||
source(row, col) =
|
||||
static_cast<uint32_t>((row * 7 + col * 13) % 1000 + 1);
|
||||
}
|
||||
}
|
||||
auto first = insert_gap_pixels(NDView<const uint32_t, 2>(source.view()),
|
||||
roi, gaps);
|
||||
auto second = insert_gap_pixels(
|
||||
NDView<const uint32_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(first.shape() == std::array<ssize_t, 2>{514, 1030});
|
||||
CHECK(total(NDView<const uint32_t, 2>(first.view())) ==
|
||||
total(NDView<const uint32_t, 2>(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<double>(kept_high) / odd;
|
||||
CHECK(fraction > 0.4);
|
||||
CHECK(fraction < 0.6);
|
||||
|
||||
GapPixels other = gaps;
|
||||
other.seed = 43;
|
||||
auto third = insert_gap_pixels(NDView<const uint32_t, 2>(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<uint16_t, 2> source({1024, 1024}, uint16_t{7});
|
||||
auto result = insert_gap_pixels(
|
||||
NDView<const uint16_t, 2>(source.view()), roi, module_gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{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<const uint16_t, 2>(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<uint16_t, 2> source({1, 4}, uint16_t{9});
|
||||
auto result = insert_gap_pixels(
|
||||
NDView<const uint16_t, 2>(source.view()), roi, gaps);
|
||||
REQUIRE(result.shape() == std::array<ssize_t, 2>{1, 4});
|
||||
CHECK(result(0, 0) == 9);
|
||||
}
|
||||
}
|
||||
@@ -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) {
|
||||
@@ -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<ssize_t>(header_size), SEEK_CUR);
|
||||
return header;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<size_t> 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;
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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<double> a;
|
||||
|
||||
+36
-18
@@ -11,11 +11,12 @@
|
||||
using aare::NDView;
|
||||
using aare::num_elements;
|
||||
using aare::Shape;
|
||||
using aare::ssize_t;
|
||||
|
||||
static_assert(std::is_convertible_v<NDView<int, 2>, NDView<const int, 2>>);
|
||||
static_assert(!std::is_convertible_v<NDView<const int, 2>, NDView<int, 2>>);
|
||||
|
||||
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);
|
||||
|
||||
@@ -33,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<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -46,7 +47,7 @@ TEST_CASE("Element reference 1D") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Assign elements through () and []") {
|
||||
TEST_CASE("Assign elements through () and []", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -79,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<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -92,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<int> vec{1, 2, 3, 4};
|
||||
NDView<int, 2> mutable_view(vec.data(), Shape<2>{2, 2});
|
||||
|
||||
@@ -103,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<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
|
||||
@@ -119,7 +120,7 @@ TEST_CASE("Element reference 2D") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Element reference 3D") {
|
||||
TEST_CASE("Element reference 3D", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 24; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -138,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<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
NDView<int, 2> data(vec.data(), Shape<2>{3, 4});
|
||||
@@ -160,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<int> vec;
|
||||
for (int i = 0; i != 12; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -184,7 +185,7 @@ TEST_CASE("Multiply and divide with single value") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("elementwise assign") {
|
||||
TEST_CASE("elementwise assign", "[NDView]") {
|
||||
std::vector<int> vec(25);
|
||||
NDView<int, 2> data(vec.data(), Shape<2>{5, 5});
|
||||
|
||||
@@ -194,7 +195,7 @@ TEST_CASE("elementwise assign") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("iterators") {
|
||||
TEST_CASE("iterators", "[NDView]") {
|
||||
std::vector<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
NDView<int, 1> data(vec.data(), Shape<1>{12});
|
||||
@@ -219,7 +220,7 @@ TEST_CASE("iterators") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("divide with another NDView") {
|
||||
TEST_CASE("divide with another NDView", "[NDView]") {
|
||||
std::vector<int> vec0{9, 12, 3};
|
||||
std::vector<int> vec1{3, 2, 1};
|
||||
std::vector<int> result{3, 6, 3};
|
||||
@@ -236,7 +237,7 @@ TEST_CASE("divide with another NDView") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Retrieve shape") {
|
||||
TEST_CASE("Retrieve shape", "[NDView]") {
|
||||
std::vector<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
NDView<int, 2> data(vec.data(), Shape<2>{3, 4});
|
||||
@@ -244,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<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -256,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<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -268,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<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -280,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<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
auto v = aare::make_view(vec);
|
||||
@@ -289,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<std::byte> 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<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
NDView<int, 2> 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);
|
||||
}
|
||||
+7
-8
@@ -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,
|
||||
@@ -46,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) {
|
||||
@@ -68,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);
|
||||
@@ -101,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
|
||||
|
||||
+2
-2
@@ -20,7 +20,7 @@ bool complete_ROI(const ROI &roi, const DetectorGeometry &geometry) {
|
||||
|
||||
bool complete_ROI(const std::vector<ROI> &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<ROIGeometry> &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);
|
||||
|
||||
+199
-143
@@ -9,6 +9,7 @@
|
||||
#include "aare/logger.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -23,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<GapPixels> gap_pixels)
|
||||
: m_master(fname) {
|
||||
|
||||
m_mode = mode;
|
||||
@@ -49,11 +51,69 @@ RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode)
|
||||
|
||||
std::optional<size_t> 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);
|
||||
|
||||
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<uint8_t>(gap_pixels->fill_value);
|
||||
break;
|
||||
case 16:
|
||||
detail::fill_as<uint16_t>(gap_pixels->fill_value);
|
||||
break;
|
||||
case 32:
|
||||
detail::fill_as<uint32_t>(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<ssize_t>(roi.pixels_y()),
|
||||
static_cast<ssize_t>(roi.pixels_x())});
|
||||
}
|
||||
}
|
||||
if (!min_frames) {
|
||||
@@ -197,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() {
|
||||
@@ -212,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(); }
|
||||
@@ -244,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<size_t>(m_roi_shapes.at(roi_index)[0]);
|
||||
}
|
||||
size_t RawFile::cols() const {
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
@@ -255,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<size_t>(m_roi_shapes.at(roi_index)[1]);
|
||||
}
|
||||
size_t RawFile::bitdepth() const { return m_master.bitdepth(); }
|
||||
|
||||
@@ -302,7 +359,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()));
|
||||
@@ -328,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<uint32_t>(rows(roi_index)),
|
||||
static_cast<uint32_t>(cols(roi_index)),
|
||||
Dtype::from_bitdepth(m_master.bitdepth()));
|
||||
std::byte *frame_buffer = f.data();
|
||||
get_frame_into(frame_index, frame_buffer, roi_index);
|
||||
@@ -338,6 +395,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<size_t> 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<size_t> frame_indices(n_parts, frame_index);
|
||||
if (n_parts == 1) {
|
||||
return frame_indices;
|
||||
}
|
||||
|
||||
std::vector<size_t> 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<size_t>(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 +447,106 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer,
|
||||
"frames (indices are zero-based)",
|
||||
frame_index, total_frames()));
|
||||
}
|
||||
std::vector<size_t> frame_numbers(
|
||||
m_master.roi_geometries().at(roi_index).num_modules_in_roi());
|
||||
std::vector<size_t> 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);
|
||||
}
|
||||
|
||||
// 1. if frame number vector is the same break
|
||||
while (!all_equal(frame_numbers)) {
|
||||
|
||||
// 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()));
|
||||
|
||||
// 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_gap_pixels) {
|
||||
switch (m_master.bitdepth()) {
|
||||
case 8:
|
||||
assemble_with_gaps<uint8_t>(frame_buffer, roi_index, frame_indices,
|
||||
header);
|
||||
break;
|
||||
case 16:
|
||||
assemble_with_gaps<uint16_t>(frame_buffer, roi_index, frame_indices,
|
||||
header);
|
||||
break;
|
||||
case 32:
|
||||
assemble_with_gaps<uint32_t>(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;
|
||||
}
|
||||
|
||||
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];
|
||||
const size_t bytes_per_pixel = m_master.bitdepth() / bits_per_byte;
|
||||
const size_t roi_width = roi.pixels_x();
|
||||
|
||||
// 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;
|
||||
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<size_t>(pos.width);
|
||||
const auto height = static_cast<size_t>(pos.height);
|
||||
auto &subfile = *m_subfiles[roi_index][part_idx];
|
||||
subfile.seek(frame_indices[part_idx]);
|
||||
|
||||
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;
|
||||
}
|
||||
std::byte *dest =
|
||||
frame_buffer + (static_cast<size_t>(pos.origin_y) * roi_width +
|
||||
static_cast<size_t>(pos.origin_x)) *
|
||||
bytes_per_pixel;
|
||||
|
||||
} 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<size_t>(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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void RawFile::assemble_with_gaps(std::byte *frame_buffer, size_t roi_index,
|
||||
const std::vector<size_t> &frame_indices,
|
||||
DetectorHeader *header) {
|
||||
const auto &roi = m_master.roi_geometries().at(roi_index);
|
||||
const ROI &rect = m_roi_rects.at(roi_index);
|
||||
NDView<T, 2> destination(reinterpret_cast<T *>(frame_buffer),
|
||||
m_roi_shapes.at(roi_index));
|
||||
detail::fill_gap_pixels(destination, rect, m_gap_layout,
|
||||
detail::fill_as<T>(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<const T, 2> source(
|
||||
reinterpret_cast<const T *>(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);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+351
-2
@@ -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 <catch2/catch_test_macros.hpp>
|
||||
@@ -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<uint32_t, uint32_t>({
|
||||
{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<uint16_t, 2> image) {
|
||||
REQUIRE(image.shape(0) == static_cast<ssize_t>(rows));
|
||||
REQUIRE(image.shape(1) == static_cast<ssize_t>(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<uint16_t>());
|
||||
}
|
||||
SECTION("read_into with headers") {
|
||||
NDArray<uint16_t, 2> image(
|
||||
{static_cast<ssize_t>(rows), static_cast<ssize_t>(cols)});
|
||||
std::vector<DetectorHeader> headers(files.n_modules());
|
||||
file.seek(1);
|
||||
file.read_into(reinterpret_cast<std::byte *>(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<uint16_t>());
|
||||
}
|
||||
}
|
||||
SECTION("generic File") {
|
||||
File reader(files.master_path());
|
||||
auto frame = reader.read_frame(1);
|
||||
check(frame.view<uint16_t>());
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/// Compare a frame read with gap pixels against the free function applied
|
||||
/// to the same frame read without gaps.
|
||||
template <typename T>
|
||||
bool matches_gap_oracle(Frame &gapped, Frame &plain, const ROI &roi,
|
||||
const GapPixels &gaps) {
|
||||
auto expected =
|
||||
insert_gap_pixels(NDView<const T, 2>(plain.view<T>()), roi, gaps);
|
||||
auto actual = gapped.view<T>();
|
||||
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<uint8_t>(gapped, plain, roi, gaps);
|
||||
case 16:
|
||||
return matches_gap_oracle<uint16_t>(gapped, plain, roi, gaps);
|
||||
case 32:
|
||||
return matches_gap_oracle<uint32_t>(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<uint32_t, uint32_t>({
|
||||
{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<ssize_t>(files.cols()), 0,
|
||||
static_cast<ssize_t>(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<uint16_t>(gaps.fill_value);
|
||||
|
||||
RawFile file(files.master_path(), "r", gaps);
|
||||
REQUIRE(file.gap_pixels() == gaps);
|
||||
REQUIRE(file.rows() == static_cast<size_t>(shape[0]));
|
||||
REQUIRE(file.cols() == static_cast<size_t>(shape[1]));
|
||||
REQUIRE(file.pixels_per_frame() ==
|
||||
static_cast<size_t>(shape[0] * shape[1]));
|
||||
REQUIRE(file.bytes_per_frame() == file.pixels_per_frame() * 2);
|
||||
|
||||
std::vector<DetectorHeader> headers(files.n_modules());
|
||||
NDArray<uint16_t, 2> image(shape);
|
||||
file.read_into(reinterpret_cast<std::byte *>(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<ssize_t>(row)),
|
||||
layout.x.gapped(static_cast<ssize_t>(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<size_t>(shape[0]));
|
||||
REQUIRE(frame.cols() == static_cast<size_t>(shape[1]));
|
||||
REQUIRE(frame.view<uint16_t>() == 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<const uint16_t, 2>(second_plain.view<uint16_t>()), detector,
|
||||
gaps);
|
||||
double gapped_total = 0;
|
||||
double expected_total = 0;
|
||||
auto view = frames[0].view<uint16_t>();
|
||||
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<ssize_t, 2> shape;
|
||||
std::optional<ModuleGaps> module_gaps;
|
||||
};
|
||||
const auto test = GENERATE(values<Case>({
|
||||
{"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<size_t>(test.shape[0]));
|
||||
REQUIRE(gapped.cols() == static_cast<size_t>(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<size_t>(test.shape[0]));
|
||||
REQUIRE(gapped_frame.cols() == static_cast<size_t>(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";
|
||||
|
||||
+11
-11
@@ -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 +
|
||||
@@ -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<UDPPortPosition>(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<size_t>(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<ssize_t>(m_pixels_x), 0,
|
||||
|
||||
+1
-1
@@ -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)$)");
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
#include <aare/algorithm.hpp>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
using aare::ssize_t;
|
||||
|
||||
TEST_CASE("Find the closed index in a 1D array", "[algorithm]") {
|
||||
aare::NDArray<double, 1> arr({5});
|
||||
for (ssize_t i = 0; i < arr.size(); i++) {
|
||||
|
||||
+3
-2
@@ -10,6 +10,7 @@ using Catch::Matchers::WithinAbs;
|
||||
#include <vector>
|
||||
|
||||
using aare::BitOffset;
|
||||
using aare::ssize_t;
|
||||
|
||||
TEST_CASE("test_adc_sar_05_decode64to16") {
|
||||
uint64_t input = 0;
|
||||
@@ -24,7 +25,7 @@ TEST_CASE("test_adc_sar_05_decode64to16") {
|
||||
// test all bits by iteratting through the bitlist
|
||||
std::vector<int> 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));
|
||||
}
|
||||
@@ -94,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<uint8_t> buffer(8);
|
||||
std::memcpy(buffer.data(), &word, sizeof(word));
|
||||
aare::NDView<const uint8_t, 2> bytes(buffer.data(), {1, 8});
|
||||
|
||||
+34
-12
@@ -267,9 +267,14 @@ template <typename Model>
|
||||
void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
|
||||
NDView<double, 3> y, NDView<double, 3> y_err,
|
||||
NDView<double, 3> par_out, NDView<double, 3> err_out,
|
||||
NDView<double, 2> chi2_out, int n_threads) {
|
||||
constexpr std::size_t npar = Model::npar;
|
||||
detail::check_fit_3d_shapes<Model>(x, y, y_err, par_out, err_out, chi2_out);
|
||||
NDView<double, 2> chi2_out, int n_threads,
|
||||
std::optional<const NDView<size_t, 3>> 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<Model>(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();
|
||||
@@ -280,14 +285,31 @@ void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
|
||||
std::array<double, npar> err{};
|
||||
for (ssize_t row = first_row; row < last_row; row++) {
|
||||
for (ssize_t col = 0; col < y.shape(1); col++) {
|
||||
NDView<double, 1> 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<size_t>(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<double, 1> values(&y(row, col, start_range),
|
||||
{num_y_samples});
|
||||
NDView<double, 1> errors =
|
||||
has_errors ? NDView<double, 1>(&y_err(row, col, 0),
|
||||
{y_err.shape(2)})
|
||||
: NDView<double, 1>{};
|
||||
has_errors
|
||||
? NDView<double, 1>(&y_err(row, col, start_range),
|
||||
{num_y_samples})
|
||||
: NDView<double, 1>{};
|
||||
|
||||
NDView<double, 1> 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)
|
||||
@@ -317,10 +339,10 @@ void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
|
||||
NDView<double, 1>); \
|
||||
template NDArray<double, 1> fit_pixel<Model>( \
|
||||
const FitModel<Model> &, NDView<double, 1>, NDView<double, 1>); \
|
||||
template void fit_3d<Model>(const FitModel<Model> &, NDView<double, 1>, \
|
||||
NDView<double, 3>, NDView<double, 3>, \
|
||||
NDView<double, 3>, NDView<double, 3>, \
|
||||
NDView<double, 2>, int);
|
||||
template void fit_3d<Model>( \
|
||||
const FitModel<Model> &, NDView<double, 1>, NDView<double, 3>, \
|
||||
NDView<double, 3>, NDView<double, 3>, NDView<double, 3>, \
|
||||
NDView<double, 2>, int, std::optional<const NDView<size_t, 3>>);
|
||||
|
||||
AARE_INSTANTIATE_FIT(model::Gaussian)
|
||||
AARE_INSTANTIATE_FIT(model::GaussianErfcPlateau)
|
||||
|
||||
@@ -17,6 +17,7 @@
|
||||
using aare::Minimizer;
|
||||
using aare::NDArray;
|
||||
using aare::NDView;
|
||||
using aare::ssize_t;
|
||||
using Catch::Approx;
|
||||
|
||||
namespace {
|
||||
@@ -1099,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<double>::quiet_NaN();
|
||||
|
||||
constexpr ssize_t n = 10;
|
||||
static constexpr ssize_t n = 10; // static: used inside GENERATE's lambda
|
||||
NDArray<double, 1> x({n});
|
||||
NDArray<double, 1> y({n});
|
||||
NDArray<double, 1> y_err({n}, 1.0);
|
||||
|
||||
Loaded 100 of 110 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user