mirror of
https://github.com/slsdetectorgroup/aare.git
synced 2026-11-24 01:27:54 +01:00
solved merge conflicts
This commit is contained in:
commit
59372310b0
43 files changed
+1265
-367
No files matched your search
+3
-1
@@ -387,6 +387,7 @@ set(PUBLICHEADERS
|
||||
include/aare/RawMasterFile.hpp
|
||||
include/aare/RawSubFile.hpp
|
||||
include/aare/VarClusterFinder.hpp
|
||||
include/aare/to_string.hpp
|
||||
include/aare/utils/task.hpp
|
||||
include/aare/utils/ifstream_helpers.hpp
|
||||
include/aare/utils/math_helpers.hpp)
|
||||
@@ -447,7 +448,7 @@ if(AARE_VERBOSE)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_VERBOSE)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logDEBUG5)
|
||||
else()
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logERROR)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logWARNING)
|
||||
endif()
|
||||
|
||||
if(AARE_CUSTOM_ASSERT)
|
||||
@@ -459,6 +460,7 @@ set_target_properties(aare_core PROPERTIES ARCHIVE_OUTPUT_DIRECTORY
|
||||
|
||||
if(AARE_TESTS)
|
||||
set(TestSources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tests/raw_file_helpers.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/algorithm.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/calibration.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/defs.test.cpp
|
||||
|
||||
+16
-3
@@ -17,7 +17,9 @@
|
||||
and ``-mtune=native`` when supported. Binaries built with this option are
|
||||
specific to the local CPU and may not be portable.
|
||||
- Support for PixeltoStrixelRemapping. Precomputedt maps are available of the most common sensor-module configurations of iLGAD abnd TEW sensors on the Jungfrau module.
|
||||
|
||||
- Added string representator in python for Cluster and Eta
|
||||
- Added roi slice method in python for easy slicing of numpy arrays ``array[roi.slice()]``.
|
||||
- added context manager for ``aare.RawMasterFile``
|
||||
|
||||
### API Changes:
|
||||
|
||||
@@ -45,6 +47,19 @@
|
||||
- ``TimingMode::Auto`` changed to ``TimingMode::AUTO_TIMING``, ``TimingMode::Trigger`` changed to ``TimingMode::TRIGGER_EXPOSURE``
|
||||
|
||||
### Bugfixes:
|
||||
- ``RawFile`` now derives its frame count from the shortest selected raw
|
||||
subfile series across all ROIs. Frame-number reads use the same bounds, and
|
||||
Python ``len(reader)`` returns the adjusted count. A warning is printed when
|
||||
subfile counts differ or their minimum differs from the recorded master
|
||||
count. The expected frame count is not used and master metadata is preserved.
|
||||
Warning-level logging is now enabled in non-verbose builds.
|
||||
- Raw frame, batch, ROI, and frame-number read errors now include the attempted
|
||||
frame index and file path in C++ and Python, preserving subfile error details.
|
||||
Subfile errors omit redundant master-file context and C++ source locations;
|
||||
out-of-range errors include the available frame count.
|
||||
Synchronization errors identify the last raw data file for the affected module.
|
||||
Top-level frame bounds errors state the total frame count and that indices
|
||||
are zero-based.
|
||||
- Fixed ``ClusterVector`` move operations to transfer storage instead of
|
||||
copying every cluster.
|
||||
- Validate that ``ClusterVector`` masks are one-dimensional, C-contiguous
|
||||
@@ -201,5 +216,3 @@ dhanya.thattil@psi.ch
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 216 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 64 KiB |
+33
-1
@@ -1,8 +1,40 @@
|
||||
RawFile
|
||||
===============
|
||||
|
||||
``total_frames()`` is the minimum actual frame count across all selected
|
||||
``RawSubFile`` objects in all ROIs. Each subfile count includes its complete
|
||||
series of ``.raw`` files and is determined when the file is opened. Disabled
|
||||
UDP ports are excluded. An empty subfile makes the count zero; opening a file
|
||||
with no selected subfiles raises an error.
|
||||
|
||||
A warning is logged once on opening if the subfile counts differ or their
|
||||
minimum differs from ``master().frames_in_file()``. It reports the subfile count
|
||||
range, the master count, and the count used for reading. The master metadata
|
||||
is preserved. Its expected frame count does not affect the count used for
|
||||
reading.
|
||||
|
||||
Frame, batch, ROI, and frame-number reads use this minimum as their bound.
|
||||
Frame-number synchronization may still fail within this bound if detector
|
||||
frame numbers differ between subfiles.
|
||||
|
||||
Read errors include the attempted zero-based frame index and the failing file
|
||||
path. Errors from a data subfile identify that subfile's path and preserve
|
||||
the underlying failure reason without adding a master-file wrapper or C++
|
||||
source location. Out-of-range subfile errors also report the available frame
|
||||
count across that subfile's series. This applies to frame, batch, ROI, and
|
||||
frame-number reads, including reads through ``aare::File``.
|
||||
|
||||
The frame index is the position in the file, not the frame number recorded by
|
||||
the detector. Batch errors report the index of the frame that failed.
|
||||
|
||||
Synchronization errors identify the last ``.raw`` data file read for the module
|
||||
that ran out of frames. Requests rejected as out of range before accessing a
|
||||
subfile report the master path, since there is no single failing data file.
|
||||
The top-level frame bounds error states the number of frames in the file and
|
||||
that indices are zero-based.
|
||||
|
||||
|
||||
.. doxygenclass:: aare::RawFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:private-members:
|
||||
:private-members:
|
||||
@@ -5,6 +5,8 @@ Inclusive ROI
|
||||
Class for Region of Interest (ROI) using inclusive bounds.
|
||||
The class is primarily used in the context of pixel-to-strixel remapping.
|
||||
|
||||
An introduction to the concept of strixel-to-pixel remapping and and overview of the corresponding API can be found in :ref:`strixel_remapping_index`.
|
||||
|
||||
|
||||
.. doxygenstruct:: aare::InclusiveROI
|
||||
:members:
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
Predefined Pixel to Strixel Maps
|
||||
Predefined Strixel to Pixel Maps
|
||||
================================
|
||||
|
||||
Includes predefined pixel to strixel maps for the sensor configurations introduced in :ref:`predefined_sensor_configs`.
|
||||
Includes predefined pixel to strixel maps for the sensor configurations introduced in :ref:`predefined_sensor_configs`.
|
||||
|
||||
An introduction to the concept of strixel-to-pixel remapping and and overview of the corresponding API can be found in :ref:`strixel_remapping_index`.
|
||||
|
||||
|
||||
Predefined Maps for 2x2 cm iLGAD Sensor
|
||||
|
||||
@@ -9,6 +9,8 @@ The PSI Photon Science Detector Group produces Jungfrau modules with three diffe
|
||||
|
||||
Below are the predefined sensor configurations for all three sensor types. Detailed information about the sensor geometry, placement and rotation on the module, strixel types and their placement can be found in the dedicated sensor sections further below.
|
||||
|
||||
An introduction to the concept of strixel-to-pixel remapping and and overview of the corresponding API can be found in :ref:`strixel_remapping_index`.
|
||||
|
||||
|
||||
Predefined Sensor Configurations
|
||||
---------------------------------
|
||||
|
||||
@@ -2,7 +2,9 @@ Sensor configurations
|
||||
=====================
|
||||
|
||||
|
||||
Helper structs to define the sensor configuration, such as sensor pixel geometry, placement and rotation of the sensor on the module, the different strixel types on the sensor and its placement.
|
||||
Helper structs to define the sensor configuration, such as sensor pixel geometry, placement and rotation of the sensor on the module, the different strixel types on the sensor and its placement.
|
||||
|
||||
An introduction to the concept of strixel-to-pixel remapping and and overview of the corresponding API can be found in :ref:`strixel_remapping_index`.
|
||||
|
||||
|
||||
.. doxygenenum:: aare::remap::defs::Rotation
|
||||
@@ -15,6 +17,19 @@ Helper structs to define the sensor configuration, such as sensor pixel geometry
|
||||
.. doxygenstruct:: aare::remap::defs::Guardring
|
||||
:members:
|
||||
|
||||
.. NOTE::
|
||||
While (multiple) guardrings are part of every sensor, iLGAD sensors
|
||||
(due to their high currents and electric fields) have an additional guardring
|
||||
that extends into the area of the sensor that would normally be
|
||||
occupied by active pixels. This area and the corresponding pixels therefore
|
||||
become unusable for photon detection.
|
||||
For standard (non-iLGAD) sensors, the regular guardrings are outside the
|
||||
pixel area and do not need to be specified with this struct.
|
||||
|
||||
.. IMPORTANT::
|
||||
The :code:`Guardring` struct describes only the guardring that extends into the sensor pixel area.
|
||||
|
||||
|
||||
.. doxygenstruct:: aare::remap::defs::GroupRouting
|
||||
:members:
|
||||
|
||||
@@ -38,4 +53,12 @@ Helper structs to define the sensor configuration, such as sensor pixel geometry
|
||||
|
||||
|
||||
.. doxygenstruct:: aare::remap::defs::StrixelGroupToPixelMap
|
||||
:members:
|
||||
:members:
|
||||
|
||||
.. IMPORTANT::
|
||||
The map coordinates (row, col) are local to this strixel group and
|
||||
are geometrically associated with :code:`effective_roi`. The stored pixel index,
|
||||
however, is flattened with respect to the original user-provided ROI,
|
||||
not :code:`effective_roi`. In other words: The map provides a local strixel grid mapped to
|
||||
the corresponding ASIC pixel indices in the original user grid, and
|
||||
:code:`effective_roi` is the ROI the algorithm used for remapping.
|
||||
@@ -1,6 +1,7 @@
|
||||
Strixel to Pixel Remapping
|
||||
==============================
|
||||
Strixel to Pixel Remapping Algorithm
|
||||
====================================
|
||||
|
||||
An introduction to the concept of strixel-to-pixel remapping and and overview of the corresponding API can be found in :ref:`strixel_remapping_index`.
|
||||
|
||||
.. doxygenfunction:: aare::remap::algo::strixel_to_pixel_map
|
||||
|
||||
|
||||
@@ -1,9 +1,101 @@
|
||||
Pixel to Strixel Remapping
|
||||
.. _strixel_remapping_index:
|
||||
|
||||
Strixel to Pixel Remapping
|
||||
==============================
|
||||
|
||||
..
|
||||
maybe document what a strixel is in here how the remapping roughly works what types are predefined
|
||||
|
||||
Here the concepts behind the pixel reordering ("remapping") that needs to be applied for detectors using sensors
|
||||
with "strixel" geometry and the corresponding API interface are explained.
|
||||
|
||||
The Strixel Concept
|
||||
----------------------
|
||||
|
||||
A *strixel* is a rectangular sensor pixel.
|
||||
|
||||
The strixel's long edge is an integer multiple of the square pixel pitch
|
||||
of the ASIC to which the sensor is coupled (i.e. 75 µm for the JUNGFRAU ASIC and 25 µm for MÖNCH). Its short edge,
|
||||
in turn, is a fraction of the ASIC pixel pitch by the same integer.
|
||||
|
||||
.. IMPORTANT::
|
||||
The integer value that defines the strixel dimensioning with respect to the ASIC pixel is called the **strixel multiplicity** :math:`m`.
|
||||
|
||||
.. math::
|
||||
\begin{equation*}
|
||||
\Delta x_{\text{strixel}} = \Delta x_{\text{pixel}}\cdot m \quad \quad \Delta y_{\text{strixel}} = \frac{\Delta y_{\text{pixel}}}{m}
|
||||
\end{equation*}
|
||||
|
||||
.. figure:: ../../figures/StrixelSketch_symbols.png
|
||||
:target: ../../figures/StrixelSketch_symbols.png
|
||||
:width: 650px
|
||||
:align: center
|
||||
:alt: Strixel Sketch
|
||||
|
||||
Example snippet of a strixel sensor layout with strixel multiplicity :math:`m = 3`.
|
||||
|
||||
.. admonition:: Physics Background
|
||||
|
||||
Rectangular pixels provide a short pitch in one dimension that enables interpolation based on charge sharing
|
||||
while retaining compatibility with established readout ASICs such as JUNGFRAU and MÖNCH. Strixel sensors are
|
||||
especially important for detector applications such as **Resonant Inelastic X-ray Scattering (RIXS)** that require
|
||||
high spatial resolution in one dimension.
|
||||
|
||||
.. admonition:: Fun Fact
|
||||
|
||||
*"Strixel"* is a mashup between the words *"strip"* and *"pixel"*. The alternative version *"stripsel"* is also popular.
|
||||
|
||||
The Remapping Concept
|
||||
-------------------------
|
||||
|
||||
Each strixel on a sensor is routed to a pixel on the readout ASIC. This reshuffles the order of the sensor strixels into the order
|
||||
of the square ASIC pixels. In order to reproduce the real physical image on the sensor, we need to provide a map that uniquely
|
||||
links each physical sensor strixel to its corresponding ASIC pixel. We refer to this procedure as "remapping".
|
||||
|
||||
.. figure:: ../../figures/StrixelRemappingConcept.png
|
||||
:target: ../../figures/StrixelRemappingConcept.png
|
||||
:width: 650px
|
||||
:align: center
|
||||
:alt: Strixel Remapping Concept
|
||||
|
||||
Illustrating the remapping between an ASIC pixel grid and a sensor strixel grid with :math:`m = 3`.
|
||||
|
||||
.. IMPORTANT::
|
||||
The remapping algorithm essentially reorders chunks of ASIC pixel columns into chunks of strixel rows based
|
||||
on the strixel multiplicity.
|
||||
|
||||
The resulting map describes
|
||||
|
||||
.. math::
|
||||
\begin{equation*}
|
||||
\text{strixel}(\text{row},\,\text{col}) \rightarrow \text{flattened ASIC pixel index} = y_{\text{pixel}}\cdot n_x + x_{\text{pixel}}
|
||||
\end{equation*}
|
||||
|
||||
where :math:`x_{\text{pixel}}` and :math:`y_{\text{pixel}}` are the x- and y-coordinates (column and row) of the reference ASIC pixel,
|
||||
respectively, and :math:`n_x` is the total number of ASIC pixel columns of the reference pixel grid.
|
||||
|
||||
.. Note::
|
||||
The reference pixel grid does not necessarily have to correspond to exactly one ASIC. It could, for example, be the
|
||||
standard output of a single JUNGFRAU detector module with dimensions :math:`2\times 4` ASICs (:math:`512\times 1024` pixels).
|
||||
|
||||
API overview
|
||||
----------------
|
||||
|
||||
..
|
||||
Include block diagram
|
||||
|
||||
The API predefines known sensor configurations and provides direct map generators for these.
|
||||
|
||||
To apply the remapping to a detector image, the API provides the following utility function:
|
||||
|
||||
.. doxygenfunction:: aare::remap::algo::ApplyRemap
|
||||
|
||||
..
|
||||
TODO: Discuss groups, predefined sensors, bond shift, rotation, modulo ordering, ROIs (?) ...
|
||||
|
||||
API Documentation
|
||||
----------------
|
||||
|
||||
.. toctree::
|
||||
:maxdepth: 1
|
||||
|
||||
|
||||
@@ -3,8 +3,38 @@ RawFile
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
|
||||
``total_frames`` and ``len(reader)`` report the minimum actual frame count
|
||||
across all selected subfiles and ROIs, including each subfile's complete
|
||||
``.raw`` series. ``read()`` uses this count, and ``read_n()`` and
|
||||
``read_n_with_roi()`` limit batches to the remaining frames. Counts are
|
||||
determined when the reader is constructed.
|
||||
An empty subfile makes the count zero, and construction fails if no subfiles
|
||||
are selected.
|
||||
|
||||
The C++ logger prints one warning to stderr on opening if the subfile counts
|
||||
differ or their minimum differs from ``reader.master.frames_in_file``. The
|
||||
warning includes the count range, the recorded master count, and the count
|
||||
used for reading. Master metadata is preserved; its expected frame count
|
||||
does not affect reading bounds. Detector frame-number mismatches can still
|
||||
cause synchronization errors within these bounds.
|
||||
|
||||
Reading errors raise ``RuntimeError`` with the attempted zero-based frame index
|
||||
and the failing file path. If a data subfile fails, its path and the underlying
|
||||
failure reason are reported. Out-of-range subfile errors include the available frame count across
|
||||
that subfile's series. This applies to ``read_frame()``, ``read_n()``,
|
||||
and the ROI reading methods. The frame index is the position in the file, not
|
||||
the frame number recorded by the detector.
|
||||
|
||||
Synchronization errors also identify the last ``.raw`` data file read for the
|
||||
module that ran out of frames. An out-of-range request rejected before accessing
|
||||
a subfile reports the master path.
|
||||
|
||||
For a file containing five frames, the valid indices are 0 through 4. Attempting
|
||||
to read index 5 raises an error stating: ``Frame index 5 is out of range: file
|
||||
contains 5 frames (indices are zero-based)``.
|
||||
|
||||
.. autoclass:: RawFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
:inherited-members:
|
||||
@@ -50,18 +50,21 @@ class ClusterFinder {
|
||||
* @param image_size Image shape as (rows, columns).
|
||||
* @param nSigma Per-pixel noise threshold multiplier.
|
||||
* @param capacity Initial cluster-vector capacity.
|
||||
* @param min_pedestal_samples Minimum number of pedestal frames to
|
||||
* accumulate to get reasonable statistics
|
||||
*/
|
||||
ClusterFinder(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 1000000)
|
||||
size_t capacity = 1000000, size_t min_pedestal_samples = 1000)
|
||||
: m_image_size(image_size), m_nSigma(nSigma),
|
||||
c2(sqrt((ClusterSizeY + 1) / 2 * (ClusterSizeX + 1) / 2)),
|
||||
c3(sqrt(ClusterSizeX * ClusterSizeY)),
|
||||
m_pedestal(image_size[0], image_size[1]), m_clusters(capacity),
|
||||
m_threshold({image_size[0], image_size[1]}, 0),
|
||||
m_pedestal(image_size[0], image_size[1], min_pedestal_samples),
|
||||
m_clusters(capacity), m_threshold({image_size[0], image_size[1]}, 0),
|
||||
m_pd_corrected_frame({image_size[0], image_size[1]}, 0) {
|
||||
LOG(logDEBUG) << "ClusterFinder: "
|
||||
<< "image_size: " << image_size[0] << "x" << image_size[1]
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity;
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity
|
||||
<< ", min_pedestal_samples: " << min_pedestal_samples;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -131,17 +131,26 @@ class ClusterFinderMT {
|
||||
}
|
||||
}
|
||||
|
||||
bool output_queues_are_empty() const {
|
||||
for (auto &q : m_output_queues) {
|
||||
if (!q->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Collect all the clusters from the output queues and write them to
|
||||
* the sink
|
||||
*/
|
||||
void collect() {
|
||||
bool empty = true;
|
||||
Backoff backoff;
|
||||
while (!m_stop_requested || !empty || !m_processing_threads_stopped) {
|
||||
while (!m_stop_requested || !output_queues_are_empty() ||
|
||||
!m_processing_threads_stopped) {
|
||||
bool moved_any = false;
|
||||
for (auto &queue : m_output_queues) {
|
||||
while (auto *front = queue->frontPtr()) {
|
||||
if (auto *front = queue->frontPtr(); front != nullptr) {
|
||||
while (!m_sink.write(std::move(*front))) {
|
||||
backoff.pause();
|
||||
}
|
||||
@@ -149,7 +158,6 @@ class ClusterFinderMT {
|
||||
moved_any = true;
|
||||
}
|
||||
}
|
||||
empty = !moved_any;
|
||||
if (moved_any) {
|
||||
backoff.reset();
|
||||
} else {
|
||||
@@ -171,16 +179,19 @@ class ClusterFinderMT {
|
||||
* allocated once and recycled, so the total resident frame memory is
|
||||
* n_threads * queue_depth * frame size. Keeping the in flight data below
|
||||
* the L3 size keeps the per frame copy cheap.
|
||||
* @param min_pedestal_samples minimum number of pedestal samples to
|
||||
* accumulate before using the pedestal
|
||||
*/
|
||||
ClusterFinderMT(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 2000, size_t n_threads = 3,
|
||||
size_t queue_depth = 16)
|
||||
size_t queue_depth = 16, size_t min_pedestal_samples = 1000)
|
||||
: m_n_threads(n_threads) {
|
||||
|
||||
LOG(logDEBUG1) << "ClusterFinderMT: "
|
||||
<< "image_size: " << image_size[0] << "x"
|
||||
<< image_size[1] << ", nSigma: " << nSigma
|
||||
<< ", capacity: " << capacity
|
||||
<< ", min_pedestal_samples: " << min_pedestal_samples
|
||||
<< ", n_threads: " << n_threads
|
||||
<< ", queue_depth: " << queue_depth;
|
||||
|
||||
@@ -188,7 +199,7 @@ class ClusterFinderMT {
|
||||
m_cluster_finders.push_back(
|
||||
std::make_unique<
|
||||
ClusterFinder<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>>(
|
||||
image_size, nSigma, capacity));
|
||||
image_size, nSigma, capacity, min_pedestal_samples));
|
||||
}
|
||||
for (size_t i = 0; i < n_threads; i++) {
|
||||
m_frame_pools.emplace_back(
|
||||
|
||||
@@ -31,7 +31,7 @@ class RawFile : public FileInterface {
|
||||
|
||||
std::vector<ROIGeometry> m_ROI_geometries;
|
||||
|
||||
/// @brief total number of frames in file
|
||||
/// @brief Minimum frame count across the selected raw subfile series.
|
||||
size_t m_frames_in_file{};
|
||||
|
||||
public:
|
||||
@@ -102,6 +102,7 @@ class RawFile : public FileInterface {
|
||||
size_t bytes_per_pixel() const;
|
||||
void seek(size_t frame_index) override;
|
||||
size_t tell() override;
|
||||
/// @brief Minimum actual frame count across all subfiles and ROIs.
|
||||
size_t total_frames() const override;
|
||||
size_t rows() const override;
|
||||
/**
|
||||
@@ -148,6 +149,9 @@ class RawFile : public FileInterface {
|
||||
static DetectorHeader read_header(const std::filesystem::path &fname);
|
||||
|
||||
private:
|
||||
std::runtime_error frame_error(size_t frame_index,
|
||||
const std::string &message) const;
|
||||
|
||||
/**
|
||||
* @brief read the frame at the given frame index into the image buffer
|
||||
* @param frame_index frame number to read
|
||||
|
||||
@@ -130,6 +130,9 @@ class RawMasterFile {
|
||||
RawMasterFile(const std::filesystem::path &fpath);
|
||||
RawMasterFile(std::istream &is, const std::string &fname); // for testing
|
||||
|
||||
/// @brief Get the filename including path of the master file.
|
||||
std::filesystem::path master_fname() const { return m_fnc.master_fname(); }
|
||||
|
||||
std::filesystem::path data_fname(size_t mod_id, size_t file_id) const;
|
||||
|
||||
const std::string &version() const; //!< For example "7.2"
|
||||
@@ -192,4 +195,4 @@ class RawMasterFile {
|
||||
void retrieve_geometry();
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -84,7 +84,13 @@ class RawSubFile {
|
||||
|
||||
size_t frames_in_file() const { return m_total_frames; }
|
||||
|
||||
/// @brief Path of the current data file in the raw subfile series.
|
||||
std::filesystem::path current_path() const;
|
||||
|
||||
private:
|
||||
std::runtime_error frame_error(size_t frame_index,
|
||||
const std::string &message) const;
|
||||
|
||||
template <typename T> void read_with_map(std::byte *image_buf);
|
||||
|
||||
void parse_fname(const std::filesystem::path &fname);
|
||||
@@ -93,4 +99,4 @@ class RawSubFile {
|
||||
std::filesystem::path fpath(size_t file_index) const;
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -37,7 +37,7 @@ InclusiveROI inline update_pixel_group_placement(
|
||||
* @brief Build the strixel-to-pixel order map for one strixel group.
|
||||
* The strixel mapping is determined by the group's multiplicity and
|
||||
* modulo ordering. A reversed modulo ordering reverses the ordering
|
||||
* within each multiplicity group; it does not reverse the complete
|
||||
* within each multiplicity chunk; it does not reverse the complete
|
||||
* strixel column ordering.
|
||||
*
|
||||
* @param group_config Configuration of the strixel group to be mapped.
|
||||
@@ -97,7 +97,7 @@ strixel_to_pixel_maps(defs::SensorConfig<N> const &sensor_config,
|
||||
* Applies a given remapping rule to an input array.
|
||||
*
|
||||
* \param input Original array
|
||||
* \param order_map Rule for remapping
|
||||
* \param order_map Rule for remapping (e.g. the output of a map generator)
|
||||
* \param output Remapped array
|
||||
*/
|
||||
template <typename T>
|
||||
|
||||
@@ -25,35 +25,27 @@ namespace aare::remap::defs {
|
||||
enum class Rotation : int { Identity = 0, Rotate180 = 1 };
|
||||
|
||||
/**
|
||||
* @brief Ordering of pixel-to-strixel routing within each multiplicity group.
|
||||
* @brief Ordering of pixel-to-strixel routing within each multiplicity chunk.
|
||||
*
|
||||
* Forward:
|
||||
* Pixels are assigned to strixel rows in increasing column order.
|
||||
*
|
||||
* Reverse:
|
||||
* The ordering within each multiplicity group is reversed.
|
||||
* The ordering within each multiplicity chunk is reversed.
|
||||
*
|
||||
* Example (multiplicity = 3):
|
||||
*
|
||||
* Forward : pixel columns [0,1,2] -> strixel rows [0,1,2]
|
||||
*
|
||||
* Reverse : pixel columns [0,1,2] -> strixel rows [2,1,0]
|
||||
*
|
||||
* This affects only the ordering inside each multiplicity group.
|
||||
* It does not mirror or reorder the groups themselves.
|
||||
* This affects only the ordering inside each multiplicity chunk.
|
||||
* It does not mirror or reorder the strixel groups themselves.
|
||||
*/
|
||||
enum class ModuloOrdering { Forward, Reverse };
|
||||
|
||||
/// @brief Describes the physical guardring around a sensor to protect the ASIC
|
||||
/// from high current
|
||||
///
|
||||
/// NOTE: While (multiple) guard rings are part of every sensor, iLGAD sensors
|
||||
/// (due to their high currents and electric fields) have an additional guard
|
||||
/// ring that extends into the area of the sensor that would normally be
|
||||
/// occupied by active pixels. This area and the corresponding pixels therefore
|
||||
/// become unusable for photon detection.
|
||||
/// For standard (non-iLGAD) sensors, the regular guard rings are outside the
|
||||
/// pixel area. This Guardsring struct only describes the guard ring that
|
||||
/// occupies the pixel area. Its extents are described in number of pixels.
|
||||
struct Guardring {
|
||||
/// @brief ring width in pixels.
|
||||
int x{};
|
||||
@@ -100,9 +92,11 @@ struct GroupStrixelGeometry {
|
||||
* within a remapping group.
|
||||
*
|
||||
* The modulo ordering specifies whether the pixels belonging to each
|
||||
* multiplicity group are mapped in forward or reversed order.
|
||||
* multiplicity chunk are mapped in forward or reversed order.
|
||||
*/
|
||||
struct GroupRouting {
|
||||
/// @brief Ordering of pixel-to-strixel routing within each multiplicity
|
||||
/// chunk.
|
||||
ModuloOrdering mod_order = ModuloOrdering::Forward;
|
||||
};
|
||||
|
||||
@@ -129,7 +123,7 @@ template <std::size_t N> struct SensorConfig {
|
||||
/// @brief pixel geometry of the sensor
|
||||
SensorPixelGeometry pixel;
|
||||
|
||||
/// @brief strixel group configurations partitions the sensor into regions
|
||||
/// @brief strixel group configurations, partitions the sensor into regions
|
||||
/// with different strixel geometries and/or routing
|
||||
std::array<GroupConfig, N> group_configs;
|
||||
};
|
||||
@@ -147,7 +141,7 @@ struct SensorModulePlacement {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Result of remapping one strixel group onto the pixel grid.
|
||||
* @brief Result of remapping one strixel group onto the ASIC pixel grid.
|
||||
*
|
||||
* The order map defines a local strixel-grid coordinate system. For each
|
||||
* map position (row, col), map(row, col) contains the flattened pixel index
|
||||
@@ -161,13 +155,6 @@ struct SensorModulePlacement {
|
||||
* where (dx, dy) is the pixel position in the coordinate system of the
|
||||
* original user-provided ROI.
|
||||
*
|
||||
* NOTE: The map coordinates (row, col) are local to this strixel group and
|
||||
* are geometrically associated with effective_roi. The stored pixel index,
|
||||
* however, is flattened with respect to the original user-provided ROI,
|
||||
* not effective_roi. (I.e.: The map provides a local strixel grid mapped to
|
||||
* the correct corresponding pixel indices in the original user grid, and
|
||||
* effective_roi is the ROI the algorithm used for remapping.)
|
||||
*
|
||||
* An entry of -1 indicates that the corresponding strixel position has no
|
||||
* valid source pixel.
|
||||
*/
|
||||
|
||||
@@ -87,4 +87,12 @@ template <> FrameDiscardPolicy string_to(const std::string &arg);
|
||||
*/
|
||||
template <> DACIndex string_to(const std::string &arg);
|
||||
|
||||
/**
|
||||
* @brief Convert a corner enum to string
|
||||
* @param arg corner enum value
|
||||
* @return string representation of the corner enum
|
||||
* @throw runtime_error if the corner value is invalid
|
||||
*/
|
||||
std::string to_string(const corner &arg);
|
||||
|
||||
} // namespace aare
|
||||
@@ -18,24 +18,55 @@ def _get_class(name, cluster_size, dtype):
|
||||
|
||||
|
||||
|
||||
def ClusterFinder(image_size, cluster_size=(3,3), n_sigma=5, dtype = np.int32, capacity = 1024):
|
||||
def ClusterFinder(image_size, *, cluster_size=(3,3), n_sigma=5, dtype = np.int32, capacity = 1024, min_pedestal_samples = 1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinder object. Provides a cleaner syntax for
|
||||
the templated ClusterFinder in C++.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image_size : tuple
|
||||
The size of the image as a tuple (height, width).
|
||||
cluster_size : tuple, optional
|
||||
The size of the cluster to find as a tuple (height, width). Default is (3,3).
|
||||
n_sigma : int, optional
|
||||
Multiplier of the standard deviation used as a threshold to identify potential photon pixels. Default is 5.
|
||||
dtype : data-type, optional
|
||||
The data type of the image. Default is np.int32.
|
||||
capacity : int, optional
|
||||
The maximum number of clusters than can be stored before reallocating. Default is 1024.
|
||||
min_pedestal_samples : int, optional
|
||||
The minimum number of pedestal samples to accumulate before using the pedestal. Default is 1000.
|
||||
"""
|
||||
cls = _get_class("ClusterFinder", cluster_size, dtype)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, min_pedestal_samples=min_pedestal_samples)
|
||||
|
||||
|
||||
|
||||
def ClusterFinderMT(image_size, cluster_size = (3,3), dtype=np.int32, n_sigma=5, capacity = 1024, n_threads = 3):
|
||||
def ClusterFinderMT(image_size, *, cluster_size = (3,3), dtype=np.int32, n_sigma=5, capacity = 1024, n_threads = 3, min_pedestal_samples = 1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinderMT object. Provides a cleaner syntax for
|
||||
the templated ClusterFinderMT in C++.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image_size : tuple
|
||||
The size of the image as a tuple (height, width).
|
||||
cluster_size : tuple, optional
|
||||
The size of the cluster to find as a tuple (height, width). Default is (3,3).
|
||||
n_sigma : int, optional
|
||||
Multiplier of the standard deviation used as a threshold to identify potential photon pixels. Default is 5.
|
||||
dtype : data-type, optional
|
||||
The data type of the image. Default is np.int32.
|
||||
capacity : int, optional
|
||||
The maximum number of clusters than can be stored before reallocating. Default is 1024.
|
||||
n_threads : int, optional
|
||||
The number of threads to use for processing. Default is 3.
|
||||
min_pedestal_samples : int, optional
|
||||
The minimum number of pedestal samples to accumulate before using the pedestal. Default is 1000.
|
||||
"""
|
||||
|
||||
cls = _get_class("ClusterFinderMT", cluster_size, dtype)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, n_threads=n_threads)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, min_pedestal_samples=min_pedestal_samples, n_threads=n_threads)
|
||||
|
||||
|
||||
def ClusterCollector(clusterfindermt, dtype=np.int32):
|
||||
|
||||
@@ -43,7 +43,7 @@ class RawFile(_aare.RawFile):
|
||||
Returns:
|
||||
int: Number of frames in file.
|
||||
"""
|
||||
return super().frames_in_file
|
||||
return self.total_frames
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
@@ -37,7 +37,6 @@ void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
return cluster;
|
||||
}))
|
||||
|
||||
// TODO! Review if to keep or not
|
||||
.def_property_readonly(
|
||||
"data",
|
||||
[](Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType> &c)
|
||||
@@ -60,6 +59,26 @@ void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
.def_readonly("y",
|
||||
&Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType>::y)
|
||||
|
||||
.def("__repr__",
|
||||
[class_name](const Cluster<Type, ClusterSizeX, ClusterSizeY,
|
||||
CoordType> &self) {
|
||||
fmt::memory_buffer data;
|
||||
fmt::format_to(std::back_inserter(data), "[[");
|
||||
for (size_t i = 0; i < self.data.size(); ++i) {
|
||||
if (i != 0) {
|
||||
fmt::format_to(std::back_inserter(data),
|
||||
i % ClusterSizeX == 0 ? "], [" : ", ");
|
||||
}
|
||||
fmt::format_to(std::back_inserter(data), "{}",
|
||||
self.data[i]);
|
||||
}
|
||||
fmt::format_to(std::back_inserter(data), "]]");
|
||||
|
||||
return fmt::format("{}(x={}, y={}, data={})", class_name,
|
||||
self.x, self.y,
|
||||
fmt::string_view(data.data(), data.size()));
|
||||
})
|
||||
|
||||
.def(
|
||||
"max_sum_2x2",
|
||||
[](Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType> &self) {
|
||||
|
||||
@@ -32,8 +32,10 @@ void define_ClusterFinder(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterFinder<ClusterType, uint16_t, pd_type>>(
|
||||
m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, pd_type, size_t>(), py::arg("image_size"),
|
||||
py::arg("n_sigma") = 5.0, py::arg("capacity") = 1'000'000)
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0,
|
||||
py::arg("capacity") = 1'000'000,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
|
||||
.def_property(
|
||||
"nSigma",
|
||||
|
||||
@@ -32,10 +32,11 @@ void define_ClusterFinderMT(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterFinderMT<ClusterType, uint16_t, pd_type>>(
|
||||
m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t, size_t>(),
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t, size_t, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0,
|
||||
py::arg("capacity") = 2048, py::arg("n_threads") = 3,
|
||||
py::arg("queue_depth") = 16)
|
||||
py::arg("queue_depth") = 16,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
.def("push_pedestal_frame",
|
||||
[](ClusterFinderMT<ClusterType, uint16_t, pd_type> &self,
|
||||
py::array_t<uint16_t> frame) {
|
||||
|
||||
@@ -36,6 +36,22 @@ void define_defs_bindings(py::module &m) {
|
||||
.def_readwrite("xmax", &ROI::xmax)
|
||||
.def_readwrite("ymin", &ROI::ymin)
|
||||
.def_readwrite("ymax", &ROI::ymax)
|
||||
|
||||
.def(
|
||||
"slice",
|
||||
[](const ROI &self) {
|
||||
return std::make_tuple(py::slice(self.ymin, self.ymax, 1),
|
||||
py::slice(self.xmin, self.xmax, 1));
|
||||
},
|
||||
R"doc(
|
||||
The slice can be used to index into a 2D array to extract the region of interest.
|
||||
|
||||
Returns
|
||||
-------
|
||||
tuple of slice
|
||||
A tuple containing two slice objects for the x and y dimensions.
|
||||
)doc")
|
||||
|
||||
.def("__str__",
|
||||
[](const ROI &self) {
|
||||
return fmt::format("ROI: xmin: {} xmax: {} ymin: {} ymax: {}",
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/to_string.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <fmt/format.h>
|
||||
// #include <pybind11/native_enum.h> only for version 3
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
@@ -18,7 +20,11 @@ void define_eta(py::module &m, const std::string &typestr) {
|
||||
.def_readwrite("c", &Eta2<T>::c,
|
||||
"eta corner value cTopLeft, cTopRight, "
|
||||
"cBottomLeft, cBottomRight")
|
||||
.def_readwrite("sum", &Eta2<T>::sum, "photon energy of cluster");
|
||||
.def_readwrite("sum", &Eta2<T>::sum, "photon energy of cluster")
|
||||
.def("__repr__", [class_name](const Eta2<T> &self) {
|
||||
return fmt::format("{}(x={}, y={}, c={}, sum={})", class_name,
|
||||
self.x, self.y, to_string(self.c), self.sum);
|
||||
});
|
||||
}
|
||||
|
||||
void define_corner_enum(py::module &m) {
|
||||
@@ -101,4 +107,4 @@ void register_calculate_3x3eta(py::module &m) {
|
||||
},
|
||||
R"(calculates eta3x3 taking into account cross pixels in cluster)",
|
||||
py::arg("cluster"));
|
||||
}
|
||||
}
|
||||
+33
-15
@@ -11,6 +11,7 @@
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <pybind11/iostream.h>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
@@ -21,14 +22,23 @@
|
||||
namespace py = pybind11;
|
||||
using namespace ::aare;
|
||||
|
||||
namespace {
|
||||
std::runtime_error raw_file_read_error(RawFile &file,
|
||||
const std::string &message) {
|
||||
return std::runtime_error(fmt::format(
|
||||
"Error reading frame index {} from file '{}': {}", file.tell(),
|
||||
file.master().master_fname().string(), message));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void define_raw_file_io_bindings(py::module &m) {
|
||||
py::class_<RawFile>(m, "RawFile")
|
||||
.def(py::init<const std::filesystem::path &>())
|
||||
.def("read_frame",
|
||||
[](RawFile &self) {
|
||||
if (self.n_modules_in_roi().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
"File contains multiple ROIs - use read_ROIs()");
|
||||
throw raw_file_read_error(
|
||||
self, "File contains multiple ROIs - use read_ROIs()");
|
||||
}
|
||||
|
||||
std::vector<size_t> shape;
|
||||
@@ -51,16 +61,19 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_n",
|
||||
[](RawFile &self, size_t n_frames) {
|
||||
if (self.n_modules_in_roi().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
throw raw_file_read_error(
|
||||
self,
|
||||
"File contains multiple ROIs - use read_n_ROIs() to "
|
||||
"read a specific ROI or use read_ROIs and "
|
||||
"read one frame at a time.");
|
||||
}
|
||||
// adjust for actual frames left in the file
|
||||
n_frames =
|
||||
std::min(n_frames, self.total_frames() - self.tell());
|
||||
std::min(n_frames, self.tell() < self.total_frames()
|
||||
? self.total_frames() - self.tell()
|
||||
: size_t{0});
|
||||
if (n_frames == 0) {
|
||||
throw std::runtime_error("No frames left in file");
|
||||
throw raw_file_read_error(self, "No frames left in file");
|
||||
}
|
||||
std::vector<size_t> shape{n_frames, self.rows(), self.cols()};
|
||||
|
||||
@@ -89,12 +102,13 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_roi",
|
||||
[](RawFile &self, const size_t roi_index) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
if (roi_index >= self.num_rois()) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"ROI index out of range.");
|
||||
throw raw_file_read_error(
|
||||
self, LOCATION + "ROI index out of range.");
|
||||
}
|
||||
|
||||
// return headers from all subfiles
|
||||
@@ -141,7 +155,8 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_rois",
|
||||
[](RawFile &self) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
size_t number_of_ROIs = self.num_rois();
|
||||
@@ -196,19 +211,22 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_n_with_roi",
|
||||
[](RawFile &self, const size_t num_frames, const size_t roi_index) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
if (roi_index >= self.num_rois()) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"ROI index out of range.");
|
||||
throw raw_file_read_error(
|
||||
self, LOCATION + "ROI index out of range.");
|
||||
}
|
||||
|
||||
// adjust for actual frames left in the file
|
||||
size_t n_frames =
|
||||
std::min(num_frames, self.total_frames() - self.tell());
|
||||
std::min(num_frames, self.tell() < self.total_frames()
|
||||
? self.total_frames() - self.tell()
|
||||
: size_t{0});
|
||||
if (n_frames == 0) {
|
||||
throw std::runtime_error("No frames left in file");
|
||||
throw raw_file_read_error(self, "No frames left in file");
|
||||
}
|
||||
std::vector<size_t> shape{
|
||||
n_frames, self.roi_geometries(roi_index).pixels_y(),
|
||||
@@ -306,4 +324,4 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
.def_property_readonly("n_modules", &RawFile::n_modules)
|
||||
.def_property_readonly("n_modules_in_roi", &RawFile::n_modules_in_roi)
|
||||
.def_property_readonly("num_rois", &RawFile::num_rois);
|
||||
}
|
||||
}
|
||||
@@ -135,9 +135,19 @@ void define_raw_master_file_bindings(py::module &m) {
|
||||
List[int]
|
||||
Vector of disabled UDP port indices relative to UDP port types (empty if none are disabled)
|
||||
)")
|
||||
.def_property_readonly("period", [](RawMasterFile &self) {
|
||||
double seconds =
|
||||
std::chrono::duration<double>(self.period()).count();
|
||||
return seconds;
|
||||
});
|
||||
.def_property_readonly(
|
||||
"period",
|
||||
[](RawMasterFile &self) {
|
||||
double seconds =
|
||||
std::chrono::duration<double>(self.period()).count();
|
||||
return seconds;
|
||||
})
|
||||
|
||||
.def("__enter__",
|
||||
[](RawMasterFile &self) -> RawMasterFile & { return self; })
|
||||
|
||||
.def("__exit__",
|
||||
[]([[maybe_unused]] RawMasterFile &self,
|
||||
[[maybe_unused]] py::object, [[maybe_unused]] py::object,
|
||||
[[maybe_unused]] py::object) { return; });
|
||||
}
|
||||
@@ -3,7 +3,7 @@ import pytest
|
||||
import numpy as np
|
||||
|
||||
from aare import _aare #import the C++ module
|
||||
from aare import corner
|
||||
from aare import ROI, corner
|
||||
from conftest import test_data_path
|
||||
|
||||
|
||||
@@ -91,6 +91,22 @@ def test_calculate_eta():
|
||||
assert eta2.sum == 4
|
||||
|
||||
|
||||
def test_cluster_representations():
|
||||
"""Test Cluster representation"""
|
||||
|
||||
cluster = _aare.Cluster2x2i(5, 6, np.array([1, 2, 3, 4], dtype=np.int32))
|
||||
assert repr(cluster) == "Cluster2x2i(x=5, y=6, data=[[1, 2], [3, 4]])"
|
||||
|
||||
def test_eta_representations():
|
||||
"""Test Eta representation"""
|
||||
eta = _aare.Etai()
|
||||
eta.x = 0.25
|
||||
eta.y = 0.75
|
||||
eta.c = corner.cBottomRight
|
||||
eta.sum = 42
|
||||
assert repr(eta) == "Etai(x=0.25, y=0.75, c=BottomRight, sum=42)"
|
||||
|
||||
|
||||
def test_max_sum():
|
||||
"""Max 2x2 Sum"""
|
||||
cluster = _aare.Cluster3x3i(5,5,np.array([1, 1, 1, 2, 3, 1, 2, 2, 1], dtype=np.int32))
|
||||
@@ -146,4 +162,3 @@ def test_3x3_reduction():
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from aare import ROI
|
||||
|
||||
|
||||
def test_roi_slice():
|
||||
"""test the ROI slice method"""
|
||||
roi = ROI(0, 4, 2, 4)
|
||||
|
||||
array = np.array([[1, 2, 3, 4],
|
||||
[5, 6, 7, 8],
|
||||
[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]])
|
||||
|
||||
sliced_array = array[roi.slice()]
|
||||
|
||||
assert sliced_array.shape == (2, 4)
|
||||
assert np.array_equal(sliced_array, np.array([[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]]))
|
||||
@@ -1,8 +1,244 @@
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
import pytest
|
||||
from aare import RawFile, ROI, UDPPortPosition
|
||||
import json
|
||||
from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition
|
||||
import numpy as np
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def small_raw_file(tmp_path):
|
||||
master_path = tmp_path / "run_master_0.json"
|
||||
master_path.write_text(json.dumps({
|
||||
"Version": 7.2,
|
||||
"Detector Type": "Jungfrau",
|
||||
"Timing Mode": "auto",
|
||||
"Geometry": {"x": 1, "y": 1},
|
||||
"Image Size in bytes": 12,
|
||||
"Pixels": {"x": 3, "y": 2},
|
||||
"Max Frames Per File": 1,
|
||||
"Total Frames": 2,
|
||||
"Frames in File": 2,
|
||||
"Frame Padding": 1,
|
||||
"Frame Discard Policy": "nodiscard",
|
||||
}))
|
||||
for index in range(2):
|
||||
data_path = tmp_path / f"run_d0_f{index}_0.raw"
|
||||
# A detector header followed by six uint16 pixels.
|
||||
data_path.write_bytes(bytes(112) + np.arange(6, dtype=np.uint16).tobytes())
|
||||
return master_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, args, kwargs", [
|
||||
("read_frame", (), {}),
|
||||
("read_n", (1,), {}),
|
||||
("read_roi", (0,), {}),
|
||||
("read_rois", (), {}),
|
||||
("read_n_with_roi", (1,), {"roi_index": 0}),
|
||||
("frame_number", (2,), {}),
|
||||
])
|
||||
def test_raw_read_error_context(small_raw_file, method, args, kwargs):
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(2)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
getattr(reader, method)(*args, **kwargs)
|
||||
assert "frame index 2" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
assert ".raw" not in str(error.value)
|
||||
if method == "read_frame":
|
||||
assert "file contains 2 frames (indices are zero-based)" in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("frame_index", [2, 17])
|
||||
def test_generic_raw_read_error_context(small_raw_file, frame_index):
|
||||
reader = File(small_raw_file)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame(frame_index)
|
||||
assert f"frame index {frame_index}" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw_subfile", [False, True])
|
||||
def test_truncated_raw_read_error_context(small_raw_file, raw_subfile):
|
||||
data_path = small_raw_file.parent / "run_d0_f1_0.raw"
|
||||
if raw_subfile:
|
||||
reader = RawSubFile(
|
||||
small_raw_file.parent / "run_d0_f0_0.raw",
|
||||
DetectorType.Jungfrau, 2, 3, 16,
|
||||
)
|
||||
else:
|
||||
reader = RawFile(small_raw_file)
|
||||
data_path.write_bytes(bytes(112))
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame()
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert str(data_path) in str(error.value)
|
||||
assert "End of file" in str(error.value)
|
||||
assert "master" not in str(error.value)
|
||||
assert "RawSubFile.cpp" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, args", [
|
||||
("read_frame", ()),
|
||||
("read_n", (1,)),
|
||||
("read_roi", (0,)),
|
||||
("frame_number", (1,)),
|
||||
])
|
||||
def test_short_raw_subfile_sets_read_bounds(small_raw_file, method, args):
|
||||
(small_raw_file.parent / "run_d0_f1_0.raw").unlink()
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
getattr(reader, method)(*args)
|
||||
assert reader.total_frames == 1
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
assert ".raw" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("counts, master_count, warn", [
|
||||
([2], 2, False),
|
||||
([2, 2], 2, False),
|
||||
([2, 2], 0, True),
|
||||
([2, 2], 1, True),
|
||||
([2, 2], 5, True),
|
||||
([1, 2], 2, True),
|
||||
([2, 1], 2, True),
|
||||
([1, 2], 1, True),
|
||||
([0, 2], 2, True),
|
||||
([0, 0], 0, False),
|
||||
])
|
||||
def test_raw_subfile_frame_counts(small_raw_file, capfd, counts, master_count, warn):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata["Geometry"]["y"] = len(counts)
|
||||
metadata["Frames in File"] = master_count
|
||||
metadata["Total Frames"] = 1000
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
data = (small_raw_file.parent / "run_d0_f0_0.raw").read_bytes()
|
||||
for module, count in enumerate(counts):
|
||||
for index in range(2):
|
||||
path = small_raw_file.parent / f"run_d{module}_f{index}_0.raw"
|
||||
if index < count:
|
||||
path.write_bytes(data)
|
||||
elif index == 0:
|
||||
path.write_bytes(b"")
|
||||
else:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
warning = capfd.readouterr().err
|
||||
if warn:
|
||||
assert warning.count("WARNING") == 1
|
||||
assert str(small_raw_file) in warning
|
||||
else:
|
||||
assert "WARNING" not in warning
|
||||
|
||||
assert reader.total_frames == min(counts)
|
||||
assert len(reader) == min(counts)
|
||||
assert reader.master.frames_in_file == master_count
|
||||
if min(counts):
|
||||
_, frames = reader.read()
|
||||
assert frames.shape == (min(counts), 2 * len(counts), 3)
|
||||
reader.seek(0)
|
||||
_, frames = reader.read_n(10)
|
||||
assert len(frames) == min(counts)
|
||||
assert reader.frame_number(min(counts) - 1) == 0
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.frame_number(min(counts))
|
||||
reader.seek(min(counts))
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.read_frame()
|
||||
assert "WARNING" not in capfd.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("short_module", [0, 1])
|
||||
def test_raw_frame_count_across_rois(small_raw_file, short_module):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({
|
||||
"Version": 8.0,
|
||||
"Geometry": {"x": 1, "y": 2},
|
||||
"Image Size": 12,
|
||||
"Receiver Rois": [
|
||||
{"xmin": 0, "xmax": 2, "ymin": 0, "ymax": 1},
|
||||
{"xmin": 0, "xmax": 2, "ymin": 2, "ymax": 3},
|
||||
],
|
||||
})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
for index in range(2):
|
||||
data = (small_raw_file.parent / f"run_d0_f{index}_0.raw").read_bytes()
|
||||
(small_raw_file.parent / f"run_d1_f{index}_0.raw").write_bytes(data)
|
||||
(small_raw_file.parent / f"run_d{short_module}_f1_0.raw").unlink()
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
assert reader.total_frames == 1
|
||||
_, rois = reader.read_rois()
|
||||
assert len(rois) == 2
|
||||
assert all(roi.shape == (2, 3) for roi in rois)
|
||||
for roi_index in range(2):
|
||||
reader.seek(0)
|
||||
_, frames = reader.read_n_with_roi(10, roi_index=roi_index)
|
||||
assert frames.shape == (1, 2, 3)
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.read_roi(roi_index)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled_port", [0, 1])
|
||||
def test_raw_frame_count_with_disabled_udp_port(small_raw_file, disabled_port):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({
|
||||
"Geometry": {"x": 1, "y": 2},
|
||||
"Frames in File": 0,
|
||||
"Number of UDP Interfaces": 2,
|
||||
"UDP Ports Type": ["bottom", "top"],
|
||||
"UDP Ports Disabled": [disabled_port],
|
||||
})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
data = (small_raw_file.parent / "run_d0_f0_0.raw").read_bytes()
|
||||
for index in range(2):
|
||||
(small_raw_file.parent / f"run_d0_f{index}_0.raw").unlink()
|
||||
path = small_raw_file.parent / f"run_d{1 - disabled_port}_f{index}_0.raw"
|
||||
path.write_bytes(data)
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
assert reader.total_frames == 2
|
||||
assert reader.master.frames_in_file == 0
|
||||
assert reader.frame_number(1) == 0
|
||||
_, frames = reader.read()
|
||||
assert frames.shape == (2, 2, 3)
|
||||
|
||||
|
||||
def test_raw_frame_count_without_selected_subfiles(small_raw_file):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({"Version": 8.0, "Image Size": 12, "Receiver Rois": []})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
with pytest.raises(RuntimeError, match="No raw subfiles selected"):
|
||||
RawFile(small_raw_file)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lagging_module", [0, 1])
|
||||
def test_raw_synchronization_error_identifies_subfile(
|
||||
small_raw_file, lagging_module
|
||||
):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata["Geometry"]["y"] = 2
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
for index in range(2):
|
||||
data = (small_raw_file.parent / f"run_d0_f{index}_0.raw").read_bytes()
|
||||
(small_raw_file.parent / f"run_d1_f{index}_0.raw").write_bytes(data)
|
||||
|
||||
ahead_path = small_raw_file.parent / f"run_d{1 - lagging_module}_f1_0.raw"
|
||||
with ahead_path.open("r+b") as output:
|
||||
output.write(np.array([1], dtype=np.uint64).tobytes())
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame()
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert "synchroniz" in str(error.value)
|
||||
lagging_path = small_raw_file.parent / f"run_d{lagging_module}_f1_0.raw"
|
||||
assert str(lagging_path) in str(error.value)
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_read_rawfile_with_roi_spanning_over_one_module(test_data_path):
|
||||
|
||||
@@ -147,4 +383,4 @@ def test_read_eiger_udp_port_disabled(test_data_path):
|
||||
rois = f.master.rois
|
||||
assert len(rois) == 2
|
||||
assert rois[0] == ROI(0, 512, 0, 512)
|
||||
assert rois[1] == ROI(1024, 1536, 0, 512)
|
||||
assert rois[1] == ROI(1024, 1536, 0, 512)
|
||||
@@ -1,5 +1,7 @@
|
||||
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from aare import RawMasterFile, ReadoutMode, DetectorType
|
||||
|
||||
@@ -11,4 +13,26 @@ def test_read_rawfile_quad_eiger_and_compare_to_numpy(test_data_path):
|
||||
|
||||
f = RawMasterFile(file_name)
|
||||
assert(f.reading_mode == ReadoutMode.UNKNOWN)
|
||||
assert(f.detector_type == DetectorType.Jungfrau)
|
||||
assert(f.detector_type == DetectorType.Jungfrau)
|
||||
|
||||
|
||||
def test_raw_master_file_context_manager(tmp_path):
|
||||
file_name = tmp_path / "run_master_0.json"
|
||||
file_name.write_text(json.dumps({
|
||||
"Version": 7.2,
|
||||
"Detector Type": "Jungfrau",
|
||||
"Timing Mode": "auto",
|
||||
"Geometry": {"x": 1, "y": 1},
|
||||
"Image Size in bytes": 12,
|
||||
"Pixels": {"x": 3, "y": 2},
|
||||
"Max Frames Per File": 1,
|
||||
"Total Frames": 2,
|
||||
"Frames in File": 2,
|
||||
"Frame Padding": 1,
|
||||
"Frame Discard Policy": "nodiscard",
|
||||
}))
|
||||
|
||||
|
||||
with RawMasterFile(file_name) as context_file:
|
||||
assert context_file.reading_mode == ReadoutMode.UNKNOWN
|
||||
assert context_file.detector_type == DetectorType.Jungfrau
|
||||
@@ -22,9 +22,11 @@ class ClusterFinderMTWrapper
|
||||
public:
|
||||
ClusterFinderMTWrapper(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 2000, size_t n_threads = 3,
|
||||
size_t queue_depth = 16)
|
||||
size_t queue_depth = 16,
|
||||
size_t minimum_pedestal_samples = 1000)
|
||||
: ClusterFinderMT<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>(
|
||||
image_size, nSigma, capacity, n_threads, queue_depth) {}
|
||||
image_size, nSigma, capacity, n_threads, queue_depth,
|
||||
minimum_pedestal_samples) {}
|
||||
|
||||
size_t get_m_input_queues_size() const {
|
||||
return this->m_input_queues.size();
|
||||
@@ -73,13 +75,14 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
File file(fpath);
|
||||
|
||||
size_t n_threads = 2;
|
||||
size_t n_frames_pd = 10;
|
||||
size_t minimum_pedestal_samples = 1;
|
||||
size_t n_frames = 10;
|
||||
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
|
||||
ClusterFinderMTWrapper<ClusterType> cf(
|
||||
{static_cast<int64_t>(file.rows()), static_cast<int64_t>(file.cols())},
|
||||
5, 2000, n_threads); // no idea what frame type is!!! default uint16_t
|
||||
5, 2000, n_threads, 16, minimum_pedestal_samples);
|
||||
|
||||
CHECK(cf.get_m_input_queues_size() == n_threads);
|
||||
CHECK(cf.get_m_output_queues_size() == n_threads);
|
||||
@@ -87,8 +90,11 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_output_queues_are_empty() == true);
|
||||
CHECK(cf.m_input_queues_are_empty() == true);
|
||||
|
||||
for (size_t i = 0; i < n_frames_pd; ++i) {
|
||||
auto frame = file.read_frame();
|
||||
auto frame = file.read_frame();
|
||||
cf.push_pedestal_frame(frame.view<uint16_t>());
|
||||
|
||||
for (size_t i = 0; i < n_frames; ++i) {
|
||||
frame = file.read_frame();
|
||||
cf.find_clusters(frame.view<uint16_t>());
|
||||
}
|
||||
|
||||
@@ -97,7 +103,7 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_output_queues_are_empty() == true);
|
||||
CHECK(cf.m_input_queues_are_empty() == true);
|
||||
|
||||
CHECK(cf.m_sink_size() == n_frames_pd);
|
||||
CHECK(cf.m_sink_size() == n_frames);
|
||||
ClusterCollector<ClusterType> clustercollector(&cf);
|
||||
|
||||
clustercollector.stop();
|
||||
@@ -105,7 +111,6 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_sink_size() == 0);
|
||||
|
||||
auto clustervec = clustercollector.steal_clusters();
|
||||
// CHECK(clustervec.size() == ) //dont know how many clusters to expect
|
||||
}
|
||||
|
||||
TEST_CASE("frame buffers are recycled when pushing more frames than the pool "
|
||||
|
||||
+109
-70
@@ -16,8 +16,15 @@ using json = nlohmann::json;
|
||||
|
||||
namespace aare {
|
||||
|
||||
std::runtime_error RawFile::frame_error(size_t frame_index,
|
||||
const std::string &message) const {
|
||||
return std::runtime_error(
|
||||
fmt::format("Error reading frame index {} from file '{}': {}",
|
||||
frame_index, m_master.master_fname().string(), message));
|
||||
}
|
||||
|
||||
RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode)
|
||||
: m_master(fname), m_frames_in_file(m_master.frames_in_file()) {
|
||||
: m_master(fname) {
|
||||
|
||||
m_mode = mode;
|
||||
|
||||
@@ -32,30 +39,31 @@ RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode)
|
||||
open_subfiles(roi_index);
|
||||
}
|
||||
|
||||
// TODO: work around for now - retrieve num_frames from subfiles
|
||||
if (!m_master.disabled_udp_ports().empty()) {
|
||||
// TODO: remove frames_from_file from master file?
|
||||
// retrieve the frame numbers from subfile as frames per file in
|
||||
// master file 0 if dataprocessor 0 was disabled
|
||||
std::vector<size_t> min_subfiles_per_roi(m_subfiles.size());
|
||||
std::transform(
|
||||
m_subfiles.begin(), m_subfiles.end(),
|
||||
min_subfiles_per_roi.begin(), [](const auto &subfiles) {
|
||||
return std::min_element(
|
||||
subfiles.begin(), subfiles.end(),
|
||||
[](const auto &raw_subfile1,
|
||||
const auto &raw_subfile2) {
|
||||
return raw_subfile1->frames_in_file() <
|
||||
raw_subfile2->frames_in_file();
|
||||
})
|
||||
->get()
|
||||
->frames_in_file();
|
||||
});
|
||||
m_frames_in_file = *std::min_element(min_subfiles_per_roi.begin(),
|
||||
min_subfiles_per_roi.end());
|
||||
|
||||
LOG(logDEBUG) << "Frames in file: " << m_frames_in_file;
|
||||
std::optional<size_t> min_frames;
|
||||
size_t max_frames = 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);
|
||||
}
|
||||
}
|
||||
if (!min_frames) {
|
||||
throw std::runtime_error(fmt::format(
|
||||
"No raw subfiles selected by '{}'", fname.string()));
|
||||
}
|
||||
m_frames_in_file = *min_frames;
|
||||
|
||||
if (m_frames_in_file != max_frames ||
|
||||
m_frames_in_file != m_master.frames_in_file()) {
|
||||
LOG(logWARNING) << fmt::format(
|
||||
"'{}': Different number of frames across subfiles. Expected {} "
|
||||
"frames but found min/max {}/{}, "
|
||||
"using {} frames.",
|
||||
fname.string(), m_master.frames_in_file(), m_frames_in_file,
|
||||
max_frames, m_frames_in_file);
|
||||
}
|
||||
LOG(logDEBUG) << "Frames in file: " << m_frames_in_file;
|
||||
} else {
|
||||
throw std::runtime_error(LOCATION +
|
||||
" Unsupported mode. Can only read RawFiles.");
|
||||
@@ -65,7 +73,8 @@ RawFile::RawFile(const std::filesystem::path &fname, const std::string &mode)
|
||||
Frame RawFile::read_roi(const size_t roi_index) {
|
||||
|
||||
if (roi_index >= m_master.roi_geometries().size()) {
|
||||
throw std::runtime_error(LOCATION + "ROI index out of range.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION + "ROI index out of range.");
|
||||
}
|
||||
return get_frame(m_current_frame++, roi_index);
|
||||
}
|
||||
@@ -86,15 +95,17 @@ std::vector<Frame> RawFile::read_rois() {
|
||||
|
||||
Frame RawFile::read_frame() {
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(LOCATION + "Multiple ROIs present in file. "
|
||||
"Use read_ROIs() instead.");
|
||||
throw frame_error(m_current_frame, LOCATION +
|
||||
"Multiple ROIs present in file. "
|
||||
"Use read_ROIs() instead.");
|
||||
}
|
||||
return get_frame(m_current_frame++);
|
||||
}
|
||||
|
||||
Frame RawFile::read_frame(size_t frame_number) {
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
throw frame_error(
|
||||
frame_number,
|
||||
LOCATION + "Multiple ROIs present in file. "
|
||||
"Use read_ROIs(const size_t frame_number) instead.");
|
||||
}
|
||||
@@ -105,8 +116,8 @@ Frame RawFile::read_frame(size_t frame_number) {
|
||||
void RawFile::read_into(std::byte *image_buf, size_t n_frames) {
|
||||
// TODO: implement this in a more efficient way
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Cannot use read_into for multiple ROIs.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION + "Cannot use read_into for multiple ROIs.");
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < n_frames; i++) {
|
||||
@@ -117,9 +128,10 @@ void RawFile::read_into(std::byte *image_buf, size_t n_frames) {
|
||||
|
||||
void RawFile::read_into(std::byte *image_buf) {
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Cannot use read_into for multiple ROIs. Use "
|
||||
"read_roi_into() for a single ROI instead.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION +
|
||||
"Cannot use read_into for multiple ROIs. Use "
|
||||
"read_roi_into() for a single ROI instead.");
|
||||
}
|
||||
return get_frame_into(m_current_frame++, image_buf);
|
||||
}
|
||||
@@ -127,16 +139,17 @@ void RawFile::read_into(std::byte *image_buf) {
|
||||
void RawFile::read_roi_into(std::byte *image_buf, const size_t roi_index,
|
||||
const size_t frame_number, DetectorHeader *header) {
|
||||
if (roi_index >= num_rois()) {
|
||||
throw std::runtime_error(LOCATION + "ROI index out of range.");
|
||||
throw frame_error(frame_number, LOCATION + "ROI index out of range.");
|
||||
}
|
||||
return get_frame_into(frame_number, image_buf, roi_index, header);
|
||||
}
|
||||
|
||||
void RawFile::read_into(std::byte *image_buf, DetectorHeader *header) {
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Cannot use read_into for multiple ROIs. Use "
|
||||
"read_roi_into() for a single ROI instead.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION +
|
||||
"Cannot use read_into for multiple ROIs. Use "
|
||||
"read_roi_into() for a single ROI instead.");
|
||||
}
|
||||
return get_frame_into(m_current_frame++, image_buf, 0, header);
|
||||
}
|
||||
@@ -146,15 +159,16 @@ void RawFile::read_into(std::byte *image_buf, size_t n_frames,
|
||||
// return get_frame_into(m_current_frame++, image_buf, header);
|
||||
|
||||
if (m_master.roi_geometries().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
throw frame_error(
|
||||
m_current_frame,
|
||||
LOCATION +
|
||||
"Cannot use read_into for multiple ROIs."); // TODO: maybe
|
||||
// pass
|
||||
// roi_index so
|
||||
// one can use
|
||||
// read_into for
|
||||
// a specific
|
||||
// ROI
|
||||
"Cannot use read_into for multiple ROIs."); // TODO: maybe
|
||||
// pass
|
||||
// roi_index so
|
||||
// one can use
|
||||
// read_into for
|
||||
// a specific
|
||||
// ROI
|
||||
}
|
||||
|
||||
for (size_t i = 0; i < n_frames; i++) {
|
||||
@@ -201,7 +215,8 @@ void RawFile::seek(size_t frame_index) {
|
||||
// if frame_number == total_frames, then the next read will throw an
|
||||
// error
|
||||
if (frame_index > total_frames()) {
|
||||
throw std::runtime_error(
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
fmt::format("frame number {} is greater than total frames {}",
|
||||
frame_index, total_frames()));
|
||||
}
|
||||
@@ -281,14 +296,22 @@ DetectorHeader RawFile::read_header(const std::filesystem::path &fname) {
|
||||
DetectorHeader h{};
|
||||
FILE *fp = fopen(fname.string().c_str(), "r");
|
||||
if (!fp)
|
||||
throw std::runtime_error(
|
||||
fmt::format("Could not open: {} for reading", fname.string()));
|
||||
throw std::runtime_error(fmt::format(
|
||||
"Could not open file '{}' for frame index 0", fname.string()));
|
||||
|
||||
size_t const rc = fread(reinterpret_cast<char *>(&h), sizeof(h), 1, fp);
|
||||
if (rc != 1)
|
||||
throw std::runtime_error(LOCATION + "Could not read header from file");
|
||||
if (rc != 1) {
|
||||
fclose(fp);
|
||||
throw std::runtime_error(
|
||||
LOCATION + fmt::format("Could not read header for frame index 0 "
|
||||
"from file '{}'",
|
||||
fname.string()));
|
||||
}
|
||||
if (fclose(fp)) {
|
||||
throw std::runtime_error(LOCATION + "Could not close file");
|
||||
throw std::runtime_error(
|
||||
LOCATION + fmt::format("Could not close file '{}' after reading "
|
||||
"frame index 0",
|
||||
fname.string()));
|
||||
}
|
||||
|
||||
return h;
|
||||
@@ -311,7 +334,12 @@ 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 << ")";
|
||||
if (frame_index >= total_frames()) {
|
||||
throw std::runtime_error(LOCATION + "Frame number out of range");
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
LOCATION +
|
||||
fmt::format("Frame index {} is out of range: file contains {} "
|
||||
"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());
|
||||
@@ -345,8 +373,17 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer,
|
||||
|
||||
// 4. if we can't increase its index => throw error
|
||||
if (frame_indices[min_frame_idx] >= total_frames()) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Frame number out of range");
|
||||
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] =
|
||||
@@ -385,14 +422,15 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer,
|
||||
.at(roi_index)
|
||||
.module_indices_in_roi(part_idx))
|
||||
.origin_x != 0)
|
||||
throw std::runtime_error(
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
LOCATION +
|
||||
" Implementation error. x pos not 0."); // TODO:
|
||||
// origin
|
||||
// can still
|
||||
// change if
|
||||
// roi
|
||||
// changes
|
||||
" 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,
|
||||
@@ -451,12 +489,12 @@ void RawFile::get_frame_into(size_t frame_index, std::byte *frame_buffer,
|
||||
std::vector<Frame> RawFile::read_n(size_t n_frames) {
|
||||
// TODO: implement this in a more efficient way
|
||||
if (num_rois() > 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Multiple ROIs defined in the master "
|
||||
"file. Use "
|
||||
"read_num_rois for a specific ROI or use "
|
||||
"read_ROIs to read one frame after "
|
||||
"the other.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION + "Multiple ROIs defined in the master "
|
||||
"file. Use "
|
||||
"read_num_rois for a specific ROI or use "
|
||||
"read_ROIs to read one frame after "
|
||||
"the other.");
|
||||
}
|
||||
|
||||
std::vector<Frame> frames;
|
||||
@@ -471,7 +509,8 @@ std::vector<Frame> RawFile::read_n(size_t n_frames) {
|
||||
std::vector<Frame> RawFile::read_n_with_roi(const size_t n_frames,
|
||||
const size_t roi_index) {
|
||||
if (roi_index >= num_rois()) {
|
||||
throw std::runtime_error(LOCATION + "ROI index out of range.");
|
||||
throw frame_error(m_current_frame,
|
||||
LOCATION + "ROI index out of range.");
|
||||
}
|
||||
|
||||
std::vector<Frame> frames;
|
||||
@@ -484,8 +523,8 @@ std::vector<Frame> RawFile::read_n_with_roi(const size_t n_frames,
|
||||
}
|
||||
|
||||
size_t RawFile::frame_number(size_t frame_index) {
|
||||
if (frame_index >= m_master.frames_in_file()) {
|
||||
throw std::runtime_error(LOCATION + " Frame number out of range");
|
||||
if (frame_index >= total_frames()) {
|
||||
throw frame_error(frame_index, "Frame number out of range");
|
||||
}
|
||||
return m_subfiles[0][0]->frame_number(frame_index);
|
||||
}
|
||||
|
||||
+163
-1
@@ -8,6 +8,7 @@
|
||||
#include <catch2/matchers/catch_matchers_string.hpp>
|
||||
#include <filesystem>
|
||||
|
||||
#include "raw_file_helpers.hpp"
|
||||
#include "test_config.hpp"
|
||||
#include "test_macros.hpp"
|
||||
|
||||
@@ -15,6 +16,167 @@ using aare::File;
|
||||
using aare::RawFile;
|
||||
using namespace aare;
|
||||
|
||||
TEST_CASE("RawFile read errors identify the frame index and master path",
|
||||
"[RawFile][read-errors]") {
|
||||
TemporaryRawFiles files;
|
||||
RawFile file(files.master_path());
|
||||
REQUIRE(file.frame_number(1) == 101);
|
||||
file.seek(2);
|
||||
const auto index_matcher =
|
||||
Catch::Matchers::ContainsSubstring("frame index 2");
|
||||
const auto path_matcher =
|
||||
Catch::Matchers::ContainsSubstring(files.master_path().string());
|
||||
const auto context = index_matcher && path_matcher;
|
||||
std::vector<std::byte> buffer(file.bytes_per_frame() * 2);
|
||||
DetectorHeader headers[2]{};
|
||||
|
||||
SECTION("sequential frame") {
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.read_frame(),
|
||||
index_matcher && path_matcher &&
|
||||
Catch::Matchers::ContainsSubstring(
|
||||
"file contains 2 frames (indices are zero-based)") &&
|
||||
!Catch::Matchers::ContainsSubstring(".raw"));
|
||||
}
|
||||
SECTION("indexed frame at EOF") {
|
||||
REQUIRE_THROWS_WITH(file.read_frame(2), context);
|
||||
}
|
||||
SECTION("indexed frame beyond EOF") {
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.read_frame(17),
|
||||
Catch::Matchers::ContainsSubstring("frame index 17") &&
|
||||
Catch::Matchers::ContainsSubstring(
|
||||
files.master_path().string()));
|
||||
}
|
||||
SECTION("batch crosses EOF") {
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_n(2), context);
|
||||
}
|
||||
SECTION("read into buffer") {
|
||||
FileInterface &reader = file;
|
||||
REQUIRE_THROWS_WITH(reader.read_into(buffer.data()), context);
|
||||
}
|
||||
SECTION("batch into buffer") {
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_into(buffer.data(), size_t{2}), context);
|
||||
}
|
||||
SECTION("read with header") {
|
||||
REQUIRE_THROWS_WITH(file.read_into(buffer.data(), headers), context);
|
||||
}
|
||||
SECTION("batch with headers") {
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_into(buffer.data(), 2, headers), context);
|
||||
}
|
||||
SECTION("single ROI") { REQUIRE_THROWS_WITH(file.read_roi(0), context); }
|
||||
SECTION("all ROIs") { REQUIRE_THROWS_WITH(file.read_rois(), context); }
|
||||
SECTION("ROI into buffer") {
|
||||
REQUIRE_THROWS_WITH(file.read_roi_into(buffer.data(), 0, 2), context);
|
||||
}
|
||||
SECTION("ROI batch") {
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_n_with_roi(2, 0), context);
|
||||
}
|
||||
SECTION("frame number") {
|
||||
REQUIRE_THROWS_WITH(file.frame_number(2), context);
|
||||
}
|
||||
SECTION("generic File") {
|
||||
File reader(files.master_path());
|
||||
REQUIRE_THROWS_WITH(reader.read_frame(2), context);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("RawFile synchronization errors retain the requested index",
|
||||
"[RawFile][read-errors]") {
|
||||
TemporaryRawFiles files(2);
|
||||
const size_t lagging_module = GENERATE(0, 1);
|
||||
{
|
||||
std::fstream output(files.data_path(1 - lagging_module, 1),
|
||||
std::ios::binary | std::ios::in | std::ios::out);
|
||||
DetectorHeader header{};
|
||||
header.frameNumber = 102;
|
||||
output.write(reinterpret_cast<const char *>(&header), sizeof(header));
|
||||
}
|
||||
RawFile file(files.master_path());
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.read_frame(1),
|
||||
Catch::Matchers::ContainsSubstring("frame index 1") &&
|
||||
Catch::Matchers::ContainsSubstring(files.master_path().string()) &&
|
||||
Catch::Matchers::ContainsSubstring(
|
||||
files.data_path(lagging_module, 1).string()) &&
|
||||
Catch::Matchers::ContainsSubstring("synchroniz"));
|
||||
}
|
||||
|
||||
TEST_CASE("RawFile reports the failing data file and requested frame",
|
||||
"[RawFile][read-errors]") {
|
||||
TemporaryRawFiles files;
|
||||
RawFile file(files.master_path());
|
||||
std::filesystem::resize_file(files.data_path(0, 1), sizeof(DetectorHeader));
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.read_frame(1),
|
||||
Catch::Matchers::ContainsSubstring("frame index 1") &&
|
||||
!Catch::Matchers::ContainsSubstring(files.master_path().string()) &&
|
||||
Catch::Matchers::ContainsSubstring(
|
||||
files.data_path(0, 1).string()) &&
|
||||
Catch::Matchers::ContainsSubstring("End of file"));
|
||||
}
|
||||
|
||||
TEST_CASE("RawFile bounds use the shortest subfile",
|
||||
"[RawFile][read-errors][frame-count]") {
|
||||
TemporaryRawFiles files(2);
|
||||
const size_t short_module = GENERATE(0, 1);
|
||||
std::filesystem::remove(files.data_path(short_module, 1));
|
||||
RawFile file(files.master_path());
|
||||
REQUIRE(file.total_frames() == 1);
|
||||
REQUIRE(file.master().frames_in_file() == 2);
|
||||
REQUIRE_NOTHROW(file.read_frame(0));
|
||||
const auto expected = Catch::Matchers::ContainsSubstring(
|
||||
"Error reading frame index 1 from file '" +
|
||||
files.master_path().string() + "':");
|
||||
|
||||
SECTION("indexed frame") {
|
||||
REQUIRE_THROWS_WITH(file.read_frame(1), expected);
|
||||
}
|
||||
SECTION("batch") {
|
||||
file.seek(0);
|
||||
REQUIRE_THROWS_WITH(file.read_n(2), expected);
|
||||
}
|
||||
SECTION("ROI") {
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_roi(0), expected);
|
||||
}
|
||||
SECTION("generic File") {
|
||||
File reader(files.master_path());
|
||||
REQUIRE_THROWS_WITH(reader.read_frame(1), expected);
|
||||
}
|
||||
SECTION("frame number") {
|
||||
REQUIRE_THROWS_WITH(file.frame_number(1), expected);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("RawFile frame count comes from the complete subfile series",
|
||||
"[RawFile][frame-count]") {
|
||||
TemporaryRawFiles files;
|
||||
const size_t master_frames = GENERATE(0, 1, 2, 5);
|
||||
auto metadata = nlohmann::json::parse(std::ifstream(files.master_path()));
|
||||
metadata["Frames in File"] = master_frames;
|
||||
metadata["Total Frames"] = 1000;
|
||||
std::ofstream(files.master_path()) << metadata;
|
||||
|
||||
RawFile file(files.master_path());
|
||||
REQUIRE(file.total_frames() == 2);
|
||||
REQUIRE(file.master().frames_in_file() == master_frames);
|
||||
REQUIRE(file.master().total_frames_expected() == 1000);
|
||||
REQUIRE(file.frame_number(1) == 101);
|
||||
REQUIRE_NOTHROW(file.read_frame(1));
|
||||
REQUIRE_THROWS(file.frame_number(2));
|
||||
REQUIRE_THROWS(file.read_frame(2));
|
||||
|
||||
File reader(files.master_path());
|
||||
REQUIRE(reader.total_frames() == 2);
|
||||
REQUIRE(reader.frame_number(1) == 101);
|
||||
REQUIRE_NOTHROW(reader.read_frame(1));
|
||||
}
|
||||
|
||||
TEST_CASE("Read number of frames from a jungfrau raw file",
|
||||
"[.with-data][RawFile]") {
|
||||
|
||||
@@ -697,4 +859,4 @@ TEST_CASE("Read Eiger frame with disabled UDP ports",
|
||||
REQUIRE(rois.size() == 1);
|
||||
REQUIRE(rois[0] == ROI{0, 1024, 0, 512});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,7 @@
|
||||
#include "aare/logger.hpp"
|
||||
#include <sstream>
|
||||
|
||||
#include "to_string.hpp"
|
||||
#include "aare/to_string.hpp"
|
||||
|
||||
namespace aare {
|
||||
|
||||
@@ -624,6 +624,10 @@ void RawMasterFile::parse_raw(std::istream &is) {
|
||||
<< m_detector_layout.row << " x " << m_detector_layout.col << "\n ";
|
||||
}
|
||||
|
||||
m_rois.push_back(
|
||||
{0, m_detector_layout.col * static_cast<ssize_t>(m_pixels_x), 0,
|
||||
m_detector_layout.row * static_cast<ssize_t>(m_pixels_y)});
|
||||
|
||||
// TODO! Read files and find actual frames
|
||||
if (m_frames_in_file == 0)
|
||||
m_frames_in_file = m_total_frames_expected;
|
||||
|
||||
+27
-9
@@ -12,6 +12,17 @@
|
||||
|
||||
namespace aare {
|
||||
|
||||
std::runtime_error RawSubFile::frame_error(size_t frame_index,
|
||||
const std::string &message) const {
|
||||
return std::runtime_error(
|
||||
fmt::format("Error reading frame index {} from file '{}': {}",
|
||||
frame_index, current_path().string(), message));
|
||||
}
|
||||
|
||||
std::filesystem::path RawSubFile::current_path() const {
|
||||
return fpath(m_current_file_index + m_offset);
|
||||
}
|
||||
|
||||
RawSubFile::RawSubFile(const std::filesystem::path &fname,
|
||||
DetectorType detector, size_t rows, size_t cols,
|
||||
size_t bitdepth, uint32_t pos_row, uint32_t pos_col)
|
||||
@@ -34,8 +45,9 @@ RawSubFile::RawSubFile(const std::filesystem::path &fname,
|
||||
void RawSubFile::seek(size_t frame_index) {
|
||||
LOG(logDEBUG) << "RawSubFile::seek(" << frame_index << ")";
|
||||
if (frame_index >= m_total_frames) {
|
||||
throw std::runtime_error(LOCATION + " Frame index out of range: " +
|
||||
std::to_string(frame_index));
|
||||
throw frame_error(
|
||||
frame_index,
|
||||
fmt::format("out of range (available frames: {})", m_total_frames));
|
||||
}
|
||||
m_current_frame_index = frame_index;
|
||||
auto file_index = first_larger(m_last_frame_in_file, frame_index);
|
||||
@@ -49,6 +61,9 @@ void RawSubFile::seek(size_t frame_index) {
|
||||
auto byte_offset =
|
||||
frame_offset * (m_bytes_per_frame + sizeof(DetectorHeader));
|
||||
m_file.seekg(byte_offset);
|
||||
if (m_file.fail()) {
|
||||
throw frame_error(frame_index, ifstream_error_msg(m_file));
|
||||
}
|
||||
}
|
||||
|
||||
size_t RawSubFile::tell() {
|
||||
@@ -66,7 +81,7 @@ void RawSubFile::read_into(std::byte *image_buf, DetectorHeader *header) {
|
||||
}
|
||||
|
||||
if (m_file.fail()) {
|
||||
throw std::runtime_error(LOCATION + ifstream_error_msg(m_file));
|
||||
throw frame_error(m_current_frame_index, ifstream_error_msg(m_file));
|
||||
}
|
||||
|
||||
// TODO! expand support for different bitdepths
|
||||
@@ -81,8 +96,8 @@ void RawSubFile::read_into(std::byte *image_buf, DetectorHeader *header) {
|
||||
} else if (m_bitdepth == 32) {
|
||||
read_with_map<uint32_t>(image_buf);
|
||||
} else {
|
||||
throw std::runtime_error(
|
||||
"Unsupported bitdepth for read with pixel map");
|
||||
throw frame_error(m_current_frame_index,
|
||||
"Unsupported bitdepth for read with pixel map");
|
||||
}
|
||||
|
||||
} else {
|
||||
@@ -91,7 +106,7 @@ void RawSubFile::read_into(std::byte *image_buf, DetectorHeader *header) {
|
||||
}
|
||||
|
||||
if (m_file.fail()) {
|
||||
throw std::runtime_error(LOCATION + ifstream_error_msg(m_file));
|
||||
throw frame_error(m_current_frame_index, ifstream_error_msg(m_file));
|
||||
}
|
||||
|
||||
++m_current_frame_index;
|
||||
@@ -135,6 +150,9 @@ size_t RawSubFile::frame_number(size_t frame_index) {
|
||||
seek(frame_index);
|
||||
DetectorHeader h{};
|
||||
m_file.read(reinterpret_cast<char *>(&h), sizeof(DetectorHeader));
|
||||
if (m_file.fail()) {
|
||||
throw frame_error(frame_index, ifstream_error_msg(m_file));
|
||||
}
|
||||
return h.frameNumber;
|
||||
}
|
||||
|
||||
@@ -178,8 +196,8 @@ void RawSubFile::open_file(size_t file_index) {
|
||||
m_file.open(fname, std::ios::binary);
|
||||
if (!m_file.is_open()) {
|
||||
throw std::runtime_error(
|
||||
LOCATION +
|
||||
fmt::format("Could not open file {}", fpath(file_index).string()));
|
||||
fmt::format("Could not open file '{}' for frame index {}",
|
||||
fname.string(), m_current_frame_index));
|
||||
}
|
||||
m_current_file_index = file_index;
|
||||
}
|
||||
@@ -208,4 +226,4 @@ void RawSubFile::scan_files() {
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
+60
-1
@@ -2,11 +2,70 @@
|
||||
#include "aare/RawSubFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "raw_file_helpers.hpp"
|
||||
#include "test_config.hpp"
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/generators/catch_generators.hpp>
|
||||
#include <catch2/matchers/catch_matchers_string.hpp>
|
||||
|
||||
using namespace aare;
|
||||
|
||||
TEST_CASE("RawSubFile errors identify the frame and actual data path",
|
||||
"[RawSubFile][read-errors]") {
|
||||
TemporaryRawFiles files;
|
||||
const size_t offset = GENERATE(0, 5);
|
||||
if (offset != 0) {
|
||||
for (size_t index = 0; index < 2; ++index) {
|
||||
std::filesystem::rename(files.data_path(0, index),
|
||||
files.data_path(0, offset + index));
|
||||
}
|
||||
}
|
||||
RawSubFile file(files.data_path(0, offset), DetectorType::Jungfrau, 2, 3,
|
||||
16);
|
||||
CHECK(file.current_path() == files.data_path(0, offset));
|
||||
std::vector<std::byte> buffer(file.bytes_per_frame() * 3);
|
||||
DetectorHeader header{};
|
||||
const auto second_path = files.data_path(0, offset + 1);
|
||||
const auto index_matcher =
|
||||
Catch::Matchers::ContainsSubstring("frame index 1");
|
||||
const auto path_matcher =
|
||||
Catch::Matchers::ContainsSubstring(second_path.string());
|
||||
const auto context = index_matcher && path_matcher;
|
||||
|
||||
SECTION("truncated header") {
|
||||
std::filesystem::resize_file(second_path, 0);
|
||||
file.seek(1);
|
||||
REQUIRE_THROWS_WITH(file.read_into(buffer.data(), &header), context);
|
||||
}
|
||||
SECTION("truncated pixels") {
|
||||
std::filesystem::resize_file(second_path, sizeof(DetectorHeader));
|
||||
file.seek(1);
|
||||
CHECK(file.current_path() == second_path);
|
||||
REQUIRE_THROWS_WITH(file.read_into(buffer.data()), context);
|
||||
}
|
||||
SECTION("frame number from truncated header") {
|
||||
std::filesystem::resize_file(second_path, 0);
|
||||
REQUIRE_THROWS_WITH(file.frame_number(1), context);
|
||||
}
|
||||
SECTION("missing next file") {
|
||||
std::filesystem::remove(second_path);
|
||||
REQUIRE_THROWS_WITH(file.seek(1), context);
|
||||
}
|
||||
SECTION("batch beyond EOF") {
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.read_into(buffer.data(), size_t{3}),
|
||||
Catch::Matchers::ContainsSubstring("frame index 2") &&
|
||||
Catch::Matchers::ContainsSubstring(second_path.string()));
|
||||
}
|
||||
SECTION("seek beyond EOF") {
|
||||
REQUIRE_THROWS_WITH(
|
||||
file.seek(17),
|
||||
Catch::Matchers::ContainsSubstring("frame index 17") &&
|
||||
Catch::Matchers::ContainsSubstring(
|
||||
files.data_path(0, offset).string()));
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Read frames directly from a RawSubFile", "[.with-data]") {
|
||||
auto fpath_raw =
|
||||
test_data_path() / "raw/jungfrau" / "jungfrau_single_d0_f0_0.raw";
|
||||
@@ -77,4 +136,4 @@ TEST_CASE("Read frames directly from a RawSubFile starting at the second file",
|
||||
auto npy_frame = npy.read_frame();
|
||||
CHECK((image.view() == npy_frame.view<uint16_t>()));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -63,8 +63,9 @@ test_placement(defs::Rotation rotation = defs::Rotation::Identity) {
|
||||
}
|
||||
|
||||
defs::GroupConfig
|
||||
test_group(defs::ModuloOrdering ordering = defs::ModuloOrdering::Forward,
|
||||
int multiplicity = 3, InclusiveROI group_roi = {10, 39, 10, 39}) {
|
||||
large_test_group(defs::ModuloOrdering ordering = defs::ModuloOrdering::Forward,
|
||||
int multiplicity = 3,
|
||||
InclusiveROI group_roi = {10, 39, 10, 39}) {
|
||||
// return {.strixel = {.multiplicity = 3, .pitch_um = 25.0},
|
||||
// .routing = {.mod_order = ordering},
|
||||
// .placement_on_sensor = {10, 39, 10, 39}};
|
||||
@@ -198,82 +199,44 @@ TEST_CASE("strixel_to_pixel_map: explicit mapping test with small ROI",
|
||||
TEST_CASE("strixel_to_pixel_map: user ROI exactly aligned with group ROI",
|
||||
"[remap][strixel_to_pixel_map]") {
|
||||
|
||||
const auto group = test_group();
|
||||
const auto group = large_test_group();
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
// User ROI is in module coordinates.
|
||||
const InclusiveROI user_roi{60, 89, 60, 89};
|
||||
|
||||
// User ROI fully covers group ROI
|
||||
const InclusiveROI user_roi_local =
|
||||
group.placement_on_sensor; // {10, 39, 10, 39}
|
||||
|
||||
const auto result =
|
||||
algo::strixel_to_pixel_map(group, sensor, placement, user_roi, {0, 0});
|
||||
|
||||
// The group occupies [10,39] x [10,39] in sensor-local coordinates.
|
||||
const InclusiveROI expected_roi{10, 39, 10, 39};
|
||||
// ROI aligns exactly with group
|
||||
const InclusiveROI expected_roi = group.placement_on_sensor;
|
||||
|
||||
CHECK(result.effective_roi == expected_roi);
|
||||
CHECK(result.map.shape(0) == 90);
|
||||
CHECK(result.map.shape(1) == 10);
|
||||
|
||||
/*
|
||||
* Mathematical definition of the expected mapping:
|
||||
*
|
||||
* sensor-local pixel:
|
||||
* (x, y)
|
||||
*
|
||||
* corresponding user-ROI pixel:
|
||||
* (x - user_roi_local.xmin) +
|
||||
* (y - user_roi_local.ymin) * user_roi_local.width()
|
||||
*
|
||||
* where user_roi_local is the user ROI rebased from module
|
||||
* coordinates into sensor coordinates.
|
||||
*
|
||||
* For Forward ordering:
|
||||
*
|
||||
* dx = x - group.xmin
|
||||
* dy = y - group.ymin
|
||||
* mod = dx % multiplicity
|
||||
*
|
||||
* strixel_col = dx / multiplicity
|
||||
* strixel_row = dy * multiplicity + mod
|
||||
*
|
||||
* This test deliberately calculates the expected values directly
|
||||
* from those definitions rather than using the implementation's
|
||||
* intermediate calculations.
|
||||
*/
|
||||
for (ssize_t y = result.effective_roi.ymin; y <= result.effective_roi.ymax;
|
||||
++y) {
|
||||
// Check some explicit values
|
||||
CHECK(result.map(0, 0) == 0); // pixel(0, 0)
|
||||
CHECK(result.map(1, 0) == 1); // pixel(0, 1)
|
||||
CHECK(result.map(2, 0) == 2); // pixel(0, 2)
|
||||
CHECK(result.map(0, 1) == 3); // pixel(0, 3)
|
||||
CHECK(result.map(1, 1) == 4); // pixel(0, 4)
|
||||
CHECK(result.map(2, 1) == 5); // pixel(0, 5)
|
||||
|
||||
for (ssize_t x = result.effective_roi.xmin;
|
||||
x <= result.effective_roi.xmax; ++x) {
|
||||
|
||||
const ssize_t dx = x - expected_roi.xmin;
|
||||
const ssize_t dy = y - expected_roi.ymin;
|
||||
|
||||
const ssize_t strixel_row = dy * group.strixel.multiplicity +
|
||||
dx % group.strixel.multiplicity;
|
||||
|
||||
const ssize_t strixel_col = dx / group.strixel.multiplicity;
|
||||
|
||||
const ssize_t expected_pixel =
|
||||
(y - user_roi_local.ymin) * user_roi_local.width() +
|
||||
(x - user_roi_local.xmin);
|
||||
|
||||
CHECK(result.map(strixel_row, strixel_col) == expected_pixel);
|
||||
}
|
||||
}
|
||||
CHECK(result.map(89, 9) == 899); // pixel(29, 29)
|
||||
CHECK(result.map(88, 9) == 898); // pixel(29, 28)
|
||||
CHECK(result.map(87, 9) == 897); // pixel(29, 27)
|
||||
CHECK(result.map(89, 8) == 896); // pixel(29, 26)
|
||||
CHECK(result.map(88, 8) == 895); // pixel(29, 25)
|
||||
CHECK(result.map(87, 8) == 894); // pixel(29, 24)
|
||||
}
|
||||
|
||||
// most important, most generic test (emulating most likely reality)
|
||||
// user ROI larger than group (and larger than sensor)
|
||||
TEST_CASE("strixel_to_pixel_map: user ROI larger than group ROI",
|
||||
"[remap][strixel_to_pixel_map]") {
|
||||
|
||||
const auto group = test_group();
|
||||
const auto group = small_test_group();
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
@@ -283,50 +246,40 @@ TEST_CASE("strixel_to_pixel_map: user ROI larger than group ROI",
|
||||
const auto result =
|
||||
algo::strixel_to_pixel_map(group, sensor, placement, user_roi, {0, 0});
|
||||
|
||||
// The group occupies [10,39] x [10,39] in sensor-local coordinates.
|
||||
const InclusiveROI expected_roi{10, 39, 10, 39};
|
||||
const InclusiveROI expected_roi = group.placement_on_sensor;
|
||||
|
||||
CHECK(result.effective_roi == expected_roi);
|
||||
CHECK(result.map.shape(0) == 90);
|
||||
CHECK(result.map.shape(1) == 10);
|
||||
CHECK(result.map.shape(0) == 6);
|
||||
CHECK(result.map.shape(1) == 2);
|
||||
|
||||
// Rebase into sensor roi:
|
||||
// {50, 99, 50, 99}
|
||||
const InclusiveROI user_roi_local = {-5, 54, -5, 54};
|
||||
// Check every pixel explicitely
|
||||
// First pixel row
|
||||
CHECK(result.map(0, 0) == 915); // pixel (15, 15)
|
||||
CHECK(result.map(1, 0) == 916); // pixel (15, 16)
|
||||
CHECK(result.map(2, 0) == 917); // pixel (15, 17)
|
||||
CHECK(result.map(0, 1) == 918); // pixel (15, 18)
|
||||
CHECK(result.map(1, 1) == 919); // pixel (15, 19)
|
||||
CHECK(result.map(2, 1) == 920); // pixel (15, 20)
|
||||
|
||||
for (ssize_t y = result.effective_roi.ymin; y <= result.effective_roi.ymax;
|
||||
++y) {
|
||||
|
||||
for (ssize_t x = result.effective_roi.xmin;
|
||||
x <= result.effective_roi.xmax; ++x) {
|
||||
|
||||
const ssize_t dx = x - expected_roi.xmin;
|
||||
const ssize_t dy = y - expected_roi.ymin;
|
||||
|
||||
const ssize_t strixel_row = dy * group.strixel.multiplicity +
|
||||
dx % group.strixel.multiplicity;
|
||||
|
||||
const ssize_t strixel_col = dx / group.strixel.multiplicity;
|
||||
|
||||
const ssize_t expected_pixel =
|
||||
(y - user_roi_local.ymin) * user_roi_local.width() +
|
||||
(x - user_roi_local.xmin);
|
||||
|
||||
CHECK(result.map(strixel_row, strixel_col) == expected_pixel);
|
||||
}
|
||||
}
|
||||
// Second pixel row + user_roi.width()
|
||||
CHECK(result.map(3, 0) == 975); // pixel (16, 15)
|
||||
CHECK(result.map(4, 0) == 976); // pixel (16, 16)
|
||||
CHECK(result.map(5, 0) == 977); // pixel (16, 17)
|
||||
CHECK(result.map(3, 1) == 978); // pixel (16, 18)
|
||||
CHECK(result.map(4, 1) == 979); // pixel (16, 19)
|
||||
CHECK(result.map(5, 1) == 980); // pixel (16, 20)
|
||||
}
|
||||
|
||||
// user ROI smaller than group
|
||||
TEST_CASE("strixel_to_pixel_map: user ROI smaller than group ROI",
|
||||
"[remap][strixel_to_pixel_map]") {
|
||||
|
||||
const auto group = test_group();
|
||||
const auto group = large_test_group();
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
// User ROI is in module coordinates.
|
||||
const InclusiveROI user_roi{65, 84, 65, 84};
|
||||
const InclusiveROI user_roi{65, 70, 65, 66};
|
||||
|
||||
const auto result =
|
||||
algo::strixel_to_pixel_map(group, sensor, placement, user_roi, {0, 0});
|
||||
@@ -335,11 +288,11 @@ TEST_CASE("strixel_to_pixel_map: user ROI smaller than group ROI",
|
||||
// coordinates)
|
||||
// Expected intersection:
|
||||
//
|
||||
// user ROI, sensor-local: {15, 34, 15, 34}
|
||||
// user ROI, sensor-local: {15, 20, 15, 16}
|
||||
// group ROI, sensor-local: {10, 39, 10, 39}
|
||||
// ----------------
|
||||
// effective ROI: {15, 34, 15, 34}
|
||||
const InclusiveROI expected_roi = {15, 34, 15, 34};
|
||||
// effective ROI: {15, 20, 15, 16}
|
||||
const InclusiveROI expected_roi = {15, 20, 15, 16};
|
||||
|
||||
CHECK(result.effective_roi == expected_roi);
|
||||
|
||||
@@ -351,131 +304,91 @@ TEST_CASE("strixel_to_pixel_map: user ROI smaller than group ROI",
|
||||
// - The algorithm makes sure that the map shape is always large enough so
|
||||
// that always full multiplicity groups are contained
|
||||
// (In this concrete example:
|
||||
// > width of user_roi is 20
|
||||
// > 20/multiplicity = 6 (plus rest)
|
||||
// > map width of 7 should, in principle, cover it
|
||||
// > width of user_roi is 6
|
||||
// > 6/multiplicity = 2
|
||||
// > map width of 2 should cover it?
|
||||
// > BUT: the placement with respect to the group_roi matters!
|
||||
// > Since both pixels at x = 15 and x = 34 are part of their own
|
||||
// separate multiplicity group, we must add 2 additional
|
||||
// multiplicity groups to the map
|
||||
// > Hence the width of the map becomes 8
|
||||
// )
|
||||
// > Since the group multiplicity chunks are not fully covered by the
|
||||
// ROI, the map will be larger > Hence the width of the map becomes 3
|
||||
// - Entries that are contained in the map but not in the user ROI, will be
|
||||
// mapped to -1
|
||||
CHECK(result.map.shape(0) == 60);
|
||||
CHECK(result.map.shape(1) == 8);
|
||||
CHECK(result.map.shape(0) == 6);
|
||||
CHECK(result.map.shape(1) == 3);
|
||||
|
||||
// Explicit check not mapped example
|
||||
CHECK(result.map(0, 0) == -1); // not mapped because not in user_roi!
|
||||
// Check every pixel explicitely
|
||||
// First pixel row
|
||||
CHECK(result.map(0, 0) == -1); // pixel (0, -2) - not in user_roi
|
||||
CHECK(result.map(1, 0) == -1); // pixel (0, -1) - not in user_roi
|
||||
CHECK(result.map(2, 0) == 0); // pixel (0, 0)
|
||||
CHECK(result.map(0, 1) == 1); // pixel (0, 1)
|
||||
CHECK(result.map(1, 1) == 2); // pixel (0, 2)
|
||||
CHECK(result.map(2, 1) == 3); // pixel (0, 3)
|
||||
CHECK(result.map(0, 2) == 4); // pixel (0, 4)
|
||||
CHECK(result.map(1, 2) == 5); // pixel (0, 5)
|
||||
CHECK(result.map(2, 2) == -1); // pixel (0, 6) - not in user_roi
|
||||
|
||||
// Now we need to establish the valid ROI within the map IN THE MAP SPACE
|
||||
// (i.e. in strixel coordinates)
|
||||
// Map starts at (0,0), but the first valid column is min_col = 1!
|
||||
// (15-10 = 5, 5/3 = 1 (plus rest)
|
||||
// First valid row becomes 15-10 = 5 -> 5*3 = 15
|
||||
constexpr ssize_t expected_min_row = 15;
|
||||
constexpr ssize_t expected_min_col = 1;
|
||||
|
||||
constexpr ssize_t expected_user_roi_local_xmin = 15;
|
||||
constexpr ssize_t expected_user_roi_local_ymin = 15;
|
||||
|
||||
// Check the whole map!
|
||||
// Also, shift strixel row and cols according to min_row/min_cols
|
||||
for (ssize_t map_row = 0; map_row < result.map.shape(0); ++map_row) {
|
||||
for (ssize_t map_col = 0; map_col < result.map.shape(1); ++map_col) {
|
||||
|
||||
const ssize_t strixel_row = expected_min_row + map_row;
|
||||
const ssize_t strixel_col = expected_min_col + map_col;
|
||||
|
||||
const ssize_t dy = strixel_row / group.strixel.multiplicity;
|
||||
const ssize_t mod = strixel_row % group.strixel.multiplicity;
|
||||
const ssize_t dx = strixel_col * group.strixel.multiplicity + mod;
|
||||
|
||||
const ssize_t x = group.placement_on_sensor.xmin + dx;
|
||||
const ssize_t y = group.placement_on_sensor.ymin + dy;
|
||||
|
||||
if (expected_roi.contains(x, y)) {
|
||||
const ssize_t expected_pixel =
|
||||
(y - expected_user_roi_local_ymin) * user_roi.width() +
|
||||
(x - expected_user_roi_local_xmin);
|
||||
|
||||
CHECK(result.map(map_row, map_col) == expected_pixel);
|
||||
} else {
|
||||
// pixel not mapped
|
||||
CHECK(result.map(map_row, map_col) == -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Second pixel row
|
||||
CHECK(result.map(3, 0) == -1); // pixel (1, -2) - not in user_roi
|
||||
CHECK(result.map(4, 0) == -1); // pixel (1, -1) - not in user_roi
|
||||
CHECK(result.map(5, 0) == 6); // pixel (1, 0)
|
||||
CHECK(result.map(3, 1) == 7); // pixel (1, 1)
|
||||
CHECK(result.map(4, 1) == 8); // pixel (1, 2)
|
||||
CHECK(result.map(5, 1) == 9); // pixel (1, 3)
|
||||
CHECK(result.map(3, 2) == 10); // pixel (1, 4)
|
||||
CHECK(result.map(4, 2) == 11); // pixel (1, 5)
|
||||
CHECK(result.map(5, 2) == -1); // pixel (1, 6) - not in user_roi
|
||||
}
|
||||
|
||||
// user ROI partially overlaps group
|
||||
TEST_CASE("strixel_to_pixel_map: user ROI partially overlaps",
|
||||
"[remap][strixel_to_pixel_map]") {
|
||||
|
||||
const auto group = test_group();
|
||||
const auto group = large_test_group();
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
// User ROI is in module coordinates.
|
||||
// In sensor-local coordinates this is {5, 34, 5, 34}.
|
||||
const InclusiveROI user_roi{55, 84, 55, 84};
|
||||
|
||||
// For reference:
|
||||
// user_roi for full covered group = {60, 89, 60, 89};
|
||||
// group roi in sensor coordinates = {10, 39, 10, 39};
|
||||
// In sensor-local coordinates this is {5, 13, 5, 11}.
|
||||
const InclusiveROI user_roi{55, 63, 55, 61};
|
||||
|
||||
const auto result =
|
||||
algo::strixel_to_pixel_map(group, sensor, placement, user_roi, {0, 0});
|
||||
|
||||
// Expected intersection:
|
||||
//
|
||||
// user ROI, sensor-local: { 5, 34, 5, 34}
|
||||
// user ROI, sensor-local: { 5, 13, 5, 11}
|
||||
// group ROI: {10, 39, 10, 39}
|
||||
// ----------------
|
||||
// effective ROI: {10, 34, 10, 34}
|
||||
const InclusiveROI expected_roi{10, 34, 10, 34};
|
||||
// effective ROI: {10, 13, 10, 11}
|
||||
const InclusiveROI expected_roi{10, 13, 10, 11};
|
||||
|
||||
CHECK(result.effective_roi == expected_roi);
|
||||
CHECK(result.map.shape(0) == 75); // 25 pixel rows * 3
|
||||
CHECK(result.map.shape(1) ==
|
||||
9); // Pixel 34 is contained in the 9th multiplicity group
|
||||
CHECK(result.map.shape(0) == 6);
|
||||
CHECK(result.map.shape(1) == 2);
|
||||
|
||||
constexpr ssize_t expected_user_roi_local_xmin = 5;
|
||||
constexpr ssize_t expected_user_roi_local_ymin = 5;
|
||||
// Check every pixel explicitely
|
||||
// First pixel row
|
||||
CHECK(result.map(0, 0) == 50); // pixel (5, 5)
|
||||
CHECK(result.map(1, 0) == 51); // pixel (5, 6)
|
||||
CHECK(result.map(2, 0) == 52); // pixel (5, 7)
|
||||
CHECK(result.map(0, 1) == 53); // pixel (5, 8)
|
||||
CHECK(result.map(1, 1) == -1); // pixel (5, 9) - not in user_roi
|
||||
CHECK(result.map(2, 1) == -1); // pixel (5, 10) - not in user_roi
|
||||
|
||||
for (ssize_t map_row = 0; map_row < result.map.shape(0); ++map_row) {
|
||||
for (ssize_t map_col = 0; map_col < result.map.shape(1); ++map_col) {
|
||||
|
||||
// Map coordinates coincide with the strixel coordinates here
|
||||
// because min_row == min_col == 0.
|
||||
const ssize_t strixel_row = map_row;
|
||||
const ssize_t strixel_col = map_col;
|
||||
|
||||
const ssize_t dy = strixel_row / group.strixel.multiplicity;
|
||||
const ssize_t mod = strixel_row % group.strixel.multiplicity;
|
||||
const ssize_t dx = strixel_col * group.strixel.multiplicity + mod;
|
||||
|
||||
const ssize_t x = group.placement_on_sensor.xmin + dx;
|
||||
const ssize_t y = group.placement_on_sensor.ymin + dy;
|
||||
|
||||
if (expected_roi.contains(x, y)) {
|
||||
const ssize_t expected_pixel =
|
||||
(y - expected_user_roi_local_ymin) * user_roi.width() +
|
||||
(x - expected_user_roi_local_xmin);
|
||||
|
||||
CHECK(result.map(map_row, map_col) == expected_pixel);
|
||||
} else {
|
||||
CHECK(result.map(map_row, map_col) == -1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Second pixel row
|
||||
CHECK(result.map(3, 0) == 59); // pixel (6, 5)
|
||||
CHECK(result.map(4, 0) == 60); // pixel (6, 6)
|
||||
CHECK(result.map(5, 0) == 61); // pixel (6, 7)
|
||||
CHECK(result.map(3, 1) == 62); // pixel (6, 8)
|
||||
CHECK(result.map(4, 1) == -1); // pixel (6, 9) - not in user_roi
|
||||
CHECK(result.map(5, 1) == -1); // pixel (6, 10) - not in user_roi
|
||||
}
|
||||
|
||||
// user ROI does not intersect group
|
||||
TEST_CASE("strixel_to_pixel_map: user ROI does not intersect group ROI",
|
||||
"[remap][strixel_to_pixel_map]") {
|
||||
|
||||
const auto group = test_group();
|
||||
const auto group = large_test_group();
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
@@ -499,7 +412,8 @@ TEST_CASE("strixel_to_pixel_map: modulo ordering",
|
||||
const InclusiveROI user_roi{60, 62, 60, 62};
|
||||
|
||||
SECTION("Forward ordering") {
|
||||
const auto forward_group = test_group(defs::ModuloOrdering::Forward);
|
||||
const auto forward_group =
|
||||
large_test_group(defs::ModuloOrdering::Forward);
|
||||
|
||||
const auto result = algo::strixel_to_pixel_map(
|
||||
forward_group, sensor, placement, user_roi, {0, 0});
|
||||
@@ -526,7 +440,8 @@ TEST_CASE("strixel_to_pixel_map: modulo ordering",
|
||||
}
|
||||
|
||||
SECTION("Reverse ordering") {
|
||||
const auto reverse_group = test_group(defs::ModuloOrdering::Reverse);
|
||||
const auto reverse_group =
|
||||
large_test_group(defs::ModuloOrdering::Reverse);
|
||||
|
||||
const auto result = algo::strixel_to_pixel_map(
|
||||
reverse_group, sensor, placement, user_roi, {0, 0});
|
||||
@@ -638,7 +553,7 @@ TEST_CASE("strixel_to_pixel_map: invalid multiplicity",
|
||||
const defs::ModuloOrdering ordering = defs::ModuloOrdering::Forward;
|
||||
const int multiplicity = 0;
|
||||
|
||||
const auto group = test_group(ordering, multiplicity);
|
||||
const auto group = large_test_group(ordering, multiplicity);
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
@@ -657,7 +572,7 @@ TEST_CASE("strixel_to_pixel_map: group width not divisible by multiplicity",
|
||||
const int multiplicity = 3;
|
||||
const InclusiveROI group_roi = {11, 39, 10, 39}; // width = 29
|
||||
|
||||
const auto group = test_group(ordering, multiplicity, group_roi);
|
||||
const auto group = large_test_group(ordering, multiplicity, group_roi);
|
||||
const auto sensor = test_sensor();
|
||||
const auto placement = test_placement();
|
||||
|
||||
|
||||
+16
-1
@@ -1,4 +1,4 @@
|
||||
#include "to_string.hpp"
|
||||
#include "aare/to_string.hpp"
|
||||
|
||||
namespace aare {
|
||||
|
||||
@@ -254,6 +254,21 @@ template <> UDPPortPosition string_to(const std::string &arg) {
|
||||
"\"");
|
||||
}
|
||||
|
||||
std::string to_string(const corner &arg) {
|
||||
switch (arg) {
|
||||
case corner::cTopLeft:
|
||||
return "TopLeft";
|
||||
case corner::cTopRight:
|
||||
return "TopRight";
|
||||
case corner::cBottomLeft:
|
||||
return "BottomLeft";
|
||||
case corner::cBottomRight:
|
||||
return "BottomRight";
|
||||
default:
|
||||
throw std::runtime_error("Invalid corner value");
|
||||
}
|
||||
}
|
||||
|
||||
std::string remove_unit(std::string &str) {
|
||||
auto it = str.begin();
|
||||
while (it != str.end()) {
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/to_string.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <string>
|
||||
|
||||
#include "to_string.hpp"
|
||||
using aare::string_to;
|
||||
|
||||
TEST_CASE("DetectorType string to enum") {
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
|
||||
#include "aare/defs.hpp"
|
||||
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <nlohmann/json.hpp>
|
||||
#include <string>
|
||||
|
||||
class TemporaryRawFiles {
|
||||
std::filesystem::path m_directory;
|
||||
|
||||
public:
|
||||
explicit TemporaryRawFiles(size_t modules = 1) {
|
||||
const auto unique =
|
||||
std::chrono::steady_clock::now().time_since_epoch().count();
|
||||
m_directory = std::filesystem::temp_directory_path() /
|
||||
("aare-raw-" + std::to_string(unique));
|
||||
std::filesystem::create_directory(m_directory);
|
||||
const nlohmann::json metadata = {
|
||||
{"Version", 7.2},
|
||||
{"Detector Type", "Jungfrau"},
|
||||
{"Timing Mode", "auto"},
|
||||
{"Geometry", {{"x", 1}, {"y", modules}}},
|
||||
{"Image Size in bytes", 12},
|
||||
{"Pixels", {{"x", 3}, {"y", 2}}},
|
||||
{"Max Frames Per File", 1},
|
||||
{"Total Frames", 2},
|
||||
{"Frames in File", 2},
|
||||
{"Frame Padding", 1},
|
||||
{"Frame Discard Policy", "nodiscard"}};
|
||||
std::ofstream(master_path()) << metadata;
|
||||
for (size_t module = 0; module < modules; ++module) {
|
||||
for (size_t file = 0; file < 2; ++file) {
|
||||
std::ofstream output(data_path(module, file), std::ios::binary);
|
||||
aare::DetectorHeader header{};
|
||||
header.frameNumber = 100 + file;
|
||||
const uint16_t pixels[6] = {1, 2, 3, 4, 5, 6};
|
||||
output.write(reinterpret_cast<const char *>(&header),
|
||||
sizeof(header));
|
||||
output.write(reinterpret_cast<const char *>(pixels),
|
||||
sizeof(pixels));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
TemporaryRawFiles(const TemporaryRawFiles &) = delete;
|
||||
TemporaryRawFiles &operator=(const TemporaryRawFiles &) = delete;
|
||||
~TemporaryRawFiles() { std::filesystem::remove_all(m_directory); }
|
||||
|
||||
std::filesystem::path master_path() const {
|
||||
return m_directory / "run_master_0.json";
|
||||
}
|
||||
|
||||
std::filesystem::path data_path(size_t module = 0, size_t file = 0) const {
|
||||
return m_directory / ("run_d" + std::to_string(module) + "_f" +
|
||||
std::to_string(file) + "_0.raw");
|
||||
}
|
||||
};
|
||||
Reference in new issue
Block a user