Merge remote-tracking branch 'origin/main' into feature/cuda_clusterfinder
Build on RHEL8 / build (push) Successful in 4m40s
Build on RHEL9 / build (push) Successful in 5m10s
Run tests using data on local RHEL8 / build (push) Successful in 4m1s

This commit is contained in:
kferjaoui committed 2026-11-17 11:26:21 +01:00
commit 06f2ab5d80
60 files changed
+4429 -69

No files matched your search

+9
View File
@@ -449,6 +449,12 @@ set(PUBLICHEADERS
include/aare/hist/PixelHistogramImpl.hpp
include/aare/hist/PedestalTrackingPixelHistogram.hpp
include/aare/GainMap.hpp
include/aare/StrixelPixelRemapping/InclusiveROI.hpp
include/aare/StrixelPixelRemapping/StrixelPixelRemapConfig.hpp
include/aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp
include/aare/StrixelPixelRemapping/StrixelPixelRemapFormat.hpp
include/aare/StrixelPixelRemapping/BaseStrixelPixelMap.hpp
include/aare/StrixelPixelRemapping/StrixelPixelMaps.hpp
include/aare/ROI.hpp
include/aare/ROIGeometry.hpp
include/aare/DetectorGeometry.hpp
@@ -509,6 +515,7 @@ set(SourceFiles
${CMAKE_CURRENT_SOURCE_DIR}/src/RawFile.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/RawMasterFile.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/RawSubFile.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/StrixelPixelRemapping/StrixelPixelRemapFormat.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/to_string.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/utils/task.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/utils/ifstream_helpers.cpp)
@@ -600,6 +607,8 @@ if(AARE_TESTS)
${CMAKE_CURRENT_SOURCE_DIR}/src/RawFile.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/RawSubFile.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/StrixelPixelRemapping/InclusiveROI.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/StrixelPixelRemapping/StrixelPixelRemapAlgorithm.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/utils/task.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/VarClusterFinder.test.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/utils/RingBufferPool.test.cpp
+1
View File
@@ -142,6 +142,7 @@
- Added the ``AARE_TUNE_LOCAL`` CMake option to build with ``-march=native``
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``
-6
View File
@@ -1885,12 +1885,6 @@ EXTERNAL_GROUPS = YES
EXTERNAL_PAGES = YES
# The PERL_PATH should be the absolute path and name of the perl script
# interpreter (i.e. the result of 'which perl').
# The default file (with absolute path) is: /usr/bin/perl.
PERL_PATH = /usr/bin/perl
#---------------------------------------------------------------------------
# Configuration options related to the XML output
Binary file not shown.

After

Width:  |  Height:  |  Size: 85 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 216 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

@@ -0,0 +1,33 @@
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:
:undoc-members:
.. doxygenfunction:: aare::toInclusiveROI
.. doxygenfunction:: aare::toHalfopenROI
.. doxygenfunction:: aare::inclusiveroi::geom::translate
.. doxygenfunction:: aare::inclusiveroi::geom::to_local
.. doxygenfunction:: aare::inclusiveroi::geom::mirror_on_y
.. doxygenfunction:: aare::inclusiveroi::geom::mirror_on_x
.. doxygenfunction:: aare::inclusiveroi::geom::mirrorXY
.. doxygenfunction:: aare::inclusiveroi::geom::intersect
.. doxygenfunction:: aare::inclusiveroi::geom::unite
.. doxygenfunction:: aare::inclusiveroi::geom::rebaseROI
@@ -0,0 +1,27 @@
.. _map_generators:
Predefined Strixel to Pixel Maps
================================
Includes predefined pixel to strixel maps using 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 Map for 2x2 cm iLGAD Sensor
----------------------------------------
.. doxygenclass:: aare::remap::Jungfrau_iLGAD_StrixelPixelMap
:members:
Predefined Map for 2x2 cm TEW Sensor
----------------------------------------
.. doxygenclass:: aare::remap::Jungfrau_TEW_StrixelPixelMap
:members:
Predefined Maps for 4x4 cm iLGAD Sensor
----------------------------------------
.. doxygenclass:: aare::remap::Jungfrau_iLGAD_Quad_StrixelPixelMap
:members:
@@ -0,0 +1,109 @@
.. _predefined_sensor_configs:
Predefined Sensor Configurations
=================================
Includes all predefined sensor configurations for Jungfrau iLGAD (inverse Low-Gain Avalache Diode) and Jungfrau TEW (Thin Entrance Window) sensors.
The PSI Photon Science Detector Group produces Jungfrau modules with three different sensor types: 2x2 cm iLGAD, 2x2 cm TEW and 4x4 cm iLGAD.
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
---------------------------------
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_iLGAD
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_TEW
.. doxygenvariable:: aare::remap::config::jungfrau::Quad_iLGAD
.. _predefined_strixel_groups:
Predefined Strixel Groups
---------------------------------
.. doxygenvariable:: aare::remap::config::jungfrau::StrxP25
.. doxygenvariable:: aare::remap::config::jungfrau::StrxP15
.. doxygenvariable:: aare::remap::config::jungfrau::StrxP18
.. doxygenvariable:: aare::remap::config::jungfrau::StrxP37
.. _predefined_sensor_placements:
Predefined Sensor Placements on Junfrau Modules
------------------------------------------------
The PSI Photon Science Detector Group produces Jungfrau modules with a 2x2 cm iLGAD/TEW sensor placed on the position of the second chip (Chip1) and the seventh chip (Chip6) of the module.
The larger 4x4cm iLGAD sensors are typically placed on the module's quad (Chip1+Chip2+Chip5+Chip6).
.. doxygenvariable:: aare::remap::config::jungfrau::Chip1
.. doxygenvariable:: aare::remap::config::jungfrau::Chip6
.. doxygenvariable:: aare::remap::config::jungfrau::Quad
2x2 cm iLGAD Sensor:
---------------------
The 2x2 cm iLGAD sensor has a guardring that extends into (and renders unusable for photon detection) part of the active pixel area with height and width of 9 pixels each and spawns over 256x256 pixels.
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_iLGAD_pix
The PSI Photon Science Detector Group produces Jungfrau modules with 2x2 cm iLGAD sensors placed on the position of the second chip (Chip1) ``Chip1`` and the seventh chip (Chip6) ``Chip6`` of the module.
See :ref:`predefined_sensor_placements` for more information.
The sensor is partitioned into three strixel groups ``StrxP25``, ``StrxP15`` and ``StrxP18``. See :ref:`predefined_strixel_groups` for more information.
Strixel group ``StrxP25`` covers the bottom 25 % of the sensor's pixel area (minus the guard ring pixels). Strixel Group ``StrxP15`` covers the next 25 % of the sensor's pixel area. Strixel group ``StrxP18`` covers the top 50 % of the sensor's pixel, whereby it is divided into two partitions (each 25 % of the pixel area) with different dimensioning of the metal layers on top of strixel implants.
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_iLGAD_P25
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_iLGAD_P15
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_iLGAD_P18
2x2 cm TEW Sensor:
---------------------
The 2x2 cm TEW sensor has no guardring extending into the active pixel area and spawns over 256x256 pixels.
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_TEW_pix
The Photon Detector Group produces Jungfrau modules with 2x2 cm TEW sensors placed on the position of the second chip (Chip1) ``Chip1`` and the seventh chip (Chip6) ``Chip6`` of the module.
See :ref:`predefined_sensor_placements` for more information.
The sensor is again partitioned into three pixel groups ``StrxP25``, ``StrxP15`` and ``StrxP18``. See :ref:`predefined_strixel_groups` for more information.
The partition is the same as for the 2x2 cm iLGAD sensor.
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_TEW_P25
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_TEW_P15
.. doxygenvariable:: aare::remap::config::jungfrau::SingleChipMP_TEW_P18
4x4 cm iLGAD Sensor:
---------------------
The 4x4 cm iLGAD sensor has a guardring height and width of 9 pixels each and spawns over 512x512 pixels.
.. doxygenvariable:: aare::remap::config::jungfrau::Quad_iLGAD_pix
The 4x4 cm iLGAD sensor is typically placed on the module's quad (Chip1+Chip2+Chip5+Chip6) ``Quad``. See :ref:`predefined_sensor_placements` for more information.
The sensor is partitioned into two strixel groups ``StrxP25``. See :ref:`predefined_strixel_groups` for more information. The bottom sensor half uses forward pixel-to-strixel routing and the top sensor half uses backward pixel to strixel routing.
.. doxygenvariable:: aare::remap::config::jungfrau::Quad_iLGAD_bottomhalf
.. doxygenvariable:: aare::remap::config::jungfrau::Quad_iLGAD_tophalf
@@ -0,0 +1,89 @@
.. _sensor_configuration:
Sensor Configuration
=====================
Helper structs for strong-typing 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`.
Inputs for the Remapping Algorithm
------------------------------------
The most central input for the :ref:`remap_algorithm` is the sensor configuration given by :code:`SensorConfig`. The :ref:`map_generators` use
:ref:`predefined_sensor_configs` to directly generate the corresponding strixel-to-pixel maps.
.. doxygenstruct:: aare::remap::defs::SensorConfig
:members:
The detailed documentation of all components of :code:`SensorConfig` can be found below in :ref:`sensor_config_components`.
To correctly anchor the coordinate system of the remapping, one can further pass the placement of the sensor on the module,
including its orientation, and specify any potential relative shift of the bump bonding alignment between sensor and ASIC.
.. doxygenstruct:: aare::remap::defs::SensorModulePlacement
:members:
.. doxygenenum:: aare::remap::defs::Rotation
.. doxygenstruct:: aare::remap::defs::BondShift
:members:
.. Note::
The :code:`BondShift` is defined within the local sensor coordinate system before any rotation has been applied, i.e.
sensor and ASIC assembly are rotated as a unity.
.. _sensor_config_components:
Components of SensorConfig
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
.. doxygenstruct:: aare::remap::defs::SensorPixelGeometry
:members:
.. 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::GroupConfig
:members:
Components of GroupConfig
"""""""""""""""""""""""""""
.. doxygenstruct:: aare::remap::defs::GroupStrixelGeometry
:members:
.. doxygenstruct:: aare::remap::defs::GroupRouting
:members:
.. doxygenenum:: aare::remap::defs::ModuloOrdering
Output of Remapping Algorithm
-------------------------------
.. doxygenstruct:: aare::remap::defs::StrixelGroupToPixelMap
: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.
@@ -0,0 +1,19 @@
.. _remap_algorithm:
Core 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`.
.. doxygenclass:: aare::remap::StrixelPixelMap
:members:
:undoc-members:
+119
View File
@@ -0,0 +1,119 @@
.. _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)
or any other user-chosen ROI.
.. IMPORTANT::
To generate a correct strixel-to-pixel map, the relative location of the contiguous strixel region on the sensor with respect
to the reference pixel grid has to be known.
API Overview
----------------
.. figure:: ../../figures/APIConcept.png
:target: ../../figures/APIConcept.png
:width: 650px
:align: center
:alt: API Concept
Basic functionality of the Strixel-to-Pixel Remapping API.
.. admonition:: Core Concept of the API
Define a :code:`SensorConfig` that can contain multiple (N) contiguous strixel groups and the sensor size.
Create a :code:`StrixelPixelMap` from the sensor configuration, its placement and rotation on the module :code:`SensorModulePlacement` and bond shift if applicable.
You can calculate the strixel-to-pixel map by passing a user ROI to the member function :code:`calculate_map()`.
Passing an input to the :code:`StrixelPixelMap` call operator returns the remapped output frame.
For convenience, the API provides **predefined StrixelPixelMap** using **predefined sensor configurations** for the most common senor configurations at the slsDetectorGroup.
API Documentation
------------------
.. toctree::
:maxdepth: 1
SensorConfiguration
StrixelPixelRemapAlgorithm
PredefinedSensorConfigs
PredefinedMaps
InclusiveROI
+3 -1
View File
@@ -31,6 +31,7 @@ AARE
python/experimental/index
python/histogram/index
python/pedestal/index
python/strixelremap/index
pyFit
pyDataSetAggregation
@@ -38,7 +39,7 @@ AARE
.. toctree::
:caption: C++ API
:maxdepth: 1
:maxdepth: 2
algorithm
NDArray
@@ -61,6 +62,7 @@ AARE
RawSubFile
RawMasterFile
VarClusterFinder
StrixelPixelRemapping/index
DataSetAggregation
+144
View File
@@ -0,0 +1,144 @@
.. _py_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)
or any other user-chosen ROI.
.. IMPORTANT::
To generate a correct strixel-to-pixel map, the relative location of the contiguous strixel region on the sensor with respect
to the reference pixel grid has to be known.
Example Usage
-------------
.. code:: python
from aare import strixelremap
import numpy as np
from aare import RawFile
file = RawFile("path/to/master_file.json") # Load a raw file with strixel data
_, frame = file.read_frame() # Read the first frame of the file
rx_roi = frame.master().rois[0] # Get ROI of the frame
# Get the pixel to strixel map for the 25 µm pitch strixels placed on Chip1
pixel_to_strixel_map_25um = strixelremap.Jungfrau_iLGAD_StrixelPixelMap(placement = strixelremap.Chip1)
# calculate the map for the given ROI
pixel_to_strixel_map_25um.calculate_map(rx_roi)
# apply map
mapped_strixels = pixel_to_strixel_map_25um(frame)
Alternatively, one can directly pass the map to the :code:`RawFile` reader to automatically remap the strixels when reading the frame:
.. code:: python
from aare import strixelremap
import numpy as np
from aare import RawFile
# Get the pixel to strixel map for the 25 µm pitch strixels placed on Chip1
pixel_to_strixel_map_25um = strixelremap.Jungfrau_iLGAD_StrixelPixelMap(placement = strixelremap.Chip1)
file = RawFile("path/to/master_file.json") # Load a raw file with strixel data
with RawFile("path/to/master_file.json", strixeltransform = [pixel_to_strixel_map_25um]) as f:
header, frames = f.read_frame()
API Documentation
------------------
.. toctree::
:caption: Pixel to Strixel Remapping
:maxdepth: 1
pySensorConfiguration
pyStrixelPixelRemapAlgorithm
pyInclusiveROI
pyPredefinedMaps
pyPredefinedSensorConfigs
@@ -0,0 +1,17 @@
Inclusive ROI
================
Class for Region of Interest (ROI) using inclusive bounds.
The class is primarily used in the context of pixel-to-strixel remapping.
.. py:currentmodule:: aare.strixelremap
.. autoclass:: InclusiveROI
:special-members: __init__
:members:
.. autofunction:: toInclusiveROI
.. autofunction:: toHalfopenROI
@@ -0,0 +1,32 @@
Predefined Pixel to Strixel Maps
================================
Includes predefined pixel to strixel maps for the sensor configurations introduced in :ref:`python_predefined_sensor_configs`.
Predefined Map for 2x2 cm iLGAD Sensor
----------------------------------------
.. py:currentmodule:: aare.strixelremap
.. autoclass:: Jungfrau_iLGAD_StrixelPixelMap
:special-members: __init__, __call__
:members:
:inherited-members:
Predefined Map for 2x2 cm TEW Sensor
----------------------------------------
.. autoclass:: Jungfrau_TEW_StrixelPixelMap
:special-members: __init__, __call__
:members:
:inherited-members:
Predefined Maps for 4x4 cm iLGAD Sensor
----------------------------------------
.. autoclass:: Jungfrau_iLGAD_Quad_StrixelPixelMap
:special-members: __init__
:members:
:inherited-members:
@@ -0,0 +1,151 @@
.. _python_predefined_sensor_configs:
Predefined Sensor Configurations
=================================
Includes all predefined sensor configurations for Jungfrau iLGAD (inverse Low-Gain Avalache Diode) and Jungfrau TEW (Thin Entrance Window) sensors.
The PSI Photon Science Detector Group produces Jungfrau modules with three different sensor types: 2x2 cm iLGAD, 2x2 cm TEW and 4x4 cm iLGAD.
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.
Predefined Sensor Configurations
---------------------------------
.. py:currentmodule:: aare.strixelremap
.. data:: SingleChipMP_iLGAD
Sensor configuration of the 2x2 cm iLGAD sensor with all strixel groups.
.. data:: SingleChipMP_TEW
Sensor configuration of the 2x2 cm TEW sensor with all strixel groups.
.. data:: Quad_iLGAD
Sensor configuration of the 4x4 cm iLGAD sensor with all strixel groups.
.. _python_predefined_strixel_groups:
Predefined Strixel Groups
---------------------------------
.. data:: StrxP25
Strixel geometry for 25 µm pitch strixels on iLGAD sensors (multiplicity = 3)
.. data:: StrxP15
Strixel geometry for 15 µm pitch strixels on iLGAD sensors (multiplicity = 5)
.. data:: StrxP18
Strixel geometry for 18.75 µm pitch strixels on iLGAD sensors (multiplicity = 4)
.. data:: StrxP37
Strixel geometry for 37.5 µm pitch strixels on iLGAD sensors (multiplicity = 2)
.. _python_predefined_sensor_placements:
Predefined Sensor Placements on Junfrau Modules
------------------------------------------------
The PSI Photon Science Detector Group produces Jungfrau modules with a 2x2 cm iLGAD/TEW sensor placed on the position of the second chip (Chip1) and the seventh chip (Chip6) of the module.
The larger 4x4cm iLGAD sensors are typically placed on the module's quad (Chip1+Chip2+Chip5+Chip6).
.. data:: Chip1
Placement of the 2x2cm iLGAD sensor on the second chip (Chip1) of the Jungfrau module, with no rotation applied.
.. data:: Chip6
Placement of the 2x2cm iLGAD sensor on the seventh chip (Chip6) of the Jungfrau module, with a 180-degree rotation applied.
.. data:: Quad
Placement of the 4x4cm iLGAD sensor on the quad (Chip1+Chip2+Chip5+Chip6) of the Jungfrau module, with no rotation applied.
2x2 cm iLGAD Sensor:
---------------------
The 2x2 cm iLGAD sensor has a guardring that extends into (and renders unusable for photon detection) part of the active pixel area with height and width of 9 pixels each and spawns over 256x256 pixels.
.. data:: SingleChipMP_iLGAD_pix
Pixel geometry for the 2x2 cm iLGAD sensor.
The PSI Photon Science Detector Group produces Jungfrau modules with 2x2 cm iLGAD sensors placed on the position of the second chip (Chip1) ``Chip1`` and the seventh chip (Chip6) ``Chip6`` of the module.
See :ref:`python_predefined_sensor_placements` for more information.
The sensor is partitioned into three strixel groups ``StrxP25``, ``StrxP15`` and ``StrxP18``. See :ref:`python_predefined_strixel_groups` for more information.
Strixel group ``StrxP25`` covers the bottom 25 % of the sensor's pixel area (minus the guard ring pixels). Strixel Group ``StrxP15`` covers the next 25 % of the sensor's pixel area. Strixel group ``StrxP18`` covers the top 50 % of the sensor's pixel, whereby it is divided into two partitions (each 25 % of the pixel area) with different dimensioning of the metal layers on top of strixel implants.
.. data:: SingleChipMP_iLGAD_P25
Strixel group of 25 µm pitch strixels on the 2x2 cm iLGAD sensor.
.. data:: SingleChipMP_iLGAD_P15
Strixel group of 15 µm pitch strixels on the 2x2 cm iLGAD sensor.
.. data:: SingleChipMP_iLGAD_P18
Strixel group of 18.75 µm pitch strixels on the 2x2 cm iLGAD sensor.
2x2 cm TEW Sensor:
---------------------
The 2x2 cm TEW sensor has no guardring extending into the active pixel area and spawns over 256x256 pixels.
.. data:: SingleChipMP_TEW_pix
Pixel geometry for the 2x2 cm TEW sensor.
The Photon Detector Group produces Jungfrau modules with 2x2 cm TEW sensors placed on the position of the second chip (Chip1) ``Chip1`` and the seventh chip (Chip6) ``Chip6`` of the module.
See :ref:`python_predefined_sensor_placements` for more information.
The sensor is again partitioned into three pixel groups ``StrxP25``, ``StrxP15`` and ``StrxP18``. See :ref:`python_predefined_strixel_groups` for more information.
The partition is the same as for the 2x2 cm iLGAD sensor.
.. data:: SingleChipMP_TEW_P25
Strixel group of 25 µm pitch strixels on the 2x2 cm TEW sensor.
.. data:: SingleChipMP_TEW_P15
Strixel group of 15 µm pitch strixels on the 2x2 cm TEW sensor.
.. data:: SingleChipMP_TEW_P18
Strixel group of 18.75 µm pitch strixels on the 2x2 cm TEW sensor.
4x4 cm iLGAD Sensor:
---------------------
The 4x4 cm iLGAD sensor has a guardring height and width of 9 pixels each and spawns over 512x512 pixels.
.. data:: Quad_iLGAD_pix
Pixel geometry for the 4x4 cm iLGAD sensor.
The 4x4 cm iLGAD sensor is typically placed on the module's quad (Chip1+Chip2+Chip5+Chip6) ``Quad``. See :ref:`python_predefined_sensor_placements` for more information.
The sensor is partitioned into two strixel groups ``StrxP25``. See :ref:`python_predefined_strixel_groups` for more information. The bottom sensor half uses forward pixel-to-strixel routing and the top sensor half uses backward pixel to strixel routing.
.. data:: Quad_iLGAD_bottomhalf
Strixel group of 25 µm pitch strixels located on the bottom half of 4x4 cm iLGAD sensor.
.. data:: Quad_iLGAD_tophalf
Strixel group of 25 µm pitch strixels located on the top half of 4x4 cm iLGAD sensor.
@@ -0,0 +1,62 @@
Sensor configurations
=====================
Helper structs for strong-typing 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:`py_strixel_remapping_index`.
.. py:currentmodule:: aare.strixelremap
.. autoclass:: Rotation
:members:
.. autoclass:: ModuloOrdering
:members:
.. autoclass:: BondShift
:noindex:
:members:
:special-members: __init__
.. autoclass:: Guardring
:members:
:special-members: __init__
.. autoclass:: GroupRouting
:members:
:special-members: __init__
.. autoclass:: SensorPixelGeometry
:members:
:special-members: __init__
.. autoclass:: GroupStrixelGeometry
:members:
:special-members: __init__
.. autoclass:: GroupConfig
:members:
:special-members: __init__
.. autoclass:: SensorModulePlacement
:members:
:special-members: __init__
.. autoclass:: StrixelGroupToPixelMap
:members:
:special-members: __init__
**Helper functions to create SensorConfig with N pixel groups:**
.. autofunction:: SensorConfig
:noindex:
.. code:: python
from aare import strixelremap
strixelremap.SensorConfig(strixelremap.SingleChipMP_iLGAD_pix, [strixelremap.StrxP15, strixelremap.StrxP25]) # returns a SensorConfig_2PixelGroups
@@ -0,0 +1,25 @@
Strixel to Pixel Remapping
==============================
.. py:currentmodule:: aare.strixelremap
**Helper functions to create StrixelPixelMap from SensorConfig with N pixel groups:**
.. autofunction:: StrixelPixelMap
:noindex:
.. code:: python
from aare import strixelremap
strixelpixelmap = strixelremap.StrixelPixelMap(strixelremap.SensorConfig(strixelremap.SingleChipMP_iLGAD_pix, [strixelremap.StrxP25]), strixelremap.Chip1, strixelremap.BondShift(2, 2)) # returns a StrixelPixelMap for the custom SensorConfig with Sensored placed on Chip1 and a BondShift of 2 pixels in x and y direction
**Example of the full StrixelPixelRemap class for a SensorConfig with 3 pixel groups:**
.. autoclass:: StrixelPixelMap_3Groups_3Maps
:special-members: __init__, __call__
:members:
:inherited-members:
+16 -3
View File
@@ -93,6 +93,19 @@ NDArray<double, 3> block_mean(const std::filesystem::path &path,
mean_over_num_frames);
buffers.commit_write(i);
fmt::print("\rProgress: {}/{} ({:.1f}%)",
(i + 1) * mean_over_num_frames,
num_samples * mean_over_num_frames,
num_samples * mean_over_num_frames == 0
? 100.0
: 100.0 *
static_cast<double>((i + 1) *
mean_over_num_frames) /
static_cast<double>(num_samples *
mean_over_num_frames));
std::fflush(stdout);
}
} catch (...) {
buffers.abort(); // wake up the other threads so they can exit
@@ -141,9 +154,7 @@ NDArray<double, 3> block_mean(const std::filesystem::path &path,
};
std::vector<std::future<void>> futures;
futures.reserve(num_processing_threads + 1);
futures.push_back(std::async(std::launch::async, reader));
futures.reserve(num_processing_threads);
const size_t rows_per_worker = rows / num_processing_threads;
for (size_t w = 0; w < num_processing_threads; ++w) {
@@ -154,6 +165,8 @@ NDArray<double, 3> block_mean(const std::filesystem::path &path,
w * rows_per_worker, row_end));
}
reader(); // run reader in main thread to avoid extra thread creation
for (auto &f : futures) {
try {
f.get();
+1
View File
@@ -128,6 +128,7 @@ class Interpolator {
* @param ix index of etaX bin
* @param iy index of etaY bin
* @param ie index of energy bin
* @param eta eta values of the cluster
* @return pair of interpolated transformed eta values (ietax, ietay)
*/
template <typename T>
+1
View File
@@ -89,6 +89,7 @@ class JungfrauDataFile : public FileInterface {
/**
* @brief Read a single frame from the file into the given NDArray
* @param image NDArray to read the frame into.
* @param header pointer to a JungfrauDataHeader or nullptr (to skip header)
*/
void read_into(NDArray<uint16_t> *image,
JungfrauDataHeader *header = nullptr);
+3 -1
View File
@@ -207,6 +207,8 @@ class RawFile : public FileInterface {
* @param frame_index frame number to read
* @param frame_buffer buffer to store the frame
* @param roi_index index of the ROI to read (default is 0 e.g. full frame)
* @param header if non-null, receives one DetectorHeader per module in
* the ROI
*/
void get_frame_into(
size_t frame_index, std::byte *frame_buffer, const size_t roi_index = 0,
@@ -214,7 +216,7 @@ class RawFile : public FileInterface {
/**
* @brief get the frame at the given frame index
* @param frame_number frame number to read
* @param frame_index frame number to read
* @param roi_index index of the ROI to read (default is 0 e.g. full frame)
* @return Frame
*/
+2
View File
@@ -49,6 +49,8 @@ class RawSubFile {
* @param rows number of rows in the subfile
* @param cols number of columns in the subfile
* @param bitdepth bitdepth of the subfile
* @param pos_row row position of the subfile in the full detector image
* @param pos_col column position of the subfile in the full detector image
* @throws std::invalid_argument if the detector,type pair is not supported
*/
RawSubFile(const std::filesystem::path &fname, DetectorType detector,
@@ -0,0 +1,462 @@
#pragma once
#include "aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp"
namespace aare::remap {
using namespace defs;
// Internal geometry helper
namespace detail {
/**
* @brief Apply physical transformations to a sensor-local ROI.
*
* IMPORTANT:
* Bond shifts are applied before rotation.
* The order is intentional because bond shifts are defined in the
* sensor's native coordinate system.
*
* This function is not intended to be exposed to the public
*/
InclusiveROI inline update_pixel_group_placement(
InclusiveROI roi, defs::SensorPixelGeometry const &pixel,
defs::BondShift bond_shift, defs::Rotation rot) {
// If there is a bond shift, translate the roi
if (bond_shift.x != 0 || bond_shift.y != 0)
roi = aare::inclusiveroi::geom::translate(roi, bond_shift.x,
bond_shift.y);
// If there is a rotation given, mirror in X and Y (emulates a rotation)
if (rot == defs::Rotation::Rotate180)
roi = aare::inclusiveroi::geom::mirrorXY(roi, pixel.num_pix_x / 2,
pixel.num_pix_y / 2);
return roi;
}
} // namespace detail
namespace detail {
struct StrixelPixelMapBindingAccess;
}
template <std::size_t N, std::size_t M = N> class StrixelPixelMap {
friend struct detail::StrixelPixelMapBindingAccess;
public:
StrixelPixelMap(const SensorConfig<N> &sensor_config,
const SensorModulePlacement &module_placement,
const BondShift &bond_shift = BondShift{0, 0});
virtual ~StrixelPixelMap() = default;
/**
* @brief Calculate the strixel-to-pixel order maps for all strixel groups
* based on the user-specified ROI.
* @param user_roi User-specified ROI in the module's native coordinate
* system.
*/
virtual void calculate_map(const ROI &user_roi);
/**
* @brief Apply the strixel-to-pixel remapping to an input array.
* @param user_roi User-specified ROI in the module's native coordinate
* system.
* @param input Input array to be remapped.
* @return std::array<NDArray<T, 2>, N> Remapped arrays for each strixel
* group.
*/
template <typename T>
std::array<NDArray<T, 2>, M> operator()(const ROI &user_roi,
const NDView<T, 2> input);
/**
* @brief Apply the strixel-to-pixel remapping to an input array.
* @param input Input array to be remapped.
* @return std::array<NDArray<T, 2>, N> Remapped arrays for each strixel
* group.
* @throws std::runtime_error If the input shape does not match the user ROI
* shape.
* @note This overload assumes that the user ROI has already been set and
* the map calculated using `calculate_map()`.
*/
template <typename T>
std::array<NDArray<T, 2>, M> operator()(const NDView<T, 2> input) const;
/**
* @brief Apply the strixel-to-pixel remapping to an input array.
* @param input Input array to be remapped.
* @param output Preallocated array to store the remapped results for each
* strixel group.
* @throws std::runtime_error If the output shape does not match the user
* ROI shape.
* @note This overload assumes that the user ROI has already been set and
* the map calculated using `calculate_map()`.
*/
template <typename T>
void operator()(const NDView<T, 2> input,
std::array<NDArray<T, 2>, M> &output) const;
/**
* @brief Get the strixel-to-pixel maps for all strixel groups.
* @return std::array<defs::StrixelGroupToPixelMap, M> Array of
* strixel-to-pixel maps. Maps are empty if the groups are not covered by
* the user ROI.
*/
std::array<defs::StrixelGroupToPixelMap, M> get_group_maps() const {
return m_group_maps;
}
const std::array<defs::StrixelGroupToPixelMap, M> &
get_group_maps_ref() const {
return m_group_maps;
}
/**
* @brief Get the strixel-to-pixel map for a specific strixel group.
* @param group_index Index of the strixel group (0-based).
* @return const defs::StrixelGroupToPixelMap& Strixel-to-pixel map for the
* specified group. Map is empty if the group is not covered by the user
* ROI.
* @throws std::out_of_range If the group_index is out of bounds (not in [0,
* M)).
*/
const defs::StrixelGroupToPixelMap &
get_group_map(std::size_t group_index) const {
if (group_index >= M) {
throw std::out_of_range("group_index out of bounds");
}
return m_group_maps[group_index];
}
/**
* @brief Get the sensor configuration associated with this StrixelPixelMap.
* @return const SensorConfig<N>& The sensor configuration.
*/
const SensorConfig<N> &get_SensorConfig() const { return m_sensorconfig; }
protected:
/**
* @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 chunk; it does not reverse the complete
* strixel column ordering.
*
* The sensor pixel geometry, module placement, bond shift and user ROI
* are taken from the members of this StrixelPixelMap.
*
* @param group_config Configuration of the strixel group to be mapped.
* @return A StrixelGroupToPixelMap describing the mapping from strixel
* coordinates to pixel indices in the user-provided ROI.
* - map(strixel_row,strixel_col) = pixel_index_in_user_roi
* - Invalid or unmapped strixel positions are initialized to -1.
* @throws std::logic_error For negative or zero strixel multiplicity.
* @throws std::logic_error If the group ROI width is not divisible by
* the strixel multiplicity.
*/
defs::StrixelGroupToPixelMap
strixel_to_pixel_map(defs::GroupConfig const &group_config);
/**
* @brief Applies all the group maps to the input.
* @param input Original array
* @return std::array<NDArray<T, 2>, N> Remapped arrays for each group
* @throws std::invalid_argument If the output shape does not match the
* order map shape for any group.
*/
template <typename T>
std::array<NDArray<T, 2>, M> apply_remap(const NDView<T, 2> input) const;
/**
* @brief Applies a given remapping rule to an input array.
* @param input Original array
* @param order_map Rule for remapping (e.g. the output of a map generator)
* @param output Remapped array
*/
template <typename T>
void apply_group_remap(const NDView<T, 2> input, NDView<T, 2> output,
const NDView<const ssize_t, 2> order_map) const;
protected:
InclusiveROI m_user_roi{};
std::array<defs::StrixelGroupToPixelMap, M>
m_group_maps{}; // TODO: do we need to store effective ROI?
SensorConfig<N> m_sensorconfig{};
private:
SensorModulePlacement m_module_placement{};
BondShift m_bond_shift{};
};
template <std::size_t N, std::size_t M>
StrixelPixelMap<N, M>::StrixelPixelMap(
const SensorConfig<N> &sensor_config,
const SensorModulePlacement &module_placement, const BondShift &bond_shift)
: m_sensorconfig(sensor_config), m_module_placement(module_placement),
m_bond_shift(bond_shift) {}
template <std::size_t N, std::size_t M>
void StrixelPixelMap<N, M>::calculate_map(const ROI &user_roi) {
m_user_roi = toInclusiveROI(user_roi);
for (size_t i = 0; i < N; ++i) {
m_group_maps[i] = strixel_to_pixel_map(m_sensorconfig.group_configs[i]);
}
}
template <std::size_t N, std::size_t M>
template <typename T>
std::array<NDArray<T, 2>, M>
StrixelPixelMap<N, M>::operator()(const ROI &user_roi,
const NDView<T, 2> input) {
if (m_user_roi.is_empty()) {
calculate_map(user_roi);
return apply_remap(input);
} else if (toInclusiveROI(user_roi) != m_user_roi) {
calculate_map(user_roi);
return apply_remap(input);
} else {
return apply_remap(input);
}
}
template <std::size_t N, std::size_t M>
template <typename T>
std::array<NDArray<T, 2>, M>
StrixelPixelMap<N, M>::operator()(const NDView<T, 2> input) const {
if (input.shape() !=
std::array<ssize_t, 2>{m_user_roi.height(), m_user_roi.width()}) {
throw std::runtime_error(
fmt::format("shape mismatch between input and map: input shape = "
"({},{}), expected shape = ({},{})",
input.shape()[0], input.shape()[1], m_user_roi.height(),
m_user_roi.width()));
}
return apply_remap(input);
}
template <std::size_t N, std::size_t M>
template <typename T>
void StrixelPixelMap<N, M>::operator()(
const NDView<T, 2> input, std::array<NDArray<T, 2>, M> &output) const {
if (input.shape() !=
std::array<ssize_t, 2>{m_user_roi.height(), m_user_roi.width()}) {
throw std::runtime_error(
fmt::format("shape mismatch between input and map: input shape = "
"({},{}), expected shape = ({},{})",
input.shape()[0], input.shape()[1], m_user_roi.height(),
m_user_roi.width()));
}
if (output.size() != m_group_maps.size()) {
throw std::runtime_error(
"output array size does not match number of group maps");
}
for (size_t i = 0; i < m_group_maps.size(); ++i) {
if (m_group_maps[i].empty()) {
output[i] = NDArray<T, 2>{};
continue;
}
apply_group_remap(input, output[i].view(), m_group_maps[i].map.view());
}
}
template <std::size_t N, std::size_t M>
template <typename T>
std::array<NDArray<T, 2>, M>
StrixelPixelMap<N, M>::apply_remap(const NDView<T, 2> input) const {
// TODO: maybe vector is better - empty ROIs - write tests !!!
std::array<NDArray<T, 2>, M> outputs;
for (size_t i = 0; i < m_group_maps.size(); ++i) {
if (m_group_maps[i].empty()) {
outputs[i] = NDArray<T, 2>{};
continue;
}
outputs[i] = NDArray<T, 2>{m_group_maps[i].map.shape()};
apply_group_remap(input, outputs[i].view(), m_group_maps[i].map.view());
}
return outputs;
}
template <std::size_t N, std::size_t M>
template <typename T>
void StrixelPixelMap<N, M>::apply_group_remap(
const NDView<T, 2> input, NDView<T, 2> output,
const NDView<const ssize_t, 2> order_map) const {
if (output.shape() != order_map.shape()) {
throw std::invalid_argument(
"output shape does not match order map shape");
}
const auto nrows = order_map.shape(0);
const auto ncols = order_map.shape(1);
for (ssize_t row = 0; row < nrows; ++row) {
for (ssize_t col = 0; col < ncols; ++col) {
auto flat_index = order_map(row, col);
// Intentionally not-mapped pixel in order_map (e.g. guard ring
// pixels)
if (flat_index < 0) {
output(row, col) = T{};
continue;
}
// Corrupt map, must throw
if (flat_index >= input.size()) {
throw std::runtime_error(
"order map contains an invalid pixel index.");
}
// Correctly mapped pixel
output(row, col) = input[flat_index];
}
}
}
template <std::size_t N, std::size_t M>
defs::StrixelGroupToPixelMap StrixelPixelMap<N, M>::strixel_to_pixel_map(
defs::GroupConfig const &group_config) {
const int multiplicity = group_config.strixel.multiplicity;
// Defensive check to be sure misconfiguration is avoided
if (multiplicity <= 0)
throw std::logic_error("Strixel multiplicity must be positive");
// The group must contain an integer number of strixel columns.
const auto group_width = group_config.placement_on_sensor.width();
if (group_width % multiplicity != 0)
throw std::logic_error(
"Group ROI width must be divisible by strixel multiplicity");
// const int total_strixel_columns = group_width / multiplicity;
// Determine the ordering of strixels within each multiplicity group.
std::vector<int> mods(multiplicity);
std::iota(mods.begin(), mods.end(), 0);
if (group_config.routing.mod_order == defs::ModuloOrdering::Reverse)
std::reverse(mods.begin(), mods.end());
// -- 1) Rebase the user ROI (rx_roi) into sensor-local coordinates
const InclusiveROI roi_user_local = inclusiveroi::geom::rebaseROI(
m_user_roi, m_module_placement.placement_on_module);
LOG(logDEBUG)
<< "aare::remap::algo::strixel_to_pixel_map: Transformed user ROI: "
<< roi_user_local << std::endl;
LOG(logDEBUG) << "aare::remap::algo::strixel_to_pixel_map: Group ROI "
"before transformation (as in global config)"
<< group_config.placement_on_sensor << '\n';
// -- 2) Apply the physical bond shift first, sensor rotation second.
const InclusiveROI roi_group = detail::update_pixel_group_placement(
group_config.placement_on_sensor, m_sensorconfig.pixel, m_bond_shift,
m_module_placement.rotation);
LOG(logDEBUG) << "aare::remap::algo::strixel_to_pixel_map: Group ROI after "
"transformation (as in local transformation) "
<< roi_group << '\n';
// -- 3) Compute effective ROI = intersection( roi_user, roi_group )
// Only pixels covered by both the user ROI and the transformed group
// contribute to this map.
const InclusiveROI effective_roi =
inclusiveroi::geom::intersect(roi_user_local, roi_group);
// If ROIs don't intersect, return empty
if (effective_roi.xmax < effective_roi.xmin ||
effective_roi.ymax < effective_roi.ymin) {
LOG(logWARNING)
<< "User-supplied ROI does not intersect with configured "
"strixel ROI, returned map is empty!\n";
return {{}, InclusiveROI::emptyROI()};
}
LOG(logDEBUG) << "aare::remap::algo::strixel_to_pixel_map: Result of "
"intersecting ROIs "
<< effective_roi << '\n';
/******************************
* Core of the algorithm
*
* Local lambda:
* Convert a sensor-local pixel coordinate into the corresponding
* local strixel coordinate.
* (Could be a separate function if preferred.)
******************************/
auto pixel_to_strixel = [&](int x, int y) {
const int dx = x - roi_group.xmin;
const int dy = y - roi_group.ymin;
const int mod = dx % multiplicity;
const int col = dx / multiplicity;
const int row = dy * multiplicity + mods[mod];
return std::pair<int, int>{row, col};
};
//-- 4) Determine the range of strixel coordinates touched by the effective
// ROI.
//
// Since effective_roi is contained in roi_group:
// dx = x - roi_group.xmin >= 0
// dy = y - roi_group.ymin >= 0
//
// The strixel column is dx / multiplicity.
// Each pixel row maps onto a complete block of `multiplicity`
// strixel rows, regardless of the modulo ordering.
const int min_col = (effective_roi.xmin - roi_group.xmin) / multiplicity;
const int max_col = (effective_roi.xmax - roi_group.xmin) / multiplicity;
const int min_row = (effective_roi.ymin - roi_group.ymin) * multiplicity;
// Catch the first row that is out of bounds (next multiplicity group) and
// calculate -1
const int max_row =
(effective_roi.ymax - roi_group.ymin + 1) * multiplicity - 1;
// Now from the found bounds of the strixel grid, we define the space to
// allocate for the order map
const int nrows = max_row - min_row + 1;
const int ncols = max_col - min_col + 1;
// And allocate
aare::NDArray<ssize_t, 2> map({nrows, ncols}, -1);
LOG(logDEBUG)
<< "aare::remap::algo::strixel_to_pixel_map: Resulting strixel grid: ("
<< map.shape(0) << ", " << map.shape(1) << ")" << '\n';
// -- 5) Populate the strixel-to-user-pixel map.
for (int y = effective_roi.ymin; y <= effective_roi.ymax; ++y) {
for (int x = effective_roi.xmin; x <= effective_roi.xmax; ++x) {
auto [row, col] = pixel_to_strixel(x, y);
const int map_col = col - min_col;
const int map_row = row - min_row;
// index into !!!ORIGINAL USER ROI GRID!!!
const ssize_t user_pixel =
static_cast<ssize_t>(y - roi_user_local.ymin) *
roi_user_local.width() +
(x - roi_user_local.xmin);
map(map_row, map_col) = user_pixel;
}
}
return {map, effective_roi};
}
} // namespace aare::remap
@@ -0,0 +1,254 @@
#pragma once
#include <aare/ROI.hpp>
#include <aare/defs.hpp>
#include <aare/logger.hpp>
#include <cstddef>
#include <iostream>
#include <stdexcept>
namespace aare {
/// @brief Inclusive Region of Interest (ROI) with inclusive bounds.
struct InclusiveROI {
/// @brief start of x-coordinate.
ssize_t xmin;
/// @brief end of x-coordinate (inclusive).
ssize_t xmax;
/// @brief start of y-coordinate.
ssize_t ymin;
/// @brief end of y-coordinate (inclusive).
ssize_t ymax;
constexpr ssize_t width() const noexcept { return xmax - xmin + 1; }
constexpr ssize_t height() const noexcept { return ymax - ymin + 1; }
constexpr ssize_t size() const noexcept { return width() * height(); }
[[nodiscard]] constexpr bool is_empty() const noexcept {
return xmax < xmin || ymax < ymin;
}
[[nodiscard]] constexpr bool contains(ssize_t x, ssize_t y) const noexcept {
return x >= xmin && x <= xmax && y >= ymin && y <= ymax;
}
[[nodiscard]] constexpr bool fits_in(ssize_t ncols,
ssize_t nrows) const noexcept {
return xmin >= 0 && ymin >= 0 && xmax < ncols && ymax < nrows;
}
constexpr bool operator==(InclusiveROI const &other) const noexcept {
return xmin == other.xmin && xmax == other.xmax && ymin == other.ymin &&
ymax == other.ymax;
}
constexpr bool operator!=(InclusiveROI const &other) const noexcept {
return !(*this == other);
}
static InclusiveROI emptyROI() noexcept { return {0, -1, 0, -1}; }
// TODO (nice to have)
// static InclusiveROI from_shape(ssize_t width, ssize_t height);
};
/**
* @brief transorms a half-open ROI to an inclusive ROI
* @param r half-open ROI
* @return inclusive ROI with same physical extent
*/
inline InclusiveROI toInclusiveROI(ROI const &r) {
return {r.xmin, r.xmax - 1, r.ymin, r.ymax - 1};
}
/** @brief
* @brief Transforms an inclusive ROI to a half-open ROI
* @param r inclusive ROI
* @return half-open ROI with same physical extent
*/
inline ROI toHalfopenROI(InclusiveROI const &r) {
return {r.xmin, r.xmax + 1, r.ymin, r.ymax + 1};
}
/***********************
* Printing utility
***********************/
inline std::ostream &operator<<(std::ostream &os, InclusiveROI const &roi) {
os << "ROI (inclusive): x=[" << roi.xmin << ", " << roi.xmax << "], y=["
<< roi.ymin << ", " << roi.ymax << "], width=" << roi.width()
<< ", height=" << roi.height() << ", pixels=" << roi.size();
return os;
}
} // namespace aare
namespace aare::inclusiveroi::geom {
/**
* @brief Coordinate space transforms for InclusiveROI.
* @param r InclusiveROI to be transformed
* @param dx translation in x direction
* @param dy translation in y direction
* @return InclusiveROI translated by (dx, dy)
*/
static inline InclusiveROI translate(InclusiveROI r, ssize_t dx, ssize_t dy) {
return {r.xmin + dx, r.xmax + dx, r.ymin + dy, r.ymax + dy};
}
/**
* @brief Convert an InclusiveROI to a local coordinate system with origin at
* (0,0).
* @param roi InclusiveROI to be converted
* @return InclusiveROI in local coordinates
*/
static inline InclusiveROI to_local(InclusiveROI const &roi) {
return {0, roi.xmax - roi.xmin, 0, roi.ymax - roi.ymin};
}
/**
* @brief Mirror an ROI on a given y-axis (vertical axis), thereby reflecting
* its x-coordinates horizontally
*
* The ROI is translated to the horizontally mirrored position while
* preserving its size
*
* Example:
* \verbatim
*
* yaxis_coord yaxis_coord
* -----------|----------- -----------|-----------
* | | r.xmax | | x0p | x1p |
* | ******|******** | | ********|****** |
* | * | roi * | -> | *mirrored roi * |
* | * | * | | * | * |
* | ******|******** | | ********|****** |
* | | | | | |
* -----------|----------- -----------|-----------
* \endverbatim
* @param r The ROI to be mirrored
* @param yaxis_coord The y-axis coordinate (in x) expressed in pixel
* coordinates
*/
static inline InclusiveROI mirror_on_y(InclusiveROI r, ssize_t yaxis_coord) {
// int x0p = (width - 1) - r.xmax;
// int x1p = (width - 1) - r.xmin;
int x0p = yaxis_coord * 2 - r.xmax - 1;
int x1p = x0p + r.width() - 1;
return {x0p, x1p, r.ymin, r.ymax};
}
/**
* @brief Mirror an ROI on a given x-axis (horizontal axis), thereby reflecting
* its y-coordinates vertically
*
* The ROI is translated to the vertically mirrored position while
* preserving its size
*
* @param r The ROI to be mirrored
* @param xaxis_coord The x-axis coordinate (in y) expressed in pixel
* coordinates
*/
static inline InclusiveROI mirror_on_x(InclusiveROI r, ssize_t xaxis_coord) {
// int y0p = (height - 1) - r.ymax;
// int y1p = (height - 1) - r.ymin;
int y0p = xaxis_coord * 2 - r.ymax - 1;
int y1p = y0p + r.height() - 1;
return {r.xmin, r.xmax, y0p, y1p};
}
/**
* @brief Mirror both x- and y-coordinates.
*
* This is equivalent to a 180° rotation about the axes intersection.
* @param r The ROI to be mirrored
* @param xaxis_coord The x-axis coordinate (in y) expressed in pixel
* coordinates
* @param yaxis_coord The y-axis coordinate (in x) expressed in pixel
* coordinates
*/
static inline InclusiveROI mirrorXY(InclusiveROI r, ssize_t xaxis_coord,
ssize_t yaxis_coord) {
// return {mirrorX(mirrorY(r, height), width)};
return {mirror_on_y(mirror_on_x(r, xaxis_coord), yaxis_coord)};
}
/**
* @brief Compute the intersection of two InclusiveROIs.
* @param a First InclusiveROI
* @param b Second InclusiveROI
* @return InclusiveROI representing the intersection of a and b or empty ROI if
* they do not intersect
*/
static inline InclusiveROI intersect(InclusiveROI const &a,
InclusiveROI const &b) {
InclusiveROI r;
r.xmin = std::max(a.xmin, b.xmin);
r.ymin = std::max(a.ymin, b.ymin);
r.xmax = std::min(a.xmax, b.xmax);
r.ymax = std::min(a.ymax, b.ymax);
if (r.xmin > r.xmax || r.ymin > r.ymax) {
LOG(TLogLevel::logWARNING) << "ROIs do not intersect!" << std::endl;
return InclusiveROI::emptyROI(); // empty
}
return r;
}
/**
* @brief Compute the union of two InclusiveROIs.
* @param a First InclusiveROI
* @param b Second InclusiveROI
* @return InclusiveROI representing the union of a and b if they are contiguous
* @throws std::runtime_error if the ROIs cannot be united contiguously
*/
static inline InclusiveROI unite(InclusiveROI const &a, InclusiveROI const &b) {
// Horizontal union: same y-range
if (a.ymin == b.ymin && a.ymax == b.ymax) {
if (a.xmax + 1 >= b.xmin &&
b.xmax + 1 >= a.xmin) { // overlap or adjacent
return {std::min(a.xmin, b.xmin), std::max(a.xmax, b.xmax), a.ymin,
a.ymax};
}
}
// Vertical union: same x-range
if (a.xmin == b.xmin && a.xmax == b.xmax) {
if (a.ymax + 1 >= b.ymin &&
b.ymax + 1 >= a.ymin) { // overlap or adjacent
return {a.xmin, a.xmax, std::min(a.ymin, b.ymin),
std::max(a.ymax, b.ymax)};
}
}
throw std::runtime_error("ROIs cannot be united contiguously");
}
/**
* @brief Rebase an ROI into the coordinate system of another ROI.
* @param roi_input The ROI to be rebased
* @param roi_base The base ROI defining the new coordinate system
* @return InclusiveROI expressed in the coordinate system of roi_base
*
* The returned ROI has the same physical extent, but is expressed relative
* to roi_base instead of the original coordinate system.
*
* In other words, roi_base.xmin/ymin become the new origin (0,0).
* Example:
*
* Global coordinates:
*
* roi_base = [100..199] x [50..149] \n
* roi_input = [120..139] x [70..89] \n
*
* After rebasing:
*
* roi_input = [20..39] x [20..39] \n
*/
static inline InclusiveROI rebaseROI(InclusiveROI const &roi_input,
InclusiveROI const &roi_base) {
return translate(roi_input, -roi_base.xmin, -roi_base.ymin);
}
} // namespace aare::inclusiveroi::geom
@@ -0,0 +1,196 @@
#include "aare/StrixelPixelRemapping/BaseStrixelPixelMap.hpp"
#include "aare/StrixelPixelRemapping/StrixelPixelRemapConfig.hpp"
namespace aare::remap {
namespace detail {
// ============================================================
// Internal implementation details
// ============================================================
// Current quick-and-dirty inclusion of a helper function to combine group maps.
// This becomes necessary for sensors like Quad_iLGAD that combine two
// independent mapping regions separated by invalid gap rows. (Used to live as
// `combine_maps` in RemapAlgorithm, but arguably should not be part of that
// public API). Eventually, one could instead split RemapGenerate into hpp and
// cpp and make this one live in an unnamed namespace inside the cpp so that it
// cannot be exposed to the user through the public API (if we want to avoid
// that)
/**
* @brief Combine TWO vertically ordered group remapping maps.
*
* Concatenates the maps in the order provided, inserting `gap_rows`
* rows of invalid entries (-1) between consecutive groups.
*
* The input maps must be ordered in the desired output order.
* Both maps must have the same number of columns.
*
* The returned effective ROI is the bounding ROI covering the
* effective ROIs of both input groups. It describes the physical
* source-pixel region and does not encode the artificial strixel
* gap rows in the output map.
*
* @param first Group map that comes first in output space.
* @param second Group map that comes second in output space.
* @param gap_rows Number of invalid strixel rows inserted between groups.
*
* @return Combined strixel-to-pixel map.
*
* @throws std::logic_error if group maps have different widths.
*/
defs::StrixelGroupToPixelMap
combine_group_maps(defs::StrixelGroupToPixelMap const &first,
defs::StrixelGroupToPixelMap const &second,
size_t gap_rows) {
const ssize_t ncols = first.map.shape(1);
// Make sure both maps have the same width.
if (second.map.shape(1) != ncols) {
throw std::logic_error("Cannot combine maps with different numbers "
"of columns");
}
// Check effective ROIs line up
if (first.effective_roi.xmin != second.effective_roi.xmin ||
first.effective_roi.xmax != second.effective_roi.xmax) {
throw std::logic_error(
"Cannot combine group maps with different x extents");
}
// Calculate total number of output rows.
ssize_t total_rows = 0;
total_rows = first.map.shape(0) + second.map.shape(0) +
static_cast<ssize_t>(gap_rows);
// Allocate and initialize with -1.
//
// -1 represents an output strixel position that has
// no corresponding input pixel.
NDArray<ssize_t, 2> combined({total_rows, ncols}, -1);
// Copy maps into the combined output.
auto copy_map = [&](auto const &source, ssize_t destination_row) {
const ssize_t nrows = source.map.shape(0);
for (ssize_t row = 0; row < nrows; ++row) {
for (ssize_t col = 0; col < ncols; ++col) {
combined(destination_row + row, col) = source.map(row, col);
}
}
};
const ssize_t first_row = 0;
const ssize_t second_row = first.map.shape(0) + gap_rows;
copy_map(first, first_row);
copy_map(second, second_row);
// Bounding pixel ROI covered by the combined groups.
InclusiveROI effective_roi = first.effective_roi;
effective_roi.xmin =
std::min(effective_roi.xmin, second.effective_roi.xmin);
effective_roi.xmax =
std::max(effective_roi.xmax, second.effective_roi.xmax);
effective_roi.ymin =
std::min(effective_roi.ymin, second.effective_roi.ymin);
effective_roi.ymax =
std::max(effective_roi.ymax, second.effective_roi.ymax);
return {std::move(combined), effective_roi};
}
} // namespace detail
/**
* @brief StrixeltoPixelMap for a JUNGFRAU single-chip multi-pitch iLGAD sensor
*/
class Jungfrau_iLGAD_StrixelPixelMap : public aare::remap::StrixelPixelMap<3> {
public:
/**
* @brief Construct a new Jungfrau_iLGAD_StrixelPixelMap object.
* @param module_placement Placement and orientation of the sensor on the
* module.
* @param bond_shift Bonding shift applied before the configured sensor
* rotation.
*/
Jungfrau_iLGAD_StrixelPixelMap(
const defs::SensorModulePlacement &module_placement,
const defs::BondShift &bond_shift = {0, 0})
: StrixelPixelMap<3>(config::jungfrau::SingleChipMP_iLGAD,
module_placement, bond_shift) {}
};
/**
* @brief StrixeltoPixelMap for a JUNGFRAU single-chip multi-pitch TEW sensor
*/
class Jungfrau_TEW_StrixelPixelMap : public aare::remap::StrixelPixelMap<3> {
public:
/**
* @brief Construct a new Jungfrau_TEW_StrixelPixelMap object.
* @param module_placement Placement and orientation of the sensor on the
* module.
* @param bond_shift Bonding shift applied before the configured sensor
* rotation.
*/
Jungfrau_TEW_StrixelPixelMap(
const defs::SensorModulePlacement &module_placement,
const defs::BondShift &bond_shift = {0, 0})
: StrixelPixelMap<3>(config::jungfrau::SingleChipMP_TEW,
module_placement, bond_shift) {}
};
/**
* @brief StrixeltoPixelMap for a JUNGFRAU single-chip quad iLGAD sensor
* @note the individual strixel groups are combined into a single map with a gap
* of invalid strixel rows in between.
*/
class Jungfrau_iLGAD_Quad_StrixelPixelMap
: public aare::remap::StrixelPixelMap<2, 1> {
public:
/**
* @brief Construct a new Jungfrau_iLGAD_Quad_StrixelPixelMap object.
* @param bond_shift Bonding shift applied before the configured sensor
* rotation.
*/
Jungfrau_iLGAD_Quad_StrixelPixelMap(const defs::BondShift &bond_shift = {0,
0})
: StrixelPixelMap<2, 1>(config::jungfrau::Quad_iLGAD,
aare::remap::config::jungfrau::Quad,
bond_shift) {}
/**
* @brief Calculate the strixel-to-pixel order maps for all strixel groups
* based on the user-specified ROI.
* @param user_roi User-specified ROI in the module's native coordinate
* system.
* @note This implementation combines the two strixel groups into a single
* map with a gap of invalid strixel rows in between.
*/
void calculate_map(const ROI &user_roi) override {
m_user_roi = toInclusiveROI(user_roi);
auto quad_bottom_half =
strixel_to_pixel_map(m_sensorconfig.group_configs[0]);
auto quad_top_half =
strixel_to_pixel_map(m_sensorconfig.group_configs[1]);
if (quad_bottom_half.map.size() == 0) {
m_group_maps[0] = quad_top_half;
return;
} else if (quad_top_half.map.size() == 0) {
m_group_maps[0] = quad_bottom_half;
return;
} else {
// TODO: good idea to combine?
m_group_maps[0] = detail::combine_group_maps(
quad_bottom_half, quad_top_half,
config::jungfrau::Quad_iLGAD_strixel_gap_rows);
}
}
};
} // namespace aare::remap
@@ -0,0 +1,207 @@
#pragma once
#include "aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp"
namespace aare::remap::config::jungfrau {
// Note: designated initializers (commented) only in C++20
/************************************
* Default strixel geometries
************************************/
/// @brief Strixel geometry for 25 µm pitch strixels on iLGAD sensors
/// (multiplicity = 3)
inline constexpr defs::GroupStrixelGeometry StrxP25{3, // .multiplicity = 3,
25.0}; //.pitch_um = 25.0};
/// @brief Strixel geometry for 15 µm pitch strixels on iLGAD sensors
/// (multiplicity = 5)
inline constexpr defs::GroupStrixelGeometry StrxP15{5, //.multiplicity = 5,
15.0}; //.pitch_um = 15.0};
/// @brief Strixel geometry for 18.75 µm pitch strixels on iLGAD sensors
/// (multiplicity = 4)
inline constexpr defs::GroupStrixelGeometry StrxP18{
4, //.multiplicity = 4,
18.75}; //.pitch_um = 18.75};
/// @brief Strixel geometry for 37.5 µm pitch strixels on iLGAD sensors
/// (multiplicity = 2)
inline constexpr defs::GroupStrixelGeometry StrxP37{2, //.multiplicity = 2,
37.5}; //.pitch_um = 37.5};
/************************************
* Default sensor placements
************************************/
/// @brief Placement of the 2x2cm iLGAD sensor on the second chip (Chip1) of the
/// Jungfrau module, with no rotation applied.
inline constexpr defs::SensorModulePlacement Chip1{
{256, 511, 0, 255}, //.placement_on_module{256, 511, 0, 255},
defs::Rotation::Identity}; //.rotation = defs::Rotation::Identity};
/// @brief Placement of the 2x2cm iLGAD sensor on the seventh chip (Chip6) of
/// the Jungfrau module, with a 180-degree rotation applied.
inline constexpr defs::SensorModulePlacement Chip6{
{512, 767, 256, 511}, //.placement_on_module{512, 767, 256, 511},
defs::Rotation::Rotate180}; //.rotation = defs::Rotation::Rotate180};
/// @brief Placement of the 4x4cm iLGAD sensor on the quad
/// (Chip1+Chip2+Chip5+Chip6) of the Jungfrau module, with no rotation applied.
inline constexpr defs::SensorModulePlacement Quad{
{256, 767, 0, 511}, //.placement_on_module{256, 767, 0, 511},
defs::Rotation::Identity}; //.rotation = defs::Rotation::Identity};
/************************************
* Single chip, multi-pitch, iLGAD
************************************/
/// @brief Pixel geometry of the 2x2 cm iLGAD sensor
inline constexpr defs::SensorPixelGeometry SingleChipMP_iLGAD_pix{
256, 256, {9, 9}};
// .num_pix_x = 256, .num_pix_y = 256, .guardring = {.x = 9, .y = 9}};
/// @brief Strixel group of 25 µm pitch strixels on the 2x2 cm iLGAD sensor
inline constexpr defs::GroupConfig SingleChipMP_iLGAD_P25{
StrxP25, //.strixel = StrxP25,
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{SingleChipMP_iLGAD_pix.guardring.x + 1, // 10
SingleChipMP_iLGAD_pix.num_pix_x - SingleChipMP_iLGAD_pix.guardring.x -
1, // 246
SingleChipMP_iLGAD_pix.guardring.y, // 9
(SingleChipMP_iLGAD_pix.num_pix_y / 4) - 1}}; // 63
/* Number of strixel columns: 79
* Number of strixel rows: 165
********************************/
/// @brief Strixel group of 15 µm pitch strixels on the 2x2 cm iLGAD sensor
inline constexpr defs::GroupConfig SingleChipMP_iLGAD_P15{
StrxP15, // .strixel
{defs::ModuloOrdering::Forward},
//.placement_on_sensor
{SingleChipMP_iLGAD_pix.guardring.x + 3, // 12
SingleChipMP_iLGAD_pix.num_pix_x - SingleChipMP_iLGAD_pix.guardring.x -
1, // 246
SingleChipMP_iLGAD_pix.num_pix_y / 4, // 64
(SingleChipMP_iLGAD_pix.num_pix_y / 4) * 2 - 1}}; // 127
/* Number of strixel columns: 47
* Number of strixel rows: 320
********************************/
/// @brief Strixel group of 18.75 µm pitch strixels on the 2x2 cm iLGAD sensor
inline constexpr defs::GroupConfig SingleChipMP_iLGAD_P18{
StrxP18, // .strixel =
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{SingleChipMP_iLGAD_pix.guardring.x + 2, // 11
SingleChipMP_iLGAD_pix.num_pix_x - SingleChipMP_iLGAD_pix.guardring.x -
1, // 246
(SingleChipMP_iLGAD_pix.num_pix_y / 4) * 2, // 128
SingleChipMP_iLGAD_pix.num_pix_y - SingleChipMP_iLGAD_pix.guardring.y -
1}}; // 246
/* Number of strixel columns: 59
* Number of strixel rows: 476
********************************/
/// @brief Sensor configuration of the 2x2 cm iLGAD sensor with all strixel
/// groups
inline constexpr defs::SensorConfig<3> SingleChipMP_iLGAD{
SingleChipMP_iLGAD_pix, //.pixel =
// .group_configs =
{SingleChipMP_iLGAD_P25, SingleChipMP_iLGAD_P15, SingleChipMP_iLGAD_P18}};
/************************************
* Single chip, multi-pitch, Thin Entrance Window (TEW)
************************************/
/// @brief Pixel geometry of the 2x2 cm TEW sensors with no guard ring.
inline constexpr defs::SensorPixelGeometry SingleChipMP_TEW_pix{
256, 256, {0, 0}};
// .num_pix_x = 256, .num_pix_y = 256, .guardring = {.x = 0, .y = 0}};
/// @brief Strixel group of 25 µm pitch strixels on the 2x2 cm TEW sensor
inline constexpr defs::GroupConfig SingleChipMP_TEW_P25{
StrxP25, //.strixel =
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{SingleChipMP_TEW_pix.guardring.x + 1, // 1
SingleChipMP_TEW_pix.num_pix_x - SingleChipMP_TEW_pix.guardring.x -
1, // 255
SingleChipMP_TEW_pix.guardring.y, // 0
(SingleChipMP_TEW_pix.num_pix_y / 4) - 1}}; // 63
/* Number of strixel columns: 85
* Number of strixel rows: 192
********************************/
/// @brief Strixel group of 15 µm pitch strixels on the 2x2 cm TEW sensor
inline constexpr defs::GroupConfig SingleChipMP_TEW_P15{
StrxP15, //.strixel =
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{SingleChipMP_TEW_pix.guardring.x + 1, // 1
SingleChipMP_TEW_pix.num_pix_x - SingleChipMP_TEW_pix.guardring.x -
1, // 255
SingleChipMP_TEW_pix.num_pix_y / 4, // 64
(SingleChipMP_TEW_pix.num_pix_y / 4) * 2 - 1}}; // 127
/* Number of strixel columns: 51
* Number of strixel rows: 320
********************************/
/// @brief Strixel group of 18.75 µm pitch strixels on the 2x2 cm TEW sensor
inline constexpr defs::GroupConfig SingleChipMP_TEW_P18{
StrxP18, //.strixel =
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{SingleChipMP_TEW_pix.guardring.x, // 0
SingleChipMP_TEW_pix.num_pix_x - SingleChipMP_TEW_pix.guardring.x -
1, // 255
(SingleChipMP_TEW_pix.num_pix_y / 4) * 2, // 128
SingleChipMP_TEW_pix.num_pix_y - SingleChipMP_TEW_pix.guardring.y -
1}}; // 255
/* Number of strixel columns: 64
* Number of strixel rows: 512
********************************/
/// @brief Sensor configuration of the 2x2 cm TEW sensor with all strixel groups
inline constexpr defs::SensorConfig<3> SingleChipMP_TEW{
SingleChipMP_TEW_pix, //.pixel =
// .group_configs
{SingleChipMP_TEW_P25, SingleChipMP_TEW_P15, SingleChipMP_TEW_P18}};
/************************************
* Quad, 25 um, iLGAD
************************************/
/// @brief Pixel geometry of the 4x4 cm iLGAD sensor
inline constexpr defs::SensorPixelGeometry Quad_iLGAD_pix{512, 512, {9, 9}};
// .num_pix_x = 512, .num_pix_y = 512, .guardring = {.x = 9, .y = 9}};
inline constexpr size_t Quad_iLGAD_strixel_gap_rows = 12;
/// @brief Strixel group of 25 µm pitch strixels located on the bottom half of
/// 4x4 cm iLGAD sensor
inline constexpr defs::GroupConfig Quad_iLGAD_bottomhalf{
StrxP25, //.strixel
{defs::ModuloOrdering::Forward},
// .placement_on_sensor
{Quad_iLGAD_pix.guardring.x + 2, // 11
Quad_iLGAD_pix.num_pix_x - Quad_iLGAD_pix.guardring.x - 1, // 502
Quad_iLGAD_pix.guardring.y, // 9
(Quad_iLGAD_pix.num_pix_y / 2) - 2}}; // 254
/// @brief Strixel group of 25 µm pitch strixels located on the top half of 4x4
/// cm iLGAD sensor
inline constexpr defs::GroupConfig Quad_iLGAD_tophalf{
StrxP25, //.strixel =
{defs::ModuloOrdering::Reverse}, //.routing =
// .placement_on_sensor
{Quad_iLGAD_pix.guardring.x + 2, // 11
Quad_iLGAD_pix.num_pix_x - Quad_iLGAD_pix.guardring.x - 1, // 502
Quad_iLGAD_pix.num_pix_y / 2 + 1, // 257
Quad_iLGAD_pix.num_pix_y - Quad_iLGAD_pix.guardring.y - 1}}; // 502
/// @brief Sensor configuration of the 4x4 cm iLGAD sensor with all strixel
/// groups
inline constexpr defs::SensorConfig<2> Quad_iLGAD{
Quad_iLGAD_pix, //.pixel =
// .group_configs
{Quad_iLGAD_bottomhalf, Quad_iLGAD_tophalf}};
} // namespace aare::remap::config::jungfrau
@@ -0,0 +1,190 @@
#pragma once
#include "aare/NDArray.hpp"
#include "aare/StrixelPixelRemapping/InclusiveROI.hpp"
#include <vector>
namespace aare::remap::defs {
/**
* @brief Physical orientation of the sensor on the module.
*
* This transformation describes how the entire sensor-ASIC assembly (pixel grid
* and strixel routing together) is mounted with respect to the module
* coordinate system.
*
* Identity:
* Sensor-ASIC assembly is mounted in its nominal orientation (wire bond pad
* aligns with bottom of HDI).
*
* Rotate180:
* Sensor-ASIC assembly is rotated by 180° before wire bonding.
* This is equivalent to mirroring both x and y coordinates.
*/
enum class Rotation : int { Identity = 0, Rotate180 = 1 };
/**
* @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 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 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
struct Guardring {
/// @brief ring width in pixels.
int x{};
/// @brief ring height in pixels.
int y{};
};
/// @brief Describes the relative shift of bump bonding connections between
/// sensor and ASIC
struct BondShift {
/// @brief Bonding shift in x direction
int x{};
/// @brief Bonding shift in y direction
int y{};
};
/**
* @brief Describes the native ASIC pixel grid of a sensor.
*
* This geometry is shared by all strixel groups on the sensor and defines
* the coordinate system in which remapping is performed.
*/
struct SensorPixelGeometry {
/// @brief Number of pixels in x direction (columns)
int num_pix_x;
/// @brief Number of pixels in y direction (rows)
int num_pix_y;
/// @brief guardring around sensor
Guardring guardring;
};
/**
* @brief Describes the strixel geometry of a single remapping group.
*/
struct GroupStrixelGeometry {
/// @brief Maximum number of pixels a strixel covers.
int multiplicity;
/// @brief Effective minimal strixel pitch [µm]
double pitch_um;
};
/**
* @brief Describes the routing between ASIC pixel columns and strixel rows
* within a remapping group.
*
* The modulo ordering specifies whether the pixels belonging to each
* 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;
};
/**
* @brief Configuration of a single contiguous strixel group on a sensor.
*/
struct GroupConfig {
/// @brief strixel geometry
GroupStrixelGeometry strixel;
/// @brief pixel-to-strixel routing pattern
GroupRouting routing;
/// @brief location on sensor (given in sensor's native coordinates)
InclusiveROI placement_on_sensor;
};
/**
* @brief Complete description of a sensor.
* Templated on the number of separate strixel groups that are part of the
* sensor.
*/
template <std::size_t N> struct SensorConfig {
/// @brief pixel geometry of the sensor
SensorPixelGeometry pixel;
/// @brief strixel group configurations, partitions the sensor into regions
/// with different strixel geometries and/or routing
std::array<GroupConfig, N> group_configs;
};
/**
* @brief Describes the placement of a sensor within the module.
*/
struct SensorModulePlacement {
/// @brief Sensor bounds in module coordinates.
InclusiveROI placement_on_module;
/// @brief Physical orientation of the mounted sensor-ASIC assembly with
/// respect to the module reference frame.
Rotation rotation;
};
/**
* @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
* of the corresponding source pixel in the user-provided input ROI for strixel
* defined at (row, col).
*
* For a valid entry:
*
* map(row, col) = dy * roi_user.width() + dx
*
* where (dx, dy) is the pixel position in the coordinate system of the
* original user-provided ROI.
*
* An entry of -1 indicates that the corresponding strixel position has no
* valid source pixel.
*/
struct StrixelGroupToPixelMap {
/**
* @brief Strixel-to-pixel order map.
*
* The indices (row, col) define the local coordinate system of the
* strixel group. Each value is a flattened index into the original
* user-provided ROI.
*/
NDArray<ssize_t, 2> map{};
/**
* @brief Effective pixel ROI covered by this map.
*
* This is the transformed group ROI after applying the bond shift and
* sensor rotation and intersecting it with the user-provided ROI.
*
* The local coordinate system of `map` is aligned with this ROI.
*/
InclusiveROI effective_roi{};
/**
* @brief Check if the map is empty
* @return true if the map is empty, false otherwise
*/
bool empty() const {
return map.size() == 0 && effective_roi == InclusiveROI::emptyROI();
}
};
} // namespace aare::remap::defs
@@ -0,0 +1,17 @@
#pragma once
#include "aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp"
namespace aare::remap::format {
std::string to_string(defs::Rotation r);
std::string to_string(defs::ModuloOrdering mo);
std::string to_string(const defs::SensorPixelGeometry &g);
std::string to_string(const defs::GroupStrixelGeometry &g);
std::string to_string(const defs::GroupRouting &r);
std::string to_string(const InclusiveROI &roi);
std::string to_string(const defs::GroupConfig &c);
std::string to_string(const defs::SensorModulePlacement &p);
std::ostream &operator<<(std::ostream &os, const defs::GroupConfig &c);
} // namespace aare::remap::format
-1
View File
@@ -198,7 +198,6 @@ class ClusterFinderMT {
/**
* @brief Construct a new ClusterFinderMT object
* @param image_size size of the image
* @param cluster_size size of the cluster
* @param nSigma number of sigma above the pedestal to consider a photon
* @param capacity initial capacity of the cluster vector. Should match
* expected number of clusters in a frame per frame.
+6 -28
View File
@@ -49,43 +49,21 @@ template <typename T> T string_to(const std::string &arg) {
}
/**
* @brief Convert a string to DetectorType
* @param name string representation of the DetectorType
* @return DetectorType
* @throw runtime_error if the string does not match any DetectorType
* @brief Convert a string to an enum value. Specialized for DetectorType,
* UDPPortPosition, TimingMode, FrameDiscardPolicy and DACIndex.
* @param arg string representation of the enum value
* @return the matching enum value
* @throw std::runtime_error if the string does not match any value
* (std::invalid_argument for DACIndex)
*/
template <> DetectorType string_to(const std::string &arg);
/**
* @brief Convert a string to UDPPortPosition
* @param name string representation of the UDPPortPosition
* @return UDPPortPosition
* @throw runtime_error if the string does not match any UDPPortPosition
*/
template <> UDPPortPosition string_to(const std::string &arg);
/**
* @brief Convert a string to TimingMode
* @param mode string representation of the TimingMode
* @return TimingMode
* @throw runtime_error if the string does not match any TimingMode
*/
template <> TimingMode string_to(const std::string &arg);
/**
* @brief Convert a string to FrameDiscardPolicy
* @param mode string representation of the FrameDiscardPolicy
* @return FrameDiscardPolicy
* @throw runtime_error if the string does not match any FrameDiscardPolicy
*/
template <> FrameDiscardPolicy string_to(const std::string &arg);
/**
* @brief Convert a string to a DACIndex
* @param arg string representation of the dacIndex
* @return DACIndex
* @throw invalid argument error if the string does not match any DACIndex
*/
template <> DACIndex string_to(const std::string &arg);
/**
+6 -5
View File
@@ -2,7 +2,7 @@
#pragma once
#include "aare/NDView.hpp"
#include "aare/utils/task.hpp"
#include <thread>
#include <future>
#include <utility>
#include <vector>
@@ -11,12 +11,13 @@ namespace aare {
template <typename F>
void RunInParallel(F func, const std::vector<std::pair<int, int>> &tasks) {
// auto tasks = split_task(0, y.shape(0), n_threads);
std::vector<std::thread> threads;
std::vector<std::future<void>> futures;
for (auto &task : tasks) {
threads.push_back(std::thread(func, task.first, task.second));
futures.push_back(
std::async(std::launch::async, func, task.first, task.second));
}
for (auto &thread : threads) {
thread.join();
for (auto &future : futures) {
future.get();
}
}
+11 -1
View File
@@ -59,7 +59,14 @@ set(_aare_py_hist src/bind_PixelHistogram.cpp
set(_aare_py_pedestal src/bind_Pedestal.cpp src/bind_FastPedestal.cpp
src/bind_calibration.cpp)
set(_aare_py_fit src/bind_Fit.cpp src/bind_Interpolator.cpp)
set(_aare_py_groups io core hist pedestal fit)
set(_aare_py_strixelremap
src/StrixelRemap/bind_InclusiveROI.cpp
src/StrixelRemap/bind_PredefinedVariables.cpp
src/StrixelRemap/bind_StrixelPixelMapDefs.cpp
src/StrixelRemap/bind_strixelmaps.cpp)
set(_aare_py_groups io core hist pedestal fit strixelremap)
pybind11_add_module(
_aare # name of the module
@@ -76,6 +83,7 @@ pybind11_add_module(
${_aare_py_hist}
${_aare_py_pedestal}
${_aare_py_fit}
${_aare_py_strixelremap}
src/bind_Eta.cpp
src/bind_VarClusterFinder.cpp)
@@ -156,6 +164,8 @@ set(PYTHON_FILES
aare/RawFile.py
aare/transform.py
aare/ScanParameters.py
aare/strixelremap/__init__.py
aare/strixelremap/StrixelRemapFactories.py
aare/utils.py)
# Copy the python files to the build directory
+51 -3
View File
@@ -4,7 +4,7 @@ import numpy as np
from .ScanParameters import ScanParameters
class RawFile(_aare.RawFile):
def __init__(self, fname, chunk_size = 1, gap_pixels = False):
def __init__(self, fname, chunk_size = 1, gap_pixels = False, strixeltransform : list = None):
"""Open a raw file for reading.
Args:
@@ -14,10 +14,19 @@ class RawFile(_aare.RawFile):
default GapPixels configuration, or pass a GapPixels. Frame
shapes then include the gaps. Only Jungfrau and Eiger are
supported.
strixeltransform: List of strixeltransform objects to apply to the data. (default None)
"""
super().__init__(fname, gap_pixels)
self._chunk_size = chunk_size
self._strixeltransform : list = strixeltransform
if self._strixeltransform is not None:
if(chunk_size != 1):
raise ValueError(f"RawFile with strixeltransform must have chunk_size 1, given {chunk_size}")
rois = super().master.rois
if(len(rois) != 1):
raise ValueError(f"RawFile with strixeltransform must have exactly one ROI, found {len(rois)}") # TODO: for now only support one ROI
[transform.calculate_map(rois[0]) for transform in self._strixeltransform]
def read(self) -> tuple:
"""Read the entire file.
@@ -29,6 +38,41 @@ class RawFile(_aare.RawFile):
self.seek(0)
return self.read_n(self.total_frames)
def read_frame(self, frame_index: int | None = None ) -> tuple:
"""Read one frame from the file and then advance the file pointer.
.. note::
Uses the position of the file pointer :py:meth:`~RawFile.tell` to determine
which frame to read unless frame_index is specified.
Args:
frame_index (int): If not None, seek to this frame before reading.
Returns:
tuple: header, data
if strixeltransform is None
tuple: header, list[list]
if strixeltransform is not None, where the list contains for each strixeltransform a list of transformed data for each strixel group.
Raises:
RuntimeError: If the file is at the end.
"""
if frame_index is not None:
self.seek(frame_index)
header, data = super().read_frame()
if header.shape == (1,):
header = header[0]
if self._strixeltransform:
res = [transform(data) for transform in self._strixeltransform]
return header, res
else:
return header, data
@property
def scan_parameters(self):
"""Return the scan parameters.
@@ -67,7 +111,11 @@ class RawFile(_aare.RawFile):
def __next__(self):
try:
if self._chunk_size == 1:
return self.read_frame()
if self._strixeltransform is not None:
header, frame = self.read_frame()
return header, [transform(frame) for transform in self._strixeltransform]
else:
return self.read_frame()
else:
return self.read_n(self._chunk_size)
+1
View File
@@ -91,4 +91,5 @@ from ._aare import (
PixelHistogram_u64,
)
from . import strixelremap
from ._aare import block_mean, mean_current_source
@@ -0,0 +1,41 @@
from .._aare import strixelremap
def SensorConfig(sensor_geometry, group_configs):
"""
Helper function to create a sensor configuration from a sensor geometry and a list of group configurations
Args:
sensor_geometry (SensorPixelGeometry): The sensor geometry
group_configs (list[GroupConfig]): The list of group configurations
"""
if(len(group_configs) == 0):
raise ValueError("group_configs must contain at least one group configuration")
N = len(group_configs)
if N > 4:
raise ValueError("sensor configs with more than 4 groups are not bound in Python")
sensor_config_cls = getattr(strixelremap, f"SensorConfig_{N}PixelGroups")
return sensor_config_cls(sensor_geometry, group_configs)
def StrixelPixelMap(sensor_config , placement : strixelremap.SensorModulePlacement, bond_shift : strixelremap.BondShift = strixelremap.BondShift(0, 0)):
"""
Helper function to create a StrixelPixelMap from a SensorConfig
Args:
sensor_config (SensorConfig): The sensor configuration
placement (SensorModulePlacement): The placement of the sensor on the module
bond_shift (BondShift, optional): The bond shift to apply to the sensor. Defaults to BondShift(0, 0).
Returns:
StrixelPixelMap: The strixel pixel map object for the given sensor configuration and placement
"""
N = len(sensor_config.group_configs)
sensor_config_cls = getattr(strixelremap, f"StrixelPixelMap_{N}Groups_{N}Maps")
return sensor_config_cls(sensor_config, placement, bond_shift)
+6
View File
@@ -0,0 +1,6 @@
from .StrixelRemapFactories import SensorConfig
from .StrixelRemapFactories import StrixelPixelMap
from .._aare.strixelremap import *
+36
View File
@@ -0,0 +1,36 @@
import numpy as np
import pyperf
from aare import strixelremap
def numpy_take(input, order_map, output):
"""Remap input array to output array using order_map with numpy.take"""
not_mapped = order_map == -1
np.take(input, order_map, out=output)
output[not_mapped] = 0
def benchmark_remap():
strixelpixelmap = strixelremap.jungfrau_ilgad_singlechip_25um_strixel_map(user_roi = strixelremap.Chip1.placement_on_module, placement = strixelremap.Chip1)
order_map = strixelpixelmap.map
user_roi_height = strixelremap.Chip1.placement_on_module.height
user_roi_width = strixelremap.Chip1.placement_on_module.width
data = np.random.randint(0, 2**16, size=(user_roi_height, user_roi_width)).astype(np.uint16)
output = np.empty(order_map.shape, dtype=data.dtype)
runner = pyperf.Runner()
runner.bench_func("apply_remap", strixelremap.apply_remap, data, order_map, output)
runner.bench_func("numpy_take", numpy_take, data, order_map, output)
if __name__ == "__main__":
benchmark_remap()
@@ -0,0 +1,116 @@
#include <fmt/format.h>
#include <pybind11/pybind11.h>
#include "aare/StrixelPixelRemapping/InclusiveROI.hpp"
namespace py = pybind11;
void define_InclusiveROI(py::module &m) {
py::class_<aare::InclusiveROI>(m, "InclusiveROI")
.def(py::init<int, int, int, int>(), py::arg("xmin"), py::arg("xmax"),
py::arg("ymin"), py::arg("ymax"))
.def_readwrite("xmin", &aare::InclusiveROI::xmin,
"minimum x coordinate (inclusive)")
.def_readwrite("xmax", &aare::InclusiveROI::xmax,
"maximum x coordinate (inclusive)")
.def_readwrite("ymin", &aare::InclusiveROI::ymin,
"minimum y coordinate (inclusive)")
.def_readwrite("ymax", &aare::InclusiveROI::ymax,
"maximum y coordinate (inclusive)")
.def_property_readonly("width", &aare::InclusiveROI::width,
"width of the ROI")
.def_property_readonly("height", &aare::InclusiveROI::height,
"height of the ROI")
.def_property_readonly("size", &aare::InclusiveROI::size,
"number of pixels in the ROI")
.def("is_empty", &aare::InclusiveROI::is_empty,
"check if the ROI is empty")
.def(
"contains",
[](const aare::InclusiveROI &self, int x, int y) {
return self.contains(x, y);
},
R"(
check if a point is contained in the ROI
Parameters
----------
x : int
x coordinate of the point
y : int
y coordinate of the point
Returns
-------
bool
True if the point is contained in the ROI, False otherwise
)")
.def(
"fits_in",
[](const aare::InclusiveROI &self, int ncols, int nrows) {
return self.fits_in(ncols, nrows);
},
R"(
check if the ROI fits within a given number of columns and rows
Parameters
----------
ncols : int
number of columns
nrows : int
number of rows
Returns
-------
bool
True if the ROI fits within the given dimensions, False otherwise
)")
.def("__eq__", &aare::InclusiveROI::operator==, py::is_operator(),
"check if two InclusiveROI objects are equal")
.def("__repr__",
[](const aare::InclusiveROI &self) {
return fmt::format(
"InclusiveROI(xmin={}, xmax={}, ymin={}, ymax={})",
self.xmin, self.xmax, self.ymin, self.ymax);
})
.def_static("emptyROI", &aare::InclusiveROI::emptyROI,
"create an empty InclusiveROI");
m.def("toInclusiveROI", &aare::toInclusiveROI, py::arg("roi").noconvert(),
R"(
Convert a half-open ROI to an inclusive ROI
Parameters
----------
roi : ROI
Half-open ROI to be converted
Returns
-------
InclusiveROI
Inclusive ROI with the same physical extent
)");
m.def("toHalfopenROI", &aare::toHalfopenROI, py::arg("roi").noconvert(),
R"(
Convert an inclusive ROI to a half-open ROI
Parameters
----------
roi : InclusiveROI
Inclusive ROI to be converted
Returns
-------
ROI
Half-open ROI with the same physical extent
)");
}
@@ -0,0 +1,151 @@
#include <pybind11/pybind11.h>
#include "aare/StrixelPixelRemapping/StrixelPixelMaps.hpp"
#include "aare/StrixelPixelRemapping/StrixelPixelRemapConfig.hpp"
namespace py = pybind11;
void define_predefinedConfigs(py::module &m) {
// Predefined strixel geometries
m.attr("StrxP25") = aare::remap::config::jungfrau::StrxP25;
// Strixel geometry for 25 µm pitch strixels on iLGAD sensors (multiplicity
// = 3)
m.attr("StrxP15") = aare::remap::config::jungfrau::StrxP15;
//"Strixel geometry for 15 µm pitch strixels on iLGAD sensors "
//"(multiplicity = 5)";
m.attr("StrxP18") = aare::remap::config::jungfrau::StrxP18;
//"Strixel geometry for 18 µm pitch strixels on iLGAD sensors "
//"(multiplicity = 4)";
m.attr("StrxP37") = aare::remap::config::jungfrau::StrxP37;
//"Strixel geometry for 37 µm pitch strixels on iLGAD sensors "
//"(multiplicity = 2)";
// Predefined sensor placements
m.attr("Chip1") = aare::remap::config::jungfrau::Chip1;
// Placement of the 2x2cm iLGAD sensor on the second chip (Chip1) of the
// Jungfrau module with no rotation applied.
m.attr("Chip6") = aare::remap::config::jungfrau::Chip6;
//"Placement of the 2x2cm iLGAD sensor on the seventh chip (Chip6) of "
//"the Jungfrau module"
//"with a 180-degree rotation applied.";
m.attr("Quad") = aare::remap::config::jungfrau::Quad;
//"Placement of the 4x4cm iLGAD sensor on the quad "
//"(Chip1+Chip2+Chip5+Chip6) of the Jungfrau module"
//"with no rotation applied.";
// Predefined sensor geometries
m.attr("SingleChipMP_iLGAD_pix") =
aare::remap::config::jungfrau::SingleChipMP_iLGAD_pix;
// "Pixel geometry of the 2x2 cm iLGAD sensor";
m.attr("Quad_iLGAD_pix") = aare::remap::config::jungfrau::Quad_iLGAD_pix;
// "Pixel geometry of the 4x4 cm iLGAD sensor";
m.attr("SingleChipMP_TEW_pix") =
aare::remap::config::jungfrau::SingleChipMP_TEW_pix;
// "Pixel geometry of the 2x2 cm TEW sensor";
// Predefined strixel groups
m.attr("SingleChipMP_iLGAD_P25") =
aare::remap::config::jungfrau::SingleChipMP_iLGAD_P25;
// "Strixel group of 25 µm pitch strixels on the 2x2 cm iLGAD sensor";
m.attr("SingleChipMP_iLGAD_P15") =
aare::remap::config::jungfrau::SingleChipMP_iLGAD_P15;
// "Strixel group of 15 µm pitch strixels on the 2x2 cm iLGAD sensor";
m.attr("SingleChipMP_iLGAD_P18") =
aare::remap::config::jungfrau::SingleChipMP_iLGAD_P18;
// "Strixel group of 18.75 µm pitch strixels on the 2x2 cm iLGAD sensor";
m.attr("SingleChipMP_TEW_P25") =
aare::remap::config::jungfrau::SingleChipMP_TEW_P25;
// "Strixel group of 25 µm pitch strixels on the 2x2 cm TEW sensor";
m.attr("SingleChipMP_TEW_P15") =
aare::remap::config::jungfrau::SingleChipMP_TEW_P15;
// "Strixel group of 15 µm pitch strixels on the 2x2 cm TEW sensor";
m.attr("SingleChipMP_TEW_P18") =
aare::remap::config::jungfrau::SingleChipMP_TEW_P18;
// "Strixel group of 18.75 µm pitch strixels on the 2x2 cm TEW sensor";
m.attr("Quad_iLGAD_bottomhalf") =
aare::remap::config::jungfrau::Quad_iLGAD_bottomhalf;
// "Strixel group of 25 µm pitch strixels located on the bottom half of "
// "4x4 cm iLGAD sensor";
m.attr("Quad_iLGAD_tophalf") =
aare::remap::config::jungfrau::Quad_iLGAD_tophalf;
// "Strixel group of 25 µm pitch strixels located on the top half of 4x4 "
// "cm iLGAD sensor";
// Predefined sensor configurations
m.attr("SingleChipMP_iLGAD") =
aare::remap::config::jungfrau::SingleChipMP_iLGAD;
// "Sensor configuration of the 2x2 cm iLGAD sensor with all strixel
// groups";
m.attr("SingleChipMP_TEW") =
aare::remap::config::jungfrau::SingleChipMP_TEW;
// "Sensor configuration of the 2x2 cm TEW sensor with all strixel groups";
m.attr("Quad_iLGAD") = aare::remap::config::jungfrau::Quad_iLGAD;
// "Sensor configuration of the 4x4 cm iLGAD sensor with all strixel "
// "groups";
}
void define_predefinedStrixelPixelMaps(py::module &m) {
py::class_<aare::remap::Jungfrau_iLGAD_StrixelPixelMap,
aare::remap::StrixelPixelMap<3, 3>>(
m, "Jungfrau_iLGAD_StrixelPixelMap")
.def(py::init<const aare::remap::defs::SensorModulePlacement &,
const aare::remap::defs::BondShift &>(),
py::arg("module_placement").noconvert(),
py::arg("bond_shift").noconvert() =
aare::remap::defs::BondShift{0, 0},
R"(
Construct a new Jungfrau_iLGAD_StrixelPixelMap object.
Parameters
----------
module_placement : SensorModulePlacement
Placement and orientation of the sensor on the module.
bond_shift : BondShift, optional
Bonding shift applied before the configured sensor rotation.
Default is (0, 0).
)");
py::class_<aare::remap::Jungfrau_TEW_StrixelPixelMap,
aare::remap::StrixelPixelMap<3, 3>>(
m, "Jungfrau_TEW_StrixelPixelMap")
.def(py::init<const aare::remap::defs::SensorModulePlacement &,
const aare::remap::defs::BondShift &>(),
py::arg("module_placement").noconvert(),
py::arg("bond_shift").noconvert() =
aare::remap::defs::BondShift{0, 0},
R"(
Construct a new Jungfrau_TEW_StrixelPixelMap object.
Parameters
----------
module_placement : SensorModulePlacement
Placement and orientation of the sensor on the module.
bond_shift : BondShift, optional
Bonding shift applied before the configured sensor rotation.
Default is (0, 0).
)");
py::class_<aare::remap::Jungfrau_iLGAD_Quad_StrixelPixelMap,
aare::remap::StrixelPixelMap<2, 1>>(
m, "Jungfrau_iLGAD_Quad_StrixelPixelMap")
.def(py::init<const aare::remap::defs::BondShift &>(),
py::arg("bond_shift").noconvert() =
aare::remap::defs::BondShift{0, 0},
R"(
Constructor for Jungfrau_iLGAD_Quad_StrixelPixelMap object.
Parameters
----------
bond_shift : BondShift, optional
Bonding shift applied before the configured sensor rotation.
Default is (0, 0).
)");
}
@@ -0,0 +1,18 @@
#include "aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp"
#include <fmt/format.h>
#include <pybind11/pybind11.h>
namespace py = pybind11;
template <std::size_t N> void define_SensorConfig(py::module &m) {
const auto class_name = fmt::format("SensorConfig_{}PixelGroups", N);
py::class_<aare::remap::defs::SensorConfig<N>>(m, class_name.c_str())
.def(py::init<aare::remap::defs::SensorPixelGeometry,
std::array<aare::remap::defs::GroupConfig, N>>(),
py::arg("pixel"), py::arg("group_configs"))
.def_readwrite("pixel", &aare::remap::defs::SensorConfig<N>::pixel,
"sensor pixel geometry (SensorPixelGeometry)")
.def_readwrite("group_configs",
&aare::remap::defs::SensorConfig<N>::group_configs,
"[list] of strixel group configurations");
}
@@ -0,0 +1,183 @@
#include <fmt/format.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include "aare/StrixelPixelRemapping/StrixelPixelRemapDefs.hpp"
#include "aare/StrixelPixelRemapping/StrixelPixelRemapFormat.hpp"
namespace py = pybind11;
using aare::ssize_t;
void define_StrixelPixelMapDefs(py::module &m) {
py::enum_<aare::remap::defs::Rotation>(m, "Rotation")
.value("Identity", aare::remap::defs::Rotation::Identity)
.value("Rotate180", aare::remap::defs::Rotation::Rotate180)
.export_values();
py::enum_<aare::remap::defs::ModuloOrdering>(m, "ModuloOrdering")
.value("Forward", aare::remap::defs::ModuloOrdering::Forward)
.value("Reverse", aare::remap::defs::ModuloOrdering::Reverse)
.export_values();
py::class_<aare::remap::defs::Guardring>(m, "Guardring")
.def(py::init<int, int>(), py::arg("x"), py::arg("y"))
.def_readwrite("x", &aare::remap::defs::Guardring::x,
"ring width in pixels")
.def_readwrite("y", &aare::remap::defs::Guardring::y,
"ring height in pixels")
.def(
"__eq__",
[](const aare::remap::defs::Guardring &self,
const aare::remap::defs::Guardring &other) {
return self.x == other.x && self.y == other.y;
},
py::is_operator())
.def("__repr__", [](const aare::remap::defs::Guardring &self) {
return fmt::format("Guardring{{x={}, y={}}}", self.x, self.y);
});
py::class_<aare::remap::defs::BondShift>(m, "BondShift")
.def(py::init<int, int>(), py::arg("x"), py::arg("y"))
.def_readwrite("x", &aare::remap::defs::BondShift::x,
"bond shift in x direction (pixels)")
.def_readwrite("y", &aare::remap::defs::BondShift::y,
"bond shift in y direction (pixels)")
.def("__repr__", [](const aare::remap::defs::BondShift &self) {
return fmt::format("BondShift{{x={}, y={}}}", self.x, self.y);
});
py::class_<aare::remap::defs::SensorPixelGeometry>(m, "SensorPixelGeometry")
.def(py::init<int, int, aare::remap::defs::Guardring>(),
py::arg("num_pix_x"), py::arg("num_pix_y"),
py::arg("guardring") = aare::remap::defs::Guardring{0, 0})
.def_readwrite("num_pix_x",
&aare::remap::defs::SensorPixelGeometry::num_pix_x,
"number of pixels in x direction")
.def_readwrite("num_pix_y",
&aare::remap::defs::SensorPixelGeometry::num_pix_y,
"number of pixels in y direction")
.def_readwrite(
"guardring", &aare::remap::defs::SensorPixelGeometry::guardring,
"physical guardring around the sensor (default Guardring(0,0))")
.def("__repr__",
[](const aare::remap::defs::SensorPixelGeometry &self) {
return fmt::format("SensorPixelGeometry{}",
aare::remap::format::to_string(self));
});
py::class_<aare::remap::defs::GroupStrixelGeometry>(m,
"GroupStrixelGeometry")
.def(py::init<int, double>(), py::arg("multiplicity"),
py::arg("pitch_um"))
.def_readwrite("multiplicity",
&aare::remap::defs::GroupStrixelGeometry::multiplicity,
"maximum number of pixels a strixel covers")
.def_readwrite("pitch_um",
&aare::remap::defs::GroupStrixelGeometry::pitch_um,
"effective minimal strixel pitch [µm]")
.def("__repr__",
[](const aare::remap::defs::GroupStrixelGeometry &self) {
return fmt::format("GroupStrixelGeometry{}",
aare::remap::format::to_string(self));
});
py::class_<aare::remap::defs::GroupRouting>(m, "GroupRouting")
.def(py::init<aare::remap::defs::ModuloOrdering>(),
py::arg("mod_order") = aare::remap::defs::ModuloOrdering::Forward)
.def_readwrite(
"mod_order", &aare::remap::defs::GroupRouting::mod_order,
"modulo ordering of pixels within each strixel multiplicity group "
"default(ModuloOrdering::Forward)")
.def("__repr__", [](const aare::remap::defs::GroupRouting &self) {
return fmt::format("GroupRouting{}",
aare::remap::format::to_string(self));
});
py::class_<aare::remap::defs::GroupConfig>(m, "GroupConfig")
.def(py::init<aare::remap::defs::GroupStrixelGeometry,
aare::remap::defs::GroupRouting, aare::InclusiveROI>(),
py::arg("strixel"), py::arg("routing"),
py::arg("placement_on_sensor"))
.def(py::init([](const aare::remap::defs::GroupStrixelGeometry &strixel,
const aare::remap::defs::ModuloOrdering &mod_order,
const aare::InclusiveROI &placement_on_sensor) {
return aare::remap::defs::GroupConfig{
strixel, {mod_order}, placement_on_sensor};
}),
py::arg("strixel"), py::arg("routing"),
py::arg("placement_on_sensor"))
.def_readwrite("strixel", &aare::remap::defs::GroupConfig::strixel,
"strixel geometry of the group")
.def_readwrite("routing", &aare::remap::defs::GroupConfig::routing,
"pixel-to-strixel routing pattern")
.def_readwrite(
"placement_on_sensor",
&aare::remap::defs::GroupConfig::placement_on_sensor,
"placement of the strixel group on the sensor (sensor-local "
"coordinates)")
.def("__repr__", [](const aare::remap::defs::GroupConfig &self) {
return fmt::format("GroupConfig{}",
aare::remap::format::to_string(self));
});
py::class_<aare::remap::defs::SensorModulePlacement>(
m, "SensorModulePlacement")
.def(py::init<aare::InclusiveROI, aare::remap::defs::Rotation>(),
py::arg("placement_on_module"), py::arg("rotation"))
.def_readwrite(
"placement_on_module",
&aare::remap::defs::SensorModulePlacement::placement_on_module,
"sensor bounds in module coordinates")
.def_readwrite(
"rotation", &aare::remap::defs::SensorModulePlacement::rotation,
"physical orientation of the mounted sensor-ASIC assembly with "
"respect to the module reference frame")
.def("__repr__",
[](const aare::remap::defs::SensorModulePlacement &self) {
return fmt::format("SensorModulePlacement{}",
aare::remap::format::to_string(self));
});
py::class_<aare::remap::defs::StrixelGroupToPixelMap>(
m, "StrixelGroupToPixelMap")
.def(py::init<>())
.def_readonly("effective_roi",
&aare::remap::defs::StrixelGroupToPixelMap::effective_roi,
"effective pixel ROI covered by this map (InclusiveROI)")
.def_property_readonly(
"map",
[](const aare::remap::defs::StrixelGroupToPixelMap &self)
-> py::array {
return py::array_t<ssize_t>(
self.map.shape(), self.map.data(),
py::cast(&self, py::return_value_policy::reference));
},
R"(
Strixel-to-pixel order map.
Returns
-------
numpy.ndarray[int]
Two-dimensional array of flattened pixel indices.
A value of ``-1`` indicates that no valid source pixel is
mapped at that position.
)")
.def("empty", &aare::remap::defs::StrixelGroupToPixelMap::empty, R"(
Check if the map is empty.
Returns
-------
bool
True if the map is empty, False otherwise.
)");
}
@@ -0,0 +1,236 @@
#include <fmt/format.h>
#include <pybind11/numpy.h>
#include <pybind11/pybind11.h>
#include "../np_helper.hpp"
#include "aare/StrixelPixelRemapping/BaseStrixelPixelMap.hpp"
using aare::ssize_t;
namespace py = pybind11;
namespace aare::remap::detail {
struct StrixelPixelMapBindingAccess {
template <std::size_t N, std::size_t M, typename T>
static void apply_group_remap(const StrixelPixelMap<N, M> &map,
NDView<T, 2> input, NDView<T, 2> output,
const NDView<const ssize_t, 2> order_map) {
map.apply_group_remap(input, output, order_map);
}
};
} // namespace aare::remap::detail
template <std::size_t N, std::size_t M = N, typename T = uint16_t>
void define_StrixelPixelRemaps(py::module &m) {
const auto class_name =
fmt::format("StrixelPixelMap_{}Groups_{}Maps", N, M);
py::class_<aare::remap::StrixelPixelMap<N, M>>(m, class_name.c_str())
.def(py::init<const aare::remap::defs::SensorConfig<N> &,
const aare::remap::defs::SensorModulePlacement &,
const aare::remap::defs::BondShift &>(),
py::arg("sensor_config"), py::arg("module_placement"),
py::arg("bond_shift") = aare::remap::defs::BondShift{0, 0})
.def("calculate_map",
&aare::remap::StrixelPixelMap<N, M>::calculate_map,
py::arg("user_roi").noconvert(),
R"(
Calculate the strixel-to-pixel order maps for all strixel groups
based on the user-specified ROI.
Parameters
----------
user_roi : ROI
User-specified ROI in the module's native coordinate system.
)")
.def_property_readonly(
"group_maps",
[](const aare::remap::StrixelPixelMap<N, M> &self) {
return self.get_group_maps();
},
R"(
Get the strixel-to-pixel order maps for all strixel groups.
Returns
-------
list of StrixelGroupToPixelMap
List of strixel-to-pixel order maps for each strixel group.
maps are empty if the groups are not covered by the user ROI.
)")
.def_property_readonly(
"sensor_config",
[](const aare::remap::StrixelPixelMap<N, M> &self) {
return self.get_SensorConfig();
},
R"(
Get the sensor configuration associated with this StrixelPixelMap.
Returns
-------
SensorConfig
The sensor configuration.
)")
.def(
"__call__",
[](aare::remap::StrixelPixelMap<N, M> &self,
const aare::ROI &user_roi,
py::array_t<T, py::array::c_style | py::array::forcecast>
input) {
if (input.ndim() != 2) {
throw std::runtime_error("Input array must be 2D");
}
auto mapped_inputs = self(user_roi, make_view_2d(input));
py::list result_list;
for (auto mapped_input : mapped_inputs) {
auto *mapped_input_ptr =
new aare::NDArray<T, 2>(mapped_input);
if (mapped_input_ptr->size() == 0) {
result_list.append(py::none());
} else {
result_list.append(return_image_data(mapped_input_ptr));
}
}
return result_list;
},
py::arg("user_roi").noconvert(), py::arg("input").noconvert(),
R"(
Apply the strixel-to-pixel remapping to an input array.
Parameters
----------
user_roi : ROI
User-specified ROI in the module's native coordinate system.
input : np.ndarray[uint16_t, 2]
Input array to be remapped.
Returns
-------
list of np.ndarray[uint16_t, 2]
Remapped arrays for each strixel group.
If a group is not covered by the user ROI, the corresponding array will be None.
)")
.def(
"__call__",
[](const aare::remap::StrixelPixelMap<N, M> &self,
py::array_t<T, py::array::c_style | py::array::forcecast>
input) {
if (input.ndim() != 2) {
throw std::runtime_error("Input array must be 2D");
}
auto mapped_inputs = self(make_view_2d(input));
py::list result_list; // TODO: can I reserve space for the list?
for (auto mapped_input : mapped_inputs) {
auto *mapped_input_ptr =
new aare::NDArray<T, 2>(mapped_input);
if (mapped_input_ptr->size() == 0) {
result_list.append(py::none());
} else {
result_list.append(return_image_data(mapped_input_ptr));
}
}
return result_list;
},
py::arg("input").noconvert(),
R"(
Apply the strixel-to-pixel remapping to an input array.
This overload assumes that the user ROI has already been set and
the map calculated using `calculate_map()`.
Parameters
----------
input : np.ndarray[uint16_t, 2]
Input array to be remapped.
Returns
-------
list of np.ndarray[uint16_t, 2]
Remapped arrays for each strixel group.
If a group is not covered by the user ROI, the corresponding array will be None.
)")
.def(
"__call__",
[](const aare::remap::StrixelPixelMap<N, M> &self,
py::array_t<T, py::array::c_style | py::array::forcecast> input,
py::list &output) {
if (input.ndim() != 2) {
throw std::runtime_error("Input array must be 2D");
}
if (output.size() != M) {
throw std::runtime_error(
fmt::format("Output list size must be equal to the "
"number of strixel groups ({}), but got {}",
M, output.size()));
}
const auto group_maps = self.get_group_maps();
const auto input_view = make_view_2d(input);
for (size_t i = 0; i < group_maps.size(); ++i) {
if (group_maps[i].empty()) {
output[i] = py::none();
} else {
if (!py::isinstance<py::array_t<T, py::array::c_style>>(
output[i])) {
throw std::runtime_error(
fmt::format("Output list element at index {} "
"is not a numpy array",
i));
}
auto out = py::array_t<T, py::array::c_style>::ensure(
output[i]);
if (!out) {
throw std::runtime_error(
"Output entry must be a C-contiguous numpy "
"array");
}
if (out.ndim() != 2) {
throw std::runtime_error("Output entry must be 2D");
}
if (!out.writeable()) {
throw std::runtime_error(
"Output entry must be writable");
}
aare::remap::detail::StrixelPixelMapBindingAccess::
apply_group_remap(self, input_view,
make_view_2d(out),
group_maps[i].map.view());
}
}
},
py::arg("input").noconvert(), py::arg("output").noconvert(),
R"(
Apply the strixel-to-pixel remapping to an input array.
This overload assumes that the user ROI has already been set and
the map calculated using `calculate_map()`.
Parameters
----------
input : np.ndarray[uint16_t, 2]
Input array to be remapped.
output : list of np.ndarray[uint16_t, 2]
Preallocated arrays to store the remapped results for each strixel group.
If a group is not covered by the user ROI, the corresponding output array will be None.
)");
}
@@ -0,0 +1,26 @@
#include "bind_SensorConfig.hpp"
#include "bind_StrixelRemap.hpp"
#include <pybind11/pybind11.h>
namespace py = pybind11;
#define DEFINE_BINDINGS_SENSORCONFIG(N) define_SensorConfig<N>(m);
#define DEFINE_BINDINGS_STRIXELPIXELMAP(N, M) \
define_StrixelPixelRemaps<N, M>(m);
void define_StrixelMapsandSensorConfigs(py::module &m) {
DEFINE_BINDINGS_SENSORCONFIG(1);
DEFINE_BINDINGS_STRIXELPIXELMAP(1, 1);
DEFINE_BINDINGS_SENSORCONFIG(2);
DEFINE_BINDINGS_STRIXELPIXELMAP(2, 2);
DEFINE_BINDINGS_SENSORCONFIG(4);
DEFINE_BINDINGS_STRIXELPIXELMAP(4, 4);
DEFINE_BINDINGS_SENSORCONFIG(3);
DEFINE_BINDINGS_STRIXELPIXELMAP(3, 3);
DEFINE_BINDINGS_STRIXELPIXELMAP(2, 1); // quad iLGAD sensor
}
+20 -8
View File
@@ -22,9 +22,15 @@ void bind_DataSetAggregation(pybind11::module_ &m) {
const size_t mean_over_num_frames,
const size_t num_processing_threads,
const size_t num_reader_threads) {
auto result = new NDArray<double, 3>(block_mean<FRAME_TYPE>(
path, num_samples, mean_over_num_frames, num_processing_threads,
num_reader_threads));
NDArray<double, 3> *result = nullptr;
{
// release the GIL only for the pure C++ computation; creating
// the numpy array below requires holding the GIL
py::gil_scoped_release release;
result = new NDArray<double, 3>(block_mean<FRAME_TYPE>(
path, num_samples, mean_over_num_frames,
num_processing_threads, num_reader_threads));
}
return return_image_data(result);
},
py::arg("path"), py::kw_only(), py::arg("num_samples"),
@@ -32,7 +38,7 @@ void bind_DataSetAggregation(pybind11::module_ &m) {
py::arg("num_reader_threads") = 8,
R"pbdoc(
Compute the block mean over several frames per sample stored in a file.
Function spawns num_processing_threads + num_reader_threads + 1 threads in total.
Function spawns num_processing_threads + num_reader_threads threads in total.
Parameters:
-----------
@@ -55,9 +61,15 @@ void bind_read_current_source(pybind11::module_ &m) {
const size_t mean_over_num_frames,
const size_t num_processing_threads, const size_t num_reader_threads,
const size_t file_offset) {
auto result = new NDArray<double, 3>(mean_current_source(
path, num_samples, mean_over_num_frames, num_processing_threads,
num_reader_threads, file_offset));
NDArray<double, 3> *result = nullptr;
{
// release the GIL only for the pure C++ computation; creating
// the numpy array below requires holding the GIL
py::gil_scoped_release release;
result = new NDArray<double, 3>(mean_current_source(
path, num_samples, mean_over_num_frames,
num_processing_threads, num_reader_threads, file_offset));
}
return return_image_data(result);
},
py::arg("path"), py::kw_only(), py::arg("num_samples"),
@@ -65,7 +77,7 @@ void bind_read_current_source(pybind11::module_ &m) {
py::arg("num_reader_threads") = 8, py::arg("file_offset") = 0,
R"pbdoc(
Compute the mean over several frames per sample stored in a file for each current source.
Function spawns num_processing_threads + num_reader_threads + 1 threads in total.
Function spawns num_processing_threads + num_reader_threads threads in total.
Parameters:
-----------
+16
View File
@@ -46,6 +46,22 @@ void define_defs_bindings(py::module &m) {
.def_readwrite("ymin", &ROI::ymin)
.def_readwrite("ymax", &ROI::ymax)
.def("shape",
[](const ROI &self) {
return std::make_tuple(self.height(), self.width());
})
.def(
"size",
[](const ROI &self) { return self.width() * self.height(); }, R"doc(
Calculate the size of the ROI.
Returns
-------
int
The total number of pixels in the ROI.
)doc")
.def(
"slice",
[](const ROI &self) {
+14 -5
View File
@@ -11,6 +11,8 @@
#include "aare/Fit.hpp"
#include "aare/FitModel.hpp"
#include "aare/Models.hpp"
#include <algorithm>
#include <iostream>
namespace py = pybind11;
using namespace pybind11::literals;
@@ -22,7 +24,9 @@ fit_dispatch(const aare::FitModel<Model> &model,
py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y,
py::object y_err_obj, int n_threads,
std::optional<py::array_t<size_t>> fit_range = std::nullopt);
std::optional<
py::array_t<size_t, py::array::c_style | py::array::forcecast>>
fit_range = std::nullopt);
template <typename Model> void bind_fit_model(py::module &m, const char *name) {
using FM = aare::FitModel<Model>;
@@ -123,8 +127,9 @@ template <typename Model> void bind_fit_model(py::module &m, const char *name) {
py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y,
py::object y_err_obj, int n_threads,
std::optional<py::array_t<size_t>> fit_range =
std::nullopt) -> py::object {
std::optional<py::array_t<size_t, py::array::c_style |
py::array::forcecast>>
fit_range = std::nullopt) -> py::object {
return fit_dispatch<Model>(self, x, y, y_err_obj, n_threads,
fit_range);
},
@@ -237,7 +242,9 @@ fit_dispatch(const aare::FitModel<Model> &model,
py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y,
py::object y_err_obj, int n_threads,
std::optional<py::array_t<size_t>> fit_range) {
std::optional<
py::array_t<size_t, py::array::c_style | py::array::forcecast>>
fit_range) {
constexpr std::size_t npar = Model::npar;
if (y.ndim() == 3) {
@@ -353,7 +360,9 @@ py::object dispatch_any_model(
py::array_t<double, py::array::c_style | py::array::forcecast> x,
py::array_t<double, py::array::c_style | py::array::forcecast> y,
py::object y_err_obj, int n_threads,
std::optional<py::array_t<size_t>> fit_range = std::nullopt) {
std::optional<
py::array_t<size_t, py::array::c_style | py::array::forcecast>>
fit_range = std::nullopt) {
using namespace aare::model;
#define AARE_DISPATCH_MODEL(Model) \
+7
View File
@@ -27,6 +27,13 @@ void define_multi_threaded_file_reader_bindings(py::module &m);
// bind_DataSetAggregation.cpp
void bind_dataset_aggregation(py::module &m);
// Strixel remapping bindings
void define_InclusiveROI(py::module &m);
void define_predefinedConfigs(py::module &m);
void define_predefinedStrixelPixelMaps(py::module &m);
void define_StrixelPixelMapDefs(py::module &m);
void define_StrixelMapsandSensorConfigs(py::module &m);
// bind_Defs.cpp
void define_defs_bindings(py::module &m);
// bind_GapPixels.cpp
+9
View File
@@ -58,4 +58,13 @@ PYBIND11_MODULE(_aare, m) {
bind_eta_types(m);
bind_dataset_aggregation(m);
auto strixelremap =
m.def_submodule("strixelremap", "Strixel remapping utilities.");
define_InclusiveROI(strixelremap);
define_StrixelPixelMapDefs(strixelremap);
define_StrixelMapsandSensorConfigs(strixelremap);
define_predefinedConfigs(strixelremap);
define_predefinedStrixelPixelMaps(strixelremap);
}
+16
View File
@@ -5,6 +5,9 @@ from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition,
from aare import GapPixels, ModuleGaps, insert_gap_pixels
import numpy as np
from aare import strixelremap
from test_helpers.RawFileHelpers import TemporaryJungfrauRawFiles
@pytest.fixture
def small_raw_file(tmp_path):
@@ -495,6 +498,19 @@ def test_read_eiger_udp_port_disabled(test_data_path):
assert rois[0] == ROI(0, 512, 0, 512)
assert rois[1] == ROI(1024, 1536, 0, 512)
def test_RawFile_with_strixeltransform():
""" list of transforms is passed to RawFile"""
transform = strixelremap.Jungfrau_iLGAD_StrixelPixelMap(module_placement = strixelremap.Chip1)
my_raw_file = TemporaryJungfrauRawFiles()
with RawFile(my_raw_file.master_path(), strixeltransform = [transform]) as f:
header, frames = f.read_frame()
assert len(frames) == 1
assert len(frames[0]) == 3
assert frames[0][0].shape == (165, 79)
assert frames[0][1].shape == (320, 47)
assert frames[0][2].shape == (476, 59)
@pytest.mark.parametrize("layout", [(1, 1), (2, 1), (1, 2), (2, 2), (3, 2)])
@pytest.mark.parametrize("reader_type", [RawFile, File])
+222
View File
@@ -0,0 +1,222 @@
import pytest
import numpy as np
from aare import strixelremap
from aare import ROI
def test_roimappings():
""" Test exclusive to inclusive roi mapping and vice versa """
roi = ROI(0, 10, 0, 5)
inclusive_roi = strixelremap.toInclusiveROI(roi)
assert inclusive_roi.xmin == 0
assert inclusive_roi.xmax == 9
assert inclusive_roi.ymin == 0
assert inclusive_roi.ymax == 4
exclusive_roi = strixelremap.toHalfopenROI(inclusive_roi)
assert exclusive_roi.xmin == 0
assert exclusive_roi.xmax == 10
assert exclusive_roi.ymin == 0
assert exclusive_roi.ymax == 5
def test_emptyROI():
""" Test creation of an empty ROI """
empty_roi = strixelremap.InclusiveROI.emptyROI()
assert empty_roi.xmin == 0
assert empty_roi.xmax == -1
assert empty_roi.ymin == 0
assert empty_roi.ymax == -1
def test_format():
""" Test string representations """
inclusive_roi = strixelremap.InclusiveROI(0, 9, 0, 4)
assert str(inclusive_roi) == "InclusiveROI(xmin=0, xmax=9, ymin=0, ymax=4)"
jungfrau_pixel_geometry = strixelremap.SingleChipMP_TEW_pix
assert str(jungfrau_pixel_geometry) == "SensorPixelGeometry{cols x rows: 256 x 256, guardring: {x = 0, y = 0}}"
strixel_group = strixelremap.StrxP25
assert str(strixel_group) == "GroupStrixelGeometry{multiplicity: 3, pitch_um: 25}"
jungfrau_group_config = strixelremap.SingleChipMP_TEW_P25
assert str(jungfrau_group_config) == "GroupConfig{strixel_group: {multiplicity: 3, pitch_um: 25}, routing: {Forward}, placement_on_sensor: {xmin=1, xmax=255, ymin=0, ymax=63}}"
sensor_placement = strixelremap.Chip1
assert str(sensor_placement) == "SensorModulePlacement{placement_on_module: {xmin=256, xmax=511, ymin=0, ymax=255}, rotation: Identity}"
def test_customSensorConfiguration():
""" Test that a custom sensor configuration can be created and used to remap strixel pixels """
my_strixel_group = strixelremap.GroupStrixelGeometry(multiplicity=2, pitch_um=25.0)
assert my_strixel_group.multiplicity == 2
assert my_strixel_group.pitch_um == 25.0
my_sensor_geometry = strixelremap.SensorPixelGeometry(num_pix_x = 10, num_pix_y = 5)
assert my_sensor_geometry.num_pix_x == 10
assert my_sensor_geometry.num_pix_y == 5
assert my_sensor_geometry.guardring == strixelremap.Guardring(0,0)
my_group_config = strixelremap.GroupConfig(strixel = my_strixel_group, routing = strixelremap.ModuloOrdering.Forward,placement_on_sensor = strixelremap.InclusiveROI(0,9,0,4))
my_sensor_config = strixelremap.SensorConfig(sensor_geometry = my_sensor_geometry, group_configs = [my_group_config])
# rebase
user_roi = strixelremap.InclusiveROI(strixelremap.Chip1.placement_on_module.xmin + 0, strixelremap.Chip1.placement_on_module.xmin + 9, strixelremap.Chip1.placement_on_module.ymin + 0, strixelremap.Chip1.placement_on_module.ymin + 4)
strixelpixelmap = strixelremap.StrixelPixelMap(sensor_config = my_sensor_config, placement = strixelremap.Chip1)
strixelpixelmap.calculate_map(strixelremap.toHalfopenROI(user_roi))
group_maps = strixelpixelmap.group_maps
assert len(group_maps) == 1
assert group_maps[0].effective_roi == my_group_config.placement_on_sensor
map = group_maps[0].map
assert map.shape == (10 ,5)
assert np.array_equal(map, np.array([[0, 2, 4, 6, 8], [1, 3, 5, 7, 9], [10, 12, 14, 16, 18], [11, 13, 15, 17, 19], [20, 22, 24, 26, 28], [21, 23, 25, 27, 29], [30, 32, 34, 36, 38], [31, 33, 35, 37, 39], [40, 42, 44, 46, 48], [41, 43, 45, 47, 49]]))
input = np.arange(50).reshape((5,10)).astype(np.uint16)
remapped_result = strixelpixelmap(input)[0]
assert remapped_result.shape == (10,5)
assert np.array_equal(remapped_result, np.array([[0, 2, 4, 6, 8], [1, 3, 5, 7, 9], [10, 12, 14, 16, 18], [11, 13, 15, 17, 19], [20, 22, 24, 26, 28], [21, 23, 25, 27, 29], [30, 32, 34, 36, 38], [31, 33, 35, 37, 39], [40, 42, 44, 46, 48], [41, 43, 45, 47, 49]]))
# check output call operator with preallocated output array
output = np.empty(map.shape, dtype=input.dtype)
strixelpixelmap(input, [output])
assert np.array_equal(output, np.array([[0, 2, 4, 6, 8], [1, 3, 5, 7, 9], [10, 12, 14, 16, 18], [11, 13, 15, 17, 19], [20, 22, 24, 26, 28], [21, 23, 25, 27, 29], [30, 32, 34, 36, 38], [31, 33, 35, 37, 39], [40, 42, 44, 46, 48], [41, 43, 45, 47, 49]]))
def test_predefined_iLGAD_singlechip():
""" Test predefined Junfrau iLGAD strixel pixel remap """
inclusive_user_roi = strixelremap.InclusiveROI(strixelremap.Chip1.placement_on_module.xmin + 11, strixelremap.Chip1.placement_on_module.xmin + 15, strixelremap.Chip1.placement_on_module.ymin + 10, strixelremap.Chip1.placement_on_module.ymin + 12)
exclusive_user_roi = strixelremap.toHalfopenROI(inclusive_user_roi)
strixelpixelmap = strixelremap.Jungfrau_iLGAD_StrixelPixelMap(module_placement = strixelremap.Chip1)
strixelpixelmap.calculate_map(exclusive_user_roi)
group_maps = strixelpixelmap.group_maps
assert len(group_maps) == 3
assert group_maps[0].map.shape == (9, 2)
assert group_maps[1].empty() == True
assert group_maps[2].empty() == True
group_map_0 = group_maps[0].map
assert np.array_equal(group_map_0, np.array([[-1, 2], [0, 3], [1, 4], [-1, 7], [5,8], [6,9], [-1,12], [10,13], [11,14]]))
input_data = np.array([[1,2,3,4,5],[1,2,3,4,5], [1,2,3,4,5]]).astype(np.uint16)
output = strixelpixelmap(input_data)
assert len(output) == 3
assert np.array_equal(output[0], np.array([[0, 3], [1,4], [2,5], [0, 3], [1,4], [2,5], [0, 3], [1,4], [2,5]]))
assert output[1] == None
assert output[2] == None
def test_predefined_iLGAD_quad_remap():
""" Test predefined Junfrau iLGAD quad strixel pixel remap """
# TODO combine map with one empty
# only one map is not covered by ROI
inclusive_user_roi = strixelremap.InclusiveROI(strixelremap.Quad.placement_on_module.xmin + 11, strixelremap.Quad.placement_on_module.xmin + 15, strixelremap.Quad.placement_on_module.ymin + 9, strixelremap.Quad.placement_on_module.ymin + 11)
exclusive_user_roi = strixelremap.toHalfopenROI(inclusive_user_roi)
strixelpixelmap = strixelremap.Jungfrau_iLGAD_Quad_StrixelPixelMap()
strixelpixelmap.calculate_map(exclusive_user_roi)
group_maps = strixelpixelmap.group_maps
assert len(group_maps) == 1
assert group_maps[0].map.shape == (9, 2)
# both maps are covered by ROI
inclusive_user_roi = strixelremap.InclusiveROI(strixelremap.Quad.placement_on_module.xmin + 11, strixelremap.Quad.placement_on_module.xmin + 15, strixelremap.Quad.placement_on_module.ymin + 9, strixelremap.Quad.placement_on_module.ymin + 260)
exclusive_user_roi = strixelremap.toHalfopenROI(inclusive_user_roi)
strixelpixelmap = strixelremap.Jungfrau_iLGAD_Quad_StrixelPixelMap()
strixelpixelmap.calculate_map(exclusive_user_roi)
group_maps = strixelpixelmap.group_maps
assert len(group_maps) == 1
# 3*246 rows top module + 3*4 rows bottom module + 12 gap rows = 762 rows, 2 columns
assert group_maps[0].map.shape == (762, 2)
def test_empty_map():
""" Test empty map when ROI does not cover any strixel pixels """
exclusive_user_roi = ROI(0, 10, 0, 5)
strixelpixelmap = strixelremap.Jungfrau_iLGAD_StrixelPixelMap(module_placement = strixelremap.Chip1)
strixelpixelmap.calculate_map(exclusive_user_roi)
group_maps = strixelpixelmap.group_maps
assert len(group_maps) == 3
assert group_maps[0].empty() == True
assert group_maps[1].empty() == True
assert group_maps[2].empty() == True
input_data = np.random.randint(0, 65535, size=exclusive_user_roi.shape(), dtype=np.uint16)
mapped_output = strixelpixelmap(input_data)
assert len(mapped_output) == 3
assert mapped_output[0] == None
assert mapped_output[1] == None
assert mapped_output[2] == None
# check that the output call operator with preallocated output arrays works as expected
output_arrays = [np.random.randint(0, 65535, size=exclusive_user_roi.shape(), dtype=np.uint16) for _ in range(3)]
strixelpixelmap(input_data, output_arrays)
assert output_arrays[0] == None
assert output_arrays[1] == None
assert output_arrays[2] == None
+108
View File
@@ -0,0 +1,108 @@
# SPDX-License-Identifier: MPL-2.0
import json
import shutil
import struct
import tempfile
import time
from pathlib import Path
from aare import ROI
import random
# TODO: maybe a fixture is better
def get_module_size_from_roi(module_idx : tuple, receiver_roi : ROI, pixels_per_module: tuple) -> tuple:
"""Get the size of a module in pixels from the receiver ROI and the pixels per module.
Args:
module_idx (tuple): The index of the module in the format (y, x).
receiver_roi (ROI): The receiver ROI.
pixels_per_module (tuple): The number of pixels per module in the x and y directions.
Returns:
tuple: The size of the module in pixels in the x and y directions.
"""
module_x = module_idx[1]
module_y = module_idx[0]
module_ROI = ROI(
module_x * pixels_per_module[1], (module_x + 1) * pixels_per_module[1],
module_y * pixels_per_module[0], (module_y + 1) * pixels_per_module[0]
)
# Calculate the size of the module in pixels
xmin = max(receiver_roi.xmin, module_ROI.xmin)
ymin = max(receiver_roi.ymin, module_ROI.ymin)
xmax = min(receiver_roi.xmax, module_ROI.xmax)
ymax = min(receiver_roi.ymax, module_ROI.ymax)
if xmin >= xmax or ymin >= ymax:
return (0, 0)
else:
module_size_x = xmax - xmin
module_size_y = ymax - ymin
return (module_size_y, module_size_x)
class TemporaryJungfrauRawFiles:
def __init__(self, modules: tuple = (2,1), pixels_per_module: tuple = (256,1024), receiver_roi : ROI = ROI(0, 1024, 0, 512)) -> None:
unique = time.monotonic_ns()
self._directory = Path(tempfile.gettempdir()) / f"aare-raw-{unique}"
self._directory.mkdir()
image_size_in_bytes = receiver_roi.size() * 2 # 2 bytes per pixel
metadata = {
"Version": 8.1,
"Detector Type": "Jungfrau",
"Timing Mode": "auto",
"Geometry": {"x": modules[1], "y": modules[0]},
"Image Size": image_size_in_bytes,
"Pixels": {"x": pixels_per_module[1], "y": pixels_per_module[0]},
"Max Frames Per File": 1,
"Total Frames": 2,
"Frames in File": 2,
"Frame Padding": 1,
"Frame Discard Policy": "nodiscard",
"UDP Ports Type" : ["bottom", "top"],
"UDP Ports Disabled": [],
"Receiver Rois": [{"xmin": receiver_roi.xmin, "xmax": receiver_roi.xmax-1, "ymin": receiver_roi.ymin, "ymax": receiver_roi.ymax-1}] # inclusive
}
self.master_path().write_text(json.dumps(metadata), encoding="utf-8")
for module_x in range(metadata["Geometry"]["x"]):
for module_y in range(metadata["Geometry"]["y"]):
size = get_module_size_from_roi((module_y, module_x), receiver_roi, pixels_per_module)
if(size == (0, 0)):
continue
values = [random.randint(0, 65535) for _ in range(size[0] * size[1])]
pixels = struct.pack(f"<{len(values)}H", *values)
for file_index in range(metadata["Frames in File"]):
with self.data_path(module_x * metadata["Geometry"]["y"] + module_y, file_index).open("wb") as output:
output.write(self._detector_header_bytes(file_index))
output.write(pixels)
def cleanup(self) -> None:
shutil.rmtree(self._directory, ignore_errors=True)
def __enter__(self) -> "TemporaryJungfrauRawFiles":
return self
def __exit__(self, exc_type, exc, tb) -> None:
self.cleanup()
def __del__(self) -> None:
self.cleanup()
def master_path(self) -> Path:
return self._directory / "run_master_0.json"
def data_path(self, module: int = 0, file: int = 0) -> Path:
return self._directory / f"run_d{module}_f{file}_0.raw"
@staticmethod
def _detector_header_bytes(frame_number: int) -> bytes:
# TODO: Mirror include/aare/DetectorHeader.hpp exactly if the full
# binary layout is required by the test.
return struct.pack("<Q", frame_number) + bytes(range(104)) #in total detector header is 112 bytes, 8 bytes for frame number and 104 bytes for the rest of the header
+15 -4
View File
@@ -90,6 +90,18 @@ NDArray<double, 3> mean_current_source(const std::filesystem::path &path,
frames_per_sample);
buffers.commit_write(b);
fmt::print("\rProgress: {}/{} ({:.1f}%)",
(b + 1) * mean_over_num_frames,
num_samples * mean_over_num_frames,
num_samples * mean_over_num_frames == 0
? 100.0
: 100.0 *
static_cast<double>((b + 1) *
mean_over_num_frames) /
static_cast<double>(num_samples *
mean_over_num_frames));
std::fflush(stdout);
}
} catch (...) {
buffers.abort(); // wake up the other threads so they can exit
@@ -155,10 +167,7 @@ NDArray<double, 3> mean_current_source(const std::filesystem::path &path,
};
std::vector<std::future<void>> futures;
futures.reserve(num_processing_threads + 1);
// reader thread
futures.push_back(std::async(std::launch::async, reader));
futures.reserve(num_processing_threads);
const size_t rows_per_worker = num_rows / num_processing_threads;
for (size_t w = 0; w < num_processing_threads; ++w) {
@@ -169,6 +178,8 @@ NDArray<double, 3> mean_current_source(const std::filesystem::path &path,
w * rows_per_worker, row_end));
}
reader(); // run reader in main thread to avoid extra thread creation
for (auto &f : futures) {
try {
f.get();
@@ -0,0 +1,237 @@
#include "aare/StrixelPixelRemapping/InclusiveROI.hpp"
#include <catch2/catch_test_macros.hpp>
using namespace aare;
// translate
TEST_CASE("translate ROI", "[InclusiveROI][geometry]") {
const InclusiveROI roi{10, 19, 20, 29};
SECTION("positive shift") {
auto result = inclusiveroi::geom::translate(roi, 5, 7);
CHECK(result == InclusiveROI{15, 24, 27, 36});
}
SECTION("negative shift") {
auto result = inclusiveroi::geom::translate(roi, -5, -7);
CHECK(result == InclusiveROI{5, 14, 13, 22});
}
SECTION("zero shift") {
CHECK(inclusiveroi::geom::translate(roi, 0, 0) == roi);
}
}
// mirror
TEST_CASE("mirror_on_y mirrors ROI about vertical axis",
"[InclusiveROI][geometry]") {
SECTION("ROI on left side of axis") {
InclusiveROI roi{1, 3, 10, 20};
auto mirrored = inclusiveroi::geom::mirror_on_y(roi, 5);
CHECK(mirrored == InclusiveROI{6, 8, 10, 20});
}
SECTION("ROI right of axis") {
InclusiveROI roi{6, 8, 10, 20};
CHECK(inclusiveroi::geom::mirror_on_y(roi, 5) ==
InclusiveROI{1, 3, 10, 20});
}
SECTION("ROI touching the axis") {
InclusiveROI roi{4, 5, 10, 20};
CHECK(inclusiveroi::geom::mirror_on_y(roi, 5) ==
InclusiveROI{4, 5, 10, 20});
}
SECTION("mirroring twice restores original ROI") {
InclusiveROI roi{2, 12, 10, 20};
auto mirrored = inclusiveroi::geom::mirror_on_y(roi, 8);
auto restored = inclusiveroi::geom::mirror_on_y(mirrored, 8);
CHECK(restored == roi);
}
SECTION("even-width base ROI") {
InclusiveROI base_roi{0, 11, 10, 20};
InclusiveROI roi{3, 7, 12, 18};
CHECK(inclusiveroi::geom::mirror_on_y(roi, base_roi.width() / 2) ==
InclusiveROI{4, 8, 12, 18});
}
SECTION("odd-width base ROI") {
InclusiveROI base_roi{0, 12, 10, 20};
InclusiveROI roi{3, 7, 12, 18};
CHECK(inclusiveroi::geom::mirror_on_y(roi, base_roi.width() / 2) ==
InclusiveROI{4, 8, 12, 18});
}
}
TEST_CASE("mirror_on_x mirrors ROI about horizontal axis",
"[InclusiveROI][geometry]") {
SECTION("ROI below axis") {
InclusiveROI roi{10, 20, 1, 3};
auto mirrored = inclusiveroi::geom::mirror_on_x(roi, 5);
CHECK(mirrored == InclusiveROI{10, 20, 6, 8});
}
SECTION("ROI above axis") {
InclusiveROI roi{10, 20, 6, 8};
CHECK(inclusiveroi::geom::mirror_on_x(roi, 5) ==
InclusiveROI{10, 20, 1, 3});
}
SECTION("ROI touching the axis") {
InclusiveROI roi{10, 20, 4, 5};
CHECK(inclusiveroi::geom::mirror_on_x(roi, 5) ==
InclusiveROI{10, 20, 4, 5});
}
SECTION("mirroring twice restores original ROI") {
InclusiveROI roi{10, 20, 2, 12};
auto mirrored = inclusiveroi::geom::mirror_on_x(roi, 8);
auto restored = inclusiveroi::geom::mirror_on_x(mirrored, 8);
CHECK(restored == roi);
}
SECTION("even-height base ROI") {
InclusiveROI base_roi{10, 20, 0, 11};
InclusiveROI roi{12, 18, 3, 7};
CHECK(inclusiveroi::geom::mirror_on_x(roi, base_roi.height() / 2) ==
InclusiveROI{12, 18, 4, 8});
}
SECTION("odd-height base ROI") {
InclusiveROI base_roi{10, 20, 0, 12};
InclusiveROI roi{12, 18, 3, 7};
CHECK(inclusiveroi::geom::mirror_on_x(roi, base_roi.height() / 2) ==
InclusiveROI{12, 18, 4, 8});
}
}
// intersect
TEST_CASE("intersect ROIs", "[InclusiveROI][geometry]") {
SECTION("partially overlapping") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{5, 14, 3, 7};
CHECK(inclusiveroi::geom::intersect(a, b) == InclusiveROI{5, 9, 3, 7});
}
SECTION("one ROI inside the other") {
InclusiveROI a{0, 20, 0, 20};
InclusiveROI b{5, 10, 7, 12};
CHECK(inclusiveroi::geom::intersect(a, b) == b);
}
SECTION("identical ROIs") {
InclusiveROI a{5, 10, 7, 12};
CHECK(inclusiveroi::geom::intersect(a, a) == a);
}
SECTION("no overlap") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{10, 19, 0, 9};
CHECK(inclusiveroi::geom::intersect(a, b).is_empty());
}
}
// rebase
TEST_CASE("rebase ROI", "[InclusiveROI][geometry]") {
SECTION("base ROI origin becomes (0,0) in the rebased coordinate system") {
InclusiveROI input{110, 119, 220, 229};
InclusiveROI base{100, 199, 200, 299};
CHECK(inclusiveroi::geom::rebaseROI(input, base) ==
InclusiveROI{10, 19, 20, 29});
}
SECTION("input larger than base") {
InclusiveROI input{90, 219, 80, 329};
InclusiveROI base{100, 199, 200, 299};
CHECK(inclusiveroi::geom::rebaseROI(input, base) ==
InclusiveROI{-10, 119, -120, 129});
}
SECTION("input outside of base") {
InclusiveROI input{10, 80, 80, 129};
InclusiveROI base{100, 199, 200, 299};
CHECK(inclusiveroi::geom::rebaseROI(input, base) ==
InclusiveROI{-90, -20, -120, -71});
}
SECTION("rebasing base itself produces origin") {
InclusiveROI base{100, 199, 200, 299};
CHECK(inclusiveroi::geom::rebaseROI(base, base) ==
InclusiveROI{0, 99, 0, 99});
}
}
// unite
TEST_CASE("unite ROIs", "[InclusiveROI][geometry]") {
SECTION("overlapping horizontally") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{5, 14, 0, 9};
CHECK(inclusiveroi::geom::unite(a, b) == InclusiveROI{0, 14, 0, 9});
}
SECTION("adjacent horizontally") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{10, 19, 0, 9};
CHECK(inclusiveroi::geom::unite(a, b) == InclusiveROI{0, 19, 0, 9});
}
SECTION("overlapping vertically") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{0, 9, 5, 14};
CHECK(inclusiveroi::geom::unite(a, b) == InclusiveROI{0, 9, 0, 14});
}
SECTION("adjacent vertically") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{0, 9, 10, 19};
CHECK(inclusiveroi::geom::unite(a, b) == InclusiveROI{0, 9, 0, 19});
}
SECTION("non-contiguous ROIs throw") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{20, 29, 0, 9};
CHECK_THROWS_AS(inclusiveroi::geom::unite(a, b), std::runtime_error);
}
SECTION("different y extents throw") {
InclusiveROI a{0, 9, 0, 9};
InclusiveROI b{5, 14, 1, 9};
CHECK_THROWS_AS(inclusiveroi::geom::unite(a, b), std::runtime_error);
}
}
@@ -0,0 +1,616 @@
#include "aare/StrixelPixelRemapping/BaseStrixelPixelMap.hpp"
#include <catch2/catch_test_macros.hpp>
// Test structure:
// Geometry utilities
// │
// ├── translate() <-- InclusiveROI.test.cpp
// ├── mirror_on_x() <-- InclusiveROI.test.cpp
// ├── mirror_on_y() <-- InclusiveROI.test.cpp
// ├── mirrorXY() <-- InclusiveROI.test.cpp
// └── algo::detail::update_pixel_group_placement()
// ├── identity
// ├── bond shift
// ├── rotation
// └── shift + rotation
// Remapping algorithm
// │
// └── strixel_to_pixel_map()
// ├── full map check for small group ROI (all hardcoded)
// ├── full group exactly aligned (full map check)
// ├── user ROI larger than group (full map check)
// ├── user ROI smaller than group (full map check)
// ├── user ROI partially overlaps group (full map ceck)
// ├── user ROI does not intersect group (check empty)
// ├── ModuloOrdering (check explicit, small map)
// | ├── Forward
// | └── Reverse
// ├── update_pixel_group_placement (check integration)
// | ├── bond shift
// | └── Rotate180
// ├── invalid multiplicity (check throws)
// └── group width not divisible by multiplicity (check throws)
// For the full map checks, I have chosen to reimplement the maths behind the
// mapping algorithm instead of hardcoding maps. This can be debated.
// Crucially, I have isolated the maths of the mapping algorithm from the
// geometry utilities that are used. These are checked separately in
// InclusiveROI.test.cpp save for algo::detail::update_pixel_group_placement(),
// which combines geometry utilities and is checked here separately for geometry
// correctness and integration into the remapping algorithm. All geometry
// operations are hardcoded in the tests here.
// TODO: Implement tests for bond shift and rotation
using namespace aare;
using namespace aare::remap;
// Local helper definitions
namespace {
defs::SensorPixelGeometry test_sensor() {
// return {.num_pix_x = 50, .num_pix_y = 50, .guardring = {0, 0}};
return {50, 50, {0, 0}};
}
defs::SensorModulePlacement
test_placement(defs::Rotation rotation = defs::Rotation::Identity) {
// return {.placement_on_module = {50, 99, 50, 99},
// .rotation = defs::Rotation::Identity};
return {{50, 99, 50, 99}, rotation};
}
defs::GroupConfig
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}};
return {{multiplicity, 25.0}, {ordering}, group_roi};
}
defs::GroupConfig asymmetric_test_group() {
// return {.strixel = {.multiplicity = 3, .pitch_um = 25.0},
// .routing = {defs::ModuloOrdering::Forward},
// .placement_on_sensor = {5, 13, 8, 16}};
return {{3, 25.0}, {defs::ModuloOrdering::Forward}, {5, 13, 8, 16}};
}
defs::GroupConfig small_test_group() {
// return {.strixel = {.multiplicity = 3, .pitch_um = 25.0},
// .routing = {defs::ModuloOrdering::Forward},
// .placement_on_sensor = {10, 15, 10, 11}};
return {{3, 25.0}, {defs::ModuloOrdering::Forward}, {10, 15, 10, 11}};
}
} // namespace
/***************************************
*
* Geometry utilities
* algo::detail::update_pixel_group_placement
*
***************************************/
TEST_CASE("update_pixel_group_placement: shift and rotation geometry",
"[remap][geometry][update_pixel_group_placement]") {
const auto group = asymmetric_test_group();
auto group_roi = group.placement_on_sensor;
const auto sensor = test_sensor();
SECTION("Identity reproduces itself") {
auto updated = ::detail::update_pixel_group_placement(
group_roi, sensor, {0, 0}, defs::Rotation::Identity);
CHECK(updated == group_roi);
}
SECTION("Bond shift") {
const defs::BondShift shift{2, 3};
auto updated = detail::update_pixel_group_placement(
group_roi, sensor, shift, defs::Rotation::Identity);
// Original group: {5, 13, 8, 16}
// After bond shift (+2, +3):
// {7, 15, 11, 19}
const InclusiveROI expected_roi{7, 15, 11, 19};
CHECK(updated == expected_roi);
}
SECTION("180 degree rotation") {
auto updated = detail::update_pixel_group_placement(
group_roi, sensor, {0, 0}, defs::Rotation::Rotate180);
// Original group: {5, 13, 8, 16}
// After rotation in 50x50 sensor:
// {36, 44, 33, 41}
const InclusiveROI expected_roi{36, 44, 33, 41};
CHECK(updated == expected_roi);
}
SECTION("bond shift and rotation") {
const auto result = detail::update_pixel_group_placement(
group_roi, sensor, {2, 3}, defs::Rotation::Rotate180);
// Original group: {5, 13, 8, 16}
// After bond shift (+2, +3):
// {7, 15, 11, 19}
// After rotation in 50x50 sensor:
// {34, 43, 30, 38}
const InclusiveROI expected_roi{34, 42, 30, 38};
CHECK(result == expected_roi);
}
}
/***************************************
*
* Remapping algorithm
* strixel_to_pixel_map
*
***************************************/
// small test group explicit mapping test
TEST_CASE("strixel_to_pixel_map: explicit mapping test with small ROI",
"[remap][strixel_to_pixel_map]") {
const auto group = small_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
// User ROI is in module coordinates, aligns with sensor
const ROI user_roi{50, 100, 50, 100};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
const InclusiveROI expected_roi{10, 15, 10, 11};
CHECK(result.effective_roi == expected_roi);
CHECK(result.map.shape(0) == 6);
CHECK(result.map.shape(1) == 2);
// Check every pixel explicitely
// First pixel row
CHECK(result.map(0, 0) == 510); // pixel (10, 10)
CHECK(result.map(1, 0) == 511); // pixel (10, 11)
CHECK(result.map(2, 0) == 512); // pixel (10, 12)
CHECK(result.map(0, 1) == 513); // pixel (10, 13)
CHECK(result.map(1, 1) == 514); // pixel (10, 14)
CHECK(result.map(2, 1) == 515); // pixel (10, 15)
// Second pixel row + user_roi.width()
CHECK(result.map(3, 0) == 560); // pixel (11, 10)
CHECK(result.map(4, 0) == 561); // pixel (11, 11)
CHECK(result.map(5, 0) == 562); // pixel (11, 12)
CHECK(result.map(3, 1) == 563); // pixel (11, 13)
CHECK(result.map(4, 1) == 564); // pixel (11, 14)
CHECK(result.map(5, 1) == 565); // pixel (11, 15)
}
// full group exactly aligned
TEST_CASE("strixel_to_pixel_map: user ROI exactly aligned with group ROI",
"[remap][strixel_to_pixel_map]") {
const auto group = large_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
// User ROI is in module coordinates.
const ROI user_roi{60, 90, 60, 90};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
// 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);
// 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)
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)
}
// 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 = small_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
// User ROI is in module coordinates.
const ROI user_roi{45, 105, 45, 105};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
const InclusiveROI expected_roi = group.placement_on_sensor;
CHECK(result.effective_roi == expected_roi);
CHECK(result.map.shape(0) == 6);
CHECK(result.map.shape(1) == 2);
// 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)
// 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 = large_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
// User ROI is in module coordinates.
const ROI user_roi{65, 71, 65, 67};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
// Now expected_roi is given by the smaller user ROI (in sensor-local
// coordinates)
// Expected intersection:
//
// user ROI, sensor-local: {15, 20, 15, 16}
// group ROI, sensor-local: {10, 39, 10, 39}
// ----------------
// effective ROI: {15, 20, 15, 16}
const InclusiveROI expected_roi = {15, 20, 15, 16};
CHECK(result.effective_roi == expected_roi);
// The map shape is now determined by the smaller user ROI in relation to
// the group ROI:
// - The group ROI still determines the modulo progression and where
// multiplicity groups start
// - The smaller user ROI determines from where we start looking
// - 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 6
// > 6/multiplicity = 2
// > map width of 2 should cover it?
// > BUT: the placement with respect to the group_roi matters!
// > 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) == 6);
CHECK(result.map.shape(1) == 3);
// 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
// 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 = 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, 13, 5, 11}.
const ROI user_roi{55, 64, 55, 62};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
// Expected intersection:
//
// user ROI, sensor-local: { 5, 13, 5, 11}
// group ROI: {10, 39, 10, 39}
// ----------------
// 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) == 6);
CHECK(result.map.shape(1) == 2);
// 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
// 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 = large_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
const ROI user_roi{10, 60, 10, 85};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_map(0);
CHECK(result.effective_roi.is_empty());
CHECK(result.empty() == true);
}
// ModuloOrdering
TEST_CASE("strixel_to_pixel_map: modulo ordering",
"[remap][strixel_to_pixel_map]") {
const auto sensor = test_sensor();
const auto placement = test_placement();
const ROI user_roi{60, 63, 60, 63};
SECTION("Forward ordering") {
const auto forward_group =
large_test_group(defs::ModuloOrdering::Forward);
StrixelPixelMap map(SensorConfig<1>{sensor, {forward_group}}, placement,
{0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
CHECK(result.map.shape(0) == 9);
CHECK(result.map.shape(1) == 1);
// Pixels x=60,61,62 correspond to modulo values 0,1,2.
//
// Forward ordering:
// mod 0 -> strixel row 0
// mod 1 -> strixel row 1
// mod 2 -> strixel row 2
CHECK(result.map(0, 0) == 0);
CHECK(result.map(1, 0) == 1);
CHECK(result.map(2, 0) == 2);
CHECK(result.map(3, 0) == 3);
CHECK(result.map(4, 0) == 4);
CHECK(result.map(5, 0) == 5);
CHECK(result.map(6, 0) == 6);
CHECK(result.map(7, 0) == 7);
CHECK(result.map(8, 0) == 8);
}
SECTION("Reverse ordering") {
const auto reverse_group =
large_test_group(defs::ModuloOrdering::Reverse);
StrixelPixelMap map(SensorConfig<1>{sensor, {reverse_group}}, placement,
{0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
CHECK(result.map.shape(0) == 9);
CHECK(result.map.shape(1) == 1);
// Reverse ordering:
// mod 0 -> strixel row 2
// mod 1 -> strixel row 1
// mod 2 -> strixel row 0
CHECK(result.map(0, 0) == 2);
CHECK(result.map(0, 1) == 1);
CHECK(result.map(0, 2) == 0);
CHECK(result.map(3, 0) == 5);
CHECK(result.map(4, 0) == 4);
CHECK(result.map(5, 0) == 3);
CHECK(result.map(6, 0) == 8);
CHECK(result.map(7, 0) == 7);
CHECK(result.map(8, 0) == 6);
}
}
// update_pixel_group_placement integration
TEST_CASE(
"strixel_to_pixel_map: update_pixel_group_placement integration",
"[remap][strixel_to_pixel_map][geometry][update_pixel_group_placement]") {
const auto group = asymmetric_test_group();
const auto sensor = test_sensor();
const auto placement = test_placement();
// user_roi = sensor_roi
const ROI user_roi = toHalfopenROI(placement.placement_on_module);
// Rebase into sensor roi:
// {50, 99, 50, 99}
const InclusiveROI user_roi_local = {0, 49, 0, 49};
// Pixel index helper (for readability)
const auto expected_pixel = [&](ssize_t x, ssize_t y) {
return (y - user_roi_local.ymin) * user_roi_local.width() +
(x - user_roi_local.xmin);
};
SECTION("bond shift integrates correctly") {
const defs::BondShift shift{2, 3};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, shift);
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
// Original group: {5, 13, 8, 16}
// After bond shift (+2, +3):
// {7, 15, 11, 19}
const InclusiveROI expected_roi{7, 15, 11, 19};
CHECK(result.effective_roi == expected_roi);
CHECK(result.map.shape(0) == 27);
CHECK(result.map.shape(1) == 3);
// Bottom-left pixel of the shifted group.
// x=7, y=11 -> dx=0, dy=0 -> strixel (0,0)
CHECK(result.map(0, 0) == expected_pixel(7, 11));
// Same pixel row, different modulo position.
// x=9, y=11 -> dx=2 -> strixel (2,0)
CHECK(result.map(2, 0) == expected_pixel(9, 11));
// A pixel from a later row and column.
// x=13, y=15 -> dx=6, dy=4 -> strixel (12,2)
CHECK(result.map(12, 2) == expected_pixel(13, 15));
}
SECTION("rotation integrates correctly") {
const auto rotated_placement =
test_placement(defs::Rotation::Rotate180);
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, rotated_placement,
{0, 0});
map.calculate_map(user_roi);
const auto result = map.get_group_maps()[0];
// Original group: {5, 13, 8, 16}
// After rotation in 50x50 sensor:
// {36, 44, 33, 41}
const InclusiveROI expected_roi{36, 44, 33, 41};
CHECK(result.effective_roi == expected_roi);
CHECK(result.map.shape(0) == 27);
CHECK(result.map.shape(1) == 3);
// Bottom-left pixel of the shifted group.
// x=36, y=33 -> dx=0, dy=0 -> strixel (0,0)
CHECK(result.map(0, 0) == expected_pixel(36, 33));
// Same pixel row, different modulo position.
// x=38, y=33 -> dx=2 -> strixel (2,0)
CHECK(result.map(2, 0) == expected_pixel(38, 33));
// A pixel from a later row and column.
// x=42, y=37 -> dx=6, dy=4 -> strixel (12,2)
CHECK(result.map(12, 2) == expected_pixel(42, 37));
}
}
// invalid multiplicity
TEST_CASE("strixel_to_pixel_map: invalid multiplicity",
"[remap][strixel_to_pixel_map]") {
const defs::ModuloOrdering ordering = defs::ModuloOrdering::Forward;
const int multiplicity = 0;
const auto group = large_test_group(ordering, multiplicity);
const auto sensor = test_sensor();
const auto placement = test_placement();
const ROI user_roi{10, 60, 10, 85};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
CHECK_THROWS_AS(map.calculate_map(user_roi), std::logic_error);
}
// group width not divisible by multiplicity
TEST_CASE("strixel_to_pixel_map: group width not divisible by multiplicity",
"[remap][strixel_to_pixel_map]") {
const defs::ModuloOrdering ordering = defs::ModuloOrdering::Forward;
const int multiplicity = 3;
const InclusiveROI group_roi = {11, 39, 10, 39}; // width = 29
const auto group = large_test_group(ordering, multiplicity, group_roi);
const auto sensor = test_sensor();
const auto placement = test_placement();
const ROI user_roi{10, 60, 10, 85};
StrixelPixelMap map(SensorConfig<1>{sensor, {group}}, placement, {0, 0});
CHECK_THROWS_AS(map.calculate_map(user_roi), std::logic_error);
}
@@ -0,0 +1,54 @@
#include "aare/StrixelPixelRemapping/StrixelPixelRemapFormat.hpp"
#include <sstream>
namespace aare::remap::format {
std::string to_string(defs::Rotation r) {
return (r == defs::Rotation::Identity ? "Identity" : "Rotate180");
}
std::string to_string(defs::ModuloOrdering mo) {
return (mo == defs::ModuloOrdering::Forward ? "Forward" : "Reverse");
}
std::string to_string(const defs::SensorPixelGeometry &g) {
return fmt::format("{{cols x rows: {} x {}, guardring: "
"{{x = {}, y = {}}}}}",
g.num_pix_x, g.num_pix_y, g.guardring.x, g.guardring.y);
}
std::string to_string(const defs::GroupStrixelGeometry &g) {
return fmt::format("{{multiplicity: {}, pitch_um: {}}}", g.multiplicity,
g.pitch_um);
}
std::string to_string(const defs::GroupRouting &r) {
return fmt::format("{{{}}}", to_string(r.mod_order));
}
std::string to_string(const InclusiveROI &roi) {
return fmt::format("{{xmin={}, xmax={}, ymin={}, ymax={}}}", roi.xmin,
roi.xmax, roi.ymin, roi.ymax);
}
std::string to_string(const defs::GroupConfig &c) {
return fmt::format("{{strixel_group: {}, routing: {}, "
"placement_on_sensor: {}}}",
to_string(c.strixel), to_string(c.routing),
to_string(c.placement_on_sensor));
}
std::string to_string(const defs::SensorModulePlacement &p) {
return fmt::format("{{placement_on_module: {}, "
"rotation: {}}}",
to_string(p.placement_on_module), to_string(p.rotation));
}
std::ostream &operator<<(std::ostream &os, const defs::GroupConfig &c) {
return os << to_string(c);
}
} // namespace aare::remap::format
+1
View File
@@ -78,6 +78,7 @@ template <class Model> class Chi2Data1D {
* @brief Compute chi2, its gradient and the Gauss-Newton Hessian in a
* single pass over the data.
*
* @param par Parameter values, size npar.
* @param grad Receives d(chi2)/dp_k, resized to npar.
* @param hess Receives the packed symmetric Hessian in the layout used by
* ROOT::Minuit2::FumiliFCNBase: element (j, k) with j <= k is
+13 -3
View File
@@ -135,6 +135,11 @@ template <typename Model> class PixelFitter {
/**
* @brief Fit one pixel.
*
* @param model Model and fit settings.
* @param x Sample positions.
* @param y Measured values at x.
* @param y_err Uncertainties of y; an empty view gives an unweighted fit.
* Points with zero error are skipped.
* @param par_out Receives npar fitted values; zeros on failure.
* @param err_out Receives npar errors when non-null; zeros on failure.
* @param chi2 Receives the chi-squared at the minimum; 0 on failure.
@@ -292,11 +297,16 @@ void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
: y.shape(2);
if (start_range + num_y_samples >
static_cast<size_t>(y.shape(2)))
static_cast<size_t>(y.shape(2))) {
throw std::runtime_error(fmt::format(
"fit_3d: fit_range out of bounds for (row={}, col={}, "
"start_range={}, num_y_samples={}, num samples={})",
row, col, start_range, num_y_samples, y.shape(2)));
"start_range={}, end_range={}, num samples={})",
row, col, start_range, start_range + num_y_samples,
y.shape(2)));
}
if (num_y_samples == 0)
continue; // no data to fit
NDView<double, 1> values(&y(row, col, start_range),
{num_y_samples});
+4
View File
@@ -14,6 +14,10 @@ namespace aare::detail {
/**
* @brief Fit one pixel with the Minuit2 minimizer selected by the model.
*
* @param model Model and fit settings.
* @param x Sample positions.
* @param y Measured values at x.
* @param y_err Uncertainties of y; an empty view gives an unweighted fit.
* @param start Starting values, see start_values() in FitHelpers.hpp.
* @param par_out Receives npar fitted values; zeros on failure.
* @param err_out Receives npar errors when non-null; zeros on failure.