mirror of
https://github.com/slsdetectorgroup/aare.git
synced 2026-11-23 15:57:53 +01:00
Merge branch 'main' into dev/jungfraucalibration
This commit is contained in:
51 files changed
+1869
-174
No files matched your search
@@ -19,13 +19,51 @@ jobs:
|
||||
matrix:
|
||||
os: [ubuntu-latest, macos-latest, windows-latest]
|
||||
|
||||
env:
|
||||
# Job level so that the build and the statistics step talk to the same
|
||||
# sccache server configured for the GitHub Actions cache
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: mozilla-actions/sccache-action@v0.0.11
|
||||
with:
|
||||
version: "v0.18.0"
|
||||
|
||||
# Without an MSVC environment scikit-build-core falls back to the Visual
|
||||
# Studio generator on Windows, and MSBuild ignores the compiler launcher
|
||||
- uses: TheMrMilchmann/setup-msvc-dev@v4.1.0
|
||||
if: runner.os == 'Windows'
|
||||
with:
|
||||
arch: x64
|
||||
|
||||
# Linux wheels build inside a manylinux container, which needs its own
|
||||
# sccache binary and the cache credentials the action exported; its
|
||||
# statistics are printed after each wheel since the host cannot see them.
|
||||
- name: Build wheels
|
||||
run: pipx run cibuildwheel==3.4.0
|
||||
env:
|
||||
CIBW_ENVIRONMENT_WINDOWS: CMAKE_GENERATOR=Ninja
|
||||
CIBW_REPAIR_WHEEL_COMMAND_LINUX: >-
|
||||
auditwheel repair -w {dest_dir} {wheel} && sccache --show-stats
|
||||
CIBW_CONFIG_SETTINGS: >-
|
||||
cmake.define.CMAKE_C_COMPILER_LAUNCHER=sccache
|
||||
cmake.define.CMAKE_CXX_COMPILER_LAUNCHER=sccache
|
||||
cmake.define.CMAKE_DISABLE_PRECOMPILE_HEADERS=ON
|
||||
CIBW_ENVIRONMENT_PASS_LINUX: >-
|
||||
SCCACHE_GHA_ENABLED ACTIONS_RESULTS_URL ACTIONS_RUNTIME_TOKEN
|
||||
ACTIONS_CACHE_SERVICE_V2
|
||||
CIBW_BEFORE_ALL_LINUX: >-
|
||||
curl -sSL https://github.com/mozilla/sccache/releases/download/v0.18.0/sccache-v0.18.0-x86_64-unknown-linux-musl.tar.gz
|
||||
| tar -xz -C /usr/local/bin --strip-components=1 --wildcards '*/sccache'
|
||||
&& chmod +x /usr/local/bin/sccache
|
||||
run: pipx run cibuildwheel==4.3.0
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
- name: Compiler cache statistics
|
||||
if: runner.os != 'Linux'
|
||||
run: sccache --show-stats
|
||||
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: cibw-wheels-${{ matrix.os }}-${{ strategy.job-index }}
|
||||
path: ./wheelhouse/*.whl
|
||||
@@ -34,12 +72,12 @@ jobs:
|
||||
name: Build source distribution
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Build sdist
|
||||
run: pipx run build --sdist
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
- uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: cibw-sdist
|
||||
path: dist/*.tar.gz
|
||||
@@ -54,7 +92,7 @@ jobs:
|
||||
# or, alternatively, upload to PyPI on every tag starting with 'v' (remove on: release above to use this)
|
||||
# if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v')
|
||||
steps:
|
||||
- uses: actions/download-artifact@v4
|
||||
- uses: actions/download-artifact@v8
|
||||
with:
|
||||
# unpacks all CIBW artifacts into dist/
|
||||
pattern: cibw-*
|
||||
|
||||
@@ -9,25 +9,42 @@ jobs:
|
||||
build:
|
||||
runs-on: windows-latest
|
||||
|
||||
env:
|
||||
# sccache keeps compiled objects in the GitHub Actions cache, so later
|
||||
# runs only recompile the translation units a change affects
|
||||
SCCACHE_GHA_ENABLED: "true"
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v6
|
||||
|
||||
- uses: actions/setup-python@v5
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: "3.12"
|
||||
|
||||
- name: Install Python dependencies
|
||||
run: python -m pip install ninja numpy matplotlib pytest pytest-check boost-histogram
|
||||
|
||||
# Puts cl.exe on the path so that CMake can use the Ninja generator
|
||||
- uses: ilammy/msvc-dev-cmd@v1
|
||||
# Puts cl.exe on the path so that CMake can use the Ninja generator.
|
||||
# Pinned to a release tag: the v4 ref of this action is a branch.
|
||||
- uses: TheMrMilchmann/setup-msvc-dev@v4.1.0
|
||||
with:
|
||||
arch: x64
|
||||
|
||||
- uses: mozilla-actions/sccache-action@v0.0.11
|
||||
with:
|
||||
version: "v0.18.0"
|
||||
|
||||
# Precompiled headers are disabled: sccache cannot cache MSVC
|
||||
# compilations that use one
|
||||
- name: Configure
|
||||
run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON
|
||||
run: cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DAARE_TESTS=ON -DAARE_PYTHON_BINDINGS=ON -DAARE_WARNINGS_AS_ERRORS=ON -DCMAKE_C_COMPILER_LAUNCHER=sccache -DCMAKE_CXX_COMPILER_LAUNCHER=sccache -DCMAKE_DISABLE_PRECOMPILE_HEADERS=ON
|
||||
|
||||
- name: Build
|
||||
run: cmake --build build
|
||||
|
||||
- name: Compiler cache statistics
|
||||
run: sccache --show-stats
|
||||
|
||||
- name: C++ unit tests
|
||||
run: ctest --test-dir build --output-on-failure -j4
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -389,6 +389,7 @@ set(PUBLICHEADERS
|
||||
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,6 +415,7 @@ set(SourceFiles
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ROIGeometry.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/GapPixels.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/DataSetAggregation.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Dtype.cpp
|
||||
@@ -486,6 +488,7 @@ if(AARE_TESTS)
|
||||
${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
|
||||
|
||||
+20
@@ -11,6 +11,26 @@
|
||||
build, so releases publish them to PyPI alongside the Linux and macOS
|
||||
wheels.
|
||||
- Added ``read_columns`` to JungfrauDataFile to only read selected columns
|
||||
- added ``NDView::sub_view(index)`` operator returns a subview at index along dimension 0
|
||||
- Added ``GapPixels`` with ``insert_gap_pixels`` and ``gapped_shape`` to
|
||||
insert gap pixels into Jungfrau and Eiger images in memory: 2 pixel gaps
|
||||
at the chip boundaries inside each module and, only when ``ModuleGaps``
|
||||
is set, gaps between modules. Gap positions follow detector coordinates
|
||||
before any ROI. Gap pixels receive a fill value or, with
|
||||
``split_counts``, half of the neighbouring double size pixel.
|
||||
|
||||
### Other:
|
||||
|
||||
- ``RawFile`` assembles multi-module frames through one placement path with
|
||||
a scratch buffer allocated once at open, instead of allocating a module
|
||||
buffer for every frame.
|
||||
|
||||
### Bugfixes:
|
||||
|
||||
- Fixed ``Matterhorn10Transform`` with 4 bit dynamic range and
|
||||
``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
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
GapPixels
|
||||
=============
|
||||
|
||||
Jungfrau and Eiger modules are built from 256x256 pixel chips. The pixels
|
||||
at a chip edge are physically double size, so an image that places the
|
||||
chips next to each other is distorted. Gap pixels restore the geometry by
|
||||
inserting pixels at every chip boundary inside a module and, optionally,
|
||||
gaps between modules.
|
||||
|
||||
Gap positions are determined in detector coordinates before any ROI.
|
||||
A ROI only receives the gaps that fall strictly inside it, so a ROI that
|
||||
starts at column 256 has no gap on its left edge.
|
||||
|
||||
Configuration
|
||||
-------------
|
||||
|
||||
``GapPixels`` holds the configuration. The chip size (256 pixels) and the
|
||||
module size (1024x512 pixels) are fixed. An Eiger quad (512x512 pixels)
|
||||
needs no special handling, since its only chip boundaries are at pixel 256.
|
||||
Gaps of up to 1024 pixels are supported, far beyond the 2 to 10 pixels of
|
||||
a real detector, and detector coordinates are limited to 2^28.
|
||||
|
||||
================ ================ ===========================================
|
||||
Field Default Meaning
|
||||
================ ================ ===========================================
|
||||
``chip_gap`` 2 Pixels inserted at each chip boundary
|
||||
inside a module. Source column 255 expands
|
||||
to the right and column 256 to the left.
|
||||
``module_gaps`` unset ``ModuleGaps{x, y}`` inserted at module
|
||||
boundaries. Unset means no pixels are
|
||||
inserted between modules.
|
||||
``ModuleGaps{8, 36}`` matches the
|
||||
slsDetectorPackage GUI.
|
||||
``fill_value`` 0 Value written to gap pixels, converted to
|
||||
the pixel type. Finite values wrap for
|
||||
integer pixels; NaN, infinity and
|
||||
magnitudes of 2^63 or more raise for
|
||||
integer pixels. Module gaps always
|
||||
receive this value.
|
||||
``split_counts`` false Split the counts of the double size edge
|
||||
pixels between the pixel and its gap pixel
|
||||
instead of writing the fill value.
|
||||
``seed`` unset Seed for the random assignment of integer
|
||||
remainders in split mode.
|
||||
================ ================ ===========================================
|
||||
|
||||
Image sizes with the default configuration and with ``ModuleGaps{8, 36}``:
|
||||
|
||||
====================================== ========== ========= ===================
|
||||
Detector range Ungapped Defaults ``ModuleGaps{8,36}``
|
||||
====================================== ========== ========= ===================
|
||||
One module, columns 1024 1030 1030
|
||||
Two modules side by side, columns 2048 2060 2068
|
||||
Two modules stacked, rows 1024 1028 1064
|
||||
ROI columns 100 to 400 300 302 302
|
||||
ROI columns 256 to 512 256 256 256
|
||||
====================================== ========== ========= ===================
|
||||
|
||||
Split counts
|
||||
------------
|
||||
|
||||
With ``split_counts`` every double size pixel at a chip boundary is halved
|
||||
between itself and its gap pixel. Integer pixels put an odd remainder on
|
||||
one side at random; floating point pixels are halved exactly. Columns are
|
||||
split first and rows second, so a pixel at a chip corner ends up in four
|
||||
parts with its total preserved. Module gaps are not split and keep the
|
||||
fill value. Splitting only happens where a gap pixel is inserted, so an
|
||||
edge pixel on a ROI border keeps its full value. Split mode requires a
|
||||
chip gap of 2.
|
||||
|
||||
Images in memory
|
||||
----------------
|
||||
|
||||
``insert_gap_pixels`` inserts gap pixels into an image in memory, such as a
|
||||
calibration map or a pedestal, and returns the gapped copy. The ROI gives
|
||||
the detector coordinates of the image, so an image that covers part of the
|
||||
detector receives exactly the gaps that fall inside it.
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
#include "aare/GapPixels.hpp"
|
||||
|
||||
aare::NDArray<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
|
||||
@@ -44,6 +44,7 @@ AARE
|
||||
NDView
|
||||
Frame
|
||||
File
|
||||
GapPixels
|
||||
MultiThreadedFileReader
|
||||
Dtype
|
||||
Cluster
|
||||
|
||||
@@ -8,6 +8,7 @@ File I/O
|
||||
pyClusterFile
|
||||
pyCtbRawFile
|
||||
pyFile
|
||||
pyGapPixels
|
||||
pyJungfrauDataFile
|
||||
pyRawFile
|
||||
pyRawMasterFile
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
GapPixels
|
||||
===================
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
|
||||
Jungfrau and Eiger modules are built from 256x256 pixel chips with double
|
||||
size pixels at the chip edges. Gap pixels restore the geometry by inserting
|
||||
pixels at every chip boundary inside a module and, optionally, gaps between
|
||||
modules.
|
||||
Gap positions are determined in detector coordinates before any ROI, so a
|
||||
ROI only receives the gaps that fall strictly inside it.
|
||||
|
||||
The chip size (256 pixels) and the module size (1024x512 pixels) are
|
||||
fixed. An Eiger quad (512x512 pixels) needs no special handling, since its
|
||||
only chip boundaries are at pixel 256.
|
||||
|
||||
================ ================ ===========================================
|
||||
Field Default Meaning
|
||||
================ ================ ===========================================
|
||||
``chip_gap`` 2 Pixels inserted at each chip boundary
|
||||
inside a module.
|
||||
``module_gaps`` None ``ModuleGaps(x, y)`` inserted at module
|
||||
boundaries. None means no pixels are
|
||||
inserted between modules.
|
||||
``ModuleGaps(8, 36)`` matches the
|
||||
slsDetectorPackage GUI.
|
||||
``fill_value`` 0 Value written to gap pixels, converted to
|
||||
the pixel dtype. Module gaps always
|
||||
receive this value.
|
||||
``split_counts`` False Split the counts of the double size edge
|
||||
pixels between the pixel and its gap
|
||||
pixel. Integer remainders go to one side
|
||||
at random. Requires a chip gap of 2.
|
||||
``seed`` None Seed for the random remainders.
|
||||
================ ================ ===========================================
|
||||
|
||||
A single Jungfrau module of ``(512, 1024)`` pixels becomes ``(514, 1030)``
|
||||
with the defaults. Two stacked modules become ``(1028, 1030)`` with the
|
||||
defaults and ``(1064, 1030)`` with ``ModuleGaps(8, 36)``.
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from aare import GapPixels, ModuleGaps, ROI, gapped_shape, insert_gap_pixels
|
||||
|
||||
# defaults: chip gaps of 2 filled with 0, (512, 1024) -> (514, 1030)
|
||||
gapped = insert_gap_pixels(image)
|
||||
|
||||
# module gaps as in the slsDetectorPackage GUI, counts split at chip edges
|
||||
gaps = GapPixels(module_gaps=ModuleGaps(8, 36), split_counts=True, seed=1)
|
||||
gapped = insert_gap_pixels(image, gaps)
|
||||
|
||||
# an image that covers columns 100 to 400 of the first ten rows
|
||||
roi = ROI(100, 400, 0, 10)
|
||||
gapped_shape(roi) # (10, 302)
|
||||
part = insert_gap_pixels(image[:10, 100:400], gaps, roi=roi)
|
||||
|
||||
``insert_gap_pixels`` accepts 2D ``uint8``, ``uint16``, ``uint32``,
|
||||
``int32``, ``float32`` and ``float64`` arrays and returns a new array of the
|
||||
same dtype. Pass ``roi`` when the image covers part of the detector.
|
||||
``gapped_shape`` returns the shape of the gapped image of a ROI.
|
||||
|
||||
.. autoclass:: GapPixels
|
||||
:members:
|
||||
:undoc-members:
|
||||
|
||||
.. autoclass:: ModuleGaps
|
||||
:members:
|
||||
:undoc-members:
|
||||
|
||||
.. autofunction:: insert_gap_pixels
|
||||
|
||||
.. autofunction:: gapped_shape
|
||||
@@ -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
|
||||
@@ -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;
|
||||
|
||||
|
||||
@@ -26,6 +26,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{};
|
||||
|
||||
@@ -154,6 +158,16 @@ class RawFile : public FileInterface {
|
||||
std::runtime_error frame_error(size_t frame_index,
|
||||
const std::string &message) const;
|
||||
|
||||
/**
|
||||
* @brief Frame index to read from each module part of a ROI so that all
|
||||
* parts hold the same detector frame number. Parts whose frame number
|
||||
* lags are advanced; the index never moves backwards.
|
||||
* @throws std::runtime_error if a part runs out of frames while
|
||||
* synchronizing
|
||||
*/
|
||||
std::vector<size_t> synchronized_frame_indices(size_t frame_index,
|
||||
size_t roi_index);
|
||||
|
||||
/**
|
||||
* @brief read the frame at the given frame index into the image buffer
|
||||
* @param frame_index frame number to read
|
||||
|
||||
@@ -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
|
||||
|
||||
+7
-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]
|
||||
@@ -34,6 +35,9 @@ build = "cp{312,313,314}-win_amd64"
|
||||
|
||||
[tool.scikit-build]
|
||||
build.verbose = true
|
||||
# A fixed build directory keeps the absolute paths of the compiled sources
|
||||
# stable between runs, which sccache needs for a cache hit
|
||||
build-dir = "build/{wheel_tag}"
|
||||
cmake.build-type = "Release"
|
||||
install.components = ["python"]
|
||||
|
||||
|
||||
@@ -25,6 +25,7 @@ from ._aare import Pedestal_d, Pedestal_f, ClusterFinder_Cluster3x3i, VarCluster
|
||||
from ._aare import DetectorType, FrameDiscardPolicy, ReadoutMode
|
||||
from ._aare import hitmap
|
||||
from ._aare import ROI
|
||||
from ._aare import GapPixels, ModuleGaps, insert_gap_pixels, gapped_shape
|
||||
from ._aare import xy
|
||||
from ._aare import corner
|
||||
|
||||
|
||||
@@ -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
|
||||
)
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/ClusterFile.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterCollector.hpp"
|
||||
#include "aare/ClusterFileSink.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <pybind11/operators.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"
|
||||
|
||||
|
||||
@@ -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,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/calibration.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/JungfrauDataFile.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
|
||||
@@ -15,6 +15,7 @@
|
||||
#include "bind_Defs.hpp"
|
||||
#include "bind_Eta.hpp"
|
||||
#include "bind_FastPedestal.hpp"
|
||||
#include "bind_GapPixels.hpp"
|
||||
#include "bind_Interpolator.hpp"
|
||||
#include "bind_MultiThreadedFileReader.hpp"
|
||||
#include "bind_Pedestal.hpp"
|
||||
@@ -157,6 +158,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);
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/VarClusterFinder.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
|
||||
@@ -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()
|
||||
@@ -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,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);
|
||||
}
|
||||
}
|
||||
+35
-18
@@ -16,7 +16,7 @@ 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);
|
||||
|
||||
@@ -34,7 +34,7 @@ TEST_CASE("Calculate size from a shape") {
|
||||
REQUIRE(num_elements(shape5) == 10485760000);
|
||||
}
|
||||
|
||||
TEST_CASE("Element reference 1D") {
|
||||
TEST_CASE("Element reference 1D", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -47,7 +47,7 @@ TEST_CASE("Element reference 1D") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Assign elements through () and []") {
|
||||
TEST_CASE("Assign elements through () and []", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -80,7 +80,7 @@ TEST_CASE("Assign elements through () and []") {
|
||||
REQUIRE(data[9] == 9);
|
||||
}
|
||||
|
||||
TEST_CASE("Element reference 1D with a const NDView") {
|
||||
TEST_CASE("Element reference 1D with a const NDView", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 10; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -93,7 +93,7 @@ TEST_CASE("Element reference 1D with a const NDView") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Convert a mutable NDView to a const NDView") {
|
||||
TEST_CASE("Convert a mutable NDView to a const NDView", "[NDView]") {
|
||||
std::vector<int> vec{1, 2, 3, 4};
|
||||
NDView<int, 2> mutable_view(vec.data(), Shape<2>{2, 2});
|
||||
|
||||
@@ -104,7 +104,7 @@ TEST_CASE("Convert a mutable NDView to a const NDView") {
|
||||
REQUIRE(const_view.strides() == mutable_view.strides());
|
||||
}
|
||||
|
||||
TEST_CASE("Element reference 2D") {
|
||||
TEST_CASE("Element reference 2D", "[NDView]") {
|
||||
std::vector<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
|
||||
@@ -120,7 +120,7 @@ TEST_CASE("Element reference 2D") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Element reference 3D") {
|
||||
TEST_CASE("Element reference 3D", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 24; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -139,7 +139,7 @@ TEST_CASE("Element reference 3D") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Plus and minus with single value") {
|
||||
TEST_CASE("Plus and minus with single value", "[NDView]") {
|
||||
std::vector<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
NDView<int, 2> data(vec.data(), Shape<2>{3, 4});
|
||||
@@ -161,7 +161,7 @@ TEST_CASE("Plus and minus with single value") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Multiply and divide with single value") {
|
||||
TEST_CASE("Multiply and divide with single value", "[NDView]") {
|
||||
std::vector<int> vec;
|
||||
for (int i = 0; i != 12; ++i) {
|
||||
vec.push_back(i);
|
||||
@@ -185,7 +185,7 @@ TEST_CASE("Multiply and divide with single value") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("elementwise assign") {
|
||||
TEST_CASE("elementwise assign", "[NDView]") {
|
||||
std::vector<int> vec(25);
|
||||
NDView<int, 2> data(vec.data(), Shape<2>{5, 5});
|
||||
|
||||
@@ -195,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});
|
||||
@@ -220,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};
|
||||
@@ -237,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});
|
||||
@@ -245,7 +245,7 @@ TEST_CASE("Retrieve shape") {
|
||||
REQUIRE(data.shape()[1] == 4);
|
||||
}
|
||||
|
||||
TEST_CASE("compare two views") {
|
||||
TEST_CASE("compare two views", "[NDView]") {
|
||||
std::vector<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -257,7 +257,7 @@ TEST_CASE("compare two views") {
|
||||
REQUIRE((view1 == view2));
|
||||
}
|
||||
|
||||
TEST_CASE("Compare two views with different size") {
|
||||
TEST_CASE("Compare two views with different size", "[NDView]") {
|
||||
std::vector<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -269,7 +269,7 @@ TEST_CASE("Compare two views with different size") {
|
||||
REQUIRE_FALSE(view1 == view2);
|
||||
}
|
||||
|
||||
TEST_CASE("Compare two views with same size but different shape") {
|
||||
TEST_CASE("Compare two views with same size but different shape", "[NDView]") {
|
||||
std::vector<int> vec1(12);
|
||||
std::iota(vec1.begin(), vec1.end(), 0);
|
||||
NDView<int, 2> view1(vec1.data(), Shape<2>{3, 4});
|
||||
@@ -281,7 +281,7 @@ TEST_CASE("Compare two views with same size but different shape") {
|
||||
REQUIRE_FALSE(view1 == view2);
|
||||
}
|
||||
|
||||
TEST_CASE("Create a view over a vector") {
|
||||
TEST_CASE("Create a view over a vector", "[NDView]") {
|
||||
std::vector<int> vec(12);
|
||||
std::iota(vec.begin(), vec.end(), 0);
|
||||
auto v = aare::make_view(vec);
|
||||
@@ -290,9 +290,26 @@ TEST_CASE("Create a view over a vector") {
|
||||
REQUIRE(v[11] == 11);
|
||||
}
|
||||
|
||||
TEST_CASE("NDView over byte") {
|
||||
TEST_CASE("NDView over byte", "[NDView]") {
|
||||
std::vector<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);
|
||||
}
|
||||
+78
-135
@@ -9,6 +9,7 @@
|
||||
#include "aare/logger.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <fmt/format.h>
|
||||
#include <nlohmann/json.hpp>
|
||||
|
||||
@@ -49,13 +50,17 @@ 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);
|
||||
if (!min_frames) {
|
||||
throw std::runtime_error(fmt::format(
|
||||
"No raw subfiles selected by '{}'", fname.string()));
|
||||
@@ -338,6 +343,47 @@ Frame RawFile::get_frame(size_t frame_index, const size_t roi_index) {
|
||||
|
||||
size_t RawFile::bytes_per_pixel() const { return m_master.bitdepth() / 8; }
|
||||
|
||||
std::vector<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 +395,45 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer,
|
||||
"frames (indices are zero-based)",
|
||||
frame_index, total_frames()));
|
||||
}
|
||||
std::vector<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);
|
||||
}
|
||||
const size_t bytes_per_pixel = m_master.bitdepth() / bits_per_byte;
|
||||
const size_t roi_width = roi.pixels_x();
|
||||
|
||||
// 1. if frame number vector is the same break
|
||||
while (!all_equal(frame_numbers)) {
|
||||
for (size_t part_idx = 0; part_idx != roi.num_modules_in_roi();
|
||||
++part_idx) {
|
||||
// origin and size of the part relative to the ROI
|
||||
const auto &pos = m_master.geometry().get_module_geometries(
|
||||
roi.module_indices_in_roi(part_idx));
|
||||
const auto width = static_cast<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]);
|
||||
|
||||
// 2. find the index of the minimum frame number,
|
||||
auto min_frame_idx = std::distance(
|
||||
frame_numbers.begin(),
|
||||
std::min_element(frame_numbers.begin(), frame_numbers.end()));
|
||||
std::byte *dest =
|
||||
frame_buffer + (static_cast<size_t>(pos.origin_y) * roi_width +
|
||||
static_cast<size_t>(pos.origin_x)) *
|
||||
bytes_per_pixel;
|
||||
|
||||
// 3. increase its index and update its respective frame
|
||||
// number
|
||||
frame_indices[min_frame_idx]++;
|
||||
|
||||
// 4. if we can't increase its index => throw error
|
||||
if (frame_indices[min_frame_idx] >= total_frames()) {
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
LOCATION +
|
||||
fmt::format(
|
||||
"Frame index {} out of range while synchronizing "
|
||||
"module {} for ROI {}; last data file '{}'",
|
||||
frame_indices[min_frame_idx], min_frame_idx,
|
||||
roi_index,
|
||||
m_subfiles[roi_index][min_frame_idx]
|
||||
->current_path()
|
||||
.string()));
|
||||
}
|
||||
|
||||
frame_numbers[min_frame_idx] =
|
||||
m_subfiles[roi_index][min_frame_idx]->frame_number(
|
||||
frame_indices[min_frame_idx]);
|
||||
}
|
||||
}
|
||||
|
||||
if (m_master.detector_layout().col == 1) {
|
||||
// get the part from each subfile and copy it to the frame
|
||||
for (size_t part_idx = 0;
|
||||
part_idx !=
|
||||
m_master.roi_geometries().at(roi_index).num_modules_in_roi();
|
||||
++part_idx) {
|
||||
auto corrected_idx = frame_indices[part_idx];
|
||||
|
||||
// This is where we start writing
|
||||
auto offset =
|
||||
(m_master.geometry()
|
||||
.get_module_geometries(
|
||||
m_master.roi_geometries()
|
||||
.at(roi_index)
|
||||
.module_indices_in_roi(part_idx))
|
||||
.origin_y *
|
||||
m_master.roi_geometries().at(roi_index).pixels_x() +
|
||||
m_master.geometry()
|
||||
.get_module_geometries(
|
||||
m_master.roi_geometries()
|
||||
.at(roi_index)
|
||||
.module_indices_in_roi(part_idx))
|
||||
.origin_x) *
|
||||
m_master.bitdepth() / 8;
|
||||
|
||||
if (m_master.geometry()
|
||||
.get_module_geometries(m_master.roi_geometries()
|
||||
.at(roi_index)
|
||||
.module_indices_in_roi(part_idx))
|
||||
.origin_x != 0)
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
LOCATION +
|
||||
" Implementation error. x pos not 0."); // TODO:
|
||||
// origin
|
||||
// can still
|
||||
// change if
|
||||
// roi
|
||||
// changes
|
||||
// TODO! What if the files don't match?
|
||||
m_subfiles[roi_index][part_idx]->seek(corrected_idx);
|
||||
m_subfiles[roi_index][part_idx]->read_into(frame_buffer + offset,
|
||||
header);
|
||||
if (header)
|
||||
++header;
|
||||
}
|
||||
|
||||
} else {
|
||||
// TODO! should we read row by row?
|
||||
|
||||
// create a buffer large enough to hold a full module
|
||||
auto bytes_per_part =
|
||||
m_master.pixels_y() * m_master.pixels_x() * m_master.bitdepth() /
|
||||
8; // TODO! replace with image_size_in_bytes // TODO
|
||||
// shouldnt it only be the module size? - check
|
||||
|
||||
auto *part_buffer = new std::byte[bytes_per_part];
|
||||
|
||||
// TODO! if we have many submodules we should reorder them on
|
||||
// the module level
|
||||
|
||||
for (size_t part_idx = 0;
|
||||
part_idx !=
|
||||
m_master.roi_geometries().at(roi_index).num_modules_in_roi();
|
||||
++part_idx) {
|
||||
auto pos = m_master.geometry().get_module_geometries(
|
||||
m_master.roi_geometries().at(roi_index).module_indices_in_roi(
|
||||
part_idx));
|
||||
auto corrected_idx = frame_indices[part_idx];
|
||||
|
||||
m_subfiles[roi_index][part_idx]->seek(corrected_idx);
|
||||
m_subfiles[roi_index][part_idx]->read_into(part_buffer, header);
|
||||
if (header)
|
||||
++header;
|
||||
|
||||
for (size_t cur_row = 0; cur_row < static_cast<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;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#define FRIEND_TEST(test_name) friend void test_name##_impl();
|
||||
|
||||
#define TEST_CASE_PRIVATE_FWD(test_name) \
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
#include <catch2/interfaces/catch_interfaces_capture.hpp>
|
||||
|
||||
Reference in new issue
Block a user