mirror of
https://github.com/slsdetectorgroup/aare.git
synced 2026-11-24 01:27:54 +01:00
Decouple the CUDA driver from the underlying cluster search (#369)
## Separate the CUDA pipeline from the search algorithm This PR keeps two things apart. **Using the GPU**: copying frames to the device, spreading them over several CUDA streams, copying results back... This is the same no matter how clusters are found. It lives in `ClusterFinderCUDA`, which never refers to the search code. **Finding the clusters**: this lives in `clusterfinder_algo.cuh`, in three parts: - `CenteredRunningPedestal` is the pedestal: how it is stored on the GPU, and how it moves to and from the host - `FixedWindow` the search algorithm - `FixedWindow::Output` is what one frame writes out, and how to read it back @tomascelko A sparse finder is a basically a new search plus a new `Output`. Thepedestal and everything the pipeline does stay as they are. What a search has to provide is listed at the top of `clusterfinder_algo.cuh`, and `require_algo` checks a few of those at compile time (concepts would be cleaner, but that needs C++20). One thing to know: `Output` uses the same number of bytes for every frame, because the host buffers are allocated before any frame runs. A search that writes a different amount per frame would either reserve room for the worst case, as the current one does, or that part would have to change...
This commit is contained in:
115 files changed
+7382
-1893
No files matched your search
@@ -47,8 +47,126 @@ cmake --build build -j4
|
||||
```
|
||||
|
||||
Useful optional settings include `AARE_DOCS`, `AARE_BENCHMARKS`, `AARE_ASAN`,
|
||||
and `AARE_WARNINGS_AS_ERRORS`. Reconfigure an existing build directory instead
|
||||
of creating alternate in-tree build layouts unless isolation is needed.
|
||||
`AARE_WARNINGS_AS_ERRORS`, `AARE_VERBOSE` (raises the compile-time log
|
||||
level), and `AARE_TUNE_LOCAL` (`-march=native`, not portable). Reconfigure an
|
||||
existing build directory instead of creating alternate in-tree build layouts
|
||||
unless isolation is needed; `build/CMakeCache.txt` records the options and
|
||||
interpreter it was configured with.
|
||||
|
||||
`-Werror=return-type` is always enabled. New code should also compile cleanly
|
||||
under the project's `-Wall -Wextra -pedantic -Wshadow -Wold-style-cast
|
||||
-Wdouble-promotion` flags, which `AARE_WARNINGS_AS_ERRORS` turns into errors.
|
||||
|
||||
The build copies `python/aare/*.py` and the compiled `_aare` extension into
|
||||
`build/aare/`, so `PYTHONPATH=build` makes the package importable. The
|
||||
extension only imports into the interpreter CMake was configured with, which
|
||||
is normally the Conda or venv Python active at configure time. Activate that
|
||||
environment, or resolve the interpreter from the cache:
|
||||
|
||||
```bash
|
||||
PY=$(grep -E '^_?Python_EXECUTABLE' build/CMakeCache.txt | head -1 | cut -d= -f2)
|
||||
PYTHONPATH="$PWD/build" "$PY" -m pytest python/tests
|
||||
```
|
||||
|
||||
Do not fall back to a different system Python.
|
||||
|
||||
With `AARE_BENCHMARKS=ON`, Google Benchmark programs build as
|
||||
`build/run_benchmarks` and `build/fit_benchmark`.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Core containers
|
||||
|
||||
- `NDArray<T, Ndim>` owns contiguous C-order memory; `NDView<T, Ndim>` is a
|
||||
non-owning view with the same shape and stride API. Both derive from
|
||||
`ArrayExpr` (expression templates for element-wise math). Shapes are
|
||||
`std::array<ssize_t, Ndim>`. `NDView<T>` converts to `NDView<const T>`.
|
||||
- `Frame` is a byte buffer plus rows, cols, and `Dtype`, the lowest common
|
||||
denominator returned by file readers. `Dtype` is a runtime type tag built
|
||||
from a bitdepth, a NumPy descriptor, or `typeid`.
|
||||
- `defs.hpp` holds detector enums (`DetectorType`, `TimingMode`,
|
||||
`FrameDiscardPolicy`, `ReadoutMode`), the on-disk `DetectorHeader`, chip
|
||||
constants (`Moench04`, `Matterhorn02`, ...), the `LOCATION` macro used in
|
||||
error messages, and `AARE_ASSERT` (active only with `AARE_CUSTOM_ASSERT`).
|
||||
- `logger.hpp` provides `LOG(logLEVEL) << ...`; levels above `AARE_LOG_LEVEL`
|
||||
(set by CMake) are compiled out.
|
||||
|
||||
### File reading
|
||||
|
||||
`File` is the generic RAII facade. It holds a `unique_ptr<FileInterface>` and
|
||||
dispatches on file extension to one of the concrete readers:
|
||||
|
||||
- `RawFile` reads slsDetector `.raw` data with a `_master_N.json` (or legacy
|
||||
`.raw`) master file. It owns a `RawMasterFile` (master JSON, older raw-text
|
||||
masters, scan parameters, ROIs, disabled UDP ports) and a two-dimensional
|
||||
table of `RawSubFile` indexed `[roi][module]`. Each `RawSubFile` handles one
|
||||
module's sequence of `_dN_fM_` data files and per-frame `DetectorHeader`s.
|
||||
Module placement into the assembled image goes through `DetectorGeometry`,
|
||||
`ModuleGeometry`, and `ROIGeometry` (module gaps, ROIs, UDP-port halves).
|
||||
Frame numbers from the detector are distinct from frame indices in the
|
||||
file; the API uses both and names them accordingly.
|
||||
- `NumpyFile` (`.npy`), `JungfrauDataFile` (legacy `.dat`), and `CtbRawFile`
|
||||
(chip test board; raw ADC samples decoded through `decode.hpp` and the
|
||||
`PixelMap` generators, exposed in Python as `aare.transform` callables).
|
||||
- `experimental::MultiThreadedFileReader` opens one `File` per worker and
|
||||
fills a caller-owned buffer in file order.
|
||||
|
||||
Some chip-specific decoding (Moench03/05 pixel maps, ADC SAR transforms)
|
||||
lives in `python/aare/transform.py` on top of C++ generators.
|
||||
|
||||
### Pedestal and cluster finding
|
||||
|
||||
- `Pedestal<T>` and `FastPedestal<T>` maintain per-pixel running mean and
|
||||
standard deviation, always accumulating in `double`. `FastPedestal` must
|
||||
see `min_pedestal_samples` frames before `ready()`.
|
||||
- `ClusterFinder<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>` is single-threaded:
|
||||
push pedestal frames, then `find_clusters(view, frame_number)` appends to an
|
||||
internal `ClusterVector` that callers take with `steal_clusters()`.
|
||||
Thresholds are `n_sigma * std` and are recomputed by `update_threshold()`.
|
||||
- `ClusterFinderMT` wraps N `ClusterFinder`s, one per thread, each with a
|
||||
`CircularFifo<FrameRef>` input queue backed by a preallocated `FramePool`
|
||||
and a `ProducerConsumerQueue` output. A collector thread funnels all
|
||||
outputs into a single sink queue. Consumers of that sink run their own
|
||||
thread: `ClusterCollector` (accumulate in memory, `steal_clusters()`) or
|
||||
`ClusterFileSink` (write the binary cluster file). The `stop()` and
|
||||
`sync()` ordering matters; read the existing tests before changing
|
||||
lifecycle code.
|
||||
- `Cluster<T, SizeX, SizeY, CoordType>` is a POD (x, y, data[]) and
|
||||
`ClusterVector<Cluster<...>>` is a frame-tagged `std::vector` of them.
|
||||
`ClusterFile` reads and writes the binary format (`int32 frame_number`,
|
||||
`uint32 n_clusters`, raw cluster bytes). The format carries no shape or
|
||||
dtype metadata, so the caller must supply matching template arguments.
|
||||
`CalculateEta.hpp` and `Interpolator` operate on `ClusterVector`s;
|
||||
`algorithm.hpp` holds small 1-D search helpers.
|
||||
- `hist/PixelHistogram` and `PedestalTrackingPixelHistogram` build per-pixel
|
||||
histograms across a frame series, multithreaded by row bands.
|
||||
|
||||
### Fitting
|
||||
|
||||
`Fit.hpp`, `FitModel<Model>`, and `Models.hpp` (`Gaussian`, `Pol1`, `Pol2`,
|
||||
`RisingScurve`, `FallingScurve`, `GaussianErfcPlateau`,
|
||||
`GaussianChargeSharing`, ...) wrap Minuit2. Template bodies and explicit
|
||||
instantiations live in `src/Fit.cpp`; `FitModelImpl` is a pimpl so Minuit2
|
||||
headers never leak into the public API. Minuit2 is a private,
|
||||
`BUILD_INTERFACE`-only dependency of `aare_core`.
|
||||
|
||||
### Python layer
|
||||
|
||||
- `python/src/module.cpp` registers everything. Templated classes are
|
||||
instantiated per value type and cluster size through the
|
||||
`DEFINE_CLUSTER_BINDINGS` and `DEFINE_BINDINGS_CLUSTERFINDER` macros,
|
||||
producing names such as `ClusterFinder_Cluster3x3i`, `Pedestal_d`, and
|
||||
`FastPedestal_i16`. Supported cluster sizes are 2x2, 3x3, 5x5, 7x7, and
|
||||
9x9; value types are `i`, `f`, `d`, and `i16` (3x3 only).
|
||||
`module_config.hpp` fixes the module-wide pedestal type (`pd_type`).
|
||||
- `python/aare/factory.py` maps NumPy dtypes to those suffixes. The facades
|
||||
in `python/aare/*.py` are thin factory functions or subclasses that select
|
||||
the right binding and add Pythonic conveniences (iteration, context
|
||||
managers, `ScanParameters`).
|
||||
- `np_helper.hpp` provides `return_image_data` (moves an `NDArray` into a
|
||||
NumPy array with a capsule deleter) and `make_view_1d/2d/3d` (views into a
|
||||
NumPy buffer).
|
||||
- `aare.experimental` and `_aare.experimental` hold unstable APIs.
|
||||
|
||||
## Implementation conventions
|
||||
|
||||
@@ -99,15 +217,19 @@ ctest --test-dir build --output-on-failure -j4
|
||||
PYTHONPATH="$PWD/build" python -m pytest python/tests
|
||||
```
|
||||
|
||||
For focused runs, use a Catch2 tag or an individual pytest file/test:
|
||||
For focused runs, use a Catch2 tag or test name, or an individual pytest
|
||||
file or test:
|
||||
|
||||
```bash
|
||||
build/run_tests "[tag]"
|
||||
build/run_tests "Exact test case name"
|
||||
PYTHONPATH="$PWD/build" python -m pytest python/tests/test_example.py
|
||||
PYTHONPATH="$PWD/build" python -m pytest python/tests/test_example.py -k name
|
||||
```
|
||||
|
||||
Large detector test files live outside this repository. To include data-backed
|
||||
tests, set `AARE_TEST_DATA` and opt in explicitly:
|
||||
Large detector test files live outside this repository in
|
||||
`https://gitea.psi.ch/detectors/aare-test-data.git` (Git LFS). To include
|
||||
data-backed tests, set `AARE_TEST_DATA` and opt in explicitly:
|
||||
|
||||
```bash
|
||||
export AARE_TEST_DATA=/path/to/aare-test-data
|
||||
@@ -116,21 +238,38 @@ PYTHONPATH="$PWD/build" python -m pytest python/tests --with-data
|
||||
```
|
||||
|
||||
- Start bug fixes with a failing regression test when practical.
|
||||
- Put C++ tests beside the relevant implementation as `src/Thing.test.cpp`.
|
||||
- Put C++ tests beside the relevant implementation as `src/Thing.test.cpp`
|
||||
and add them to `TestSources` in the root `CMakeLists.txt`.
|
||||
- Mark C++ tests requiring external files with `[.with-data]`.
|
||||
- Mark Python tests requiring external files with `@pytest.mark.withdata`.
|
||||
- Mark Python tests requiring external files with `@pytest.mark.withdata` and
|
||||
use the `test_data_path` fixture from `python/tests/conftest.py`.
|
||||
- Prefer synthesizing small input files over depending on external data.
|
||||
`tests/raw_file_helpers.hpp` builds throwaway raw files in C++, and many
|
||||
Python tests write small raw files into `tmp_path`.
|
||||
- `tests/test_config.hpp.in` provides `test_data_path()`;
|
||||
`tests/test_macros.hpp` and `tests/friend_test.hpp` (`TEST_CASE_PRIVATE`
|
||||
with `FRIEND_TEST`) let a test reach private members.
|
||||
- Run both suites for changes that cross the C++/Python boundary.
|
||||
- Do not silently skip required data-backed coverage. Report when the external
|
||||
test data is unavailable.
|
||||
|
||||
## Formatting and static analysis
|
||||
|
||||
The project uses pre-commit. Install the git hook once per clone with
|
||||
`pre-commit install` so it runs on every commit. The hooks in
|
||||
`.pre-commit-config.yaml` are clang-format on C++, cmake-format on CMake
|
||||
files, `typos` on `docs/` (project words are whitelisted in `typos.toml`), and
|
||||
basic YAML, TOML, JSON, and large-file checks. CI runs the same hooks on pull
|
||||
requests.
|
||||
|
||||
Before handing off a broad change, run the relevant checks:
|
||||
|
||||
```bash
|
||||
pre-commit run --all-files
|
||||
cmake --build build --target check-format
|
||||
cmake --build build --target clang-tidy
|
||||
pre-commit install # once per clone
|
||||
pre-commit run --all-files # what CI runs
|
||||
cmake --build build --target check-format # diff-based clang-format check
|
||||
cmake --build build --target format-files # apply clang-format to all .cpp/.hpp
|
||||
cmake --build build --target clang-tidy # uses build/compile_commands.json
|
||||
```
|
||||
|
||||
C++ formatting follows `.clang-format` (four-space indentation and an 80-column
|
||||
@@ -139,7 +278,9 @@ code as part of a focused change.
|
||||
|
||||
## Documentation and release notes
|
||||
|
||||
- Update the relevant `.rst` pages for public behavior or API changes.
|
||||
- Update the relevant `.rst` pages for public behavior or API changes. C++
|
||||
pages live at `docs/src/<Class>.rst`; Python pages live under
|
||||
`docs/src/python/<area>/`.
|
||||
- Add new pages to `docs/src/index.rst` or the relevant nested toctree.
|
||||
- Update `RELEASE.md` under `## Next` for user-visible features, bug fixes, and
|
||||
API changes.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
# CLAUDE.md
|
||||
|
||||
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
|
||||
|
||||
All project guidance lives in `AGENTS.md`: layout, build and test commands,
|
||||
architecture, conventions, formatting, documentation, and release notes.
|
||||
Read it and follow it. Keep new guidance there rather than here so that every
|
||||
agent and contributor sees the same instructions.
|
||||
+25
-3
@@ -394,6 +394,7 @@ set(PUBLICHEADERS
|
||||
include/aare/hist/PixelHistogramImpl.hpp
|
||||
include/aare/hist/PedestalTrackingPixelHistogram.hpp
|
||||
include/aare/GainMap.hpp
|
||||
include/aare/ROI.hpp
|
||||
include/aare/ROIGeometry.hpp
|
||||
include/aare/DetectorGeometry.hpp
|
||||
include/aare/JungfrauDataFile.hpp
|
||||
@@ -408,13 +409,20 @@ set(PUBLICHEADERS
|
||||
include/aare/RawMasterFile.hpp
|
||||
include/aare/RawSubFile.hpp
|
||||
include/aare/VarClusterFinder.hpp
|
||||
include/aare/to_string.hpp
|
||||
include/aare/utils/task.hpp
|
||||
include/aare/utils/ifstream_helpers.hpp
|
||||
include/aare/utils/math_helpers.hpp)
|
||||
|
||||
if(AARE_CUDA)
|
||||
list(APPEND PUBLICHEADERS include/aare/ClusterFinderCUDA.hpp
|
||||
include/aare/clusterfinder_kernel.cuh include/aare/utils/cuda_check.cuh)
|
||||
list(
|
||||
APPEND
|
||||
PUBLICHEADERS
|
||||
include/aare/ClusterFinderCUDA.hpp
|
||||
include/aare/clusterfinder_algo.cuh
|
||||
include/aare/clusterfinder_kernel.cuh
|
||||
include/aare/RAII_device.hpp
|
||||
include/aare/utils/cuda_check.cuh)
|
||||
endif()
|
||||
|
||||
set(SourceFiles
|
||||
@@ -422,6 +430,7 @@ set(SourceFiles
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/CtbRawFile.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/decode.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/defs.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ROI.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ROIGeometry.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.cpp
|
||||
@@ -470,7 +479,7 @@ if(AARE_VERBOSE)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_VERBOSE)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logDEBUG5)
|
||||
else()
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logERROR)
|
||||
target_compile_definitions(aare_core PUBLIC AARE_LOG_LEVEL=aare::logWARNING)
|
||||
endif()
|
||||
|
||||
if(AARE_CUSTOM_ASSERT)
|
||||
@@ -493,11 +502,13 @@ endif()
|
||||
|
||||
if(AARE_TESTS)
|
||||
set(TestSources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/tests/raw_file_helpers.hpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/algorithm.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/calibration.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/defs.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/decode.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Dtype.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/FilePtr.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Fit.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Frame.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/DetectorGeometry.test.cpp
|
||||
@@ -512,6 +523,7 @@ if(AARE_TESTS)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFile.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFinderMT.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/Pedestal.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/FastPedestal.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PixelHistogramImpl.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PixelHistogram.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/hist/PedestalTrackingPixelHistogram.test.cpp
|
||||
@@ -521,11 +533,21 @@ if(AARE_TESTS)
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/NumpyHelpers.test.cpp
|
||||
${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/utils/task.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/to_string.test.cpp)
|
||||
target_sources(tests PRIVATE ${TestSources})
|
||||
endif()
|
||||
|
||||
# GPU tests: the Catch2 case is plain C++, the CUDA work sits in a .cu helper so
|
||||
# Catch2 is never compiled by nvcc.
|
||||
if(AARE_TESTS AND AARE_CUDA)
|
||||
target_sources(
|
||||
tests PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFinderCUDA.test.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/src/ClusterFinderCUDA_testimpl.cu)
|
||||
target_link_libraries(tests PRIVATE aare_cuda)
|
||||
endif()
|
||||
|
||||
if(AARE_MASTER_PROJECT)
|
||||
set(AARE_INSTALL_TARGETS aare_core aare_compiler_flags)
|
||||
if(AARE_CUDA)
|
||||
|
||||
+88
-3
@@ -4,6 +4,16 @@
|
||||
|
||||
### New Features:
|
||||
|
||||
- Added the Python ``FrameDiscardPolicy`` enum with ``NoDiscard``, ``Discard``,
|
||||
and ``DiscardPartial``, enabling access to ``RawMasterFile.frame_discard_policy``.
|
||||
- Added the Python ``Pedestal`` factory with ``dtype`` selection, matching
|
||||
``FastPedestal`` and defaulting to ``float64`` output.
|
||||
- Added ``FastPedestal`` in C++ and Python for per-pixel running mean
|
||||
and population standard deviation. It supports exponentially
|
||||
- Added ``ClusterFile.frames()`` and ``ClusterFile.chunks()`` in C++ and
|
||||
Python for iteration from the current file position. Frames preserve empty
|
||||
frames and frame numbers; chunks support an optional positive size override.
|
||||
Python's default file iteration continues to yield chunks.
|
||||
- Added ``FastPedestal`` in C++ and Python for per-pixel running mean,
|
||||
population variance, and standard deviation. It supports exponentially
|
||||
weighted updates, initialization from files, direct subtraction from NumPy
|
||||
@@ -16,9 +26,32 @@
|
||||
- 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.
|
||||
- Added string representator in python for Cluster and Eta
|
||||
- Added roi slice method in python for easy slicing of numpy arrays ``array[roi.slice()]``.
|
||||
- added context manager for ``aare.RawMasterFile``
|
||||
|
||||
### API Changes:
|
||||
|
||||
- ``FastPedestal`` variance is now a private ``double`` intermediate. Removed
|
||||
the C++ ``variance()``/``variance_unchecked()`` APIs and Python ``var()``.
|
||||
Standard deviation is calculated before conversion to the output type,
|
||||
avoiding overflow of intermediate variance for ``int16`` output. Negative
|
||||
variance from floating-point roundoff is clamped to zero.
|
||||
- ``Pedestal`` now always accumulates sums and sums of squares in ``double``,
|
||||
like ``FastPedestal``. Mean and standard deviation output types
|
||||
are unchanged. Removed the C++ ``get_sum()``/``get_sum2()`` getters and
|
||||
Python ``sum``/``sum2`` properties; internal sums are no longer exposed.
|
||||
- Removed the public ``Pedestal.variance()`` and ``cached_std()`` APIs and
|
||||
C++ ``update_std()``. Use ``std()`` to calculate the current population
|
||||
standard deviation; variance is now an internal implementation detail.
|
||||
- Added ``ClusterFile::read_frame(ClusterVector&)`` for allocation-reusing C++
|
||||
reads. It returns ``false`` at a clean end of file. The value-returning C++
|
||||
overload now returns ``std::optional<ClusterVector<ClusterType>>`` and
|
||||
Python ``read_frame()`` returns ``None`` at end of file. Incomplete frames
|
||||
still raise an error.
|
||||
- Added an explicit boolean conversion to the C++ ``FilePtr`` type.
|
||||
- Removed the public C++ ``ClusterFile::open`` method. Construct a new
|
||||
``ClusterFile`` to reopen a file or change its mode.
|
||||
- ``ClusterFinder`` now uses ``FastPedestal``. It must receive 1000 pedestal
|
||||
frames before cluster finding; ``find_clusters()`` raises
|
||||
an error until initialization is complete. Added ``update_threshold()`` to
|
||||
@@ -37,8 +70,62 @@
|
||||
- ``NDView<T, Ndim>`` now converts to ``NDView<const T, Ndim>``;
|
||||
``expand4to8bit`` and ``expand24to32bit`` accept const input views.
|
||||
|
||||
- ``RawMasterFile::geometry()`` is deprecetad and returns full detector geometry information including module geometry. Use
|
||||
``RawMasterFile::module_layout()`` to get num_modules in x an y
|
||||
- ``RawMasterFile::rois()`` always returns a list of rois (no optional). Per default it returns a list of one ROI element spawing the entire detector
|
||||
- ``TimingMode::Auto`` changed to ``TimingMode::AUTO_TIMING``, ``TimingMode::Trigger`` changed to ``TimingMode::TRIGGER_EXPOSURE``
|
||||
|
||||
### Bugfixes:
|
||||
- Mismatched operators inhibited vectorization in gcc of NDArray math operators
|
||||
- ``RawFile`` and ``File`` reject raw files with frame padding disabled unless
|
||||
the frame discard policy is ``discardpartial``. The constructor reports the
|
||||
master path before opening data subfiles. Legacy ``.raw`` master files now
|
||||
parse the frame discard policy so unpadded ``discardpartial`` files remain
|
||||
readable.
|
||||
- Fixed ``CtbRawFile.read_frame(index)`` and reads after ``seek(index)`` at
|
||||
subfile boundaries skipping a subfile, returning the wrong frame or raising
|
||||
``Subfile index out of range``.
|
||||
- ``Pedestal`` reports mismatched frame shapes with exceptions in all push
|
||||
overloads, including Debug builds, instead of aborting on assertions.
|
||||
- Python ``Pedestal`` constructors reject negative dimensions and sample
|
||||
counts instead of converting them to large unsigned values.
|
||||
- ``Pedestal`` clamps negative variance from floating-point roundoff to zero,
|
||||
preventing NaN standard deviations for nearly constant inputs.
|
||||
- Python ``Pedestal.push()`` now requires C-contiguous ``uint16`` frames
|
||||
without implicit conversion. Both ``push()`` and ``push_with_threshold()``
|
||||
validate that frames and thresholds are two-dimensional before constructing
|
||||
views, preventing incorrect results from unsupported array layouts or ranks.
|
||||
|
||||
- Fixed a leaked empty ``ClusterVector`` at the end of Python ``ClusterFile``
|
||||
iteration. Chunk iteration now rejects a zero chunk size.
|
||||
- ``ClusterFile::read_clusters`` and Python iteration now report incomplete
|
||||
frame headers and cluster records instead of treating truncated files as a
|
||||
clean end of file, with or without ROI or noise filtering.
|
||||
- ``ClusterFile::write_frame`` now reports incomplete writes instead of
|
||||
silently continuing with a truncated file.
|
||||
- Gain-map application now checks the complete cluster footprint, preventing
|
||||
out-of-bounds access for cluster sizes larger than 3x3.
|
||||
- ``RawFile`` now derives its frame count from the shortest selected raw
|
||||
subfile series across all ROIs. Frame-number reads use the same bounds, and
|
||||
Python ``len(reader)`` returns the adjusted count. A warning is printed when
|
||||
subfile counts differ or their minimum differs from the recorded master
|
||||
count. The expected frame count is not used and master metadata is preserved.
|
||||
Warning-level logging is now enabled in non-verbose builds.
|
||||
- Raw frame, batch, ROI, and frame-number read errors now include the attempted
|
||||
frame index and file path in C++ and Python, preserving subfile error details.
|
||||
Subfile errors omit redundant master-file context and C++ source locations;
|
||||
out-of-range errors include the available frame count.
|
||||
Synchronization errors identify the last raw data file for the affected module.
|
||||
Top-level frame bounds errors state the total frame count and that indices
|
||||
are zero-based.
|
||||
- Fixed ``ClusterVector`` move operations to transfer storage instead of
|
||||
copying every cluster.
|
||||
- Validate that ``ClusterVector`` masks are one-dimensional, C-contiguous
|
||||
Boolean arrays.
|
||||
- Preserve signed ``ClusterVector`` frame numbers when filtering or reducing
|
||||
cluster dimensions.
|
||||
- Fixed broken reading of old (pre reordering) Moench03
|
||||
- Supports reading all timing modes supported in slsDetectorPackage (auto, trigger, gating, burst_trigger, trigger_gating)
|
||||
|
||||
## 2026.7.2
|
||||
|
||||
@@ -54,6 +141,7 @@
|
||||
- ``aare.transfrom.Matterhorn10Transform`` reshapes data such that first dimension is number of counters
|
||||
- Added support for len() for files. Returns the number of frames
|
||||
- Added support for direct subtraction of Pedestal from numpy array
|
||||
- Added support to read files with disabled udp ports
|
||||
|
||||
### Bugfixes:
|
||||
|
||||
@@ -185,6 +273,3 @@ dhanya.thattil@psi.ch
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -18,8 +18,9 @@ FetchContent_MakeAvailable(benchmark)
|
||||
add_executable(benchmarks)
|
||||
|
||||
target_sources(
|
||||
benchmarks PRIVATE ndarray_benchmark.cpp ndview_benchmark.cpp
|
||||
calculateeta_benchmark.cpp reduce_benchmark.cpp)
|
||||
benchmarks
|
||||
PRIVATE ndarray_benchmark.cpp ndview_benchmark.cpp calculateeta_benchmark.cpp
|
||||
reduce_benchmark.cpp clusterfile_benchmark.cpp)
|
||||
|
||||
# Link Google Benchmark and other necessary libraries
|
||||
target_link_libraries(benchmarks PRIVATE benchmark::benchmark aare_core
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/ClusterFile.hpp"
|
||||
|
||||
#include <benchmark/benchmark.h>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
|
||||
class ClusterFileFixture : public benchmark::Fixture {
|
||||
using Cluster = aare::Cluster<int32_t, 3, 3>;
|
||||
using File = aare::ClusterFile<Cluster>;
|
||||
using Vector = aare::ClusterVector<Cluster>;
|
||||
|
||||
std::filesystem::path m_path;
|
||||
static constexpr int32_t frame_count = 256;
|
||||
static constexpr size_t chunk_size = 1000;
|
||||
|
||||
static void observe(Vector &clusters) {
|
||||
benchmark::DoNotOptimize(clusters.data());
|
||||
benchmark::DoNotOptimize(clusters.size());
|
||||
}
|
||||
|
||||
public:
|
||||
void SetUp(const benchmark::State &state) override {
|
||||
const auto stamp =
|
||||
std::chrono::steady_clock::now().time_since_epoch().count();
|
||||
m_path = std::filesystem::temp_directory_path() /
|
||||
("aare-cluster-benchmark-" + std::to_string(stamp) + ".clust");
|
||||
File writer(m_path, chunk_size, "w");
|
||||
Vector frame(0);
|
||||
frame.resize(state.range(0));
|
||||
for (int32_t number = 0; number < frame_count; ++number) {
|
||||
frame.set_frame_number(number);
|
||||
writer.write_frame(frame);
|
||||
}
|
||||
}
|
||||
|
||||
void TearDown(const benchmark::State &) override {
|
||||
std::error_code error;
|
||||
std::filesystem::remove(m_path, error);
|
||||
}
|
||||
|
||||
template <bool Frames, bool Iterate> void read(benchmark::State &state) {
|
||||
for (auto _ : state) {
|
||||
File reader(m_path, chunk_size);
|
||||
if constexpr (Iterate) {
|
||||
auto consume = [](auto range) {
|
||||
for (auto &clusters : range) {
|
||||
observe(clusters);
|
||||
}
|
||||
};
|
||||
if constexpr (Frames) {
|
||||
consume(reader.frames());
|
||||
} else {
|
||||
consume(reader.chunks());
|
||||
}
|
||||
} else if constexpr (Frames) {
|
||||
Vector frame(0);
|
||||
while (reader.read_frame(frame)) {
|
||||
observe(frame);
|
||||
}
|
||||
} else {
|
||||
while (true) {
|
||||
auto chunk = reader.read_clusters(chunk_size);
|
||||
if (chunk.empty()) {
|
||||
break;
|
||||
}
|
||||
observe(chunk);
|
||||
}
|
||||
}
|
||||
}
|
||||
state.SetBytesProcessed(state.iterations() * frame_count *
|
||||
state.range(0) * sizeof(Cluster));
|
||||
}
|
||||
};
|
||||
|
||||
BENCHMARK_DEFINE_F(ClusterFileFixture, ReadFrames)(benchmark::State &state) {
|
||||
read<true, false>(state);
|
||||
}
|
||||
BENCHMARK_DEFINE_F(ClusterFileFixture, IterateFrames)(benchmark::State &state) {
|
||||
read<true, true>(state);
|
||||
}
|
||||
BENCHMARK_DEFINE_F(ClusterFileFixture, ReadChunks)(benchmark::State &state) {
|
||||
read<false, false>(state);
|
||||
}
|
||||
BENCHMARK_DEFINE_F(ClusterFileFixture, IterateChunks)(benchmark::State &state) {
|
||||
read<false, true>(state);
|
||||
}
|
||||
|
||||
BENCHMARK_REGISTER_F(ClusterFileFixture, ReadFrames)->Arg(64)->Arg(1024);
|
||||
BENCHMARK_REGISTER_F(ClusterFileFixture, IterateFrames)->Arg(64)->Arg(1024);
|
||||
BENCHMARK_REGISTER_F(ClusterFileFixture, ReadChunks)->Arg(64)->Arg(1024);
|
||||
BENCHMARK_REGISTER_F(ClusterFileFixture, IterateChunks)->Arg(64)->Arg(1024);
|
||||
+1
-1
@@ -36,7 +36,7 @@ add_custom_target(
|
||||
docs
|
||||
COMMAND ${DOXYGEN_EXECUTABLE} ${DOXYGEN_OUT}
|
||||
COMMAND
|
||||
${SPHINX_EXECUTABLE} -a -b html
|
||||
${SPHINX_EXECUTABLE} -W -a -b html
|
||||
-Dbreathe_projects.aare=${CMAKE_CURRENT_BINARY_DIR}/xml -c "${SPHINX_BUILD}"
|
||||
${SPHINX_BUILD}/src ${SPHINX_BUILD}/html
|
||||
COMMENT "Generating documentation with Sphinx")
|
||||
@@ -36,6 +36,19 @@ extensions = ['breathe',
|
||||
breathe_default_project = "aare"
|
||||
napoleon_use_ivar = True
|
||||
|
||||
# CUDA execution-space and pointer qualifiers are not C++, so Sphinx's C++
|
||||
# domain cannot parse declarations such as the __global__ kernels in
|
||||
# aare::device. Declaring them as attributes lets the parser skip them instead
|
||||
# of failing, which matters because the docs are built with -W.
|
||||
cpp_id_attributes = [
|
||||
'__global__',
|
||||
'__device__',
|
||||
'__host__',
|
||||
'__forceinline__',
|
||||
'__shared__',
|
||||
'__restrict__',
|
||||
]
|
||||
|
||||
|
||||
# Add any paths that contain templates here, relative to this directory.
|
||||
templates_path = ['_templates']
|
||||
|
||||
@@ -1,8 +1,40 @@
|
||||
ClusterFile
|
||||
=============
|
||||
|
||||
Use ``frames()`` to iterate over complete frames, including empty frames and
|
||||
frames whose clusters are all rejected by ROI or noise filtering. Each result
|
||||
keeps its stored frame number; missing frame numbers are not synthesized.
|
||||
|
||||
.. code-block:: cpp
|
||||
|
||||
using ClusterType = aare::Cluster<int32_t, 3, 3>;
|
||||
aare::ClusterFile<ClusterType> file("clusters.clust");
|
||||
for (auto &frame : file.frames()) {
|
||||
process_frame(frame.frame_number(), frame);
|
||||
}
|
||||
|
||||
Use ``chunks()`` for the constructor's chunk size, or ``chunks(10000)`` to
|
||||
request a different size for that traversal. The size must be positive and
|
||||
counts selected clusters after filtering. Chunks may split or combine frames,
|
||||
so their frame numbers are not reliable per-cluster metadata. Empty chunks are
|
||||
not yielded; only the final chunk can contain fewer clusters than requested.
|
||||
Both ranges apply the configured gain map and report incomplete files as
|
||||
errors, just like the explicit read methods.
|
||||
|
||||
Ranges borrow the file and consume its current position without rewinding.
|
||||
Constructing a range does not read; ``begin()`` reads the first result and
|
||||
increment reads the next. Breaking a loop does not read ahead. Use one
|
||||
traversal at a time and separate files for independent cursors. Switching to
|
||||
frame reads after a chunk stops partway through a frame raises an error until
|
||||
the remaining clusters in that frame have been read.
|
||||
|
||||
The file must outlive its ranges and iterators and must not be moved while
|
||||
they are in use. Iterators are move only and support C++17 range-based loops,
|
||||
not algorithms requiring copyable STL input iterators. References to a result
|
||||
last until advancement or iterator destruction. Move a result out with
|
||||
``auto retained = std::move(frame)`` to retain it. Frame iteration reuses the
|
||||
current vector's storage when it has not been moved out.
|
||||
|
||||
.. doxygenclass:: aare::ClusterFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:private-members:
|
||||
|
||||
+41
-1
@@ -1,8 +1,48 @@
|
||||
RawFile
|
||||
===============
|
||||
|
||||
Reading requires frame padding to be enabled
|
||||
or ``Frame Discard Policy`` to be ``discardpartial``.
|
||||
The constructor checks the
|
||||
parsed master metadata before opening data subfiles and throws
|
||||
``std::runtime_error`` with the master path if this requirement is not met.
|
||||
This applies to JSON and legacy ``.raw`` masters, including when opened through
|
||||
``aare::File``. ``RawMasterFile`` can still be used to inspect their metadata.
|
||||
|
||||
``total_frames()`` is the minimum actual frame count across all selected
|
||||
``RawSubFile`` objects in all ROIs. Each subfile count includes its complete
|
||||
series of ``.raw`` files and is determined when the file is opened. Disabled
|
||||
UDP ports are excluded. An empty subfile makes the count zero; opening a file
|
||||
with no selected subfiles raises an error.
|
||||
|
||||
A warning is logged once on opening if the subfile counts differ or their
|
||||
minimum differs from ``master().frames_in_file()``. It reports the subfile count
|
||||
range, the master count, and the count used for reading. The master metadata
|
||||
is preserved. Its expected frame count does not affect the count used for
|
||||
reading.
|
||||
|
||||
Frame, batch, ROI, and frame-number reads use this minimum as their bound.
|
||||
Frame-number synchronization may still fail within this bound if detector
|
||||
frame numbers differ between subfiles.
|
||||
|
||||
Read errors include the attempted zero-based frame index and the failing file
|
||||
path. Errors from a data subfile identify that subfile's path and preserve
|
||||
the underlying failure reason without adding a master-file wrapper or C++
|
||||
source location. Out-of-range subfile errors also report the available frame
|
||||
count across that subfile's series. This applies to frame, batch, ROI, and
|
||||
frame-number reads, including reads through ``aare::File``.
|
||||
|
||||
The frame index is the position in the file, not the frame number recorded by
|
||||
the detector. Batch errors report the index of the frame that failed.
|
||||
|
||||
Synchronization errors identify the last ``.raw`` data file read for the module
|
||||
that ran out of frames. Requests rejected as out of range before accessing a
|
||||
subfile report the master path, since there is no single failing data file.
|
||||
The top-level frame bounds error states the number of frames in the file and
|
||||
that indices are zero-based.
|
||||
|
||||
|
||||
.. doxygenclass:: aare::RawFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:private-members:
|
||||
:private-members:
|
||||
@@ -3,17 +3,16 @@
|
||||
ClusterVector
|
||||
================
|
||||
|
||||
The ClusterVector, holds clusters from the ClusterFinder. Since it is templated
|
||||
in C++ we use a suffix indicating the type of cluster it holds. The suffix follows
|
||||
the same pattern as for ClusterFile i.e. ``ClusterVector_Cluster3x3i``
|
||||
for a vector holding 3x3 integer clusters.
|
||||
A ClusterVector stores fixed-size clusters contiguously. Since it is templated
|
||||
in C++, each bound class has a suffix indicating the cluster type. The suffix
|
||||
follows the same pattern as ClusterFile; for example,
|
||||
``ClusterVector_Cluster3x3i`` stores 3x3 clusters with 32-bit integer pixels.
|
||||
|
||||
|
||||
At the moment the functionality from python is limited and it is not supported
|
||||
to push_back clusters to the vector. The intended use case is to pass it to
|
||||
C++ functions that support the ClusterVector or to view it as a numpy array.
|
||||
The intended use case is to pass a ClusterVector to C++ functions that support
|
||||
it or to view it as a NumPy array.
|
||||
|
||||
**View ClusterVector as numpy array**
|
||||
**View ClusterVector as a NumPy array**
|
||||
|
||||
.. code:: python
|
||||
|
||||
@@ -25,7 +24,16 @@ C++ functions that support the ClusterVector or to view it as a numpy array.
|
||||
clusters = np.array(cluster_vector)
|
||||
|
||||
# Avoid copying the data by passing copy=False
|
||||
clusters = np.array(cluster_vector, copy = False)
|
||||
clusters = np.array(cluster_vector, copy=False)
|
||||
|
||||
.. warning::
|
||||
|
||||
A NumPy array created with ``copy=False`` is a view of the ClusterVector's
|
||||
current storage. Do not call ``push_back`` or otherwise change the
|
||||
ClusterVector while using the view. A ``push_back`` that reallocates the
|
||||
backing buffer leaves existing NumPy views pointing to invalid memory, and
|
||||
appending without reallocation does not update their shape. Use
|
||||
``copy=True`` if the ClusterVector may change after creating the array.
|
||||
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
@@ -35,7 +43,8 @@ C++ functions that support the ClusterVector or to view it as a numpy array.
|
||||
:undoc-members:
|
||||
:inherited-members:
|
||||
|
||||
Below is the API of the ClusterVector_Cluster3x3i but all variants share the same API.
|
||||
Below is the API of ``ClusterVector_Cluster3x3i``. All variants share the same
|
||||
API.
|
||||
|
||||
.. autoclass:: aare._aare.ClusterVector_Cluster3x3i
|
||||
:special-members: __init__, __call__
|
||||
@@ -45,14 +54,39 @@ Below is the API of the ClusterVector_Cluster3x3i but all variants share the sam
|
||||
:inherited-members:
|
||||
|
||||
|
||||
**Free Functions:**
|
||||
**Free Functions:**
|
||||
|
||||
.. autofunction:: reduce_to_3x3
|
||||
.. py:function:: hitmap(image_size, clusters)
|
||||
:noindex:
|
||||
|
||||
Reduce a single Cluster to 3x3 by taking the 3x3 subcluster with highest photon energy.
|
||||
Count cluster centers into an ``int32`` image. ``image_size`` is given as
|
||||
``(rows, columns)``, and output element ``[y, x]`` contains the number of
|
||||
photon hits at that coordinate. Out-of-bounds hits are ignored. All registered
|
||||
ClusterVector variants are accepted.
|
||||
|
||||
.. autofunction:: reduce_to_2x2
|
||||
:param tuple[int, int] image_size: Shape of the output image.
|
||||
:param ClusterVector clusters: Clusters whose centers are counted.
|
||||
:return: Hit counts with shape ``image_size``.
|
||||
:rtype: numpy.ndarray
|
||||
|
||||
.. py:function:: reduce_to_3x3(clustervector)
|
||||
:noindex:
|
||||
|
||||
Reduce a single Cluster to 2x2 by taking the 2x2 subcluster with highest photon energy.
|
||||
Return a new vector containing the central 3x3 block of every input cluster.
|
||||
Cluster order, coordinates, frame number, and pixel dtype are preserved.
|
||||
|
||||
:param ClusterVector clustervector: Input clusters with both dimensions at
|
||||
least 3 and at least one dimension greater than 3.
|
||||
:return: Reduced 3x3 clusters.
|
||||
:rtype: ClusterVector
|
||||
|
||||
.. py:function:: reduce_to_2x2(clustervector)
|
||||
:noindex:
|
||||
|
||||
Return a new vector containing the highest-sum center-adjacent 2x2 block of
|
||||
every input cluster. Cluster order, coordinates, frame number, and pixel
|
||||
dtype are preserved.
|
||||
|
||||
:param ClusterVector clustervector: Input clusters of size 2x2 or larger.
|
||||
:return: Reduced 2x2 clusters.
|
||||
:rtype: ClusterVector
|
||||
@@ -1,26 +1,78 @@
|
||||
|
||||
ClusterFile
|
||||
============
|
||||
===========
|
||||
|
||||
The :func:`ClusterFile` factory is the main interface for reading and writing
|
||||
cluster files. Use ``mode="r"`` to read, ``mode="w"`` to truncate and
|
||||
write, or ``mode="a"`` to append.
|
||||
|
||||
The :class:`ClusterFile` class is the main interface to read and write clusters in aare. Unfortunately the
|
||||
old file format does not include metadata like the cluster size and the data type. This means that the
|
||||
user has to know this information from other sources. Specifying the wrong cluster size or data type
|
||||
will lead to garbage data being read.
|
||||
The format does not store the cluster dimensions, value type, coordinate type,
|
||||
padding, or byte order. The ``cluster_size`` and ``dtype`` arguments must match
|
||||
the writer; otherwise the bytes are interpreted incorrectly.
|
||||
|
||||
Use ``frames()`` when frame boundaries and the frame number matter:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
with ClusterFile("clusters.clust") as file:
|
||||
for frame in file.frames():
|
||||
print(frame.frame_number, frame.size)
|
||||
|
||||
Each stored frame is yielded, including empty frames and frames whose clusters
|
||||
are all rejected by filtering. Missing frame numbers are not synthesized.
|
||||
The explicit ``read_frame()`` method returns one frame or ``None`` at EOF.
|
||||
|
||||
Use ``chunks()`` to iterate over chunks of ``chunk_size`` clusters. Per default
|
||||
the chunk size defined in the constructor is used. Alternatively one can pass
|
||||
an explicit chunk size to the function for that specific traversal:
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
with ClusterFile("clusters.clust", chunk_size=1000) as file:
|
||||
for clusters in file.chunks(10000):
|
||||
process(clusters)
|
||||
|
||||
Chunk sizes must be positive and count selected clusters after filtering.
|
||||
``file.chunks(10000)`` does not overwrite the constructor argument ``chunk_size``
|
||||
. Iterating directly
|
||||
over ``file`` or calling ``next(file)`` still reads chunks using that default.
|
||||
Chunks and ``read_clusters(n_clusters)`` may split or combine frames, so their
|
||||
frame numbers are not reliable per-cluster metadata. Empty chunks are not
|
||||
yielded.
|
||||
Chunk reads and iteration raise an error if they encounter an incomplete frame
|
||||
header or cluster record, including when ROI or noise filtering is enabled.
|
||||
They return fewer clusters than requested only at a clean end of file.
|
||||
|
||||
Both iterators consume the current file position without rewinding. Creating
|
||||
an iterator does not read; each ``next()`` reads one result without prefetching
|
||||
the following result. Use one traversal at a time and separate readers for
|
||||
independent cursors. Switching to frames after a chunk stops partway through a
|
||||
frame raises an error until the remaining clusters in that frame have been
|
||||
read. Exhausted iterators continue to raise ``StopIteration``.
|
||||
|
||||
Iterators keep their file object alive, but explicitly closing the file or
|
||||
leaving its ``with`` block prevents further reads. Every yielded
|
||||
``ClusterVector`` owns its storage and can be retained after iteration advances
|
||||
or the file closes. NumPy views also remain valid across those operations;
|
||||
as usual, resizing or modifying the allocation of their backing vector can
|
||||
invalidate them.
|
||||
|
||||
When a gain map is configured, it is applied to every cluster whose complete
|
||||
footprint lies inside the map. Clusters whose footprint extends beyond the
|
||||
gain-map boundaries remain in the returned cluster vector, but all their data
|
||||
values are set to zero.
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
|
||||
.. autoclass:: ClusterFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:inherited-members:
|
||||
.. autofunction:: ClusterFile
|
||||
|
||||
|
||||
Below is the API of the ClusterFile_Cluster3x3i but all variants share the same API.
|
||||
Below is the API of ``ClusterFile_Cluster3x3i``; all compiled variants share the
|
||||
same API.
|
||||
|
||||
.. autoclass:: aare._aare.ClusterFile_Cluster3x3i
|
||||
:special-members: __init__
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
:inherited-members:
|
||||
@@ -6,6 +6,10 @@ Read analog, digital and transceiver samples from a raw file containing
|
||||
data from the Chip Test Board. Uses :mod:`aare.transform` to decode the
|
||||
data into a format that the user can work with.
|
||||
|
||||
``read_frame(index)`` reads the frame at the zero-based index across the raw
|
||||
subfiles and advances the position to ``index + 1``. A subsequent
|
||||
``read_frame()`` reads the following frame, including across subfile boundaries.
|
||||
|
||||
.. code:: python
|
||||
|
||||
import aare
|
||||
@@ -22,4 +26,4 @@ data into a format that the user can work with.
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
:inherited-members:
|
||||
@@ -3,8 +3,45 @@ RawFile
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
|
||||
Reading requires frame padding to be enabled
|
||||
or ``Frame Discard Policy`` to be ``discardpartial``. Construction raises
|
||||
``RuntimeError`` with the master path before opening data subfiles if this
|
||||
requirement is not met. This applies to JSON and legacy ``.raw`` masters,
|
||||
including when opened through ``File``. ``RawMasterFile`` can still be used
|
||||
to inspect their metadata.
|
||||
|
||||
``total_frames`` and ``len(reader)`` report the minimum actual frame count
|
||||
across all selected subfiles and ROIs, including each subfile's complete
|
||||
``.raw`` series. ``read()`` uses this count, and ``read_n()`` and
|
||||
``read_n_with_roi()`` limit batches to the remaining frames. Counts are
|
||||
determined when the reader is constructed.
|
||||
An empty subfile makes the count zero, and construction fails if no subfiles
|
||||
are selected.
|
||||
|
||||
The C++ logger prints one warning to stderr on opening if the subfile counts
|
||||
differ or their minimum differs from ``reader.master.frames_in_file``. The
|
||||
warning includes the count range, the recorded master count, and the count
|
||||
used for reading. Master metadata is preserved; its expected frame count
|
||||
does not affect reading bounds. Detector frame-number mismatches can still
|
||||
cause synchronization errors within these bounds.
|
||||
|
||||
Reading errors raise ``RuntimeError`` with the attempted zero-based frame index
|
||||
and the failing file path. If a data subfile fails, its path and the underlying
|
||||
failure reason are reported. Out-of-range subfile errors include the available frame count across
|
||||
that subfile's series. This applies to ``read_frame()``, ``read_n()``,
|
||||
and the ROI reading methods. The frame index is the position in the file, not
|
||||
the frame number recorded by the detector.
|
||||
|
||||
Synchronization errors also identify the last ``.raw`` data file read for the
|
||||
module that ran out of frames. An out-of-range request rejected before accessing
|
||||
a subfile reports the master path.
|
||||
|
||||
For a file containing five frames, the valid indices are 0 through 4. Attempting
|
||||
to read index 5 raises an error stating: ``Frame index 5 is out of range: file
|
||||
contains 5 frames (indices are zero-based)``.
|
||||
|
||||
.. autoclass:: RawFile
|
||||
:members:
|
||||
:undoc-members:
|
||||
:show-inheritance:
|
||||
:inherited-members:
|
||||
:inherited-members:
|
||||
@@ -1,7 +1,7 @@
|
||||
FastPedestal
|
||||
============
|
||||
|
||||
``FastPedestal`` calculates a running mean, variance and standard deviation for each pixel in a
|
||||
``FastPedestal`` calculates a running mean and standard deviation for each pixel in a
|
||||
series of frames. The python binding only exposes ``uint16`` input but the underlying
|
||||
C++ class is templated. Initialize it with ``n_samples`` frames using
|
||||
``add_init_frame()``. Once ``ready`` is true, use ``push_ema()`` to update the exponential
|
||||
@@ -18,7 +18,10 @@ The public factory selects the bound C++ specialization from ``dtype``:
|
||||
* ``numpy.float32`` creates ``FastPedestal_f``
|
||||
* ``numpy.int16`` creates ``FastPedestal_i16``
|
||||
|
||||
The internal calculations are done with double, but the cached mean and on demand var and std are returned in the specified type.
|
||||
Internal moments and variance are calculated in double precision. Variance is
|
||||
private and stays in double precision through the square root; the cached mean
|
||||
and on-demand standard deviation are returned in the specified type. Negative
|
||||
variance caused by floating-point roundoff is clamped to zero.
|
||||
|
||||
Factory
|
||||
-------
|
||||
|
||||
@@ -1,30 +1,57 @@
|
||||
Pedestal
|
||||
========
|
||||
|
||||
``Pedestal`` calculates a running mean and variance for each pixel in a series
|
||||
of ``uint16`` frames. ``push()`` updates the cached mean immediately. For
|
||||
faster batch initialization, use ``push_no_update()`` for each frame and call
|
||||
``update_mean()`` after the batch.
|
||||
``Pedestal`` calculates a running mean and population standard deviation for
|
||||
each pixel in a series of ``uint16`` frames. ``push()`` updates the cached mean
|
||||
immediately; ``std()`` calculates the noise from the current statistics.
|
||||
|
||||
Three specializations are available from :mod:`aare`:
|
||||
``push()`` and ``push_with_threshold()`` require C-contiguous, two-dimensional
|
||||
NumPy frames with dtype ``uint16`` and shape matching the pedestal.
|
||||
``push_with_threshold()`` also requires a C-contiguous, two-dimensional
|
||||
threshold array with the pedestal's output dtype and shape. Noncontiguous
|
||||
inputs raise ``TypeError``; inputs with the wrong number of dimensions raise
|
||||
``ValueError``. Mismatched frame or threshold shapes raise ``RuntimeError``.
|
||||
Use ``numpy.ascontiguousarray()`` to copy a sliced or transposed array into the
|
||||
required layout when needed.
|
||||
|
||||
* ``Pedestal_d`` uses ``float64`` storage
|
||||
* ``Pedestal_f`` uses ``float32`` storage
|
||||
* ``Pedestal_i16`` uses ``int16`` storage
|
||||
Internal sums and sums of squares always use ``float64``. Three
|
||||
specializations are available from :mod:`aare` for the mean and standard
|
||||
deviation output types:
|
||||
|
||||
* ``Pedestal_d`` returns ``float64``
|
||||
* ``Pedestal_f`` returns ``float32``
|
||||
* ``Pedestal_i16`` returns ``int16``
|
||||
|
||||
The public ``Pedestal`` factory selects the specialization from ``dtype``,
|
||||
defaulting to ``numpy.float64``.
|
||||
|
||||
Constructor dimensions and ``n_samples`` must be positive integers. Negative
|
||||
values raise ``TypeError`` and zero values raise ``RuntimeError``.
|
||||
Internally, negative variance caused by floating-point roundoff is clamped to
|
||||
zero before taking its square root, keeping the standard deviation finite for
|
||||
nearly constant inputs. Only the final standard deviation is converted to the
|
||||
output dtype.
|
||||
|
||||
Factory
|
||||
-------
|
||||
|
||||
.. py:currentmodule:: aare
|
||||
|
||||
.. autofunction:: Pedestal
|
||||
|
||||
Example
|
||||
-------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from aare import Pedestal_d
|
||||
import numpy as np
|
||||
from aare import Pedestal
|
||||
|
||||
pedestal = Pedestal_d(512, 1024, 100)
|
||||
pedestal = Pedestal(512, 1024, n_samples=100, dtype=np.float32)
|
||||
|
||||
for frame in initialization_frames:
|
||||
pedestal.push_no_update(frame)
|
||||
pedestal.push(frame)
|
||||
|
||||
pedestal.update_mean()
|
||||
mean = pedestal.mean()
|
||||
noise = pedestal.std()
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ class ArrayAdd : public ArrayExpr<ArrayAdd<A, B, Ndim>, Ndim> {
|
||||
ArrayAdd(const A &arr1, const B &arr2) : arr1_(arr1), arr2_(arr2) {
|
||||
assert(arr1.size() == arr2.size());
|
||||
}
|
||||
auto operator[](int i) const { return arr1_[i] + arr2_[i]; }
|
||||
auto operator[](size_t i) const { return arr1_[i] + arr2_[i]; }
|
||||
size_t size() const { return arr1_.size(); }
|
||||
std::array<ssize_t, Ndim> shape() const { return arr1_.shape(); }
|
||||
};
|
||||
@@ -43,7 +43,7 @@ class ArraySub : public ArrayExpr<ArraySub<A, B, Ndim>, Ndim> {
|
||||
ArraySub(const A &arr1, const B &arr2) : arr1_(arr1), arr2_(arr2) {
|
||||
assert(arr1.size() == arr2.size());
|
||||
}
|
||||
auto operator[](int i) const { return arr1_[i] - arr2_[i]; }
|
||||
auto operator[](size_t i) const { return arr1_[i] - arr2_[i]; }
|
||||
size_t size() const { return arr1_.size(); }
|
||||
std::array<ssize_t, Ndim> shape() const { return arr1_.shape(); }
|
||||
};
|
||||
@@ -57,7 +57,7 @@ class ArrayMul : public ArrayExpr<ArrayMul<A, B, Ndim>, Ndim> {
|
||||
ArrayMul(const A &arr1, const B &arr2) : arr1_(arr1), arr2_(arr2) {
|
||||
assert(arr1.size() == arr2.size());
|
||||
}
|
||||
auto operator[](int i) const { return arr1_[i] * arr2_[i]; }
|
||||
auto operator[](size_t i) const { return arr1_[i] * arr2_[i]; }
|
||||
size_t size() const { return arr1_.size(); }
|
||||
std::array<ssize_t, Ndim> shape() const { return arr1_.shape(); }
|
||||
};
|
||||
@@ -71,7 +71,7 @@ class ArrayDiv : public ArrayExpr<ArrayDiv<A, B, Ndim>, Ndim> {
|
||||
ArrayDiv(const A &arr1, const B &arr2) : arr1_(arr1), arr2_(arr2) {
|
||||
assert(arr1.size() == arr2.size());
|
||||
}
|
||||
auto operator[](int i) const { return arr1_[i] / arr2_[i]; }
|
||||
auto operator[](size_t i) const { return arr1_[i] / arr2_[i]; }
|
||||
size_t size() const { return arr1_.size(); }
|
||||
std::array<ssize_t, Ndim> shape() const { return arr1_.shape(); }
|
||||
};
|
||||
|
||||
+23
-12
@@ -52,9 +52,9 @@ struct Cluster {
|
||||
|
||||
// TODO: handle 1 dimensional clusters
|
||||
/**
|
||||
* @brief sum of 2x2 subcluster with highest energy
|
||||
* @return photon energy of subcluster, 2x2 subcluster index relative to
|
||||
* cluster center
|
||||
* @brief Find the highest-sum center-adjacent 2x2 subcluster.
|
||||
* @return Sum and corner index of the selected 2x2 subcluster relative to
|
||||
* the cluster center
|
||||
*/
|
||||
Sum_index_pair<T, corner> max_sum_2x2() const {
|
||||
|
||||
@@ -117,13 +117,10 @@ struct Cluster {
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Reduce a cluster to a 2x2 cluster by selecting the 2x2 block with the
|
||||
* highest sum.
|
||||
* @brief Reduce a cluster to its highest-sum center-adjacent 2x2 block.
|
||||
* @param c Cluster to reduce
|
||||
* @return reduced cluster
|
||||
* @return Reduced cluster with the input coordinates
|
||||
* @note The cluster is filled using row major ordering starting at the top-left
|
||||
* (thus for a max subcluster in the top left cornern the photon hit is at
|
||||
* the fourth position)
|
||||
*/
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
@@ -194,17 +191,21 @@ Cluster<T, 2, 2, uint16_t> reduce_to_2x2(const Cluster<T, 3, 3, uint16_t> &c) {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reduce a cluster to a 3x3 cluster
|
||||
* @brief Reduce a cluster to the 3x3 block around its center index.
|
||||
* @param c Cluster to reduce
|
||||
* @return reduced cluster
|
||||
* @pre ClusterSizeX and ClusterSizeY must both be at least 3, and at least one
|
||||
* must be greater than 3.
|
||||
* @return Reduced cluster with the input coordinates are preserved.
|
||||
*/
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType = int16_t>
|
||||
Cluster<T, 3, 3, CoordType>
|
||||
reduce_to_3x3(const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &c) {
|
||||
|
||||
static_assert(ClusterSizeX >= 3 && ClusterSizeY >= 3,
|
||||
"Cluster sizes must be at least 3x3 for reduction to 3x3");
|
||||
static_assert(ClusterSizeX >= 3 && ClusterSizeY >= 3 &&
|
||||
(ClusterSizeX > 3 || ClusterSizeY > 3),
|
||||
"Cluster sizes must both be at least 3, and at least one "
|
||||
"must be greater than 3 for reduction to 3x3");
|
||||
|
||||
Cluster<T, 3, 3, CoordType> result{};
|
||||
|
||||
@@ -236,4 +237,14 @@ struct is_cluster<Cluster<T, X, Y, CoordType>> : std::true_type {}; // Cluster
|
||||
|
||||
template <typename T> constexpr bool is_cluster_v = is_cluster<T>::value;
|
||||
|
||||
/// True when both cluster dimensions exceed 2. The fixed-window finders
|
||||
/// (CPU and CUDA) require it; lives here so the CUDA kernel header can use it
|
||||
/// without pulling in ClusterFinder.hpp.
|
||||
template <typename ClusterType,
|
||||
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
|
||||
struct no_2x2_cluster {
|
||||
constexpr static bool value =
|
||||
ClusterType::cluster_size_x > 2 && ClusterType::cluster_size_y > 2;
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
+306
-181
@@ -3,46 +3,39 @@
|
||||
|
||||
#include "aare/Cluster.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/FilePtr.hpp"
|
||||
#include "aare/GainMap.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
#include "aare/ROI.hpp"
|
||||
#include "aare/logger.hpp"
|
||||
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <utility>
|
||||
|
||||
namespace aare {
|
||||
|
||||
/*
|
||||
Binary cluster file. Expects data to be laid out as:
|
||||
int32_t frame_number
|
||||
uint32_t number_of_clusters
|
||||
int16_t x, int16_t y, int32_t data[9] x number_of_clusters
|
||||
int32_t frame_number
|
||||
uint32_t number_of_clusters
|
||||
....
|
||||
*/
|
||||
|
||||
// TODO: change to support any type of clusters, e.g. header line with
|
||||
// clsuter_size_x, cluster_size_y,
|
||||
/**
|
||||
* @brief Class to read and write cluster files
|
||||
* Expects data to be laid out as:
|
||||
* @brief Read and write legacy binary cluster files.
|
||||
*
|
||||
* Each frame is stored as:
|
||||
*
|
||||
* int32_t frame_number
|
||||
* uint32_t number_of_clusters
|
||||
* int16_t x, int16_t y, int32_t data[9] * number_of_clusters
|
||||
* int32_t frame_number
|
||||
* uint32_t number_of_clusters
|
||||
* etc.
|
||||
* ClusterType clusters[number_of_clusters]
|
||||
*
|
||||
* The format stores clusters as their native in-memory representation and has
|
||||
* no metadata describing the cluster dimensions, value type, coordinate type,
|
||||
* padding, or byte order. Readers must therefore use the same ClusterType and
|
||||
* a compatible platform ABI as the writer.
|
||||
*/
|
||||
template <typename ClusterType,
|
||||
typename Enable = std::enable_if_t<is_cluster_v<ClusterType>>>
|
||||
class ClusterFile {
|
||||
FILE *fp{};
|
||||
const std::string m_filename{};
|
||||
FilePtr m_fp;
|
||||
std::string m_filename{};
|
||||
uint32_t m_num_left{}; /*Number of photons left in frame*/
|
||||
size_t m_chunk_size{}; /*Number of clusters to read at a time*/
|
||||
std::string m_mode; /*Mode to open the file in*/
|
||||
@@ -54,48 +47,150 @@ class ClusterFile {
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Construct a new Cluster File object
|
||||
* @param fname path to the file
|
||||
* @param chunk_size number of clusters to read at a time when iterating
|
||||
* over the file
|
||||
* @param mode mode to open the file in. "r" for reading, "w" for writing,
|
||||
* "a" for appending
|
||||
* @throws std::runtime_error if the file could not be opened
|
||||
* @brief Single-pass range over frames or chunks of selected clusters.
|
||||
*
|
||||
* The range borrows the file and shares its current position with all
|
||||
* other reads. Use only one traversal at a time. The file must outlive the
|
||||
* range and its iterators and must not be moved while they are in use.
|
||||
* Constructing a range does not read; begin() reads the first result.
|
||||
* Calling begin() again starts at the file's then-current position.
|
||||
*/
|
||||
template <bool ByFrame> class ReadRange {
|
||||
ClusterFile *m_file;
|
||||
size_t m_chunk_size;
|
||||
|
||||
friend class ClusterFile;
|
||||
ReadRange(ClusterFile &file, size_t chunk_size)
|
||||
: m_file(&file), m_chunk_size(chunk_size) {}
|
||||
|
||||
public:
|
||||
struct Sentinel {};
|
||||
|
||||
/**
|
||||
* @brief Move-only iterator for C++17 range-based loops.
|
||||
*
|
||||
* References to the current vector are valid until the iterator is
|
||||
* advanced or destroyed. Move the vector out to retain its storage.
|
||||
* Frame iteration reuses storage when the vector is not moved out.
|
||||
* This is not a copyable STL input iterator.
|
||||
*/
|
||||
class Iterator {
|
||||
ClusterFile *m_file;
|
||||
size_t m_chunk_size;
|
||||
ClusterVector<ClusterType> m_clusters{0};
|
||||
|
||||
friend class ReadRange;
|
||||
Iterator(ClusterFile &file, size_t chunk_size)
|
||||
: m_file(&file), m_chunk_size(chunk_size) {
|
||||
++*this;
|
||||
}
|
||||
|
||||
public:
|
||||
using value_type = ClusterVector<ClusterType>;
|
||||
|
||||
Iterator(const Iterator &) = delete;
|
||||
Iterator &operator=(const Iterator &) = delete;
|
||||
Iterator(Iterator &&) noexcept = default;
|
||||
Iterator &operator=(Iterator &&) noexcept = default;
|
||||
~Iterator() = default;
|
||||
|
||||
value_type &operator*() { return m_clusters; }
|
||||
value_type *operator->() { return &m_clusters; }
|
||||
|
||||
Iterator &operator++() {
|
||||
if (m_file) {
|
||||
if constexpr (ByFrame) {
|
||||
if (!m_file->read_frame(m_clusters)) {
|
||||
m_file = nullptr;
|
||||
}
|
||||
} else {
|
||||
m_clusters = m_file->read_clusters(m_chunk_size);
|
||||
if (m_clusters.empty()) {
|
||||
m_file = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
void operator++(int) { ++*this; }
|
||||
|
||||
friend bool operator==(const Iterator &it, Sentinel /*end*/) {
|
||||
return it.m_file == nullptr;
|
||||
}
|
||||
friend bool operator!=(const Iterator &it, Sentinel end) {
|
||||
return !(it == end);
|
||||
}
|
||||
friend bool operator==(Sentinel end, const Iterator &it) {
|
||||
return it == end;
|
||||
}
|
||||
friend bool operator!=(Sentinel end, const Iterator &it) {
|
||||
return !(it == end);
|
||||
}
|
||||
};
|
||||
|
||||
Iterator begin() const { return Iterator(*m_file, m_chunk_size); }
|
||||
Sentinel end() const { return {}; }
|
||||
};
|
||||
|
||||
using FrameRange = ReadRange<true>;
|
||||
using ChunkRange = ReadRange<false>;
|
||||
|
||||
/**
|
||||
* @brief Open a cluster file.
|
||||
* @param fname Path to the file.
|
||||
* @param chunk_size Maximum number of selected clusters per chunk step.
|
||||
* @param mode File mode: "r" to read, "w" to truncate and write, or "a"
|
||||
* to append.
|
||||
* @throws std::runtime_error If the mode is unsupported or the file cannot
|
||||
* be opened.
|
||||
*/
|
||||
ClusterFile(const std::filesystem::path &fname, size_t chunk_size = 1000,
|
||||
const std::string &mode = "r")
|
||||
|
||||
: m_filename(fname.string()), m_chunk_size(chunk_size), m_mode(mode) {
|
||||
|
||||
if (mode == "r") {
|
||||
fp = fopen(m_filename.c_str(), "rb");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for reading: " +
|
||||
m_filename);
|
||||
}
|
||||
} else if (mode == "w") {
|
||||
fp = fopen(m_filename.c_str(), "wb");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for writing: " +
|
||||
m_filename);
|
||||
}
|
||||
} else if (mode == "a") {
|
||||
fp = fopen(m_filename.c_str(), "ab");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for appending: " +
|
||||
m_filename);
|
||||
}
|
||||
} else {
|
||||
throw std::runtime_error("Unsupported mode: " + mode);
|
||||
}
|
||||
: m_filename(fname.string()), m_chunk_size(chunk_size) {
|
||||
open(mode);
|
||||
}
|
||||
|
||||
~ClusterFile() { close(); }
|
||||
/**
|
||||
* @brief Iterate over complete frames from the current file position.
|
||||
*
|
||||
* Empty and fully filtered frames are yielded with their stored frame
|
||||
* numbers. Reading stops only at a clean end of file. Advancing uses
|
||||
* read_frame(), including its error for a prior partial-frame read.
|
||||
*/
|
||||
FrameRange frames() & { return FrameRange(*this, 0); }
|
||||
FrameRange frames() && = delete;
|
||||
|
||||
/** @brief Iterate using the chunk size supplied to the constructor. */
|
||||
ChunkRange chunks() & { return chunks(m_chunk_size); }
|
||||
ChunkRange chunks() && = delete;
|
||||
|
||||
/**
|
||||
* @brief Read n_clusters clusters from the file discarding
|
||||
* frame numbers. If EOF is reached the returned vector will
|
||||
* have less than n_clusters clusters
|
||||
* @brief Iterate over chunks from the current file position.
|
||||
* @param chunk_size Maximum number of selected clusters per step.
|
||||
* @throws std::invalid_argument If chunk_size is zero.
|
||||
* @note Chunks can span frames; their frame numbers are not per-cluster
|
||||
* metadata. Advancing uses read_clusters() and propagates its errors.
|
||||
* Only the final chunk can be short. Empty chunks are not yielded.
|
||||
*/
|
||||
ChunkRange chunks(size_t chunk_size) & {
|
||||
if (chunk_size == 0) {
|
||||
throw std::invalid_argument("Chunk size must be greater than zero");
|
||||
}
|
||||
return ChunkRange(*this, chunk_size);
|
||||
}
|
||||
ChunkRange chunks(size_t) && = delete;
|
||||
|
||||
/**
|
||||
* @brief Read up to n_clusters without preserving frame boundaries.
|
||||
* @param n_clusters Maximum number of selected clusters to return.
|
||||
* @return A cluster vector that may contain fewer clusters at a clean end
|
||||
* of file.
|
||||
* @note The returned vector may combine data from several frames, so its
|
||||
* frame number must not be used as per-cluster metadata.
|
||||
* @throws std::runtime_error If the file is not open for reading, an I/O
|
||||
* error occurs, or an incomplete frame header or cluster record is read.
|
||||
*/
|
||||
ClusterVector<ClusterType> read_clusters(size_t n_clusters) {
|
||||
if (m_mode != "r") {
|
||||
@@ -109,76 +204,116 @@ class ClusterFile {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read a single frame from the file and return the
|
||||
* clusters. The cluster vector will have the frame number
|
||||
* set.
|
||||
* @throws std::runtime_error if the file is not opened for
|
||||
* reading or the file pointer not at the beginning of a
|
||||
* frame
|
||||
* @brief Read the next complete frame.
|
||||
* @return The selected clusters with the stored frame number set, or
|
||||
* std::nullopt at a clean end of file before the next frame.
|
||||
* @throws std::runtime_error If the file is not open for reading, a prior
|
||||
* partial-frame read left clusters unread, or the frame is incomplete.
|
||||
* @note A complete frame produces an engaged optional even when it contains
|
||||
* no clusters or all of its clusters are removed by the configured filters.
|
||||
*/
|
||||
ClusterVector<ClusterType> read_frame() {
|
||||
std::optional<ClusterVector<ClusterType>> read_frame() {
|
||||
ClusterVector<ClusterType> clusters(0);
|
||||
if (!read_frame(clusters)) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return std::optional<ClusterVector<ClusterType>>{std::move(clusters)};
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Read the next complete frame into an existing cluster vector.
|
||||
* @param clusters Destination whose storage is reused when large enough.
|
||||
* Existing clusters are replaced after a frame header is read and remain
|
||||
* unchanged at a clean end of file.
|
||||
* @return true when a complete frame was read, or false at a clean end of
|
||||
* file before the next frame.
|
||||
* @throws std::runtime_error If the file is not open for reading, a prior
|
||||
* partial-frame read left clusters unread, or a frame is incomplete.
|
||||
* @note A complete frame is a successful read even when it contains no
|
||||
* clusters or all of its clusters are removed by the configured filters.
|
||||
*/
|
||||
bool read_frame(ClusterVector<ClusterType> &clusters) {
|
||||
if (m_mode != "r") {
|
||||
throw std::runtime_error(LOCATION + "File not opened for reading");
|
||||
}
|
||||
if (m_noise_map || m_roi) {
|
||||
return read_frame_with_cut();
|
||||
} else {
|
||||
return read_frame_without_cut();
|
||||
if (m_num_left) {
|
||||
throw std::runtime_error(
|
||||
LOCATION + "There are still clusters left in the last frame");
|
||||
}
|
||||
|
||||
if (m_noise_map || m_roi) {
|
||||
return read_frame_with_cut(clusters);
|
||||
}
|
||||
return read_frame_without_cut(clusters);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Write one frame to the file.
|
||||
* @param clusters Clusters to write, including their frame number.
|
||||
* @throws std::runtime_error If the file is not open for writing or any
|
||||
* part of the frame cannot be written completely.
|
||||
*/
|
||||
void write_frame(const ClusterVector<ClusterType> &clusters) {
|
||||
if (m_mode != "w" && m_mode != "a") {
|
||||
throw std::runtime_error("File not opened for writing");
|
||||
}
|
||||
|
||||
int32_t frame_number = clusters.frame_number();
|
||||
fwrite(&frame_number, sizeof(frame_number), 1, fp);
|
||||
if (fwrite(&frame_number, sizeof(frame_number), 1, m_fp.get()) != 1) {
|
||||
throw std::runtime_error(LOCATION + "Could not write frame number");
|
||||
}
|
||||
|
||||
uint32_t n_clusters = clusters.size();
|
||||
fwrite(&n_clusters, sizeof(n_clusters), 1, fp);
|
||||
fwrite(clusters.data(), clusters.item_size(), clusters.size(), fp);
|
||||
if (fwrite(&n_clusters, sizeof(n_clusters), 1, m_fp.get()) != 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Could not write number of clusters");
|
||||
}
|
||||
|
||||
if (fwrite(clusters.data(), clusters.item_size(), clusters.size(),
|
||||
m_fp.get()) != clusters.size()) {
|
||||
throw std::runtime_error(LOCATION + "Could not write clusters");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return the chunk size
|
||||
* @brief Return the default number of selected clusters per chunk step.
|
||||
*/
|
||||
size_t chunk_size() const { return m_chunk_size; }
|
||||
|
||||
/**
|
||||
* @brief Estimate the number of clusters in the file from its size
|
||||
* @brief Estimate the number of clusters in the file from its size.
|
||||
*
|
||||
* Frame headers are included in the estimate, so the result may be slightly
|
||||
* larger than the actual number of clusters. The file position is not
|
||||
* changed.
|
||||
*
|
||||
* @throws std::runtime_error if the file is not opened for reading
|
||||
* Frame-header bytes are included in the estimate, so it may exceed the
|
||||
* actual number of clusters. The file position is not changed.
|
||||
*/
|
||||
size_t estimate_n_clusters() const {
|
||||
return std::filesystem::file_size(m_filename) / sizeof(ClusterType);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set the region of interest to use when reading
|
||||
* clusters. If set only clusters within the ROI will be
|
||||
* read.
|
||||
* @brief Select clusters by their center coordinate when reading.
|
||||
* @param roi Half-open region of interest: [xmin, xmax) x [ymin, ymax).
|
||||
*/
|
||||
void set_roi(ROI roi) { m_roi = roi; }
|
||||
|
||||
/**
|
||||
* @brief Set the noise map to use when reading clusters. If
|
||||
* set clusters below the noise level will be discarded.
|
||||
* Selection criteria one of: Central pixel above noise,
|
||||
* highest 2x2 sum above 2 * noise, total sum above 3 *
|
||||
* noise.
|
||||
* @brief Discard clusters that do not pass the noise thresholds.
|
||||
* @param noise_map Per-pixel noise indexed as [y, x]. The map is copied.
|
||||
* A cluster is retained only when its central pixel exceeds the local
|
||||
* noise, its highest 2x2 sum exceeds twice the noise, and its total sum
|
||||
* exceeds three times the noise.
|
||||
* @warning The map must cover every cluster center coordinate in the file.
|
||||
*/
|
||||
void set_noise_map(const NDView<int32_t, 2> noise_map) {
|
||||
m_noise_map = NDArray<int32_t, 2>(noise_map);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Set the gain map to use when reading clusters. If set the gain map
|
||||
* will be applied to the clusters that pass ROI and noise_map selection.
|
||||
* The gain map is expected to be in ADU/energy.
|
||||
* @brief Apply a gain map to clusters selected while reading.
|
||||
* @param gain_map Per-pixel gain in ADU/energy, indexed as [y, x]. The map
|
||||
* is copied and inverted internally.
|
||||
* @note Clusters whose complete footprint extends beyond the gain map are
|
||||
* retained with all cluster data values set to zero.
|
||||
*/
|
||||
void set_gain_map(const NDView<double, 2> gain_map) {
|
||||
m_gain_map = InvertedGainMap(gain_map);
|
||||
@@ -193,65 +328,53 @@ class ClusterFile {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Close the file. If not closed the file will be
|
||||
* closed in the destructor
|
||||
* @brief Close the file.
|
||||
*
|
||||
* Calling close more than once is safe. The destructor closes an open file
|
||||
* automatically.
|
||||
*/
|
||||
void close() {
|
||||
if (fp) {
|
||||
fclose(fp);
|
||||
fp = nullptr;
|
||||
}
|
||||
m_fp = FilePtr{};
|
||||
m_mode = "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return the current position in the file (bytes)
|
||||
* @brief Return the current byte position in the file.
|
||||
* @throws std::runtime_error If the file is closed or its position cannot
|
||||
* be determined.
|
||||
*/
|
||||
int64_t tell() {
|
||||
if (!fp) {
|
||||
if (!m_fp.get()) {
|
||||
throw std::runtime_error(LOCATION + "File not opened");
|
||||
}
|
||||
return ftell(fp);
|
||||
return m_fp.tell();
|
||||
}
|
||||
|
||||
private:
|
||||
/** @brief Open the file in specific mode
|
||||
*
|
||||
*/
|
||||
void open(const std::string &mode) {
|
||||
if (fp) {
|
||||
close();
|
||||
}
|
||||
close();
|
||||
|
||||
if (mode == "r") {
|
||||
fp = fopen(m_filename.c_str(), "rb");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for reading: " +
|
||||
m_filename);
|
||||
}
|
||||
m_fp = FilePtr(m_filename, "rb");
|
||||
m_mode = "r";
|
||||
} else if (mode == "w") {
|
||||
fp = fopen(m_filename.c_str(), "wb");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for writing: " +
|
||||
m_filename);
|
||||
}
|
||||
m_fp = FilePtr(m_filename, "wb");
|
||||
m_mode = "w";
|
||||
} else if (mode == "a") {
|
||||
fp = fopen(m_filename.c_str(), "ab");
|
||||
if (!fp) {
|
||||
throw std::runtime_error("Could not open file for appending: " +
|
||||
m_filename);
|
||||
}
|
||||
m_fp = FilePtr(m_filename, "ab");
|
||||
m_mode = "a";
|
||||
} else {
|
||||
throw std::runtime_error("Unsupported mode: " + mode);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ClusterVector<ClusterType> read_clusters_with_cut(size_t n_clusters);
|
||||
ClusterVector<ClusterType> read_clusters_without_cut(size_t n_clusters);
|
||||
ClusterVector<ClusterType> read_frame_with_cut();
|
||||
ClusterVector<ClusterType> read_frame_without_cut();
|
||||
bool read_frame_header(int32_t &frame_number, uint32_t &n_clusters);
|
||||
bool read_frame_with_cut(ClusterVector<ClusterType> &clusters);
|
||||
bool read_frame_without_cut(ClusterVector<ClusterType> &clusters);
|
||||
bool is_selected(ClusterType &cl);
|
||||
ClusterType read_one_cluster();
|
||||
};
|
||||
@@ -281,25 +404,31 @@ ClusterFile<ClusterType, Enable>::read_clusters_without_cut(size_t n_clusters) {
|
||||
} else {
|
||||
nn = nph;
|
||||
}
|
||||
nph_read += fread((buf + nph_read), clusters.item_size(), nn, fp);
|
||||
const auto count =
|
||||
fread((buf + nph_read), clusters.item_size(), nn, m_fp.get());
|
||||
if (count != nn) {
|
||||
throw std::runtime_error(LOCATION + "Could not read clusters");
|
||||
}
|
||||
nph_read += count;
|
||||
m_num_left = nph - nn; // write back the number of photons left
|
||||
}
|
||||
|
||||
if (nph_read < n_clusters) {
|
||||
// keep on reading frames and photons until reaching n_clusters
|
||||
while (fread(&iframe, sizeof(iframe), 1, fp)) {
|
||||
while (read_frame_header(iframe, nph)) {
|
||||
clusters.set_frame_number(iframe);
|
||||
// read number of clusters in frame
|
||||
if (fread(&nph, sizeof(nph), 1, fp)) {
|
||||
if (nph > (n_clusters - nph_read))
|
||||
nn = n_clusters - nph_read;
|
||||
else
|
||||
nn = nph;
|
||||
if (nph > (n_clusters - nph_read))
|
||||
nn = n_clusters - nph_read;
|
||||
else
|
||||
nn = nph;
|
||||
|
||||
nph_read +=
|
||||
fread((buf + nph_read), clusters.item_size(), nn, fp);
|
||||
m_num_left = nph - nn;
|
||||
const auto count =
|
||||
fread((buf + nph_read), clusters.item_size(), nn, m_fp.get());
|
||||
if (count != nn) {
|
||||
throw std::runtime_error(LOCATION + "Could not read clusters");
|
||||
}
|
||||
nph_read += count;
|
||||
m_num_left = nph - nn;
|
||||
if (nph_read >= n_clusters)
|
||||
break;
|
||||
}
|
||||
@@ -339,16 +468,15 @@ ClusterFile<ClusterType, Enable>::read_clusters_with_cut(size_t n_clusters) {
|
||||
}
|
||||
|
||||
int32_t frame_number = 0; // frame number needs to be 4 bytes!
|
||||
while (fread(&frame_number, sizeof(frame_number), 1, fp)) {
|
||||
if (fread(&m_num_left, sizeof(m_num_left), 1, fp)) {
|
||||
clusters.set_frame_number(
|
||||
frame_number); // cluster vector will hold the last
|
||||
// frame number
|
||||
while (m_num_left && clusters.size() < n_clusters) {
|
||||
ClusterType c = read_one_cluster();
|
||||
if (is_selected(c)) {
|
||||
clusters.push_back(c);
|
||||
}
|
||||
uint32_t n_clusters_in_frame = 0;
|
||||
while (read_frame_header(frame_number, n_clusters_in_frame)) {
|
||||
m_num_left = n_clusters_in_frame;
|
||||
clusters.set_frame_number(
|
||||
frame_number); // cluster vector will hold the last frame number
|
||||
while (m_num_left && clusters.size() < n_clusters) {
|
||||
ClusterType c = read_one_cluster();
|
||||
if (is_selected(c)) {
|
||||
clusters.push_back(c);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -366,7 +494,7 @@ ClusterFile<ClusterType, Enable>::read_clusters_with_cut(size_t n_clusters) {
|
||||
template <typename ClusterType, typename Enable>
|
||||
ClusterType ClusterFile<ClusterType, Enable>::read_one_cluster() {
|
||||
ClusterType c;
|
||||
auto rc = fread(&c, sizeof(c), 1, fp);
|
||||
auto rc = fread(&c, sizeof(c), 1, m_fp.get());
|
||||
if (rc != 1) {
|
||||
throw std::runtime_error(LOCATION + "Could not read cluster");
|
||||
}
|
||||
@@ -375,73 +503,70 @@ ClusterType ClusterFile<ClusterType, Enable>::read_one_cluster() {
|
||||
}
|
||||
|
||||
template <typename ClusterType, typename Enable>
|
||||
ClusterVector<ClusterType>
|
||||
ClusterFile<ClusterType, Enable>::read_frame_without_cut() {
|
||||
if (m_mode != "r") {
|
||||
throw std::runtime_error(LOCATION + "File not opened for reading");
|
||||
bool ClusterFile<ClusterType, Enable>::read_frame_header(int32_t &frame_number,
|
||||
uint32_t &n_clusters) {
|
||||
const auto frame_number_bytes =
|
||||
fread(&frame_number, 1, sizeof(frame_number), m_fp.get());
|
||||
if (frame_number_bytes == 0 && feof(m_fp.get()) && !ferror(m_fp.get())) {
|
||||
return false;
|
||||
}
|
||||
if (m_num_left) {
|
||||
throw std::runtime_error(
|
||||
LOCATION + "There are still photons left in the last frame");
|
||||
}
|
||||
int32_t frame_number;
|
||||
if (fread(&frame_number, sizeof(frame_number), 1, fp) != 1) {
|
||||
if (feof(fp))
|
||||
throw std::runtime_error(LOCATION + "Unexpected end of file");
|
||||
else if (ferror(fp))
|
||||
if (frame_number_bytes != sizeof(frame_number)) {
|
||||
if (ferror(m_fp.get())) {
|
||||
throw std::runtime_error(LOCATION + "Error reading from file");
|
||||
|
||||
throw std::runtime_error(
|
||||
LOCATION +
|
||||
"Unexpected error (not feof or ferror) when reading frame number");
|
||||
}
|
||||
throw std::runtime_error(LOCATION + "Incomplete frame number");
|
||||
}
|
||||
|
||||
const auto cluster_count_bytes =
|
||||
fread(&n_clusters, 1, sizeof(n_clusters), m_fp.get());
|
||||
if (cluster_count_bytes != sizeof(n_clusters)) {
|
||||
if (ferror(m_fp.get())) {
|
||||
throw std::runtime_error(LOCATION + "Error reading from file");
|
||||
}
|
||||
throw std::runtime_error(LOCATION + "Incomplete number of clusters");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename ClusterType, typename Enable>
|
||||
bool ClusterFile<ClusterType, Enable>::read_frame_without_cut(
|
||||
ClusterVector<ClusterType> &clusters) {
|
||||
int32_t frame_number;
|
||||
uint32_t n_clusters;
|
||||
if (fread(&n_clusters, sizeof(n_clusters), 1, fp) != 1) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"Could not read number of clusters");
|
||||
if (!read_frame_header(frame_number, n_clusters)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LOG(logDEBUG1) << "Reading " << n_clusters << " clusters from frame "
|
||||
<< frame_number;
|
||||
|
||||
ClusterVector<ClusterType> clusters(n_clusters);
|
||||
clusters.set_frame_number(frame_number);
|
||||
clusters.resize(n_clusters);
|
||||
|
||||
LOG(logDEBUG1) << "clusters.item_size(): " << clusters.item_size();
|
||||
|
||||
if (fread(clusters.data(), clusters.item_size(), n_clusters, fp) !=
|
||||
if (fread(clusters.data(), clusters.item_size(), n_clusters, m_fp.get()) !=
|
||||
static_cast<size_t>(n_clusters)) {
|
||||
throw std::runtime_error(LOCATION + "Could not read clusters");
|
||||
}
|
||||
|
||||
if (m_gain_map)
|
||||
m_gain_map->apply_gain_map(clusters);
|
||||
return clusters;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename ClusterType, typename Enable>
|
||||
ClusterVector<ClusterType>
|
||||
ClusterFile<ClusterType, Enable>::read_frame_with_cut() {
|
||||
if (m_mode != "r") {
|
||||
throw std::runtime_error("File not opened for reading");
|
||||
}
|
||||
if (m_num_left) {
|
||||
throw std::runtime_error(
|
||||
"There are still photons left in the last frame");
|
||||
}
|
||||
bool ClusterFile<ClusterType, Enable>::read_frame_with_cut(
|
||||
ClusterVector<ClusterType> &clusters) {
|
||||
int32_t frame_number;
|
||||
if (fread(&frame_number, sizeof(frame_number), 1, fp) != 1) {
|
||||
throw std::runtime_error("Could not read frame number");
|
||||
uint32_t n_clusters;
|
||||
if (!read_frame_header(frame_number, n_clusters)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (fread(&m_num_left, sizeof(m_num_left), 1, fp) != 1) {
|
||||
throw std::runtime_error("Could not read number of clusters");
|
||||
}
|
||||
|
||||
ClusterVector<ClusterType> clusters;
|
||||
clusters.reserve(m_num_left);
|
||||
m_num_left = n_clusters;
|
||||
clusters.resize(0);
|
||||
clusters.reserve(n_clusters);
|
||||
clusters.set_frame_number(frame_number);
|
||||
while (m_num_left) {
|
||||
ClusterType c = read_one_cluster();
|
||||
@@ -451,7 +576,7 @@ ClusterFile<ClusterType, Enable>::read_frame_with_cut() {
|
||||
}
|
||||
if (m_gain_map)
|
||||
m_gain_map->apply_gain_map(clusters);
|
||||
return clusters;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename ClusterType, typename Enable>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp" // no_2x2_cluster
|
||||
#include "aare/ClusterFile.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/Dtype.hpp"
|
||||
@@ -12,13 +13,6 @@
|
||||
|
||||
namespace aare {
|
||||
|
||||
template <typename ClusterType,
|
||||
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
|
||||
struct no_2x2_cluster {
|
||||
constexpr static bool value =
|
||||
ClusterType::cluster_size_x > 2 && ClusterType::cluster_size_y > 2;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Find fixed-size photon clusters using a per-pixel pedestal and noise
|
||||
* threshold.
|
||||
@@ -50,18 +44,21 @@ class ClusterFinder {
|
||||
* @param image_size Image shape as (rows, columns).
|
||||
* @param nSigma Per-pixel noise threshold multiplier.
|
||||
* @param capacity Initial cluster-vector capacity.
|
||||
* @param min_pedestal_samples Minimum number of pedestal frames to
|
||||
* accumulate to get reasonable statistics
|
||||
*/
|
||||
ClusterFinder(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 1000000)
|
||||
size_t capacity = 1000000, size_t min_pedestal_samples = 1000)
|
||||
: m_image_size(image_size), m_nSigma(nSigma),
|
||||
c2(sqrt((ClusterSizeY + 1) / 2 * (ClusterSizeX + 1) / 2)),
|
||||
c3(sqrt(ClusterSizeX * ClusterSizeY)),
|
||||
m_pedestal(image_size[0], image_size[1]), m_clusters(capacity),
|
||||
m_threshold({image_size[0], image_size[1]}, 0),
|
||||
m_pedestal(image_size[0], image_size[1], min_pedestal_samples),
|
||||
m_clusters(capacity), m_threshold({image_size[0], image_size[1]}, 0),
|
||||
m_pd_corrected_frame({image_size[0], image_size[1]}, 0) {
|
||||
LOG(logDEBUG) << "ClusterFinder: "
|
||||
<< "image_size: " << image_size[0] << "x" << image_size[1]
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity;
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity
|
||||
<< ", min_pedestal_samples: " << min_pedestal_samples;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
+167
-353
@@ -1,7 +1,8 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
#include "aare/clusterfinder_kernel.cuh"
|
||||
#include "aare/RAII_device.hpp"
|
||||
#include "aare/clusterfinder_algo.cuh"
|
||||
#include "aare/utils/cuda_check.cuh"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
@@ -9,40 +10,90 @@
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <limits>
|
||||
#include <memory>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace aare {
|
||||
|
||||
// Per-stream device resources (device-side only; all pinned host staging is
|
||||
// class-level)
|
||||
template <typename ClusterType, typename FRAME_TYPE, typename PEDESTAL_TYPE>
|
||||
struct StreamContext {
|
||||
cudaStream_t stream = nullptr;
|
||||
FRAME_TYPE *d_frame = nullptr;
|
||||
// Device pedestal precision is set by DEVICE_PED_TYPE in the kernel header.
|
||||
// Accumulators hold CENTERED moments of Y = X - d_pd_off (see kernel):
|
||||
// d_pd_sum ~ n*E[Y], d_pd_sum2 ~ n*E[Y^2], d_pd_mean = full mean
|
||||
// (X0+E[Y]).
|
||||
device::DEVICE_PED_TYPE *d_pd_mean = nullptr;
|
||||
device::DEVICE_PED_TYPE *d_pd_sum = nullptr;
|
||||
device::DEVICE_PED_TYPE *d_pd_sum2 = nullptr;
|
||||
device::DEVICE_PED_TYPE *d_pd_off = nullptr; // frozen per-pixel baseline X0
|
||||
uint8_t *d_output = nullptr; // [uint32_t count | ClusterType clusters[max]]
|
||||
/**
|
||||
* @brief One stream's device resources, owned.
|
||||
*
|
||||
* Four RAII members and nothing else: constructed means allocated, destroyed
|
||||
* means freed, and no cuda* call appears in this class. What a stream needs is
|
||||
* delegated to the policies — Algo::pedestal::Buffers for the pedestal arrays,
|
||||
* Algo::Output for the block one frame writes — so adding an algorithm never
|
||||
* touches this class.
|
||||
*
|
||||
* m_stream is declared LAST and so destroyed FIRST: its deleter synchronises
|
||||
* before any buffer below it is freed. That ordering is the whole destructor.
|
||||
*
|
||||
* Non-copyable and non-movable so a mis-written move can never double-free.
|
||||
* The driver holds contexts through unique_ptr.
|
||||
*/
|
||||
template <typename Algo> class StreamContext {
|
||||
using FrameType = typename Algo::frame_type;
|
||||
using Ped = typename Algo::pedestal;
|
||||
|
||||
DeviceBuffer<FrameType> m_frame;
|
||||
typename Ped::Buffers m_ped;
|
||||
typename Algo::Output m_output;
|
||||
Stream m_stream;
|
||||
|
||||
public:
|
||||
StreamContext(size_t n_pixels, uint32_t max_clusters_per_frame)
|
||||
: m_frame(n_pixels), m_ped(Ped::allocate(n_pixels)),
|
||||
m_output(Algo::Output::allocate(max_clusters_per_frame)),
|
||||
m_stream(make_stream()) {}
|
||||
|
||||
StreamContext(const StreamContext &) = delete;
|
||||
StreamContext &operator=(const StreamContext &) = delete;
|
||||
StreamContext(StreamContext &&) = delete;
|
||||
StreamContext &operator=(StreamContext &&) = delete;
|
||||
|
||||
cudaStream_t stream() const { return m_stream.get(); }
|
||||
FrameType *frame() const { return m_frame.get(); }
|
||||
const typename Algo::Output &output() const { return m_output; }
|
||||
const typename Ped::Buffers &pedestal() const { return m_ped; }
|
||||
|
||||
/// The pointer bundle Algo::launch consumes. Built on the fly, never
|
||||
/// stored, so it cannot outlive the buffers it points into.
|
||||
typename Ped::View pedestal_view() const { return Ped::make_view(m_ped); }
|
||||
};
|
||||
|
||||
template <typename ClusterType = Cluster<int32_t, 3, 3>,
|
||||
typename FRAME_TYPE = uint16_t, typename PEDESTAL_TYPE = double,
|
||||
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
|
||||
/**
|
||||
* @brief GPU cluster-finding driver: streams, batching, host staging.
|
||||
*
|
||||
* Everything that depends on WHICH kernel runs lives in Algo and its pedestal
|
||||
* model Algo::pedestal (see clusterfinder_algo.cuh): the device buffers a
|
||||
* stream needs, how the host pedestal is turned into them and read back, the
|
||||
* layout of one frame's output, and the launch itself. This class owns the
|
||||
* pipeline around that and never names a kernel: N streams
|
||||
* each with a StreamContext, two pinned ping-pong output slots, batch-done
|
||||
* events, and the chunked submit-before-collect loop that keeps the GPU busy
|
||||
* while the host marshals results.
|
||||
*
|
||||
* @tparam Algo e.g. cuda::FixedWindow<Cluster<int32_t, 3, 3>>
|
||||
* @tparam PEDESTAL_TYPE host-side pedestal precision
|
||||
*/
|
||||
template <typename Algo, typename PEDESTAL_TYPE = double>
|
||||
class ClusterFinderCUDA {
|
||||
public:
|
||||
using algorithm = Algo;
|
||||
using ClusterType = typename Algo::cluster_type;
|
||||
using FRAME_TYPE = typename Algo::frame_type;
|
||||
using Ped = typename Algo::pedestal;
|
||||
using Output = typename Algo::Output;
|
||||
|
||||
private:
|
||||
static_assert(no_2x2_cluster<ClusterType>::value,
|
||||
"ClusterFinderCUDA: both cluster dimensions must exceed 2");
|
||||
static_assert(cuda::contract::require_algo<Algo>::value,
|
||||
"ClusterFinderCUDA: Algo does not satisfy the contract in "
|
||||
"clusterfinder_algo.cuh");
|
||||
using COMPUTE_TYPE =
|
||||
device::COMPUTE_TYPE; // match the kernel's internal precision
|
||||
|
||||
static constexpr int BLOCK_X = 16;
|
||||
static constexpr int BLOCK_Y = 16;
|
||||
static constexpr int col_radius = ClusterType::cluster_size_x / 2;
|
||||
static constexpr int row_radius = ClusterType::cluster_size_y / 2;
|
||||
|
||||
// Two ping-pong output slots. At most 2 batches can be in flight at once:
|
||||
// the caller submits batch B before collecting batch A, so A and B occupy
|
||||
// separate slots. A third submit() without an intervening collect() throws.
|
||||
@@ -76,22 +127,18 @@ class ClusterFinderCUDA {
|
||||
int n_streams;
|
||||
size_t m_max_clusters_per_frame;
|
||||
|
||||
// Per-frame output layout helpers
|
||||
size_t m_output_bytes_per_frame; // sizeof(uint32_t) + max *
|
||||
// sizeof(ClusterType), aligned
|
||||
size_t m_clusters_offset; // offset of cluster array within output block
|
||||
// Cached copy of Output::bytes_per_frame(m_max_clusters_per_frame): the
|
||||
// device block size and the pinned host slot stride, which are the same
|
||||
// number. The layout itself belongs to Algo::Output.
|
||||
size_t m_output_bytes_per_frame;
|
||||
|
||||
COMPUTE_TYPE m_nSigma;
|
||||
Pedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
FastPedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
ClusterVector<ClusterType> m_clusters;
|
||||
bool m_pedestal_dirty = true;
|
||||
// Frozen per-pixel baseline X0 (~mean at t=0), captured once on the first
|
||||
// sync and reused so the centered device accumulators never need rebasing.
|
||||
// Cleared by clear_pedestal() to force re-capture on the next sync.
|
||||
std::vector<device::DEVICE_PED_TYPE> m_offset;
|
||||
|
||||
using SC = StreamContext<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>;
|
||||
std::vector<SC> v_sc;
|
||||
// One per stream. unique_ptr so the context can stay non-movable.
|
||||
std::vector<std::unique_ptr<StreamContext<Algo>>> v_sc;
|
||||
|
||||
float m_total_kernel_ms = 0.0f;
|
||||
size_t m_frames_processed = 0;
|
||||
@@ -117,11 +164,6 @@ class ClusterFinderCUDA {
|
||||
// finishes, even if the next batch is already queued in the same streams.
|
||||
std::vector<cudaEvent_t> m_batch_done[NUM_SLOTS];
|
||||
|
||||
// Kernel parameters
|
||||
dim3 grid;
|
||||
dim3 block;
|
||||
size_t shmem_bytes;
|
||||
|
||||
/// Copy every frame of a pinned output slot into results, turning the
|
||||
/// packed device layout into owned ClusterVectors. This is exactly the work
|
||||
/// collect_view() exists to avoid.
|
||||
@@ -140,16 +182,11 @@ class ClusterFinderCUDA {
|
||||
for (size_t frame_idx = 0; frame_idx < n_frames; ++frame_idx) {
|
||||
const void *h_out = static_cast<const char *>(slot_base) +
|
||||
frame_idx * m_output_bytes_per_frame;
|
||||
uint32_t n_found = *reinterpret_cast<const uint32_t *>(h_out);
|
||||
// The device counter increments past the cap (only the write is
|
||||
// guarded), so this clamp is an out-of-bounds guard, not a tuning
|
||||
// choice.
|
||||
n_found = std::min<uint32_t>(
|
||||
n_found, static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
const uint32_t n_found = Output::host_count(
|
||||
h_out, static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
|
||||
if (n_found > 0) {
|
||||
const auto *src = reinterpret_cast<const ClusterType *>(
|
||||
static_cast<const char *>(h_out) + m_clusters_offset);
|
||||
const ClusterType *src = Output::host_clusters(h_out);
|
||||
results[frame_idx].resize(n_found);
|
||||
std::memcpy(results[frame_idx].data(), src,
|
||||
n_found * sizeof(ClusterType));
|
||||
@@ -278,18 +315,16 @@ class ClusterFinderCUDA {
|
||||
const uint8_t *m_base = nullptr;
|
||||
size_t m_n_frames = 0;
|
||||
uint64_t m_first_frame = 0;
|
||||
size_t m_stride = 0; // bytes per frame in the pinned buffer
|
||||
size_t m_cl_offset = 0; // byte offset of the cluster array in a frame
|
||||
size_t m_stride = 0; // bytes per frame in the pinned buffer
|
||||
size_t m_max_clusters = 0;
|
||||
int m_slot = -1;
|
||||
|
||||
BatchView(ClusterFinderCUDA *owner, const void *base, size_t n_frames,
|
||||
uint64_t first_frame, size_t stride, size_t cl_offset,
|
||||
size_t max_clusters, int slot)
|
||||
uint64_t first_frame, size_t stride, size_t max_clusters,
|
||||
int slot)
|
||||
: m_owner(owner), m_base(static_cast<const uint8_t *>(base)),
|
||||
m_n_frames(n_frames), m_first_frame(first_frame),
|
||||
m_stride(stride), m_cl_offset(cl_offset),
|
||||
m_max_clusters(max_clusters), m_slot(slot) {}
|
||||
m_stride(stride), m_max_clusters(max_clusters), m_slot(slot) {}
|
||||
|
||||
public:
|
||||
BatchView() = default;
|
||||
@@ -321,17 +356,13 @@ class ClusterFinderCUDA {
|
||||
|
||||
uint32_t count(size_t i) const {
|
||||
check(i);
|
||||
uint32_t n =
|
||||
*reinterpret_cast<const uint32_t *>(m_base + i * m_stride);
|
||||
// The device counter increments past the cap (only the write is
|
||||
// guarded), so clamp: this is an out-of-bounds guard.
|
||||
return std::min<uint32_t>(n, static_cast<uint32_t>(m_max_clusters));
|
||||
return Output::host_count(m_base + i * m_stride,
|
||||
static_cast<uint32_t>(m_max_clusters));
|
||||
}
|
||||
|
||||
const ClusterType *clusters(size_t i) const {
|
||||
check(i);
|
||||
return reinterpret_cast<const ClusterType *>(m_base + i * m_stride +
|
||||
m_cl_offset);
|
||||
return Output::host_clusters(m_base + i * m_stride);
|
||||
}
|
||||
|
||||
size_t total_clusters() const {
|
||||
@@ -363,7 +394,6 @@ class ClusterFinderCUDA {
|
||||
m_n_frames = o.m_n_frames;
|
||||
m_first_frame = o.m_first_frame;
|
||||
m_stride = o.m_stride;
|
||||
m_cl_offset = o.m_cl_offset;
|
||||
m_max_clusters = o.m_max_clusters;
|
||||
m_slot = o.m_slot;
|
||||
o.m_owner = nullptr;
|
||||
@@ -390,6 +420,10 @@ class ClusterFinderCUDA {
|
||||
* fixed-size D2H
|
||||
* @param n_streams_ number of CUDA streams for multi-frame
|
||||
* overlap
|
||||
* @param min_pedestal_samples number of frames the host pedestal
|
||||
* accumulates before it is ready, and the reciprocal of the steady-state
|
||||
* update weight. Matches ClusterFinder so a CPU/GPU comparison warms up
|
||||
* identically.
|
||||
* @param time_kernels enable per-frame CUDA-event kernel
|
||||
* timing. Off by default: it adds two event records per frame to the
|
||||
* streams and one host-side query per frame, and the resulting number is
|
||||
@@ -397,12 +431,13 @@ class ClusterFinderCUDA {
|
||||
*/
|
||||
ClusterFinderCUDA(Shape<2> shape_, COMPUTE_TYPE nSigma = 5.0,
|
||||
size_t max_clusters_per_frame = 2048, int n_streams_ = 4,
|
||||
size_t min_pedestal_samples = 1000,
|
||||
bool time_kernels = false)
|
||||
: m_shape(shape_), nrows(shape_[0]), ncols(shape_[1]),
|
||||
m_image_size(nrows * ncols), n_streams(n_streams_),
|
||||
m_max_clusters_per_frame(max_clusters_per_frame), m_nSigma(nSigma),
|
||||
m_pedestal(shape_[0], shape_[1]), m_clusters(max_clusters_per_frame),
|
||||
m_time_kernels(time_kernels) {
|
||||
m_pedestal(shape_[0], shape_[1], min_pedestal_samples),
|
||||
m_clusters(max_clusters_per_frame), m_time_kernels(time_kernels) {
|
||||
if (n_streams_ <= 0) {
|
||||
throw std::invalid_argument(
|
||||
"ClusterFinderCUDA: n_streams must be > 0");
|
||||
@@ -420,46 +455,26 @@ class ClusterFinderCUDA {
|
||||
"ClusterFinderCUDA: max_clusters_per_frame must be > 0");
|
||||
}
|
||||
|
||||
// Grid/Block dimensions
|
||||
block = dim3(BLOCK_X, BLOCK_Y);
|
||||
grid = dim3((static_cast<unsigned int>(ncols) + BLOCK_X - 1) / BLOCK_X,
|
||||
(static_cast<unsigned int>(nrows) + BLOCK_Y - 1) / BLOCK_Y);
|
||||
|
||||
// Shared memory: one tile of (BLOCK_X + 2*col_radius) x (BLOCK_Y +
|
||||
// 2*row_radius) elements
|
||||
// Mixed precision used -> shmem takes COMPUTE_TYPE = floats (not
|
||||
// PEDESTAL_TYPE)
|
||||
shmem_bytes = (BLOCK_X + 2 * col_radius) * (BLOCK_Y + 2 * row_radius) *
|
||||
sizeof(COMPUTE_TYPE);
|
||||
// The kernel indexes pixels with int32_t
|
||||
if (m_image_size >
|
||||
static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
|
||||
throw std::invalid_argument(
|
||||
"ClusterFinderCUDA: nrows * ncols must fit in int32_t");
|
||||
}
|
||||
|
||||
m_image_bytes = m_image_size * sizeof(FRAME_TYPE);
|
||||
|
||||
// Output block layout: [count][padding to ClusterType
|
||||
// alignment][clusters]
|
||||
constexpr size_t cluster_align = alignof(ClusterType);
|
||||
const size_t count_bytes = sizeof(uint32_t);
|
||||
// next multiple of cluster_align
|
||||
m_clusters_offset =
|
||||
(count_bytes + cluster_align - 1) & ~(cluster_align - 1);
|
||||
m_output_bytes_per_frame =
|
||||
m_clusters_offset + m_max_clusters_per_frame * sizeof(ClusterType);
|
||||
// The block layout is Algo::Output's; the driver only caches the
|
||||
// stride, which it needs to index pinned host slots.
|
||||
m_output_bytes_per_frame = Output::bytes_per_frame(
|
||||
static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
|
||||
v_sc.resize(n_streams);
|
||||
for (int k = 0; k < n_streams; ++k) {
|
||||
auto &sc = v_sc[k];
|
||||
CUDA_CHECK(
|
||||
cudaStreamCreateWithFlags(&sc.stream, cudaStreamNonBlocking));
|
||||
CUDA_CHECK(cudaMalloc(&sc.d_frame, m_image_bytes));
|
||||
CUDA_CHECK(cudaMalloc(
|
||||
&sc.d_pd_mean, m_image_size * sizeof(device::DEVICE_PED_TYPE)));
|
||||
CUDA_CHECK(cudaMalloc(
|
||||
&sc.d_pd_sum, m_image_size * sizeof(device::DEVICE_PED_TYPE)));
|
||||
CUDA_CHECK(cudaMalloc(
|
||||
&sc.d_pd_sum2, m_image_size * sizeof(device::DEVICE_PED_TYPE)));
|
||||
CUDA_CHECK(cudaMalloc(
|
||||
&sc.d_pd_off, m_image_size * sizeof(device::DEVICE_PED_TYPE)));
|
||||
CUDA_CHECK(cudaMalloc(&sc.d_output, m_output_bytes_per_frame));
|
||||
}
|
||||
// One RAII context per stream: stream handle, frame buffer, the
|
||||
// algorithm's pedestal arrays and the packed output block.
|
||||
v_sc.reserve(n_streams);
|
||||
for (int k = 0; k < n_streams; ++k)
|
||||
v_sc.push_back(std::make_unique<StreamContext<Algo>>(
|
||||
m_image_size, static_cast<uint32_t>(m_max_clusters_per_frame)));
|
||||
|
||||
for (int s = 0; s < NUM_SLOTS; ++s) {
|
||||
m_batch_done[s].resize(n_streams);
|
||||
@@ -470,24 +485,12 @@ class ClusterFinderCUDA {
|
||||
}
|
||||
|
||||
~ClusterFinderCUDA() {
|
||||
for (auto &sc : v_sc) {
|
||||
if (sc.stream)
|
||||
cudaStreamSynchronize(sc.stream);
|
||||
if (sc.d_frame)
|
||||
cudaFree(sc.d_frame);
|
||||
if (sc.d_pd_mean)
|
||||
cudaFree(sc.d_pd_mean);
|
||||
if (sc.d_pd_sum)
|
||||
cudaFree(sc.d_pd_sum);
|
||||
if (sc.d_pd_sum2)
|
||||
cudaFree(sc.d_pd_sum2);
|
||||
if (sc.d_pd_off)
|
||||
cudaFree(sc.d_pd_off);
|
||||
if (sc.d_output)
|
||||
cudaFree(sc.d_output);
|
||||
if (sc.stream)
|
||||
cudaStreamDestroy(sc.stream);
|
||||
}
|
||||
// Drain before freeing anything: an uncollected batch may still have
|
||||
// a D2H in flight into the pinned slots below. Members, and so the
|
||||
// stream contexts, are destroyed only after this body returns.
|
||||
for (auto &sc : v_sc)
|
||||
if (sc)
|
||||
cudaStreamSynchronize(sc->stream());
|
||||
|
||||
for (int s = 0; s < NUM_SLOTS; ++s) {
|
||||
for (auto e : m_kernel_start_pools[s])
|
||||
@@ -541,13 +544,18 @@ class ClusterFinderCUDA {
|
||||
}
|
||||
|
||||
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
|
||||
m_pedestal.push(frame);
|
||||
if (!m_pedestal.ready()) {
|
||||
m_pedestal.add_init_frame(frame);
|
||||
} else {
|
||||
m_pedestal.push_ema(frame);
|
||||
}
|
||||
m_pedestal_dirty = true;
|
||||
}
|
||||
|
||||
/// Drops the host pedestal. The device baseline follows on the next sync,
|
||||
/// which re-derives it from the (now empty) host mean.
|
||||
void clear_pedestal() {
|
||||
m_pedestal.clear();
|
||||
m_offset.clear(); // re-capture the baseline on the next sync
|
||||
m_pedestal_dirty = true;
|
||||
}
|
||||
|
||||
@@ -569,13 +577,9 @@ class ClusterFinderCUDA {
|
||||
sync_pedestal_to_device();
|
||||
m_pedestal_dirty = false;
|
||||
}
|
||||
auto &sc = v_sc.at(static_cast<size_t>(stream));
|
||||
CUDA_CHECK(cudaStreamSynchronize(sc.stream));
|
||||
using DPT = device::DEVICE_PED_TYPE;
|
||||
std::vector<DPT> h_mean(m_image_size);
|
||||
CUDA_CHECK(cudaMemcpy(h_mean.data(), sc.d_pd_mean,
|
||||
m_image_size * sizeof(DPT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
auto &sc = *v_sc.at(static_cast<size_t>(stream));
|
||||
std::vector<typename Ped::DevicePedT> h_mean;
|
||||
Ped::download_mean(sc.pedestal(), m_image_size, h_mean, sc.stream());
|
||||
NDArray<PEDESTAL_TYPE, 2> out(
|
||||
{static_cast<ssize_t>(nrows), static_cast<ssize_t>(ncols)});
|
||||
for (size_t i = 0; i < m_image_size; ++i)
|
||||
@@ -592,28 +596,15 @@ class ClusterFinderCUDA {
|
||||
sync_pedestal_to_device();
|
||||
m_pedestal_dirty = false;
|
||||
}
|
||||
auto &sc = v_sc.at(static_cast<size_t>(stream));
|
||||
CUDA_CHECK(cudaStreamSynchronize(sc.stream));
|
||||
using DPT = device::DEVICE_PED_TYPE;
|
||||
std::vector<DPT> h_mean(m_image_size), h_sum2(m_image_size);
|
||||
CUDA_CHECK(cudaMemcpy(h_mean.data(), sc.d_pd_mean,
|
||||
m_image_size * sizeof(DPT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
CUDA_CHECK(cudaMemcpy(h_sum2.data(), sc.d_pd_sum2,
|
||||
m_image_size * sizeof(DPT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
const double n = static_cast<double>(m_pedestal.n_samples());
|
||||
auto &sc = *v_sc.at(static_cast<size_t>(stream));
|
||||
std::vector<double> h_noise;
|
||||
Ped::download_noise(sc.pedestal(),
|
||||
static_cast<uint32_t>(m_pedestal.n_samples()),
|
||||
m_image_size, h_noise, sc.stream());
|
||||
NDArray<PEDESTAL_TYPE, 2> out(
|
||||
{static_cast<ssize_t>(nrows), static_cast<ssize_t>(ncols)});
|
||||
for (size_t i = 0; i < m_image_size; ++i) {
|
||||
// Accumulators are centered on X0 = m_offset[i], so the variance is
|
||||
// E[Y^2] - E[Y]^2 with E[Y] = mean - X0 (mirrors the kernel).
|
||||
double resid = static_cast<double>(h_mean[i]) -
|
||||
static_cast<double>(m_offset[i]);
|
||||
double var = static_cast<double>(h_sum2[i]) / n - resid * resid;
|
||||
out.data()[i] =
|
||||
static_cast<PEDESTAL_TYPE>(std::sqrt(std::max(var, 0.0)));
|
||||
}
|
||||
for (size_t i = 0; i < m_image_size; ++i)
|
||||
out.data()[i] = static_cast<PEDESTAL_TYPE>(h_noise[i]);
|
||||
return out;
|
||||
}
|
||||
|
||||
@@ -688,45 +679,39 @@ class ClusterFinderCUDA {
|
||||
m_next_slot = 1 - slot;
|
||||
|
||||
const size_t n_frames_batch = static_cast<size_t>(frames.shape(0));
|
||||
const uint32_t n_pd_samples =
|
||||
static_cast<uint32_t>(m_pedestal.n_samples());
|
||||
const typename Algo::LaunchParams launch_params{
|
||||
static_cast<int32_t>(nrows), static_cast<int32_t>(ncols), m_nSigma,
|
||||
static_cast<uint32_t>(m_max_clusters_per_frame)};
|
||||
const typename Ped::Params ped_params{
|
||||
static_cast<uint32_t>(m_pedestal.n_samples())};
|
||||
|
||||
grow_output_slot(slot, n_frames_batch);
|
||||
ensure_event_pool(slot, n_frames_batch);
|
||||
|
||||
// Launch all frames round-robin across streams
|
||||
for (size_t frame_idx = 0; frame_idx < n_frames_batch; ++frame_idx) {
|
||||
auto &sc = v_sc[frame_idx % n_streams];
|
||||
|
||||
auto &sc = *v_sc[frame_idx % n_streams];
|
||||
const FRAME_TYPE *h_src = frames.data() + frame_idx * m_image_size;
|
||||
auto *d_cluster_count = reinterpret_cast<uint32_t *>(sc.d_output);
|
||||
|
||||
CUDA_CHECK(cudaMemsetAsync(d_cluster_count, 0, sizeof(uint32_t),
|
||||
sc.stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.d_frame, h_src, m_image_bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream));
|
||||
CUDA_CHECK(cudaMemsetAsync(sc.output().count(), 0, sizeof(uint32_t),
|
||||
sc.stream()));
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.frame(), h_src, m_image_bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream()));
|
||||
|
||||
auto *d_clusters = reinterpret_cast<ClusterType *>(
|
||||
sc.d_output + m_clusters_offset);
|
||||
if (m_time_kernels)
|
||||
CUDA_CHECK(cudaEventRecord(
|
||||
m_kernel_start_pools[slot][frame_idx], sc.stream));
|
||||
device::find_clusters_in_single_frame<ClusterType, FRAME_TYPE>
|
||||
<<<grid, block, shmem_bytes, sc.stream>>>(
|
||||
sc.d_frame, sc.d_pd_mean, sc.d_pd_sum, sc.d_pd_sum2,
|
||||
sc.d_pd_off, n_pd_samples, m_nSigma, nrows, ncols,
|
||||
d_clusters, d_cluster_count,
|
||||
static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
m_kernel_start_pools[slot][frame_idx], sc.stream()));
|
||||
Algo::launch(launch_params, ped_params, sc.frame(),
|
||||
sc.pedestal_view(), sc.output(), sc.stream());
|
||||
if (m_time_kernels)
|
||||
CUDA_CHECK(cudaEventRecord(m_kernel_stop_pools[slot][frame_idx],
|
||||
sc.stream));
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
sc.stream()));
|
||||
|
||||
void *h_out = static_cast<char *>(h_output_slots[slot]) +
|
||||
frame_idx * m_output_bytes_per_frame;
|
||||
CUDA_CHECK(cudaMemcpyAsync(h_out, sc.d_output,
|
||||
CUDA_CHECK(cudaMemcpyAsync(h_out, sc.output().data(),
|
||||
m_output_bytes_per_frame,
|
||||
cudaMemcpyDeviceToHost, sc.stream));
|
||||
cudaMemcpyDeviceToHost, sc.stream()));
|
||||
}
|
||||
|
||||
// Record per-stream "batch done" events after all D2H for this batch.
|
||||
@@ -736,7 +721,8 @@ class ClusterFinderCUDA {
|
||||
const int streams_used =
|
||||
std::min<int>(n_streams, static_cast<int>(n_frames_batch));
|
||||
for (int k = 0; k < streams_used; ++k)
|
||||
CUDA_CHECK(cudaEventRecord(m_batch_done[slot][k], v_sc[k].stream));
|
||||
CUDA_CHECK(
|
||||
cudaEventRecord(m_batch_done[slot][k], v_sc[k]->stream()));
|
||||
|
||||
m_slot_n_frames[slot] = n_frames_batch;
|
||||
m_slot_first_frame[slot] = first_frame;
|
||||
@@ -777,29 +763,6 @@ class ClusterFinderCUDA {
|
||||
results.back().set_frame_number(first_frame + i);
|
||||
}
|
||||
|
||||
// for (size_t frame_idx = 0; frame_idx < n_frames_batch; ++frame_idx) {
|
||||
// const void *h_out =
|
||||
// static_cast<const char *>(h_output_slots[slot]) +
|
||||
// frame_idx * m_output_bytes_per_frame;
|
||||
// uint32_t n_found = *reinterpret_cast<const uint32_t *>(h_out);
|
||||
// n_found = std::min<uint32_t>(
|
||||
// n_found, static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
|
||||
// if (n_found > 0) {
|
||||
// const auto *src = reinterpret_cast<const ClusterType *>(
|
||||
// static_cast<const char *>(h_out) + m_clusters_offset);
|
||||
// results[frame_idx].resize(n_found);
|
||||
// std::memcpy(results[frame_idx].data(), src,
|
||||
// n_found * sizeof(ClusterType));
|
||||
// }
|
||||
|
||||
// float kernel_ms = 0.0f;
|
||||
// CUDA_CHECK(cudaEventElapsedTime(
|
||||
// &kernel_ms, m_kernel_start_pools[slot][frame_idx],
|
||||
// m_kernel_stop_pools[slot][frame_idx]));
|
||||
// m_total_kernel_ms += kernel_ms;
|
||||
// }
|
||||
|
||||
// materialize_slot() is the original copy loop verbatim, just hoisted
|
||||
// into a helper so find_clusters_batched() shares it;
|
||||
// accumulate_kernel_times is the m_time_kernels branch that used to
|
||||
@@ -828,8 +791,8 @@ class ClusterFinderCUDA {
|
||||
|
||||
m_slot_view_held[slot] = true;
|
||||
return BatchView(this, h_output_slots[slot], n_frames, first_frame,
|
||||
m_output_bytes_per_frame, m_clusters_offset,
|
||||
m_max_clusters_per_frame, slot);
|
||||
m_output_bytes_per_frame, m_max_clusters_per_frame,
|
||||
slot);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -892,116 +855,6 @@ class ClusterFinderCUDA {
|
||||
return results;
|
||||
}
|
||||
|
||||
// Previous implementation: one launch loop over the whole batch, one
|
||||
// cudaStreamSynchronize per stream, then one single-threaded copy loop over
|
||||
// every frame. Kept for reference — it is what the numbers in
|
||||
// docs/ClusterFinderCUDA_benchmark_results.md opt3/opt4 (Act I, sections
|
||||
// 5-6) were measured against.
|
||||
//
|
||||
// std::vector<ClusterVector<ClusterType>>
|
||||
// find_clusters_batched(NDView<FRAME_TYPE, 3> frames,
|
||||
// uint64_t first_frame = 0) {
|
||||
// if (m_pedestal_dirty) {
|
||||
// sync_pedestal_to_device();
|
||||
// m_pedestal_dirty = false;
|
||||
// }
|
||||
//
|
||||
// const size_t n_frames_batch =
|
||||
// static_cast<size_t>(frames.shape(0));
|
||||
// const uint32_t n_pd_samples =
|
||||
// static_cast<uint32_t>(m_pedestal.n_samples());
|
||||
//
|
||||
// // Lazy grow D2H output staging buffer (one slot per frame)
|
||||
// if (n_frames_batch > m_output_slot_capacity[0]) {
|
||||
// if (h_output_slots[0])
|
||||
// CUDA_CHECK(cudaFreeHost(h_output_slots[0]));
|
||||
// CUDA_CHECK(cudaMallocHost(&h_output_slots[0],
|
||||
// n_frames_batch *
|
||||
// m_output_bytes_per_frame));
|
||||
// m_output_slot_capacity[0] = n_frames_batch;
|
||||
// }
|
||||
//
|
||||
// ensure_event_pool(0, n_frames_batch);
|
||||
//
|
||||
// std::vector<ClusterVector<ClusterType>> results;
|
||||
// results.reserve(n_frames_batch);
|
||||
// for (size_t i = 0; i < n_frames_batch; ++i) {
|
||||
// results.emplace_back();
|
||||
// results.back().set_frame_number(first_frame + i);
|
||||
// }
|
||||
//
|
||||
// for (size_t frame_idx = 0; frame_idx < n_frames_batch;
|
||||
// ++frame_idx) {
|
||||
// auto &sc = v_sc[frame_idx % n_streams];
|
||||
//
|
||||
// const FRAME_TYPE *h_src =
|
||||
// frames.data() + frame_idx * m_image_size;
|
||||
// auto *d_cluster_count =
|
||||
// reinterpret_cast<uint32_t *>(sc.d_output);
|
||||
//
|
||||
// CUDA_CHECK(cudaMemsetAsync(d_cluster_count, 0,
|
||||
// sizeof(uint32_t), sc.stream));
|
||||
// CUDA_CHECK(cudaMemcpyAsync(sc.d_frame, h_src, m_image_bytes,
|
||||
// cudaMemcpyHostToDevice, sc.stream));
|
||||
//
|
||||
// auto *d_clusters = reinterpret_cast<ClusterType *>(
|
||||
// sc.d_output + m_clusters_offset);
|
||||
// if (m_time_kernels)
|
||||
// CUDA_CHECK(cudaEventRecord(
|
||||
// m_kernel_start_pools[0][frame_idx], sc.stream));
|
||||
// device::find_clusters_in_single_frame<ClusterType, FRAME_TYPE>
|
||||
// <<<grid, block, shmem_bytes, sc.stream>>>(
|
||||
// sc.d_frame, sc.d_pd_mean, sc.d_pd_sum, sc.d_pd_sum2,
|
||||
// sc.d_pd_off, n_pd_samples, m_nSigma, nrows, ncols,
|
||||
// d_clusters, d_cluster_count,
|
||||
// static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
// if (m_time_kernels)
|
||||
// CUDA_CHECK(cudaEventRecord(
|
||||
// m_kernel_stop_pools[0][frame_idx], sc.stream));
|
||||
// CUDA_CHECK(cudaGetLastError());
|
||||
//
|
||||
// void *h_out = static_cast<char *>(h_output_slots[0]) +
|
||||
// frame_idx * m_output_bytes_per_frame;
|
||||
// CUDA_CHECK(cudaMemcpyAsync(h_out, sc.d_output,
|
||||
// m_output_bytes_per_frame,
|
||||
// cudaMemcpyDeviceToHost, sc.stream));
|
||||
// }
|
||||
//
|
||||
// const int streams_used =
|
||||
// std::min<int>(n_streams, static_cast<int>(n_frames_batch));
|
||||
// for (int k = 0; k < streams_used; ++k)
|
||||
// CUDA_CHECK(cudaStreamSynchronize(v_sc[k].stream));
|
||||
//
|
||||
// for (size_t frame_idx = 0; frame_idx < n_frames_batch;
|
||||
// ++frame_idx) {
|
||||
// const void *h_out =
|
||||
// static_cast<const char *>(h_output_slots[0]) +
|
||||
// frame_idx * m_output_bytes_per_frame;
|
||||
// uint32_t n_found = *reinterpret_cast<const uint32_t *>(h_out);
|
||||
// n_found = std::min<uint32_t>(
|
||||
// n_found, static_cast<uint32_t>(m_max_clusters_per_frame));
|
||||
//
|
||||
// if (n_found > 0) {
|
||||
// const auto *src = reinterpret_cast<const ClusterType *>(
|
||||
// static_cast<const char *>(h_out) + m_clusters_offset);
|
||||
// results[frame_idx].resize(n_found);
|
||||
// std::memcpy(results[frame_idx].data(), src,
|
||||
// n_found * sizeof(ClusterType));
|
||||
// }
|
||||
//
|
||||
// if (m_time_kernels) {
|
||||
// float kernel_ms = 0.0f;
|
||||
// CUDA_CHECK(cudaEventElapsedTime(
|
||||
// &kernel_ms, m_kernel_start_pools[0][frame_idx],
|
||||
// m_kernel_stop_pools[0][frame_idx]));
|
||||
// m_total_kernel_ms += kernel_ms;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// m_frames_processed += n_frames_batch;
|
||||
// return results;
|
||||
// }
|
||||
|
||||
/// True if per-frame kernel timing was enabled at construction.
|
||||
bool kernel_timing_enabled() const { return m_time_kernels; }
|
||||
|
||||
@@ -1068,57 +921,18 @@ class ClusterFinderCUDA {
|
||||
|
||||
private:
|
||||
/**
|
||||
* Upload the current host pedestal (mean, sum, sum2) to every stream's
|
||||
* device buffers. Called lazily before a find_clusters call when the
|
||||
* host pedestal has been updated.
|
||||
* Upload the current host pedestal to every stream's device buffers.
|
||||
* Called lazily before a launch when the host pedestal has been updated.
|
||||
* How the host pedestal becomes device arrays (for CenteredRunningPedestal:
|
||||
* the centering on a per-pixel baseline) is the pedestal model's business;
|
||||
* the driver only fans one prepared image out over the streams.
|
||||
*/
|
||||
void sync_pedestal_to_device() {
|
||||
NDArray<PEDESTAL_TYPE, 2> h_mean = m_pedestal.mean();
|
||||
NDArray<PEDESTAL_TYPE, 2> h_sum = m_pedestal.get_sum();
|
||||
NDArray<PEDESTAL_TYPE, 2> h_sum2 = m_pedestal.get_sum2();
|
||||
|
||||
using DPT = device::DEVICE_PED_TYPE;
|
||||
const double n = static_cast<double>(m_pedestal.n_samples());
|
||||
|
||||
// Capture the frozen per-pixel baseline X0 (≈ mean at t=0) ONCE. Fixed
|
||||
// for the run so the centered device accumulators never need rebasing;
|
||||
// clear_pedestal() empties m_offset to force a fresh capture.
|
||||
if (m_offset.size() != m_image_size) {
|
||||
m_offset.resize(m_image_size);
|
||||
for (size_t i = 0; i < m_image_size; ++i)
|
||||
m_offset[i] = static_cast<DPT>(std::llround(h_mean.data()[i]));
|
||||
}
|
||||
|
||||
// Center in DOUBLE (where sum2 ~ n·E[X²] is still exact), then cast the
|
||||
// SMALL centered results to DPT — this is what dodges the f32
|
||||
// cancellation. Device holds: sum ~ n·E[Y], sum2 ~ n·E[Y²], Y = X − X0.
|
||||
// Σ(X−X0) = ΣX − n·X0
|
||||
// Σ(X−X0)² = ΣX² − 2·X0·ΣX + n·X0²
|
||||
std::vector<DPT> f_mean(m_image_size);
|
||||
std::vector<DPT> f_sum(m_image_size);
|
||||
std::vector<DPT> f_sum2(m_image_size);
|
||||
for (size_t i = 0; i < m_image_size; ++i) {
|
||||
const double X0 = static_cast<double>(m_offset[i]);
|
||||
const double s = h_sum.data()[i];
|
||||
const double s2 = h_sum2.data()[i];
|
||||
f_mean[i] = static_cast<DPT>(h_mean.data()[i]);
|
||||
f_sum[i] = static_cast<DPT>(s - n * X0);
|
||||
f_sum2[i] = static_cast<DPT>(s2 - 2.0 * X0 * s + n * X0 * X0);
|
||||
}
|
||||
|
||||
const size_t bytes = m_image_size * sizeof(DPT);
|
||||
for (auto &sc : v_sc) {
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.d_pd_mean, f_mean.data(), bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.d_pd_sum, f_sum.data(), bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.d_pd_sum2, f_sum2.data(), bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(sc.d_pd_off, m_offset.data(), bytes,
|
||||
cudaMemcpyHostToDevice, sc.stream));
|
||||
}
|
||||
const auto image = Ped::prepare_pedestal(m_pedestal);
|
||||
for (auto &sc : v_sc)
|
||||
CUDA_CHECK(cudaStreamSynchronize(sc.stream));
|
||||
Ped::upload_pedestal(image, sc->pedestal(), sc->stream());
|
||||
for (auto &sc : v_sc)
|
||||
CUDA_CHECK(cudaStreamSynchronize(sc->stream()));
|
||||
}
|
||||
|
||||
/// Grow one slot's pinned D2H buffer to hold n_frames. Only ever grows, so
|
||||
|
||||
@@ -42,8 +42,8 @@ struct StreamContextGraph {
|
||||
device::DEVICE_PED_TYPE *karg_d_pd_off = nullptr;
|
||||
uint32_t karg_n_pd_samples = 0;
|
||||
device::COMPUTE_TYPE karg_nSigma = 0.0f;
|
||||
size_t karg_nrows = 0;
|
||||
size_t karg_ncols = 0;
|
||||
int32_t karg_nrows = 0; // must match the kernel signature exactly:
|
||||
int32_t karg_ncols = 0; // kernelParams is untyped
|
||||
ClusterType *karg_d_clusters = nullptr;
|
||||
uint32_t *karg_d_cluster_count = nullptr;
|
||||
uint32_t karg_max_clusters = 0;
|
||||
@@ -94,7 +94,7 @@ class ClusterFinderCUDAGraph {
|
||||
size_t m_clusters_offset; // offset of cluster array within output block
|
||||
|
||||
COMPUTE_TYPE m_nSigma;
|
||||
Pedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
FastPedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
ClusterVector<ClusterType> m_clusters;
|
||||
bool m_pedestal_dirty = true;
|
||||
bool m_graphs_dirty = true; // set when pedestal or h_output_pinned changes
|
||||
@@ -125,11 +125,13 @@ class ClusterFinderCUDAGraph {
|
||||
*/
|
||||
ClusterFinderCUDAGraph(Shape<2> shape_, COMPUTE_TYPE nSigma = 5.0,
|
||||
size_t max_clusters_per_frame = 2048,
|
||||
int n_streams_ = 4)
|
||||
int n_streams_ = 4,
|
||||
size_t min_pedestal_samples = 1000)
|
||||
: m_shape(shape_), nrows(shape_[0]), ncols(shape_[1]),
|
||||
m_image_size(nrows * ncols), n_streams(n_streams_),
|
||||
m_max_clusters_per_frame(max_clusters_per_frame), m_nSigma(nSigma),
|
||||
m_pedestal(shape_[0], shape_[1]), m_clusters(max_clusters_per_frame) {
|
||||
m_pedestal(shape_[0], shape_[1], min_pedestal_samples),
|
||||
m_clusters(max_clusters_per_frame) {
|
||||
if (n_streams_ <= 0) {
|
||||
throw std::invalid_argument(
|
||||
"ClusterFinderCUDAGraph: n_streams must be > 0");
|
||||
@@ -147,6 +149,13 @@ class ClusterFinderCUDAGraph {
|
||||
"ClusterFinderCUDAGraph: max_clusters_per_frame must be > 0");
|
||||
}
|
||||
|
||||
// The kernel indexes pixels with int32_t
|
||||
if (m_image_size >
|
||||
static_cast<size_t>(std::numeric_limits<int32_t>::max())) {
|
||||
throw std::invalid_argument(
|
||||
"ClusterFinderCUDAGraph: nrows * ncols must fit in int32_t");
|
||||
}
|
||||
|
||||
// Grid/Block dimensions
|
||||
block = dim3(BLOCK_X, BLOCK_Y);
|
||||
grid = dim3((static_cast<unsigned int>(ncols) + BLOCK_X - 1) / BLOCK_X,
|
||||
@@ -261,7 +270,11 @@ class ClusterFinderCUDAGraph {
|
||||
}
|
||||
|
||||
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
|
||||
m_pedestal.push(frame);
|
||||
if (!m_pedestal.ready()) {
|
||||
m_pedestal.add_init_frame(frame);
|
||||
} else {
|
||||
m_pedestal.push_ema(frame);
|
||||
}
|
||||
m_pedestal_dirty = true;
|
||||
}
|
||||
|
||||
@@ -420,8 +433,10 @@ class ClusterFinderCUDAGraph {
|
||||
*/
|
||||
void sync_pedestal_to_device() {
|
||||
NDArray<PEDESTAL_TYPE, 2> h_mean = m_pedestal.mean();
|
||||
NDArray<PEDESTAL_TYPE, 2> h_sum = m_pedestal.get_sum();
|
||||
NDArray<PEDESTAL_TYPE, 2> h_sum2 = m_pedestal.get_sum2();
|
||||
// FastPedestal keeps both moments in double whatever PEDESTAL_TYPE is,
|
||||
// so let the accessors name their own type here.
|
||||
auto h_sum = m_pedestal.get_sum();
|
||||
auto h_sum2 = m_pedestal.get_sum2();
|
||||
|
||||
using DPT = device::DEVICE_PED_TYPE;
|
||||
const double n = static_cast<double>(m_pedestal.n_samples());
|
||||
@@ -524,8 +539,8 @@ class ClusterFinderCUDAGraph {
|
||||
sc.karg_d_pd_off = sc.d_pd_off;
|
||||
sc.karg_n_pd_samples = n_pd_samples;
|
||||
sc.karg_nSigma = m_nSigma;
|
||||
sc.karg_nrows = nrows;
|
||||
sc.karg_ncols = ncols;
|
||||
sc.karg_nrows = static_cast<int32_t>(nrows);
|
||||
sc.karg_ncols = static_cast<int32_t>(ncols);
|
||||
sc.karg_d_clusters = reinterpret_cast<ClusterType *>(
|
||||
sc.d_output + m_clusters_offset);
|
||||
sc.karg_d_cluster_count = reinterpret_cast<uint32_t *>(sc.d_output);
|
||||
@@ -548,7 +563,8 @@ class ClusterFinderCUDAGraph {
|
||||
cudaKernelNodeParams kp = {};
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-pro-type-reinterpret-cast)
|
||||
kp.func = reinterpret_cast<void *>(
|
||||
device::find_clusters_in_single_frame<ClusterType, FRAME_TYPE>);
|
||||
device::find_clusters_in_single_frame<ClusterType, FRAME_TYPE,
|
||||
BLOCK_X, BLOCK_Y>);
|
||||
kp.gridDim = grid;
|
||||
kp.blockDim = block;
|
||||
kp.sharedMemBytes = static_cast<unsigned int>(shmem_bytes);
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
#include "aare/ClusterFinder.hpp" // no_2x2_cluster guard, reused here
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/Dtype.hpp"
|
||||
#include "aare/FastPedestal.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
#include <cstddef>
|
||||
#include <utility>
|
||||
@@ -45,7 +45,7 @@ class ClusterFinderFrozen {
|
||||
PEDESTAL_TYPE m_nSigma;
|
||||
const PEDESTAL_TYPE c2;
|
||||
const PEDESTAL_TYPE c3;
|
||||
Pedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
FastPedestal<PEDESTAL_TYPE> m_pedestal;
|
||||
ClusterVector<ClusterType> m_clusters;
|
||||
|
||||
static const uint8_t ClusterSizeX = ClusterType::cluster_size_x;
|
||||
@@ -54,21 +54,28 @@ class ClusterFinderFrozen {
|
||||
|
||||
public:
|
||||
ClusterFinderFrozen(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 1000000)
|
||||
size_t capacity = 1000000,
|
||||
size_t min_pedestal_samples = 1000)
|
||||
: m_image_size(image_size), m_nSigma(nSigma),
|
||||
c2(sqrt((ClusterSizeY + 1) / 2 * (ClusterSizeX + 1) / 2)),
|
||||
c3(sqrt(ClusterSizeX * ClusterSizeY)),
|
||||
m_pedestal(image_size[0], image_size[1]), m_clusters(capacity) {
|
||||
m_pedestal(image_size[0], image_size[1], min_pedestal_samples),
|
||||
m_clusters(capacity) {
|
||||
LOG(logDEBUG) << "ClusterFinderFrozen: "
|
||||
<< "image_size: " << image_size[0] << "x" << image_size[1]
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity;
|
||||
<< ", nSigma: " << nSigma << ", capacity: " << capacity
|
||||
<< ", min_pedestal_samples: " << min_pedestal_samples;
|
||||
}
|
||||
|
||||
void set_nSigma(PEDESTAL_TYPE nSigma) { m_nSigma = nSigma; }
|
||||
PEDESTAL_TYPE get_nSigma() const { return m_nSigma; }
|
||||
|
||||
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
|
||||
m_pedestal.push(frame);
|
||||
if (!m_pedestal.ready()) {
|
||||
m_pedestal.add_init_frame(frame);
|
||||
} else {
|
||||
m_pedestal.push_ema(frame);
|
||||
}
|
||||
}
|
||||
|
||||
NDArray<PEDESTAL_TYPE, 2> pedestal() { return m_pedestal.mean(); }
|
||||
@@ -86,6 +93,11 @@ class ClusterFinderFrozen {
|
||||
}
|
||||
|
||||
void find_clusters(NDView<FRAME_TYPE, 2> frame, uint64_t frame_number = 0) {
|
||||
if (!m_pedestal.ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot find clusters");
|
||||
}
|
||||
|
||||
int dy = ClusterSizeY / 2;
|
||||
int dx = ClusterSizeX / 2;
|
||||
int has_center_pixel_x = ClusterSizeX % 2;
|
||||
@@ -177,7 +189,7 @@ class ClusterFinderFrozen {
|
||||
// only affects decisions from the NEXT frame on -> matches CUDA. Each
|
||||
// pixel is visited at most once per frame, so push order is irrelevant.
|
||||
for (const auto &p : deferred)
|
||||
m_pedestal.push_fast(p.first, p.second, frame(p.first, p.second));
|
||||
m_pedestal.push_ema(p.first, p.second, frame(p.first, p.second));
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -131,30 +131,57 @@ class ClusterFinderMT {
|
||||
}
|
||||
}
|
||||
|
||||
bool output_queues_are_empty() const {
|
||||
for (auto &q : m_output_queues) {
|
||||
if (!q->isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Collect all the clusters from the output queues and write them to
|
||||
* the sink
|
||||
*/
|
||||
// void collect() {
|
||||
// Backoff backoff;
|
||||
// while (!m_stop_requested || !output_queues_are_empty() ||
|
||||
// !m_processing_threads_stopped) {
|
||||
// bool moved_any = false;
|
||||
// for (auto &queue : m_output_queues) {
|
||||
// if (auto *front = queue->frontPtr(); front != nullptr) {
|
||||
// while (!m_sink.write(std::move(*front))) {
|
||||
// backoff.pause();
|
||||
// }
|
||||
// queue->popFront();
|
||||
// moved_any = true;
|
||||
// }
|
||||
// }
|
||||
// if (moved_any) {
|
||||
// backoff.reset();
|
||||
// } else {
|
||||
// backoff.pause();
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
void collect() {
|
||||
bool empty = true;
|
||||
Backoff backoff;
|
||||
while (!m_stop_requested || !empty || !m_processing_threads_stopped) {
|
||||
for (;;) {
|
||||
const bool done = m_stop_requested && m_processing_threads_stopped;
|
||||
bool moved_any = false;
|
||||
for (auto &queue : m_output_queues) {
|
||||
while (auto *front = queue->frontPtr()) {
|
||||
while (!m_sink.write(std::move(*front))) {
|
||||
while (!m_sink.write(std::move(*front)))
|
||||
backoff.pause();
|
||||
}
|
||||
queue->popFront();
|
||||
moved_any = true;
|
||||
}
|
||||
}
|
||||
empty = !moved_any;
|
||||
if (moved_any) {
|
||||
backoff.reset();
|
||||
} else {
|
||||
backoff.pause();
|
||||
}
|
||||
if (done &&
|
||||
!moved_any) // swept after observing done, so this is real
|
||||
break;
|
||||
moved_any ? backoff.reset() : backoff.pause();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -171,16 +198,19 @@ class ClusterFinderMT {
|
||||
* allocated once and recycled, so the total resident frame memory is
|
||||
* n_threads * queue_depth * frame size. Keeping the in flight data below
|
||||
* the L3 size keeps the per frame copy cheap.
|
||||
* @param min_pedestal_samples minimum number of pedestal samples to
|
||||
* accumulate before using the pedestal
|
||||
*/
|
||||
ClusterFinderMT(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 2000, size_t n_threads = 3,
|
||||
size_t queue_depth = 16)
|
||||
size_t queue_depth = 16, size_t min_pedestal_samples = 1000)
|
||||
: m_n_threads(n_threads) {
|
||||
|
||||
LOG(logDEBUG1) << "ClusterFinderMT: "
|
||||
<< "image_size: " << image_size[0] << "x"
|
||||
<< image_size[1] << ", nSigma: " << nSigma
|
||||
<< ", capacity: " << capacity
|
||||
<< ", min_pedestal_samples: " << min_pedestal_samples
|
||||
<< ", n_threads: " << n_threads
|
||||
<< ", queue_depth: " << queue_depth;
|
||||
|
||||
@@ -188,7 +218,7 @@ class ClusterFinderMT {
|
||||
m_cluster_finders.push_back(
|
||||
std::make_unique<
|
||||
ClusterFinder<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>>(
|
||||
image_size, nSigma, capacity));
|
||||
image_size, nSigma, capacity, min_pedestal_samples));
|
||||
}
|
||||
for (size_t i = 0; i < n_threads; i++) {
|
||||
m_frame_pools.emplace_back(
|
||||
|
||||
@@ -20,14 +20,19 @@ template <typename ClusterType,
|
||||
class ClusterVector; // Forward declaration
|
||||
|
||||
/**
|
||||
* @brief ClusterVector is a container for clusters of various sizes. It
|
||||
* uses a contiguous memory buffer to store the clusters. It is templated on
|
||||
* the data type and the coordinate type of the clusters.
|
||||
* @note push_back can invalidate pointers to elements in the container
|
||||
* @brief Move-only container that stores fixed-size clusters contiguously.
|
||||
*
|
||||
* The pixel type, cluster dimensions, and coordinate type are determined by
|
||||
* the Cluster specialization supplied as the template argument.
|
||||
*
|
||||
* @note push_back, reserve, and resize can invalidate pointers, references, and
|
||||
* iterators to elements in the container.
|
||||
* @warning ClusterVector is currently move only to catch unintended copies,
|
||||
* but this might change since there are probably use cases where copying is
|
||||
* needed.
|
||||
* @tparam T data type of the pixels in the cluster
|
||||
* @tparam ClusterSizeX cluster size in the x dimension
|
||||
* @tparam ClusterSizeY cluster size in the y dimension
|
||||
* @tparam CoordType data type of the x and y coordinates of the cluster
|
||||
* (normally uint16_t)
|
||||
*/
|
||||
@@ -44,11 +49,11 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
|
||||
/**
|
||||
* @brief Construct a new ClusterVector object
|
||||
* @param capacity initial capacity of the buffer in number of clusters
|
||||
* @param capacity minimum initial capacity in number of clusters
|
||||
* @param frame_number frame number of the clusters. Default is 0, which is
|
||||
* also used to indicate that the clusters come from many frames
|
||||
*/
|
||||
ClusterVector(size_t capacity = 1024, uint64_t frame_number = 0)
|
||||
ClusterVector(size_t capacity = 1024, int32_t frame_number = 0)
|
||||
: m_frame_number(frame_number) {
|
||||
m_data.reserve(capacity);
|
||||
}
|
||||
@@ -57,18 +62,24 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
ClusterVector &operator=(ClusterVector &&other) noexcept = default;
|
||||
|
||||
/**
|
||||
* @brief Create a copy of the clustervector by filtering clusters in the
|
||||
* ClusterVector using a boolean mask.
|
||||
* @param mask boolean 1d mask
|
||||
* @return ClusterVector containing only the clusters where the mask is
|
||||
* true
|
||||
* @brief Return a filtered copy selected by a one-dimensional Boolean mask.
|
||||
* @param mask boolean 1d mask true if element in ClusterVector will be
|
||||
* included
|
||||
* @return ClusterVector containing the selected clusters in their original
|
||||
* order and with the original frame number
|
||||
* @throws std::runtime_error if the mask length differs from size()
|
||||
*/
|
||||
ClusterVector operator()(NDView<bool, 1> mask) {
|
||||
if (static_cast<size_t>(mask.size()) != m_data.size()) {
|
||||
throw std::runtime_error(
|
||||
LOCATION + "Mask size does not match number of clusters");
|
||||
}
|
||||
ClusterVector result(capacity(), frame_number());
|
||||
if (m_data.empty()) {
|
||||
return ClusterVector(0, frame_number());
|
||||
}
|
||||
const auto selected =
|
||||
static_cast<size_t>(std::count(mask.begin(), mask.end(), true));
|
||||
ClusterVector result(selected, frame_number());
|
||||
for (size_t i = 0; i < m_data.size(); ++i) {
|
||||
if (mask(i)) {
|
||||
result.push_back(m_data[i]);
|
||||
@@ -77,20 +88,9 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
return result;
|
||||
}
|
||||
|
||||
// // Move assignment operator
|
||||
// ClusterVector &operator=(ClusterVector &&other) noexcept {
|
||||
// if (this != &other) {
|
||||
// m_data = other.m_data;
|
||||
// m_frame_number = other.m_frame_number;
|
||||
// other.m_data.clear();
|
||||
// other.m_frame_number = 0;
|
||||
// }
|
||||
// return *this;
|
||||
// }
|
||||
|
||||
/**
|
||||
* @brief Sum the pixels in each cluster
|
||||
* @return std::vector<T> vector of sums for each cluster
|
||||
* @brief Sum the pixels in each cluster.
|
||||
* @return One sum for every cluster, in container order
|
||||
*/
|
||||
std::vector<T> sum() {
|
||||
std::vector<T> sums(m_data.size());
|
||||
@@ -103,9 +103,10 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Sum the pixels in the 2x2 subcluster with the biggest pixel sum in
|
||||
* each cluster
|
||||
* @return vector of sums index pairs for each cluster
|
||||
* @brief Find the highest-sum center-adjacent 2x2 subcluster in each
|
||||
* cluster.
|
||||
* @return One sum and corner-index pair for every cluster, in container
|
||||
* order
|
||||
*/
|
||||
std::vector<Sum_index_pair<T, corner>> sum_2x2() {
|
||||
std::vector<Sum_index_pair<T, corner>> sums_2x2(m_data.size());
|
||||
@@ -125,10 +126,29 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
*/
|
||||
void reserve(size_t capacity) { m_data.reserve(capacity); }
|
||||
|
||||
/**
|
||||
* @brief Change the number of stored clusters.
|
||||
* @param size new number of clusters
|
||||
* @note Growing the vector value-initializes new clusters and can
|
||||
* invalidate pointers, references, and iterators.
|
||||
*/
|
||||
void resize(size_t size) { m_data.resize(size); }
|
||||
|
||||
/**
|
||||
* @brief Append a cluster to the vector.
|
||||
* @param cluster cluster to append
|
||||
* @note Reallocation invalidates pointers, references, iterators, and
|
||||
* zero-copy NumPy views of the storage.
|
||||
*/
|
||||
void push_back(const ClusterType &cluster) { m_data.push_back(cluster); }
|
||||
|
||||
/**
|
||||
* @brief Append all clusters from another vector.
|
||||
* @param other vector whose clusters are appended
|
||||
* @return Reference to this vector
|
||||
* @note The frame number of this vector is unchanged.
|
||||
* @warning other must not refer to this vector.
|
||||
*/
|
||||
ClusterVector &operator+=(const ClusterVector &other) {
|
||||
m_data.insert(m_data.end(), other.begin(), other.end());
|
||||
|
||||
@@ -145,8 +165,10 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
*/
|
||||
bool empty() const { return m_data.empty(); }
|
||||
|
||||
/** @brief Return the cluster size in the x dimension. */
|
||||
uint8_t cluster_size_x() const { return ClusterSizeX; }
|
||||
|
||||
/** @brief Return the cluster size in the y dimension. */
|
||||
uint8_t cluster_size_y() const { return ClusterSizeY; }
|
||||
|
||||
/**
|
||||
@@ -161,7 +183,7 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
auto end() const { return m_data.end(); }
|
||||
|
||||
/**
|
||||
* @brief Return the size in bytes of a single cluster
|
||||
* @brief Return the size in bytes of one stored cluster, including padding.
|
||||
*/
|
||||
size_t item_size() const {
|
||||
return sizeof(ClusterType); // 2 * sizeof(CoordType) + ClusterSizeX *
|
||||
@@ -172,8 +194,8 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
ClusterType const *data() const { return m_data.data(); }
|
||||
|
||||
/**
|
||||
* @brief Return a reference to the i-th cluster casted to type V
|
||||
* @tparam V type of the cluster
|
||||
* @brief Return a reference to the i-th cluster without bounds checking.
|
||||
* @param i zero-based cluster index
|
||||
*/
|
||||
ClusterType &operator[](size_t i) { return m_data[i]; }
|
||||
|
||||
@@ -185,16 +207,20 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
|
||||
*/
|
||||
int32_t frame_number() const { return m_frame_number; }
|
||||
|
||||
/**
|
||||
* @brief Set the signed 32-bit frame number associated with the clusters.
|
||||
* @param frame_number frame number, or 0 for clusters from multiple frames
|
||||
*/
|
||||
void set_frame_number(int32_t frame_number) {
|
||||
m_frame_number = frame_number;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Reduce a cluster to a 2x2 cluster by selecting the 2x2 block with the
|
||||
* highest sum.
|
||||
* @param cv Clustervector containing clusters to reduce
|
||||
* @return Clustervector with reduced clusters
|
||||
* @brief Reduce every cluster to its highest-sum center-adjacent 2x2 block.
|
||||
* @param cv ClusterVector containing clusters to reduce
|
||||
* @return ClusterVector of 2x2 clusters in the original order and with the
|
||||
* original frame number
|
||||
* @note The cluster is filled using row major ordering starting at the top-left
|
||||
* (thus for a max subcluster in the top left cornern the photon hit is at
|
||||
* the fourth position)
|
||||
@@ -204,7 +230,8 @@ template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
ClusterVector<Cluster<T, 2, 2, CoordType>> reduce_to_2x2(
|
||||
const ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>>
|
||||
&cv) {
|
||||
ClusterVector<Cluster<T, 2, 2, CoordType>> result;
|
||||
ClusterVector<Cluster<T, 2, 2, CoordType>> result(cv.size(),
|
||||
cv.frame_number());
|
||||
for (const auto &c : cv) {
|
||||
result.push_back(reduce_to_2x2(c));
|
||||
}
|
||||
@@ -212,20 +239,25 @@ ClusterVector<Cluster<T, 2, 2, CoordType>> reduce_to_2x2(
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Reduce a cluster to a 3x3 cluster
|
||||
* @param cv Clustervector containing clusters to reduce
|
||||
* @return Clustervector with reduced clusters
|
||||
* @brief Reduce every cluster to the 3x3 block around its center index.
|
||||
* @param cv ClusterVector containing clusters to reduce
|
||||
* @pre ClusterSizeX and ClusterSizeY must both be at least 3, and at least one
|
||||
* must be greater than 3.
|
||||
* @return ClusterVector of 3x3 clusters in the original order and with the
|
||||
* original frame number
|
||||
* @note Coordinates are preserved.
|
||||
*/
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
typename CoordType>
|
||||
ClusterVector<Cluster<T, 3, 3, CoordType>> reduce_to_3x3(
|
||||
const ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>>
|
||||
&cv) {
|
||||
ClusterVector<Cluster<T, 3, 3, CoordType>> result;
|
||||
ClusterVector<Cluster<T, 3, 3, CoordType>> result(cv.size(),
|
||||
cv.frame_number());
|
||||
for (const auto &c : cv) {
|
||||
result.push_back(reduce_to_3x3(c));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -1,8 +1,7 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/ROI.hpp"
|
||||
#include "aare/ROIGeometry.hpp"
|
||||
#include "aare/RawMasterFile.hpp" //ROI refactor away
|
||||
#include "aare/defs.hpp"
|
||||
#include <iostream>
|
||||
|
||||
namespace aare {
|
||||
@@ -97,6 +96,8 @@ class DetectorGeometry {
|
||||
const xy udp_interfaces_per_module = xy{1, 1},
|
||||
const bool quad = false);
|
||||
|
||||
DetectorGeometry() = default;
|
||||
|
||||
~DetectorGeometry() = default;
|
||||
|
||||
/**
|
||||
@@ -114,6 +115,8 @@ class DetectorGeometry {
|
||||
size_t modules_x() const;
|
||||
size_t modules_y() const;
|
||||
|
||||
xy udp_interfaces_per_module() const;
|
||||
|
||||
const std::vector<ModuleGeometry> &get_module_geometries() const;
|
||||
|
||||
const ModuleGeometry &get_module_geometries(const size_t index) const;
|
||||
@@ -125,6 +128,7 @@ class DetectorGeometry {
|
||||
size_t m_modules_y{};
|
||||
size_t m_pixels_x{};
|
||||
size_t m_pixels_y{};
|
||||
xy m_udp_interfaces_per_module{};
|
||||
static constexpr ModuleConfig cfg{0, 0};
|
||||
|
||||
// TODO: maybe remove - should be a member in ROIGeometry - in particular
|
||||
|
||||
@@ -4,20 +4,20 @@
|
||||
#include "aare/Frame.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <sys/types.h>
|
||||
|
||||
namespace aare {
|
||||
|
||||
/**
|
||||
* @brief Maintain per-pixel mean, population variance, and standard deviation.
|
||||
* @brief Maintain per-pixel mean and population standard deviation.
|
||||
*
|
||||
* Initialization accumulates exactly n_samples frames. Subsequent push_ema()
|
||||
* update the exponential moving average initialized with the mean using
|
||||
* a smoothing factor of (1/ n_samples). Internal moments are stored
|
||||
* in double precision.
|
||||
* @tparam PEDESTAL_TYPE Type returned for the mean, variance, and standard
|
||||
* deviation.
|
||||
* in double precision. Variance is a private double-precision intermediate.
|
||||
* @tparam PEDESTAL_TYPE Type returned for the mean and standard deviation.
|
||||
*/
|
||||
template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
|
||||
@@ -93,7 +93,7 @@ template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
* @brief Return a copy of the cached mean.
|
||||
* @throws std::runtime_error if ready() is false.
|
||||
*/
|
||||
NDArray<PEDESTAL_TYPE, 2> mean() {
|
||||
NDArray<PEDESTAL_TYPE, 2> mean() const {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return mean");
|
||||
@@ -127,58 +127,12 @@ template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
*/
|
||||
PEDESTAL_TYPE mean_unchecked(ssize_t index) const { return m_mean[index]; }
|
||||
|
||||
/**
|
||||
* @brief Calculate and return the population variance of every pixel.
|
||||
* @throws std::runtime_error if ready() is false.
|
||||
* @note The result is normalized by n_samples.
|
||||
*/
|
||||
NDArray<PEDESTAL_TYPE, 2> variance() {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return variance");
|
||||
}
|
||||
NDArray<PEDESTAL_TYPE, 2> res({m_rows, m_cols});
|
||||
for (ssize_t i = 0; i < m_sum.size(); ++i) {
|
||||
res[i] = variance_unchecked(i);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate the population variance at (row, col).
|
||||
* @throws std::runtime_error if ready() is false or either index is out of
|
||||
* range.
|
||||
*/
|
||||
PEDESTAL_TYPE variance(const uint32_t row, const uint32_t col) const {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return variance");
|
||||
}
|
||||
if (row >= m_rows || col >= m_cols) {
|
||||
throw std::runtime_error(fmt::format(
|
||||
"Invalid indices for FastPedestal variance: row={}, "
|
||||
"col={} must be in [0, {}), [0, {})",
|
||||
row, col, m_rows, m_cols));
|
||||
}
|
||||
return variance_unchecked(rc_to_index(row, col));
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate the population variance at a flat row-major index.
|
||||
* @pre ready() is true and index is valid; the index is not checked.
|
||||
*/
|
||||
PEDESTAL_TYPE variance_unchecked(ssize_t index) const {
|
||||
const auto &entry = m_sum[index];
|
||||
const auto m = entry.sum * m_inv_samples;
|
||||
return std::fma(-m, m, entry.sum2 * m_inv_samples);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate and return the population standard deviation of every
|
||||
* pixel.
|
||||
* @throws std::runtime_error if ready() is false.
|
||||
*/
|
||||
NDArray<PEDESTAL_TYPE, 2> std() {
|
||||
NDArray<PEDESTAL_TYPE, 2> std() const {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return std");
|
||||
@@ -190,6 +144,43 @@ template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return a copy of the per-pixel first moment, ~ n * E[X].
|
||||
* @throws std::runtime_error if ready() is false.
|
||||
* @note The two moments are stored interleaved for cache locality, so this
|
||||
* de-interleaves them into a plain array. Intended for callers that need a
|
||||
* contiguous moment array rather than per-pixel access, such as the CUDA
|
||||
* pedestal upload.
|
||||
*/
|
||||
NDArray<double, 2> get_sum() const {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return sum");
|
||||
}
|
||||
NDArray<double, 2> res({m_rows, m_cols});
|
||||
for (ssize_t i = 0; i < m_sum.size(); ++i) {
|
||||
res[i] = m_sum[i].sum;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Return a copy of the per-pixel second moment, ~ n * E[X^2].
|
||||
* @throws std::runtime_error if ready() is false.
|
||||
* @see get_sum() for why this is a de-interleaving copy.
|
||||
*/
|
||||
NDArray<double, 2> get_sum2() const {
|
||||
if (!ready()) {
|
||||
throw std::runtime_error(
|
||||
"Pedestal is not ready, cannot return sum2");
|
||||
}
|
||||
NDArray<double, 2> res({m_rows, m_cols});
|
||||
for (ssize_t i = 0; i < m_sum.size(); ++i) {
|
||||
res[i] = m_sum[i].sum2;
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Calculate the population standard deviation at (row, col).
|
||||
* @throws std::runtime_error if ready() is false or either index is out of
|
||||
@@ -206,7 +197,7 @@ template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
"col={} must be in [0, {}), [0, {})",
|
||||
row, col, m_rows, m_cols));
|
||||
}
|
||||
return std::sqrt(variance(row, col));
|
||||
return std_unchecked(rc_to_index(row, col));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -410,6 +401,14 @@ template <typename PEDESTAL_TYPE> class FastPedestal {
|
||||
uint32_t n_samples() const { return m_samples; }
|
||||
|
||||
private:
|
||||
double variance_unchecked(ssize_t index) const {
|
||||
const auto &entry = m_sum[index];
|
||||
const auto mean = entry.sum * m_inv_samples;
|
||||
const auto variance = std::fma(-mean, mean, entry.sum2 * m_inv_samples);
|
||||
// Roundoff in the moments can make a near-zero variance negative.
|
||||
return std::max(variance, 0.0);
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Write the cached mean after the final add_init_frame. All other
|
||||
* (non initialization) pushes update the cached mean immediately.
|
||||
|
||||
@@ -18,6 +18,7 @@ class FilePtr {
|
||||
FilePtr &operator=(const FilePtr &) = delete; // since we handle a resource
|
||||
FilePtr(FilePtr &&other);
|
||||
FilePtr &operator=(FilePtr &&other);
|
||||
explicit operator bool() const noexcept;
|
||||
FILE *get();
|
||||
ssize_t tell();
|
||||
void seek(ssize_t offset, int whence = SEEK_SET) {
|
||||
@@ -28,4 +29,4 @@ class FilePtr {
|
||||
~FilePtr();
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
+24
-13
@@ -34,29 +34,40 @@ class InvertedGainMap {
|
||||
template <typename ClusterType,
|
||||
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
|
||||
void apply_gain_map(ClusterVector<ClusterType> &clustervec) {
|
||||
// in principle we need to know the size of the image for this lookup
|
||||
size_t ClusterSizeX = clustervec.cluster_size_x();
|
||||
size_t ClusterSizeY = clustervec.cluster_size_y();
|
||||
|
||||
using T = typename ClusterVector<ClusterType>::value_type;
|
||||
|
||||
int64_t index_cluster_center_x = ClusterSizeX / 2;
|
||||
int64_t index_cluster_center_y = ClusterSizeY / 2;
|
||||
constexpr size_t cluster_size_x = ClusterType::cluster_size_x;
|
||||
constexpr size_t cluster_size_y = ClusterType::cluster_size_y;
|
||||
constexpr ssize_t pixel_left_from_center = cluster_size_x / 2;
|
||||
constexpr ssize_t pixels_right_from_center =
|
||||
cluster_size_x - pixel_left_from_center - 1;
|
||||
constexpr ssize_t pixels_top_from_center = cluster_size_y / 2;
|
||||
constexpr ssize_t pixels_bottom_from_center =
|
||||
cluster_size_y - pixels_top_from_center - 1;
|
||||
|
||||
for (size_t i = 0; i < clustervec.size(); i++) {
|
||||
auto &cl = clustervec[i];
|
||||
const auto center_x = static_cast<ssize_t>(cl.x);
|
||||
const auto center_y = static_cast<ssize_t>(cl.y);
|
||||
|
||||
if (cl.x > 0 && cl.y > 0 && cl.x < m_gain_map.shape(1) - 1 &&
|
||||
cl.y < m_gain_map.shape(0) - 1) {
|
||||
for (size_t j = 0; j < ClusterSizeX * ClusterSizeY; j++) {
|
||||
size_t x = cl.x + j % ClusterSizeX - index_cluster_center_x;
|
||||
size_t y = cl.y + j / ClusterSizeX - index_cluster_center_y;
|
||||
if (center_x >= pixel_left_from_center &&
|
||||
center_y >= pixels_top_from_center &&
|
||||
center_x < m_gain_map.shape(1) - pixels_right_from_center &&
|
||||
center_y < m_gain_map.shape(0) - pixels_bottom_from_center) {
|
||||
for (size_t j = 0; j < cluster_size_x * cluster_size_y; j++) {
|
||||
const auto x = center_x +
|
||||
static_cast<ssize_t>(j % cluster_size_x) -
|
||||
pixel_left_from_center;
|
||||
const auto y = center_y +
|
||||
static_cast<ssize_t>(j / cluster_size_x) -
|
||||
pixels_top_from_center;
|
||||
cl.data[j] = static_cast<T>(
|
||||
static_cast<double>(cl.data[j]) *
|
||||
m_gain_map(
|
||||
y, x)); // cast after conversion to keep precision
|
||||
}
|
||||
} else {
|
||||
// clear edge clusters
|
||||
// Clear clusters whose footprint extends beyond the gain map.
|
||||
cl.data.fill(0);
|
||||
}
|
||||
}
|
||||
@@ -66,4 +77,4 @@ class InvertedGainMap {
|
||||
NDArray<double, 2> m_gain_map{};
|
||||
};
|
||||
|
||||
} // end of namespace aare
|
||||
} // end of namespace aare
|
||||
+118
-126
@@ -3,15 +3,19 @@
|
||||
#include "aare/Frame.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
|
||||
namespace aare {
|
||||
|
||||
/**
|
||||
* @brief Calculate the pedestal of a series of frames. Can be used as
|
||||
* standalone but mostly used in the ClusterFinder.
|
||||
* @brief Maintain per-pixel mean and population standard deviation.
|
||||
*
|
||||
* @tparam SUM_TYPE type of the sum
|
||||
* Each pixel accumulates its first n_samples values. Subsequent pushes update
|
||||
* the exponential moving average with a smoothing factor of 1 / n_samples.
|
||||
* Statistics are available during initialization and are zero for empty pixels.
|
||||
* Internal moments and the private variance intermediate use double precision.
|
||||
* @tparam SUM_TYPE Type returned for the mean and standard deviation.
|
||||
*/
|
||||
template <typename SUM_TYPE = double> class Pedestal {
|
||||
uint32_t m_rows;
|
||||
@@ -20,98 +24,110 @@ template <typename SUM_TYPE = double> class Pedestal {
|
||||
uint32_t m_samples;
|
||||
NDArray<uint32_t, 2> m_cur_samples;
|
||||
|
||||
// TODO! in case of int needs to be changed to uint64_t
|
||||
NDArray<SUM_TYPE, 2> m_sum;
|
||||
NDArray<SUM_TYPE, 2> m_sum2;
|
||||
NDArray<double, 2> m_sum;
|
||||
NDArray<double, 2> m_sum2;
|
||||
|
||||
// Cache mean since it is used over and over in the ClusterFinder
|
||||
// This optimization is related to the access pattern of the ClusterFinder
|
||||
// Relies on having more reads than pushes to the pedestal
|
||||
NDArray<SUM_TYPE, 2> m_mean;
|
||||
|
||||
// Cache std. Only refreshed via update_std() to keep push() cheap.
|
||||
NDArray<SUM_TYPE, 2> m_std;
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief Construct an empty pedestal with zero mean and standard deviation.
|
||||
* @param rows Number of image rows.
|
||||
* @param cols Number of image columns.
|
||||
* @param n_samples Number of initialization samples per pixel and
|
||||
* reciprocal of the weight assigned to each subsequent value.
|
||||
* @throws std::runtime_error if rows, cols, or n_samples is zero.
|
||||
*/
|
||||
Pedestal(uint32_t rows, uint32_t cols, uint32_t n_samples = 1000)
|
||||
: m_rows(rows), m_cols(cols), m_samples(n_samples),
|
||||
m_cur_samples(NDArray<uint32_t, 2>({rows, cols}, 0)),
|
||||
m_sum(NDArray<SUM_TYPE, 2>({rows, cols})),
|
||||
m_sum2(NDArray<SUM_TYPE, 2>({rows, cols})),
|
||||
m_mean(NDArray<SUM_TYPE, 2>({rows, cols})),
|
||||
m_std(NDArray<SUM_TYPE, 2>({rows, cols})) {
|
||||
assert(rows > 0 && cols > 0 && n_samples > 0);
|
||||
m_sum = 0;
|
||||
m_sum2 = 0;
|
||||
m_mean = 0;
|
||||
m_std = 0;
|
||||
m_sum(NDArray<double, 2>({rows, cols}, 0.0)),
|
||||
m_sum2(NDArray<double, 2>({rows, cols}, 0.0)),
|
||||
m_mean(NDArray<SUM_TYPE, 2>({rows, cols}, SUM_TYPE(0))) {
|
||||
if (!(rows > 0 && cols > 0 && n_samples > 0)) {
|
||||
throw std::runtime_error(
|
||||
fmt::format("Invalid parameters for Pedestal: rows={}, "
|
||||
"cols={}, n_samples={} need to be positive",
|
||||
rows, cols, n_samples));
|
||||
}
|
||||
}
|
||||
|
||||
~Pedestal() = default;
|
||||
|
||||
NDArray<SUM_TYPE, 2> mean() { return m_mean; }
|
||||
|
||||
/**
|
||||
* @brief Return a non-owning view of the cached mean.
|
||||
* @note The caller must treat the data as read-only and must not retain the
|
||||
* view after this object is destroyed, moved, or assigned.
|
||||
*/
|
||||
NDView<const SUM_TYPE, 2> view() const { return m_mean.view(); }
|
||||
|
||||
/**
|
||||
* @brief Return the cached mean at (row, col), or zero for an empty pixel.
|
||||
* @pre row and col are valid pixel indices.
|
||||
*/
|
||||
SUM_TYPE mean(const uint32_t row, const uint32_t col) const {
|
||||
return m_mean(row, col);
|
||||
}
|
||||
|
||||
NDArray<SUM_TYPE, 2> cached_std() { return m_std; }
|
||||
|
||||
SUM_TYPE cached_std(const uint32_t row, const uint32_t col) const {
|
||||
return m_std(row, col);
|
||||
}
|
||||
/** @brief Return a copy of the cached mean. */
|
||||
NDArray<SUM_TYPE, 2> mean() const { return m_mean; }
|
||||
|
||||
/**
|
||||
* @brief Calculate the population standard deviation at (row, col).
|
||||
* @pre row and col are valid pixel indices.
|
||||
* @note Variance is normalized by the pixel's current sample count. Empty
|
||||
* pixels return zero, and negative variance from roundoff is clamped to
|
||||
* zero.
|
||||
*/
|
||||
SUM_TYPE std(const uint32_t row, const uint32_t col) const {
|
||||
return std::sqrt(variance(row, col));
|
||||
}
|
||||
|
||||
SUM_TYPE variance(const uint32_t row, const uint32_t col) const {
|
||||
if (m_cur_samples(row, col) == 0) {
|
||||
return 0.0;
|
||||
/**
|
||||
* @brief Calculate and return the population standard deviation of every
|
||||
* pixel. Empty pixels return zero.
|
||||
*/
|
||||
NDArray<SUM_TYPE, 2> std() const {
|
||||
NDArray<SUM_TYPE, 2> res({m_rows, m_cols});
|
||||
for (uint32_t row = 0; row < m_rows; ++row) {
|
||||
for (uint32_t col = 0; col < m_cols; ++col) {
|
||||
res(row, col) = std(row, col);
|
||||
}
|
||||
}
|
||||
return m_sum2(row, col) / m_cur_samples(row, col) -
|
||||
mean(row, col) * mean(row, col);
|
||||
}
|
||||
|
||||
NDArray<SUM_TYPE, 2> variance() {
|
||||
NDArray<SUM_TYPE, 2> variance_array({m_rows, m_cols});
|
||||
for (uint32_t i = 0; i < m_rows * m_cols; i++) {
|
||||
variance_array(i / m_cols, i % m_cols) =
|
||||
variance(i / m_cols, i % m_cols);
|
||||
}
|
||||
return variance_array;
|
||||
}
|
||||
|
||||
NDArray<SUM_TYPE, 2> std() {
|
||||
NDArray<SUM_TYPE, 2> standard_deviation_array({m_rows, m_cols});
|
||||
for (uint32_t i = 0; i < m_rows * m_cols; i++) {
|
||||
standard_deviation_array(i / m_cols, i % m_cols) =
|
||||
std(i / m_cols, i % m_cols);
|
||||
}
|
||||
|
||||
return standard_deviation_array;
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Zero the moments, cached mean, and sample counts of every pixel.
|
||||
*/
|
||||
void clear() {
|
||||
m_sum = 0;
|
||||
m_sum2 = 0;
|
||||
m_cur_samples = 0;
|
||||
m_mean = 0;
|
||||
m_std = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Zero the moments, cached mean, and sample count at (row, col).
|
||||
* @pre row and col are valid pixel indices.
|
||||
*/
|
||||
void clear(const uint32_t row, const uint32_t col) {
|
||||
m_sum(row, col) = 0;
|
||||
m_sum2(row, col) = 0;
|
||||
m_cur_samples(row, col) = 0;
|
||||
m_mean(row, col) = 0;
|
||||
m_std(row, col) = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Accumulate or exponentially update every pixel and its cached
|
||||
* mean.
|
||||
* @param frame Frame whose shape must exactly match the pedestal.
|
||||
* @throws std::runtime_error if the shape differs.
|
||||
*/
|
||||
template <typename T> void push(NDView<T, 2> frame) {
|
||||
assert(frame.size() == m_rows * m_cols);
|
||||
|
||||
// TODO! move away from m_rows, m_cols
|
||||
if (frame.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
|
||||
throw std::runtime_error(
|
||||
@@ -125,11 +141,18 @@ template <typename SUM_TYPE = double> class Pedestal {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Push only pixels whose absolute difference from the cached mean is
|
||||
* strictly less than their threshold.
|
||||
* @param frame Frame whose shape must exactly match the pedestal.
|
||||
* @param threshold Per-pixel thresholds with the same shape as the
|
||||
* pedestal.
|
||||
* @throws std::runtime_error if either shape differs.
|
||||
* @note Rejected pixels keep their statistics and sample counts unchanged.
|
||||
*/
|
||||
template <typename T>
|
||||
void push_with_threshold(const NDView<T, 2> frame,
|
||||
const NDView<SUM_TYPE, 2> threshold) {
|
||||
assert(frame.size() == m_rows * m_cols);
|
||||
|
||||
// TODO! move away from m_rows, m_cols
|
||||
if (frame.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
|
||||
throw std::runtime_error(
|
||||
@@ -152,45 +175,43 @@ template <typename SUM_TYPE = double> class Pedestal {
|
||||
}
|
||||
|
||||
/**
|
||||
* Push but don't update the cached mean. Speeds up the process
|
||||
* when initializing the pedestal.
|
||||
*
|
||||
* @brief Accumulate or exponentially update every pixel from a Frame.
|
||||
* @tparam T Actual pixel type stored in frame; this is not runtime-checked.
|
||||
* @param frame Frame whose shape must exactly match the pedestal.
|
||||
* @throws std::runtime_error if the shape differs.
|
||||
*/
|
||||
template <typename T> void push_no_update(NDView<T, 2> frame) {
|
||||
assert(frame.size() == m_rows * m_cols);
|
||||
template <typename T> void push(Frame &frame) { push<T>(frame.view<T>()); }
|
||||
|
||||
// TODO! move away from m_rows, m_cols
|
||||
if (frame.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
|
||||
throw std::runtime_error(
|
||||
"Frame shape does not match pedestal shape");
|
||||
}
|
||||
|
||||
for (size_t row = 0; row < m_rows; row++) {
|
||||
for (size_t col = 0; col < m_cols; col++) {
|
||||
push_no_update<T>(row, col, frame(row, col));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T> void push(Frame &frame) {
|
||||
assert(frame.rows() == static_cast<size_t>(m_rows) &&
|
||||
frame.cols() == static_cast<size_t>(m_cols));
|
||||
push<T>(frame.view<T>());
|
||||
}
|
||||
|
||||
// getter functions
|
||||
/** @brief Return the number of image rows. */
|
||||
uint32_t rows() const { return m_rows; }
|
||||
uint32_t cols() const { return m_cols; }
|
||||
uint32_t n_samples() const { return m_samples; }
|
||||
NDArray<uint32_t, 2> cur_samples() const { return m_cur_samples; }
|
||||
NDArray<SUM_TYPE, 2> get_sum() const { return m_sum; }
|
||||
NDArray<SUM_TYPE, 2> get_sum2() const { return m_sum2; }
|
||||
|
||||
// pixel level operations (should be refactored to allow users to implement
|
||||
// their own pixel level operations)
|
||||
/** @brief Return the number of image columns. */
|
||||
uint32_t cols() const { return m_cols; }
|
||||
|
||||
/**
|
||||
* @brief Return the initialization sample count per pixel and steady-state
|
||||
* update-weight denominator.
|
||||
*/
|
||||
uint32_t n_samples() const { return m_samples; }
|
||||
|
||||
/**
|
||||
* @brief Return a copy of the per-pixel initialization sample counts.
|
||||
* @note Each count is in [0, n_samples] and does not change during
|
||||
* steady-state pushes. Thresholded pushes can leave counts unequal.
|
||||
*/
|
||||
NDArray<uint32_t, 2> cur_samples() const { return m_cur_samples; }
|
||||
|
||||
/**
|
||||
* @brief Accumulate or exponentially update one pixel and its cached mean.
|
||||
* @param row Pixel row.
|
||||
* @param col Pixel column.
|
||||
* @param val_ New pixel value, with weight 1 / n_samples after
|
||||
* initialization.
|
||||
* @pre row and col are valid pixel indices.
|
||||
*/
|
||||
template <typename T>
|
||||
void push(const uint32_t row, const uint32_t col, const T val_) {
|
||||
SUM_TYPE val = static_cast<SUM_TYPE>(val_);
|
||||
const auto val = static_cast<double>(val_);
|
||||
if (m_cur_samples(row, col) < m_samples) {
|
||||
m_sum(row, col) += val;
|
||||
m_sum2(row, col) += val * val;
|
||||
@@ -204,45 +225,16 @@ template <typename SUM_TYPE = double> class Pedestal {
|
||||
m_mean(row, col) = m_sum(row, col) / m_cur_samples(row, col);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void push_no_update(const uint32_t row, const uint32_t col, const T val_) {
|
||||
SUM_TYPE val = static_cast<SUM_TYPE>(val_);
|
||||
if (m_cur_samples(row, col) < m_samples) {
|
||||
m_sum(row, col) += val;
|
||||
m_sum2(row, col) += val * val;
|
||||
m_cur_samples(row, col)++;
|
||||
} else {
|
||||
m_sum(row, col) += val - m_sum(row, col) / m_cur_samples(row, col);
|
||||
m_sum2(row, col) +=
|
||||
val * val - m_sum2(row, col) / m_cur_samples(row, col);
|
||||
private:
|
||||
double variance(const uint32_t row, const uint32_t col) const {
|
||||
if (m_cur_samples(row, col) == 0) {
|
||||
return 0.0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Update the mean of the pedestal. This is used after having done
|
||||
* push_no_update. It is not necessary to call this function after push.
|
||||
*/
|
||||
void update_mean() { m_mean = m_sum / m_cur_samples; }
|
||||
|
||||
/**
|
||||
* @brief Refresh the cached std for all pixels from the current sums.
|
||||
* Kept separate from push() so pushes stay cheap; call before reading
|
||||
* cached_std() (analogous to update_mean()).
|
||||
*/
|
||||
void update_std() {
|
||||
for (uint32_t i = 0; i < m_rows * m_cols; i++) {
|
||||
m_std(i / m_cols, i % m_cols) = std(i / m_cols, i % m_cols);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void push_fast(const uint32_t row, const uint32_t col, const T val_) {
|
||||
// Assume we reached the steady state where all pixels have
|
||||
// m_samples samples
|
||||
SUM_TYPE val = static_cast<SUM_TYPE>(val_);
|
||||
m_sum(row, col) += val - m_sum(row, col) / m_samples;
|
||||
m_sum2(row, col) += val * val - m_sum2(row, col) / m_samples;
|
||||
m_mean(row, col) = m_sum(row, col) / m_samples;
|
||||
const auto mean = m_sum(row, col) / m_cur_samples(row, col);
|
||||
const auto var =
|
||||
m_sum2(row, col) / m_cur_samples(row, col) - mean * mean;
|
||||
// Roundoff in the moments can make a near-zero variance negative.
|
||||
return std::max(var, 0.0);
|
||||
}
|
||||
};
|
||||
} // namespace aare
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
#include "aare/utils/cuda_check.cuh"
|
||||
#include <cuda_runtime.h>
|
||||
#include <memory>
|
||||
|
||||
namespace aare {
|
||||
|
||||
template <typename T> struct CudaFreeDeleter {
|
||||
void operator()(T *p) const noexcept {
|
||||
if (p)
|
||||
cudaFree(p);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T> class DeviceBuffer {
|
||||
std::unique_ptr<T, CudaFreeDeleter<T>> m_ptr{nullptr};
|
||||
size_t m_n{0};
|
||||
|
||||
public:
|
||||
DeviceBuffer() = default;
|
||||
explicit DeviceBuffer(size_t N) : m_n{N} {
|
||||
T *raw_ptr = nullptr;
|
||||
CUDA_CHECK(cudaMalloc(&raw_ptr, m_n * sizeof(T)));
|
||||
m_ptr.reset(raw_ptr);
|
||||
}
|
||||
|
||||
DeviceBuffer(DeviceBuffer &&) noexcept = default;
|
||||
DeviceBuffer &operator=(DeviceBuffer &&) noexcept = default;
|
||||
|
||||
DeviceBuffer(const DeviceBuffer &) = delete;
|
||||
DeviceBuffer &operator=(const DeviceBuffer &) = delete;
|
||||
|
||||
T *get() const noexcept { return m_ptr.get(); }
|
||||
size_t size() const noexcept { return m_n; }
|
||||
size_t bytes() const noexcept { return m_n * sizeof(T); }
|
||||
};
|
||||
|
||||
struct StreamDeleter {
|
||||
void operator()(cudaStream_t s) const noexcept {
|
||||
if (s) {
|
||||
cudaStreamSynchronize(s);
|
||||
cudaStreamDestroy(s);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
using Stream = std::unique_ptr<CUstream_st, StreamDeleter>;
|
||||
|
||||
inline Stream make_stream() {
|
||||
cudaStream_t raw_ptr = nullptr;
|
||||
CUDA_CHECK(cudaStreamCreateWithFlags(&raw_ptr, cudaStreamNonBlocking));
|
||||
return Stream{raw_ptr};
|
||||
}
|
||||
|
||||
} // namespace aare
|
||||
@@ -0,0 +1,132 @@
|
||||
#pragma once
|
||||
#include "aare/defs.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstddef>
|
||||
#include <numeric>
|
||||
#include <optional>
|
||||
#include <stdexcept>
|
||||
#include <vector>
|
||||
|
||||
namespace aare {
|
||||
|
||||
class ROIGeometry; // forward declaration to avoid circular dependency
|
||||
class DetectorGeometry; // forward declaration to avoid circular dependency
|
||||
|
||||
struct ROI {
|
||||
ssize_t xmin{};
|
||||
ssize_t xmax{};
|
||||
ssize_t ymin{};
|
||||
ssize_t ymax{};
|
||||
|
||||
ssize_t height() const { return ymax - ymin; }
|
||||
ssize_t width() const { return xmax - xmin; }
|
||||
bool contains(ssize_t x, ssize_t y) const {
|
||||
return x >= xmin && x < xmax && y >= ymin && y < ymax;
|
||||
}
|
||||
|
||||
bool operator==(const ROI &other) const {
|
||||
return xmin == other.xmin && xmax == other.xmax && ymin == other.ymin &&
|
||||
ymax == other.ymax;
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Merge all consecutive ROIs in a vector into a single ROI.
|
||||
* @param rois vector of ROIs to merge
|
||||
* @return vector of merged ROIs
|
||||
* @tparam horizontally_aligned true if the ROIs are horizontally aligned, false
|
||||
* otherwise
|
||||
* @tparam vertically_aligned true if the ROIs are vertically aligned, false
|
||||
* otherwise
|
||||
*/
|
||||
template <bool horizontally_aligned = false, bool vertically_aligned = false>
|
||||
std::vector<ROI> merge_consecutive_rois(std::vector<ROI> &rois) {
|
||||
|
||||
if constexpr (horizontally_aligned && vertically_aligned) {
|
||||
throw std::runtime_error(
|
||||
LOCATION + "Vector of the same ROI? Cannot merge ROIs both "
|
||||
"horizontally and vertically at the same time.");
|
||||
}
|
||||
|
||||
if (rois.empty()) {
|
||||
return {};
|
||||
}
|
||||
if (rois.size() == 1) {
|
||||
return rois;
|
||||
}
|
||||
|
||||
auto merge_along_x = [](std::vector<ROI> in_rois) {
|
||||
std::sort(in_rois.begin(), in_rois.end(),
|
||||
[](const ROI &a, const ROI &b) {
|
||||
return (a.ymin != b.ymin) ? (a.ymin < b.ymin)
|
||||
: (a.xmin < b.xmin);
|
||||
}); // N log (N)
|
||||
|
||||
std::vector<ROI> merged_rois;
|
||||
merged_rois.reserve(in_rois.size());
|
||||
merged_rois.push_back(in_rois[0]);
|
||||
|
||||
for (size_t i = 1; i < in_rois.size(); ++i) {
|
||||
auto &last = merged_rois.back();
|
||||
const auto ¤t = in_rois[i];
|
||||
if (last.ymin == current.ymin && last.ymax == current.ymax &&
|
||||
last.xmax == current.xmin) {
|
||||
// merge
|
||||
last.xmax = current.xmax;
|
||||
} else {
|
||||
merged_rois.push_back(current);
|
||||
}
|
||||
}
|
||||
return merged_rois;
|
||||
};
|
||||
|
||||
auto merge_along_y = [](std::vector<ROI> in_rois) {
|
||||
std::sort(in_rois.begin(), in_rois.end(),
|
||||
[](const ROI &a, const ROI &b) {
|
||||
return (a.xmin != b.xmin) ? (a.xmin < b.xmin)
|
||||
: (a.ymin < b.ymin);
|
||||
});
|
||||
|
||||
std::vector<ROI> merged_rois;
|
||||
merged_rois.reserve(in_rois.size());
|
||||
merged_rois.push_back(in_rois[0]);
|
||||
|
||||
for (size_t i = 1; i < in_rois.size(); ++i) {
|
||||
auto &last = merged_rois.back();
|
||||
const auto ¤t = in_rois[i];
|
||||
if (last.xmin == current.xmin && last.xmax == current.xmax &&
|
||||
last.ymax == current.ymin) {
|
||||
last.ymax = current.ymax;
|
||||
} else {
|
||||
merged_rois.push_back(current);
|
||||
}
|
||||
}
|
||||
return merged_rois;
|
||||
};
|
||||
|
||||
if constexpr (horizontally_aligned) {
|
||||
return merge_along_y(rois); // one sort + one pass
|
||||
} else if constexpr (vertically_aligned) {
|
||||
return merge_along_x(rois); // one sort + one pass
|
||||
} else {
|
||||
return merge_along_y(merge_along_x(rois)); // generic case: two passes
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Check if the ROI covers the entire detector geometry
|
||||
* @param roi Region of interest
|
||||
* @param geometry Detector geometry
|
||||
* @return true if the ROI covers the entire detector geometry, false otherwise
|
||||
*/
|
||||
bool complete_ROI(const ROI &roi, const DetectorGeometry &geometry);
|
||||
|
||||
bool complete_ROI(const std::vector<ROI> &rois,
|
||||
const DetectorGeometry &geometry);
|
||||
|
||||
bool complete_ROI(const ROIGeometry &roi, const DetectorGeometry &geometry);
|
||||
|
||||
bool complete_ROI(const std::vector<ROIGeometry> &rois,
|
||||
const DetectorGeometry &geometry);
|
||||
|
||||
} // namespace aare
|
||||
@@ -1,6 +1,8 @@
|
||||
#pragma once
|
||||
#include "aare/DetectorGeometry.hpp"
|
||||
#include "aare/defs.hpp"
|
||||
#include "aare/ROI.hpp"
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace aare {
|
||||
|
||||
@@ -17,11 +19,6 @@ class ROIGeometry {
|
||||
*/
|
||||
ROIGeometry(const ROI &roi, DetectorGeometry &geometry);
|
||||
|
||||
/** @brief Constructor for ROI geometry expanding over full detector
|
||||
* @param geometry general detector geometry
|
||||
*/
|
||||
ROIGeometry(DetectorGeometry &geometry);
|
||||
|
||||
/// @brief Get number of modules in the ROI
|
||||
size_t num_modules_in_roi() const;
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/DetectorGeometry.hpp"
|
||||
#include "aare/FileInterface.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
#include "aare/NDArray.hpp" //for pixel map
|
||||
@@ -30,17 +29,18 @@ class RawFile : public FileInterface {
|
||||
RawMasterFile m_master;
|
||||
size_t m_current_frame{};
|
||||
|
||||
DetectorGeometry m_geometry;
|
||||
|
||||
/// @brief Geometries e.g. number of modules, size etc. for each ROI
|
||||
std::vector<ROIGeometry> m_ROI_geometries;
|
||||
|
||||
/// @brief Minimum frame count across the selected raw subfile series.
|
||||
size_t m_frames_in_file{};
|
||||
|
||||
public:
|
||||
/**
|
||||
* @brief RawFile constructor
|
||||
* @param fname path to the master file (.json)
|
||||
* @param mode file mode (only "r" is supported at the moment)
|
||||
|
||||
* @throws std::runtime_error if frame padding is disabled and the frame
|
||||
* discard policy is not DiscardPartial.
|
||||
*/
|
||||
RawFile(const std::filesystem::path &fname, const std::string &mode = "r");
|
||||
virtual ~RawFile() override = default;
|
||||
@@ -104,6 +104,7 @@ class RawFile : public FileInterface {
|
||||
size_t bytes_per_pixel() const;
|
||||
void seek(size_t frame_index) override;
|
||||
size_t tell() override;
|
||||
/// @brief Minimum actual frame count across all subfiles and ROIs.
|
||||
size_t total_frames() const override;
|
||||
size_t rows() const override;
|
||||
/**
|
||||
@@ -122,7 +123,7 @@ class RawFile : public FileInterface {
|
||||
size_t n_modules() const;
|
||||
|
||||
/**
|
||||
* @brief number of ROIs defined
|
||||
* @brief number of ROIs defined (always 1 for complete ROI)
|
||||
*/
|
||||
size_t num_rois() const;
|
||||
|
||||
@@ -150,6 +151,9 @@ class RawFile : public FileInterface {
|
||||
static DetectorHeader read_header(const std::filesystem::path &fname);
|
||||
|
||||
private:
|
||||
std::runtime_error frame_error(size_t frame_index,
|
||||
const std::string &message) const;
|
||||
|
||||
/**
|
||||
* @brief read the frame at the given frame index into the image buffer
|
||||
* @param frame_index frame number to read
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/defs.hpp"
|
||||
#include "aare/DetectorGeometry.hpp"
|
||||
#include "aare/ROI.hpp"
|
||||
#include <algorithm>
|
||||
#include <chrono>
|
||||
#include <filesystem>
|
||||
@@ -88,7 +89,8 @@ class RawMasterFile {
|
||||
std::optional<std::chrono::nanoseconds> m_exptime;
|
||||
std::chrono::nanoseconds m_period{0};
|
||||
|
||||
xy m_geometry{};
|
||||
/// @brief modules in x and y direction
|
||||
xy m_detector_layout{};
|
||||
xy m_udp_interfaces_per_module{1, 1};
|
||||
|
||||
size_t m_max_frames_per_file{};
|
||||
@@ -109,12 +111,28 @@ class RawMasterFile {
|
||||
std::optional<size_t> m_number_of_rows;
|
||||
std::optional<uint8_t> m_counter_mask;
|
||||
|
||||
std::optional<std::vector<ROI>> m_rois;
|
||||
/// @brief index of disabled UDP ports - index relative to UDP_port_types
|
||||
std::vector<size_t> m_disabled_udp_ports{};
|
||||
|
||||
/// @brief udp port types
|
||||
std::optional<std::vector<UDPPortPosition>> m_udp_port_types{};
|
||||
|
||||
/// @brief ROIs defined in master file or derived from disabled UDP ports
|
||||
std::vector<ROI> m_rois;
|
||||
|
||||
/// @brief Detector geometry - geometry for each module
|
||||
DetectorGeometry m_geometry{};
|
||||
|
||||
/// @brief ROI geometries
|
||||
std::vector<ROIGeometry> m_ROI_geometries;
|
||||
|
||||
public:
|
||||
RawMasterFile(const std::filesystem::path &fpath);
|
||||
RawMasterFile(std::istream &is, const std::string &fname); // for testing
|
||||
|
||||
/// @brief Get the filename including path of the master file.
|
||||
std::filesystem::path master_fname() const { return m_fnc.master_fname(); }
|
||||
|
||||
std::filesystem::path data_fname(size_t mod_id, size_t file_id) const;
|
||||
|
||||
const std::string &version() const; //!< For example "7.2"
|
||||
@@ -131,10 +149,14 @@ class RawMasterFile {
|
||||
const FrameDiscardPolicy &frame_discard_policy() const;
|
||||
|
||||
size_t total_frames_expected() const;
|
||||
xy geometry() const;
|
||||
xy detector_layout() const;
|
||||
size_t n_modules() const;
|
||||
uint8_t quad() const;
|
||||
|
||||
const DetectorGeometry &geometry() const;
|
||||
|
||||
const std::vector<ROIGeometry> &roi_geometries() const;
|
||||
|
||||
ReadoutMode get_reading_mode() const;
|
||||
|
||||
std::optional<size_t> analog_samples() const;
|
||||
@@ -143,9 +165,21 @@ class RawMasterFile {
|
||||
std::optional<size_t> number_of_rows() const;
|
||||
std::optional<uint8_t> counter_mask() const;
|
||||
|
||||
std::optional<std::vector<ROI>> rois() const;
|
||||
/// @brief Get the types of UDP ports
|
||||
/// @return Optional vector of UDP port types as strings (only present for
|
||||
/// masterfile version >= 8.1)
|
||||
std::optional<std::vector<UDPPortPosition>> udp_port_types() const;
|
||||
|
||||
std::optional<ROI> roi() const;
|
||||
/// @brief Get the indices of disabled UDP ports
|
||||
/// @return vector of indices of disabled UDP ports (empty if none are
|
||||
/// disabled)
|
||||
std::vector<size_t> disabled_udp_ports() const;
|
||||
|
||||
std::vector<ROI> rois() const;
|
||||
|
||||
/// @brief get roi for the case of a single ROI
|
||||
/// @return ROI object (complete ROI if no roi present in master file)
|
||||
ROI roi() const;
|
||||
|
||||
ScanParameters scan_parameters() const;
|
||||
|
||||
@@ -157,7 +191,8 @@ class RawMasterFile {
|
||||
private:
|
||||
void parse_json(std::istream &is);
|
||||
void parse_raw(std::istream &is);
|
||||
void update_rois_from_disabled_udp_ports();
|
||||
void retrieve_geometry();
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -84,7 +84,13 @@ class RawSubFile {
|
||||
|
||||
size_t frames_in_file() const { return m_total_frames; }
|
||||
|
||||
/// @brief Path of the current data file in the raw subfile series.
|
||||
std::filesystem::path current_path() const;
|
||||
|
||||
private:
|
||||
std::runtime_error frame_error(size_t frame_index,
|
||||
const std::string &message) const;
|
||||
|
||||
template <typename T> void read_with_map(std::byte *image_buf);
|
||||
|
||||
void parse_fname(const std::filesystem::path &fname);
|
||||
@@ -93,4 +99,4 @@ class RawSubFile {
|
||||
std::filesystem::path fpath(size_t file_index) const;
|
||||
};
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -0,0 +1,368 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp"
|
||||
#include "aare/FastPedestal.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/clusterfinder_kernel.cuh"
|
||||
#include "aare/utils/cuda_check.cuh"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cuda_runtime.h>
|
||||
#include <type_traits>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include "aare/RAII_device.hpp"
|
||||
|
||||
namespace aare::cuda {
|
||||
|
||||
/**
|
||||
* @brief The contract ClusterFinderCUDA<Algo> requires of its policies.
|
||||
*
|
||||
* C++17 has no concepts, so this list is the contract. It is documentation,
|
||||
* not machinery: a missing or misspelled member is reported clearly enough by
|
||||
* the compiler at the point of use. require_algo below asserts only the few
|
||||
* requirements that would otherwise compile and then misbehave at runtime.
|
||||
*
|
||||
* Ped (the pedestal model, e.g. CenteredRunningPedestal):
|
||||
* DevicePedT element type of the device arrays
|
||||
* Buffers owning, move-only, default-constructible
|
||||
* View non-owning pointers the kernel takes
|
||||
* Params per-launch pedestal scalars
|
||||
* HostImage host image of Buffers, ready to upload
|
||||
* Buffers allocate(size_t n_pixels)
|
||||
* View make_view(const Buffers &)
|
||||
* HostImage prepare_pedestal(FastPedestal<HostPedT> &) [template on HostPedT]
|
||||
* void upload_pedestal(const HostImage &, const Buffers &, cudaStream_t)
|
||||
* void download_mean(const Buffers &, size_t, std::vector<DevicePedT> &,
|
||||
* cudaStream_t)
|
||||
* void download_noise(const Buffers &, uint32_t, size_t,
|
||||
* std::vector<double> &, cudaStream_t)
|
||||
* The layout of View is between Ped and the kernel; the driver never reads it.
|
||||
*
|
||||
* Algo (the search algorithm, e.g. FixedWindow):
|
||||
* cluster_type, frame_type, pedestal pedestal must satisfy the above
|
||||
* LaunchParams per-launch algorithm scalars
|
||||
* Output owning, move-only device output
|
||||
* block Output Output::allocate(uint32_t max_clusters_per_frame) static
|
||||
* constexpr size_t Output::clusters_offset static size_t
|
||||
* Output::bytes_per_frame(uint32_t) device and host stride uint8_t *data()
|
||||
* const block base, for the D2H size_t bytes() const
|
||||
* uint32_t *count() const
|
||||
* cluster_type *clusters() const
|
||||
* uint32_t Output::host_count(const void *, uint32_t)
|
||||
* const cluster_type *Output::host_clusters(const void *)
|
||||
* void launch(const LaunchParams &, const pedestal::Params &,
|
||||
* const frame_type *, const pedestal::View &, const Output &,
|
||||
* cudaStream_t)
|
||||
*/
|
||||
namespace contract {
|
||||
|
||||
/// Only the requirements that fail *silently* are asserted. A missing type or
|
||||
/// a misspelled member already names itself at the point of use; a copyable
|
||||
/// Output does not, it compiles and double-frees a device pointer.
|
||||
template <class Algo> struct require_algo {
|
||||
using Ped = typename Algo::pedestal;
|
||||
using Output = typename Algo::Output;
|
||||
using Buffers = typename Ped::Buffers;
|
||||
|
||||
static_assert(std::is_move_constructible<Output>::value &&
|
||||
!std::is_copy_constructible<Output>::value,
|
||||
"Algo::Output owns device memory: it must be move-only.");
|
||||
static_assert(std::is_move_constructible<Buffers>::value &&
|
||||
!std::is_copy_constructible<Buffers>::value,
|
||||
"Ped::Buffers owns device memory: it must be move-only.");
|
||||
static_assert(std::is_trivially_copyable<typename Ped::View>::value,
|
||||
"Ped::View is passed to a kernel: it must be a trivially "
|
||||
"copyable bundle of pointers, owning nothing.");
|
||||
static_assert(
|
||||
std::is_same<decltype(Output::clusters_offset), const size_t>::value &&
|
||||
std::is_same<decltype(Output::bytes_per_frame(0)), size_t>::value,
|
||||
"Algo::Output must expose the block layout as 'static constexpr size_t "
|
||||
"clusters_offset' and 'static size_t bytes_per_frame(uint32_t)': the "
|
||||
"driver sizes its pinned host slots from them, before any Output "
|
||||
"exists.");
|
||||
|
||||
static constexpr bool value = true;
|
||||
};
|
||||
|
||||
} // namespace contract
|
||||
|
||||
/**
|
||||
* @brief Per-pixel running pedestal, kept centered on a frozen baseline.
|
||||
*
|
||||
* Four device arrays per pixel: the full mean, and the first and second
|
||||
* moments of Y = X - off, where `off` is a per-pixel baseline frozen for the
|
||||
* lifetime of an uploaded image. Centering keeps the accumulators O(rms)
|
||||
* instead of O(1e10), which is what makes the single-precision running update
|
||||
* the kernel performs safe. See prepare_pedestal() for the host side.
|
||||
*
|
||||
* The state is bound to the sequence of frames launched against it: each frame
|
||||
* sees what its predecessors left. Two streams must not share one Buffers.
|
||||
*
|
||||
* Stateless policy. Every function is static, Buffers is the only owning type,
|
||||
* and the caller supplies it.
|
||||
*/
|
||||
struct CenteredRunningPedestal {
|
||||
using DevicePedT = device::DEVICE_PED_TYPE;
|
||||
|
||||
struct Buffers {
|
||||
DeviceBuffer<DevicePedT> mean;
|
||||
DeviceBuffer<DevicePedT> sum;
|
||||
DeviceBuffer<DevicePedT> sum2;
|
||||
DeviceBuffer<DevicePedT> off;
|
||||
|
||||
Buffers() = default;
|
||||
explicit Buffers(size_t n_pixels)
|
||||
: mean{n_pixels}, sum{n_pixels}, sum2{n_pixels}, off{n_pixels} {}
|
||||
|
||||
Buffers(const Buffers &) = delete;
|
||||
Buffers &operator=(const Buffers &) = delete;
|
||||
|
||||
Buffers(Buffers &&o) noexcept = default;
|
||||
Buffers &operator=(Buffers &&o) noexcept = default;
|
||||
};
|
||||
|
||||
/// Non-owning. Every pointer is device memory owned by the caller.
|
||||
struct View {
|
||||
DevicePedT *d_pd_mean; ///< full mean = off + sum/n
|
||||
DevicePedT *d_pd_sum; ///< ~ n * E[Y], Y = X - off
|
||||
DevicePedT *d_pd_sum2; ///< ~ n * E[Y^2]
|
||||
const DevicePedT
|
||||
*d_pd_off; ///< frozen baseline, never written on device
|
||||
};
|
||||
|
||||
struct Params {
|
||||
uint32_t n_samples;
|
||||
};
|
||||
|
||||
/// Host image of the device pedestal arrays, ready to upload.
|
||||
struct HostImage {
|
||||
std::vector<DevicePedT> mean;
|
||||
std::vector<DevicePedT> sum;
|
||||
std::vector<DevicePedT> sum2;
|
||||
std::vector<DevicePedT> off;
|
||||
};
|
||||
|
||||
static Buffers allocate(size_t n_pixels) { return Buffers{n_pixels}; }
|
||||
|
||||
static View make_view(const Buffers &pedestal) {
|
||||
return View{pedestal.mean.get(), pedestal.sum.get(),
|
||||
pedestal.sum2.get(), pedestal.off.get()};
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a host pedestal into the centered device representation.
|
||||
*
|
||||
* The baseline X0 is the rounded host mean, so a re-prepare and re-upload
|
||||
* replace baseline and accumulators together and the device never rebases.
|
||||
*
|
||||
* Centering is done in double, where sum2 ~ n*E[X^2] is still exact, and
|
||||
* only the small centered results are narrowed to DevicePedT:
|
||||
* sum(X - X0) = sum(X) - n*X0
|
||||
* sum(X - X0)^2 = sum(X^2) - 2*X0*sum(X) + n*X0^2
|
||||
*
|
||||
* `mean` is deliberately NOT centered. It stays the full E[X] that the
|
||||
* kernel subtracts from a raw pixel every frame and writes back itself as
|
||||
* X0 + sum/n. At O(1e4) ADU float holds it comfortably; n*E[X^2] is the
|
||||
* term that would not survive.
|
||||
*/
|
||||
template <typename HostPedT>
|
||||
static HostImage prepare_pedestal(FastPedestal<HostPedT> &host) {
|
||||
NDArray<HostPedT, 2> h_mean = host.mean();
|
||||
// FastPedestal keeps both moments in double whatever HostPedT is, so
|
||||
// let the accessors name their own type here.
|
||||
auto h_sum = host.get_sum();
|
||||
auto h_sum2 = host.get_sum2();
|
||||
const size_t n_pixels = static_cast<size_t>(h_mean.size());
|
||||
const double n = static_cast<double>(host.n_samples());
|
||||
|
||||
HostImage img;
|
||||
img.mean.resize(n_pixels);
|
||||
img.sum.resize(n_pixels);
|
||||
img.sum2.resize(n_pixels);
|
||||
img.off.resize(n_pixels);
|
||||
for (size_t i = 0; i < n_pixels; ++i) {
|
||||
const double X0 =
|
||||
static_cast<double>(std::llround(h_mean.data()[i]));
|
||||
const double s = static_cast<double>(h_sum.data()[i]);
|
||||
const double s2 = static_cast<double>(h_sum2.data()[i]);
|
||||
img.off[i] = static_cast<DevicePedT>(X0);
|
||||
img.mean[i] = static_cast<DevicePedT>(h_mean.data()[i]);
|
||||
img.sum[i] = static_cast<DevicePedT>(s - n * X0);
|
||||
img.sum2[i] =
|
||||
static_cast<DevicePedT>(s2 - 2.0 * X0 * s + n * X0 * X0);
|
||||
}
|
||||
return img;
|
||||
}
|
||||
|
||||
/// Asynchronous H2D of a prepared image into one stream's buffers.
|
||||
static void upload_pedestal(const HostImage &h, const Buffers &d,
|
||||
cudaStream_t stream) {
|
||||
const size_t bytes = h.mean.size() * sizeof(DevicePedT);
|
||||
CUDA_CHECK(cudaMemcpyAsync(d.mean.get(), h.mean.data(), bytes,
|
||||
cudaMemcpyHostToDevice, stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d.sum.get(), h.sum.data(), bytes,
|
||||
cudaMemcpyHostToDevice, stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d.sum2.get(), h.sum2.data(), bytes,
|
||||
cudaMemcpyHostToDevice, stream));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d.off.get(), h.off.data(), bytes,
|
||||
cudaMemcpyHostToDevice, stream));
|
||||
}
|
||||
|
||||
/// Synchronous D2H of the device mean (the pedestal the kernel decides
|
||||
/// with). Waits for `stream` first so an in-flight update has landed.
|
||||
static void download_mean(const Buffers &d, size_t n_pixels,
|
||||
std::vector<DevicePedT> &out,
|
||||
cudaStream_t stream) {
|
||||
CUDA_CHECK(cudaStreamSynchronize(stream));
|
||||
out.resize(n_pixels);
|
||||
CUDA_CHECK(cudaMemcpy(out.data(), d.mean.get(),
|
||||
n_pixels * sizeof(DevicePedT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
}
|
||||
|
||||
/// Synchronous D2H of the device rms, computed as the kernel does:
|
||||
/// sqrt(max(E[Y^2] - E[Y]^2, 0)) with E[Y] = mean - off.
|
||||
static void download_noise(const Buffers &d, uint32_t n_samples,
|
||||
size_t n_pixels, std::vector<double> &out,
|
||||
cudaStream_t stream) {
|
||||
CUDA_CHECK(cudaStreamSynchronize(stream));
|
||||
std::vector<DevicePedT> h_mean(n_pixels), h_sum2(n_pixels),
|
||||
h_off(n_pixels);
|
||||
CUDA_CHECK(cudaMemcpy(h_mean.data(), d.mean.get(),
|
||||
n_pixels * sizeof(DevicePedT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
CUDA_CHECK(cudaMemcpy(h_sum2.data(), d.sum2.get(),
|
||||
n_pixels * sizeof(DevicePedT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
CUDA_CHECK(cudaMemcpy(h_off.data(), d.off.get(),
|
||||
n_pixels * sizeof(DevicePedT),
|
||||
cudaMemcpyDeviceToHost));
|
||||
const double n = static_cast<double>(n_samples);
|
||||
out.resize(n_pixels);
|
||||
for (size_t i = 0; i < n_pixels; ++i) {
|
||||
const double resid =
|
||||
static_cast<double>(h_mean[i]) - static_cast<double>(h_off[i]);
|
||||
const double var =
|
||||
static_cast<double>(h_sum2[i]) / n - resid * resid;
|
||||
out[i] = std::sqrt(std::max(var, 0.0));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Fixed-size window cluster search on the GPU.
|
||||
*
|
||||
* One thread per pixel evaluates a cluster_size_x by cluster_size_y window
|
||||
* around it from a shared-memory tile, with local-maximum suppression so an
|
||||
* event yields one cluster. Non-photon pixels feed a per-pixel running
|
||||
* pedestal that is updated in place, frame by frame, on the device.
|
||||
*
|
||||
* This struct is the search half of the GPU path: the shape of the output one
|
||||
* frame writes, and the launch itself. The pedestal model is a separate
|
||||
* policy, `Ped`. It owns nothing and holds no state; every function is static
|
||||
* and every buffer is supplied by the caller.
|
||||
*
|
||||
* Two ways to use it:
|
||||
* - through ClusterFinderCUDA<FixedWindow<...>>, which owns streams and
|
||||
* buffers and pipelines batches over them;
|
||||
* - directly, from code that manages its own device memory: allocate an
|
||||
* Output, build a Ped::View over your pedestal arrays, and call launch()
|
||||
* on your stream.
|
||||
*/
|
||||
template <typename ClusterType, typename FrameType = uint16_t,
|
||||
class Ped = CenteredRunningPedestal, int BLOCK_X = 16,
|
||||
int BLOCK_Y = 16>
|
||||
struct FixedWindow {
|
||||
static_assert(no_2x2_cluster<ClusterType>::value,
|
||||
"FixedWindow: both cluster dimensions must exceed 2");
|
||||
|
||||
using cluster_type = ClusterType;
|
||||
using frame_type = FrameType;
|
||||
using pedestal = Ped;
|
||||
|
||||
/// The output block one frame writes: a count word followed by the
|
||||
/// clusters, in one allocation. Owns the device copy and knows how to read
|
||||
/// a host copy of it. This is what a sparse finder replaces.
|
||||
struct Output {
|
||||
DeviceBuffer<uint8_t> d_block;
|
||||
|
||||
/// Byte offset of the cluster array: the count word, padded up to the
|
||||
/// cluster alignment. A property of the layout, not of an allocation.
|
||||
static constexpr size_t clusters_offset =
|
||||
(sizeof(uint32_t) + alignof(ClusterType) - 1) &
|
||||
~(alignof(ClusterType) - 1);
|
||||
|
||||
/// Per-frame stride, on the device and in a pinned host slot. Static so
|
||||
/// the driver can size its host slots before any Output exists.
|
||||
static constexpr size_t bytes_per_frame(uint32_t max_clusters) {
|
||||
return clusters_offset +
|
||||
static_cast<size_t>(max_clusters) * sizeof(ClusterType);
|
||||
}
|
||||
|
||||
static Output allocate(uint32_t max_clusters_per_frame) {
|
||||
return Output{
|
||||
DeviceBuffer<uint8_t>(bytes_per_frame(max_clusters_per_frame))};
|
||||
}
|
||||
|
||||
uint8_t *data() const { return d_block.get(); }
|
||||
size_t bytes() const { return d_block.bytes(); }
|
||||
|
||||
uint32_t *count() const {
|
||||
return reinterpret_cast<uint32_t *>(d_block.get());
|
||||
}
|
||||
|
||||
ClusterType *clusters() const {
|
||||
return reinterpret_cast<ClusterType *>(d_block.get() +
|
||||
clusters_offset);
|
||||
}
|
||||
|
||||
/// Readers for a host copy of one frame's block, used by the driver's
|
||||
/// collect(), collect_view() and materialize_slot().
|
||||
static uint32_t host_count(const void *h_block, uint32_t max_clusters) {
|
||||
// The device counter increments past the cap (only the write is
|
||||
// guarded), so this clamp is an out-of-bounds guard.
|
||||
return std::min(*reinterpret_cast<const uint32_t *>(h_block),
|
||||
max_clusters);
|
||||
}
|
||||
|
||||
static const ClusterType *host_clusters(const void *h_block) {
|
||||
return reinterpret_cast<const ClusterType *>(
|
||||
static_cast<const char *>(h_block) + clusters_offset);
|
||||
}
|
||||
};
|
||||
|
||||
struct LaunchParams {
|
||||
int32_t nrows, ncols;
|
||||
float nSigma;
|
||||
uint32_t max_clusters;
|
||||
};
|
||||
|
||||
/// Enqueue cluster finding for one frame on `stream`. Allocates nothing
|
||||
/// and synchronises nothing. The caller must have zeroed output.count().
|
||||
static void launch(const LaunchParams &lp, const typename Ped::Params &pp,
|
||||
const FrameType *d_frame, const typename Ped::View &pv,
|
||||
const Output &output, cudaStream_t stream) {
|
||||
constexpr int col_radius = ClusterType::cluster_size_x / 2;
|
||||
constexpr int row_radius = ClusterType::cluster_size_y / 2;
|
||||
constexpr size_t shmem_bytes = (BLOCK_X + 2 * col_radius) *
|
||||
(BLOCK_Y + 2 * row_radius) *
|
||||
sizeof(device::COMPUTE_TYPE);
|
||||
const dim3 block(BLOCK_X, BLOCK_Y);
|
||||
const dim3 grid(
|
||||
(static_cast<unsigned>(lp.ncols) + BLOCK_X - 1) / BLOCK_X,
|
||||
(static_cast<unsigned>(lp.nrows) + BLOCK_Y - 1) / BLOCK_Y);
|
||||
|
||||
device::find_clusters_in_single_frame<ClusterType, FrameType, BLOCK_X,
|
||||
BLOCK_Y>
|
||||
<<<grid, block, shmem_bytes, stream>>>(
|
||||
d_frame, pv.d_pd_mean, pv.d_pd_sum, pv.d_pd_sum2, pv.d_pd_off,
|
||||
pp.n_samples, lp.nSigma, lp.nrows, lp.ncols, output.clusters(),
|
||||
output.count(), lp.max_clusters);
|
||||
CUDA_CHECK(cudaGetLastError());
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace aare::cuda
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp"
|
||||
#include "aare/ClusterFinder.hpp"
|
||||
#include "aare/Cluster.hpp" // Cluster, no_2x2_cluster; nothing else from aare
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cuda_runtime.h>
|
||||
#include <type_traits>
|
||||
|
||||
@@ -14,8 +15,10 @@ using COMPUTE_TYPE = float;
|
||||
/// Device pedestal storage and running variance update. See COMPUTE_TYPE.
|
||||
using DEVICE_PED_TYPE = float;
|
||||
|
||||
/// BLOCK_X/BLOCK_Y must equal the launch block dims; they are template
|
||||
/// parameters so the shared-memory tile geometry is compile-time.
|
||||
template <typename ClusterType = Cluster<int32_t, 3, 3>,
|
||||
typename FRAME_TYPE = uint16_t,
|
||||
typename FRAME_TYPE = uint16_t, int BLOCK_X = 16, int BLOCK_Y = 16,
|
||||
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
|
||||
__global__ void find_clusters_in_single_frame(
|
||||
const FRAME_TYPE *__restrict__ d_frame,
|
||||
@@ -23,7 +26,7 @@ __global__ void find_clusters_in_single_frame(
|
||||
DEVICE_PED_TYPE *__restrict__ d_pd_sum,
|
||||
DEVICE_PED_TYPE *__restrict__ d_pd_sum2,
|
||||
const DEVICE_PED_TYPE *__restrict__ d_pd_off, const uint32_t n_pd_samples,
|
||||
const COMPUTE_TYPE m_nSigma, const size_t nrows, const size_t ncols,
|
||||
const COMPUTE_TYPE m_nSigma, const int32_t nrows, const int32_t ncols,
|
||||
// const uint64_t frame_number,
|
||||
ClusterType *d_clusters, uint32_t *d_cluster_count,
|
||||
const uint32_t max_clusters) {
|
||||
@@ -43,141 +46,80 @@ __global__ void find_clusters_in_single_frame(
|
||||
// constexpr int pow2_c2 = ((CSY + 1) / 2) * ((CSX + 1) / 2);
|
||||
constexpr int pow2_c3 = CSX * CSY;
|
||||
|
||||
// Thread/pixel mapping
|
||||
auto col_global =
|
||||
static_cast<ssize_t>(threadIdx.x + blockDim.x * blockIdx.x);
|
||||
auto row_global =
|
||||
static_cast<ssize_t>(threadIdx.y + blockDim.y * blockIdx.y);
|
||||
auto global_tid = static_cast<ssize_t>(col_global + ncols * row_global);
|
||||
auto local_tid = threadIdx.x + blockDim.x * threadIdx.y;
|
||||
// Outer stencil loop policy. Small windows are fully unrolled: at 3x3 the
|
||||
// kernel is a single latency-bound wave and needs every tap in flight, and
|
||||
// a rolled loop reloads the taps it could have kept in registers (nsys on
|
||||
// detector data: 4.32 -> 4.95 us). Large windows are rolled: unrolled 9x9
|
||||
// costs 96+ registers and caps occupancy at 2 blocks/SM. 25 taps is where
|
||||
// the register cost starts to bite (7x7 unrolled: 64-72 registers).
|
||||
constexpr int OUTER_UNROLL = (CSX * CSY <= 25) ? CSY : 1;
|
||||
|
||||
// ====================
|
||||
// Shared memory layout
|
||||
// ====================
|
||||
// The tile is laid out contiguously in a 1D configuration:
|
||||
// [0 ... tile_size-1] = pedestal-subtracted frame values
|
||||
//
|
||||
// Each tile has (blockDim.x + 2*col_radius) x (blockDim.y + 2*row_radius)
|
||||
// elements, with a halo of col_radius/row_radius pixels on each side.
|
||||
// Shared-memory tile: the block's pixels plus a halo of
|
||||
// col_radius/row_radius on each side, laid out row-major.
|
||||
constexpr int TILE_W = BLOCK_X + 2 * col_radius;
|
||||
constexpr int TILE_H = BLOCK_Y + 2 * row_radius;
|
||||
constexpr int TILE_SIZE = TILE_W * TILE_H;
|
||||
constexpr int N_THREADS = BLOCK_X * BLOCK_Y;
|
||||
|
||||
// Thread/pixel mapping. 32-bit signed: 64-bit integer math is emulated on
|
||||
// the GPU, and the bounds checks below rely on negative coordinates.
|
||||
const int col_global = static_cast<int>(threadIdx.x + BLOCK_X * blockIdx.x);
|
||||
const int row_global = static_cast<int>(threadIdx.y + BLOCK_Y * blockIdx.y);
|
||||
const int global_tid = col_global + ncols * row_global;
|
||||
const int local_tid = static_cast<int>(threadIdx.x + BLOCK_X * threadIdx.y);
|
||||
|
||||
// CUDA prefers raw bytes + aligned cast
|
||||
// Compile error happens when using: `extern __shared__ T sh[];`
|
||||
extern __shared__ __align__(sizeof(COMPUTE_TYPE)) unsigned char smem[];
|
||||
COMPUTE_TYPE *shmem = reinterpret_cast<COMPUTE_TYPE *>(smem);
|
||||
|
||||
// Stride includes halo on both sides
|
||||
auto shmem_stride = static_cast<int>(blockDim.x) + 2 * col_radius;
|
||||
auto tile_size =
|
||||
shmem_stride * (static_cast<int>(blockDim.y) + 2 * row_radius);
|
||||
|
||||
// Offset so that thread (0,0) maps to shared-memory position
|
||||
// (row_radius, col_radius) i.e. past the top-left halo.
|
||||
auto shmem_tid =
|
||||
(static_cast<int>(threadIdx.y) + row_radius) * shmem_stride +
|
||||
// This thread's own pixel in the tile (past the top-left halo)
|
||||
const int shmem_tid =
|
||||
(static_cast<int>(threadIdx.y) + row_radius) * TILE_W +
|
||||
(static_cast<int>(threadIdx.x) + col_radius);
|
||||
|
||||
// Cooperative zero-fill
|
||||
for (int idx = static_cast<int>(local_tid); idx < tile_size;
|
||||
idx += static_cast<int>(blockDim.x * blockDim.y)) {
|
||||
shmem[idx] = COMPUTE_TYPE{0};
|
||||
}
|
||||
__syncthreads();
|
||||
// ==========================================================
|
||||
// Cooperative tile load: interior, halo and OOB zeros in one pass
|
||||
// ==========================================================
|
||||
// Every thread strides over the flat tile, so the halo costs the same
|
||||
// per thread as the interior instead of being serialised on edge lanes.
|
||||
// Cells outside the frame are written as 0, which is what the stencil
|
||||
// expects and removes the need for a separate zero-fill + barrier.
|
||||
const int tile_row0 = static_cast<int>(BLOCK_Y * blockIdx.y) - row_radius;
|
||||
const int tile_col0 = static_cast<int>(BLOCK_X * blockIdx.x) - col_radius;
|
||||
|
||||
// OOB flag
|
||||
bool valid_pixel = col_global < static_cast<ssize_t>(ncols) &&
|
||||
row_global < static_cast<ssize_t>(nrows);
|
||||
|
||||
// ======================================================
|
||||
// Load pedestal-subtracted frame data into shared memory (MIXED PRECISION)
|
||||
// ======================================================
|
||||
|
||||
// Helper: read (frame - pedestal_mean) from global memory, or 0 if OOB.
|
||||
// gr, gc are the global row/col of the pixel to load.
|
||||
// Returns the pedestal-subtracted value.
|
||||
auto load_pixel = [&] __device__(ssize_t gr, ssize_t gc) -> COMPUTE_TYPE {
|
||||
auto gid = gc + ncols * gr;
|
||||
return static_cast<COMPUTE_TYPE>(d_frame[gid]) - d_pd_mean[gid];
|
||||
};
|
||||
|
||||
// A. Interior: every valid thread loads its own pixel
|
||||
if (valid_pixel) {
|
||||
shmem[shmem_tid] = load_pixel(row_global, col_global);
|
||||
}
|
||||
|
||||
// B. Halo regions (Boundaries)
|
||||
// B.1 Top rows of the halo
|
||||
if (threadIdx.y == 0 && valid_pixel) {
|
||||
for (int i = 1; i <= row_radius; ++i) {
|
||||
if (row_global - i >= 0)
|
||||
shmem[shmem_tid - i * shmem_stride] =
|
||||
load_pixel(row_global - i, col_global);
|
||||
}
|
||||
// Top-left corner rectangle
|
||||
if (threadIdx.x == 0) {
|
||||
for (int i = 1; i <= row_radius; ++i)
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (row_global - i >= 0 && col_global - j >= 0)
|
||||
shmem[shmem_tid - i * shmem_stride - j] =
|
||||
load_pixel(row_global - i, col_global - j);
|
||||
}
|
||||
// Top-right corner rectangle
|
||||
if (threadIdx.x == blockDim.x - 1) {
|
||||
for (int i = 1; i <= row_radius; ++i)
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (row_global - i >= 0 &&
|
||||
col_global + j < static_cast<ssize_t>(ncols))
|
||||
shmem[shmem_tid - i * shmem_stride + j] =
|
||||
load_pixel(row_global - i, col_global + j);
|
||||
// Two phases, loads then stores, so every warp pays ONE global round trip
|
||||
// for the whole tile instead of one per iteration. With a single loop the
|
||||
// warps that own a second cell (3 of 8 at 3x3) issued their second load
|
||||
// only after storing the first, and the rest of the block sat at the
|
||||
// barrier for that extra latency. N_ITER is 2 at 3x3 and 3 at 9x9.
|
||||
constexpr int N_ITER = (TILE_SIZE + N_THREADS - 1) / N_THREADS;
|
||||
COMPUTE_TYPE v[N_ITER];
|
||||
#pragma unroll
|
||||
for (int k = 0; k < N_ITER; ++k) {
|
||||
const int idx = local_tid + k * N_THREADS;
|
||||
const int tr = idx / TILE_W; // constexpr divisor: mul + shift
|
||||
const int tc = idx - tr * TILE_W;
|
||||
const int gr = tile_row0 + tr;
|
||||
const int gc = tile_col0 + tc;
|
||||
v[k] = COMPUTE_TYPE{0};
|
||||
if (idx < TILE_SIZE && gr >= 0 && gr < nrows && gc >= 0 && gc < ncols) {
|
||||
const int gid = gc + ncols * gr;
|
||||
v[k] = static_cast<COMPUTE_TYPE>(d_frame[gid]) - d_pd_mean[gid];
|
||||
}
|
||||
}
|
||||
|
||||
// B.2 Left column of the halo
|
||||
if (threadIdx.x == 0 && valid_pixel) {
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (col_global - j >= 0)
|
||||
shmem[shmem_tid - j] = load_pixel(row_global, col_global - j);
|
||||
#pragma unroll
|
||||
for (int k = 0; k < N_ITER; ++k) {
|
||||
const int idx = local_tid + k * N_THREADS;
|
||||
if (idx < TILE_SIZE)
|
||||
shmem[idx] = v[k];
|
||||
}
|
||||
|
||||
// B.3 Right column of the halo
|
||||
if (threadIdx.x == blockDim.x - 1 && valid_pixel) {
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (col_global + j < static_cast<ssize_t>(ncols))
|
||||
shmem[shmem_tid + j] = load_pixel(row_global, col_global + j);
|
||||
}
|
||||
|
||||
// B.4 Bottom rows of the halo
|
||||
if (threadIdx.y == blockDim.y - 1 && valid_pixel) {
|
||||
for (int i = 1; i <= row_radius; ++i) {
|
||||
if (row_global + i < static_cast<ssize_t>(nrows))
|
||||
shmem[shmem_tid + i * shmem_stride] =
|
||||
load_pixel(row_global + i, col_global);
|
||||
}
|
||||
// Bottom-left corner rectangle
|
||||
if (threadIdx.x == 0) {
|
||||
for (int i = 1; i <= row_radius; ++i)
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (row_global + i < static_cast<ssize_t>(nrows) &&
|
||||
col_global - j >= 0)
|
||||
shmem[shmem_tid + i * shmem_stride - j] =
|
||||
load_pixel(row_global + i, col_global - j);
|
||||
}
|
||||
// Bottom-right corner rectangle
|
||||
if (threadIdx.x == blockDim.x - 1) {
|
||||
for (int i = 1; i <= row_radius; ++i)
|
||||
for (int j = 1; j <= col_radius; ++j)
|
||||
if (row_global + i < static_cast<ssize_t>(nrows) &&
|
||||
col_global + j < static_cast<ssize_t>(ncols))
|
||||
shmem[shmem_tid + i * shmem_stride + j] =
|
||||
load_pixel(row_global + i, col_global + j);
|
||||
}
|
||||
}
|
||||
|
||||
__syncthreads();
|
||||
|
||||
// =====================
|
||||
// Cluster-finding logic
|
||||
// =====================
|
||||
if (!valid_pixel)
|
||||
if (col_global >= ncols || row_global >= nrows)
|
||||
return;
|
||||
|
||||
// Per-pixel variance from global pedestal arrays.
|
||||
@@ -187,17 +129,17 @@ __global__ void find_clusters_in_single_frame(
|
||||
// both O(rms), so this difference has no catastrophic cancellation even in
|
||||
// float — unlike the raw E[X^2] - E[X]^2 form, where X ~ 4600 makes both
|
||||
// terms ~2e7. NOTE: Keep thresholds squared to avoid one sqrtf() per pixel.
|
||||
DEVICE_PED_TYPE mean_px = d_pd_mean[global_tid];
|
||||
DEVICE_PED_TYPE resid = mean_px - d_pd_off[global_tid]; // E[Y] ~ O(1)
|
||||
DEVICE_PED_TYPE var_px =
|
||||
const DEVICE_PED_TYPE mean_px = d_pd_mean[global_tid];
|
||||
const DEVICE_PED_TYPE resid = mean_px - d_pd_off[global_tid]; // E[Y] ~ O(1)
|
||||
const DEVICE_PED_TYPE var_px =
|
||||
d_pd_sum2[global_tid] / static_cast<DEVICE_PED_TYPE>(n_pd_samples) -
|
||||
resid * resid;
|
||||
COMPUTE_TYPE rms_sq = static_cast<COMPUTE_TYPE>(
|
||||
const COMPUTE_TYPE rms_sq = static_cast<COMPUTE_TYPE>(
|
||||
var_px > DEVICE_PED_TYPE{0} ? var_px : DEVICE_PED_TYPE{0});
|
||||
COMPUTE_TYPE nSig_sq_rms_sq = m_nSigma * m_nSigma * rms_sq;
|
||||
const COMPUTE_TYPE nSig_sq_rms_sq = m_nSigma * m_nSigma * rms_sq;
|
||||
|
||||
// Pedestal-subtracted value of the center pixel (already in shmem)
|
||||
COMPUTE_TYPE val_pixel = shmem[shmem_tid];
|
||||
const COMPUTE_TYPE val_pixel = shmem[shmem_tid];
|
||||
|
||||
// Negative pedestal early exit:
|
||||
// val_pixel < -nSigma * rms
|
||||
@@ -218,11 +160,12 @@ __global__ void find_clusters_in_single_frame(
|
||||
// (ir>=0, ic<=0) PEDESTAL_TYPE br = PEDESTAL_TYPE{0}; // bottom-right
|
||||
// (ir>=0, ic>=0)
|
||||
|
||||
#pragma unroll
|
||||
// See OUTER_UNROLL above for why this is size-dependent.
|
||||
#pragma unroll OUTER_UNROLL
|
||||
for (int ir = -row_radius; ir <= row_radius; ++ir) {
|
||||
#pragma unroll
|
||||
for (int ic = -col_radius; ic <= col_radius; ++ic) {
|
||||
COMPUTE_TYPE val = shmem[shmem_tid + ir * shmem_stride + ic];
|
||||
COMPUTE_TYPE val = shmem[shmem_tid + ir * TILE_W + ic];
|
||||
|
||||
total += val;
|
||||
max_val = val > max_val ? val : max_val;
|
||||
@@ -289,18 +232,18 @@ __global__ void find_clusters_in_single_frame(
|
||||
// pedestal via push_fast(). In this kernel, the GPU updates all pixels in a
|
||||
// frame simultaneously. So the updated pedestal will only be used starting
|
||||
// from the next frame. -> This avoids a/serialization and b/global mem I/O.
|
||||
if (!is_photon && valid_pixel) {
|
||||
if (!is_photon) {
|
||||
// Update the CENTERED moments of Y = X - X0 (X0 = frozen baseline).
|
||||
// Both sum (~n*E[Y]) and sum2 (~n*E[Y^2]) stay O(rms)-scale, so the
|
||||
// running EMA and its float rounding never touch the ~1e10 magnitudes
|
||||
// the raw accumulators would reach. Reconstruct the full mean as
|
||||
// X0 + sum/n for the pedestal subtraction on the next frame.
|
||||
DEVICE_PED_TYPE X0 = d_pd_off[global_tid];
|
||||
DEVICE_PED_TYPE y =
|
||||
const DEVICE_PED_TYPE X0 = d_pd_off[global_tid];
|
||||
const DEVICE_PED_TYPE y =
|
||||
static_cast<DEVICE_PED_TYPE>(d_frame[global_tid]) - X0;
|
||||
DEVICE_PED_TYPE sum = d_pd_sum[global_tid];
|
||||
DEVICE_PED_TYPE sum2 = d_pd_sum2[global_tid];
|
||||
DEVICE_PED_TYPE n = static_cast<DEVICE_PED_TYPE>(n_pd_samples);
|
||||
const DEVICE_PED_TYPE n = static_cast<DEVICE_PED_TYPE>(n_pd_samples);
|
||||
|
||||
sum += y - sum / n;
|
||||
sum2 += y * y - sum2 / n;
|
||||
@@ -315,41 +258,34 @@ __global__ void find_clusters_in_single_frame(
|
||||
if (!is_photon) return; // Debugging
|
||||
*/
|
||||
|
||||
// Delay building clusterData until we know this thread will write a photon.
|
||||
// This avoids CSX*CSY conversions/rounds for the overwhelmingly common
|
||||
// background pixels.
|
||||
CT clusterData[CSX * CSY];
|
||||
int idx = 0;
|
||||
|
||||
#pragma unroll
|
||||
for (int ir = -row_radius; ir <= row_radius; ++ir) {
|
||||
#pragma unroll
|
||||
for (int ic = -col_radius; ic <= col_radius; ++ic) {
|
||||
COMPUTE_TYPE val = shmem[shmem_tid + ir * shmem_stride + ic];
|
||||
if constexpr (std::is_integral_v<CT>)
|
||||
clusterData[idx] = static_cast<CT>(lround(val));
|
||||
else
|
||||
clusterData[idx] = static_cast<CT>(val);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
|
||||
// Write cluster to global output buffer using atomic index
|
||||
// for coordination across all blocks
|
||||
// Claim an output slot (atomic index coordinates across all blocks)
|
||||
uint32_t write_idx = atomicAdd(d_cluster_count, 1u);
|
||||
|
||||
// Guard against overflowing the pre-allocated cluster buffer
|
||||
if (write_idx >= max_clusters)
|
||||
return;
|
||||
|
||||
ClusterType cluster{};
|
||||
cluster.x = static_cast<decltype(cluster.x)>(col_global);
|
||||
cluster.y = static_cast<decltype(cluster.y)>(row_global);
|
||||
// Convert straight from shmem into the global cluster. No local
|
||||
// CSX*CSY staging array: with the outer loop rolled it would be indexed
|
||||
// at runtime and land in local memory (328 B stack at 9x9).
|
||||
ClusterType *out = d_clusters + write_idx;
|
||||
out->x = static_cast<decltype(out->x)>(col_global);
|
||||
out->y = static_cast<decltype(out->y)>(row_global);
|
||||
CT *dst = reinterpret_cast<CT *>(&out->data);
|
||||
int idx = 0;
|
||||
|
||||
memcpy(reinterpret_cast<CT *>(&cluster.data), clusterData,
|
||||
sizeof(CT) * CSX * CSY);
|
||||
|
||||
d_clusters[write_idx] = cluster;
|
||||
#pragma unroll OUTER_UNROLL
|
||||
for (int ir = -row_radius; ir <= row_radius; ++ir) {
|
||||
#pragma unroll
|
||||
for (int ic = -col_radius; ic <= col_radius; ++ic) {
|
||||
COMPUTE_TYPE val = shmem[shmem_tid + ir * TILE_W + ic];
|
||||
if constexpr (std::is_integral_v<CT>)
|
||||
dst[idx] = static_cast<CT>(lround(val));
|
||||
else
|
||||
dst[idx] = static_cast<CT>(val);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace aare::device
|
||||
+15
-14
@@ -94,19 +94,6 @@ template <typename T> struct t_xy {
|
||||
};
|
||||
using xy = t_xy<uint32_t>;
|
||||
|
||||
struct ROI {
|
||||
ssize_t xmin{};
|
||||
ssize_t xmax{};
|
||||
ssize_t ymin{};
|
||||
ssize_t ymax{};
|
||||
|
||||
ssize_t height() const { return ymax - ymin; }
|
||||
ssize_t width() const { return xmax - xmin; }
|
||||
bool contains(ssize_t x, ssize_t y) const {
|
||||
return x >= xmin && x < xmax && y >= ymin && y < ymax;
|
||||
}
|
||||
};
|
||||
|
||||
/// @brief Chip specifications for Matterhorn1
|
||||
struct Matterhorn10 {
|
||||
constexpr static size_t nRows = 256;
|
||||
@@ -315,7 +302,21 @@ enum class corner : int {
|
||||
cBottomRight = 3
|
||||
};
|
||||
|
||||
enum class TimingMode { Auto, Trigger };
|
||||
enum class UDPPortPosition : uint8_t {
|
||||
LEFT = 0,
|
||||
RIGHT = 1,
|
||||
TOP = 2,
|
||||
BOTTOM = 3
|
||||
};
|
||||
|
||||
enum class TimingMode : uint8_t {
|
||||
AUTO_TIMING = 0,
|
||||
TRIGGER_EXPOSURE = 1,
|
||||
GATED = 2,
|
||||
BURST_TRIGGER = 3,
|
||||
TRIGGER_GATED = 4
|
||||
};
|
||||
|
||||
enum class FrameDiscardPolicy { NoDiscard, Discard, DiscardPartial };
|
||||
|
||||
using DataTypeVariants = std::variant<uint16_t, uint32_t>;
|
||||
|
||||
@@ -55,6 +55,14 @@ template <typename T> T string_to(const std::string &arg) {
|
||||
*/
|
||||
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
|
||||
@@ -79,4 +87,12 @@ template <> FrameDiscardPolicy string_to(const std::string &arg);
|
||||
*/
|
||||
template <> DACIndex string_to(const std::string &arg);
|
||||
|
||||
/**
|
||||
* @brief Convert a corner enum to string
|
||||
* @param arg corner enum value
|
||||
* @return string representation of the corner enum
|
||||
* @throw runtime_error if the corner value is invalid
|
||||
*/
|
||||
std::string to_string(const corner &arg);
|
||||
|
||||
} // namespace aare
|
||||
@@ -1,13 +1,14 @@
|
||||
#pragma once
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cuda_runtime.h>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
|
||||
inline void __cuda_check(cudaError_t err, const char *file, int line) {
|
||||
if (err != cudaSuccess) {
|
||||
std::fprintf(stderr, "[%s:%d] CUDA error: %s\n", file, line,
|
||||
cudaGetErrorString(err));
|
||||
std::exit(1);
|
||||
throw std::runtime_error((std::ostringstream{}
|
||||
<< "[CUDA ERROR] " << cudaGetErrorString(err)
|
||||
<< " at " << file << ":" << line)
|
||||
.str());
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -69,6 +69,7 @@ set(PYTHON_FILES
|
||||
aare/ClusterVector.py
|
||||
aare/Cluster.py
|
||||
aare/FastPedestal.py
|
||||
aare/Pedestal.py
|
||||
aare/calibration.py
|
||||
aare/factory.py
|
||||
aare/experimental.py
|
||||
|
||||
+118
-20
@@ -18,17 +18,33 @@ def _get_class(name, cluster_size, dtype):
|
||||
|
||||
|
||||
|
||||
def ClusterFinder(image_size, cluster_size=(3,3), n_sigma=5, dtype = np.int32, capacity = 1024):
|
||||
def ClusterFinder(image_size, *, cluster_size=(3,3), n_sigma=5, dtype = np.int32, capacity = 1024, min_pedestal_samples = 1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinder object. Provides a cleaner syntax for
|
||||
the templated ClusterFinder in C++.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image_size : tuple
|
||||
The size of the image as a tuple (height, width).
|
||||
cluster_size : tuple, optional
|
||||
The size of the cluster to find as a tuple (height, width). Default is (3,3).
|
||||
n_sigma : int, optional
|
||||
Multiplier of the standard deviation used as a threshold to identify potential photon pixels. Default is 5.
|
||||
dtype : data-type, optional
|
||||
The data type of the image. Default is np.int32.
|
||||
capacity : int, optional
|
||||
The maximum number of clusters than can be stored before reallocating. Default is 1024.
|
||||
min_pedestal_samples : int, optional
|
||||
The minimum number of pedestal samples to accumulate before using the pedestal. Default is 1000.
|
||||
"""
|
||||
cls = _get_class("ClusterFinder", cluster_size, dtype)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, min_pedestal_samples=min_pedestal_samples)
|
||||
|
||||
|
||||
|
||||
def ClusterFinderFrozen(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int32, capacity=1024):
|
||||
def ClusterFinderFrozen(image_size, *, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
capacity=1024, min_pedestal_samples=1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinderFrozen object.
|
||||
|
||||
@@ -37,19 +53,40 @@ def ClusterFinderFrozen(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int3
|
||||
pedestal updates are deferred to the end of the frame). This mirrors the CUDA
|
||||
kernel's per-frame update model, so running it against ClusterFinderCUDA
|
||||
isolates pedestal-update timing as the sole variable.
|
||||
|
||||
min_pedestal_samples matches ClusterFinder so the twins warm up identically;
|
||||
a comparison run must pass the same value to both.
|
||||
"""
|
||||
cls = _get_class("ClusterFinderFrozen", cluster_size, dtype)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity,
|
||||
min_pedestal_samples=min_pedestal_samples)
|
||||
|
||||
|
||||
def ClusterFinderMT(image_size, cluster_size = (3,3), dtype=np.int32, n_sigma=5, capacity = 1024, n_threads = 3):
|
||||
def ClusterFinderMT(image_size, *, cluster_size = (3,3), dtype=np.int32, n_sigma=5, capacity = 1024, n_threads = 3, min_pedestal_samples = 1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinderMT object. Provides a cleaner syntax for
|
||||
the templated ClusterFinderMT in C++.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
image_size : tuple
|
||||
The size of the image as a tuple (height, width).
|
||||
cluster_size : tuple, optional
|
||||
The size of the cluster to find as a tuple (height, width). Default is (3,3).
|
||||
n_sigma : int, optional
|
||||
Multiplier of the standard deviation used as a threshold to identify potential photon pixels. Default is 5.
|
||||
dtype : data-type, optional
|
||||
The data type of the image. Default is np.int32.
|
||||
capacity : int, optional
|
||||
The maximum number of clusters than can be stored before reallocating. Default is 1024.
|
||||
n_threads : int, optional
|
||||
The number of threads to use for processing. Default is 3.
|
||||
min_pedestal_samples : int, optional
|
||||
The minimum number of pedestal samples to accumulate before using the pedestal. Default is 1000.
|
||||
"""
|
||||
|
||||
cls = _get_class("ClusterFinderMT", cluster_size, dtype)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, n_threads=n_threads)
|
||||
return cls(image_size, n_sigma=n_sigma, capacity=capacity, min_pedestal_samples=min_pedestal_samples, n_threads=n_threads)
|
||||
|
||||
|
||||
def _cuda_available():
|
||||
@@ -57,8 +94,15 @@ def _cuda_available():
|
||||
return hasattr(_aare, "ClusterFinderCUDA_Cluster3x3i")
|
||||
|
||||
|
||||
def ClusterFinderCUDA(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
# GPU algorithm name -> suffix of the bound C++ class. The C++ driver is
|
||||
# templated on the algorithm (see clusterfinder_algo.cuh); each one is bound as
|
||||
# its own class and selected here, so users never see the template.
|
||||
_CUDA_ALGORITHMS = {"fixed_window": ""}
|
||||
|
||||
|
||||
def ClusterFinderCUDA(image_size, *, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
max_clusters_per_frame=2048, n_streams=4,
|
||||
min_pedestal_samples=1000, algorithm="fixed_window",
|
||||
time_kernels=False):
|
||||
"""
|
||||
Factory function to create a ClusterFinderCUDA object. Provides a cleaner
|
||||
@@ -81,6 +125,14 @@ def ClusterFinderCUDA(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
but as tight as possible to minimize PCIe traffic. Default 2048.
|
||||
n_streams : int, optional
|
||||
Number of CUDA streams for H2D/kernel/D2H pipelining. Default 4.
|
||||
min_pedestal_samples : int, optional
|
||||
Frames the host pedestal accumulates before it is ready, and the
|
||||
reciprocal of the steady-state update weight. Matches ClusterFinder so
|
||||
a CPU/GPU comparison warms up identically. Default 1000.
|
||||
algorithm : str, optional
|
||||
GPU algorithm. "fixed_window" (default): a cluster_size window around
|
||||
each pixel with local-maximum suppression. Memory and streams are
|
||||
managed internally whichever algorithm is chosen.
|
||||
time_kernels : bool, optional
|
||||
Enable per-frame CUDA-event kernel timing, exposed via
|
||||
avg_kernel_time_ms(). Off by default because it adds two event records
|
||||
@@ -117,11 +169,17 @@ def ClusterFinderCUDA(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
"Rebuild with -DAARE_CUDA=ON (and -DAARE_PYTHON_BINDINGS=ON)."
|
||||
)
|
||||
|
||||
cls = _get_class("ClusterFinderCUDA", cluster_size, dtype)
|
||||
if algorithm not in _CUDA_ALGORITHMS:
|
||||
raise ValueError(
|
||||
f"Unknown CUDA algorithm {algorithm!r}; "
|
||||
f"choose from {sorted(_CUDA_ALGORITHMS)}")
|
||||
cls = _get_class("ClusterFinderCUDA" + _CUDA_ALGORITHMS[algorithm],
|
||||
cluster_size, dtype)
|
||||
return cls(image_size,
|
||||
n_sigma=n_sigma,
|
||||
max_clusters_per_frame=max_clusters_per_frame,
|
||||
n_streams=n_streams,
|
||||
min_pedestal_samples=min_pedestal_samples,
|
||||
time_kernels=time_kernels)
|
||||
|
||||
def find_cluster_views_batched_iter(cf, frames, first_frame=0, chunk=None):
|
||||
@@ -187,8 +245,9 @@ def find_cluster_views_batched_iter(cf, frames, first_frame=0, chunk=None):
|
||||
view.release()
|
||||
|
||||
|
||||
def ClusterFinderCUDAGraph(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
max_clusters_per_frame=2048, n_streams=4):
|
||||
def ClusterFinderCUDAGraph(image_size, *, cluster_size=(3,3), n_sigma=5, dtype=np.int32,
|
||||
max_clusters_per_frame=2048, n_streams=4,
|
||||
min_pedestal_samples=1000):
|
||||
"""
|
||||
Factory function to create a ClusterFinderCUDAGraph object. Uses pre-recorded
|
||||
CUDA Graphs to reduce per-frame CPU API overhead (~23 µs vs ~31 µs for the
|
||||
@@ -209,6 +268,8 @@ def ClusterFinderCUDAGraph(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.i
|
||||
Hard upper bound on clusters per frame. Default 2048.
|
||||
n_streams : int, optional
|
||||
Number of CUDA streams (one graph per stream). Default 4.
|
||||
min_pedestal_samples : int, optional
|
||||
Frames the host pedestal accumulates before it is ready. Default 1000.
|
||||
|
||||
Note
|
||||
----
|
||||
@@ -225,7 +286,8 @@ def ClusterFinderCUDAGraph(image_size, cluster_size=(3,3), n_sigma=5, dtype=np.i
|
||||
return cls(image_size,
|
||||
n_sigma=n_sigma,
|
||||
max_clusters_per_frame=max_clusters_per_frame,
|
||||
n_streams=n_streams)
|
||||
n_streams=n_streams,
|
||||
min_pedestal_samples=min_pedestal_samples)
|
||||
|
||||
|
||||
def ClusterCollector(clusterfindermt, dtype=np.int32):
|
||||
@@ -248,19 +310,55 @@ def ClusterFileSink(clusterfindermt, cluster_file, dtype=np.int32):
|
||||
|
||||
|
||||
def ClusterFile(fname, cluster_size=(3,3), dtype=np.int32, chunk_size = 1000, mode = "r"):
|
||||
"""
|
||||
Factory function to create a ClusterFile object. Provides a cleaner syntax for
|
||||
the templated ClusterFile in C++.
|
||||
"""Create a reader or writer for a binary cluster file.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
fname : path-like
|
||||
Cluster file to open.
|
||||
cluster_size : tuple[int, int], default=(3, 3)
|
||||
Cluster dimensions stored in the file.
|
||||
dtype : numpy dtype, default=numpy.int32
|
||||
Data type of the cluster values stored in the file.
|
||||
chunk_size : int, default=1000
|
||||
Maximum number of selected clusters returned by ``chunks()`` and
|
||||
default iteration. Must be positive when iterating over chunks.
|
||||
mode : {"r", "w", "a"}, default="r"
|
||||
Open for reading, truncate and write, or append, respectively.
|
||||
|
||||
Returns
|
||||
-------
|
||||
ClusterFile
|
||||
The compiled ClusterFile specialization matching ``cluster_size`` and
|
||||
``dtype``.
|
||||
|
||||
Notes
|
||||
-----
|
||||
The file format contains no cluster shape or data-type metadata. Supplying
|
||||
values that do not match the file causes its bytes to be interpreted
|
||||
incorrectly. Use ``frames()`` to iterate over complete frames, including
|
||||
empty or fully filtered frames with their stored frame numbers. Use
|
||||
``chunks()`` or ``chunks(chunk_size)`` to iterate over selected clusters
|
||||
in batches. Chunks may combine frames, so their frame number is not
|
||||
reliable per-cluster metadata.
|
||||
|
||||
Iterators consume the current file position without rewinding; use one
|
||||
traversal at a time. Each result owns its storage and remains valid after
|
||||
advancing the iterator or closing the file.
|
||||
|
||||
Examples
|
||||
--------
|
||||
|
||||
.. code-block:: python
|
||||
|
||||
from aare import ClusterFile
|
||||
|
||||
with ClusterFile("clusters.clust", cluster_size=(3,3), dtype=np.int32) as cf:
|
||||
# cf is now a ClusterFile_Cluster3x3i object but you don't need to know that.
|
||||
for clusters in cf:
|
||||
# Loop over clusters in chunks of 1000
|
||||
# The type of clusters will be a ClusterVector_Cluster3x3i in this case
|
||||
|
||||
with ClusterFile(
|
||||
"clusters.clust", cluster_size=(3, 3), dtype=np.int32
|
||||
) as cf:
|
||||
for clusters in cf.chunks():
|
||||
# Process clusters in chunks of at most 1000.
|
||||
...
|
||||
|
||||
"""
|
||||
|
||||
|
||||
@@ -7,16 +7,33 @@ from .ClusterFinder import _get_class
|
||||
|
||||
def ClusterVector(cluster_size=(3,3), dtype = np.int32):
|
||||
"""
|
||||
Factory function to create a ClusterVector object. Provides a cleaner syntax for
|
||||
the templated ClusterVector in C++.
|
||||
Create an empty ClusterVector for a supported cluster size and pixel dtype.
|
||||
|
||||
.. code-block:: python
|
||||
Parameters
|
||||
----------
|
||||
cluster_size : tuple[int, int], default=(3, 3)
|
||||
Cluster dimensions in the x and y directions.
|
||||
dtype : numpy.dtype, default=numpy.int32
|
||||
Pixel storage type. The cluster size and dtype combination must have a
|
||||
compiled binding.
|
||||
|
||||
from aare import ClusterVector
|
||||
|
||||
ClusterVector(cluster_size=(3,3), dtype=np.float64)
|
||||
Returns
|
||||
-------
|
||||
ClusterVector
|
||||
An empty vector with frame number 0 and space reserved for at least
|
||||
1024 clusters.
|
||||
|
||||
Raises
|
||||
------
|
||||
ValueError
|
||||
If the requested size and dtype combination is unavailable.
|
||||
|
||||
Examples
|
||||
--------
|
||||
>>> import numpy as np
|
||||
>>> from aare import ClusterVector
|
||||
>>> clusters = ClusterVector(cluster_size=(3, 3), dtype=np.float64)
|
||||
"""
|
||||
|
||||
cls = _get_class("ClusterVector", cluster_size, dtype)
|
||||
return cls()
|
||||
|
||||
@@ -22,7 +22,7 @@ def FastPedestal(rows, cols, n_samples=1000, dtype=np.float64):
|
||||
cols: Number of image columns.
|
||||
n_samples: Initialization frame count and steady-state update-weight
|
||||
denominator.
|
||||
dtype: Output dtype for the mean, variance, and standard deviation.
|
||||
dtype: Output dtype for the mean and standard deviation.
|
||||
Supported values are ``np.float64``, ``np.float32``, and
|
||||
``np.int16``.
|
||||
"""
|
||||
@@ -41,7 +41,7 @@ def from_file(filename, n_samples=1000, skip_first=0, dtype=np.float64):
|
||||
filename: Input image file.
|
||||
n_samples: Number of frames used for initialization.
|
||||
skip_first: Number of leading frames to ignore.
|
||||
dtype: Output dtype for the mean, variance, and standard deviation.
|
||||
dtype: Output dtype for the mean and standard deviation.
|
||||
|
||||
Raises:
|
||||
RuntimeError: If fewer than ``n_samples`` frames remain after
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
import numpy as np
|
||||
|
||||
from .factory import _get_typed_class
|
||||
|
||||
|
||||
def Pedestal(rows, cols, n_samples=1000, dtype=np.float64):
|
||||
"""Create an empty per-pixel running pedestal.
|
||||
|
||||
This factory hides the dtype suffix used by the templated C++ bindings.
|
||||
Call ``push()`` to update the statistics and cached mean for each frame.
|
||||
Statistics are available during initialization and are zero for empty pixels.
|
||||
Internal moments and variance always use double precision.
|
||||
|
||||
Args:
|
||||
rows: Number of image rows.
|
||||
cols: Number of image columns.
|
||||
n_samples: Number of samples accumulated before switching to
|
||||
steady-state updates with weight ``1 / n_samples``.
|
||||
dtype: Output dtype for the mean and standard deviation.
|
||||
Supported values are ``np.float64``, ``np.float32``, and
|
||||
``np.int16``.
|
||||
"""
|
||||
cls = _get_typed_class("Pedestal", dtype)
|
||||
return cls(rows, cols, n_samples)
|
||||
@@ -43,7 +43,7 @@ class RawFile(_aare.RawFile):
|
||||
Returns:
|
||||
int: Number of frames in file.
|
||||
"""
|
||||
return super().frames_in_file
|
||||
return self.total_frames
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
@@ -39,15 +39,18 @@ from ._aare import (
|
||||
RawSubFile,
|
||||
)
|
||||
from ._aare import Pedestal_d, Pedestal_f, ClusterFinder_Cluster3x3i, VarClusterFinder
|
||||
from ._aare import DetectorType, ReadoutMode
|
||||
from ._aare import DetectorType, FrameDiscardPolicy, ReadoutMode
|
||||
from ._aare import hitmap
|
||||
from ._aare import ROI
|
||||
from ._aare import corner
|
||||
|
||||
from ._aare import UDPPortPosition
|
||||
|
||||
# from ._aare import ClusterFinderMT, ClusterCollector, ClusterFileSink, ClusterVector_i
|
||||
|
||||
from ._version import __version__
|
||||
from .FastPedestal import FastPedestal
|
||||
from .Pedestal import Pedestal
|
||||
from .ClusterFinder import (ClusterFinder, ClusterFinderFrozen, ClusterCollector, ClusterFinderMT, ClusterFileSink, ClusterFile,
|
||||
ClusterFinderCUDA, ClusterFinderCUDAGraph, _cuda_available, find_cluster_views_batched_iter)
|
||||
from .ClusterVector import ClusterVector
|
||||
|
||||
@@ -5,9 +5,12 @@ def load_calibration(fname, hg0=False):
|
||||
"""
|
||||
Load calibration data from a file.
|
||||
|
||||
Parameters:
|
||||
fname (str): Path to the calibration file.
|
||||
hg0 (bool): If True, load HG0 calibration data instead of G0.
|
||||
Parameters
|
||||
----------
|
||||
fname : str
|
||||
Path to the calibration file.
|
||||
hg0 : bool
|
||||
If True, load HG0 calibration data instead of G0.
|
||||
|
||||
"""
|
||||
gains = 3
|
||||
|
||||
+44
-14
@@ -37,7 +37,6 @@ void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
return cluster;
|
||||
}))
|
||||
|
||||
// TODO! Review if to keep or not
|
||||
.def_property_readonly(
|
||||
"data",
|
||||
[](Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType> &c)
|
||||
@@ -60,6 +59,26 @@ void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
.def_readonly("y",
|
||||
&Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType>::y)
|
||||
|
||||
.def("__repr__",
|
||||
[class_name](const Cluster<Type, ClusterSizeX, ClusterSizeY,
|
||||
CoordType> &self) {
|
||||
fmt::memory_buffer data;
|
||||
fmt::format_to(std::back_inserter(data), "[[");
|
||||
for (size_t i = 0; i < self.data.size(); ++i) {
|
||||
if (i != 0) {
|
||||
fmt::format_to(std::back_inserter(data),
|
||||
i % ClusterSizeX == 0 ? "], [" : ", ");
|
||||
}
|
||||
fmt::format_to(std::back_inserter(data), "{}",
|
||||
self.data[i]);
|
||||
}
|
||||
fmt::format_to(std::back_inserter(data), "]]");
|
||||
|
||||
return fmt::format("{}(x={}, y={}, data={})", class_name,
|
||||
self.x, self.y,
|
||||
fmt::string_view(data.data(), data.size()));
|
||||
})
|
||||
|
||||
.def(
|
||||
"max_sum_2x2",
|
||||
[](Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType> &self) {
|
||||
@@ -67,8 +86,16 @@ void define_Cluster(py::module &m, const std::string &typestr) {
|
||||
return py::make_tuple(max_sum.sum,
|
||||
static_cast<int>(max_sum.index));
|
||||
},
|
||||
R"(calculates sum of 2x2 subcluster with highest energy and index relative to cluster center 0: top_left, 1: top_right, 2: bottom_left, 3: bottom_right
|
||||
)");
|
||||
R"doc(
|
||||
Return the highest-sum center-adjacent 2x2 subcluster.
|
||||
|
||||
Returns
|
||||
-------
|
||||
tuple
|
||||
``(sum, index)``, where index is 0 for top-left, 1 for
|
||||
top-right, 2 for bottom-left, or 3 for bottom-right relative to
|
||||
the cluster center.
|
||||
)doc");
|
||||
}
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
@@ -80,7 +107,14 @@ void reduce_to_3x3(py::module &m) {
|
||||
[](const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
|
||||
return reduce_to_3x3(cl);
|
||||
},
|
||||
py::return_value_policy::move, R"(Reduce cluster to 3x3 subcluster)");
|
||||
py::return_value_policy::move, py::arg("cluster"), R"doc(
|
||||
Return the 3x3 block around the cluster's center index.
|
||||
|
||||
Both input dimensions must be at least 3, and at least one must be
|
||||
greater than 3.
|
||||
The input coordinates are preserved and output data is stored in
|
||||
row-major order.
|
||||
)doc");
|
||||
}
|
||||
|
||||
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
@@ -92,16 +126,12 @@ void reduce_to_2x2(py::module &m) {
|
||||
[](const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
|
||||
return reduce_to_2x2(cl);
|
||||
},
|
||||
py::return_value_policy::move,
|
||||
R"(
|
||||
Reduce cluster to 2x2 subcluster by taking the 2x2 subcluster with
|
||||
the highest photon energy.
|
||||
py::return_value_policy::move, py::arg("cluster"), R"doc(
|
||||
Return the highest-sum center-adjacent 2x2 block.
|
||||
|
||||
RETURN:
|
||||
|
||||
reduced cluster (cluster is filled in row major ordering starting at the top left. Thus for a max subcluster in the top left corner the photon hit is at the fourth position.)
|
||||
|
||||
)");
|
||||
The input coordinates are preserved and output data is stored in
|
||||
row-major order.
|
||||
)doc");
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
#pragma GCC diagnostic pop
|
||||
+123
-28
@@ -11,6 +11,7 @@
|
||||
#include <pybind11/stl.h>
|
||||
#include <pybind11/stl/filesystem.h>
|
||||
#include <string>
|
||||
#include <utility>
|
||||
|
||||
// Disable warnings for unused parameters, as we ignore some
|
||||
// in the __exit__ method
|
||||
@@ -20,18 +21,90 @@
|
||||
namespace py = pybind11;
|
||||
using namespace ::aare;
|
||||
|
||||
template <typename Range> class ClusterFileIterator {
|
||||
Range m_range;
|
||||
std::optional<typename Range::Iterator> m_iterator;
|
||||
bool m_done{false};
|
||||
|
||||
public:
|
||||
explicit ClusterFileIterator(Range range) : m_range(std::move(range)) {}
|
||||
|
||||
typename Range::Iterator::value_type next() {
|
||||
if (m_done) {
|
||||
throw py::stop_iteration();
|
||||
}
|
||||
// Advance before returning the next result, never after yielding it.
|
||||
if (m_iterator) {
|
||||
++*m_iterator;
|
||||
} else {
|
||||
m_iterator.emplace(m_range.begin());
|
||||
}
|
||||
if (*m_iterator == m_range.end()) {
|
||||
m_done = true;
|
||||
throw py::stop_iteration();
|
||||
}
|
||||
return std::move(**m_iterator);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Iterator>
|
||||
void define_cluster_file_iterator(py::module &m, const std::string &name) {
|
||||
py::class_<Iterator>(m, name.c_str())
|
||||
.def(
|
||||
"__iter__", [](Iterator &self) -> Iterator & { return self; },
|
||||
py::return_value_policy::reference_internal)
|
||||
.def("__next__", &Iterator::next);
|
||||
}
|
||||
|
||||
template <typename Type, uint8_t CoordSizeX, uint8_t CoordSizeY,
|
||||
typename CoordType = uint16_t>
|
||||
void define_ClusterFile(py::module &m, const std::string &typestr) {
|
||||
|
||||
using ClusterType = Cluster<Type, CoordSizeX, CoordSizeY, CoordType>;
|
||||
using File = ClusterFile<ClusterType>;
|
||||
using FrameIterator = ClusterFileIterator<typename File::FrameRange>;
|
||||
using ChunkIterator = ClusterFileIterator<typename File::ChunkRange>;
|
||||
|
||||
auto class_name = fmt::format("ClusterFile_{}", typestr);
|
||||
define_cluster_file_iterator<FrameIterator>(m,
|
||||
class_name + "_FrameIterator");
|
||||
define_cluster_file_iterator<ChunkIterator>(m,
|
||||
class_name + "_ChunkIterator");
|
||||
|
||||
py::class_<ClusterFile<ClusterType>>(m, class_name.c_str())
|
||||
py::class_<ClusterFile<ClusterType>>(
|
||||
m, class_name.c_str(),
|
||||
"Read and write legacy binary cluster files. The format contains no "
|
||||
"cluster type or shape metadata, so this class must match the file.")
|
||||
.def(py::init<const std::filesystem::path &, size_t,
|
||||
const std::string &>(),
|
||||
py::arg(), py::arg("chunk_size") = 1000, py::arg("mode") = "r")
|
||||
py::arg("fname"), py::arg("chunk_size") = 1000,
|
||||
py::arg("mode") = "r",
|
||||
"Open a cluster file. Mode must be 'r' to read, 'w' to truncate "
|
||||
"and write, or 'a' to append.")
|
||||
.def(
|
||||
"frames", [](File &self) { return FrameIterator(self.frames()); },
|
||||
py::keep_alive<0, 1>(),
|
||||
"Iterate over complete frames from the current position, including "
|
||||
"empty and fully filtered frames with their stored frame numbers. "
|
||||
"Results own their storage. The iterator keeps the file alive but "
|
||||
"shares its cursor; use only one traversal at a time.")
|
||||
.def(
|
||||
"chunks", [](File &self) { return ChunkIterator(self.chunks()); },
|
||||
py::keep_alive<0, 1>(),
|
||||
"Iterate from the current position using the constructor's chunk "
|
||||
"size, which must be positive. Results own their storage. The "
|
||||
"iterator keeps the file alive but shares its cursor; use only "
|
||||
"one traversal at a time.")
|
||||
.def(
|
||||
"chunks",
|
||||
[](File &self, size_t chunk_size) {
|
||||
return ChunkIterator(self.chunks(chunk_size));
|
||||
},
|
||||
py::arg("chunk_size"), py::keep_alive<0, 1>(),
|
||||
"Iterate over chunks of up to chunk_size selected clusters. The "
|
||||
"size must be positive and does not change the constructor's "
|
||||
"default. Chunks may span frames; their frame numbers are not "
|
||||
"per-cluster metadata. Only the final chunk can be short.")
|
||||
.def(
|
||||
"read_clusters",
|
||||
[](ClusterFile<ClusterType> &self, size_t n_clusters) {
|
||||
@@ -39,32 +112,60 @@ void define_ClusterFile(py::module &m, const std::string &typestr) {
|
||||
self.read_clusters(n_clusters));
|
||||
return v;
|
||||
},
|
||||
py::return_value_policy::take_ownership, py::arg("n_clusters"))
|
||||
.def("read_frame",
|
||||
[](ClusterFile<ClusterType> &self) {
|
||||
auto v = new ClusterVector<ClusterType>(self.read_frame());
|
||||
return v;
|
||||
})
|
||||
.def("set_roi", &ClusterFile<ClusterType>::set_roi, py::arg("roi"))
|
||||
.def("tell", &ClusterFile<ClusterType>::tell)
|
||||
py::return_value_policy::take_ownership, py::arg("n_clusters"),
|
||||
"Read up to n_clusters without preserving frame boundaries. The "
|
||||
"result may combine frames, so its frame number is not reliable "
|
||||
"per-cluster metadata.")
|
||||
.def(
|
||||
"read_frame",
|
||||
[](ClusterFile<ClusterType> &self) -> py::object {
|
||||
auto clusters = self.read_frame();
|
||||
if (!clusters) {
|
||||
return py::none();
|
||||
}
|
||||
return py::cast(
|
||||
new ClusterVector<ClusterType>(std::move(*clusters)),
|
||||
py::return_value_policy::take_ownership);
|
||||
},
|
||||
"Read and return the next complete frame with its frame number, "
|
||||
"or None at end of file.")
|
||||
.def("set_roi", &ClusterFile<ClusterType>::set_roi, py::arg("roi"),
|
||||
"Select clusters whose centers lie within the half-open ROI.")
|
||||
.def("tell", &ClusterFile<ClusterType>::tell,
|
||||
"Return the current byte position in the file.")
|
||||
.def("estimate_n_clusters",
|
||||
&ClusterFile<ClusterType>::estimate_n_clusters)
|
||||
&ClusterFile<ClusterType>::estimate_n_clusters,
|
||||
"Estimate the number of clusters from the file size. Frame "
|
||||
"headers can make this larger than the actual count.")
|
||||
.def(
|
||||
"set_noise_map",
|
||||
[](ClusterFile<ClusterType> &self, py::array_t<int32_t> noise_map) {
|
||||
[](ClusterFile<ClusterType> &self,
|
||||
py::array_t<int32_t, py::array::c_style> noise_map) {
|
||||
auto view = make_view_2d(noise_map);
|
||||
self.set_noise_map(view);
|
||||
},
|
||||
py::arg("noise_map"))
|
||||
py::arg("noise_map"),
|
||||
"Set a two-dimensional, C-contiguous int32 noise map indexed as "
|
||||
"[y, x]. The map must cover every cluster center coordinate.")
|
||||
|
||||
.def("set_gain_map",
|
||||
[](ClusterFile<ClusterType> &self, py::array_t<double> gain_map) {
|
||||
auto view = make_view_2d(gain_map);
|
||||
self.set_gain_map(view);
|
||||
})
|
||||
.def(
|
||||
"set_gain_map",
|
||||
[](ClusterFile<ClusterType> &self,
|
||||
py::array_t<double, py::array::c_style> gain_map) {
|
||||
auto view = make_view_2d(gain_map);
|
||||
self.set_gain_map(view);
|
||||
},
|
||||
py::arg("gain_map"),
|
||||
"Set a two-dimensional, C-contiguous float64 gain map in "
|
||||
"ADU/energy, indexed as [y, x]. Clusters whose complete footprint "
|
||||
"extends beyond the map are retained with all data values set to "
|
||||
"zero.")
|
||||
|
||||
.def("close", &ClusterFile<ClusterType>::close)
|
||||
.def("write_frame", &ClusterFile<ClusterType>::write_frame)
|
||||
.def("close", &ClusterFile<ClusterType>::close,
|
||||
"Close the file. Calling close more than once is safe.")
|
||||
.def("write_frame", &ClusterFile<ClusterType>::write_frame,
|
||||
py::arg("clusters"),
|
||||
"Write one ClusterVector, including its frame number.")
|
||||
.def("__enter__", [](ClusterFile<ClusterType> &self) { return &self; })
|
||||
.def("__exit__",
|
||||
[](ClusterFile<ClusterType> &self,
|
||||
@@ -74,14 +175,8 @@ void define_ClusterFile(py::module &m, const std::string &typestr) {
|
||||
self.close();
|
||||
})
|
||||
.def("__iter__", [](ClusterFile<ClusterType> &self) { return &self; })
|
||||
.def("__next__", [](ClusterFile<ClusterType> &self) {
|
||||
auto v = new ClusterVector<ClusterType>(
|
||||
self.read_clusters(self.chunk_size()));
|
||||
if (v->size() == 0) {
|
||||
throw py::stop_iteration();
|
||||
}
|
||||
return v;
|
||||
});
|
||||
.def("__next__",
|
||||
[](File &self) { return ChunkIterator(self.chunks()).next(); });
|
||||
}
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
@@ -32,8 +32,10 @@ void define_ClusterFinder(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterFinder<ClusterType, uint16_t, pd_type>>(
|
||||
m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, pd_type, size_t>(), py::arg("image_size"),
|
||||
py::arg("n_sigma") = 5.0, py::arg("capacity") = 1'000'000)
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0,
|
||||
py::arg("capacity") = 1'000'000,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
|
||||
.def_property(
|
||||
"nSigma",
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
#pragma once
|
||||
#include "aare/ClusterFinderCUDA.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/FastPedestal.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -27,7 +27,10 @@ void define_ClusterFinderCUDA(py::module &m, const std::string &typestr) {
|
||||
auto class_name = fmt::format("ClusterFinderCUDA_{}", typestr);
|
||||
|
||||
using ClusterType = Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>;
|
||||
using CF = ClusterFinderCUDA<ClusterType, uint16_t, pd_type>;
|
||||
// The driver is templated on the algorithm; a second algorithm is a second
|
||||
// instantiation registered under its own suffix (see ClusterFinder.py).
|
||||
using Algo = aare::cuda::FixedWindow<ClusterType, uint16_t>;
|
||||
using CF = ClusterFinderCUDA<Algo, pd_type>;
|
||||
using ContigArr =
|
||||
py::array_t<uint16_t, py::array::c_style | py::array::forcecast>;
|
||||
|
||||
@@ -109,9 +112,10 @@ void define_ClusterFinderCUDA(py::module &m, const std::string &typestr) {
|
||||
coordinates as (x, y).)");
|
||||
|
||||
py::class_<CF>(m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, float, size_t, int, bool>(),
|
||||
.def(py::init<Shape<2>, float, size_t, int, size_t, bool>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0f,
|
||||
py::arg("max_clusters_per_frame") = 2048, py::arg("n_streams") = 4,
|
||||
py::arg("min_pedestal_samples") = 1000,
|
||||
py::arg("time_kernels") = false)
|
||||
|
||||
.def_property(
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
#pragma once
|
||||
#include "aare/ClusterFinderCUDA_graph.hpp"
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/FastPedestal.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
@@ -31,9 +31,10 @@ void define_ClusterFinderCUDAGraph(py::module &m, const std::string &typestr) {
|
||||
py::array_t<uint16_t, py::array::c_style | py::array::forcecast>;
|
||||
|
||||
py::class_<CF>(m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, float, size_t, int>(), py::arg("image_size"),
|
||||
py::arg("n_sigma") = 5.0f,
|
||||
py::arg("max_clusters_per_frame") = 2048, py::arg("n_streams") = 4)
|
||||
.def(py::init<Shape<2>, float, size_t, int, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0f,
|
||||
py::arg("max_clusters_per_frame") = 2048, py::arg("n_streams") = 4,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
|
||||
.def_property(
|
||||
"nSigma", &CF::get_nSigma, &CF::set_nSigma,
|
||||
|
||||
@@ -27,8 +27,10 @@ void define_ClusterFinderFrozen(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterFinderFrozen<ClusterType, uint16_t, pd_type>>(
|
||||
m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, pd_type, size_t>(), py::arg("image_size"),
|
||||
py::arg("n_sigma") = 5.0, py::arg("capacity") = 1'000'000)
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0,
|
||||
py::arg("capacity") = 1'000'000,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
|
||||
.def_property(
|
||||
"nSigma",
|
||||
|
||||
@@ -32,10 +32,11 @@ void define_ClusterFinderMT(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterFinderMT<ClusterType, uint16_t, pd_type>>(
|
||||
m, class_name.c_str())
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t, size_t>(),
|
||||
.def(py::init<Shape<2>, pd_type, size_t, size_t, size_t, size_t>(),
|
||||
py::arg("image_size"), py::arg("n_sigma") = 5.0,
|
||||
py::arg("capacity") = 2048, py::arg("n_threads") = 3,
|
||||
py::arg("queue_depth") = 16)
|
||||
py::arg("queue_depth") = 16,
|
||||
py::arg("min_pedestal_samples") = 1000)
|
||||
.def("push_pedestal_frame",
|
||||
[](ClusterFinderMT<ClusterType, uint16_t, pd_type> &self,
|
||||
py::array_t<uint16_t> frame) {
|
||||
|
||||
@@ -29,37 +29,73 @@ void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
|
||||
py::class_<ClusterVector<
|
||||
Cluster<Type, ClusterSizeX, ClusterSizeY, CoordType>, void>>(
|
||||
m, class_name.c_str(), py::buffer_protocol(),
|
||||
py::module_local())
|
||||
m, class_name.c_str(), R"doc(
|
||||
A contiguous, move-only container of fixed-size clusters.
|
||||
|
||||
.def(py::init()) // TODO change!!!
|
||||
The class supports the Python buffer protocol, so ``numpy.array`` can
|
||||
either copy its data or create a zero-copy view. A zero-copy view is
|
||||
valid only while the ClusterVector's underlying allocation and size
|
||||
remain unchanged.
|
||||
)doc",
|
||||
py::buffer_protocol(), py::module_local())
|
||||
|
||||
.def(py::init(), R"doc(
|
||||
Create an empty ClusterVector with frame number 0 and space reserved
|
||||
for at least 1024 clusters.
|
||||
)doc")
|
||||
|
||||
.def(
|
||||
"__call__",
|
||||
[](ClusterVector<ClusterType> &self, py::array_t<bool> mask) {
|
||||
[](ClusterVector<ClusterType> &self,
|
||||
py::array_t<bool, py::array::c_style> mask) {
|
||||
return self(make_view_1d(mask));
|
||||
},
|
||||
py::arg("mask"), R"(
|
||||
Create a copy of the clustervector and apply a boolean mask to the ClusterVector.
|
||||
py::arg("mask").noconvert(), R"doc(
|
||||
Return a filtered copy of this ClusterVector.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
mask : numpy.ndarray
|
||||
One-dimensional, writable, C-contiguous array with dtype
|
||||
``numpy.bool_`` and one element per cluster.
|
||||
|
||||
mask : 1d boolean numpy array
|
||||
Mask to apply to the ClusterVector. Must be the same length as the number of clusters in the ClusterVector.
|
||||
Returns
|
||||
-------
|
||||
ClusterVector
|
||||
Selected clusters in their original order. The frame number is
|
||||
preserved.
|
||||
)doc")
|
||||
|
||||
)")
|
||||
.def(
|
||||
"push_back",
|
||||
[](ClusterVector<ClusterType> &self, const ClusterType &cluster) {
|
||||
self.push_back(cluster);
|
||||
},
|
||||
py::arg("cluster"), R"doc(
|
||||
Append one cluster.
|
||||
|
||||
.def("push_back",
|
||||
[](ClusterVector<ClusterType> &self, const ClusterType &cluster) {
|
||||
self.push_back(cluster);
|
||||
})
|
||||
Notes
|
||||
-----
|
||||
Do not call this method while a zero-copy NumPy view of the
|
||||
ClusterVector exists. Reallocation invalidates the view, while an
|
||||
append without reallocation leaves its shape unchanged.
|
||||
)doc")
|
||||
|
||||
.def("sum",
|
||||
[](ClusterVector<ClusterType> &self) {
|
||||
auto *vec = new std::vector<Type>(self.sum());
|
||||
return return_vector(vec);
|
||||
})
|
||||
.def(
|
||||
"sum",
|
||||
[](ClusterVector<ClusterType> &self) {
|
||||
auto *vec = new std::vector<Type>(self.sum());
|
||||
return return_vector(vec);
|
||||
},
|
||||
R"doc(
|
||||
Return the sum of all pixels in each cluster.
|
||||
|
||||
Returns
|
||||
-------
|
||||
numpy.ndarray
|
||||
One value per cluster, in container order and with the cluster
|
||||
pixel dtype.
|
||||
)doc")
|
||||
.def(
|
||||
"sum_2x2",
|
||||
[](ClusterVector<ClusterType> &self) {
|
||||
@@ -68,24 +104,45 @@ void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
|
||||
return return_vector(vec);
|
||||
},
|
||||
R"(calculates sum of 2x2 subcluster with highest energy and index relative to cluster center 0: top_left, 1: top_right, 2: bottom_left, 3: bottom_right
|
||||
)")
|
||||
.def_property_readonly("size", &ClusterVector<ClusterType>::size)
|
||||
.def("empty", &ClusterVector<ClusterType>::empty)
|
||||
.def("item_size", &ClusterVector<ClusterType>::item_size)
|
||||
.def_property_readonly("fmt",
|
||||
[typestr](ClusterVector<ClusterType> &self) {
|
||||
return fmt_format<ClusterType>;
|
||||
})
|
||||
R"doc(
|
||||
Return the highest-sum center-adjacent 2x2 subcluster for each
|
||||
cluster.
|
||||
|
||||
Returns
|
||||
-------
|
||||
numpy.ndarray
|
||||
Structured array with ``sum`` and ``index`` fields. Indices are
|
||||
0 for top-left, 1 for top-right, 2 for bottom-left, and 3 for
|
||||
bottom-right, relative to the cluster center.
|
||||
)doc")
|
||||
.def_property_readonly("size", &ClusterVector<ClusterType>::size,
|
||||
"Number of stored clusters.")
|
||||
.def("empty", &ClusterVector<ClusterType>::empty,
|
||||
"Return True when no clusters are stored.")
|
||||
.def("item_size", &ClusterVector<ClusterType>::item_size,
|
||||
"Return the size in bytes of one stored cluster, including "
|
||||
"padding.")
|
||||
.def_property_readonly(
|
||||
"fmt",
|
||||
[typestr](ClusterVector<ClusterType> &self) {
|
||||
return fmt_format<ClusterType>;
|
||||
},
|
||||
"PEP 3118 format string for one stored cluster.")
|
||||
|
||||
.def_property_readonly("cluster_size_x",
|
||||
&ClusterVector<ClusterType>::cluster_size_x)
|
||||
&ClusterVector<ClusterType>::cluster_size_x,
|
||||
"Cluster size in the x dimension.")
|
||||
.def_property_readonly("cluster_size_y",
|
||||
&ClusterVector<ClusterType>::cluster_size_y)
|
||||
&ClusterVector<ClusterType>::cluster_size_y,
|
||||
"Cluster size in the y dimension.")
|
||||
.def_property_readonly("capacity",
|
||||
&ClusterVector<ClusterType>::capacity)
|
||||
&ClusterVector<ClusterType>::capacity,
|
||||
"Number of clusters that fit without "
|
||||
"reallocation.")
|
||||
.def_property("frame_number", &ClusterVector<ClusterType>::frame_number,
|
||||
&ClusterVector<ClusterType>::set_frame_number)
|
||||
&ClusterVector<ClusterType>::set_frame_number,
|
||||
"Signed 32-bit frame number; 0 can indicate clusters "
|
||||
"from multiple frames.")
|
||||
.def_buffer(
|
||||
[typestr](ClusterVector<ClusterType> &self) -> py::buffer_info {
|
||||
return py::buffer_info(
|
||||
@@ -99,31 +156,38 @@ void define_ClusterVector(py::module &m, const std::string &typestr) {
|
||||
});
|
||||
|
||||
// Free functions using ClusterVector
|
||||
m.def("hitmap",
|
||||
[](std::array<size_t, 2> image_size, ClusterVector<ClusterType> &cv) {
|
||||
// Create a numpy array to hold the hitmap
|
||||
// The shape of the array is (image_size[0], image_size[1])
|
||||
// note that the python array is passed as [row, col] which
|
||||
// is the opposite of the clusters [x,y]
|
||||
py::array_t<int32_t> hitmap(image_size);
|
||||
auto r = hitmap.mutable_unchecked<2>();
|
||||
m.def(
|
||||
"hitmap",
|
||||
[](std::array<size_t, 2> image_size, ClusterVector<ClusterType> &cv) {
|
||||
// Create a numpy array to hold the hitmap
|
||||
// The shape of the array is (image_size[0], image_size[1])
|
||||
// note that the python array is passed as [row, col] which
|
||||
// is the opposite of the clusters [x,y]
|
||||
py::array_t<int32_t> hitmap(image_size);
|
||||
auto r = hitmap.mutable_unchecked<2>();
|
||||
|
||||
// Initialize hitmap to 0
|
||||
for (py::ssize_t i = 0; i < r.shape(0); i++)
|
||||
for (py::ssize_t j = 0; j < r.shape(1); j++)
|
||||
r(i, j) = 0;
|
||||
// Initialize hitmap to 0
|
||||
for (py::ssize_t i = 0; i < r.shape(0); i++)
|
||||
for (py::ssize_t j = 0; j < r.shape(1); j++)
|
||||
r(i, j) = 0;
|
||||
|
||||
// Loop over the clusters and increment the hitmap
|
||||
// Skip out of bound clusters
|
||||
for (const auto &cluster : cv) {
|
||||
auto x = cluster.x;
|
||||
auto y = cluster.y;
|
||||
if (x < image_size[1] && y < image_size[0])
|
||||
r(cluster.y, cluster.x) += 1;
|
||||
}
|
||||
// Loop over the clusters and increment the hitmap
|
||||
// Skip out of bound clusters
|
||||
for (const auto &cluster : cv) {
|
||||
auto x = cluster.x;
|
||||
auto y = cluster.y;
|
||||
if (x < image_size[1] && y < image_size[0])
|
||||
r(cluster.y, cluster.x) += 1;
|
||||
}
|
||||
|
||||
return hitmap;
|
||||
});
|
||||
return hitmap;
|
||||
},
|
||||
py::arg("image_size"), py::arg("clusters"), R"doc(
|
||||
Count cluster centers into an ``int32`` image whose shape is given by
|
||||
``image_size`` as ``(rows, columns)``. Element ``[y, x]`` contains the
|
||||
number of cluster centers at that coordinate. Out-of-bounds centers are
|
||||
ignored.
|
||||
)doc");
|
||||
}
|
||||
|
||||
template <typename Type, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
|
||||
@@ -136,15 +200,12 @@ void define_2x2_reduction(py::module &m) {
|
||||
return new ClusterVector<Cluster<Type, 2, 2, CoordType>>(
|
||||
reduce_to_2x2(cv));
|
||||
},
|
||||
R"(
|
||||
Reduce cluster to 2x2 subcluster by taking the 2x2 subcluster with
|
||||
the highest photon energy.
|
||||
|
||||
Parameters
|
||||
|
||||
cv : ClusterVector (clusters are filled in row-major ordering starting at the top left. Thus for a max subcluster in the top left corner the photon hit is at the fourth position.)
|
||||
|
||||
)",
|
||||
R"doc(
|
||||
Reduce every cluster to its highest-sum center-adjacent 2x2 block.
|
||||
Returns a new ClusterVector; cluster order, coordinates, and frame
|
||||
number are preserved. Input pixel data is interpreted in row-major
|
||||
order.
|
||||
)doc",
|
||||
py::arg("clustervector"));
|
||||
}
|
||||
|
||||
@@ -159,13 +220,13 @@ void define_3x3_reduction(py::module &m) {
|
||||
return new ClusterVector<Cluster<Type, 3, 3, CoordType>>(
|
||||
reduce_to_3x3(cv));
|
||||
},
|
||||
R"(
|
||||
Reduce cluster to 3x3 subcluster
|
||||
|
||||
Parameters
|
||||
|
||||
cv : ClusterVector
|
||||
)",
|
||||
R"doc(
|
||||
Reduce every cluster to the 3x3 block around its center index.
|
||||
Both input dimensions must be at least 3, and at least one must be
|
||||
greater than 3.
|
||||
Returns a new ClusterVector; cluster order, coordinates, and frame
|
||||
number are preserved.
|
||||
)doc",
|
||||
py::arg("clustervector"));
|
||||
}
|
||||
|
||||
|
||||
@@ -27,4 +27,77 @@ void define_defs_bindings(py::module &m) {
|
||||
moench05.attr("nRows") = Moench05::nRows;
|
||||
moench05.attr("nCols") = Moench05::nCols;
|
||||
moench05.attr("adcNumbers") = Moench05::adcNumbers;
|
||||
|
||||
py::class_<ROI>(m, "ROI")
|
||||
.def(py::init<>())
|
||||
.def(py::init<ssize_t, ssize_t, ssize_t, ssize_t>(), py::arg("xmin"),
|
||||
py::arg("xmax"), py::arg("ymin"), py::arg("ymax"))
|
||||
.def_readwrite("xmin", &ROI::xmin)
|
||||
.def_readwrite("xmax", &ROI::xmax)
|
||||
.def_readwrite("ymin", &ROI::ymin)
|
||||
.def_readwrite("ymax", &ROI::ymax)
|
||||
|
||||
.def(
|
||||
"slice",
|
||||
[](const ROI &self) {
|
||||
return std::make_tuple(py::slice(self.ymin, self.ymax, 1),
|
||||
py::slice(self.xmin, self.xmax, 1));
|
||||
},
|
||||
R"doc(
|
||||
The slice can be used to index into a 2D array to extract the region of interest.
|
||||
|
||||
Returns
|
||||
-------
|
||||
tuple of slice
|
||||
A tuple containing two slice objects for the x and y dimensions.
|
||||
)doc")
|
||||
|
||||
.def("__str__",
|
||||
[](const ROI &self) {
|
||||
return fmt::format("ROI: xmin: {} xmax: {} ymin: {} ymax: {}",
|
||||
self.xmin, self.xmax, self.ymin, self.ymax);
|
||||
})
|
||||
.def("__repr__",
|
||||
[](const ROI &self) {
|
||||
return fmt::format(
|
||||
"<ROI: xmin: {} xmax: {} ymin: {} ymax: {}>", self.xmin,
|
||||
self.xmax, self.ymin, self.ymax);
|
||||
})
|
||||
.def("__iter__",
|
||||
[](const ROI &self) {
|
||||
return py::make_iterator(&self.xmin, &self.ymax + 1); // NOLINT
|
||||
})
|
||||
|
||||
.def("__eq__", [](const ROI &self, const ROI &other) {
|
||||
return self.xmin == other.xmin && self.xmax == other.xmax &&
|
||||
self.ymin == other.ymin && self.ymax == other.ymax;
|
||||
});
|
||||
|
||||
py::enum_<DetectorType>(m, "DetectorType")
|
||||
.value("Jungfrau", DetectorType::Jungfrau)
|
||||
.value("Eiger", DetectorType::Eiger)
|
||||
.value("Mythen3", DetectorType::Mythen3)
|
||||
.value("Moench", DetectorType::Moench)
|
||||
.value("Moench03", DetectorType::Moench03)
|
||||
.value("Moench03_old", DetectorType::Moench03_old)
|
||||
.value("ChipTestBoard", DetectorType::ChipTestBoard)
|
||||
.value("Unknown", DetectorType::Unknown);
|
||||
|
||||
py::enum_<UDPPortPosition>(m, "UDPPortPosition")
|
||||
.value("LEFT", UDPPortPosition::LEFT)
|
||||
.value("RIGHT", UDPPortPosition::RIGHT)
|
||||
.value("TOP", UDPPortPosition::TOP)
|
||||
.value("BOTTOM", UDPPortPosition::BOTTOM);
|
||||
|
||||
py::enum_<TimingMode>(m, "TimingMode")
|
||||
.value("AUTO_TIMING", TimingMode::AUTO_TIMING)
|
||||
.value("TRIGGER_EXPOSURE", TimingMode::TRIGGER_EXPOSURE)
|
||||
.value("GATED", TimingMode::GATED)
|
||||
.value("BURST_TRIGGER", TimingMode::BURST_TRIGGER)
|
||||
.value("TRIGGER_GATED", TimingMode::TRIGGER_GATED);
|
||||
|
||||
py::enum_<FrameDiscardPolicy>(m, "FrameDiscardPolicy")
|
||||
.value("NoDiscard", FrameDiscardPolicy::NoDiscard)
|
||||
.value("Discard", FrameDiscardPolicy::Discard)
|
||||
.value("DiscardPartial", FrameDiscardPolicy::DiscardPartial);
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
#include "aare/CalculateEta.hpp"
|
||||
#include "aare/to_string.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <fmt/format.h>
|
||||
// #include <pybind11/native_enum.h> only for version 3
|
||||
#include <pybind11/pybind11.h>
|
||||
|
||||
@@ -18,7 +20,11 @@ void define_eta(py::module &m, const std::string &typestr) {
|
||||
.def_readwrite("c", &Eta2<T>::c,
|
||||
"eta corner value cTopLeft, cTopRight, "
|
||||
"cBottomLeft, cBottomRight")
|
||||
.def_readwrite("sum", &Eta2<T>::sum, "photon energy of cluster");
|
||||
.def_readwrite("sum", &Eta2<T>::sum, "photon energy of cluster")
|
||||
.def("__repr__", [class_name](const Eta2<T> &self) {
|
||||
return fmt::format("{}(x={}, y={}, c={}, sum={})", class_name,
|
||||
self.x, self.y, to_string(self.c), self.sum);
|
||||
});
|
||||
}
|
||||
|
||||
void define_corner_enum(py::module &m) {
|
||||
@@ -101,4 +107,4 @@ void register_calculate_3x3eta(py::module &m) {
|
||||
},
|
||||
R"(calculates eta3x3 taking into account cross pixels in cluster)",
|
||||
py::arg("cluster"));
|
||||
}
|
||||
}
|
||||
@@ -15,8 +15,7 @@ void define_fast_pedestal_bindings(py::module &m, const std::string &name) {
|
||||
|
||||
py::class_<FastPedestal<SUM_TYPE>>(
|
||||
m, name.c_str(),
|
||||
"Maintain a per-pixel running mean, population variance, and "
|
||||
"standard deviation.",
|
||||
"Maintain a per-pixel running mean and population standard deviation.",
|
||||
py::buffer_protocol())
|
||||
.def(py::init<uint32_t, uint32_t, uint32_t>(), py::arg("rows"),
|
||||
py::arg("cols"), py::arg("n_samples"),
|
||||
@@ -33,15 +32,6 @@ void define_fast_pedestal_bindings(py::module &m, const std::string &name) {
|
||||
return return_image_data(mean);
|
||||
},
|
||||
"Return a copy of the cached mean. The pedestal must be ready.")
|
||||
.def(
|
||||
"var",
|
||||
[](FastPedestal<SUM_TYPE> &self) {
|
||||
auto variance = new NDArray<SUM_TYPE, 2>{};
|
||||
*variance = self.variance();
|
||||
return return_image_data(variance);
|
||||
},
|
||||
"Return the population variance, normalized by n_samples, as a "
|
||||
"NumPy array. The pedestal must be ready.")
|
||||
.def(
|
||||
"std",
|
||||
[](FastPedestal<SUM_TYPE> &self) {
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
template <typename SUM_TYPE>
|
||||
void define_pedestal_bindings(py::module &m, const std::string &name) {
|
||||
|
||||
py::class_<Pedestal<SUM_TYPE>>(
|
||||
m, name.c_str(),
|
||||
"Maintain a per-pixel running mean and population standard deviation. "
|
||||
"Statistics are available during initialization and are zero for empty "
|
||||
"pixels.",
|
||||
py::buffer_protocol())
|
||||
.def(py::init<uint32_t, uint32_t, uint32_t>(), py::arg("rows"),
|
||||
py::arg("cols"), py::arg("n_samples"),
|
||||
"Construct an empty pedestal. Each pixel accumulates n_samples "
|
||||
"values before switching to exponential updates.")
|
||||
.def(py::init<uint32_t, uint32_t>(), py::arg("rows"), py::arg("cols"),
|
||||
"Construct an empty pedestal with n_samples=1000.")
|
||||
.def(
|
||||
"mean",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto mea = new NDArray<SUM_TYPE, 2>{};
|
||||
*mea = self.mean();
|
||||
return return_image_data(mea);
|
||||
},
|
||||
"Return a copy of the cached mean. Empty pixels return zero.")
|
||||
.def(
|
||||
"view",
|
||||
[](py::object self_py) {
|
||||
return py::module_::import("numpy").attr("asarray")(self_py);
|
||||
},
|
||||
"Return a non-owning, non-writable NumPy view of the cached mean.")
|
||||
.def(
|
||||
"std",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto std = new NDArray<SUM_TYPE, 2>{};
|
||||
*std = self.std();
|
||||
return return_image_data(std);
|
||||
},
|
||||
"Return the population standard deviation as a NumPy array. "
|
||||
"Empty pixels return zero.")
|
||||
.def(
|
||||
"__array_ufunc__",
|
||||
[](py::object self, py::object ufunc, const std::string &method,
|
||||
py::args inputs, py::kwargs kwargs) -> py::object {
|
||||
if (method != "__call__" || inputs.size() != 2 ||
|
||||
inputs[1].ptr() != self.ptr() ||
|
||||
py::cast<std::string>(ufunc.attr("__name__")) !=
|
||||
"subtract") {
|
||||
return py::reinterpret_borrow<py::object>(
|
||||
Py_NotImplemented);
|
||||
}
|
||||
|
||||
auto mean =
|
||||
py::module_::import("builtins").attr("memoryview")(self);
|
||||
return ufunc(inputs[0], mean, **kwargs);
|
||||
},
|
||||
"Support subtracting a Pedestal from a NumPy array.")
|
||||
.def("clear", py::overload_cast<>(&Pedestal<SUM_TYPE>::clear),
|
||||
"Reset all statistics and per-pixel sample counts to zero.")
|
||||
.def_property_readonly("rows", &Pedestal<SUM_TYPE>::rows,
|
||||
"Number of image rows.")
|
||||
.def_property_readonly("cols", &Pedestal<SUM_TYPE>::cols,
|
||||
"Number of image columns.")
|
||||
.def_property_readonly(
|
||||
"n_samples", &Pedestal<SUM_TYPE>::n_samples,
|
||||
"Initialization sample count per pixel and steady-state "
|
||||
"update-weight denominator.")
|
||||
.def(
|
||||
"clone",
|
||||
[&](Pedestal<SUM_TYPE> &pedestal) {
|
||||
return Pedestal<SUM_TYPE>(pedestal);
|
||||
},
|
||||
"Return an independent copy of the pedestal and its state.")
|
||||
// TODO! add push for other data types
|
||||
.def(
|
||||
"push",
|
||||
[](Pedestal<SUM_TYPE> &pedestal,
|
||||
py::array_t<uint16_t, py::array::c_style> &f) {
|
||||
if (f.ndim() != 2) {
|
||||
throw py::value_error("Frame must be 2-dimensional");
|
||||
}
|
||||
auto v = make_view_2d(f);
|
||||
pedestal.push(v);
|
||||
},
|
||||
py::arg("frame").noconvert(),
|
||||
"Accumulate or exponentially update every pixel from a "
|
||||
"C-contiguous uint16 frame matching the pedestal shape. After "
|
||||
"n_samples values per pixel, new values have weight 1 / n_samples.")
|
||||
.def(
|
||||
"push_with_threshold",
|
||||
[](Pedestal<SUM_TYPE> &pedestal,
|
||||
py::array_t<uint16_t, py::array::c_style> &f,
|
||||
py::array_t<SUM_TYPE, py::array::c_style> &threshold) {
|
||||
if (f.ndim() != 2) {
|
||||
throw py::value_error("Frame must be 2-dimensional");
|
||||
}
|
||||
if (threshold.ndim() != 2) {
|
||||
throw py::value_error("Threshold must be 2-dimensional");
|
||||
}
|
||||
auto frame_view = make_view_2d(f);
|
||||
auto threshold_view = make_view_2d(threshold);
|
||||
pedestal.push_with_threshold(frame_view, threshold_view);
|
||||
},
|
||||
py::arg("frame").noconvert(), py::arg("threshold").noconvert(),
|
||||
"Push only pixels where abs(frame - mean) is strictly less than "
|
||||
"threshold. Both arrays must be C-contiguous with the pedestal "
|
||||
"shape; frame must be uint16 and threshold must use the output "
|
||||
"dtype. Rejected pixels keep their statistics and sample counts.")
|
||||
.def_buffer([](Pedestal<SUM_TYPE> &self) {
|
||||
auto mean = self.view();
|
||||
return py::buffer_info(
|
||||
const_cast<SUM_TYPE *>(mean.data()), sizeof(SUM_TYPE),
|
||||
py::format_descriptor<SUM_TYPE>::format(), 2,
|
||||
{static_cast<py::ssize_t>(mean.shape(0)),
|
||||
static_cast<py::ssize_t>(mean.shape(1))},
|
||||
{static_cast<py::ssize_t>(mean.strides()[0] * sizeof(SUM_TYPE)),
|
||||
static_cast<py::ssize_t>(mean.strides()[1] *
|
||||
sizeof(SUM_TYPE))},
|
||||
true);
|
||||
});
|
||||
}
|
||||
+33
-15
@@ -11,6 +11,7 @@
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <fmt/format.h>
|
||||
#include <pybind11/iostream.h>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
@@ -21,14 +22,23 @@
|
||||
namespace py = pybind11;
|
||||
using namespace ::aare;
|
||||
|
||||
namespace {
|
||||
std::runtime_error raw_file_read_error(RawFile &file,
|
||||
const std::string &message) {
|
||||
return std::runtime_error(fmt::format(
|
||||
"Error reading frame index {} from file '{}': {}", file.tell(),
|
||||
file.master().master_fname().string(), message));
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void define_raw_file_io_bindings(py::module &m) {
|
||||
py::class_<RawFile>(m, "RawFile")
|
||||
.def(py::init<const std::filesystem::path &>())
|
||||
.def("read_frame",
|
||||
[](RawFile &self) {
|
||||
if (self.n_modules_in_roi().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
"File contains multiple ROIs - use read_ROIs()");
|
||||
throw raw_file_read_error(
|
||||
self, "File contains multiple ROIs - use read_ROIs()");
|
||||
}
|
||||
|
||||
std::vector<size_t> shape;
|
||||
@@ -51,16 +61,19 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_n",
|
||||
[](RawFile &self, size_t n_frames) {
|
||||
if (self.n_modules_in_roi().size() > 1) {
|
||||
throw std::runtime_error(
|
||||
throw raw_file_read_error(
|
||||
self,
|
||||
"File contains multiple ROIs - use read_n_ROIs() to "
|
||||
"read a specific ROI or use read_ROIs and "
|
||||
"read one frame at a time.");
|
||||
}
|
||||
// adjust for actual frames left in the file
|
||||
n_frames =
|
||||
std::min(n_frames, self.total_frames() - self.tell());
|
||||
std::min(n_frames, self.tell() < self.total_frames()
|
||||
? self.total_frames() - self.tell()
|
||||
: size_t{0});
|
||||
if (n_frames == 0) {
|
||||
throw std::runtime_error("No frames left in file");
|
||||
throw raw_file_read_error(self, "No frames left in file");
|
||||
}
|
||||
std::vector<size_t> shape{n_frames, self.rows(), self.cols()};
|
||||
|
||||
@@ -89,12 +102,13 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_roi",
|
||||
[](RawFile &self, const size_t roi_index) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
if (roi_index >= self.num_rois()) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"ROI index out of range.");
|
||||
throw raw_file_read_error(
|
||||
self, LOCATION + "ROI index out of range.");
|
||||
}
|
||||
|
||||
// return headers from all subfiles
|
||||
@@ -141,7 +155,8 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_rois",
|
||||
[](RawFile &self) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
size_t number_of_ROIs = self.num_rois();
|
||||
@@ -196,19 +211,22 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
"read_n_with_roi",
|
||||
[](RawFile &self, const size_t num_frames, const size_t roi_index) {
|
||||
if (self.num_rois() == 0) {
|
||||
throw std::runtime_error(LOCATION + "No ROIs defined.");
|
||||
throw raw_file_read_error(self,
|
||||
LOCATION + "No ROIs defined.");
|
||||
}
|
||||
|
||||
if (roi_index >= self.num_rois()) {
|
||||
throw std::runtime_error(LOCATION +
|
||||
"ROI index out of range.");
|
||||
throw raw_file_read_error(
|
||||
self, LOCATION + "ROI index out of range.");
|
||||
}
|
||||
|
||||
// adjust for actual frames left in the file
|
||||
size_t n_frames =
|
||||
std::min(num_frames, self.total_frames() - self.tell());
|
||||
std::min(num_frames, self.tell() < self.total_frames()
|
||||
? self.total_frames() - self.tell()
|
||||
: size_t{0});
|
||||
if (n_frames == 0) {
|
||||
throw std::runtime_error("No frames left in file");
|
||||
throw raw_file_read_error(self, "No frames left in file");
|
||||
}
|
||||
std::vector<size_t> shape{
|
||||
n_frames, self.roi_geometries(roi_index).pixels_y(),
|
||||
@@ -306,4 +324,4 @@ void define_raw_file_io_bindings(py::module &m) {
|
||||
.def_property_readonly("n_modules", &RawFile::n_modules)
|
||||
.def_property_readonly("n_modules_in_roi", &RawFile::n_modules_in_roi)
|
||||
.def_property_readonly("num_rois", &RawFile::num_rois);
|
||||
}
|
||||
}
|
||||
@@ -73,10 +73,27 @@ py::array_t<T> pybind_calculate_pedestal_g0(
|
||||
}
|
||||
|
||||
void bind_calibration(py::module &m) {
|
||||
py::options options;
|
||||
options.disable_function_signatures();
|
||||
|
||||
m.def("apply_calibration", &pybind_apply_calibration<double>,
|
||||
py::arg("raw_data").noconvert(), py::kw_only(),
|
||||
py::arg("pd").noconvert(), py::arg("cal").noconvert(),
|
||||
py::arg("n_threads") = 4);
|
||||
py::arg("n_threads") = 4,
|
||||
R"(
|
||||
Apply the calibration to the raw data and return the result as a 3D array of doubles.
|
||||
|
||||
Parameters
|
||||
----------
|
||||
raw_data : array_like
|
||||
3D array of shape ``(frames, rows, cols)``.
|
||||
pd : array_like
|
||||
Pedestal array.
|
||||
cal : array_like
|
||||
Calibration array.
|
||||
n_threads : int, optional
|
||||
Number of threads to use. Defaults to 4.
|
||||
)");
|
||||
|
||||
m.def("apply_calibration", &pybind_apply_calibration<float>,
|
||||
py::arg("raw_data").noconvert(), py::kw_only(),
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Probes used by the python test-suite to exercise the helpers in
|
||||
// np_helper.hpp. Internal, no API guarantees.
|
||||
#pragma once
|
||||
|
||||
#include "aare/NDArray.hpp"
|
||||
#include "aare/NDView.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
#include <type_traits>
|
||||
|
||||
namespace py = pybind11;
|
||||
using namespace ::aare;
|
||||
|
||||
// Arrays are taken with the default flags (no c_style) so that nothing is
|
||||
// made contiguous by pybind11 before it reaches make_view
|
||||
template <typename T, ssize_t Ndim>
|
||||
void define_make_view_probes(py::module &m, const std::string &suffix) {
|
||||
|
||||
// Copy what C++ sees through the view back to python
|
||||
m.def(("view_roundtrip_" + suffix).c_str(),
|
||||
[](py::array_t<T> arr) {
|
||||
auto view = make_view<Ndim>(arr);
|
||||
return return_image_data(new NDArray<T, Ndim>(view));
|
||||
},
|
||||
py::arg("arr").noconvert());
|
||||
|
||||
// Same as above but through a read only view
|
||||
m.def(("const_view_roundtrip_" + suffix).c_str(),
|
||||
[](py::array_t<T> arr) {
|
||||
auto view = make_const_view<Ndim>(arr);
|
||||
static_assert(
|
||||
std::is_same_v<decltype(view), NDView<const T, Ndim>>);
|
||||
auto out = new NDArray<T, Ndim>(view.shape());
|
||||
std::copy(view.begin(), view.end(), out->begin());
|
||||
return return_image_data(out);
|
||||
},
|
||||
py::arg("arr").noconvert());
|
||||
|
||||
// Write through the view
|
||||
m.def(("view_fill_" + suffix).c_str(),
|
||||
[](py::array_t<T> arr, T value) {
|
||||
auto view = make_view<Ndim>(arr);
|
||||
view = value;
|
||||
},
|
||||
py::arg("arr").noconvert(), py::arg("value"));
|
||||
}
|
||||
|
||||
void define_testing_bindings(py::module &m) {
|
||||
auto testing = m.def_submodule(
|
||||
"testing", "Internal helpers for the test-suite, no API guarantees");
|
||||
|
||||
// noconvert + overloads gives dispatch on dtype
|
||||
define_make_view_probes<double, 1>(testing, "1d");
|
||||
define_make_view_probes<double, 2>(testing, "2d");
|
||||
define_make_view_probes<double, 3>(testing, "3d");
|
||||
define_make_view_probes<uint16_t, 1>(testing, "1d");
|
||||
define_make_view_probes<uint16_t, 2>(testing, "2d");
|
||||
define_make_view_probes<uint16_t, 3>(testing, "3d");
|
||||
}
|
||||
+1
-33
@@ -2,6 +2,7 @@
|
||||
#include "aare/CtbRawFile.hpp"
|
||||
#include "aare/File.hpp"
|
||||
#include "aare/Frame.hpp"
|
||||
#include "aare/ROI.hpp"
|
||||
#include "aare/RawFile.hpp"
|
||||
#include "aare/RawMasterFile.hpp"
|
||||
#include "aare/RawSubFile.hpp"
|
||||
@@ -27,16 +28,6 @@ using namespace ::aare;
|
||||
|
||||
void define_file_io_bindings(py::module &m) {
|
||||
|
||||
py::enum_<DetectorType>(m, "DetectorType")
|
||||
.value("Jungfrau", DetectorType::Jungfrau)
|
||||
.value("Eiger", DetectorType::Eiger)
|
||||
.value("Mythen3", DetectorType::Mythen3)
|
||||
.value("Moench", DetectorType::Moench)
|
||||
.value("Moench03", DetectorType::Moench03)
|
||||
.value("Moench03_old", DetectorType::Moench03_old)
|
||||
.value("ChipTestBoard", DetectorType::ChipTestBoard)
|
||||
.value("Unknown", DetectorType::Unknown);
|
||||
|
||||
PYBIND11_NUMPY_DTYPE(DetectorHeader, frameNumber, expLength, packetNumber,
|
||||
bunchId, timestamp, modId, row, column, reserved,
|
||||
debug, roundRNumber, detType, version, packetMask);
|
||||
@@ -170,28 +161,5 @@ void define_file_io_bindings(py::module &m) {
|
||||
.def_property_readonly("stop", &ScanParameters::stop)
|
||||
.def_property_readonly("step", &ScanParameters::step);
|
||||
|
||||
py::class_<ROI>(m, "ROI")
|
||||
.def(py::init<>())
|
||||
.def(py::init<ssize_t, ssize_t, ssize_t, ssize_t>(), py::arg("xmin"),
|
||||
py::arg("xmax"), py::arg("ymin"), py::arg("ymax"))
|
||||
.def_readwrite("xmin", &ROI::xmin)
|
||||
.def_readwrite("xmax", &ROI::xmax)
|
||||
.def_readwrite("ymin", &ROI::ymin)
|
||||
.def_readwrite("ymax", &ROI::ymax)
|
||||
.def("__str__",
|
||||
[](const ROI &self) {
|
||||
return fmt::format("ROI: xmin: {} xmax: {} ymin: {} ymax: {}",
|
||||
self.xmin, self.xmax, self.ymin, self.ymax);
|
||||
})
|
||||
.def("__repr__",
|
||||
[](const ROI &self) {
|
||||
return fmt::format(
|
||||
"<ROI: xmin: {} xmax: {} ymin: {} ymax: {}>", self.xmin,
|
||||
self.xmax, self.ymin, self.ymax);
|
||||
})
|
||||
.def("__iter__", [](const ROI &self) {
|
||||
return py::make_iterator(&self.xmin, &self.ymax + 1); // NOLINT
|
||||
});
|
||||
|
||||
#pragma GCC diagnostic pop
|
||||
}
|
||||
@@ -17,18 +17,19 @@
|
||||
#include "bind_FastPedestal.hpp"
|
||||
#include "bind_Interpolator.hpp"
|
||||
#include "bind_MultiThreadedFileReader.hpp"
|
||||
#include "bind_Pedestal.hpp"
|
||||
#include "bind_PedestalTrackingPixelHistogram.hpp"
|
||||
#include "bind_PixelHistogram.hpp"
|
||||
#include "bind_PixelMap.hpp"
|
||||
#include "bind_RawFile.hpp"
|
||||
#include "bind_calibration.hpp"
|
||||
#include "bind_testing.hpp"
|
||||
|
||||
// TODO! migrate the other names
|
||||
#include "ctb_raw_file.hpp"
|
||||
#include "file.hpp"
|
||||
#include "fit.hpp"
|
||||
#include "jungfrau_data_file.hpp"
|
||||
#include "pedestal.hpp"
|
||||
#include "raw_master_file.hpp"
|
||||
#include "raw_sub_file.hpp"
|
||||
#include "var_cluster.hpp"
|
||||
@@ -90,6 +91,7 @@ PYBIND11_MODULE(_aare, m) {
|
||||
define_jungfrau_data_file_io_bindings(m);
|
||||
|
||||
bind_calibration(m);
|
||||
define_testing_bindings(m);
|
||||
|
||||
DEFINE_CLUSTER_BINDINGS(int, 3, 3, uint16_t, i);
|
||||
DEFINE_CLUSTER_BINDINGS(double, 3, 3, uint16_t, d);
|
||||
@@ -130,9 +132,6 @@ PYBIND11_MODULE(_aare, m) {
|
||||
DEFINE_BINDINGS_CLUSTERFINDER(double, 9, 9, uint16_t, d);
|
||||
DEFINE_BINDINGS_CLUSTERFINDER(float, 9, 9, uint16_t, f);
|
||||
|
||||
define_3x3_reduction<int, 3, 3, uint16_t>(m);
|
||||
define_3x3_reduction<double, 3, 3, uint16_t>(m);
|
||||
define_3x3_reduction<float, 3, 3, uint16_t>(m);
|
||||
define_3x3_reduction<int, 5, 5, uint16_t>(m);
|
||||
define_3x3_reduction<double, 5, 5, uint16_t>(m);
|
||||
define_3x3_reduction<float, 5, 5, uint16_t>(m);
|
||||
@@ -143,9 +142,6 @@ PYBIND11_MODULE(_aare, m) {
|
||||
define_3x3_reduction<double, 9, 9, uint16_t>(m);
|
||||
define_3x3_reduction<float, 9, 9, uint16_t>(m);
|
||||
|
||||
reduce_to_3x3<int, 3, 3, uint16_t>(m);
|
||||
reduce_to_3x3<double, 3, 3, uint16_t>(m);
|
||||
reduce_to_3x3<float, 3, 3, uint16_t>(m);
|
||||
reduce_to_3x3<int, 5, 5, uint16_t>(m);
|
||||
reduce_to_3x3<double, 5, 5, uint16_t>(m);
|
||||
reduce_to_3x3<float, 5, 5, uint16_t>(m);
|
||||
|
||||
+47
-18
@@ -41,31 +41,60 @@ template <typename T> py::array return_vector(std::vector<T> *vec) {
|
||||
free_when_done); // numpy array references this parent
|
||||
}
|
||||
|
||||
// todo rewrite generic
|
||||
template <class T, int Flags>
|
||||
auto get_shape_3d(const py::array_t<T, Flags> &arr) {
|
||||
return aare::Shape<3>{arr.shape(0), arr.shape(1), arr.shape(2)};
|
||||
// Create a NDView of a numpy array. NDView assumes C-order strides so we
|
||||
// reject anything that is not Ndim dimensional and C-contiguous instead of
|
||||
// silently reading the data in the wrong order.
|
||||
template <ssize_t Ndim, class T, int Flags>
|
||||
auto get_checked_shape(const py::array_t<T, Flags> &arr) {
|
||||
if (arr.ndim() != Ndim) {
|
||||
throw py::value_error(
|
||||
fmt::format("Expected {}D array, got {}D", Ndim, arr.ndim()));
|
||||
}
|
||||
if (!(arr.flags() & py::array::c_style)) {
|
||||
throw py::value_error(
|
||||
"Array is not C-contiguous. Use np.ascontiguousarray(arr)");
|
||||
}
|
||||
aare::Shape<Ndim> shape{};
|
||||
for (ssize_t i = 0; i < Ndim; ++i) {
|
||||
shape[i] = arr.shape(i);
|
||||
}
|
||||
return shape;
|
||||
}
|
||||
|
||||
template <ssize_t Ndim, class T, int Flags>
|
||||
auto make_view(py::array_t<T, Flags> &arr) {
|
||||
auto shape = get_checked_shape<Ndim>(arr);
|
||||
return aare::NDView<T, Ndim>(arr.mutable_data(), shape);
|
||||
}
|
||||
|
||||
// Read only view, also works for numpy arrays that are not writeable
|
||||
template <ssize_t Ndim, class T, int Flags>
|
||||
auto make_const_view(const py::array_t<T, Flags> &arr) {
|
||||
auto shape = get_checked_shape<Ndim>(arr);
|
||||
return aare::NDView<const T, Ndim>(arr.data(), shape);
|
||||
}
|
||||
|
||||
template <class T, int Flags> auto make_view_3d(py::array_t<T, Flags> &arr) {
|
||||
return aare::NDView<T, 3>(arr.mutable_data(), get_shape_3d<T, Flags>(arr));
|
||||
return make_view<3>(arr);
|
||||
}
|
||||
|
||||
template <class T, int Flags>
|
||||
auto get_shape_2d(const py::array_t<T, Flags> &arr) {
|
||||
return aare::Shape<2>{arr.shape(0), arr.shape(1)};
|
||||
}
|
||||
|
||||
template <class T, int Flags>
|
||||
auto get_shape_1d(const py::array_t<T, Flags> &arr) {
|
||||
return aare::Shape<1>{arr.shape(0)};
|
||||
}
|
||||
|
||||
template <class T, int Flags> auto make_view_2d(py::array_t<T, Flags> &arr) {
|
||||
return aare::NDView<T, 2>(arr.mutable_data(), get_shape_2d<T, Flags>(arr));
|
||||
return make_view<2>(arr);
|
||||
}
|
||||
template <class T, int Flags> auto make_view_1d(py::array_t<T, Flags> &arr) {
|
||||
return aare::NDView<T, 1>(arr.mutable_data(), get_shape_1d<T, Flags>(arr));
|
||||
return make_view<1>(arr);
|
||||
}
|
||||
|
||||
template <class T, int Flags>
|
||||
auto make_const_view_3d(const py::array_t<T, Flags> &arr) {
|
||||
return make_const_view<3>(arr);
|
||||
}
|
||||
template <class T, int Flags>
|
||||
auto make_const_view_2d(const py::array_t<T, Flags> &arr) {
|
||||
return make_const_view<2>(arr);
|
||||
}
|
||||
template <class T, int Flags>
|
||||
auto make_const_view_1d(const py::array_t<T, Flags> &arr) {
|
||||
return make_const_view<1>(arr);
|
||||
}
|
||||
|
||||
template <typename ClusterType> struct fmt_format_trait; // forward declaration
|
||||
|
||||
@@ -1,125 +0,0 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
|
||||
#include "aare/Pedestal.hpp"
|
||||
#include "np_helper.hpp"
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <pybind11/numpy.h>
|
||||
#include <pybind11/pybind11.h>
|
||||
#include <pybind11/stl.h>
|
||||
|
||||
namespace py = pybind11;
|
||||
|
||||
template <typename SUM_TYPE>
|
||||
void define_pedestal_bindings(py::module &m, const std::string &name) {
|
||||
|
||||
py::class_<Pedestal<SUM_TYPE>>(m, name.c_str(), py::buffer_protocol())
|
||||
.def(py::init<int, int, int>())
|
||||
.def(py::init<int, int>())
|
||||
.def("mean",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto mea = new NDArray<SUM_TYPE, 2>{};
|
||||
*mea = self.mean();
|
||||
return return_image_data(mea);
|
||||
})
|
||||
.def("view",
|
||||
[](py::object self_py) {
|
||||
auto &self = self_py.cast<Pedestal<SUM_TYPE> &>();
|
||||
auto v = self.view();
|
||||
std::array<py::ssize_t, 2> shape{
|
||||
static_cast<py::ssize_t>(v.shape(0)),
|
||||
static_cast<py::ssize_t>(v.shape(1))};
|
||||
std::array<py::ssize_t, 2> byte_strides{
|
||||
static_cast<py::ssize_t>(v.strides()[0]) *
|
||||
static_cast<py::ssize_t>(sizeof(SUM_TYPE)),
|
||||
static_cast<py::ssize_t>(v.strides()[1]) *
|
||||
static_cast<py::ssize_t>(sizeof(SUM_TYPE))};
|
||||
auto arr = py::array_t<SUM_TYPE>(shape, byte_strides, v.data(),
|
||||
self_py);
|
||||
arr.attr("setflags")(py::arg("write") = false);
|
||||
return arr;
|
||||
})
|
||||
.def("variance",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto var = new NDArray<SUM_TYPE, 2>{};
|
||||
*var = self.variance();
|
||||
return return_image_data(var);
|
||||
})
|
||||
.def("std",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto std = new NDArray<SUM_TYPE, 2>{};
|
||||
*std = self.std();
|
||||
return return_image_data(std);
|
||||
})
|
||||
.def("cached_std",
|
||||
[](Pedestal<SUM_TYPE> &self) {
|
||||
auto standard_deviation = new NDArray<SUM_TYPE, 2>{};
|
||||
*standard_deviation = self.cached_std();
|
||||
return return_image_data(standard_deviation);
|
||||
})
|
||||
.def(
|
||||
"__array_ufunc__",
|
||||
[](py::object self, py::object ufunc, const std::string &method,
|
||||
py::args inputs, py::kwargs kwargs) -> py::object {
|
||||
if (method != "__call__" || inputs.size() != 2 ||
|
||||
inputs[1].ptr() != self.ptr() ||
|
||||
py::cast<std::string>(ufunc.attr("__name__")) !=
|
||||
"subtract") {
|
||||
return py::reinterpret_borrow<py::object>(
|
||||
Py_NotImplemented);
|
||||
}
|
||||
|
||||
auto mean =
|
||||
py::module_::import("builtins").attr("memoryview")(self);
|
||||
return ufunc(inputs[0], mean, **kwargs);
|
||||
},
|
||||
"Support subtracting a Pedestal from a NumPy array.")
|
||||
.def("clear", py::overload_cast<>(&Pedestal<SUM_TYPE>::clear))
|
||||
.def_property_readonly("rows", &Pedestal<SUM_TYPE>::rows)
|
||||
.def_property_readonly("cols", &Pedestal<SUM_TYPE>::cols)
|
||||
.def_property_readonly("n_samples", &Pedestal<SUM_TYPE>::n_samples)
|
||||
.def_property_readonly("sum", &Pedestal<SUM_TYPE>::get_sum)
|
||||
.def_property_readonly("sum2", &Pedestal<SUM_TYPE>::get_sum2)
|
||||
.def("clone",
|
||||
[&](Pedestal<SUM_TYPE> &pedestal) {
|
||||
return Pedestal<SUM_TYPE>(pedestal);
|
||||
})
|
||||
// TODO! add push for other data types
|
||||
.def("push",
|
||||
[](Pedestal<SUM_TYPE> &pedestal, py::array_t<uint16_t> &f) {
|
||||
auto v = make_view_2d(f);
|
||||
pedestal.push(v);
|
||||
})
|
||||
.def(
|
||||
"push_with_threshold",
|
||||
[](Pedestal<SUM_TYPE> &pedestal,
|
||||
py::array_t<uint16_t, py::array::c_style> &f,
|
||||
py::array_t<SUM_TYPE, py::array::c_style> &threshold) {
|
||||
auto frame_view = make_view_2d(f);
|
||||
auto threshold_view = make_view_2d(threshold);
|
||||
pedestal.push_with_threshold(frame_view, threshold_view);
|
||||
},
|
||||
py::arg("frame").noconvert(), py::arg("threshold").noconvert())
|
||||
.def(
|
||||
"push_no_update",
|
||||
[](Pedestal<SUM_TYPE> &pedestal,
|
||||
py::array_t<uint16_t, py::array::c_style> &f) {
|
||||
auto v = make_view_2d(f);
|
||||
pedestal.push_no_update(v);
|
||||
},
|
||||
py::arg().noconvert())
|
||||
.def("update_mean", &Pedestal<SUM_TYPE>::update_mean)
|
||||
.def_buffer([](Pedestal<SUM_TYPE> &self) {
|
||||
auto mean = self.view();
|
||||
return py::buffer_info(
|
||||
const_cast<SUM_TYPE *>(mean.data()), sizeof(SUM_TYPE),
|
||||
py::format_descriptor<SUM_TYPE>::format(), 2,
|
||||
{static_cast<py::ssize_t>(mean.shape(0)),
|
||||
static_cast<py::ssize_t>(mean.shape(1))},
|
||||
{static_cast<py::ssize_t>(mean.strides()[0] * sizeof(SUM_TYPE)),
|
||||
static_cast<py::ssize_t>(mean.strides()[1] *
|
||||
sizeof(SUM_TYPE))},
|
||||
true);
|
||||
});
|
||||
}
|
||||
@@ -66,7 +66,8 @@ void define_raw_master_file_bindings(py::module &m) {
|
||||
|
||||
.def_property_readonly("total_frames_expected",
|
||||
&RawMasterFile::total_frames_expected)
|
||||
.def_property_readonly("geometry", &RawMasterFile::geometry)
|
||||
.def_property_readonly("detector_layout",
|
||||
&RawMasterFile::detector_layout)
|
||||
.def_property_readonly("udp_interfaces_per_module",
|
||||
&RawMasterFile::udp_interfaces_per_module)
|
||||
.def_property_readonly("analog_samples", &RawMasterFile::analog_samples,
|
||||
@@ -107,9 +108,46 @@ void define_raw_master_file_bindings(py::module &m) {
|
||||
return std::nullopt;
|
||||
}
|
||||
})
|
||||
.def_property_readonly("period", [](RawMasterFile &self) {
|
||||
double seconds =
|
||||
std::chrono::duration<double>(self.period()).count();
|
||||
return seconds;
|
||||
});
|
||||
.def_property_readonly("rois", &RawMasterFile::rois, R"(
|
||||
Get the ROIs defined in the master file
|
||||
|
||||
Returns
|
||||
----------
|
||||
List[ROI]
|
||||
List of ROIs (default complete ROI)
|
||||
)")
|
||||
.def_property_readonly("udp_port_types", &RawMasterFile::udp_port_types,
|
||||
R"(
|
||||
Get the types of UDP ports
|
||||
|
||||
Returns
|
||||
----------
|
||||
Optional[List[UDPPortPosition]]
|
||||
Optional vector of UDP port types as strings (only present for
|
||||
masterfile version >= 8.1)
|
||||
)")
|
||||
.def_property_readonly("disabled_udp_ports",
|
||||
&RawMasterFile::disabled_udp_ports, R"(
|
||||
Get the indices of disabled UDP ports
|
||||
|
||||
Returns
|
||||
----------
|
||||
List[int]
|
||||
Vector of disabled UDP port indices relative to UDP port types (empty if none are disabled)
|
||||
)")
|
||||
.def_property_readonly(
|
||||
"period",
|
||||
[](RawMasterFile &self) {
|
||||
double seconds =
|
||||
std::chrono::duration<double>(self.period()).count();
|
||||
return seconds;
|
||||
})
|
||||
|
||||
.def("__enter__",
|
||||
[](RawMasterFile &self) -> RawMasterFile & { return self; })
|
||||
|
||||
.def("__exit__",
|
||||
[]([[maybe_unused]] RawMasterFile &self,
|
||||
[[maybe_unused]] py::object, [[maybe_unused]] py::object,
|
||||
[[maybe_unused]] py::object) { return; });
|
||||
}
|
||||
@@ -57,7 +57,7 @@
|
||||
"text": [
|
||||
"Image size: (400, 400) cluster (3, 3)\n",
|
||||
"Pedestal frames: 1000\n",
|
||||
"Data frames: 10000 of 100000 in file\n"
|
||||
"Data frames: 100000 of 100000 in file\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -67,7 +67,7 @@
|
||||
"pd = File(base / 'Cu_factor_10_pedestal_master_0.json')\n",
|
||||
"\n",
|
||||
"n_frames_pd = 1000 # pedestal frames, taken from the head of the file\n",
|
||||
"N = 10000 # data frames, read after those\n",
|
||||
"N = 100000 # data frames, read after those\n",
|
||||
"cluster_size = (3, 3)\n",
|
||||
"rows, cols = f.rows, f.cols\n",
|
||||
"image_size = (rows, cols)\n",
|
||||
@@ -81,14 +81,14 @@
|
||||
"# counts each pedestal tracks on only 1/n of the frames while the CUDA finder's\n",
|
||||
"# single pedestal sees all of them, and the cluster counts drift apart. Keep it\n",
|
||||
"# low when comparing counts; raise it to measure CPU throughput.\n",
|
||||
"N_THREADS = 4\n",
|
||||
"N_THREADS = 24\n",
|
||||
"\n",
|
||||
"# Fixed per-frame output slot the kernel writes into, copied WHOLE on every D2H.\n",
|
||||
"# Too low does not error -- it TRUNCATES. The CUDA cell prints the peak actually\n",
|
||||
"# reached, which is how you size this for a new dataset.\n",
|
||||
"CAP = 3000\n",
|
||||
"\n",
|
||||
"capacity = 10_000 # initial ClusterVector capacity, CPU side\n",
|
||||
"capacity = 3_000 # initial ClusterVector capacity, CPU side\n",
|
||||
"N_BINS = 200\n",
|
||||
"E_MIN, E_MAX = -2, 4000 # spectrum range, ADU\n",
|
||||
"\n",
|
||||
@@ -113,11 +113,12 @@
|
||||
"outputs": [],
|
||||
"source": [
|
||||
"cf_cpu = ClusterFinderMT(image_size, cluster_size, n_sigma=N_SIGMA,\n",
|
||||
" capacity=capacity, n_threads=N_THREADS)\n",
|
||||
" capacity=capacity, min_pedestal_samples=n_frames_pd, n_threads=N_THREADS)\n",
|
||||
"sink = ClusterCollector(cf_cpu)\n",
|
||||
"\n",
|
||||
"cf_cuda = ClusterFinderCUDA(image_size, cluster_size, n_sigma=N_SIGMA,\n",
|
||||
" max_clusters_per_frame=CAP, n_streams=N_STREAMS)"
|
||||
" max_clusters_per_frame=CAP, n_streams=N_STREAMS, \n",
|
||||
" n_pedestal_frames=n_frames_pd, algorithm=\"fixed_window\", time_kernels=False)"
|
||||
]
|
||||
},
|
||||
{
|
||||
@@ -140,12 +141,12 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Pedestal (1000 frames): 0.86s\n"
|
||||
"Pedestal (1000 frames): 1.34s\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
"source": [
|
||||
"f.seek(0)\n",
|
||||
"pd.seek(0)\n",
|
||||
"t0 = time.perf_counter()\n",
|
||||
"for _ in range(n_frames_pd):\n",
|
||||
" pd_img = pd.read_frame()\n",
|
||||
@@ -174,7 +175,7 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"Reading 10000 frames: 5.15s (1,942 FPS, 3.20 GB at 0.62 GB/s)\n"
|
||||
"Reading 100000 frames: 5.20s (19,219 FPS, 32.00 GB at 6.15 GB/s)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -206,14 +207,14 @@
|
||||
"name": "stderr",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"100%|█████████████████████████████████████████| 10000/10000 [00:02<00:00, 3440.17it/s]\n"
|
||||
"100%|██████████████████████████████████████████████████████████████| 100000/100000 [00:23<00:00, 4310.91it/s]\n"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"CPU MT (4 threads): 2.91s 3,434 FPS 23,242,745 clusters (2324.3/frame)\n"
|
||||
"CPU MT (24 threads): 23.20s 4,310 FPS 233,099,227 clusters (2331.0/frame)\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -252,7 +253,7 @@
|
||||
},
|
||||
{
|
||||
"cell_type": "code",
|
||||
"execution_count": 14,
|
||||
"execution_count": 7,
|
||||
"id": "cuda",
|
||||
"metadata": {},
|
||||
"outputs": [
|
||||
@@ -260,10 +261,10 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"CUDA batched: 0.21s 48,578 FPS 23,244,600 clusters (2324.5/frame)\n",
|
||||
" input pinned in 0.08s, once, outside the loop\n",
|
||||
" vs CPU: 14.15x\n",
|
||||
" peak clusters in one frame: 2,522 of CAP 3,000\n"
|
||||
"CUDA batched: 3.18s 31,484 FPS 233,093,554 clusters (2330.9/frame)\n",
|
||||
" input pinned in 0.84s, once, outside the loop\n",
|
||||
" vs CPU: 7.30x\n",
|
||||
" peak clusters in one frame: 2,545 of CAP 3,000\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -319,10 +320,10 @@
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
" s FPS us/frame clusters\n",
|
||||
"CPU MT (4 thr) 2.91 3,434 291.2 23,242,745\n",
|
||||
"CUDA batched 0.55 18,074 55.3 23,244,269\n",
|
||||
"CPU MT (24 thr) 23.20 4,310 232.0 233,099,227\n",
|
||||
"CUDA batched 3.18 31,484 31.8 233,093,554\n",
|
||||
"\n",
|
||||
"speedup: 5.26x\n"
|
||||
"speedup: 7.30x\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -369,7 +370,7 @@
|
||||
{
|
||||
"data": {
|
||||
"image/png":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAA3kAAAKACAYAAAAhGrGwAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjgsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvwVt1zgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAiCJJREFUeJzt3QmcjPUfwPHv7IWEXDlyVq6QXIkuKkREF12ionSS+hcprA7pQHJ0IilUkg4KlaNIuUtKSpHcx7qt3X3+r+9vd6aZ2Znd2TXns5/36/XsPPPMM8/zm9/8Zvb5zu9yWJZlCQAAAADAFuIinQAAAAAAQPAQ5AEAAACAjRDkAQAAAICNEOQBAAAAgI0Q5AEAAACAjRDkAQAAAICNEOQBAAAAgI0Q5AEAAACAjRDkAQAAAICNEOQBiBlr166V22+/XapXry6FCxeWU089VRo1aiTPP/+87N2717Vfy5YtzRIq48aNk0mTJoXs+IgdlAVPTzzxhHTo0EHOOOMMcTgc0qNHD7959+eff8q1114rp512mvkst27dWlauXBlw3ufl+dOmTZPzzjvPfG9UrFhR+vbtK4cOHcq2n27Tx3Qf3Vefo88N1CuvvCJnn322JCUlmde/f//+gJ8LAMFEkAcgJrzxxhvSuHFj+fHHH+V///uffPHFFzJz5ky54YYb5NVXX5U777wzbGnhwh6UBd9Gjhwpe/bskauvvtoEOv7s2rVLLr74YtmwYYNMmDBB3n//fTl27Jj5cea3337LtYDl5fnvvvuu3HTTTdK0aVOZM2eODB482PxIowGiN9329ttvm310X32OPve9997LNU2rV6+WBx98UFq1aiVff/21LF26VIoVK5br8wAgJCwAiHJLliyx4uPjrSuvvNI6duxYtsePHz9uzZo1y3X/0ksvNUuo1K1bN+jHz8jIsI4cOWLFilhKayjlpSykpqZaJ06csOwsPT3dtV60aFGre/fuPvf73//+ZyUmJlp//fWXa1tKSopVpkwZq0uXLrmeJ9Dnp6WlWRUqVLDatGnj8fx3333X0kug2bNnu7Z9/vnnZtt7773nsW/r1q2tihUrmmPlZMqUKeb5y5YtyzX9hw8fznUfADgZ1OQBiHrPPvusafr0+uuvS6FChbI9rjUGWnPgz4IFC8zz9dbdX3/9Zba7N73UJmA33nijaa6l5ypXrpxcfvnl5ld6Va1aNVm3bp0sXLjQPFcX3eZ04MABeeSRR0yTUk2XNlvT5l+HDx/2OLc+7/777ze1kHXq1DHn0hqEnEyfPl2aN28uRYsWNc3T2rZtK6tWrfLYR5vH6WMbN26U9u3bm/XKlSvLww8/LMePH/fYNzU1VZ5++mmpXbu2OX/ZsmVNc1itJXGnr0+b4H300UfSsGFD04wtOTnZPKZ50aZNGznllFPM8++77z75/PPPPfL7qaeekoSEBNmyZUu213THHXdI6dKlTS2MP7m9J+5p1Nrdc88916TxzDPPlNGjR2c7XqDvUUZGhml+p032ihQpYpoFXnDBBfLJJ5/kWhacZe6dd94xea/n0LTr+zJkyBDzmDcth7pdy6X36/rss89M3ms6tLzofedz9L6WifPPP1+WL18ukRQXF9hlhb5Pl112mVStWtW1rXjx4qYm7dNPP5W0tLSgPP/777+Xbdu2mXLtTlsA6GdDj+N+TN2mj7nT5/7777+ybNkyv+nRGsRbb73VrDdr1syjqao+Vq9ePVm0aJG0aNHCfFa03Ds/0/r5qVChguu97d+/f7ay6Pxc//rrr+Zzr++3Pue5555zvc6LLrrIbK9Zs6bP75Lt27fL3XffLZUqVTLlXsu/fo6983r8+PHSoEEDcz6tidTvh8cffzzH9wNA9EmIdAIAICfp6emm6ZM21dRgJdQ0MNJzaj+/KlWqyO7du2XJkiWuvjV6IXj99ddLiRIlTLNN5Qw8jxw5Ipdeeqn8888/5qJIgw0NAgYNGiQ//fSTzJ8/3+Pi/uOPP5bFixebx8uXLy+nn356joGu9nfSC0691QDthRdeME3WfvjhBznnnHNc+544ccIEvdqEVQMMvbjUQEvTrOdyBjCdOnUy53/00UfNxefff/9tmqnpRakGC3rR6aR9ndavX2/OrReHejGpF8/6enVdLww1/VOnTjXBqzu9sHzmmWfktddeM0Glk/aj1P5Our8GZfl9T5w06NNgTYMozU9tptenTx+TVxrU5fU90gvrKVOmmHwcOnSouTDWfHAGYTmVBacBAwaYwFyDeQ2AcnqP/VmzZo05zsCBA8259MJcgxnd9tVXX7l+BHnsscdMQLhp0yaP9y7aHD16VP744w+55pprsj2m74c+roG9Bisn+/yff/7Ztd1dYmKiCV6cjytd1yBLf5DwPqbzcf2c+KLvv5Z9Ld8TJ040x9YfPZz0s6JBoH7W9P1yBsO///67Kd9abvVzpEHc8OHDzWdav/fc6eda3/fevXubJuvahFTLgP5oMWPGDPP+awCnP0xo2dXAUr83nQGe/gig59WyftZZZ5nmpJpeLc+aZqWfx3vvvVceeOABefHFF83++sPEL7/84vN1A4hiJ1UPCAAhtn37dtME6sYbbwz4Od7NNb/55htzDL11t2nTJrN94sSJ5v7u3bvN/VGjRuWrid6wYcOsuLg468cff/TY/uGHH2ZrGqb3S5QoYe3duzfX17N582YrISHBeuCBBzy2Hzx40CpfvrxH8zRtHqfHfv/99z32bd++vVWrVi3X/alTp5r9ZsyY4bGfpl23jxs3zrWtatWqprnsb7/9lq3JnMPhsNatW+exvW3bttnyW9N1+umnm6a1TsOHDzf5pe+DP4G+J5pGTcvq1auzNbUrXry4q3lcoO/RokWLzP2BAwfmqyw4y9wll1yS7bHBgwebx7xpOdTt7vmhr6tIkSLWP//849qmr1H302aI7s3+Pv74Y7P9k08+saKBv+aaW7duNenU98KbNpXUx7SJtj95ef4zzzxj7m/bti3bvtqEs2bNmq77NWrUMGXX27///muO8eyzz+b4ep3vn3fZ0vKh27/66qtcm2xrc96FCxea/desWZPtc+3+edV9y5Yta7avXLnStX3Pnj3m89qvXz/Xtrvvvts69dRTrb///tvjnC+++KJ5vvMzfP/991unnXZajukEEBtorpkL/QW8Y8eOppmQ/lKqv7znI5A2v4jpr4r6K6/WRugveQCiS6lSpcwv3FpDNmLECNMUUmu8AqVN6PTXc23ep02gnIs2r/LVXFSbm5UsWTLX43755ZfmOLfddpvHcbX2S2ulvI+r59LvLe/aCK2pc0+rNj/U/dyPqWnXWjDvY+rzvWtWtJmivl73WkSlA1V40xq1nTt3ygcffGDua75q7d9VV13l0dz1ZN6TunXrmmZm7m6++WZT0+EcdTHQ90gH3VDa/PRkXHfddXKyNK3a3NNJa5uU1rhq0z/v7e7vsy/urzuvSzD5arIayGP5eb6/fQPdL9A0+aOfc/28e9MaRy2j+pmLj483NYz6mVZac+59fq31c9IaRx3JU5ttalNe98+M1hh7f951QBi9lnF/P9u1a+f6LCut7dMacv0Mz5o1y9SaA4hNBHm50HbxetEwZsyYfGeyXty8+eabJtDTphjaX0C/SAHkrkyZMuZCVpughZpeRGnzN73g16aBOj2DNrnSEfMOHjyY6/N37NhhpnnQCzX3Rfu16I893hdMenEWCD2u0pH+vI+tfXq8j6v55d38UX9gcu/3psfUizltguh9TG3aFUhadRRF7R/nzdc2vQjVpqVjx451XXRqMzHvpp0n857ohbI35zZNa17eI+2XqBfdvo6ZF4G+xznRi3Z3zlEr/W3PqX+j8n7teVmCQQMefV+d74k751Qo3q8tv8/X/p7K377u59F985um/JQDna5BPxPa10+bTeoPDDp6sPZ9VdrsNLfPtb7nvtKl270/73rt4f1+6g8jylnuu3XrZkYr1QBRf6DQYFH7GM6bNy/frx1AZNAnLxf6K5fzly5ftK+H9lHRvh96waS/EGt7euccXfpLnP5arW35a9WqFdx3DygA9EJbB9nQmhXtR6V9TvLKeWHkPfCIr1+pdSCHt956y6zr8Ow6NLv28dLPuvaryi0g1b5QepHk7/H81Aw4n/fhhx96DDRxMvSYelGrU1H44j30u6+06vOdAag7DRJ90cBMB7XQWjX94UxrBnVus9wE+p74Oq9zm/NiP9D3SANJ7Qeozz+ZQM1XvrmXR/c+fOGqNdFAIpI0/7UGSvtAetNt+rgOmhOM59evX9+13b3GWWux9EdX91pn3Vf71elj7v3ynOfR/+/BLAfa504HdNHgzll7p0Ixt56Wa62N176xvmgNn5P2+9VFf+TW1kzaT1f7eupnL1jfPwBCjyDvJOkXof4arZ2V9UtSO+JfeeWV5p9CjRo1zC9n+s9Gf7XW7fpL8RVXXGF+kT6ZXwWBgkQHF5g9e7b06tXLNCHynn9LByTQYMW7iaKTszmg1uBojZCTc5REfzQI0R9xdFAD90mW9cLc+1d2pRdC2hRbAwodnCRYNM160amDTQSj+Z8zrfq9pYGM/lKfH3phqi0UdFAG9wtof5NH60AZOnCKDgajzcN0TrW8NoHz954oHUBFBylxb7Kpg1NowKo1gHl5j/THvWHDhpkf6XTQFX/8lYWcuJdHrZ110v8X4dCkSROJNC0Lo0aNMiOuOgdU0ppZrcXSQYO8Bz/J7/O1bGuQrqOQdu3a1fV8/cFEa9Lc58rTY+p8nFq23PfVkSr1/3t+Pyf+OMu+92A9OkBRsGm51+9QbfocSBNxpQPB6OdAf0zp3Lmz+XwR5AGxgyDvJOgFl/7qp7ULzl/BdAQ3vdjUkar0QkLb22uzB+2HMnnyZHNB9dBDD5kR2bxHzgLgm45OqBfbOuqbjhZ3zz33mGZGGtxpHy2dWkF/ZfcX5GmTO/1xRSLine truncated
|
||||
"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 truncated
|
||||
"text/plain": [
|
||||
"<Figure size 900x650 with 2 Axes>"
|
||||
]
|
||||
@@ -431,15 +432,15 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"CPU 23,242,745 clusters\n",
|
||||
"CUDA 23,244,269 clusters net +1,524 (0.0066%)\n",
|
||||
"CPU 233,099,227 clusters\n",
|
||||
"CUDA 233,093,554 clusters net -5,673 (0.0024%)\n",
|
||||
"\n",
|
||||
"exact-position mismatches CPU-only 1,976 CUDA-only 3,500\n",
|
||||
" of which shifted by 1 px 120 107\n",
|
||||
" genuine add / drop 1,856 3,393\n",
|
||||
"exact-position mismatches CPU-only 135,742 CUDA-only 130,069\n",
|
||||
" of which shifted by 1 px 104,347 104,198\n",
|
||||
" genuine add / drop 31,395 25,871\n",
|
||||
"\n",
|
||||
"frames touched by a genuine difference: 2,385 of 10,000\n",
|
||||
"[4.3s]\n"
|
||||
"frames touched by a genuine difference: 41,569 of 100,000\n",
|
||||
"[40.2s]\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
@@ -534,7 +535,7 @@
|
||||
{
|
||||
"data": {
|
||||
"image/png":
|
||||
"iVBORw0KGgoAAAANSUhEUgAAA3kAAAFeCAYAAAA4xtZyAAAAOnRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjEwLjgsIGh0dHBzOi8vbWF0cGxvdGxpYi5vcmcvwVt1zgAAAAlwSFlzAAAPYQAAD2EBqD+naQAAY95JREFUeJzt3Qd8FGX+x/FfQkIIEErovSi9SlGwHFUUFU+xVzjLqdhRsd3ZTuTUEz317F3s97frqaAoIr0piCAovfdQA0n2//o+44TNZhOSkLK7fN6v10B2dnZ2dubZ2fnN8zy/Jy4QCAQMAAAAABAT4st6AwAAAAAAxYcgDwAAAABiCEEeAAAAAMQQgjwAAAAAiCEEeQAAAAAQQwjyAAAAACCGEOQBAAAAQAwhyAMAAACAGEKQBwAAAAAxhCAPUe+nn36yv/zlL9asWTOrUKGCVa5c2bp06WIPPfSQbd68OXu53r17u6mkPPXUU/bKK6+U2PqjUXHtk7i4OLvnnnuyH2udmrd06dIcy/3tb3+zxo0bW0JCglWrVs3N27t3r1155ZVWr149K1eunHXu3PmgtwfRL7RMFdSuXbvc67799ttcz+VVLpHTa6+9Zueee661atXK4uPjrWnTpnnuoh07dtgNN9xg9evXd+d3fX/ffvvtAu/Swrx+1qxZ1r9/f/cbovPH4MGD7ffffw+77BNPPGGtW7e2pKQk99tz77332r59+wq0TV9//bV169bNKlWq5MrLhx9+aIcS7Sftu3/+85855r/zzjvWrl07S05Odvtlzpw57rumvyP1fFBQjz32mCtPKit6r8Jei+g14abQffj+++/beeedZ4cffrjbj/puXXDBBbZo0aJ81797925r2bKlW+e//vWvXOVV34lVq1YVaptR9hLKegOAg/H888/bsGHD3MXCLbfcYm3btnU/IDNmzLBnnnnGJk+ebB988EGpBTQ1a9a0oUOHlsr7RYOS2icnn3yyO7YK3HwfffSRjRw50u68804bOHCgu/iSp59+2p599ll3Uda1a1f3YwUUlYI8XdBL6IVauHKJ3F5//XVbu3atHXnkkZaVlZVvcKQL4+nTp7uLWV2Evvnmm+4iVq87//zzD7h7C/r6BQsWuOOpIPDdd9+1PXv22F133WXHHXecCzZq1aqVvazOM3//+9/ttttuswEDBrj16waTLoKfe+65fLcnEAjY2Wef7bbl448/doGefr8Otd+FLVu22LXXXps9b8OGDXbRRRfZiSee6J7X+Vv76LLLLnPzop2uR3Ss+/bta5988kmR1nHmmWfaTTfdlGOebmoGe/DBB61u3brud7B58+a2YsUKe+CBB9yN7ylTprggOhyV5507d4Z9rl+/fu67escdd9irr75apG1HGQkAUWrSpEmBcuXKBU488cTAnj17cj2fnp4e+Oijj7If9+rVy00lpV27dsW+/qysrMCuXbsC0aq49olOVXfffXe+y9x///1uuXXr1uWYf9lllwWSk5MDxWnnzp3Fuj6UvoKUqXA2bNhQ5NceKvbu3RvYt29fns9nZmZm/33yyScHmjRpEna5zz77zO3rN998M8f8448/PlC/fv1ARkZGvttRmNefddZZgZo1awa2bduWPW/p0qWBxMTEwIgRI7Lnbdy4MVChQoXAX//61xzrHDlyZCAuLi7w888/57tNK1eudNv04IMPBg7F84zKRYMGDQK33XZbjvkTJ050++Wdd94pk+0q6nf65Zdfdq89kOAyX5TfRb3H1VdffcDlQn//ZNWqVa4cX3rppWFfM3Xq1ED58uUD7733nnufhx9+ONcy//3vf9311vLlywu13ShbNNdE1NLdKTUt0J1Tv9YmWPny5e3UU0/N8/VqbqXXhza7UlMrzQ9uZqgmO2pepCY/eq86deq4u1u6wytqEvHzzz/bd999l92MIrgJUlpamt18882uqYa2q0GDBq4JUeidM73ummuucXf92rRp494rvztn6enpdt9997ll1RSpRo0a1qdPH5s0aVL2Mrojffvtt+d476uvvtq2bt1aoOYq+hzBNXF+k7Tx48fbVVdd5Wrq9L66Y7569eocr8tvn4Sj/XT55Ze79anGTXdwf/311wM2i9N6dSdddGz8z6L/X3jhBdcUxd8G/7jqd1N3jHXnXs1aqlev7u6UhjbP0t399u3b24QJE+zoo4+2ihUr2iWXXFKk46oaDB0rraNTp0726aef5vpsqlFQTYM+h46/7tRefPHF7lj7VAtyxRVXWMOGDd37+s3FMjIy7EDUJEq1D6pt0ufW9qhGItxd3KlTp9qgQYPc8VD5Ouyww9znK8z25tXcKlzTRh3HU045xe2XI444Inv7/P2k1+ix7ojrzrJq7EOPVbhmUCq/Byp7qklQ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 truncated
|
||||
"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 truncated
|
||||
"text/plain": [
|
||||
"<Figure size 900x360 with 1 Axes>"
|
||||
]
|
||||
@@ -546,7 +547,7 @@
|
||||
"name": "stdout",
|
||||
"output_type": "stream",
|
||||
"text": [
|
||||
"first half: -263 second half: +1,787\n"
|
||||
"first half: -2,032 second half: -3,641\n"
|
||||
]
|
||||
}
|
||||
],
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# ClusterFinderCUDA nsys probes
|
||||
|
||||
Per-engine GPU time per frame (kernel, H2D, D2H) for the CUDA cluster finder,
|
||||
traced with Nsight Systems on real MOENCH data. The tallest engine is the
|
||||
roofline: the engines overlap and PCIe is full-duplex, so throughput is bound by
|
||||
the max, not the sum.
|
||||
|
||||
These are *not* throughput numbers. nsys inflates wall clock several-fold by
|
||||
tracing every CUDA call. Use them to answer "what does the kernel cost" and
|
||||
"which engine binds", and measure sustained FPS separately without a profiler.
|
||||
|
||||
## Files
|
||||
|
||||
| file | role |
|
||||
|---|---|
|
||||
| `run_probes.py` | driver: runs each config under nsys, exports SQLite, writes `probes.csv` |
|
||||
| `nsys_kernel_probe.py` | the traced process: pedestal, one batched pass, exit |
|
||||
| `gpu_span.py` | reads the SQLite export, computes busy time, duty cycle, roofline |
|
||||
| `common.py` | paths, guards (fresh build, idle GPU), `env.json` stamp |
|
||||
|
||||
## Requirements
|
||||
|
||||
- A built tree with the CUDA extension: `build/aare/_aare_cuda*.so`. Run the
|
||||
scripts with a Python of the same minor version as the build, with numpy and
|
||||
matplotlib installed (`aare/__init__.py` imports both). On pc-moench-04 the
|
||||
build is 3.11 and the `py` conda environment works:
|
||||
`/home/ferjao_k/.conda/envs/py/bin/python`.
|
||||
- Nsight Systems. Default path `/opt/nvidia/nsight-systems/2024.5.1/bin/nsys`,
|
||||
override with `NSYS=...`.
|
||||
- The MOENCH dataset under `/mnt/sls_det_storage/.../2026032408/process/xrf/`
|
||||
(override with `AARE_PERF_DATA=<dir>`). 1000 pedestal frames, 20 000 data
|
||||
frames, 5 sigma.
|
||||
- An idle GPU. The driver aborts above 5 % utilisation: a competing process
|
||||
leaves per-op averages intact but ruins duty cycles and rooflines.
|
||||
|
||||
Paths are resolved relative to this folder. `AARE_REPO` and `AARE_BUILD`
|
||||
override the repo root and build directory.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd python/tests/perf
|
||||
python run_probes.py # full sweep: 4 configs, 20k frames each (~5 min)
|
||||
python run_probes.py --frames 2000 # smoke test only; clocks do not ramp, kernel reads ~7 % slow
|
||||
python run_probes.py --only 3x3_s1_uncontended 9x9_s1_uncontended --tag mychange
|
||||
```
|
||||
|
||||
Configs, matching the campaign in `docs/ClusterFinderCUDA_benchmark_results.md`
|
||||
on branch `bench/cuda_cf`:
|
||||
|
||||
| label | cluster | cap | streams | batch | frames |
|
||||
|---|---|---|---|---|---|
|
||||
| `3x3_s4` | 3x3 | 3000 | 4 | 2000 | 20 000 |
|
||||
| `3x3_s1_uncontended` | 3x3 | 3000 | 1 | 2000 | 20 000 |
|
||||
| `9x9_s4` | 9x9 | 1700 | 4 | 2000 | 20 000 |
|
||||
| `9x9_s1_uncontended` | 9x9 | 1700 | 1 | 2000 | 20 000 |
|
||||
|
||||
Keep the cap: at 9x9 the D2H slot is `4 + cap * sizeof(cluster)` and is copied
|
||||
whole, so the cap sets the D2H bar.
|
||||
|
||||
Output goes to `results/<date>_<f32|f64>[_tag]/`: `env.json` (git rev, dirty
|
||||
flag, driver, pedestal type), one `.nsys-rep` + `.sqlite` per config, and
|
||||
`probes.csv`. Re-running one config replaces its own row and keeps the others.
|
||||
|
||||
To inspect one trace by hand:
|
||||
|
||||
```bash
|
||||
nsys stats --report cuda_gpu_sum results/<dir>/probe_9x9_s1_uncontended_cap1700.nsys-rep
|
||||
python gpu_span.py results/<dir>/probe_9x9_s1_uncontended_cap1700.sqlite 20000
|
||||
```
|
||||
|
||||
`probes.csv` and `env.json` are small and can be committed with a result;
|
||||
the `.nsys-rep` and `.sqlite` traces are tens of MB each and are gitignored.
|
||||
|
||||
## Reading the numbers
|
||||
|
||||
- **Quote kernel changes from the `s1_uncontended` rows.** With one stream
|
||||
nothing overlaps, so the kernel column is the kernel alone. The 1-stream
|
||||
kernel and transfer numbers reproduce across sessions to about 1 %.
|
||||
- **4-stream transfer columns drift by up to 20 % between sessions** on an
|
||||
identical build (H2D and D2H fight for the PCIe link). Only compare s4
|
||||
rows taken in the same session, and read them for the bottleneck, not for
|
||||
a percentage.
|
||||
- A kernel below the tallest transfer bar is invisible end to end. Further
|
||||
kernel work only pays once it is the tallest bar.
|
||||
|
||||
## Reference, 2026-09-10, RTX 4090, driver 595.71.05, float pedestal
|
||||
|
||||
Kernel us/frame. "before" is commit 7177f00 (pre-refactor kernel, rebuilt and
|
||||
re-probed the same day, matching its August numbers): `results/2026-09-10_f32_ref7177/`.
|
||||
"after" is the kernel with the cooperative tile load, size-dependent unroll
|
||||
and two-phase load: `results/2026-09-10_f32/`.
|
||||
|
||||
| config | before | after | roofline after | binds |
|
||||
|---|--:|--:|--:|---|
|
||||
| 3x3, 1 stream | 4.32 | 4.65 | 13.13 | H2D |
|
||||
| 3x3, 4 streams | 5.00 | 5.64 | 16.35 | H2D |
|
||||
| 9x9, 1 stream | 23.80 | 15.29 | 22.00 | D2H |
|
||||
| 9x9, 4 streams | 24.72 | 15.59 | 25.39 | D2H |
|
||||
|
||||
Both sizes are transfer-bound; sustained throughput is unchanged (3x3 about
|
||||
61 400 FPS, 9x9 about 39 600 FPS on the zero-copy path).
|
||||
@@ -0,0 +1,102 @@
|
||||
"""Shared plumbing for the nsys probes: paths, guards, environment stamp.
|
||||
|
||||
Two guards are enforced here because both have produced wrong numbers before:
|
||||
a stale extension (header edited after the build) and a busy GPU (another
|
||||
process leaves per-op averages intact but destroys duty cycles).
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
REPO = Path(os.environ.get("AARE_REPO", HERE.parents[2]))
|
||||
BUILD = Path(os.environ.get("AARE_BUILD", REPO / "build"))
|
||||
sys.path.insert(0, str(BUILD))
|
||||
|
||||
DATA_DIR = Path(os.environ.get(
|
||||
"AARE_PERF_DATA",
|
||||
"/mnt/sls_det_storage/moench_data/2603_MaxIVBeamtime/2026032408/process/xrf/"))
|
||||
DATA_FILE = DATA_DIR / "Cu_factor_10_data_master_0.json"
|
||||
PEDESTAL_FILE = DATA_DIR / "Cu_factor_10_pedestal_master_0.json"
|
||||
|
||||
N_PEDESTAL_FRAMES = 1000
|
||||
N_SIGMA = 5
|
||||
|
||||
NSYS = os.environ.get("NSYS", "/opt/nvidia/nsight-systems/2024.5.1/bin/nsys")
|
||||
|
||||
|
||||
def _sh(cmd: str, default: str = "unknown") -> str:
|
||||
try:
|
||||
return subprocess.run(cmd, shell=True, capture_output=True, text=True,
|
||||
timeout=30).stdout.strip() or default
|
||||
except Exception:
|
||||
return default
|
||||
|
||||
|
||||
def device_ped_type() -> str:
|
||||
"""DEVICE_PED_TYPE from the kernel header (the float/double build axis)."""
|
||||
hdr = REPO / "include/aare/clusterfinder_kernel.cuh"
|
||||
for line in hdr.read_text().splitlines()[:40]:
|
||||
if "using DEVICE_PED_TYPE" in line and not line.strip().startswith("//"):
|
||||
return line.split("=")[1].split(";")[0].strip()
|
||||
return "unknown"
|
||||
|
||||
|
||||
def assert_build_fresh() -> None:
|
||||
"""Abort if a CUDA header is newer than the installed extension."""
|
||||
so = list((BUILD / "aare").glob("_aare_cuda*.so"))
|
||||
if not so:
|
||||
raise RuntimeError(f"no _aare_cuda*.so under {BUILD / 'aare'}")
|
||||
built = max(f.stat().st_mtime for f in so)
|
||||
headers = ["clusterfinder_kernel.cuh", "clusterfinder_algo.cuh",
|
||||
"ClusterFinderCUDA.hpp"]
|
||||
stale = [h for h in headers
|
||||
if (REPO / "include/aare" / h).stat().st_mtime > built]
|
||||
if stale:
|
||||
raise RuntimeError(f"{', '.join(stale)} newer than the extension: rebuild first")
|
||||
|
||||
|
||||
def assert_idle_gpu(max_pct: int = 5) -> None:
|
||||
pct = _sh("nvidia-smi --query-gpu=utilization.gpu --format=csv,noheader")
|
||||
try:
|
||||
val = int(pct.split()[0])
|
||||
except Exception:
|
||||
return
|
||||
if val > max_pct:
|
||||
raise SystemExit(f"GPU is {val}% busy: numbers would not be quotable. Aborting.")
|
||||
|
||||
|
||||
def capture_env() -> dict:
|
||||
import aare
|
||||
|
||||
return {
|
||||
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
|
||||
"host": _sh("hostname"),
|
||||
"git_rev": _sh(f"git -C {REPO} rev-parse --short HEAD"),
|
||||
"git_branch": _sh(f"git -C {REPO} rev-parse --abbrev-ref HEAD"),
|
||||
"git_dirty": bool(_sh(f"git -C {REPO} status --porcelain", default="")),
|
||||
"aare_version": getattr(aare, "__version__", "unknown"),
|
||||
"device_ped_type": device_ped_type(),
|
||||
"gpu": _sh("nvidia-smi --query-gpu=name --format=csv,noheader"),
|
||||
"driver": _sh("nvidia-smi --query-gpu=driver_version --format=csv,noheader"),
|
||||
"nvcc": _sh("nvcc --version | tail -1"),
|
||||
"python": sys.version.split()[0],
|
||||
}
|
||||
|
||||
|
||||
def results_dir(tag: str = "") -> Path:
|
||||
"""perf/results/<date>_<f32|f64>[_tag]/"""
|
||||
short = {"float": "f32", "double": "f64"}.get(device_ped_type(), "unk")
|
||||
name = f"{time.strftime('%Y-%m-%d')}_{short}" + (f"_{tag}" if tag else "")
|
||||
d = HERE / "results" / name
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
def write_env(path: Path, env: dict) -> None:
|
||||
path.write_text(json.dumps(env, indent=2) + "\n")
|
||||
@@ -0,0 +1,68 @@
|
||||
"""Per-engine busy time and duty cycle from an nsys SQLite export.
|
||||
|
||||
nsys stats --force-export=true --report cuda_gpu_sum <rep>.nsys-rep
|
||||
python gpu_span.py <rep>.sqlite <n_frames>
|
||||
|
||||
Per engine (kernel / H2D / D2H): sum of op durations, busy = union of the
|
||||
intervals (overlaps not double-counted), duty = busy / processing window.
|
||||
The window is first kernel start to last D2H end, so the pedestal-upload
|
||||
copies that precede any kernel are excluded.
|
||||
|
||||
Roofline = tallest engine's busy time per frame. PCIe is full-duplex and the
|
||||
engines overlap, so the floor is the max, never the sum.
|
||||
"""
|
||||
import sqlite3
|
||||
import sys
|
||||
|
||||
Q = {"kernel": "SELECT start,end FROM CUPTI_ACTIVITY_KIND_KERNEL ORDER BY start",
|
||||
"H2D": "SELECT start,end FROM CUPTI_ACTIVITY_KIND_MEMCPY WHERE copyKind=1 ORDER BY start",
|
||||
"D2H": "SELECT start,end FROM CUPTI_ACTIVITY_KIND_MEMCPY WHERE copyKind=2 ORDER BY start"}
|
||||
|
||||
|
||||
def union(rows):
|
||||
busy, cs, ce = 0, *rows[0]
|
||||
for s, e in rows[1:]:
|
||||
if s > ce:
|
||||
busy += ce - cs
|
||||
cs, ce = s, e
|
||||
else:
|
||||
ce = max(ce, e)
|
||||
return busy + ce - cs
|
||||
|
||||
|
||||
def analyze(sqlite_path, n_frames) -> dict:
|
||||
db = sqlite3.connect(str(sqlite_path))
|
||||
ops = {k: db.execute(q).fetchall() for k, q in Q.items()}
|
||||
lo = ops["kernel"][0][0]
|
||||
hi = max(ops["kernel"][-1][1], ops["D2H"][-1][1])
|
||||
span = hi - lo
|
||||
|
||||
out = {"n_frames": n_frames, "window_ms": span / 1e6,
|
||||
"window_us_per_frame": span / 1e3 / n_frames}
|
||||
for k, rows in ops.items():
|
||||
rows = [r for r in rows if r[1] > lo]
|
||||
tot, busy = sum(e - s for s, e in rows), union(rows)
|
||||
out[f"{k}_n"] = len(rows)
|
||||
out[f"{k}_sum_ms"] = tot / 1e6
|
||||
out[f"{k}_busy_ms"] = busy / 1e6
|
||||
out[f"{k}_overlap"] = tot / busy
|
||||
out[f"{k}_duty_pct"] = 100 * busy / span
|
||||
out[f"{k}_us_per_frame"] = busy / 1e3 / n_frames
|
||||
tallest = max(("kernel", "H2D", "D2H"), key=lambda k: out[f"{k}_us_per_frame"])
|
||||
out["bottleneck"] = tallest
|
||||
out["roofline_us_per_frame"] = out[f"{tallest}_us_per_frame"]
|
||||
out["roofline_fps"] = 1e6 / out["roofline_us_per_frame"]
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
N = int(sys.argv[2]) if len(sys.argv) > 2 else 2000
|
||||
r = analyze(sys.argv[1], N)
|
||||
print(f"processing window: {r['window_ms']:.1f} ms / {N} frames = "
|
||||
f"{r['window_us_per_frame']:.1f} us/frame")
|
||||
for k in ("kernel", "H2D", "D2H"):
|
||||
print(f" {k:6s} sum={r[k + '_sum_ms']:7.2f} ms busy={r[k + '_busy_ms']:7.2f} ms "
|
||||
f"overlap={r[k + '_overlap']:4.2f}x duty={r[k + '_duty_pct']:5.1f}% "
|
||||
f"per-frame={r[k + '_us_per_frame']:5.2f} us")
|
||||
print(f" roofline = {r['bottleneck']} at {r['roofline_us_per_frame']:.2f} us/frame "
|
||||
f"= {r['roofline_fps']:,.0f} FPS")
|
||||
@@ -0,0 +1,47 @@
|
||||
"""The process nsys traces: train the pedestal, run one batched pass, exit.
|
||||
|
||||
nsys_kernel_probe.py <n_streams> <n_frames> <cluster_dim> <cap> <batch>
|
||||
|
||||
Run by run_probes.py; run directly only under `nsys profile --trace=cuda`.
|
||||
The wall time printed is profiler-inflated and is not a throughput number.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402 (puts the build dir on sys.path)
|
||||
|
||||
from aare import File, ClusterFinderCUDA # noqa: E402
|
||||
|
||||
n_streams, N, cdim, cap, batch = (int(a) for a in sys.argv[1:6])
|
||||
|
||||
f = File(common.DATA_FILE)
|
||||
pd = File(common.PEDESTAL_FILE)
|
||||
|
||||
cf = ClusterFinderCUDA((f.rows, f.cols), (cdim, cdim), n_sigma=common.N_SIGMA,
|
||||
max_clusters_per_frame=cap, n_streams=n_streams)
|
||||
for _ in range(common.N_PEDESTAL_FRAMES):
|
||||
cf.push_pedestal_frame(pd.read_frame().copy())
|
||||
|
||||
data = f.read_n(N)
|
||||
cf.register_input_buffer(data)
|
||||
# Pin the output slots without processing frames: a warm-up pass would advance
|
||||
# the device pedestal and make this run incomparable with the next.
|
||||
cf.reserve_output_slots(cf.chunk_size_for(min(N, batch)))
|
||||
|
||||
t0 = time.perf_counter()
|
||||
n = 0
|
||||
for start in range(0, N, batch):
|
||||
for cv in cf.find_clusters_batched(data[start:min(start + batch, N)],
|
||||
first_frame=start):
|
||||
n += cv.size
|
||||
t = time.perf_counter() - t0
|
||||
cf.unregister_input_buffer()
|
||||
|
||||
h2d = f.rows * f.cols * 2
|
||||
slot = 2 + 2 + cdim * cdim * 4 # x, y (uint16) + data (int32)
|
||||
print(f"n_streams={n_streams} N={N} cluster={cdim}x{cdim} cap={cap} batch={batch}")
|
||||
print(f" H2D/frame={h2d:,} B D2H/frame={cap * slot:,} B "
|
||||
f"({slot} B/slot, {100 * n / N / cap:.0f}% filled)")
|
||||
print(f" wall={t:.3f}s ({N / t:.0f} FPS, profiler-inflated) clusters/frame={n / N:.2f}")
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"timestamp": "2026-09-10 13:37:02",
|
||||
"host": "pc-moench-04.psi.ch",
|
||||
"git_rev": "272b483",
|
||||
"git_branch": "testing/cuda_cf_api",
|
||||
"git_dirty": true,
|
||||
"aare_version": "2026.7.2",
|
||||
"device_ped_type": "float",
|
||||
"gpu": "NVIDIA GeForce RTX 4090",
|
||||
"driver": "595.71.05",
|
||||
"gpu_busy_pct": "0 %",
|
||||
"nvcc": "Build cuda_12.4.r12.4/compiler.34097967_0",
|
||||
"python": "3.11.15"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
n_frames,window_ms,window_us_per_frame,window_fps,kernel_n,kernel_sum_ms,kernel_busy_ms,kernel_overlap,kernel_duty_pct,kernel_us_per_frame,H2D_n,H2D_sum_ms,H2D_busy_ms,H2D_overlap,H2D_duty_pct,H2D_us_per_frame,D2H_n,D2H_sum_ms,D2H_busy_ms,D2H_overlap,D2H_duty_pct,D2H_us_per_frame,bottleneck,roofline_us_per_frame,roofline_fps,label,cluster_dim,cap,n_streams,batch,device_ped_type
|
||||
20000,467.758071,23.38790355,42757.145712617756,20000,112.903327,112.777756,1.0011134376534323,24.110274732170254,5.6388878,19999,326.931385,326.931385,1.0,69.89326433236467,16.34656925,20000,152.729782,152.729782,1.0,32.65144771815172,7.6364891,H2D,16.34656925,61174.91595369468,3x3_s4,3,3000,4,2000,float
|
||||
20000,861.486383,43.07431915,23215.689063305832,20000,92.96108,92.96108,1.0,10.790777641345493,4.648054,19999,262.616382,262.616382,1.0,30.484101337211733,13.130819099999998,20000,105.867334,105.867334,1.0,12.288915540525728,5.2933667,H2D,13.130819099999998,76156.71135093166,3x3_s1_uncontended,3,3000,1,2000,float
|
||||
20000,1502.075647,75.10378235,13314.908633226778,20000,312.858126,311.891228,1.0031001128380566,20.76401602162451,15.5945614,19999,414.382371,414.382371,1.0,27.58731704542441,20.719118549999997,20000,507.805309,507.805309,1.0,33.806906464012464,25.39026545,D2H,25.39026545,39385.17310775103,9x9_s4,9,1700,4,2000,float
|
||||
20000,1652.407506,82.6203753,12103.551894661994,20000,305.830789,305.830789,1.0,18.508194128234614,15.29153945,19999,264.610496,264.610496,1.0,16.01363435104125,13.2305248,20000,440.039995,440.039995,1.0,26.630234576046522,22.00199975,D2H,22.00199975,45450.41411519878,9x9_s1_uncontended,9,1700,1,2000,float
|
||||
|
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"timestamp": "2026-09-10 12:31:37",
|
||||
"host": "pc-moench-04.psi.ch",
|
||||
"git_rev": "7177f00",
|
||||
"git_branch": "HEAD",
|
||||
"git_dirty": true,
|
||||
"aare_version": "2026.7.2",
|
||||
"device_ped_type": "float",
|
||||
"gpu": "NVIDIA GeForce RTX 4090",
|
||||
"driver": "595.71.05",
|
||||
"gpu_busy_pct": "0 %",
|
||||
"nvcc": "Build cuda_12.4.r12.4/compiler.34097967_0",
|
||||
"python": "3.11.15"
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
n_frames,window_ms,window_us_per_frame,window_fps,kernel_n,kernel_sum_ms,kernel_busy_ms,kernel_overlap,kernel_duty_pct,kernel_us_per_frame,H2D_n,H2D_sum_ms,H2D_busy_ms,H2D_overlap,H2D_duty_pct,H2D_us_per_frame,D2H_n,D2H_sum_ms,D2H_busy_ms,D2H_overlap,D2H_duty_pct,D2H_us_per_frame,bottleneck,roofline_us_per_frame,roofline_fps,label,cluster_dim,cap,n_streams,batch,device_ped_type
|
||||
20000,657.208045,32.86040225,30431.763810803626,20000,100.861444,100.083645,1.0077714895375762,15.228609229821586,5.00418225,19999,316.797856,316.797856,1.0,48.20358764780489,15.839892800000001,20000,144.76269,144.76269,1.0,22.02691995348292,7.2381345,H2D,15.839892800000001,63131.740386525846,3x3_s4,3,3000,4,2000,float
|
||||
20000,1151.676025,57.58380124999999,17365.99492031624,20000,86.388419,86.388419,1.0,7.501104227640755,4.31942095,19999,262.127428,262.127428,1.0,22.760517915617807,13.1063714,20000,105.9432,105.9432,1.0,9.199045365210237,5.29716,H2D,13.1063714,76298.76870420443,3x3_s1_uncontended,3,3000,1,2000,float
|
||||
20000,1845.553098,92.2776549,10836.85970437465,20000,511.593396,494.436337,1.0347002388701865,26.790686084069524,24.72181685,19999,342.849695,342.849695,1.0,18.577070222013194,17.14248475,20000,495.751951,495.751951,1.0,26.86197170578508,24.78759755,D2H,24.78759755,40342.75600863949,9x9_s4,9,1700,4,2000,float
|
||||
20000,2824.450123,141.22250615000002,7081.0243158965495,20000,475.987403,475.987403,1.0,16.852391873517252,23.799370149999998,19999,262.138573,262.138573,1.0,9.281048047737114,13.10692865,20000,439.610736,439.610736,1.0,15.564471555725893,21.9805368,kernel,23.799370149999998,42017.918696894594,9x9_s1_uncontended,9,1700,1,2000,float
|
||||
|
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python3
|
||||
"""nsys probe sweep: per-engine GPU time per frame, duty cycles, roofline.
|
||||
|
||||
python3.11 run_probes.py # full sweep, 20k frames
|
||||
python3.11 run_probes.py --frames 2000 # quick check (clocks may not ramp)
|
||||
python3.11 run_probes.py --only 9x9_s1_uncontended --tag mytag
|
||||
|
||||
Per config: an .nsys-rep + .sqlite in results/<date>_<f32|f64>[_tag]/ and one
|
||||
row in probes.csv (re-running a config replaces its own row only).
|
||||
|
||||
20 000 frames, not fewer: over a short run the GPU clocks never fully ramp and
|
||||
the kernel reads ~10 % slow.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import csv
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402
|
||||
import gpu_span # noqa: E402
|
||||
|
||||
HERE = Path(__file__).resolve().parent
|
||||
|
||||
# (cluster_dim, cap, n_streams, label)
|
||||
# s4 = the production configuration.
|
||||
# s1 = uncontended control: one stream, so H2D and D2H never coexist and the
|
||||
# kernel number is the kernel alone. Quote kernel changes from s1.
|
||||
# The cap sets the D2H bar (the slot is copied whole regardless of fill), so a
|
||||
# probe at a different cap is a different measurement.
|
||||
CONFIGS = [
|
||||
(3, 3000, 4, "3x3_s4"),
|
||||
(3, 3000, 1, "3x3_s1_uncontended"),
|
||||
(9, 1700, 4, "9x9_s4"),
|
||||
(9, 1700, 1, "9x9_s1_uncontended"),
|
||||
]
|
||||
|
||||
|
||||
def run_one(cdim, cap, streams, label, n_frames, batch, outdir) -> dict | None:
|
||||
rep = outdir / f"probe_{label}_cap{cap}"
|
||||
print(f"\n--- {label}: {cdim}x{cdim} cap={cap} streams={streams} N={n_frames} ---")
|
||||
|
||||
prof = [common.NSYS, "profile", "--trace=cuda", "--sample=none",
|
||||
"--cpuctxsw=none", "--force-overwrite=true", "-o", str(rep),
|
||||
sys.executable, str(HERE / "nsys_kernel_probe.py"),
|
||||
str(streams), str(n_frames), str(cdim), str(cap), str(batch)]
|
||||
p = subprocess.run(prof, capture_output=True, text=True)
|
||||
for line in p.stdout.splitlines():
|
||||
if line.strip().startswith(("n_streams", "H2D/frame", "wall")):
|
||||
print(" ", line.strip())
|
||||
if not rep.with_suffix(".nsys-rep").exists():
|
||||
print(f" FAILED: {p.stderr.strip()[-400:]}")
|
||||
return None
|
||||
|
||||
subprocess.run([common.NSYS, "stats", "--force-export=true", "--report",
|
||||
"cuda_gpu_sum", str(rep.with_suffix(".nsys-rep"))],
|
||||
capture_output=True, text=True)
|
||||
sq = rep.with_suffix(".sqlite")
|
||||
if not sq.exists():
|
||||
print(" FAILED: no sqlite export")
|
||||
return None
|
||||
|
||||
r = gpu_span.analyze(sq, n_frames)
|
||||
r.update(label=label, cluster_dim=cdim, cap=cap, n_streams=streams,
|
||||
batch=batch, device_ped_type=common.device_ped_type())
|
||||
print(f" kernel {r['kernel_us_per_frame']:5.2f} us (duty {r['kernel_duty_pct']:4.1f}%) "
|
||||
f"H2D {r['H2D_us_per_frame']:5.2f} ({r['H2D_duty_pct']:4.1f}%) "
|
||||
f"D2H {r['D2H_us_per_frame']:5.2f} ({r['D2H_duty_pct']:4.1f}%)")
|
||||
print(f" -> roofline: {r['bottleneck']}-bound at "
|
||||
f"{r['roofline_us_per_frame']:.2f} us/frame = {r['roofline_fps']:,.0f} FPS")
|
||||
return r
|
||||
|
||||
|
||||
def main() -> int:
|
||||
ap = argparse.ArgumentParser(description=__doc__,
|
||||
formatter_class=argparse.RawDescriptionHelpFormatter)
|
||||
ap.add_argument("--frames", type=int, default=20_000)
|
||||
ap.add_argument("--batch", type=int, default=2000)
|
||||
ap.add_argument("--tag", default="")
|
||||
ap.add_argument("--only", nargs="+", default=None, help="subset of labels")
|
||||
ap.add_argument("--cap", type=int, default=None, help="override every cap")
|
||||
args = ap.parse_args()
|
||||
|
||||
common.assert_build_fresh()
|
||||
common.assert_idle_gpu()
|
||||
env = common.capture_env()
|
||||
outdir = common.results_dir(args.tag)
|
||||
common.write_env(outdir / "env.json", env)
|
||||
print(f"build: DEVICE_PED_TYPE={env['device_ped_type']} git={env['git_rev']}"
|
||||
f"{' (dirty)' if env['git_dirty'] else ''}")
|
||||
print(f"out: {outdir}")
|
||||
|
||||
rows = []
|
||||
for cdim, cap, streams, label in CONFIGS:
|
||||
if args.only and label not in args.only:
|
||||
continue
|
||||
r = run_one(cdim, args.cap or cap, streams, label, args.frames, args.batch, outdir)
|
||||
if r:
|
||||
rows.append(r)
|
||||
|
||||
if not rows:
|
||||
return 1
|
||||
out = outdir / "probes.csv"
|
||||
|
||||
def key(r):
|
||||
return (str(r["label"]), str(r["cap"]), str(r["n_streams"]))
|
||||
|
||||
prior = list(csv.DictReader(out.open())) if out.exists() else []
|
||||
fresh = {key(r) for r in rows}
|
||||
merged = [r for r in prior if key(r) not in fresh] + rows
|
||||
with out.open("w", newline="") as fh:
|
||||
w = csv.DictWriter(fh, fieldnames=list(rows[0]))
|
||||
w.writeheader()
|
||||
w.writerows(merged)
|
||||
|
||||
print(f"\n=== rooflines ({env['device_ped_type']} build, us/frame) ===")
|
||||
print(f"{'config':<22} {'kernel':>8} {'H2D':>8} {'D2H':>8} "
|
||||
f"{'bottleneck':<10} {'roofline':>9} {'FPS':>10}")
|
||||
for r in rows:
|
||||
print(f"{r['label']:<22} {r['kernel_us_per_frame']:8.2f} "
|
||||
f"{r['H2D_us_per_frame']:8.2f} {r['D2H_us_per_frame']:8.2f} "
|
||||
f"{r['bottleneck']:<10} {r['roofline_us_per_frame']:9.2f} "
|
||||
f"{r['roofline_fps']:10,.0f}")
|
||||
print(f"\n-> {out}")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -3,7 +3,7 @@ import pytest
|
||||
import numpy as np
|
||||
|
||||
from aare import _aare #import the C++ module
|
||||
from aare import corner
|
||||
from aare import ROI, corner
|
||||
from conftest import test_data_path
|
||||
|
||||
|
||||
@@ -91,6 +91,22 @@ def test_calculate_eta():
|
||||
assert eta2.sum == 4
|
||||
|
||||
|
||||
def test_cluster_representations():
|
||||
"""Test Cluster representation"""
|
||||
|
||||
cluster = _aare.Cluster2x2i(5, 6, np.array([1, 2, 3, 4], dtype=np.int32))
|
||||
assert repr(cluster) == "Cluster2x2i(x=5, y=6, data=[[1, 2], [3, 4]])"
|
||||
|
||||
def test_eta_representations():
|
||||
"""Test Eta representation"""
|
||||
eta = _aare.Etai()
|
||||
eta.x = 0.25
|
||||
eta.y = 0.75
|
||||
eta.c = corner.cBottomRight
|
||||
eta.sum = 42
|
||||
assert repr(eta) == "Etai(x=0.25, y=0.75, c=BottomRight, sum=42)"
|
||||
|
||||
|
||||
def test_max_sum():
|
||||
"""Max 2x2 Sum"""
|
||||
cluster = _aare.Cluster3x3i(5,5,np.array([1, 1, 1, 2, 3, 1, 2, 2, 1], dtype=np.int32))
|
||||
@@ -146,4 +162,3 @@ def test_3x3_reduction():
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -6,10 +6,279 @@ import boost_histogram as bh
|
||||
import time
|
||||
from pathlib import Path
|
||||
import pickle
|
||||
import struct
|
||||
import gc
|
||||
import weakref
|
||||
|
||||
from aare import ClusterFile
|
||||
from aare import ClusterFile, ROI
|
||||
from conftest import test_data_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def iterator_file(tmp_path):
|
||||
fname = tmp_path / "iteration.clust"
|
||||
records = [
|
||||
(-11, []),
|
||||
(42, [(5, 6, 10), (7, 8, 20)]),
|
||||
(103, []),
|
||||
(104, [(5, 6, 30), (7, 8, 40)]),
|
||||
(105, []),
|
||||
]
|
||||
fname.write_bytes(b"".join(
|
||||
struct.pack("@iI", number, len(clusters))
|
||||
+ b"".join(struct.pack("@HH9i", x, y, *([value] * 9))
|
||||
for x, y, value in clusters)
|
||||
for number, clusters in records
|
||||
))
|
||||
return fname
|
||||
|
||||
|
||||
def test_frames_preserve_empty_frames_and_frame_numbers(iterator_file):
|
||||
with ClusterFile(iterator_file) as reader:
|
||||
frames = reader.frames()
|
||||
assert iter(frames) is frames
|
||||
assert reader.tell() == 0
|
||||
results = list(frames)
|
||||
assert [frame.frame_number for frame in results] == [-11, 42, 103, 104, 105]
|
||||
assert [frame.size for frame in results] == [0, 2, 0, 2, 0]
|
||||
for _ in range(2):
|
||||
with pytest.raises(StopIteration):
|
||||
next(frames)
|
||||
assert list(reader.frames()) == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("chunk_size, sizes", [(1, [1, 1, 1, 1]), (2, [2, 2]),
|
||||
(3, [3, 1]), (10, [4])])
|
||||
@pytest.mark.parametrize("explicit", [False, True])
|
||||
def test_chunks_cross_frames(iterator_file, chunk_size, sizes, explicit):
|
||||
with ClusterFile(iterator_file, chunk_size=chunk_size) as reader:
|
||||
chunks = reader.chunks(chunk_size=chunk_size) if explicit else reader.chunks()
|
||||
assert iter(chunks) is chunks
|
||||
assert reader.tell() == 0
|
||||
results = list(chunks)
|
||||
assert [chunk.size for chunk in results] == sizes
|
||||
data = np.concatenate([np.asarray(chunk) for chunk in results])
|
||||
np.testing.assert_array_equal(data["x"], [5, 7, 5, 7])
|
||||
np.testing.assert_array_equal(data["data"][:, 0, 0], [10, 20, 30, 40])
|
||||
for _ in range(2):
|
||||
with pytest.raises(StopIteration):
|
||||
next(chunks)
|
||||
|
||||
|
||||
def test_chunk_override_preserves_default_iteration(iterator_file):
|
||||
with ClusterFile(iterator_file, chunk_size=2) as reader:
|
||||
assert iter(reader) is reader
|
||||
assert next(reader.chunks(1)).size == 1
|
||||
assert [chunk.size for chunk in reader] == [2, 1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_roi", [False, True])
|
||||
@pytest.mark.parametrize("use_noise", [False, True])
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_iterators_apply_filters_and_gain(iterator_file, use_roi, use_noise, method):
|
||||
with ClusterFile(iterator_file, chunk_size=3) as reader:
|
||||
if use_roi:
|
||||
reader.set_roi(ROI(0, 6, 0, 12))
|
||||
if use_noise:
|
||||
reader.set_noise_map(np.full((12, 12), 15, dtype=np.int32))
|
||||
reader.set_gain_map(np.full((12, 12), 2.0))
|
||||
results = list(getattr(reader, method)())
|
||||
if method == "frames":
|
||||
assert [frame.frame_number for frame in results] == [-11, 42, 103, 104, 105]
|
||||
expected = [value / 2 for x, value in [(5, 10), (7, 20), (5, 30), (7, 40)]
|
||||
if (not use_roi or x == 5) and (not use_noise or value > 15)]
|
||||
data = np.concatenate([np.asarray(result) for result in results])
|
||||
np.testing.assert_array_equal(data["data"][:, 0, 0], expected)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_iterators_handle_all_rejected_clusters(iterator_file, method):
|
||||
with ClusterFile(iterator_file) as reader:
|
||||
reader.set_roi(ROI(0, 1, 0, 1))
|
||||
results = list(getattr(reader, method)())
|
||||
assert len(results) == (5 if method == "frames" else 0)
|
||||
assert all(result.size == 0 for result in results)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_iterator_keeps_file_alive(iterator_file, method):
|
||||
reader = ClusterFile(iterator_file)
|
||||
owner = weakref.ref(reader)
|
||||
iterator = getattr(reader, method)()
|
||||
del reader
|
||||
gc.collect()
|
||||
assert owner() is not None
|
||||
results = list(iterator)
|
||||
assert sum(result.size for result in results) == 4
|
||||
del iterator
|
||||
gc.collect()
|
||||
assert owner() is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_retained_results_and_numpy_views_own_storage(iterator_file, method):
|
||||
with ClusterFile(iterator_file, chunk_size=2) as reader:
|
||||
reader.read_frame() # Skip the initial empty frame.
|
||||
iterator = getattr(reader, method)()
|
||||
first = next(iterator)
|
||||
array = np.asarray(first)
|
||||
expected = array.copy()
|
||||
results = list(iterator)
|
||||
np.testing.assert_array_equal(np.asarray(first), expected)
|
||||
del first, results, iterator, reader
|
||||
gc.collect()
|
||||
np.testing.assert_array_equal(array, expected)
|
||||
|
||||
|
||||
def test_frame_iteration_resumes_without_reading_ahead(iterator_file):
|
||||
with ClusterFile(iterator_file) as reader:
|
||||
reader.read_frame()
|
||||
for frame in reader.frames():
|
||||
assert frame.frame_number == 42
|
||||
break
|
||||
assert reader.read_frame().frame_number == 103
|
||||
assert [frame.frame_number for frame in reader.frames()] == [104, 105]
|
||||
|
||||
|
||||
def test_partial_chunk_must_be_completed_before_frame_iteration(iterator_file):
|
||||
with ClusterFile(iterator_file) as reader:
|
||||
for chunk in reader.chunks(1):
|
||||
assert chunk.size == 1
|
||||
break
|
||||
with pytest.raises(RuntimeError, match="clusters left"):
|
||||
next(reader.frames())
|
||||
assert reader.read_clusters(1).size == 1
|
||||
assert [frame.frame_number for frame in reader.frames()] == [103, 104, 105]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_empty_iterators(tmp_path, method):
|
||||
fname = tmp_path / "empty.clust"
|
||||
fname.touch()
|
||||
with ClusterFile(fname) as reader:
|
||||
iterator = getattr(reader, method)()
|
||||
for _ in range(2):
|
||||
with pytest.raises(StopIteration):
|
||||
next(iterator)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
@pytest.mark.parametrize("started", [False, True])
|
||||
def test_iterators_reject_closed_files(iterator_file, method, started):
|
||||
reader = ClusterFile(iterator_file, chunk_size=1)
|
||||
iterator = getattr(reader, method)()
|
||||
if started:
|
||||
next(iterator)
|
||||
reader.close()
|
||||
with pytest.raises(RuntimeError, match="not opened for reading"):
|
||||
next(iterator)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
@pytest.mark.parametrize("mode", ["w", "a"])
|
||||
def test_iterators_reject_writing_modes(tmp_path, method, mode):
|
||||
with ClusterFile(tmp_path / "output.clust", mode=mode) as reader:
|
||||
with pytest.raises(RuntimeError, match="not opened for reading"):
|
||||
next(getattr(reader, method)())
|
||||
|
||||
|
||||
def test_chunk_sizes_must_be_positive(iterator_file):
|
||||
with ClusterFile(iterator_file, chunk_size=0) as reader:
|
||||
with pytest.raises(ValueError, match="greater than zero"):
|
||||
reader.chunks()
|
||||
with pytest.raises(ValueError, match="greater than zero"):
|
||||
reader.chunks(0)
|
||||
with pytest.raises(ValueError, match="greater than zero"):
|
||||
next(reader)
|
||||
with pytest.raises(TypeError):
|
||||
reader.chunks(-1)
|
||||
assert reader.tell() == 0
|
||||
assert reader.read_clusters(0).size == 0
|
||||
assert len(list(reader.frames())) == 5
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method", ["frames", "chunks"])
|
||||
def test_iterators_defer_read_errors_until_next_result(tmp_path, method):
|
||||
fname = tmp_path / "truncated.clust"
|
||||
cluster = struct.pack("@HH9i", 5, 6, *range(9))
|
||||
frame = struct.pack("@iI", 42, 1) + cluster
|
||||
fname.write_bytes(frame + frame[:-1])
|
||||
with ClusterFile(fname, chunk_size=1) as reader:
|
||||
iterator = getattr(reader, method)()
|
||||
assert next(iterator).size == 1
|
||||
assert reader.tell() == len(frame)
|
||||
with pytest.raises(RuntimeError):
|
||||
next(iterator)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"shape, dtype",
|
||||
[(shape, dtype)
|
||||
for shape in [(2, 2), (3, 3), (5, 5), (7, 7), (9, 9)]
|
||||
for dtype in [np.int32, np.float32, np.float64]]
|
||||
+ [((3, 3), np.int16)],
|
||||
)
|
||||
def test_iterators_are_bound_for_each_cluster_type(tmp_path, shape, dtype):
|
||||
fname = tmp_path / "typed_frames.clust"
|
||||
values = list(range(shape[0] * shape[1]))
|
||||
record = struct.pack("@HH" + np.dtype(dtype).char * len(values), 5, 6, *values)
|
||||
fname.write_bytes((struct.pack("@iI", -42, 1) + record) * 3)
|
||||
with ClusterFile(fname, cluster_size=shape, dtype=dtype) as reader:
|
||||
frame = next(reader.frames())
|
||||
assert frame.frame_number == -42
|
||||
np.testing.assert_array_equal(np.asarray(frame)["data"].reshape(-1), values)
|
||||
chunks = list(reader.chunks())
|
||||
assert len(chunks) == 1
|
||||
assert chunks[0].size == 2
|
||||
np.testing.assert_array_equal(np.asarray(chunks[0])["data"].reshape(-1), values * 2)
|
||||
|
||||
|
||||
def test_read_frame_returns_none_at_eof(tmp_path):
|
||||
fname = tmp_path / "empty.clust"
|
||||
fname.touch()
|
||||
|
||||
with ClusterFile(fname) as f:
|
||||
assert f.read_frame() is None
|
||||
|
||||
|
||||
def test_read_frame_raises_for_malformed_file(tmp_path):
|
||||
fname = tmp_path / "malformed.clust"
|
||||
fname.write_bytes(b"\x00")
|
||||
|
||||
with ClusterFile(fname) as f, pytest.raises(RuntimeError):
|
||||
f.read_frame()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("use_roi", [False, True])
|
||||
@pytest.mark.parametrize("method", ["read_clusters", "default", "frames", "chunks"])
|
||||
@pytest.mark.parametrize(
|
||||
"size",
|
||||
[
|
||||
pytest.param(3, id="partial-frame-number"),
|
||||
pytest.param(4, id="missing-cluster-count"),
|
||||
pytest.param(7, id="partial-cluster-count"),
|
||||
pytest.param(48, id="missing-cluster-record"),
|
||||
pytest.param(87, id="partial-cluster-record"),
|
||||
],
|
||||
)
|
||||
def test_chunk_reads_reject_incomplete_frames(tmp_path, use_roi, method, size):
|
||||
fname = tmp_path / "incomplete.clust"
|
||||
cluster = struct.pack("@HH9i", 5, 6, *range(9))
|
||||
frame = struct.pack("@iI", 42, 2) + cluster * 2
|
||||
fname.write_bytes(frame[:size])
|
||||
|
||||
with ClusterFile(fname) as reader:
|
||||
if use_roi:
|
||||
reader.set_roi(ROI(0, 10, 0, 10))
|
||||
with pytest.raises(RuntimeError):
|
||||
if method == "default":
|
||||
next(reader)
|
||||
elif method == "read_clusters":
|
||||
reader.read_clusters(10)
|
||||
else:
|
||||
next(getattr(reader, method)())
|
||||
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_cluster_file(test_data_path):
|
||||
"""Test ClusterFile"""
|
||||
|
||||
@@ -83,12 +83,15 @@ def test_make_a_hitmap_from_cluster_vector():
|
||||
|
||||
def test_2x2_reduction():
|
||||
cv = ClusterVector((3,3))
|
||||
cv.frame_number = -135
|
||||
|
||||
cv.push_back(_aare.Cluster3x3i(5, 5, np.array([1, 1, 1, 2, 3, 1, 2, 2, 1], dtype=np.int32)))
|
||||
cv.push_back(_aare.Cluster3x3i(5, 5, np.array([2, 2, 1, 2, 3, 1, 1, 1, 1], dtype=np.int32)))
|
||||
|
||||
reduced_cv = np.array(_aare.reduce_to_2x2(cv), copy=False)
|
||||
reduced = _aare.reduce_to_2x2(cv)
|
||||
reduced_cv = np.array(reduced, copy=False)
|
||||
|
||||
assert reduced.frame_number == cv.frame_number
|
||||
assert reduced_cv.size == 2
|
||||
assert reduced_cv[0]["x"] == 5
|
||||
assert reduced_cv[0]["y"] == 5
|
||||
@@ -100,14 +103,17 @@ def test_2x2_reduction():
|
||||
|
||||
def test_3x3_reduction():
|
||||
cv = _aare.ClusterVector_Cluster5x5d()
|
||||
cv.frame_number = 246
|
||||
|
||||
cv.push_back(_aare.Cluster5x5d(5,5,np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 2.0, 2.0, 3.0,
|
||||
1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.double)))
|
||||
cv.push_back(_aare.Cluster5x5d(5,5,np.array([1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 2.0, 2.0, 3.0,
|
||||
1.0, 1.0, 1.0, 2.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0], dtype=np.double)))
|
||||
|
||||
reduced_cv = np.array(_aare.reduce_to_3x3(cv), copy=False)
|
||||
reduced = _aare.reduce_to_3x3(cv)
|
||||
reduced_cv = np.array(reduced, copy=False)
|
||||
|
||||
assert reduced.frame_number == cv.frame_number
|
||||
assert reduced_cv.size == 2
|
||||
assert reduced_cv[0]["x"] == 5
|
||||
assert reduced_cv[0]["y"] == 5
|
||||
@@ -130,3 +136,26 @@ def test_masking():
|
||||
assert cv_masked_array[0]["x"] == 1
|
||||
assert cv_masked_array[0]["y"] == 2
|
||||
assert (cv_masked_array[0]["data"] == np.ones((3,3),dtype=np.int32)).all()
|
||||
|
||||
|
||||
def test_masking_requires_c_contiguous_array():
|
||||
cv = _aare.ClusterVector_Cluster3x3i()
|
||||
cv.push_back(_aare.Cluster3x3i(1, 2, np.ones(9, dtype=np.int32)))
|
||||
cv.push_back(_aare.Cluster3x3i(3, 4, np.ones(9, dtype=np.int32)))
|
||||
|
||||
mask = np.array([True, False, True, False], dtype=bool)[::2]
|
||||
assert not mask.flags.c_contiguous
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
cv(mask)
|
||||
|
||||
|
||||
def test_masking_requires_one_dimension():
|
||||
cv = _aare.ClusterVector_Cluster3x3i()
|
||||
cv.push_back(_aare.Cluster3x3i(1, 2, np.ones(9, dtype=np.int32)))
|
||||
cv.push_back(_aare.Cluster3x3i(3, 4, np.ones(9, dtype=np.int32)))
|
||||
|
||||
mask = np.array([[True, False]], dtype=bool)
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
cv(mask)
|
||||
@@ -0,0 +1,58 @@
|
||||
|
||||
|
||||
import pytest
|
||||
import numpy as np
|
||||
from aare import CtbRawFile
|
||||
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_basic_properites(test_data_path):
|
||||
f = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
assert f.total_frames == 47
|
||||
assert f.image_size_in_bytes == 640
|
||||
assert f.master.analog_samples == 10
|
||||
assert f.master.digital_samples is None
|
||||
assert f.master.transceiver_samples is None
|
||||
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_seek_and_read(test_data_path):
|
||||
f = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
f.seek(0)
|
||||
header, raw_data = f.read_frame()
|
||||
assert header['frameNumber'] == 48 #we know that the first frame in this file is 48
|
||||
|
||||
#Seek a multiple of frames in file
|
||||
f.seek(9)
|
||||
header, raw_data = f.read_frame()
|
||||
assert header['frameNumber'] == 57
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_read_all_frames_direct_and_iterate(test_data_path):
|
||||
"""
|
||||
We want to make sure that iterating and reading give the same result.
|
||||
"""
|
||||
f0 = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
f1 = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
|
||||
for h0, d0 in f0:
|
||||
h1, d1 = f1.read_frame()
|
||||
assert h0 == h1
|
||||
assert np.all(d0 == d1)
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_read_all_frames_with_index_and_iterate(test_data_path):
|
||||
"""
|
||||
We want to make sure that iterating and reading give the same result.
|
||||
"""
|
||||
f0 = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
f1 = CtbRawFile(test_data_path/'raw/ctb/run_master_0.json')
|
||||
|
||||
frames_read = 0
|
||||
for i,(h0, d0) in enumerate(f0):
|
||||
h1, d1 = f1.read_frame(i)
|
||||
assert h0 == h1
|
||||
assert np.all(d0 == d1)
|
||||
frames_read += 1
|
||||
|
||||
assert frames_read == f0.total_frames
|
||||
@@ -143,3 +143,17 @@ def test_fast_pedestal_rejects_wrong_shape():
|
||||
|
||||
with pytest.raises(RuntimeError, match="shape"):
|
||||
pedestal.add_init_frame(np.zeros((2, 2), dtype=np.uint16))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
def test_fast_pedestal_std_uses_double_variance(dtype):
|
||||
pedestal = FastPedestal(1, 1, n_samples=2, dtype=dtype)
|
||||
pedestal.add_init_frame(np.array([[0]], dtype=np.uint16))
|
||||
pedestal.add_init_frame(np.array([[1000]], dtype=np.uint16))
|
||||
|
||||
assert pedestal.std().dtype == dtype
|
||||
np.testing.assert_array_equal(pedestal.std(), [[500]])
|
||||
|
||||
pedestal.push_ema(np.array([[1000]], dtype=np.uint16))
|
||||
expected = np.array([[np.sqrt(187500.0)]], dtype=dtype)
|
||||
np.testing.assert_array_equal(pedestal.std(), expected)
|
||||
@@ -1,7 +1,106 @@
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from aare import Pedestal_d, Pedestal_f
|
||||
from aare import Pedestal, Pedestal_d, Pedestal_f, Pedestal_i16
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("dtype", "pedestal_type"),
|
||||
[(np.float64, Pedestal_d), (np.float32, Pedestal_f), (np.int16, Pedestal_i16)],
|
||||
)
|
||||
def test_pedestal_factory(dtype, pedestal_type):
|
||||
pedestal = Pedestal(rows=2, cols=3, n_samples=4, dtype=dtype)
|
||||
|
||||
assert isinstance(pedestal, pedestal_type)
|
||||
assert pedestal.rows == 2
|
||||
assert pedestal.cols == 3
|
||||
assert pedestal.n_samples == 4
|
||||
|
||||
|
||||
def test_pedestal_factory_defaults_to_double():
|
||||
pedestal = Pedestal(2, 3)
|
||||
|
||||
assert isinstance(pedestal, Pedestal_d)
|
||||
assert pedestal.n_samples == 1000
|
||||
|
||||
|
||||
def test_pedestal_factory_rejects_unbound_dtype():
|
||||
with pytest.raises(ValueError, match="Unsupported dtype for Pedestal"):
|
||||
Pedestal(2, 3, dtype=np.int32)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
@pytest.mark.parametrize("name", ["rows", "cols", "n_samples"])
|
||||
def test_pedestal_factory_rejects_negative_parameters(dtype, name):
|
||||
parameters = dict(rows=1, cols=1, n_samples=10)
|
||||
parameters[name] = -1
|
||||
with pytest.raises(TypeError):
|
||||
Pedestal(**parameters, dtype=dtype)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("pedestal_type", [Pedestal_d, Pedestal_f, Pedestal_i16])
|
||||
@pytest.mark.parametrize(
|
||||
"args", [(-1, 1), (1, -1), (-1, 1, 10), (1, -1, 10), (1, 1, -1)]
|
||||
)
|
||||
def test_pedestal_constructor_rejects_negative_parameters(pedestal_type, args):
|
||||
with pytest.raises(TypeError):
|
||||
pedestal_type(*args)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
def test_pedestal_std_stays_finite_after_settling(dtype):
|
||||
pedestal = Pedestal(1, 1, n_samples=10, dtype=dtype)
|
||||
pedestal.push(np.array([[16382]], dtype=np.uint16))
|
||||
frame = np.array([[16383]], dtype=np.uint16)
|
||||
for _ in range(201):
|
||||
pedestal.push(frame)
|
||||
|
||||
noise = pedestal.std().item()
|
||||
assert np.isfinite(noise)
|
||||
assert 0 <= noise < 1e-3
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("pedestal_type", "expected_dtype"),
|
||||
[(Pedestal_d, np.float64), (Pedestal_f, np.float32), (Pedestal_i16, np.int16)],
|
||||
)
|
||||
def test_double_precision_moments(pedestal_type, expected_dtype):
|
||||
pedestal = pedestal_type(1, 1, 2)
|
||||
for value in [30000, 30003, 30002]:
|
||||
pedestal.push(np.array([[value]], dtype=np.uint16))
|
||||
|
||||
assert pedestal.mean().dtype == expected_dtype
|
||||
assert pedestal.std().dtype == expected_dtype
|
||||
np.testing.assert_array_equal(
|
||||
pedestal.mean(), np.array([[30001.75]], dtype=expected_dtype)
|
||||
)
|
||||
np.testing.assert_allclose(
|
||||
pedestal.std(),
|
||||
np.array([[np.sqrt(1.1875)]], dtype=expected_dtype),
|
||||
rtol=1e-6,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
@pytest.mark.parametrize("method", ["push", "push_with_threshold"])
|
||||
@pytest.mark.parametrize("shape", [(2, 2), (3, 2)])
|
||||
def test_pedestal_rejects_mismatched_frame_shapes(dtype, method, shape):
|
||||
pedestal = Pedestal(2, 3, dtype=dtype)
|
||||
initial = np.full((2, 3), 7, dtype=np.uint16)
|
||||
pedestal.push(initial)
|
||||
frame = np.zeros(shape, dtype=np.uint16)
|
||||
args = (
|
||||
(np.full((2, 3), 10, dtype=dtype),)
|
||||
if method == "push_with_threshold"
|
||||
else ()
|
||||
)
|
||||
|
||||
with pytest.raises(
|
||||
RuntimeError, match="Frame shape does not match pedestal shape"
|
||||
):
|
||||
getattr(pedestal, method)(frame, *args)
|
||||
|
||||
np.testing.assert_array_equal(pedestal.mean(), initial)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
@@ -38,3 +137,68 @@ def test_pedestal_exposes_mean_as_read_only_buffer():
|
||||
np.testing.assert_array_equal(mean, pedestal.view())
|
||||
assert np.shares_memory(mean, pedestal.view())
|
||||
assert not mean.flags.writeable
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
@pytest.mark.parametrize("method", ["push", "push_with_threshold"])
|
||||
def test_pedestal_push_accepts_contiguous_frames(dtype, method):
|
||||
pedestal = Pedestal(2, 3, dtype=dtype)
|
||||
frame = np.arange(6, dtype=np.uint16).reshape(2, 3)
|
||||
args = (
|
||||
(np.full((2, 3), 10, dtype=dtype),)
|
||||
if method == "push_with_threshold"
|
||||
else ()
|
||||
)
|
||||
|
||||
getattr(pedestal, method)(frame, *args)
|
||||
|
||||
np.testing.assert_array_equal(pedestal.mean(), frame)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
@pytest.mark.parametrize("input_name", ["push_frame", "threshold_frame", "threshold"])
|
||||
@pytest.mark.parametrize("layout", ["transpose", "slice", "reverse"])
|
||||
def test_pedestal_rejects_noncontiguous_inputs(dtype, input_name, layout):
|
||||
pedestal = Pedestal(2, 3, dtype=dtype)
|
||||
frame = np.zeros((2, 3), dtype=np.uint16)
|
||||
threshold = np.full((2, 3), 10, dtype=dtype)
|
||||
input_dtype = dtype if input_name == "threshold" else np.uint16
|
||||
if layout == "transpose":
|
||||
invalid = np.ones((3, 2), dtype=input_dtype).T
|
||||
elif layout == "slice":
|
||||
invalid = np.ones((2, 6), dtype=input_dtype)[:, ::2]
|
||||
else:
|
||||
invalid = np.ones((4, 6), dtype=input_dtype)[:2, :3][:, ::-1]
|
||||
assert not invalid.flags.c_contiguous
|
||||
|
||||
with pytest.raises(TypeError):
|
||||
if input_name == "push_frame":
|
||||
pedestal.push(invalid)
|
||||
elif input_name == "threshold_frame":
|
||||
pedestal.push_with_threshold(invalid, threshold)
|
||||
else:
|
||||
pedestal.push_with_threshold(frame, invalid)
|
||||
|
||||
np.testing.assert_array_equal(pedestal.mean(), np.zeros((2, 3)))
|
||||
|
||||
|
||||
@pytest.mark.parametrize("dtype", [np.float64, np.float32, np.int16])
|
||||
@pytest.mark.parametrize("input_name", ["push_frame", "threshold_frame", "threshold"])
|
||||
@pytest.mark.parametrize("shape", [(), (6,), (2, 3, 2)])
|
||||
def test_pedestal_rejects_inputs_with_wrong_ndim(dtype, input_name, shape):
|
||||
pedestal = Pedestal(2, 3, dtype=dtype)
|
||||
frame = np.ones((2, 3), dtype=np.uint16)
|
||||
threshold = np.full((2, 3), 10, dtype=dtype)
|
||||
input_dtype = dtype if input_name == "threshold" else np.uint16
|
||||
invalid = np.ones(shape, dtype=input_dtype)
|
||||
name = "Threshold" if input_name == "threshold" else "Frame"
|
||||
|
||||
with pytest.raises(ValueError, match=f"{name} must be 2-dimensional"):
|
||||
if input_name == "push_frame":
|
||||
pedestal.push(invalid)
|
||||
elif input_name == "threshold_frame":
|
||||
pedestal.push_with_threshold(invalid, threshold)
|
||||
else:
|
||||
pedestal.push_with_threshold(frame, invalid)
|
||||
|
||||
np.testing.assert_array_equal(pedestal.mean(), np.zeros((2, 3)))
|
||||
@@ -0,0 +1,21 @@
|
||||
import pytest
|
||||
|
||||
import numpy as np
|
||||
|
||||
from aare import ROI
|
||||
|
||||
|
||||
def test_roi_slice():
|
||||
"""test the ROI slice method"""
|
||||
roi = ROI(0, 4, 2, 4)
|
||||
|
||||
array = np.array([[1, 2, 3, 4],
|
||||
[5, 6, 7, 8],
|
||||
[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]])
|
||||
|
||||
sliced_array = array[roi.slice()]
|
||||
|
||||
assert sliced_array.shape == (2, 4)
|
||||
assert np.array_equal(sliced_array, np.array([[9, 10, 11, 12],
|
||||
[13, 14, 15, 16]]))
|
||||
@@ -1,8 +1,299 @@
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
import pytest
|
||||
from aare import RawFile
|
||||
import json
|
||||
from aare import File, RawFile, RawSubFile, DetectorType, ROI, UDPPortPosition
|
||||
import numpy as np
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def small_raw_file(tmp_path):
|
||||
master_path = tmp_path / "run_master_0.json"
|
||||
master_path.write_text(json.dumps({
|
||||
"Version": 7.2,
|
||||
"Detector Type": "Jungfrau",
|
||||
"Timing Mode": "auto",
|
||||
"Geometry": {"x": 1, "y": 1},
|
||||
"Image Size in bytes": 12,
|
||||
"Pixels": {"x": 3, "y": 2},
|
||||
"Max Frames Per File": 1,
|
||||
"Total Frames": 2,
|
||||
"Frames in File": 2,
|
||||
"Frame Padding": 1,
|
||||
"Frame Discard Policy": "nodiscard",
|
||||
}))
|
||||
for index in range(2):
|
||||
data_path = tmp_path / f"run_d0_f{index}_0.raw"
|
||||
# A detector header followed by six uint16 pixels.
|
||||
data_path.write_bytes(bytes(112) + np.arange(6, dtype=np.uint16).tobytes())
|
||||
return master_path
|
||||
|
||||
|
||||
@pytest.mark.parametrize("reader_type", [RawFile, File])
|
||||
@pytest.mark.parametrize("legacy_master", [False, True])
|
||||
@pytest.mark.parametrize("padding, policy, supported", [
|
||||
(0, "nodiscard", False),
|
||||
(0, "discard", False),
|
||||
(0, "discardpartial", True),
|
||||
(1, "nodiscard", True),
|
||||
(1, "discard", True),
|
||||
(1, "discardpartial", True),
|
||||
])
|
||||
def test_raw_frame_policy(small_raw_file, reader_type, legacy_master,
|
||||
padding, policy, supported):
|
||||
master_path = small_raw_file
|
||||
if legacy_master:
|
||||
master_path = master_path.with_suffix(".raw")
|
||||
master_path.write_text(
|
||||
"Version : 6.4\n"
|
||||
"Detector Type : Jungfrau\n"
|
||||
"Timing Mode : auto\n"
|
||||
"Geometry : [1, 1]\n"
|
||||
"Image Size : 12\n"
|
||||
"Pixels : [3, 2]\n"
|
||||
"Dynamic Range : 16\n"
|
||||
"Max Frames Per File : 1\n"
|
||||
"Total Frames : 2\n"
|
||||
"Frames in File : 2\n"
|
||||
f"Frame Padding : {padding}\n"
|
||||
f"Frame Discard Policy : {policy}\n"
|
||||
)
|
||||
else:
|
||||
metadata = json.loads(master_path.read_text())
|
||||
metadata["Frame Padding"] = padding
|
||||
metadata["Frame Discard Policy"] = policy
|
||||
master_path.write_text(json.dumps(metadata))
|
||||
|
||||
if supported:
|
||||
reader = reader_type(master_path)
|
||||
assert reader.total_frames == 2
|
||||
frame = reader.read_frame()
|
||||
if reader_type is RawFile:
|
||||
_, frame = frame
|
||||
np.testing.assert_array_equal(frame, np.arange(6).reshape(2, 3))
|
||||
else:
|
||||
message = "requires frame padding or discardpartial"
|
||||
with pytest.raises(RuntimeError, match=message) as error:
|
||||
reader_type(master_path)
|
||||
assert str(master_path) in str(error.value)
|
||||
|
||||
for index in range(2):
|
||||
(master_path.parent / f"run_d0_f{index}_0.raw").unlink()
|
||||
with pytest.raises(RuntimeError, match=message) as error:
|
||||
reader_type(master_path)
|
||||
assert str(master_path) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, args, kwargs", [
|
||||
("read_frame", (), {}),
|
||||
("read_n", (1,), {}),
|
||||
("read_roi", (0,), {}),
|
||||
("read_rois", (), {}),
|
||||
("read_n_with_roi", (1,), {"roi_index": 0}),
|
||||
("frame_number", (2,), {}),
|
||||
])
|
||||
def test_raw_read_error_context(small_raw_file, method, args, kwargs):
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(2)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
getattr(reader, method)(*args, **kwargs)
|
||||
assert "frame index 2" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
assert ".raw" not in str(error.value)
|
||||
if method == "read_frame":
|
||||
assert "file contains 2 frames (indices are zero-based)" in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("frame_index", [2, 17])
|
||||
def test_generic_raw_read_error_context(small_raw_file, frame_index):
|
||||
reader = File(small_raw_file)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame(frame_index)
|
||||
assert f"frame index {frame_index}" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw_subfile", [False, True])
|
||||
def test_truncated_raw_read_error_context(small_raw_file, raw_subfile):
|
||||
data_path = small_raw_file.parent / "run_d0_f1_0.raw"
|
||||
if raw_subfile:
|
||||
reader = RawSubFile(
|
||||
small_raw_file.parent / "run_d0_f0_0.raw",
|
||||
DetectorType.Jungfrau, 2, 3, 16,
|
||||
)
|
||||
else:
|
||||
reader = RawFile(small_raw_file)
|
||||
data_path.write_bytes(bytes(112))
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame()
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert str(data_path) in str(error.value)
|
||||
assert "End of file" in str(error.value)
|
||||
assert "master" not in str(error.value)
|
||||
assert "RawSubFile.cpp" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("method, args", [
|
||||
("read_frame", ()),
|
||||
("read_n", (1,)),
|
||||
("read_roi", (0,)),
|
||||
("frame_number", (1,)),
|
||||
])
|
||||
def test_short_raw_subfile_sets_read_bounds(small_raw_file, method, args):
|
||||
(small_raw_file.parent / "run_d0_f1_0.raw").unlink()
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
getattr(reader, method)(*args)
|
||||
assert reader.total_frames == 1
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert str(small_raw_file) in str(error.value)
|
||||
assert ".raw" not in str(error.value)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("counts, master_count, warn", [
|
||||
([2], 2, False),
|
||||
([2, 2], 2, False),
|
||||
([2, 2], 0, True),
|
||||
([2, 2], 1, True),
|
||||
([2, 2], 5, True),
|
||||
([1, 2], 2, True),
|
||||
([2, 1], 2, True),
|
||||
([1, 2], 1, True),
|
||||
([0, 2], 2, True),
|
||||
([0, 0], 0, False),
|
||||
])
|
||||
def test_raw_subfile_frame_counts(small_raw_file, capfd, counts, master_count, warn):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata["Geometry"]["y"] = len(counts)
|
||||
metadata["Frames in File"] = master_count
|
||||
metadata["Total Frames"] = 1000
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
data = (small_raw_file.parent / "run_d0_f0_0.raw").read_bytes()
|
||||
for module, count in enumerate(counts):
|
||||
for index in range(2):
|
||||
path = small_raw_file.parent / f"run_d{module}_f{index}_0.raw"
|
||||
if index < count:
|
||||
path.write_bytes(data)
|
||||
elif index == 0:
|
||||
path.write_bytes(b"")
|
||||
else:
|
||||
path.unlink(missing_ok=True)
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
warning = capfd.readouterr().err
|
||||
if warn:
|
||||
assert warning.count("WARNING") == 1
|
||||
assert str(small_raw_file) in warning
|
||||
else:
|
||||
assert "WARNING" not in warning
|
||||
|
||||
assert reader.total_frames == min(counts)
|
||||
assert len(reader) == min(counts)
|
||||
assert reader.master.frames_in_file == master_count
|
||||
if min(counts):
|
||||
_, frames = reader.read()
|
||||
assert frames.shape == (min(counts), 2 * len(counts), 3)
|
||||
reader.seek(0)
|
||||
_, frames = reader.read_n(10)
|
||||
assert len(frames) == min(counts)
|
||||
assert reader.frame_number(min(counts) - 1) == 0
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.frame_number(min(counts))
|
||||
reader.seek(min(counts))
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.read_frame()
|
||||
assert "WARNING" not in capfd.readouterr().err
|
||||
|
||||
|
||||
@pytest.mark.parametrize("short_module", [0, 1])
|
||||
def test_raw_frame_count_across_rois(small_raw_file, short_module):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({
|
||||
"Version": 8.0,
|
||||
"Geometry": {"x": 1, "y": 2},
|
||||
"Image Size": 12,
|
||||
"Receiver Rois": [
|
||||
{"xmin": 0, "xmax": 2, "ymin": 0, "ymax": 1},
|
||||
{"xmin": 0, "xmax": 2, "ymin": 2, "ymax": 3},
|
||||
],
|
||||
})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
for index in range(2):
|
||||
data = (small_raw_file.parent / f"run_d0_f{index}_0.raw").read_bytes()
|
||||
(small_raw_file.parent / f"run_d1_f{index}_0.raw").write_bytes(data)
|
||||
(small_raw_file.parent / f"run_d{short_module}_f1_0.raw").unlink()
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
assert reader.total_frames == 1
|
||||
_, rois = reader.read_rois()
|
||||
assert len(rois) == 2
|
||||
assert all(roi.shape == (2, 3) for roi in rois)
|
||||
for roi_index in range(2):
|
||||
reader.seek(0)
|
||||
_, frames = reader.read_n_with_roi(10, roi_index=roi_index)
|
||||
assert frames.shape == (1, 2, 3)
|
||||
with pytest.raises(RuntimeError):
|
||||
reader.read_roi(roi_index)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("disabled_port", [0, 1])
|
||||
def test_raw_frame_count_with_disabled_udp_port(small_raw_file, disabled_port):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({
|
||||
"Geometry": {"x": 1, "y": 2},
|
||||
"Frames in File": 0,
|
||||
"Number of UDP Interfaces": 2,
|
||||
"UDP Ports Type": ["bottom", "top"],
|
||||
"UDP Ports Disabled": [disabled_port],
|
||||
})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
data = (small_raw_file.parent / "run_d0_f0_0.raw").read_bytes()
|
||||
for index in range(2):
|
||||
(small_raw_file.parent / f"run_d0_f{index}_0.raw").unlink()
|
||||
path = small_raw_file.parent / f"run_d{1 - disabled_port}_f{index}_0.raw"
|
||||
path.write_bytes(data)
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
assert reader.total_frames == 2
|
||||
assert reader.master.frames_in_file == 0
|
||||
assert reader.frame_number(1) == 0
|
||||
_, frames = reader.read()
|
||||
assert frames.shape == (2, 2, 3)
|
||||
|
||||
|
||||
def test_raw_frame_count_without_selected_subfiles(small_raw_file):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata.update({"Version": 8.0, "Image Size": 12, "Receiver Rois": []})
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
with pytest.raises(RuntimeError, match="No raw subfiles selected"):
|
||||
RawFile(small_raw_file)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lagging_module", [0, 1])
|
||||
def test_raw_synchronization_error_identifies_subfile(
|
||||
small_raw_file, lagging_module
|
||||
):
|
||||
metadata = json.loads(small_raw_file.read_text())
|
||||
metadata["Geometry"]["y"] = 2
|
||||
small_raw_file.write_text(json.dumps(metadata))
|
||||
for index in range(2):
|
||||
data = (small_raw_file.parent / f"run_d0_f{index}_0.raw").read_bytes()
|
||||
(small_raw_file.parent / f"run_d1_f{index}_0.raw").write_bytes(data)
|
||||
|
||||
ahead_path = small_raw_file.parent / f"run_d{1 - lagging_module}_f1_0.raw"
|
||||
with ahead_path.open("r+b") as output:
|
||||
output.write(np.array([1], dtype=np.uint64).tobytes())
|
||||
|
||||
reader = RawFile(small_raw_file)
|
||||
reader.seek(1)
|
||||
with pytest.raises(RuntimeError) as error:
|
||||
reader.read_frame()
|
||||
assert "frame index 1" in str(error.value)
|
||||
assert "synchroniz" in str(error.value)
|
||||
lagging_path = small_raw_file.parent / f"run_d{lagging_module}_f1_0.raw"
|
||||
assert str(lagging_path) in str(error.value)
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_read_rawfile_with_roi_spanning_over_one_module(test_data_path):
|
||||
|
||||
@@ -110,3 +401,41 @@ def test_read_rawfile_eiger_and_compare_to_numpy(test_data_path):
|
||||
header, image1 = f.read_frame()
|
||||
|
||||
assert (image == image1).all()
|
||||
|
||||
|
||||
@pytest.mark.withdata
|
||||
def test_read_eiger_udp_port_disabled(test_data_path):
|
||||
with RawFile(test_data_path / "raw/eiger/one_udp_port_disabled_master_0.json") as f:
|
||||
_, frame = f.read_rois()
|
||||
|
||||
assert(len(frame) == 2)
|
||||
assert frame[0].shape == (256, 512)
|
||||
assert frame[1].shape == (256, 1024)
|
||||
assert f.master.udp_port_types == [UDPPortPosition.LEFT, UDPPortPosition.RIGHT]
|
||||
rois = f.master.rois
|
||||
assert len(rois) == 2
|
||||
assert rois[0] == ROI(512, 1024, 0, 256)
|
||||
assert rois[1] == ROI(0, 1024, 256, 512)
|
||||
|
||||
with RawFile(test_data_path / "raw/eiger/quad_eiger_disabled_bottom_port_master_0.json") as f:
|
||||
_, frame = f.read_frame()
|
||||
|
||||
assert frame.shape == (256, 512)
|
||||
assert(f.master.disabled_udp_ports == [1])
|
||||
assert f.master.udp_port_types == [UDPPortPosition.TOP, UDPPortPosition.BOTTOM]
|
||||
rois = f.master.rois
|
||||
assert len(rois) == 1
|
||||
assert rois[0] == ROI(0, 512, 256, 512)
|
||||
|
||||
with RawFile(test_data_path / "raw/eiger/2_modules_eiger_disabled_udp_port_master_0.json") as f:
|
||||
_, frame = f.read_rois()
|
||||
|
||||
assert(len(frame) == 2)
|
||||
assert frame[0].shape == (512, 512)
|
||||
assert frame[1].shape == (512, 512)
|
||||
assert (f.master.disabled_udp_ports == [1, 3, 5, 7])
|
||||
assert f.master.udp_port_types == [UDPPortPosition.LEFT, UDPPortPosition.RIGHT]
|
||||
rois = f.master.rois
|
||||
assert len(rois) == 2
|
||||
assert rois[0] == ROI(0, 512, 0, 512)
|
||||
assert rois[1] == ROI(1024, 1536, 0, 512)
|
||||
@@ -1,7 +1,9 @@
|
||||
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
from aare import RawMasterFile, ReadoutMode, DetectorType
|
||||
from aare import RawMasterFile, ReadoutMode, DetectorType, FrameDiscardPolicy
|
||||
|
||||
|
||||
@pytest.mark.withdata
|
||||
@@ -11,4 +13,37 @@ def test_read_rawfile_quad_eiger_and_compare_to_numpy(test_data_path):
|
||||
|
||||
f = RawMasterFile(file_name)
|
||||
assert(f.reading_mode == ReadoutMode.UNKNOWN)
|
||||
assert(f.detector_type == DetectorType.Jungfrau)
|
||||
assert(f.detector_type == DetectorType.Jungfrau)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"policy, expected_policy",
|
||||
[
|
||||
("nodiscard", FrameDiscardPolicy.NoDiscard),
|
||||
("discard", FrameDiscardPolicy.Discard),
|
||||
("discardpartial", FrameDiscardPolicy.DiscardPartial),
|
||||
],
|
||||
)
|
||||
def test_raw_master_file_context_manager(tmp_path, policy, expected_policy):
|
||||
file_name = tmp_path / "run_master_0.json"
|
||||
file_name.write_text(json.dumps({
|
||||
"Version": 7.2,
|
||||
"Detector Type": "Jungfrau",
|
||||
"Timing Mode": "auto",
|
||||
"Geometry": {"x": 1, "y": 1},
|
||||
"Image Size in bytes": 12,
|
||||
"Pixels": {"x": 3, "y": 2},
|
||||
"Max Frames Per File": 1,
|
||||
"Total Frames": 2,
|
||||
"Frames in File": 2,
|
||||
"Frame Padding": 1,
|
||||
"Frame Discard Policy": policy,
|
||||
}))
|
||||
|
||||
|
||||
with RawMasterFile(file_name) as context_file:
|
||||
assert context_file.reading_mode == ReadoutMode.UNKNOWN
|
||||
assert context_file.detector_type == DetectorType.Jungfrau
|
||||
frame_discard_policy = context_file.frame_discard_policy
|
||||
assert isinstance(frame_discard_policy, FrameDiscardPolicy)
|
||||
assert frame_discard_policy == expected_policy
|
||||
@@ -0,0 +1,74 @@
|
||||
# SPDX-License-Identifier: MPL-2.0
|
||||
"""Probe make_view in np_helper.hpp through the bindings in _aare.testing"""
|
||||
import numpy as np
|
||||
import pytest
|
||||
|
||||
from aare._aare import testing
|
||||
|
||||
|
||||
|
||||
|
||||
def test_make_view_roundtrip():
|
||||
"""Send an array to C++ and check that we get the same array back"""
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
out = testing.view_roundtrip_2d(arr)
|
||||
np.testing.assert_array_equal(out, arr)
|
||||
|
||||
#Sanity check to make sure we got a copy an not just the same thing back
|
||||
arr[3,2] = 31655
|
||||
assert arr[3,2] != out[3,2]
|
||||
|
||||
def test_make_view_const_roundtrip():
|
||||
"""Const works if the array is not writeable"""
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
arr.flags.writeable = False
|
||||
out = testing.const_view_roundtrip_2d(arr)
|
||||
np.testing.assert_array_equal(out, arr)
|
||||
|
||||
def test_make_view_const_roundtrip_writable():
|
||||
"""Const works also if the array is writeable"""
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
out = testing.const_view_roundtrip_2d(arr)
|
||||
np.testing.assert_array_equal(out, arr)
|
||||
|
||||
def test_make_view_fill():
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
testing.view_fill_2d(arr, 7)
|
||||
assert (arr == 7).all()
|
||||
|
||||
def test_make_view_fill_rejects_nonwriteable():
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
arr.flags.writeable = False
|
||||
with pytest.raises(ValueError, match="not writeable"):
|
||||
testing.view_fill_2d(arr, 7)
|
||||
|
||||
def test_make_view_2d_rejects_1d():
|
||||
arr = np.arange(30, dtype=np.uint16)
|
||||
with pytest.raises(ValueError, match="Expected 2D array, got 1D"):
|
||||
testing.view_roundtrip_2d(arr)
|
||||
|
||||
def test_make_view_2d_rejects_3d():
|
||||
arr = np.arange(30, dtype=np.uint16).reshape(3, 5, 2)
|
||||
with pytest.raises(ValueError, match="Expected 2D array, got 3D"):
|
||||
testing.view_roundtrip_2d(arr)
|
||||
|
||||
def test_make_view_rejects_noncontiguous():
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
arr = arr[::2, ::3] # non-contiguous
|
||||
assert not arr.flags.c_contiguous
|
||||
with pytest.raises(ValueError, match="not C-contiguous"):
|
||||
testing.view_roundtrip_2d(arr)
|
||||
|
||||
def test_make_view_rejects_noncontiguous_const():
|
||||
arr = np.arange(30, dtype=np.float64).reshape(5, 6)
|
||||
arr = arr[::2, ::3] # non-contiguous
|
||||
assert not arr.flags.c_contiguous
|
||||
with pytest.raises(ValueError, match="not C-contiguous"):
|
||||
testing.const_view_roundtrip_2d(arr)
|
||||
|
||||
def test_make_view_rejects_fortran_order():
|
||||
arr = np.asfortranarray(np.arange(30, dtype=np.float64).reshape(5, 6))
|
||||
assert not arr.flags.c_contiguous
|
||||
with pytest.raises(ValueError, match="not C-contiguous"):
|
||||
testing.view_roundtrip_2d(arr)
|
||||
|
||||
+11
-10
@@ -24,8 +24,8 @@ TEST_CASE("Test sum of Cluster", "[cluster]") {
|
||||
using ClusterTypes = std::variant<Cluster<int, 2, 2>, Cluster<int, 3, 3>,
|
||||
Cluster<int, 5, 5>, Cluster<int, 2, 3>>;
|
||||
|
||||
using ClusterTypesLargerThan2x2 =
|
||||
std::variant<Cluster<int, 3, 3>, Cluster<int, 4, 4>, Cluster<int, 5, 5>>;
|
||||
using ReducibleTo3x3ClusterTypes =
|
||||
std::variant<Cluster<int, 3, 4>, Cluster<int, 4, 3>, Cluster<int, 5, 5>>;
|
||||
|
||||
TEST_CASE("Test reduce to 2x2 Cluster", "[cluster]") {
|
||||
auto [cluster, expected_reduced_cluster] = GENERATE(
|
||||
@@ -68,14 +68,15 @@ TEST_CASE("Test reduce to 2x2 Cluster", "[cluster]") {
|
||||
|
||||
TEST_CASE("Test reduce to 3x3 Cluster", "[cluster]") {
|
||||
auto [cluster, expected_reduced_cluster] = GENERATE(
|
||||
std::make_tuple(ClusterTypesLargerThan2x2{Cluster<int, 3, 3>{
|
||||
5, 5, {1, 1, 1, 1, 3, 1, 1, 1, 1}}},
|
||||
Cluster<int, 3, 3>{5, 5, {1, 1, 1, 1, 3, 1, 1, 1, 1}}),
|
||||
std::make_tuple(
|
||||
ClusterTypesLargerThan2x2{Cluster<int, 4, 4>{
|
||||
5, 5, {2, 2, 1, 1, 2, 2, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1}}},
|
||||
Cluster<int, 3, 3>{5, 5, {2, 1, 1, 1, 3, 1, 1, 1, 1}}),
|
||||
std::make_tuple(ClusterTypesLargerThan2x2{Cluster<int, 5, 5>{
|
||||
ReducibleTo3x3ClusterTypes{Cluster<int, 3, 4>{
|
||||
5, 5, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}},
|
||||
Cluster<int, 3, 3>{5, 5, {3, 4, 5, 6, 7, 8, 9, 10, 11}}),
|
||||
std::make_tuple(
|
||||
ReducibleTo3x3ClusterTypes{Cluster<int, 4, 3>{
|
||||
5, 5, {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}}},
|
||||
Cluster<int, 3, 3>{5, 5, {1, 2, 3, 5, 6, 7, 9, 10, 11}}),
|
||||
std::make_tuple(ReducibleTo3x3ClusterTypes{Cluster<int, 5, 5>{
|
||||
5, 5, {1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 2, 2, 3,
|
||||
1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1}}},
|
||||
Cluster<int, 3, 3>{5, 5, {2, 1, 1, 2, 3, 1, 2, 1, 1}}));
|
||||
@@ -89,4 +90,4 @@ TEST_CASE("Test reduce to 3x3 Cluster", "[cluster]") {
|
||||
CHECK(std::equal(reduced_cluster.data.begin(),
|
||||
reduced_cluster.data.begin() + 9,
|
||||
expected_reduced_cluster.data.begin()));
|
||||
}
|
||||
}
|
||||
+608
-61
@@ -5,12 +5,74 @@
|
||||
#include "aare/defs.hpp"
|
||||
#include <algorithm>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
#include <catch2/generators/catch_generators.hpp>
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <vector>
|
||||
|
||||
using aare::Cluster;
|
||||
using aare::ClusterFile;
|
||||
using aare::ClusterVector;
|
||||
|
||||
namespace {
|
||||
|
||||
class TemporaryClusterFile {
|
||||
public:
|
||||
TemporaryClusterFile() {
|
||||
const auto unique =
|
||||
std::chrono::steady_clock::now().time_since_epoch().count();
|
||||
m_path = std::filesystem::temp_directory_path() /
|
||||
("aare-cluster-file-" + std::to_string(unique) + ".clust");
|
||||
}
|
||||
|
||||
TemporaryClusterFile(const TemporaryClusterFile &) = delete;
|
||||
TemporaryClusterFile &operator=(const TemporaryClusterFile &) = delete;
|
||||
|
||||
~TemporaryClusterFile() {
|
||||
std::error_code error;
|
||||
std::filesystem::remove(m_path, error);
|
||||
}
|
||||
|
||||
const std::filesystem::path &path() const { return m_path; }
|
||||
|
||||
private:
|
||||
std::filesystem::path m_path;
|
||||
};
|
||||
|
||||
using TestCluster = Cluster<double, 3, 3>;
|
||||
|
||||
ClusterVector<TestCluster> make_test_frame(int32_t frame_number,
|
||||
double offset) {
|
||||
ClusterVector<TestCluster> clusters(2, frame_number);
|
||||
clusters.push_back(
|
||||
TestCluster{5,
|
||||
6,
|
||||
{offset, offset + 1, offset + 2, offset + 3, offset + 4,
|
||||
offset + 5, offset + 6, offset + 7, offset + 8}});
|
||||
clusters.push_back(TestCluster{7,
|
||||
8,
|
||||
{offset + 9, offset + 10, offset + 11,
|
||||
offset + 12, offset + 13, offset + 14,
|
||||
offset + 15, offset + 16, offset + 17}});
|
||||
return clusters;
|
||||
}
|
||||
|
||||
void check_frame(const ClusterVector<TestCluster> &actual,
|
||||
const ClusterVector<TestCluster> &expected) {
|
||||
REQUIRE(actual.frame_number() == expected.frame_number());
|
||||
REQUIRE(actual.size() == expected.size());
|
||||
for (size_t i = 0; i < expected.size(); ++i) {
|
||||
CHECK(actual[i].x == expected[i].x);
|
||||
CHECK(actual[i].y == expected[i].y);
|
||||
CHECK(actual[i].data == expected[i].data);
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Read one frame from a cluster file", "[.with-data]") {
|
||||
// We know that the frame has 97 clusters
|
||||
auto fpath = test_data_path() / "clust" / "single_frame_97_clustrers.clust";
|
||||
@@ -20,12 +82,14 @@ TEST_CASE("Read one frame from a cluster file", "[.with-data]") {
|
||||
CHECK(f.estimate_n_clusters() == 97);
|
||||
CHECK(f.tell() == 0);
|
||||
auto clusters = f.read_frame();
|
||||
CHECK(clusters.size() == 97);
|
||||
CHECK(clusters.frame_number() == 135);
|
||||
CHECK(clusters[0].x == 1);
|
||||
CHECK(clusters[0].y == 200);
|
||||
REQUIRE(clusters);
|
||||
CHECK(clusters->size() == 97);
|
||||
CHECK(clusters->frame_number() == 135);
|
||||
CHECK((*clusters)[0].x == 1);
|
||||
CHECK((*clusters)[0].y == 200);
|
||||
int32_t expected_cluster_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
|
||||
CHECK(std::equal(std::begin(clusters[0].data), std::end(clusters[0].data),
|
||||
CHECK(std::equal(std::begin((*clusters)[0].data),
|
||||
std::end((*clusters)[0].data),
|
||||
std::begin(expected_cluster_data)));
|
||||
}
|
||||
|
||||
@@ -42,22 +106,24 @@ TEST_CASE("Read one frame using ROI", "[.with-data]") {
|
||||
roi.ymax = 249;
|
||||
f.set_roi(roi);
|
||||
auto clusters = f.read_frame();
|
||||
REQUIRE(clusters.size() == 49);
|
||||
REQUIRE(clusters.frame_number() == 135);
|
||||
REQUIRE(clusters);
|
||||
REQUIRE(clusters->size() == 49);
|
||||
REQUIRE(clusters->frame_number() == 135);
|
||||
|
||||
// Check that all clusters are within the ROI
|
||||
for (size_t i = 0; i < clusters.size(); i++) {
|
||||
auto c = clusters[i];
|
||||
for (size_t i = 0; i < clusters->size(); i++) {
|
||||
auto c = (*clusters)[i];
|
||||
REQUIRE(c.x >= roi.xmin);
|
||||
REQUIRE(c.x <= roi.xmax);
|
||||
REQUIRE(c.y >= roi.ymin);
|
||||
REQUIRE(c.y <= roi.ymax);
|
||||
}
|
||||
|
||||
CHECK(clusters[0].x == 1);
|
||||
CHECK(clusters[0].y == 200);
|
||||
CHECK((*clusters)[0].x == 1);
|
||||
CHECK((*clusters)[0].y == 200);
|
||||
int32_t expected_cluster_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
|
||||
CHECK(std::equal(std::begin(clusters[0].data), std::end(clusters[0].data),
|
||||
CHECK(std::equal(std::begin((*clusters)[0].data),
|
||||
std::end((*clusters)[0].data),
|
||||
std::begin(expected_cluster_data)));
|
||||
}
|
||||
|
||||
@@ -284,70 +350,551 @@ TEST_CASE("Read cluster from multiple frame file", "[.with-data]") {
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Write cluster with potential padding",
|
||||
"[.with-data][.ClusterFile]") {
|
||||
TEST_CASE("ClusterFile flushes a frame when the writer is destroyed",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
|
||||
using ClusterType = Cluster<double, 3, 3>;
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(expected);
|
||||
}
|
||||
|
||||
REQUIRE(std::filesystem::exists(test_data_path() / "clust"));
|
||||
const auto expected_file_size = sizeof(int32_t) + sizeof(uint32_t) +
|
||||
expected.size() * sizeof(TestCluster);
|
||||
CHECK(std::filesystem::file_size(file.path()) == expected_file_size);
|
||||
|
||||
auto fpath = test_data_path() / "clust" / "single_frame_2_clusters.clust";
|
||||
|
||||
ClusterFile<ClusterType> file(fpath, 1000, "w");
|
||||
|
||||
ClusterVector<ClusterType> clustervec(2);
|
||||
uint16_t coordinate = 5;
|
||||
clustervec.push_back(ClusterType{
|
||||
coordinate, coordinate, {0., 0., 0., 0., 0., 0., 0., 0., 0.}});
|
||||
clustervec.push_back(ClusterType{
|
||||
coordinate, coordinate, {0., 0., 0., 0., 0., 0., 0., 0., 0.}});
|
||||
|
||||
file.write_frame(clustervec);
|
||||
|
||||
file.close();
|
||||
|
||||
file.open("r");
|
||||
|
||||
auto read_cluster_vector = file.read_frame();
|
||||
|
||||
CHECK(read_cluster_vector.size() == 2);
|
||||
CHECK(read_cluster_vector.frame_number() == 0);
|
||||
|
||||
CHECK(read_cluster_vector[0].x == clustervec[0].x);
|
||||
CHECK(read_cluster_vector[0].y == clustervec[0].y);
|
||||
CHECK(std::equal(
|
||||
clustervec[0].data.begin(), clustervec[0].data.end(),
|
||||
read_cluster_vector[0].data.begin(), [](double a, double b) {
|
||||
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
|
||||
}));
|
||||
|
||||
CHECK(read_cluster_vector[1].x == clustervec[1].x);
|
||||
CHECK(read_cluster_vector[1].y == clustervec[1].y);
|
||||
CHECK(std::equal(
|
||||
clustervec[1].data.begin(), clustervec[1].data.end(),
|
||||
read_cluster_vector[1].data.begin(), [](double a, double b) {
|
||||
return std::abs(a - b) < std::numeric_limits<double>::epsilon();
|
||||
}));
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto actual = reader.read_frame();
|
||||
REQUIRE(actual);
|
||||
check_frame(*actual, expected);
|
||||
}
|
||||
|
||||
TEST_CASE("Read frame and modify cluster data", "[.with-data][.ClusterFile]") {
|
||||
TEST_CASE("ClusterFile appends frames", "[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto first_expected = make_test_frame(42, 0.0);
|
||||
auto second_expected = make_test_frame(43, 100.0);
|
||||
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(first_expected);
|
||||
}
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "a");
|
||||
writer.write_frame(second_expected);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto first_actual = reader.read_frame();
|
||||
auto second_actual = reader.read_frame();
|
||||
REQUIRE(first_actual);
|
||||
REQUIRE(second_actual);
|
||||
check_frame(*first_actual, first_expected);
|
||||
check_frame(*second_actual, second_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile reads frames into an existing cluster vector",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto first_expected = make_test_frame(42, 0.0);
|
||||
auto second_expected = make_test_frame(43, 100.0);
|
||||
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(first_expected);
|
||||
writer.write_frame(second_expected);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
ClusterVector<TestCluster> actual(2);
|
||||
const auto initial_data = actual.data();
|
||||
|
||||
REQUIRE(reader.read_frame(actual));
|
||||
CHECK(actual.data() == initial_data);
|
||||
check_frame(actual, first_expected);
|
||||
|
||||
REQUIRE(reader.read_frame(actual));
|
||||
CHECK(actual.data() == initial_data);
|
||||
check_frame(actual, second_expected);
|
||||
|
||||
CHECK_FALSE(reader.read_frame(actual));
|
||||
check_frame(actual, second_expected);
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile reports a clean end of file", "[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
ClusterVector<TestCluster> clusters;
|
||||
CHECK_FALSE(reader.read_frame(clusters));
|
||||
CHECK(clusters.empty());
|
||||
CHECK_FALSE(reader.read_frame().has_value());
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile reports complete frames with no output clusters",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
ClusterVector<TestCluster> empty_frame(0, 41);
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(empty_frame);
|
||||
writer.write_frame(expected);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
ClusterVector<TestCluster> clusters;
|
||||
auto empty_actual = reader.read_frame();
|
||||
REQUIRE(empty_actual);
|
||||
CHECK(empty_actual->empty());
|
||||
CHECK(empty_actual->frame_number() == 41);
|
||||
|
||||
aare::ROI roi;
|
||||
roi.xmin = 100;
|
||||
roi.xmax = 200;
|
||||
roi.ymin = 100;
|
||||
roi.ymax = 200;
|
||||
reader.set_roi(roi);
|
||||
|
||||
REQUIRE(reader.read_frame(clusters));
|
||||
CHECK(clusters.empty());
|
||||
CHECK(clusters.frame_number() == expected.frame_number());
|
||||
CHECK_FALSE(reader.read_frame(clusters));
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile rejects incomplete frames", "[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(expected);
|
||||
}
|
||||
|
||||
SECTION("incomplete frame number") {
|
||||
std::filesystem::resize_file(file.path(), sizeof(int32_t) - 1);
|
||||
}
|
||||
SECTION("incomplete cluster count") {
|
||||
std::filesystem::resize_file(file.path(),
|
||||
sizeof(int32_t) + sizeof(uint32_t) - 1);
|
||||
}
|
||||
SECTION("incomplete cluster data") {
|
||||
std::filesystem::resize_file(
|
||||
file.path(), std::filesystem::file_size(file.path()) - 1);
|
||||
}
|
||||
|
||||
{
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
ClusterVector<TestCluster> clusters;
|
||||
CHECK_THROWS_AS(reader.read_frame(clusters), std::runtime_error);
|
||||
}
|
||||
{
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
CHECK_THROWS_AS(reader.read_frame(), std::runtime_error);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile close is idempotent", "[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(expected);
|
||||
writer.close();
|
||||
|
||||
CHECK_NOTHROW(writer.close());
|
||||
CHECK_THROWS_AS(writer.tell(), std::runtime_error);
|
||||
CHECK_THROWS_AS(writer.write_frame(expected), std::runtime_error);
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto actual = reader.read_frame();
|
||||
REQUIRE(actual);
|
||||
check_frame(*actual, expected);
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile chunk reads reject incomplete frames", "[ClusterFile]") {
|
||||
const auto use_roi = GENERATE(false, true);
|
||||
CAPTURE(use_roi);
|
||||
TemporaryClusterFile file;
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(expected);
|
||||
}
|
||||
|
||||
SECTION("incomplete frame number") {
|
||||
std::filesystem::resize_file(file.path(), sizeof(int32_t) - 1);
|
||||
}
|
||||
SECTION("missing cluster count") {
|
||||
std::filesystem::resize_file(file.path(), sizeof(int32_t));
|
||||
}
|
||||
SECTION("incomplete cluster count") {
|
||||
std::filesystem::resize_file(file.path(),
|
||||
sizeof(int32_t) + sizeof(uint32_t) - 1);
|
||||
}
|
||||
SECTION("missing cluster record") {
|
||||
std::filesystem::resize_file(file.path(), sizeof(int32_t) +
|
||||
sizeof(uint32_t) +
|
||||
sizeof(TestCluster));
|
||||
}
|
||||
SECTION("incomplete cluster record") {
|
||||
std::filesystem::resize_file(
|
||||
file.path(), std::filesystem::file_size(file.path()) - 1);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
if (use_roi) {
|
||||
reader.set_roi(aare::ROI{0, 10, 0, 10});
|
||||
}
|
||||
CHECK_THROWS_AS(reader.read_clusters(10), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile chunk reads reject truncated leftover clusters",
|
||||
"[ClusterFile]") {
|
||||
const auto use_roi = GENERATE(false, true);
|
||||
const auto requested = GENERATE(1, 10);
|
||||
CAPTURE(use_roi, requested);
|
||||
TemporaryClusterFile file;
|
||||
auto expected = make_test_frame(42, 0.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(expected);
|
||||
}
|
||||
std::filesystem::resize_file(file.path(),
|
||||
std::filesystem::file_size(file.path()) - 1);
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
if (use_roi) {
|
||||
reader.set_roi(aare::ROI{0, 10, 0, 10});
|
||||
}
|
||||
auto first = reader.read_clusters(1);
|
||||
REQUIRE(first.size() == 1);
|
||||
CHECK(first[0].data == expected[0].data);
|
||||
CHECK_THROWS_AS(reader.read_clusters(requested), std::runtime_error);
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile chunk reads preserve valid frame traversal",
|
||||
"[ClusterFile]") {
|
||||
const auto use_roi = GENERATE(false, true);
|
||||
CAPTURE(use_roi);
|
||||
TemporaryClusterFile file;
|
||||
auto first = make_test_frame(42, 0.0);
|
||||
auto second = make_test_frame(43, 100.0);
|
||||
ClusterVector<TestCluster> empty(0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(empty);
|
||||
writer.write_frame(first);
|
||||
writer.write_frame(empty);
|
||||
writer.write_frame(second);
|
||||
writer.write_frame(empty);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
if (use_roi) {
|
||||
reader.set_roi(aare::ROI{0, 10, 0, 10});
|
||||
}
|
||||
CHECK(reader.read_clusters(0).empty());
|
||||
CHECK(reader.tell() == 0);
|
||||
|
||||
auto initial = reader.read_clusters(1);
|
||||
REQUIRE(initial.size() == 1);
|
||||
CHECK(initial[0].data == first[0].data);
|
||||
const auto position = reader.tell();
|
||||
CHECK(reader.read_clusters(0).empty());
|
||||
CHECK(reader.tell() == position);
|
||||
CHECK_THROWS_AS(reader.read_frame(), std::runtime_error);
|
||||
|
||||
auto crossing = reader.read_clusters(2);
|
||||
REQUIRE(crossing.size() == 2);
|
||||
CHECK(crossing[0].data == first[1].data);
|
||||
CHECK(crossing[1].data == second[0].data);
|
||||
|
||||
auto final = reader.read_clusters(10);
|
||||
REQUIRE(final.size() == 1);
|
||||
CHECK(final[0].data == second[1].data);
|
||||
CHECK(static_cast<uintmax_t>(reader.tell()) ==
|
||||
std::filesystem::file_size(file.path()));
|
||||
CHECK(reader.read_clusters(10).empty());
|
||||
CHECK_FALSE(reader.read_frame());
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile frames preserve empty frames and reuse storage",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto first = make_test_frame(-42, 0.0);
|
||||
auto second = make_test_frame(105, 100.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(ClusterVector<TestCluster>(0, -43));
|
||||
writer.write_frame(first);
|
||||
writer.write_frame(ClusterVector<TestCluster>(0, 0));
|
||||
writer.write_frame(second);
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto frames = reader.frames();
|
||||
CHECK(reader.tell() == 0);
|
||||
const TestCluster *storage = nullptr;
|
||||
std::vector<int32_t> frame_numbers;
|
||||
for (auto &frame : frames) {
|
||||
frame_numbers.push_back(frame.frame_number());
|
||||
if (frame.frame_number() == -42) {
|
||||
check_frame(frame, first);
|
||||
storage = frame.data();
|
||||
} else if (frame.frame_number() == 105) {
|
||||
check_frame(frame, second);
|
||||
CHECK(frame.data() == storage);
|
||||
} else {
|
||||
CHECK(frame.empty());
|
||||
}
|
||||
}
|
||||
CHECK(frame_numbers == std::vector<int32_t>{-43, -42, 0, 105});
|
||||
CHECK(frames.begin() == frames.end());
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile chunks preserve cluster order across frame boundaries",
|
||||
"[ClusterFile]") {
|
||||
const auto chunk_size = GENERATE(1, 2, 3, 10);
|
||||
TemporaryClusterFile file;
|
||||
auto first = make_test_frame(42, 0.0);
|
||||
auto second = make_test_frame(43, 100.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(ClusterVector<TestCluster>(0));
|
||||
writer.write_frame(first);
|
||||
writer.write_frame(ClusterVector<TestCluster>(0));
|
||||
writer.write_frame(second);
|
||||
writer.write_frame(ClusterVector<TestCluster>(0));
|
||||
}
|
||||
|
||||
ClusterFile<TestCluster> reader(file.path(), chunk_size);
|
||||
auto chunks = reader.chunks();
|
||||
auto requested = static_cast<size_t>(chunk_size);
|
||||
SECTION("constructor size") {}
|
||||
SECTION("explicit size overrides the constructor") {
|
||||
chunks = reader.chunks(3);
|
||||
requested = 3;
|
||||
CHECK(reader.chunk_size() == static_cast<size_t>(chunk_size));
|
||||
}
|
||||
CHECK(reader.tell() == 0);
|
||||
size_t count = 0;
|
||||
for (auto &chunk : chunks) {
|
||||
REQUIRE(chunk.size() == std::min(requested, 4 - count));
|
||||
for (const auto &cluster : chunk) {
|
||||
REQUIRE(count < 4);
|
||||
const auto &expected = count < 2 ? first[count] : second[count - 2];
|
||||
CHECK(cluster.x == expected.x);
|
||||
CHECK(cluster.y == expected.y);
|
||||
CHECK(cluster.data == expected.data);
|
||||
++count;
|
||||
}
|
||||
}
|
||||
CHECK(count == 4);
|
||||
CHECK(chunks.begin() == chunks.end());
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile iterator results can be moved out without copying",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto first = make_test_frame(42, 0.0);
|
||||
auto second = make_test_frame(43, 100.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(first);
|
||||
writer.write_frame(second);
|
||||
}
|
||||
ClusterFile<TestCluster> reader(file.path(), 2);
|
||||
auto check_moves = [&](auto range) {
|
||||
auto it = range.begin();
|
||||
REQUIRE(it != range.end());
|
||||
CHECK(range.end() != it);
|
||||
const auto storage = it->data();
|
||||
auto retained = std::move(*it);
|
||||
CHECK(retained.data() == storage);
|
||||
++it;
|
||||
REQUIRE(it != range.end());
|
||||
check_frame(*it, second);
|
||||
check_frame(retained, first);
|
||||
it++;
|
||||
CHECK(it == range.end());
|
||||
CHECK(range.end() == it);
|
||||
++it;
|
||||
CHECK(it == range.end());
|
||||
reader.close();
|
||||
check_frame(retained, first);
|
||||
};
|
||||
SECTION("frames") { check_moves(reader.frames()); }
|
||||
SECTION("chunks") { check_moves(reader.chunks()); }
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile iteration preserves filtering and gain correction",
|
||||
"[ClusterFile]") {
|
||||
const auto use_roi = GENERATE(false, true);
|
||||
const auto use_noise = GENERATE(false, true);
|
||||
TemporaryClusterFile file;
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(make_test_frame(42, 0.0));
|
||||
writer.write_frame(make_test_frame(43, 100.0));
|
||||
}
|
||||
ClusterFile<TestCluster> reader(file.path(), 3);
|
||||
ClusterFile<TestCluster> reference(file.path());
|
||||
aare::NDArray<double, 2> gain({12, 12}, 2.0);
|
||||
aare::NDArray<int32_t, 2> noise({12, 12}, 5);
|
||||
for (auto *file_reader : {&reader, &reference}) {
|
||||
file_reader->set_gain_map(gain.view());
|
||||
if (use_roi) {
|
||||
file_reader->set_roi(aare::ROI{0, 6, 0, 12});
|
||||
}
|
||||
if (use_noise) {
|
||||
file_reader->set_noise_map(noise.view());
|
||||
}
|
||||
}
|
||||
SECTION("frames include fully rejected frames") {
|
||||
size_t count = 0;
|
||||
for (auto &frame : reader.frames()) {
|
||||
auto expected = reference.read_frame();
|
||||
REQUIRE(expected);
|
||||
check_frame(frame, *expected);
|
||||
++count;
|
||||
}
|
||||
CHECK(count == 2);
|
||||
CHECK_FALSE(reference.read_frame());
|
||||
}
|
||||
SECTION("chunks count selected clusters") {
|
||||
for (auto &chunk : reader.chunks()) {
|
||||
auto expected = reference.read_clusters(3);
|
||||
check_frame(chunk, expected);
|
||||
}
|
||||
CHECK(reference.read_clusters(3).empty());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile iteration resumes after an early exit",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
auto first = make_test_frame(42, 0.0);
|
||||
auto second = make_test_frame(43, 100.0);
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(first);
|
||||
writer.write_frame(second);
|
||||
}
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
SECTION("breaking a frame loop does not consume the following frame") {
|
||||
for (auto &frame : reader.frames()) {
|
||||
check_frame(frame, first);
|
||||
break;
|
||||
}
|
||||
auto next = reader.read_frame();
|
||||
REQUIRE(next);
|
||||
check_frame(*next, second);
|
||||
}
|
||||
SECTION("partial chunks must be completed before frame iteration") {
|
||||
for (auto &chunk : reader.chunks(1)) {
|
||||
REQUIRE(chunk.size() == 1);
|
||||
CHECK(chunk[0].data == first[0].data);
|
||||
break;
|
||||
}
|
||||
CHECK_THROWS_AS(reader.frames().begin(), std::runtime_error);
|
||||
auto remainder = reader.read_clusters(1);
|
||||
REQUIRE(remainder.size() == 1);
|
||||
CHECK(remainder[0].data == first[1].data);
|
||||
auto it = reader.frames().begin();
|
||||
REQUIRE(it != reader.frames().end());
|
||||
check_frame(*it, second);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterFile iterators distinguish EOF from read errors",
|
||||
"[ClusterFile]") {
|
||||
TemporaryClusterFile file;
|
||||
{
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, "w");
|
||||
writer.write_frame(make_test_frame(42, 0.0));
|
||||
}
|
||||
auto check_error = [&] {
|
||||
ClusterFile<TestCluster> frame_reader(file.path());
|
||||
ClusterFile<TestCluster> chunk_reader(file.path());
|
||||
CHECK_THROWS_AS(frame_reader.frames().begin(), std::runtime_error);
|
||||
CHECK_THROWS_AS(chunk_reader.chunks().begin(), std::runtime_error);
|
||||
};
|
||||
SECTION("empty file") {
|
||||
std::filesystem::resize_file(file.path(), 0);
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
CHECK(reader.frames().begin() == reader.frames().end());
|
||||
CHECK(reader.chunks().begin() == reader.chunks().end());
|
||||
}
|
||||
SECTION("partial header") {
|
||||
std::filesystem::resize_file(file.path(), 7);
|
||||
check_error();
|
||||
}
|
||||
SECTION("partial record") {
|
||||
std::filesystem::resize_file(
|
||||
file.path(), std::filesystem::file_size(file.path()) - 1);
|
||||
check_error();
|
||||
}
|
||||
SECTION("partial record encountered on increment") {
|
||||
std::filesystem::resize_file(
|
||||
file.path(), std::filesystem::file_size(file.path()) - 1);
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto it = reader.chunks(1).begin();
|
||||
REQUIRE(it != reader.chunks(1).end());
|
||||
CHECK_THROWS_AS(++it, std::runtime_error);
|
||||
}
|
||||
SECTION("closed before first read") {
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto frames = reader.frames();
|
||||
auto chunks = reader.chunks();
|
||||
reader.close();
|
||||
CHECK_THROWS_AS(frames.begin(), std::runtime_error);
|
||||
CHECK_THROWS_AS(chunks.begin(), std::runtime_error);
|
||||
}
|
||||
SECTION("closed during traversal") {
|
||||
ClusterFile<TestCluster> reader(file.path());
|
||||
auto it = reader.frames().begin();
|
||||
reader.close();
|
||||
CHECK_THROWS_AS(++it, std::runtime_error);
|
||||
}
|
||||
SECTION("write and append modes") {
|
||||
const auto mode = GENERATE("w", "a");
|
||||
ClusterFile<TestCluster> writer(file.path(), 1000, mode);
|
||||
CHECK_THROWS_AS(writer.frames().begin(), std::runtime_error);
|
||||
CHECK_THROWS_AS(writer.chunks().begin(), std::runtime_error);
|
||||
}
|
||||
SECTION("zero chunk sizes are rejected without reading") {
|
||||
ClusterFile<TestCluster> reader(file.path(), 0);
|
||||
CHECK_THROWS_AS(reader.chunks(), std::invalid_argument);
|
||||
CHECK_THROWS_AS(reader.chunks(0), std::invalid_argument);
|
||||
CHECK(reader.tell() == 0);
|
||||
CHECK(reader.read_clusters(0).empty());
|
||||
CHECK(reader.frames().begin() != reader.frames().end());
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("Read frame and modify cluster data", "[.with-data]") {
|
||||
auto fpath = test_data_path() / "clust" / "single_frame_97_clustrers.clust";
|
||||
REQUIRE(std::filesystem::exists(fpath));
|
||||
|
||||
ClusterFile<Cluster<int32_t, 3, 3>> f(fpath);
|
||||
|
||||
auto clusters = f.read_frame();
|
||||
CHECK(clusters.size() == 97);
|
||||
CHECK(clusters.frame_number() == 135);
|
||||
REQUIRE(clusters);
|
||||
CHECK(clusters->size() == 97);
|
||||
CHECK(clusters->frame_number() == 135);
|
||||
|
||||
int32_t expected_cluster_data[] = {0, 1, 2, 3, 4, 5, 6, 7, 8};
|
||||
clusters.push_back(
|
||||
clusters->push_back(
|
||||
Cluster<int32_t, 3, 3>{0, 0, {0, 1, 2, 3, 4, 5, 6, 7, 8}});
|
||||
|
||||
CHECK(clusters.size() == 98);
|
||||
CHECK(clusters[0].x == 1);
|
||||
CHECK(clusters[0].y == 200);
|
||||
CHECK(clusters->size() == 98);
|
||||
CHECK((*clusters)[0].x == 1);
|
||||
CHECK((*clusters)[0].y == 200);
|
||||
|
||||
CHECK(std::equal(std::begin(clusters[0].data), std::end(clusters[0].data),
|
||||
CHECK(std::equal(std::begin((*clusters)[0].data),
|
||||
std::end((*clusters)[0].data),
|
||||
std::begin(expected_cluster_data)));
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "ClusterFinderCUDA_testimpl.hpp"
|
||||
#include <algorithm>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
using namespace aare;
|
||||
|
||||
namespace {
|
||||
|
||||
template <typename C> void sort_by_position(std::vector<C> &v) {
|
||||
std::sort(v.begin(), v.end(), [](const C &a, const C &b) {
|
||||
return std::make_pair(a.y, a.x) < std::make_pair(b.y, b.x);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename C> bool identical(std::vector<C> a, std::vector<C> b) {
|
||||
if (a.size() != b.size())
|
||||
return false;
|
||||
sort_by_position(a);
|
||||
sort_by_position(b);
|
||||
for (size_t i = 0; i < a.size(); ++i)
|
||||
if (a[i].x != b[i].x || a[i].y != b[i].y || a[i].data != b[i].data)
|
||||
return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename R> void check(const R &r) {
|
||||
REQUIRE(r.manual.size() == r.driver.size());
|
||||
size_t total = 0;
|
||||
for (size_t f = 0; f < r.manual.size(); ++f) {
|
||||
INFO("frame " << f << ": manual " << r.manual[f].size() << " driver "
|
||||
<< r.driver[f].size());
|
||||
REQUIRE(identical(r.manual[f], r.driver[f]));
|
||||
total += r.manual[f].size();
|
||||
}
|
||||
// Guard against a vacuous pass: the synthetic frames carry photons.
|
||||
REQUIRE(total > 0);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
// FixedWindow::launch is the public contract for code that owns its device
|
||||
// memory. Driving it by hand on raw cudaMalloc buffers must give exactly what
|
||||
// ClusterFinderCUDA gives over the same frames. Odd frame dimensions keep the
|
||||
// partial-block and halo paths in play.
|
||||
TEST_CASE("FixedWindow::launch on caller-owned buffers matches the driver",
|
||||
"[cuda]") {
|
||||
SECTION("3x3") { check(test_cuda::run_fixed_window_3x3(61, 97, 1000, 20)); }
|
||||
SECTION("9x9") { check(test_cuda::run_fixed_window_9x9(61, 97, 1000, 20)); }
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "ClusterFinderCUDA_testimpl.hpp"
|
||||
#include "aare/ClusterFinderCUDA.hpp"
|
||||
#include "aare/clusterfinder_algo.cuh"
|
||||
#include <algorithm>
|
||||
#include <random>
|
||||
|
||||
namespace aare::test_cuda {
|
||||
namespace {
|
||||
|
||||
struct Synth {
|
||||
int nrows, ncols, n_ped, n_sig;
|
||||
std::vector<uint16_t> ped; // n_ped frames
|
||||
std::vector<uint16_t> sig; // n_sig frames with photons
|
||||
};
|
||||
|
||||
/// Deterministic pedestal + signal frames: per-pixel baseline in [4000, 5000),
|
||||
/// Gaussian noise of rms 8, and photons at random positions plus all four
|
||||
/// corners so the halo and bounds paths are exercised.
|
||||
Synth make_synth(int nrows, int ncols, int n_ped, int n_sig) {
|
||||
std::mt19937 rng(12345);
|
||||
std::uniform_real_distribution<double> base_d(4000.0, 5000.0);
|
||||
std::normal_distribution<double> noise(0.0, 8.0);
|
||||
std::uniform_int_distribution<int> row_d(0, nrows - 1), col_d(0, ncols - 1);
|
||||
std::uniform_real_distribution<double> amp(150.0, 400.0);
|
||||
|
||||
const size_t npx = static_cast<size_t>(nrows) * ncols;
|
||||
std::vector<double> base(npx);
|
||||
for (auto &b : base)
|
||||
b = base_d(rng);
|
||||
|
||||
auto to_u16 = [](double v) {
|
||||
return static_cast<uint16_t>(std::clamp(std::lround(v), 0L, 65535L));
|
||||
};
|
||||
|
||||
Synth s{nrows, ncols, n_ped, n_sig, {}, {}};
|
||||
s.ped.resize(static_cast<size_t>(n_ped) * npx);
|
||||
for (int f = 0; f < n_ped; ++f)
|
||||
for (size_t i = 0; i < npx; ++i)
|
||||
s.ped[f * npx + i] = to_u16(base[i] + noise(rng));
|
||||
|
||||
s.sig.resize(static_cast<size_t>(n_sig) * npx);
|
||||
std::vector<double> frame(npx);
|
||||
for (int f = 0; f < n_sig; ++f) {
|
||||
for (size_t i = 0; i < npx; ++i)
|
||||
frame[i] = base[i] + noise(rng);
|
||||
for (int k = 0; k < 40; ++k) {
|
||||
const int r = row_d(rng), c = col_d(rng);
|
||||
frame[r * ncols + c] += amp(rng);
|
||||
if (c + 1 < ncols)
|
||||
frame[r * ncols + c + 1] += 0.3 * amp(rng);
|
||||
}
|
||||
for (int r : {0, nrows - 1})
|
||||
for (int c : {0, ncols - 1})
|
||||
frame[r * ncols + c] += 300.0;
|
||||
for (size_t i = 0; i < npx; ++i)
|
||||
s.sig[f * npx + i] = to_u16(frame[i]);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
template <int N>
|
||||
ManualVsDriver<Cluster<int32_t, N, N>> run(int nrows, int ncols, int n_ped,
|
||||
int n_frames) {
|
||||
using C = Cluster<int32_t, N, N>;
|
||||
using Algo = cuda::FixedWindow<C, uint16_t>;
|
||||
|
||||
const size_t npx = static_cast<size_t>(nrows) * ncols;
|
||||
const uint32_t max_clusters = 4096;
|
||||
const float nSigma = 5.0f;
|
||||
const Synth s = make_synth(nrows, ncols, n_ped, n_frames);
|
||||
const Shape<2> shape{static_cast<ssize_t>(nrows),
|
||||
static_cast<ssize_t>(ncols)};
|
||||
|
||||
ManualVsDriver<C> out;
|
||||
out.manual.resize(n_frames);
|
||||
out.driver.resize(n_frames);
|
||||
|
||||
// ---- Route 1: caller-owned buffers, nothing from the driver ----------
|
||||
{
|
||||
Pedestal<double> ped(nrows, ncols);
|
||||
for (int f = 0; f < n_ped; ++f)
|
||||
ped.push(NDView<uint16_t, 2>(
|
||||
const_cast<uint16_t *>(s.ped.data() + f * npx), shape));
|
||||
|
||||
using Ped = typename Algo::pedestal;
|
||||
const auto img = Ped::prepare_pedestal(ped);
|
||||
|
||||
// Raw cudaMalloc on purpose: this route must not touch Ped::Buffers or
|
||||
// StreamContext, only the launch contract. The pedestal goes in as a
|
||||
// Ped::View over caller-owned pointers; the output block is owning by
|
||||
// design, so it comes from Algo::Output::allocate().
|
||||
float *d_mean = nullptr, *d_sum = nullptr, *d_sum2 = nullptr,
|
||||
*d_off = nullptr;
|
||||
uint16_t *d_frame = nullptr;
|
||||
const size_t pbytes = npx * sizeof(float);
|
||||
CUDA_CHECK(cudaMalloc(&d_mean, pbytes));
|
||||
CUDA_CHECK(cudaMalloc(&d_sum, pbytes));
|
||||
CUDA_CHECK(cudaMalloc(&d_sum2, pbytes));
|
||||
CUDA_CHECK(cudaMalloc(&d_off, pbytes));
|
||||
CUDA_CHECK(cudaMalloc(&d_frame, npx * sizeof(uint16_t)));
|
||||
auto d_output = Algo::Output::allocate(max_clusters);
|
||||
|
||||
cudaStream_t st = nullptr;
|
||||
CUDA_CHECK(cudaStreamCreate(&st));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d_mean, img.mean.data(), pbytes,
|
||||
cudaMemcpyHostToDevice, st));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d_sum, img.sum.data(), pbytes,
|
||||
cudaMemcpyHostToDevice, st));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d_sum2, img.sum2.data(), pbytes,
|
||||
cudaMemcpyHostToDevice, st));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d_off, img.off.data(), pbytes,
|
||||
cudaMemcpyHostToDevice, st));
|
||||
|
||||
const typename Ped::View pv{d_mean, d_sum, d_sum2, d_off};
|
||||
const typename Algo::LaunchParams lp{nrows, ncols, nSigma,
|
||||
max_clusters};
|
||||
const typename Ped::Params pp{static_cast<uint32_t>(ped.n_samples())};
|
||||
|
||||
std::vector<C> h_clusters(max_clusters);
|
||||
uint32_t h_count = 0;
|
||||
for (int f = 0; f < n_frames; ++f) {
|
||||
CUDA_CHECK(
|
||||
cudaMemsetAsync(d_output.count(), 0, sizeof(uint32_t), st));
|
||||
CUDA_CHECK(cudaMemcpyAsync(d_frame, s.sig.data() + f * npx,
|
||||
npx * sizeof(uint16_t),
|
||||
cudaMemcpyHostToDevice, st));
|
||||
Algo::launch(lp, pp, d_frame, pv, d_output, st);
|
||||
CUDA_CHECK(cudaMemcpyAsync(&h_count, d_output.count(),
|
||||
sizeof(uint32_t), cudaMemcpyDeviceToHost,
|
||||
st));
|
||||
CUDA_CHECK(cudaStreamSynchronize(st));
|
||||
const uint32_t n = std::min(h_count, max_clusters);
|
||||
CUDA_CHECK(cudaMemcpy(h_clusters.data(), d_output.clusters(),
|
||||
n * sizeof(C), cudaMemcpyDeviceToHost));
|
||||
out.manual[f].assign(h_clusters.begin(), h_clusters.begin() + n);
|
||||
}
|
||||
|
||||
CUDA_CHECK(cudaStreamDestroy(st));
|
||||
CUDA_CHECK(cudaFree(d_mean));
|
||||
CUDA_CHECK(cudaFree(d_sum));
|
||||
CUDA_CHECK(cudaFree(d_sum2));
|
||||
CUDA_CHECK(cudaFree(d_off));
|
||||
CUDA_CHECK(cudaFree(d_frame));
|
||||
}
|
||||
|
||||
// ---- Route 2: the driver. One stream so the per-frame pedestal update
|
||||
// follows the same sequence as route 1. --------------------------------
|
||||
{
|
||||
ClusterFinderCUDA<Algo> cf(shape, nSigma, max_clusters, 1);
|
||||
for (int f = 0; f < n_ped; ++f)
|
||||
cf.push_pedestal_frame(NDView<uint16_t, 2>(
|
||||
const_cast<uint16_t *>(s.ped.data() + f * npx), shape));
|
||||
auto res = cf.find_clusters_batched(
|
||||
NDView<uint16_t, 3>(
|
||||
const_cast<uint16_t *>(s.sig.data()),
|
||||
{static_cast<ssize_t>(n_frames), shape[0], shape[1]}),
|
||||
0);
|
||||
for (int f = 0; f < n_frames; ++f)
|
||||
for (size_t i = 0; i < res[f].size(); ++i)
|
||||
out.driver[f].push_back(res[f][i]);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
ManualVsDriver<Cluster<int32_t, 3, 3>>
|
||||
run_fixed_window_3x3(int nrows, int ncols, int n_ped, int n_frames) {
|
||||
return run<3>(nrows, ncols, n_ped, n_frames);
|
||||
}
|
||||
ManualVsDriver<Cluster<int32_t, 9, 9>>
|
||||
run_fixed_window_9x9(int nrows, int ncols, int n_ped, int n_frames) {
|
||||
return run<9>(nrows, ncols, n_ped, n_frames);
|
||||
}
|
||||
|
||||
} // namespace aare::test_cuda
|
||||
@@ -0,0 +1,24 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
// Plain C++ interface to the CUDA test work in ClusterFinderCUDA_testimpl.cu,
|
||||
// so the Catch2 test case itself never has to be compiled by nvcc.
|
||||
#pragma once
|
||||
#include "aare/Cluster.hpp"
|
||||
#include <cstdint>
|
||||
#include <vector>
|
||||
|
||||
namespace aare::test_cuda {
|
||||
|
||||
/// Clusters found per frame by two independent routes over the same data:
|
||||
/// `manual` drives FixedWindow::launch on hand-allocated device buffers,
|
||||
/// `driver` goes through ClusterFinderCUDA. They must agree exactly.
|
||||
template <typename C> struct ManualVsDriver {
|
||||
std::vector<std::vector<C>> manual;
|
||||
std::vector<std::vector<C>> driver;
|
||||
};
|
||||
|
||||
ManualVsDriver<Cluster<int32_t, 3, 3>>
|
||||
run_fixed_window_3x3(int nrows, int ncols, int n_ped, int n_frames);
|
||||
ManualVsDriver<Cluster<int32_t, 9, 9>>
|
||||
run_fixed_window_9x9(int nrows, int ncols, int n_ped, int n_frames);
|
||||
|
||||
} // namespace aare::test_cuda
|
||||
@@ -22,9 +22,11 @@ class ClusterFinderMTWrapper
|
||||
public:
|
||||
ClusterFinderMTWrapper(Shape<2> image_size, PEDESTAL_TYPE nSigma = 5.0,
|
||||
size_t capacity = 2000, size_t n_threads = 3,
|
||||
size_t queue_depth = 16)
|
||||
size_t queue_depth = 16,
|
||||
size_t minimum_pedestal_samples = 1000)
|
||||
: ClusterFinderMT<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>(
|
||||
image_size, nSigma, capacity, n_threads, queue_depth) {}
|
||||
image_size, nSigma, capacity, n_threads, queue_depth,
|
||||
minimum_pedestal_samples) {}
|
||||
|
||||
size_t get_m_input_queues_size() const {
|
||||
return this->m_input_queues.size();
|
||||
@@ -73,13 +75,14 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
File file(fpath);
|
||||
|
||||
size_t n_threads = 2;
|
||||
size_t n_frames_pd = 10;
|
||||
size_t minimum_pedestal_samples = 1;
|
||||
size_t n_frames = 10;
|
||||
|
||||
using ClusterType = Cluster<int32_t, 3, 3>;
|
||||
|
||||
ClusterFinderMTWrapper<ClusterType> cf(
|
||||
{static_cast<int64_t>(file.rows()), static_cast<int64_t>(file.cols())},
|
||||
5, 2000, n_threads); // no idea what frame type is!!! default uint16_t
|
||||
5, 2000, n_threads, 16, minimum_pedestal_samples);
|
||||
|
||||
CHECK(cf.get_m_input_queues_size() == n_threads);
|
||||
CHECK(cf.get_m_output_queues_size() == n_threads);
|
||||
@@ -87,8 +90,11 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_output_queues_are_empty() == true);
|
||||
CHECK(cf.m_input_queues_are_empty() == true);
|
||||
|
||||
for (size_t i = 0; i < n_frames_pd; ++i) {
|
||||
auto frame = file.read_frame();
|
||||
auto frame = file.read_frame();
|
||||
cf.push_pedestal_frame(frame.view<uint16_t>());
|
||||
|
||||
for (size_t i = 0; i < n_frames; ++i) {
|
||||
frame = file.read_frame();
|
||||
cf.find_clusters(frame.view<uint16_t>());
|
||||
}
|
||||
|
||||
@@ -97,7 +103,7 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_output_queues_are_empty() == true);
|
||||
CHECK(cf.m_input_queues_are_empty() == true);
|
||||
|
||||
CHECK(cf.m_sink_size() == n_frames_pd);
|
||||
CHECK(cf.m_sink_size() == n_frames);
|
||||
ClusterCollector<ClusterType> clustercollector(&cf);
|
||||
|
||||
clustercollector.stop();
|
||||
@@ -105,7 +111,6 @@ TEST_CASE("multithreaded cluster finder", "[.with-data]") {
|
||||
CHECK(cf.m_sink_size() == 0);
|
||||
|
||||
auto clustervec = clustercollector.steal_clusters();
|
||||
// CHECK(clustervec.size() == ) //dont know how many clusters to expect
|
||||
}
|
||||
|
||||
TEST_CASE("frame buffers are recycled when pushing more frames than the pool "
|
||||
|
||||
+160
-13
@@ -1,5 +1,8 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/ClusterVector.hpp"
|
||||
#include "aare/GainMap.hpp"
|
||||
#include "aare/NDArray.hpp"
|
||||
#include <algorithm>
|
||||
#include <cstdint>
|
||||
#include <utility>
|
||||
|
||||
@@ -22,27 +25,79 @@ TEST_CASE("After pushing back one element the ClusterVector is not empty") {
|
||||
REQUIRE(!cv.empty());
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterVector move constructor preserves contents") {
|
||||
ClusterVector<C1> source(4, 42);
|
||||
TEST_CASE("Filtering a ClusterVector selects the masked elements") {
|
||||
ClusterVector<C1> source(8, 123);
|
||||
source.push_back(C1{1, 2, {3, 4, 5, 6}});
|
||||
source.push_back(C1{7, 8, {9, 10, 11, 12}});
|
||||
source.push_back(C1{13, 14, {15, 16, 17, 18}});
|
||||
source.push_back(C1{19, 20, {21, 22, 23, 24}});
|
||||
|
||||
ClusterVector<C1> moved(std::move(source));
|
||||
SECTION("Some elements are selected") {
|
||||
std::array<bool, 4> mask{true, false, false, true};
|
||||
|
||||
REQUIRE(moved.size() == 1);
|
||||
CHECK(moved.frame_number() == 42);
|
||||
CHECK(moved[0].data[3] == 6);
|
||||
auto filtered = source(aare::NDView<bool, 1>{mask.data(), {4}});
|
||||
|
||||
CHECK(filtered.size() == 2);
|
||||
CHECK(filtered.frame_number() == 123);
|
||||
CHECK(filtered[0].x == 1);
|
||||
CHECK(filtered[1].x == 19);
|
||||
}
|
||||
|
||||
SECTION("No elements are selected") {
|
||||
std::array<bool, 4> mask{false, false, false, false};
|
||||
|
||||
auto filtered = source(aare::NDView<bool, 1>{mask.data(), {4}});
|
||||
|
||||
CHECK(filtered.empty());
|
||||
CHECK(filtered.frame_number() == 123);
|
||||
}
|
||||
|
||||
SECTION("An empty vector accepts a default empty mask") {
|
||||
ClusterVector<C1> empty_source(0, -123);
|
||||
|
||||
auto filtered = empty_source(aare::NDView<bool, 1>{});
|
||||
|
||||
CHECK(filtered.empty());
|
||||
CHECK(filtered.frame_number() == -123);
|
||||
}
|
||||
}
|
||||
|
||||
TEST_CASE("ClusterVector move assignment preserves contents") {
|
||||
ClusterVector<C1> source(4, 42);
|
||||
TEST_CASE("Move constructing a ClusterVector transfers its storage") {
|
||||
ClusterVector<C1> source(4, 123);
|
||||
source.push_back(C1{1, 2, {3, 4, 5, 6}});
|
||||
ClusterVector<C1> moved(1);
|
||||
source.push_back(C1{7, 8, {9, 10, 11, 12}});
|
||||
|
||||
moved = std::move(source);
|
||||
const auto *source_data = source.data();
|
||||
const auto source_capacity = source.capacity();
|
||||
|
||||
REQUIRE(moved.size() == 1);
|
||||
CHECK(moved.frame_number() == 42);
|
||||
CHECK(moved[0].data[3] == 6);
|
||||
ClusterVector<C1> destination(std::move(source));
|
||||
|
||||
CHECK(destination.data() == source_data);
|
||||
CHECK(destination.capacity() == source_capacity);
|
||||
CHECK(destination.size() == 2);
|
||||
CHECK(destination.frame_number() == 123);
|
||||
CHECK(destination[0].x == 1);
|
||||
CHECK(destination[1].x == 7);
|
||||
}
|
||||
|
||||
TEST_CASE("Move assigning a ClusterVector transfers its storage") {
|
||||
ClusterVector<C1> source(4, 123);
|
||||
source.push_back(C1{1, 2, {3, 4, 5, 6}});
|
||||
source.push_back(C1{7, 8, {9, 10, 11, 12}});
|
||||
|
||||
const auto *source_data = source.data();
|
||||
const auto source_capacity = source.capacity();
|
||||
|
||||
ClusterVector<C1> destination(2, 456);
|
||||
destination.push_back(C1{13, 14, {15, 16, 17, 18}});
|
||||
destination = std::move(source);
|
||||
|
||||
CHECK(destination.data() == source_data);
|
||||
CHECK(destination.capacity() == source_capacity);
|
||||
CHECK(destination.size() == 2);
|
||||
CHECK(destination.frame_number() == 123);
|
||||
CHECK(destination[0].x == 1);
|
||||
CHECK(destination[1].x == 7);
|
||||
}
|
||||
|
||||
TEST_CASE("item_size return the size of the cluster stored") {
|
||||
@@ -256,6 +311,28 @@ TEST_CASE("Concatenate two cluster vectors where we need to allocate") {
|
||||
REQUIRE(ptr[3].y == 17);
|
||||
}
|
||||
|
||||
TEST_CASE("Reducing a ClusterVector preserves its frame number") {
|
||||
SECTION("Reduce to 2x2") {
|
||||
ClusterVector<Cluster<int32_t, 3, 3>> source(1, -135);
|
||||
source.push_back(Cluster<int32_t, 3, 3>{});
|
||||
|
||||
auto reduced = aare::reduce_to_2x2(source);
|
||||
|
||||
CHECK(reduced.size() == source.size());
|
||||
CHECK(reduced.frame_number() == source.frame_number());
|
||||
}
|
||||
|
||||
SECTION("Reduce to 3x3") {
|
||||
ClusterVector<Cluster<int32_t, 5, 5>> source(1, -246);
|
||||
source.push_back(Cluster<int32_t, 5, 5>{});
|
||||
|
||||
auto reduced = aare::reduce_to_3x3(source);
|
||||
|
||||
CHECK(reduced.size() == source.size());
|
||||
CHECK(reduced.frame_number() == source.frame_number());
|
||||
}
|
||||
}
|
||||
|
||||
struct ClusterTestData {
|
||||
uint8_t ClusterSizeX;
|
||||
uint8_t ClusterSizeY;
|
||||
@@ -300,3 +377,73 @@ TEST_CASE("Gain Map Calculation Index Map") {
|
||||
CHECK(index_map_x == clustertestdata.index_map_x);
|
||||
CHECK(index_map_y == clustertestdata.index_map_y);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
template <uint8_t ClusterSizeX, uint8_t ClusterSizeY>
|
||||
void check_gain_map_cluster_bounds() {
|
||||
using ClusterType = Cluster<double, ClusterSizeX, ClusterSizeY>;
|
||||
|
||||
constexpr ssize_t rows = 16;
|
||||
constexpr ssize_t cols = 16;
|
||||
constexpr uint16_t left = ClusterSizeX / 2;
|
||||
constexpr uint16_t right = ClusterSizeX - left - 1;
|
||||
constexpr uint16_t top = ClusterSizeY / 2;
|
||||
constexpr uint16_t bottom = ClusterSizeY - top - 1;
|
||||
|
||||
aare::NDArray<double, 2> gain_map({rows, cols}, 2.0);
|
||||
aare::InvertedGainMap inverted_gain_map(gain_map);
|
||||
ClusterVector<ClusterType> clusters(6);
|
||||
|
||||
const auto add_cluster = [&clusters](uint16_t x, uint16_t y) {
|
||||
ClusterType cluster{};
|
||||
cluster.x = x;
|
||||
cluster.y = y;
|
||||
cluster.data.fill(2.0);
|
||||
clusters.push_back(cluster);
|
||||
};
|
||||
|
||||
add_cluster(left, top);
|
||||
add_cluster(cols - right - 1, rows - bottom - 1);
|
||||
add_cluster(left - 1, top);
|
||||
add_cluster(left, top - 1);
|
||||
add_cluster(cols - right, top);
|
||||
add_cluster(left, rows - bottom);
|
||||
|
||||
inverted_gain_map.apply_gain_map(clusters);
|
||||
|
||||
for (size_t i = 0; i < 2; ++i) {
|
||||
CHECK(std::all_of(clusters[i].data.begin(), clusters[i].data.end(),
|
||||
[](double value) { return value == 1.0; }));
|
||||
}
|
||||
for (size_t i = 2; i < clusters.size(); ++i) {
|
||||
CHECK(std::all_of(clusters[i].data.begin(), clusters[i].data.end(),
|
||||
[](double value) { return value == 0.0; }));
|
||||
}
|
||||
|
||||
aare::NDArray<double, 2> small_gain_map(
|
||||
{ClusterSizeY - 1, ClusterSizeX - 1}, 2.0);
|
||||
aare::InvertedGainMap small_inverted_gain_map(small_gain_map);
|
||||
ClusterVector<ClusterType> oversized_cluster(1);
|
||||
ClusterType cluster{};
|
||||
cluster.x = left;
|
||||
cluster.y = top;
|
||||
cluster.data.fill(2.0);
|
||||
oversized_cluster.push_back(cluster);
|
||||
|
||||
small_inverted_gain_map.apply_gain_map(oversized_cluster);
|
||||
|
||||
CHECK(std::all_of(oversized_cluster[0].data.begin(),
|
||||
oversized_cluster[0].data.end(),
|
||||
[](double value) { return value == 0.0; }));
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST_CASE("Gain map bounds cover the full cluster footprint", "[GainMap]") {
|
||||
SECTION("3x3") { check_gain_map_cluster_bounds<3, 3>(); }
|
||||
SECTION("5x5") { check_gain_map_cluster_bounds<5, 5>(); }
|
||||
SECTION("7x7") { check_gain_map_cluster_bounds<7, 7>(); }
|
||||
SECTION("9x9") { check_gain_map_cluster_bounds<9, 9>(); }
|
||||
SECTION("5x7") { check_gain_map_cluster_bounds<5, 7>(); }
|
||||
}
|
||||
+4
-4
@@ -24,9 +24,9 @@ void CtbRawFile::read_into(std::byte *image_buf, DetectorHeader *header) {
|
||||
throw std::runtime_error(LOCATION + " End of file reached");
|
||||
}
|
||||
|
||||
if (m_current_frame != 0 &&
|
||||
m_current_frame % m_master.max_frames_per_file() == 0) {
|
||||
open_data_file(m_current_subfile + 1);
|
||||
const auto index = sub_file_index(m_current_frame);
|
||||
if (index != m_current_subfile) {
|
||||
open_data_file(index);
|
||||
}
|
||||
|
||||
if (header) {
|
||||
@@ -79,4 +79,4 @@ void CtbRawFile::open_data_file(size_t subfile_index) {
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace aare
|
||||
} // namespace aare
|
||||
@@ -11,7 +11,8 @@ DetectorGeometry::DetectorGeometry(const xy &geometry,
|
||||
const ssize_t module_pixels_x,
|
||||
const ssize_t module_pixels_y,
|
||||
const xy udp_interfaces_per_module,
|
||||
const bool quad) {
|
||||
const bool quad)
|
||||
: m_udp_interfaces_per_module(udp_interfaces_per_module) {
|
||||
|
||||
size_t num_modules = geometry.col * geometry.row;
|
||||
module_geometries.reserve(num_modules);
|
||||
@@ -43,6 +44,10 @@ DetectorGeometry::DetectorGeometry(const xy &geometry,
|
||||
m_pixels_y += static_cast<size_t>((geometry.row - 1) * cfg.module_gap_row);
|
||||
}
|
||||
|
||||
xy DetectorGeometry::udp_interfaces_per_module() const {
|
||||
return m_udp_interfaces_per_module;
|
||||
}
|
||||
|
||||
size_t DetectorGeometry::n_modules() const { return m_modules_x * m_modules_y; }
|
||||
|
||||
size_t DetectorGeometry::pixels_x() const { return m_pixels_x; }
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
// SPDX-License-Identifier: MPL-2.0
|
||||
#include "aare/FastPedestal.hpp"
|
||||
|
||||
#include <catch2/catch_template_test_macros.hpp>
|
||||
#include <catch2/catch_test_macros.hpp>
|
||||
|
||||
using namespace aare;
|
||||
|
||||
TEMPLATE_TEST_CASE("fast pedestal keeps variance in double precision",
|
||||
"[fast-pedestal]", double, float, int16_t) {
|
||||
FastPedestal<TestType> pedestal(1, 1, 2);
|
||||
NDArray<uint16_t, 2> frame({1, 1}, 0);
|
||||
pedestal.add_init_frame(frame.view());
|
||||
frame[0] = 1000;
|
||||
pedestal.add_init_frame(frame.view());
|
||||
|
||||
const auto &ready = pedestal;
|
||||
REQUIRE(ready.std(0, 0) == static_cast<TestType>(500));
|
||||
REQUIRE(ready.std_unchecked(0) == ready.std(0, 0));
|
||||
REQUIRE(ready.std()[0] == ready.std(0, 0));
|
||||
|
||||
pedestal.push_ema(frame.view());
|
||||
REQUIRE(ready.std(0, 0) == static_cast<TestType>(std::sqrt(187500.0)));
|
||||
REQUIRE(ready.std_unchecked(0) == ready.std(0, 0));
|
||||
REQUIRE(ready.std()[0] == ready.std(0, 0));
|
||||
}
|
||||
|
||||
TEST_CASE("fast pedestal validates standard deviation access",
|
||||
"[fast-pedestal]") {
|
||||
FastPedestal<double> pedestal(1, 1, 1);
|
||||
REQUIRE_THROWS(pedestal.std());
|
||||
REQUIRE_THROWS(pedestal.std(0, 0));
|
||||
|
||||
NDArray<uint16_t, 2> frame({1, 1}, 42);
|
||||
pedestal.add_init_frame(frame.view());
|
||||
REQUIRE(pedestal.std(0, 0) == 0.0);
|
||||
REQUIRE_THROWS(pedestal.std(1, 0));
|
||||
REQUIRE_THROWS(pedestal.std(0, 1));
|
||||
}
|
||||
|
||||
TEMPLATE_TEST_CASE("fast pedestal std stays finite after settling",
|
||||
"[fast-pedestal]", double, float, int16_t) {
|
||||
FastPedestal<TestType> pedestal(1, 1, 10);
|
||||
NDArray<uint16_t, 2> frame({1, 1}, 16382);
|
||||
pedestal.add_init_frame(frame.view());
|
||||
frame[0] = 16383;
|
||||
for (int i = 0; i < 9; ++i) {
|
||||
pedestal.add_init_frame(frame.view());
|
||||
}
|
||||
for (int i = 0; i < 300; ++i) {
|
||||
pedestal.push_ema(frame.view());
|
||||
}
|
||||
|
||||
const auto noise = pedestal.std(0, 0);
|
||||
REQUIRE(std::isfinite(noise));
|
||||
REQUIRE(noise >= 0);
|
||||
REQUIRE(static_cast<double>(noise) < 1e-3);
|
||||
REQUIRE(pedestal.std_unchecked(0) == noise);
|
||||
REQUIRE(pedestal.std()[0] == noise);
|
||||
}
|
||||
@@ -22,6 +22,8 @@ FilePtr &FilePtr::operator=(FilePtr &&other) {
|
||||
return *this;
|
||||
}
|
||||
|
||||
FilePtr::operator bool() const noexcept { return fp_ != nullptr; }
|
||||
|
||||
FILE *FilePtr::get() { return fp_; }
|
||||
|
||||
ssize_t FilePtr::tell() {
|
||||
|
||||
Loaded 100 of 115 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user