Merge branch 'main' into fix/spsc-move-assign-leak
Build on RHEL9 / build (push) Successful in 3m12s
Build on RHEL8 / build (push) Successful in 3m44s
Run tests using data on local RHEL8 / build (push) Successful in 4m26s

This commit is contained in:
Erik Fröjdh authored and GitHub committed 2026-09-23 16:17:54 +02:00
commit e5cd15dc28
277 files changed
+25657 -4532

No files matched your search

+5 -4
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/defs.hpp"
#include <array>
@@ -28,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(); }
};
@@ -42,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(); }
};
@@ -56,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(); }
};
@@ -70,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(); }
};
+48
View File
@@ -0,0 +1,48 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <chrono>
#include <thread>
namespace aare {
/**
* @brief Hint the CPU that this is a spin-wait. Prefer this over yield() when
* the wait is expected to be short.
*/
inline void cpu_relax() noexcept {
#if defined(__x86_64__) || defined(__i386__)
__builtin_ia32_pause();
#elif defined(__aarch64__)
asm volatile("yield" ::: "memory");
#else
std::this_thread::yield();
#endif
}
/**
* @brief Escalating wait for producer/consumer idle and backpressure loops.
*
* Starts with a pause instruction (sub-microsecond, no syscall), then yield,
* then a short sleep. Call reset() whenever work arrives so a busy pipeline
* never leaves the pause tier.
*/
class Backoff {
int m_count{0};
public:
void reset() noexcept { m_count = 0; }
void pause() noexcept {
if (m_count < 64) {
cpu_relax();
} else if (m_count < 256) {
std::this_thread::yield();
} else {
std::this_thread::sleep_for(std::chrono::microseconds(50));
}
++m_count;
}
};
} // namespace aare
+369 -95
View File
@@ -1,18 +1,13 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Cluster.hpp"
#include "aare/ClusterVector.hpp"
#include "aare/NDArray.hpp"
#include "aare/defs.hpp"
namespace aare {
enum class corner : int {
cBottomLeft = 0,
cBottomRight = 1,
cTopLeft = 2,
cTopRight = 3
};
enum class pixel : int {
pBottomLeft = 0,
pBottom = 1,
@@ -25,149 +20,428 @@ enum class pixel : int {
pTopRight = 8
};
// TODO: better to have sum after x,y
/**
* eta struct
*/
template <typename T> struct Eta2 {
double x;
double y;
int c{0};
T sum;
/// @brief eta in x direction
double x{};
/// @brief eta in y direction
double y{};
/// @brief index of subcluster with highest energy value (given as corner
/// relative to cluster center)
corner c{0};
/// @brief photon energy (cluster sum)
T sum{};
};
/**
* @brief Calculate the eta2 values for all clusters in a Clustervector
* @brief Calculate the eta2 values for all clusters in a ClusterVector
*/
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
NDArray<double, 2> calculate_eta2(const ClusterVector<ClusterType> &clusters) {
NDArray<double, 2> eta2({static_cast<int64_t>(clusters.size()), 2});
std::vector<Eta2<typename ClusterType::value_type>>
calculate_eta2(const ClusterVector<ClusterType> &clusters) {
std::vector<Eta2<typename ClusterType::value_type>> eta2{};
eta2.reserve(clusters.size());
for (size_t i = 0; i < clusters.size(); i++) {
auto e = calculate_eta2(clusters[i]);
eta2(i, 0) = e.x;
eta2(i, 1) = e.y;
eta2.push_back(e);
}
return eta2;
}
/**
* @brief Calculate the full eta2 values for all clusters in a ClusterVector
*/
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
std::vector<Eta2<typename ClusterType::value_type>>
calculate_full_eta2(const ClusterVector<ClusterType> &clusters) {
std::vector<Eta2<typename ClusterType::value_type>> eta2{};
eta2.reserve(clusters.size());
for (size_t i = 0; i < clusters.size(); i++) {
auto e = calculate_full_eta2(clusters[i]);
eta2.push_back(e);
}
return eta2;
}
/**
* @brief Calculate eta3 for all 3x3 clusters in a ClusterVector
*/
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
std::vector<Eta2<typename ClusterType::value_type>>
calculate_eta3(const ClusterVector<ClusterType> &clusters) {
std::vector<Eta2<typename ClusterType::value_type>> eta2{};
eta2.reserve(clusters.size());
for (size_t i = 0; i < clusters.size(); i++) {
auto e = calculate_eta3(clusters[i]);
eta2.push_back(e);
}
return eta2;
}
/**
* @brief Calculate cross eta3 for all 3x3 clusters in a ClusterVector
*/
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
std::vector<Eta2<typename ClusterType::value_type>>
calculate_cross_eta3(const ClusterVector<ClusterType> &clusters) {
std::vector<Eta2<typename ClusterType::value_type>> eta2{};
eta2.reserve(clusters.size());
for (size_t i = 0; i < clusters.size(); i++) {
auto e = calculate_cross_eta3(clusters[i]);
eta2.push_back(e);
}
return eta2;
}
/**
* @brief helper function to calculate eta2 x and y values
* @param eta reference to the Eta2 object to update
* @param left_x value of the left pixel
* @param right_x value of the right pixel
* @param bottom_y value of the bottom pixel
* @param top_y value of the top pixel
*/
template <typename T>
inline void calculate_eta2(Eta2<T> &eta, const T left_x, const T right_x,
const T bottom_y, const T top_y) {
if ((right_x + left_x) != 0)
eta.x = static_cast<double>(right_x) /
static_cast<double>(right_x + left_x); // between (0,1) the
// closer to zero left
// value probably larger
if ((top_y + bottom_y) != 0)
eta.y = static_cast<double>(top_y) /
static_cast<double>(top_y + bottom_y); // between (0,1) the
// closer to zero bottom
// value probably larger
}
/**
* @brief Calculate the eta2 values for a generic sized cluster and return them
* in a Eta2 struct containing etay, etax and the index of the respective 2x2
* subcluster.
* in a Eta2 struct containing etay, etax and the index (as corner) of the
* respective 2x2 subcluster relative to the cluster center.
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType>
typename CoordType = uint16_t>
Eta2<T>
calculate_eta2(const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
Eta2<T> eta{};
auto max_sum = cl.max_sum_2x2();
eta.sum = max_sum.first;
auto c = max_sum.second;
static_assert(ClusterSizeX > 1 && ClusterSizeY > 1);
Eta2<T> eta{};
size_t cluster_center_index =
(ClusterSizeX / 2) + (ClusterSizeY / 2) * ClusterSizeX;
size_t index_bottom_left_max_2x2_subcluster =
(int(c / (ClusterSizeX - 1))) * ClusterSizeX + c % (ClusterSizeX - 1);
auto max_sum = cl.max_sum_2x2();
eta.sum = max_sum.sum;
corner c = max_sum.index;
// calculate direction of gradient
// check that cluster center is in max subcluster
if (cluster_center_index != index_bottom_left_max_2x2_subcluster &&
cluster_center_index != index_bottom_left_max_2x2_subcluster + 1 &&
cluster_center_index !=
index_bottom_left_max_2x2_subcluster + ClusterSizeX &&
cluster_center_index !=
index_bottom_left_max_2x2_subcluster + ClusterSizeX + 1)
throw std::runtime_error("Photon center is not in max 2x2_subcluster");
if ((cluster_center_index - index_bottom_left_max_2x2_subcluster) %
ClusterSizeX ==
0) {
if ((cl.data[cluster_center_index + 1] +
cl.data[cluster_center_index]) != 0)
eta.x = static_cast<double>(cl.data[cluster_center_index + 1]) /
static_cast<double>((cl.data[cluster_center_index + 1] +
cl.data[cluster_center_index]));
} else {
if ((cl.data[cluster_center_index] +
cl.data[cluster_center_index - 1]) != 0)
eta.x = static_cast<double>(cl.data[cluster_center_index]) /
static_cast<double>((cl.data[cluster_center_index - 1] +
cl.data[cluster_center_index]));
}
if ((cluster_center_index - index_bottom_left_max_2x2_subcluster) /
ClusterSizeX <
1) {
assert(cluster_center_index + ClusterSizeX <
ClusterSizeX * ClusterSizeY); // suppress warning
if ((cl.data[cluster_center_index] +
cl.data[cluster_center_index + ClusterSizeX]) != 0)
eta.y = static_cast<double>(
cl.data[cluster_center_index + ClusterSizeX]) /
static_cast<double>(
(cl.data[cluster_center_index] +
cl.data[cluster_center_index + ClusterSizeX]));
} else {
if ((cl.data[cluster_center_index] +
cl.data[cluster_center_index - ClusterSizeX]) != 0)
eta.y = static_cast<double>(cl.data[cluster_center_index]) /
static_cast<double>(
(cl.data[cluster_center_index] +
cl.data[cluster_center_index - ClusterSizeX]));
// subcluster top right from center
switch (c) {
case (corner::cTopLeft):
calculate_eta2(eta, cl.data[cluster_center_index - 1],
cl.data[cluster_center_index],
cl.data[cluster_center_index - ClusterSizeX],
cl.data[cluster_center_index]);
// dx = -1
// dy = -1
break;
case (corner::cTopRight):
calculate_eta2(eta, cl.data[cluster_center_index],
cl.data[cluster_center_index + 1],
cl.data[cluster_center_index - ClusterSizeX],
cl.data[cluster_center_index]);
// dx = 0
// dy = -1
break;
case (corner::cBottomLeft):
calculate_eta2(eta, cl.data[cluster_center_index - 1],
cl.data[cluster_center_index],
cl.data[cluster_center_index],
cl.data[cluster_center_index + ClusterSizeX]);
// dx = -1
// dy = 0
break;
case (corner::cBottomRight):
calculate_eta2(eta, cl.data[cluster_center_index],
cl.data[cluster_center_index + 1],
cl.data[cluster_center_index],
cl.data[cluster_center_index + ClusterSizeX]);
// dx = 0
// dy = 0
break;
}
eta.c = c; // TODO only supported for 2x2 and 3x3 clusters -> at least no
// underyling enum class
eta.c = c;
return eta;
}
// TODO! Look up eta2 calculation - photon center should be top right corner
template <typename T>
Eta2<T> calculate_eta2(const Cluster<T, 2, 2, int16_t> &cl) {
/**
* @brief Calculate the eta2 values for a generic sized cluster and return them
* in a Eta2 struct containing etay, etax and the index (as corner) of the
* respective 2x2 subcluster relative to the cluster center.
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType>
Eta2<T> calculate_full_eta2(
const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
static_assert(ClusterSizeX > 1 && ClusterSizeY > 1);
Eta2<T> eta{};
if ((cl.data[0] + cl.data[1]) != 0)
eta.x = static_cast<double>(cl.data[1]) /
(cl.data[0] + cl.data[1]); // between (0,1) the closer to zero
// left value probably larger
if ((cl.data[0] + cl.data[2]) != 0)
eta.y = static_cast<double>(cl.data[2]) /
(cl.data[0] + cl.data[2]); // between (0,1) the closer to zero
// bottom value probably larger
constexpr size_t cluster_center_index =
(ClusterSizeX / 2) + (ClusterSizeY / 2) * ClusterSizeX;
auto max_sum = cl.max_sum_2x2();
eta.sum = max_sum.sum;
corner c = max_sum.index;
// subcluster top right from center
switch (c) {
case (corner::cTopLeft):
if (eta.sum != 0) {
eta.x = static_cast<double>(
cl.data[cluster_center_index] +
cl.data[cluster_center_index - ClusterSizeX]) /
static_cast<double>(eta.sum);
eta.y = static_cast<double>(cl.data[cluster_center_index - 1] +
cl.data[cluster_center_index]) /
static_cast<double>(eta.sum);
}
// dx = -1
// dy = -1
break;
case (corner::cTopRight):
if (eta.sum != 0) {
eta.x = static_cast<double>(
cl.data[cluster_center_index + 1] +
cl.data[cluster_center_index - ClusterSizeX + 1]) /
static_cast<double>(eta.sum);
eta.y = static_cast<double>(cl.data[cluster_center_index] +
cl.data[cluster_center_index + 1]) /
static_cast<double>(eta.sum);
}
// dx = 0
// dy = -1
break;
case (corner::cBottomLeft):
if (eta.sum != 0) {
eta.x = static_cast<double>(
cl.data[cluster_center_index] +
cl.data[cluster_center_index + ClusterSizeX]) /
static_cast<double>(eta.sum);
eta.y = static_cast<double>(
cl.data[cluster_center_index + ClusterSizeX] +
cl.data[cluster_center_index + ClusterSizeX - 1]) /
static_cast<double>(eta.sum);
}
// dx = -1
// dy = 0
break;
case (corner::cBottomRight):
if (eta.sum != 0) {
eta.x = static_cast<double>(
cl.data[cluster_center_index + 1] +
cl.data[cluster_center_index + ClusterSizeX + 1]) /
static_cast<double>(eta.sum);
eta.y = static_cast<double>(
cl.data[cluster_center_index + ClusterSizeX] +
cl.data[cluster_center_index + ClusterSizeX + 1]) /
static_cast<double>(eta.sum);
}
// dx = 0
// dy = 0
break;
}
eta.c = c;
return eta;
}
template <typename T>
Eta2<T> calculate_eta2(const Cluster<T, 2, 2, uint16_t> &cl) {
Eta2<T> eta{};
// TODO: maybe have as member function of cluster
const uint8_t photon_hit_index =
std::max_element(cl.data.begin(), cl.data.end()) - cl.data.begin();
eta.c = static_cast<corner>(3 - photon_hit_index);
switch (eta.c) {
case corner::cTopLeft:
calculate_eta2(eta, cl.data[2], cl.data[3], cl.data[1], cl.data[3]);
break;
case corner::cTopRight:
calculate_eta2(eta, cl.data[2], cl.data[3], cl.data[0], cl.data[2]);
break;
case corner::cBottomLeft:
calculate_eta2(eta, cl.data[0], cl.data[1], cl.data[1], cl.data[3]);
break;
case corner::cBottomRight:
calculate_eta2(eta, cl.data[0], cl.data[1], cl.data[0], cl.data[2]);
break;
}
eta.sum = cl.sum();
return eta;
}
// calculates Eta3 for 3x3 cluster based on code from analyze_cluster
// TODO only supported for 3x3 Clusters
template <typename T> Eta2<T> calculate_eta3(const Cluster<T, 3, 3> &cl) {
template <typename T>
Eta2<T> calculate_full_eta2(const Cluster<T, 2, 2, uint16_t> &cl) {
Eta2<T> eta{};
T sum = 0;
eta.sum = cl.sum();
std::for_each(std::begin(cl.data), std::end(cl.data),
[&sum](T x) { sum += x; });
const uint8_t photon_hit_index =
std::max_element(cl.data.begin(), cl.data.end()) - cl.data.begin();
eta.sum = sum;
eta.c = static_cast<corner>(3 - photon_hit_index);
if (eta.sum != 0) {
eta.x = static_cast<double>(cl.data[1] + cl.data[3]) /
static_cast<double>(eta.sum);
eta.y = static_cast<double>(cl.data[2] + cl.data[3]) /
static_cast<double>(eta.sum);
}
return eta;
}
// TODO generalize
template <typename T>
Eta2<T> calculate_eta2(const Cluster<T, 1, 2, uint16_t> &cl) {
Eta2<T> eta{};
eta.x = 0;
eta.y = static_cast<double>(cl.data[1]) / cl.data[0];
eta.sum = cl.sum();
}
template <typename T>
Eta2<T> calculate_eta2(const Cluster<T, 2, 1, uint16_t> &cl) {
Eta2<T> eta{};
eta.x = static_cast<double>(cl.data[1]) / cl.data[0];
eta.y = 0;
eta.sum = cl.sum();
}
/**
* @brief calculates cross Eta3 for 3x3 cluster
* cross Eta3 calculates the eta by taking into account only the cross pixels
* {top, bottom, left, right, center}
*/
template <typename T, typename CoordType = uint16_t>
Eta2<T> calculate_cross_eta3(const Cluster<T, 3, 3, CoordType> &cl) {
Eta2<T> eta{};
T photon_energy = cl.sum();
eta.sum = photon_energy;
if ((cl.data[3] + cl.data[4] + cl.data[5]) != 0)
eta.x = static_cast<double>(-cl.data[3] + cl.data[3 + 2]) /
eta.x =
static_cast<double>(-cl.data[3] + cl.data[3 + 2]) /
(cl.data[3] + cl.data[4] + cl.data[5]); // (-1,1)
static_cast<double>(cl.data[3] + cl.data[4] + cl.data[5]); // (-1,1)
if ((cl.data[1] + cl.data[4] + cl.data[7]) != 0)
eta.y = static_cast<double>(-cl.data[1] + cl.data[2 * 3 + 1]) /
(cl.data[1] + cl.data[4] + cl.data[7]);
static_cast<double>(cl.data[1] + cl.data[4] + cl.data[7]);
return eta;
}
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = uint16_t>
Eta2<T> calculate_cross_eta3(
const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
static_assert(ClusterSizeX > 2 && ClusterSizeY > 2,
"calculate_eta3 only defined for clusters larger than 2x2");
if constexpr (ClusterSizeX != 3 || ClusterSizeY != 3) {
auto reduced_cluster = reduce_cluster_to_3x3(cl);
return calculate_cross_eta3(reduced_cluster);
} else {
return calculate_cross_eta3(cl);
}
}
/**
* @brief calculates Eta3 for 3x3 cluster
* It calculates the eta by taking into account all pixels in the 3x3 cluster
*/
template <typename T, typename CoordType = uint16_t>
Eta2<T> calculate_eta3(const Cluster<T, 3, 3, CoordType> &cl) {
Eta2<T> eta{};
T photon_energy = cl.sum();
eta.sum = photon_energy;
// TODO: how do we handle potential arithmetic overflows? - T could be
// uint16
if (photon_energy != 0) {
std::array<T, 2> column_sums{
static_cast<T>(cl.data[0] + cl.data[3] + cl.data[6]),
static_cast<T>(cl.data[2] + cl.data[5] + cl.data[8])};
eta.x = static_cast<double>(-column_sums[0] + column_sums[1]) /
static_cast<double>(photon_energy);
std::array<T, 2> row_sums{
static_cast<T>(cl.data[0] + cl.data[1] + cl.data[2]),
static_cast<T>(cl.data[6] + cl.data[7] + cl.data[8])};
eta.y = static_cast<double>(-row_sums[0] + row_sums[1]) /
static_cast<double>(photon_energy);
}
return eta;
}
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = uint16_t>
Eta2<T>
calculate_eta3(const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cl) {
static_assert(ClusterSizeX > 2 && ClusterSizeY > 2,
"calculate_eta3 only defined for clusters larger than 2x2");
if constexpr (ClusterSizeX != 3 || ClusterSizeY != 3) {
auto reduced_cluster = reduce_cluster_to_3x3(cl);
return calculate_eta3(reduced_cluster);
} else {
return calculate_eta3(cl);
}
}
} // namespace aare
+44 -3
View File
@@ -1,10 +1,13 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <cassert>
#include <chrono>
#include <fmt/color.h>
#include <fmt/format.h>
#include <memory>
#include <thread>
#include <utility>
#include "aare/ProducerConsumerQueue.hpp"
@@ -16,7 +19,7 @@ template <class ItemType> class CircularFifo {
aare::ProducerConsumerQueue<ItemType> filled_slots;
public:
CircularFifo() : CircularFifo(100){};
CircularFifo() : CircularFifo(100) {};
CircularFifo(uint32_t size)
: fifo_size(size), free_slots(size + 1), filled_slots(size + 1) {
@@ -28,6 +31,23 @@ template <class ItemType> class CircularFifo {
}
}
/**
* @brief Construct a fifo and seed the free list using a factory.
* @param size number of items circulating in the fifo
* @param make_item callable invoked as make_item(i) for each slot index i
*
* Use this instead of CircularFifo(size) when the items need to be
* initialized, for example to hold a preallocated buffer or to carry
* their own slot index.
*/
template <class F>
CircularFifo(uint32_t size, F make_item)
: fifo_size(size), free_slots(size + 1), filled_slots(size + 1) {
for (size_t i = 0; i < fifo_size; ++i) {
free_slots.write(make_item(i));
}
}
bool next() {
// TODO! avoid default constructing ItemType
ItemType it;
@@ -46,6 +66,13 @@ template <class ItemType> class CircularFifo {
auto numFreeSlots() const noexcept { return free_slots.sizeGuess(); }
auto isFull() const noexcept { return filled_slots.isFull(); }
/**
* @brief True if there are no filled slots waiting to be consumed.
* @note Prefer this over numFilledSlots() == 0 since sizeGuess() may
* under-report when called from the producing thread.
*/
auto isEmpty() const noexcept { return filled_slots.isEmpty(); }
ItemType pop_free() {
ItemType v;
while (!free_slots.read(v))
@@ -74,8 +101,22 @@ template <class ItemType> class CircularFifo {
ItemType *frontPtr() { return filled_slots.frontPtr(); }
// TODO! Add function to move item from filled to free to be used
// with the frontPtr function
/**
* @brief Return the front filled item to the free list. To be used
* together with frontPtr() once the item has been consumed in place.
* @warning The fifo must not be empty when calling this.
*
* The item is written to the free list before it is popped from the
* filled list, so it can never be dropped. The write cannot fail: both
* queues hold size + 1 slots while only size items circulate.
*/
void recycle_front() {
ItemType *it = filled_slots.frontPtr();
assert(it != nullptr);
[[maybe_unused]] const bool ok = free_slots.write(std::move(*it));
assert(ok);
filled_slots.popFront();
}
template <class... Args> void push_value(Args &&...recordArgs) {
while (!filled_slots.write(std::forward<Args>(recordArgs)...))
+113 -117
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
/************************************************
* @file Cluster.hpp
@@ -8,7 +9,7 @@
#pragma once
#include "logger.hpp"
#include "defs.hpp"
#include <algorithm>
#include <array>
#include <cstdint>
@@ -18,8 +19,12 @@
namespace aare {
// requires clause c++20 maybe update
/**
* @brief Cluster struct
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = int16_t>
typename CoordType = uint16_t>
struct Cluster {
static_assert(std::is_arithmetic_v<T>, "T needs to be an arithmetic type");
@@ -28,8 +33,11 @@ struct Cluster {
static_assert(ClusterSizeX > 0 && ClusterSizeY > 0,
"Cluster sizes must be bigger than zero");
/// @brief Cluster center x coordinate (in pixel coordinates)
CoordType x;
/// @brief Cluster center y coordinate (in pixel coordinates)
CoordType y;
/// @brief Cluster data stored in row-major order starting from top-left
std::array<T, ClusterSizeX * ClusterSizeY> data;
static constexpr uint8_t cluster_size_x = ClusterSizeX;
@@ -37,9 +45,18 @@ struct Cluster {
using value_type = T;
using coord_type = CoordType;
/**
* @brief Sum of all elements in the cluster
*/
T sum() const { return std::accumulate(data.begin(), data.end(), T{}); }
std::pair<T, int> max_sum_2x2() const {
// TODO: handle 1 dimensional clusters
/**
* @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 {
if constexpr (cluster_size_x == 3 && cluster_size_y == 3) {
std::array<T, 4> sum_2x2_subclusters;
@@ -50,96 +67,122 @@ struct Cluster {
int index = std::max_element(sum_2x2_subclusters.begin(),
sum_2x2_subclusters.end()) -
sum_2x2_subclusters.begin();
return std::make_pair(sum_2x2_subclusters[index], index);
return Sum_index_pair<T, corner>{sum_2x2_subclusters[index],
corner{index}};
} else if constexpr (cluster_size_x == 2 && cluster_size_y == 2) {
return std::make_pair(data[0] + data[1] + data[2] + data[3], 0);
return Sum_index_pair<T, corner>{
data[0] + data[1] + data[2] + data[3], corner{0}};
} else {
constexpr size_t num_2x2_subclusters =
(ClusterSizeX - 1) * (ClusterSizeY - 1);
constexpr size_t cluster_center_index =
(ClusterSizeX / 2) + (ClusterSizeY / 2) * ClusterSizeX;
std::array<T, num_2x2_subclusters> sum_2x2_subcluster;
for (size_t i = 0; i < ClusterSizeY - 1; ++i) {
for (size_t j = 0; j < ClusterSizeX - 1; ++j)
sum_2x2_subcluster[i * (ClusterSizeX - 1) + j] =
data[i * ClusterSizeX + j] +
data[i * ClusterSizeX + j + 1] +
data[(i + 1) * ClusterSizeX + j] +
data[(i + 1) * ClusterSizeX + j + 1];
std::array<T, 4> sum_2x2_subcluster{0};
// subcluster top left from center
sum_2x2_subcluster[0] =
data[cluster_center_index] + data[cluster_center_index - 1] +
data[cluster_center_index - ClusterSizeX] +
data[cluster_center_index - 1 - ClusterSizeX];
// subcluster top right from center
if (ClusterSizeX > 2) {
sum_2x2_subcluster[1] =
data[cluster_center_index] +
data[cluster_center_index + 1] +
data[cluster_center_index - ClusterSizeX] +
data[cluster_center_index - ClusterSizeX + 1];
}
// subcluster bottom left from center
if (ClusterSizeY > 2) {
sum_2x2_subcluster[2] =
data[cluster_center_index] +
data[cluster_center_index - 1] +
data[cluster_center_index + ClusterSizeX] +
data[cluster_center_index + ClusterSizeX - 1];
}
// subcluster bottom right from center
if (ClusterSizeX > 2 && ClusterSizeY > 2) {
sum_2x2_subcluster[3] =
data[cluster_center_index] +
data[cluster_center_index + 1] +
data[cluster_center_index + ClusterSizeX] +
data[cluster_center_index + ClusterSizeX + 1];
}
int index = std::max_element(sum_2x2_subcluster.begin(),
sum_2x2_subcluster.end()) -
sum_2x2_subcluster.begin();
return std::make_pair(sum_2x2_subcluster[index], index);
return Sum_index_pair<T, corner>{sum_2x2_subcluster[index],
corner{index}};
}
}
};
/**
* @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
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = int16_t>
typename CoordType = uint16_t>
Cluster<T, 2, 2, CoordType>
reduce_to_2x2(const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &c) {
static_assert(ClusterSizeX >= 2 && ClusterSizeY >= 2,
"Cluster sizes must be at least 2x2 for reduction to 2x2");
// TODO maybe add sanity check and check that center is in max subcluster
Cluster<T, 2, 2, CoordType> result;
Cluster<T, 2, 2, CoordType> result{};
auto [sum, index] = c.max_sum_2x2();
int16_t cluster_center_index =
constexpr int16_t cluster_center_index =
(ClusterSizeX / 2) + (ClusterSizeY / 2) * ClusterSizeX;
int16_t index_bottom_left_max_2x2_subcluster =
(int(index / (ClusterSizeX - 1))) * ClusterSizeX +
index % (ClusterSizeX - 1);
int16_t index_top_left_max_2x2_subcluster = cluster_center_index;
switch (index) {
case corner::cTopLeft:
index_top_left_max_2x2_subcluster -= (ClusterSizeX + 1);
break;
case corner::cTopRight:
index_top_left_max_2x2_subcluster -= ClusterSizeX;
break;
case corner::cBottomLeft:
index_top_left_max_2x2_subcluster -= 1;
break;
case corner::cBottomRight:
// no change needed
break;
}
result.x =
c.x + (index_bottom_left_max_2x2_subcluster - cluster_center_index) %
ClusterSizeX;
result.x = c.x;
result.y = c.y;
result.y =
c.y - (index_bottom_left_max_2x2_subcluster - cluster_center_index) /
ClusterSizeX;
result.data = {
c.data[index_bottom_left_max_2x2_subcluster],
c.data[index_bottom_left_max_2x2_subcluster + 1],
c.data[index_bottom_left_max_2x2_subcluster + ClusterSizeX],
c.data[index_bottom_left_max_2x2_subcluster + ClusterSizeX + 1]};
c.data[index_top_left_max_2x2_subcluster],
c.data[index_top_left_max_2x2_subcluster + 1],
c.data[index_top_left_max_2x2_subcluster + ClusterSizeX],
c.data[index_top_left_max_2x2_subcluster + ClusterSizeX + 1]};
return result;
}
template <typename T>
Cluster<T, 2, 2, int16_t> reduce_to_2x2(const Cluster<T, 3, 3, int16_t> &c) {
Cluster<T, 2, 2, int16_t> result;
Cluster<T, 2, 2, uint16_t> reduce_to_2x2(const Cluster<T, 3, 3, uint16_t> &c) {
Cluster<T, 2, 2, uint16_t> result{};
auto [s, i] = c.max_sum_2x2();
result.x = c.x;
result.y = c.y;
switch (i) {
case 0:
result.x = c.x - 1;
result.y = c.y + 1;
case corner::cTopLeft:
result.data = {c.data[0], c.data[1], c.data[3], c.data[4]};
break;
case 1:
result.x = c.x;
result.y = c.y + 1;
case corner::cTopRight:
result.data = {c.data[1], c.data[2], c.data[4], c.data[5]};
break;
case 2:
result.x = c.x - 1;
result.y = c.y;
case corner::cBottomLeft:
result.data = {c.data[3], c.data[4], c.data[6], c.data[7]};
break;
case 3:
result.x = c.x;
result.y = c.y;
case corner::cBottomRight:
result.data = {c.data[4], c.data[5], c.data[7], c.data[8]};
break;
}
@@ -147,88 +190,41 @@ Cluster<T, 2, 2, int16_t> reduce_to_2x2(const Cluster<T, 3, 3, int16_t> &c) {
return result;
}
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = int16_t>
inline std::pair<T, uint16_t>
max_3x3_sum(const Cluster<T, ClusterSizeX, ClusterSizeY, CoordType> &cluster) {
if constexpr (ClusterSizeX == 3 && ClusterSizeY == 3) {
return std::make_pair(cluster.sum(), 0);
} else {
size_t index = 0;
T max_3x3_subcluster_sum = 0;
for (size_t i = 0; i < ClusterSizeY - 2; ++i) {
for (size_t j = 0; j < ClusterSizeX - 2; ++j) {
T sum = cluster.data[i * ClusterSizeX + j] +
cluster.data[i * ClusterSizeX + j + 1] +
cluster.data[i * ClusterSizeX + j + 2] +
cluster.data[(i + 1) * ClusterSizeX + j] +
cluster.data[(i + 1) * ClusterSizeX + j + 1] +
cluster.data[(i + 1) * ClusterSizeX + j + 2] +
cluster.data[(i + 2) * ClusterSizeX + j] +
cluster.data[(i + 2) * ClusterSizeX + j + 1] +
cluster.data[(i + 2) * ClusterSizeX + j + 2];
if (sum > max_3x3_subcluster_sum) {
max_3x3_subcluster_sum = sum;
index = i * (ClusterSizeX - 2) + j;
}
}
}
return std::make_pair(max_3x3_subcluster_sum, index);
}
}
/**
* @brief Reduce a cluster to a 3x3 cluster by selecting the 3x3 block with the
* highest sum.
* @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;
// TODO maybe add sanity check and check that center is in max subcluster
auto [sum, index] = max_3x3_sum(c);
Cluster<T, 3, 3, CoordType> result{};
int16_t cluster_center_index =
(ClusterSizeX / 2) + (ClusterSizeY / 2) * ClusterSizeX;
int16_t index_center_max_3x3_subcluster =
(int(index / (ClusterSizeX - 2))) * ClusterSizeX + ClusterSizeX +
index % (ClusterSizeX - 2) + 1;
result.x = c.x;
result.y = c.y;
int16_t index_3x3_subcluster_cluster_center =
int((cluster_center_index - 1 - ClusterSizeX) / ClusterSizeX) *
(ClusterSizeX - 2) +
(cluster_center_index - 1 - ClusterSizeX) % ClusterSizeX;
result.data = {c.data[cluster_center_index - ClusterSizeX - 1],
c.data[cluster_center_index - ClusterSizeX],
c.data[cluster_center_index - ClusterSizeX + 1],
c.data[cluster_center_index - 1],
c.data[cluster_center_index],
c.data[cluster_center_index + 1],
c.data[cluster_center_index + ClusterSizeX - 1],
c.data[cluster_center_index + ClusterSizeX],
c.data[cluster_center_index + ClusterSizeX + 1]};
result.x =
c.x + (index % (ClusterSizeX - 2) -
(index_3x3_subcluster_cluster_center % (ClusterSizeX - 2)));
result.y =
c.y - (index / (ClusterSizeX - 2) -
(index_3x3_subcluster_cluster_center / (ClusterSizeX - 2)));
result.data = {c.data[index_center_max_3x3_subcluster - ClusterSizeX - 1],
c.data[index_center_max_3x3_subcluster - ClusterSizeX],
c.data[index_center_max_3x3_subcluster - ClusterSizeX + 1],
c.data[index_center_max_3x3_subcluster - 1],
c.data[index_center_max_3x3_subcluster],
c.data[index_center_max_3x3_subcluster + 1],
c.data[index_center_max_3x3_subcluster + ClusterSizeX - 1],
c.data[index_center_max_3x3_subcluster + ClusterSizeX],
c.data[index_center_max_3x3_subcluster + ClusterSizeX + 1]};
return result;
}
+35 -13
View File
@@ -1,58 +1,80 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <atomic>
#include <thread>
#include <type_traits>
#include <utility>
#include <vector>
#include "aare/Backoff.hpp"
#include "aare/ClusterFinderMT.hpp"
#include "aare/ClusterVector.hpp"
#include "aare/ProducerConsumerQueue.hpp"
#include "aare/defs.hpp"
namespace aare {
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
class ClusterCollector {
ProducerConsumerQueue<ClusterVector<ClusterType>> *m_source;
using SourceQueue = ProducerConsumerQueue<ClusterVector<ClusterType>>;
SourceQueue *m_source;
std::atomic<bool> m_stop_requested{false};
std::atomic<bool> m_stopped{true};
std::chrono::milliseconds m_default_wait{1};
std::thread m_thread;
std::vector<ClusterVector<ClusterType>> m_clusters;
void process() {
m_stopped = false;
m_stopped.store(false, std::memory_order_release);
fmt::print("ClusterCollector started\n");
while (!m_stop_requested || !m_source->isEmpty()) {
Backoff backoff;
while (true) {
if (ClusterVector<ClusterType> *clusters = m_source->frontPtr();
clusters != nullptr) {
backoff.reset();
m_clusters.push_back(std::move(*clusters));
m_source->popFront();
} else {
std::this_thread::sleep_for(m_default_wait);
continue;
}
if (m_stop_requested.load(std::memory_order_acquire))
break;
backoff.pause();
}
fmt::print("ClusterCollector stopped\n");
m_stopped = true;
m_stopped.store(true, std::memory_order_release);
}
public:
ClusterCollector(ClusterFinderMT<ClusterType, uint16_t, double> *source) {
m_source = source->sink();
explicit ClusterCollector(SourceQueue *source) : m_source(source) {
m_thread =
std::thread(&ClusterCollector::process,
this); // only one process does that so why isnt it
// automatically written to m_cluster in collect
// - instead of writing first to m_sink?
}
template <typename Finder,
std::enable_if_t<
std::is_same_v<decltype(std::declval<Finder &>().sink()),
SourceQueue *>,
int> = 0>
explicit ClusterCollector(Finder *source)
: ClusterCollector(source->sink()) {}
void stop() {
m_stop_requested = true;
m_thread.join();
m_stop_requested.store(true, std::memory_order_release);
if (m_thread.joinable())
m_thread.join();
}
std::vector<ClusterVector<ClusterType>> steal_clusters() {
if (!m_stopped) {
if (!m_stopped.load(std::memory_order_acquire)) {
throw std::runtime_error("ClusterCollector is still running");
}
return std::move(m_clusters);
}
};
} // namespace aare
} // namespace aare
+325 -169
View File
@@ -1,47 +1,41 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#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*/
@@ -53,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") {
@@ -108,63 +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 Set the region of interest to use when reading
* clusters. If set only clusters within the ROI will be
* read.
* @brief Estimate the number of clusters in the file from its size.
*
* 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 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);
@@ -179,55 +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 byte position in the file.
* @throws std::runtime_error If the file is closed or its position cannot
* be determined.
*/
int64_t tell() {
if (!m_fp.get()) {
throw std::runtime_error(LOCATION + "File not opened");
}
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();
};
@@ -257,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;
}
@@ -315,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);
}
}
@@ -342,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");
}
@@ -351,66 +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("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(
"There are still photons left in the last frame");
}
int32_t frame_number;
if (fread(&frame_number, sizeof(frame_number), 1, fp) != 1) {
throw std::runtime_error(LOCATION + "Could not read frame number");
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 + "Incomplete frame number");
}
int32_t n_clusters; // Saved as 32bit integer in the cluster file
if (fread(&n_clusters, sizeof(n_clusters), 1, fp) != 1) {
throw std::runtime_error(LOCATION +
"Could not read number of clusters");
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 (!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();
@@ -420,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>
@@ -438,8 +594,8 @@ bool ClusterFile<ClusterType, Enable>::is_selected(ClusterType &cl) {
if (m_noise_map) {
auto sum_1x1 = cl.data[cluster_center_index]; // central pixel
auto sum_2x2 = cl.max_sum_2x2().first; // highest sum of 2x2 subclusters
auto total_sum = cl.sum(); // sum of all pixels
auto sum_2x2 = cl.max_sum_2x2().sum; // highest sum of 2x2 subclusters
auto total_sum = cl.sum(); // sum of all pixels
auto noise =
(*m_noise_map)(cl.y, cl.x); // TODO! check if this is correct
+3 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <atomic>
#include <filesystem>
@@ -10,7 +11,8 @@
namespace aare {
template <typename ClusterType,
typename = std::enable_if_t<is_cluster_v<ClusterType>>>
typename = std::enable_if_t<is_cluster_v<ClusterType>>,
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
class ClusterFileSink {
ProducerConsumerQueue<ClusterVector<ClusterType>> *m_source;
std::atomic<bool> m_stop_requested{false};
+242 -98
View File
@@ -1,7 +1,9 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/ClusterFile.hpp"
#include "aare/ClusterVector.hpp"
#include "aare/Dtype.hpp"
#include "aare/FastPedestal.hpp"
#include "aare/NDArray.hpp"
#include "aare/NDView.hpp"
#include "aare/Pedestal.hpp"
@@ -10,54 +12,111 @@
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.
* @tparam ClusterType Output cluster type; both dimensions must exceed 2.
* @tparam FRAME_TYPE Input pixel type.
* @tparam PEDESTAL_TYPE Type used for pedestal and threshold calculations.
*/
template <typename ClusterType = Cluster<int32_t, 3, 3>,
typename FRAME_TYPE = uint16_t, typename PEDESTAL_TYPE = double>
typename FRAME_TYPE = uint16_t, typename PEDESTAL_TYPE = double,
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
class ClusterFinder {
Shape<2> m_image_size;
const PEDESTAL_TYPE m_nSigma;
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;
static const uint8_t ClusterSizeY = ClusterType::cluster_size_y;
using CT = typename ClusterType::value_type;
NDArray<PEDESTAL_TYPE, 2> m_threshold;
NDArray<PEDESTAL_TYPE, 2> m_pd_corrected_frame;
public:
/**
* @brief Construct a new ClusterFinder object
* @param image_size size of the image
* @param cluster_size size of the cluster (x, y)
* @param nSigma number of sigma above the pedestal to consider a photon
* @param capacity initial capacity of the cluster vector
*
* @brief Construct a cluster finder with an empty pedestal.
* @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_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;
}
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
m_pedestal.push(frame);
}
NDArray<PEDESTAL_TYPE, 2> pedestal() { return m_pedestal.mean(); }
NDArray<PEDESTAL_TYPE, 2> noise() { return m_pedestal.std(); }
void clear_pedestal() { m_pedestal.clear(); }
/**
* @brief Move the clusters from the ClusterVector in the ClusterFinder to a
* new ClusterVector and return it.
* @param realloc_same_capacity if true the new ClusterVector will have the
* same capacity as the old one
* @brief Set the noise multiplier used for threshold calculation and
* recompute the threshold.
* @param nSigma New per-pixel noise multiplier.
*/
void set_nSigma(PEDESTAL_TYPE nSigma) {
m_nSigma = nSigma;
update_threshold();
}
/** @brief Return the current noise multiplier used for threshold
* calculation. */
PEDESTAL_TYPE get_nSigma() const { return m_nSigma; }
/**
* @brief Add a dark frame to the pedestal estimator.
*
* The threshold is initialized automatically when the pedestal first
* becomes ready. Later frames update the ready pedestal.
* @param frame Dark frame matching the configured image shape.
* @throws std::runtime_error if the frame shape does not match.
*/
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
if (!m_pedestal.ready()) {
m_pedestal.add_init_frame(frame);
// Initialize the threshold when the pedestal becomes ready.
if (m_pedestal.ready()) {
update_threshold();
}
} else {
m_pedestal.push_ema(frame);
}
}
/** @brief Return a copy of the per-pixel pedestal mean. */
NDArray<PEDESTAL_TYPE, 2> pedestal() { return m_pedestal.mean(); }
/** @brief Return the per-pixel pedestal standard deviation (noise). */
NDArray<PEDESTAL_TYPE, 2> noise() { return m_pedestal.std(); }
/** @brief Clear the pedestal and mark it as not ready. */
void clear_pedestal() { m_pedestal.clear(); }
/** @brief Recompute the threshold as noise multiplied by nSigma. */
void update_threshold() { m_threshold = m_pedestal.std() * m_nSigma; }
/**
* @brief Move out all accumulated clusters and reset the internal vector.
* @param realloc_same_capacity Preserve the previous capacity when true.
* @return The accumulated clusters and their frame metadata.
*/
ClusterVector<ClusterType>
steal_clusters(bool realloc_same_capacity = false) {
@@ -68,94 +127,179 @@ class ClusterFinder {
m_clusters = ClusterVector<ClusterType>{};
return tmp;
}
private:
/**
* @brief Process a single pixel: scan its cluster window, decide whether it
* is a photon or a pedestal value, and store the cluster if needed.
* @tparam CheckBounds Skip out-of-image neighbours when true; assume the
* complete window is in bounds when false. Skipped cluster values remain 0.
*/
template <bool CheckBounds>
void process_pixel(const NDView<FRAME_TYPE, 2> &frame, const int iy,
const int ix) {
constexpr int dy = ClusterSizeY / 2;
constexpr int dx = ClusterSizeX / 2;
constexpr int has_center_pixel_x = ClusterSizeX % 2;
constexpr int has_center_pixel_y = ClusterSizeY % 2;
PEDESTAL_TYPE max = std::numeric_limits<PEDESTAL_TYPE>::lowest();
PEDESTAL_TYPE total = 0;
const int cols = static_cast<int>(frame.shape(1));
const int rows = static_cast<int>(frame.shape(0));
const auto center =
(static_cast<std::size_t>(iy) * static_cast<std::size_t>(cols)) +
static_cast<std::size_t>(ix);
const auto *corrected = m_pd_corrected_frame.data();
const PEDESTAL_TYPE threshold = m_threshold.data()[center];
const PEDESTAL_TYPE value = corrected[center];
if (value < -threshold)
return; // NEGATIVE_PEDESTAL, nothing to do for this pixel
// TODO! No pedestal update???
for (int ir = -dy; ir < dy + has_center_pixel_y; ir++) {
const int y = iy + ir;
if constexpr (CheckBounds) {
if (y < 0 || y >= rows)
continue;
}
const auto *row = corrected + static_cast<std::size_t>(y) * cols;
for (int ic = -dx; ic < dx + has_center_pixel_x; ic++) {
const int x = ix + ic;
if constexpr (CheckBounds) {
if (x < 0 || x >= cols)
continue;
}
const PEDESTAL_TYPE val = row[x];
total += val;
max = std::max(max, val);
}
}
if ((max > threshold)) {
if (value < max)
return; // Not max go to the next pixel, no pedestal update
} else if (total > c3 * threshold) {
// pass, store the cluster below
} else {
m_pedestal.push_ema_unchecked(center, frame.data()[center]);
return; // It was a pedestal value nothing to store
}
// Store cluster
if (value == max) {
ClusterType cluster{};
cluster.x = ix;
cluster.y = iy;
int i = 0;
for (int ir = -dy; ir < dy + has_center_pixel_y; ir++) {
const int y = iy + ir;
for (int ic = -dx; ic < dx + has_center_pixel_x; ic++, i++) {
const int x = ix + ic;
if constexpr (CheckBounds) {
if (x < 0 || x >= cols || y < 0 || y >= rows)
continue;
}
const PEDESTAL_TYPE corrected_value =
corrected[(static_cast<std::size_t>(y) * cols) + x];
// If the cluster type is an integral type, and the
// pedestal is a floating point type then we need to
// round the value before storing it
if constexpr (std::is_integral_v<CT> &&
std::is_floating_point_v<PEDESTAL_TYPE>) {
cluster.data[i] =
static_cast<CT>(std::lround(corrected_value));
}
// On the other hand if both are floating point or both
// are integral then we can just static cast directly
else {
cluster.data[i] = static_cast<CT>(corrected_value);
}
}
}
// Add the cluster to the output ClusterVector
m_clusters.push_back(cluster);
}
}
public:
/**
* @brief Find clusters in one frame and update eligible pedestal pixels.
* @param frame Input frame matching the configured image shape.
* @param frame_number Metadata assigned to the accumulated clusters.
* @pre frame has the same shape as image_size passed to the constructor.
* @throws std::runtime_error if the pedestal is not ready.
* @note Clusters accumulate until steal_clusters() is called.
*/
void find_clusters(NDView<FRAME_TYPE, 2> frame, uint64_t frame_number = 0) {
// // TODO! deal with even size clusters
// // currently 3,3 -> +/- 1
// // 4,4 -> +/- 2
int dy = ClusterSizeY / 2;
int dx = ClusterSizeX / 2;
int has_center_pixel_x =
ClusterSizeX %
2; // for even sized clusters there is no proper cluster center and
// even amount of pixels around the center
int has_center_pixel_y = ClusterSizeY % 2;
if (!m_pedestal.ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot find clusters");
}
constexpr int dy = ClusterSizeY / 2;
constexpr int dx = ClusterSizeX / 2;
constexpr int has_center_pixel_x = ClusterSizeX % 2;
constexpr int has_center_pixel_y = ClusterSizeY % 2;
// Largest neighbour offset below/right of the current pixel. Pixels
// further than this from an edge have their whole window in bounds.
constexpr int down = dy + has_center_pixel_y - 1;
constexpr int right = dx + has_center_pixel_x - 1;
m_clusters.set_frame_number(frame_number);
for (int iy = 0; iy < frame.shape(0); iy++) {
for (int ix = 0; ix < frame.shape(1); ix++) {
PEDESTAL_TYPE max = std::numeric_limits<FRAME_TYPE>::min();
PEDESTAL_TYPE total = 0;
const int rows = static_cast<int>(frame.shape(0));
const int cols = static_cast<int>(frame.shape(1));
// What can we short circuit here?
PEDESTAL_TYPE rms = m_pedestal.std(iy, ix);
PEDESTAL_TYPE value = (frame(iy, ix) - m_pedestal.mean(iy, ix));
// TODO! See if we can get the same performace using the operator-
// m_pd_corrected_frame = frame - m_pedestal.view();
if (value < -m_nSigma * rms)
continue; // NEGATIVE_PEDESTAL go to next pixel
// TODO! No pedestal update???
// here we should be able to safely assume that the frame and corrected
// frame have the same size
auto n_pixels = frame.size();
auto pd = m_pedestal.view().data();
auto corrected = m_pd_corrected_frame.data();
auto frame_data = frame.data();
for (ssize_t i = 0; i < n_pixels; i++) {
corrected[i] = static_cast<PEDESTAL_TYPE>(frame_data[i]) - pd[i];
}
for (int ir = -dy; ir < dy + has_center_pixel_y; ir++) {
for (int ic = -dx; ic < dx + has_center_pixel_x; ic++) {
if (ix + ic >= 0 && ix + ic < frame.shape(1) &&
iy + ir >= 0 && iy + ir < frame.shape(0)) {
PEDESTAL_TYPE val =
frame(iy + ir, ix + ic) -
m_pedestal.mean(iy + ir, ix + ic);
// Interior pixels can skip the per-neighbour bounds checks; pixels
// within dx/dy of an edge take the bounds-checked path. Iteration order
// (row-major, increasing ix) is preserved so results are identical.
const int ix_begin = dx;
const int ix_end = cols - right; // exclusive
total += val;
max = std::max(max, val);
}
}
}
for (int iy = 0; iy < rows; iy++) {
const bool interior_row = iy >= dy && iy < rows - down;
if ((max > m_nSigma * rms)) {
if (value < max)
continue; // Not max go to the next pixel
// but also no pedestal update
} else if (total > c3 * m_nSigma * rms) {
// pass
} else {
// m_pedestal.push(iy, ix, frame(iy, ix)); // Safe option
m_pedestal.push_fast(
iy, ix,
frame(iy,
ix)); // Assume we have reached n_samples in the
// pedestal, slight performance improvement
continue; // It was a pedestal value nothing to store
}
// Store cluster
if (value == max) {
ClusterType cluster{};
cluster.x = ix;
cluster.y = iy;
// Fill the cluster data since we have a photon to store
// It's worth redoing the look since most of the time we
// don't have a photon
int i = 0;
for (int ir = -dy; ir < dy + has_center_pixel_y; ir++) {
for (int ic = -dx; ic < dx + has_center_pixel_y; ic++) {
if (ix + ic >= 0 && ix + ic < frame.shape(1) &&
iy + ir >= 0 && iy + ir < frame.shape(0)) {
CT tmp =
static_cast<CT>(frame(iy + ir, ix + ic)) -
static_cast<CT>(
m_pedestal.mean(iy + ir, ix + ic));
cluster.data[i] =
tmp; // Watch for out of bounds access
}
i++;
}
}
// Add the cluster to the output ClusterVector
m_clusters.push_back(cluster);
}
if (!interior_row || ix_begin >= ix_end) {
for (int ix = 0; ix < cols; ix++)
process_pixel<true>(frame, iy, ix);
continue;
}
for (int ix = 0; ix < ix_begin; ix++)
process_pixel<true>(frame, iy, ix);
for (int ix = ix_begin; ix < ix_end; ix++)
process_pixel<false>(frame, iy, ix);
for (int ix = ix_end; ix < cols; ix++)
process_pixel<true>(frame, iy, ix);
}
}
};
} // namespace aare
} // namespace aare
+170 -42
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <atomic>
#include <cstdint>
@@ -5,11 +6,13 @@
#include <thread>
#include <vector>
#include "aare/Backoff.hpp"
#include "aare/CircularFifo.hpp"
#include "aare/ClusterFinder.hpp"
#include "aare/NDArray.hpp"
#include "aare/ProducerConsumerQueue.hpp"
#include "aare/logger.hpp"
#include <ctime>
namespace aare {
enum class FrameType {
@@ -17,10 +20,40 @@ enum class FrameType {
PEDESTAL,
};
struct FrameWrapper {
FrameType type;
uint64_t frame_number;
NDArray<uint16_t, 2> data;
/**
* @brief Ticket identifying a frame buffer in a FramePool. Trivially
* copyable, the buffer itself never travels through the queues.
*/
struct FrameRef {
FrameType type{};
uint32_t slot{};
uint64_t frame_number{};
};
/**
* @brief Fixed set of frame buffers allocated once at construction.
*
* Buffers are addressed by slot index and are never moved or reallocated, so
* the queues only need to pass a FrameRef around. This keeps the per frame
* allocation out of the hot path entirely.
*/
class FramePool {
std::vector<NDArray<uint16_t, 2>> m_buffers;
public:
FramePool(size_t depth, Shape<2> shape) {
m_buffers.reserve(depth); // no reallocation, slots stay stable
for (size_t i = 0; i < depth; ++i) {
m_buffers.emplace_back(shape);
}
}
NDArray<uint16_t, 2> &operator[](uint32_t slot) { return m_buffers[slot]; }
const NDArray<uint16_t, 2> &operator[](uint32_t slot) const {
return m_buffers[slot];
}
size_t size() const { return m_buffers.size(); }
};
/**
@@ -32,7 +65,8 @@ struct FrameWrapper {
* @tparam CT type of the cluster data
*/
template <typename ClusterType = Cluster<int32_t, 3, 3>,
typename FRAME_TYPE = uint16_t, typename PEDESTAL_TYPE = double>
typename FRAME_TYPE = uint16_t, typename PEDESTAL_TYPE = double,
typename = std::enable_if_t<no_2x2_cluster<ClusterType>::value>>
class ClusterFinderMT {
protected:
@@ -40,17 +74,18 @@ class ClusterFinderMT {
size_t m_current_thread{0};
size_t m_n_threads{0};
using Finder = ClusterFinder<ClusterType, FRAME_TYPE, PEDESTAL_TYPE>;
using InputQueue = ProducerConsumerQueue<FrameWrapper>;
using InputQueue = CircularFifo<FrameRef>;
using OutputQueue = ProducerConsumerQueue<ClusterVector<ClusterType>>;
std::vector<std::unique_ptr<InputQueue>> m_input_queues;
std::vector<std::unique_ptr<OutputQueue>> m_output_queues;
std::vector<std::unique_ptr<FramePool>> m_frame_pools;
OutputQueue m_sink{1000}; // All clusters go into this queue
std::vector<std::unique_ptr<Finder>> m_cluster_finders;
std::vector<std::thread> m_threads;
std::thread m_collect_thread;
std::chrono::milliseconds m_default_wait{1};
std::chrono::microseconds m_default_wait{50};
private:
std::atomic<bool> m_stop_requested{false};
@@ -63,50 +98,71 @@ class ClusterFinderMT {
void process(int thread_id) {
auto cf = m_cluster_finders[thread_id].get();
auto q = m_input_queues[thread_id].get();
bool realloc_same_capacity = true;
auto *pool = m_frame_pools[thread_id].get();
Backoff backoff;
while (!m_stop_requested || !q->isEmpty()) {
if (FrameWrapper *frame = q->frontPtr(); frame != nullptr) {
if (FrameRef *ref = q->frontPtr(); ref != nullptr) {
backoff.reset();
auto view = (*pool)[ref->slot].view();
switch (frame->type) {
case FrameType::DATA:
cf->find_clusters(frame->data.view(), frame->frame_number);
m_output_queues[thread_id]->write(
cf->steal_clusters(realloc_same_capacity));
switch (ref->type) {
case FrameType::DATA: {
cf->find_clusters(view, ref->frame_number);
// Steal before the write so a failed write cannot drop the
// clusters by re-stealing an empty vector on retry.
auto clusters = cf->steal_clusters(true);
while (!m_output_queues[thread_id]->write(
std::move(clusters))) {
backoff.pause();
}
break;
}
case FrameType::PEDESTAL:
m_cluster_finders[thread_id]->push_pedestal_frame(
frame->data.view());
m_cluster_finders[thread_id]->push_pedestal_frame(view);
break;
}
// frame is processed now discard it
m_input_queues[thread_id]->popFront();
// frame is processed, hand the buffer back to the free list
q->recycle_front();
} else {
std::this_thread::sleep_for(m_default_wait);
backoff.pause();
}
}
}
bool output_queues_are_empty() const {
for (auto &q : m_output_queues) {
if (!q->isEmpty()) {
return false;
}
}
return true;
}
/**
* @brief Collect all the clusters from the output queues and write them to
* the sink
*/
void collect() {
bool empty = true;
while (!m_stop_requested || !empty || !m_processing_threads_stopped) {
empty = true;
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 (!queue->isEmpty()) {
while (!m_sink.write(std::move(*queue->frontPtr()))) {
std::this_thread::sleep_for(m_default_wait);
if (auto *front = queue->frontPtr(); front != nullptr) {
while (!m_sink.write(std::move(*front))) {
backoff.pause();
}
queue->popFront();
empty = false;
moved_any = true;
}
}
if (moved_any) {
backoff.reset();
} else {
backoff.pause();
}
}
}
@@ -119,25 +175,40 @@ class ClusterFinderMT {
* @param capacity initial capacity of the cluster vector. Should match
* expected number of clusters in a frame per frame.
* @param n_threads number of threads to use
* @param queue_depth number of frame buffers per thread. These are
* 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 capacity = 2000, size_t n_threads = 3,
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
<< ", n_threads: " << n_threads;
<< ", min_pedestal_samples: " << min_pedestal_samples
<< ", n_threads: " << n_threads
<< ", queue_depth: " << queue_depth;
for (size_t i = 0; i < n_threads; i++) {
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_input_queues.emplace_back(std::make_unique<InputQueue>(200));
m_frame_pools.emplace_back(
std::make_unique<FramePool>(queue_depth, image_size));
m_input_queues.emplace_back(std::make_unique<InputQueue>(
static_cast<uint32_t>(queue_depth), [](size_t slot) {
return FrameRef{FrameType::DATA,
static_cast<uint32_t>(slot), 0};
}));
m_output_queues.emplace_back(std::make_unique<OutputQueue>(200));
}
// TODO! Should we start automatically?
@@ -207,13 +278,22 @@ class ClusterFinderMT {
* expected to be dark. No photon finding is done. Just pedestal update.
*/
void push_pedestal_frame(NDView<FRAME_TYPE, 2> frame) {
FrameWrapper fw{FrameType::PEDESTAL, 0,
NDArray(frame)}; // TODO! copies the data!
for (size_t i = 0; i < m_n_threads; ++i) {
auto *q = m_input_queues[i].get();
Backoff backoff;
for (auto &queue : m_input_queues) {
while (!queue->write(fw)) {
std::this_thread::sleep_for(m_default_wait);
FrameRef ref;
while (!q->try_pop_free(ref)) {
backoff.pause();
}
ref.type = FrameType::PEDESTAL;
ref.frame_number = 0;
(*m_frame_pools[i])[ref.slot].copy_from(frame);
// Cannot fail, the free list is what limits how many frames are
// in flight so there is always room in the filled list.
q->try_push_value(ref);
}
}
@@ -223,11 +303,29 @@ class ClusterFinderMT {
* @note Spin locks with a default wait if the queue is full.
*/
void find_clusters(NDView<FRAME_TYPE, 2> frame, uint64_t frame_number = 0) {
FrameWrapper fw{FrameType::DATA, frame_number,
NDArray(frame)}; // TODO! copies the data!
while (!m_input_queues[m_current_thread % m_n_threads]->write(fw)) {
std::this_thread::sleep_for(m_default_wait);
const size_t tid = m_current_thread % m_n_threads;
auto *q = m_input_queues[tid].get();
Backoff backoff;
FrameRef ref;
while (!q->try_pop_free(ref)) {
backoff.pause();
}
ref.type = FrameType::DATA;
ref.frame_number = frame_number;
// DualTimer dt;
(*m_frame_pools[tid])[ref.slot].copy_from(frame);
// auto [wall_ns, cpu_ns] = dt.elapsed();
// std::cerr << "ClusterFinderMT: find_clusters: copied frame "
// << frame_number << " took " << wall_ns/1000.0 << " wall_us
// and "
// << cpu_ns/1000.0 << " cpu_us" << std::endl;
// Cannot fail, the free list is what limits how many frames are in
// flight so there is always room in the filled list.
q->try_push_value(ref);
m_current_thread++;
}
@@ -240,6 +338,19 @@ class ClusterFinderMT {
}
}
/**
* @brief Recompute the threshold (nSigma * pedestal std) on all cluster
* finders. Requires the processing threads to be stopped.
*/
void update_threshold() {
if (!m_processing_threads_stopped) {
throw std::runtime_error("ClusterFinderMT is still running");
}
for (auto &cf : m_cluster_finders) {
cf->update_threshold();
}
}
/**
* @brief Return the pedestal currently used by the cluster finder
* @param thread_index index of the thread
@@ -279,6 +390,23 @@ class ClusterFinderMT {
// auto rc = m_input_queue.write(std::move(frame));
// fmt::print("pushed frame {}\n", rc);
// }
/**
* @brief Set the nSigma value for all the cluster finders.
* @param nSigma number of sigma above the pedestal to consider a photon
* during cluster finding.
*/
void set_nSigma(const PEDESTAL_TYPE nSigma) {
// Wait for all queues to be empty before changing the sigma
for (auto &q : m_input_queues) {
while (!q->isEmpty()) {
std::this_thread::sleep_for(m_default_wait);
}
}
for (auto &cf : m_cluster_finders) {
cf->set_nSigma(nSigma);
}
}
};
} // namespace aare
+99 -47
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Cluster.hpp" //TODO maybe store in seperate file !!!
#include <algorithm>
@@ -19,16 +20,21 @@ 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 int16_t)
* (normally uint16_t)
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType>
@@ -43,35 +49,48 @@ 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);
}
// Move constructor
ClusterVector(ClusterVector &&other) noexcept
: m_data(other.m_data), m_frame_number(other.m_frame_number) {
other.m_data.clear();
}
ClusterVector(ClusterVector &&other) noexcept = default;
ClusterVector &operator=(ClusterVector &&other) noexcept = default;
// 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;
/**
* @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");
}
return *this;
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]);
}
}
return result;
}
/**
* @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());
@@ -84,17 +103,17 @@ class ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>> {
}
/**
* @brief Sum the pixels in the 2x2 subcluster with the biggest pixel sum in
* each cluster
* @return std::vector<T> vector of sums 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<T> sum_2x2() {
std::vector<T> sums_2x2(m_data.size());
std::vector<Sum_index_pair<T, corner>> sum_2x2() {
std::vector<Sum_index_pair<T, corner>> sums_2x2(m_data.size());
std::transform(m_data.begin(), m_data.end(), sums_2x2.begin(),
[](const ClusterType &cluster) {
return cluster.max_sum_2x2().first;
});
std::transform(
m_data.begin(), m_data.end(), sums_2x2.begin(),
[](const ClusterType &cluster) { return cluster.max_sum_2x2(); });
return sums_2x2;
}
@@ -107,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());
@@ -127,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; }
/**
@@ -143,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 *
@@ -154,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]; }
@@ -167,23 +207,31 @@ 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)
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = uint16_t>
typename CoordType>
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));
}
@@ -191,21 +239,25 @@ ClusterVector<Cluster<T, 2, 2, CoordType>> reduce_to_2x2(
}
/**
* @brief Reduce a cluster to a 3x3 cluster by selecting the 3x3 block with the
* highest sum.
* @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 = uint16_t>
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
+2
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/FileInterface.hpp"
@@ -27,6 +28,7 @@ class CtbRawFile {
size_t image_size_in_bytes() const;
size_t frames_in_file() const;
size_t total_frames() const;
RawMasterFile master() const;
+72 -12
View File
@@ -1,6 +1,9 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/RawMasterFile.hpp" //ROI refactor away
#include "aare/defs.hpp"
#include "aare/ROI.hpp"
#include "aare/ROIGeometry.hpp"
#include <iostream>
namespace aare {
struct ModuleConfig {
@@ -17,16 +20,69 @@ struct ModuleConfig {
};
/**
* @brief Class to hold the geometry of a module. Where pixel 0 is located and
* the size of the module
* @brief Class to hold the geometry of a module. Where pixel 0 is located
* relative to full Detector/ROI and the size of the module e.g. size of ROI
* occupied by the module
*/
struct ModuleGeometry {
/// @brief start x coordinate of the module in the full detector/ROI
int origin_x{};
/// @brief start y coordinate of the module in the full detector/ROI
int origin_y{};
/// @brief height of the module in pixels
int height{};
/// @brief width of the module in pixels
int width{};
/// @brief module index of the module in the detector
int row_index{};
/// @brief module index of the module in the detector
int col_index{};
/**
* @brief checks if module is in the region of interest
*/
bool module_in_roi(const ROI &roi) {
// module is to the left of the roi
bool to_the_left = origin_x + width - 1 < roi.xmin;
bool to_the_right = origin_x >= roi.xmax;
bool above = origin_y + height - 1 < roi.ymin;
bool below = origin_y >= roi.ymax;
return !(to_the_left || to_the_right || below || above);
}
/**
* @brief Update the module geometry given a region of interest
*/
void update_geometry_with_roi(const ROI &roi) {
if (!(module_in_roi(roi))) {
return; // do nothing
}
int new_width = std::min(origin_x + width, static_cast<int>(roi.xmax)) -
std::max(origin_x, static_cast<int>(roi.xmin));
// ROI starts inside module
if (roi.xmin >= origin_x && roi.xmin < origin_x + width) {
origin_x = 0;
} else {
origin_x -= roi.xmin;
}
int new_height =
std::min(origin_y + height, static_cast<int>(roi.ymax)) -
std::max(origin_y, static_cast<int>(roi.ymin));
if (roi.ymin >= origin_y && roi.ymin < origin_y + height) {
origin_y = 0;
} else {
origin_y -= roi.ymin;
}
height = new_height;
width = new_width;
}
};
/**
@@ -40,6 +96,8 @@ class DetectorGeometry {
const xy udp_interfaces_per_module = xy{1, 1},
const bool quad = false);
DetectorGeometry() = default;
~DetectorGeometry() = default;
/**
@@ -48,34 +106,36 @@ class DetectorGeometry {
* @param roi
* @return DetectorGeometry
*/
void update_geometry_with_roi(ROI roi);
size_t n_modules() const;
size_t n_modules_in_roi() const;
size_t pixels_x() const;
size_t pixels_y() const;
size_t modules_x() const;
size_t modules_y() const;
const std::vector<ssize_t> &get_modules_in_roi() const;
ssize_t get_modules_in_roi(const size_t index) 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;
ModuleGeometry &get_module_geometries(const size_t index);
private:
size_t m_modules_x{};
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};
std::vector<ModuleGeometry> module_geometries{};
std::vector<ssize_t> modules_in_roi{};
// TODO: maybe remove - should be a member in ROIGeometry - in particular
// only works as no overlap between ROIs allowed? maybe just have another
// additional vector of ModuleGeometry for each ROIGeometry - some
// duplication but nicer design?
std::vector<ModuleGeometry> module_geometries;
};
} // namespace aare
+1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <cstdint>
#include <map>
+386
View File
@@ -0,0 +1,386 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/File.hpp"
#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 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. Variance is a private double-precision intermediate.
* @tparam PEDESTAL_TYPE Type returned for the mean and standard deviation.
*/
template <typename PEDESTAL_TYPE> class FastPedestal {
// Did we accumulate enough samples and updated the mean?
bool m_ready = false;
uint32_t m_rows;
uint32_t m_cols;
uint32_t m_samples;
double m_inv_samples; // precompute 1/m_samples for faster division
uint32_t m_cur_samples = 0; // number of samples accumulated so far
// For cache locality we want to keep sum and sum2 close. Should
// improve performance for random access.
struct Entry {
double sum;
double sum2;
};
NDArray<Entry, 2> m_sum;
// 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
// But also makes sense when subtracting the pedestal from the frame
NDArray<PEDESTAL_TYPE, 2> m_mean;
// Helper function to convert row and column indices to a flat index
// used to provide both row column and flat index access to the pedestal
size_t rc_to_index(uint32_t row, uint32_t col) const {
return (static_cast<std::size_t>(row) * m_cols) + col;
}
public:
/**
* @brief Construct an empty pedestal that becomes ready after n_samples
* initialization frames.
* @param rows Number of image rows.
* @param cols Number of image columns.
* @param n_samples Number of initialization frames and reciprocal of the
* weight assigned to each subsequent value.
* @throws std::runtime_error if rows, cols, or n_samples is zero.
*/
FastPedestal(uint32_t rows, uint32_t cols, uint32_t n_samples = 1000)
: m_rows(rows), m_cols(cols), m_samples(n_samples),
m_inv_samples(1.0 / n_samples), m_sum({rows, cols}, Entry{0, 0}),
m_mean({rows, cols}, PEDESTAL_TYPE(0)) {
if (!(rows > 0 && cols > 0 && n_samples > 0)) {
throw std::runtime_error(
fmt::format("Invalid parameters for FastPedestal: rows={}, "
"cols={}, n_samples={} need to be positive",
rows, cols, n_samples));
}
}
~FastPedestal() = default;
/**
* @brief Return a non-owning view of the cached mean.
* @throws std::runtime_error if ready() is false.
* @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 PEDESTAL_TYPE, 2> view() const {
if (!ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot return view");
}
return m_mean.view();
}
/**
* @brief Return a copy of the cached mean.
* @throws std::runtime_error if ready() is false.
*/
NDArray<PEDESTAL_TYPE, 2> mean() const {
if (!ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot return mean");
}
return m_mean;
}
/**
* @brief Return the cached mean at (row, col).
* @throws std::runtime_error if ready() is false or either index is out of
* range.
*/
PEDESTAL_TYPE mean(uint32_t row, uint32_t col) const {
if (!ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot return mean");
}
if (row >= m_rows || col >= m_cols) {
throw std::runtime_error(
fmt::format("Invalid indices for FastPedestal mean: row={}, "
"col={} must be in [0, {}), [0, {})",
row, col, m_rows, m_cols));
}
return m_mean(row, col);
}
/**
* @brief Return the cached mean at a flat row-major index.
* @pre ready() is true, the cache is current, and index is valid; the index
* is not checked.
*/
PEDESTAL_TYPE mean_unchecked(ssize_t index) const { return m_mean[index]; }
/**
* @brief Calculate and return the population standard deviation of every
* pixel.
* @throws std::runtime_error if ready() is false.
*/
NDArray<PEDESTAL_TYPE, 2> std() const {
if (!ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot return std");
}
NDArray<PEDESTAL_TYPE, 2> res({m_rows, m_cols});
for (ssize_t i = 0; i < m_sum.size(); ++i) {
res[i] = std_unchecked(i);
}
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
* range.
*/
PEDESTAL_TYPE std(const uint32_t row, const uint32_t col) const {
if (!ready()) {
throw std::runtime_error(
"Pedestal is not ready, cannot return std");
}
if (row >= m_rows || col >= m_cols) {
throw std::runtime_error(
fmt::format("Invalid indices for FastPedestal std: row={}, "
"col={} must be in [0, {}), [0, {})",
row, col, m_rows, m_cols));
}
return std_unchecked(rc_to_index(row, col));
}
/**
* @brief Calculate the population standard deviation at a flat row-major
* index.
* @pre ready() is true and index is valid; the index is not checked.
*/
PEDESTAL_TYPE std_unchecked(ssize_t index) const {
return std::sqrt(variance_unchecked(index));
}
/**
* @brief Return whether initialization is complete (cur_samples() equals
* n_samples()).
*/
bool ready() const { return m_ready; }
/**
* @brief Return the stored number of accumulated initialization frames.
* @note The value is in [0, n_samples] and does not change during
* steady-state pushes.
*/
uint32_t cur_samples() const { return m_cur_samples; }
/**
* @brief Zero the moments and cached mean, and mark the pedestal not ready.
*/
void clear() {
m_sum = Entry{0., 0.};
m_mean = PEDESTAL_TYPE(0.);
m_cur_samples = 0;
m_ready = false;
}
/**
* @brief Update every pixel using the steady-state exponential estimator,
* giving the new value weight 1 / n_samples.
* @param frame Frame whose shape must exactly match the pedestal.
* @throws std::runtime_error if the shape differs or ready() is false.
*/
template <typename T> void push_ema(NDView<T, 2> frame) {
if (frame.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
throw std::runtime_error(
"Frame shape does not match pedestal shape");
}
if (!ready()) {
throw std::runtime_error("Pedestal is not ready, cannot push");
}
const auto size = static_cast<std::size_t>(m_rows) * m_cols;
const auto *data = frame.data();
for (std::size_t index = 0; index < size; ++index) {
push_ema_unchecked(index, data[index]);
}
}
/**
* @brief Update every pixel from a Frame using the steady-state estimator.
* @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 or ready() is false.
*/
template <typename T> void push_ema(Frame &frame) {
push_ema<T>(frame.view<T>());
}
/**
* @brief Update the exponential moving average with smoothing factor
* 1/n_samples
* @param row Pixel row.
* @param col Pixel column.
* @param val New pixel value.
* @pre row and col are valid; indices are not checked.
* @throws std::runtime_error if ready() is false.
*/
template <typename T>
void push_ema(const uint32_t row, const uint32_t col, const T val) {
if (!ready()) {
throw std::runtime_error("Pedestal is not ready, cannot push");
}
push_ema_unchecked(rc_to_index(row, col), val);
}
/**
* @brief Update one pixel and its cached mean without runtime checks in
* release builds.
* @param index Flat row-major pixel index.
* @param value New pixel value, with weight 1 / n_samples.
* @pre ready() is true and index is a valid flat row-major index. These
* preconditions are asserted only in debug builds.
*/
template <typename T>
void push_ema_unchecked(const std::size_t index, const T value) noexcept {
assert(m_ready);
assert(index < static_cast<std::size_t>(m_sum.size()));
const auto val = static_cast<double>(value);
auto &entry = m_sum[index];
entry.sum += val - entry.sum * m_inv_samples;
entry.sum2 += val * val - entry.sum2 * m_inv_samples;
m_mean[index] = static_cast<PEDESTAL_TYPE>(entry.sum * m_inv_samples);
}
/**
* @brief Accumulate one initialization frame.
* @param frame Frame whose shape must exactly match the pedestal.
* @throws std::runtime_error if the shape differs or n_samples frames have
* already been accumulated.
* @note The statistics can be accessed and ready() becomes true only after
* the n_samples frames have been added.
*/
template <typename T> void add_init_frame(NDView<T, 2> frame) {
if (frame.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
throw std::runtime_error(
"Frame shape does not match pedestal shape");
}
// if the pedestal is already initialized we cannot add more frames
if (ready()) {
throw std::runtime_error("Pedestal initialization is already done");
}
for (ssize_t i = 0; i < m_sum.size(); ++i) {
const auto val = static_cast<double>(frame[i]);
auto &entry = m_sum[i];
entry.sum += val;
entry.sum2 += val * val;
}
m_cur_samples += 1;
if (m_cur_samples == m_samples) {
update_mean();
m_ready = true;
}
}
/**
* @brief Initialize from n_samples frames after skip_first, then apply all
* remaining file frames as steady-state updates.
* @tparam T Pixel representation stored in the file; this is not checked.
* @param filename Input image file. Its dimensions define the pedestal
* shape.
* @param n_samples Number of initialization frames.
* @param skip_first Number of leading frames to ignore.
* @throws std::runtime_error if fewer than n_samples frames remain after
* skip_first, or if any constructor argument is invalid.
*/
template <typename T>
static FastPedestal from_file(const std::filesystem::path &filename,
uint32_t n_samples = 1000,
uint32_t skip_first = 0) {
File f(filename);
const auto total_frames = f.total_frames();
const auto first_frame = static_cast<size_t>(skip_first);
const auto initialization_frames = static_cast<size_t>(n_samples);
if (first_frame > total_frames ||
initialization_frames > total_frames - first_frame) {
throw std::runtime_error(
"File has less frames than the number of samples needed to "
"initialize the pedestal");
}
if (skip_first > 0) {
f.seek(static_cast<size_t>(skip_first));
}
const auto rows = static_cast<uint32_t>(f.rows());
const auto cols = static_cast<uint32_t>(f.cols());
FastPedestal pedestal(rows, cols, n_samples);
NDArray<T, 2> frame({rows, cols});
auto frame_index = first_frame;
const auto initialization_end = first_frame + initialization_frames;
while (frame_index < initialization_end) {
f.read_into(frame.buffer());
pedestal.template add_init_frame<T>(frame.view());
frame_index++;
}
// read the rest of the file
while (frame_index < total_frames) {
f.read_into(frame.buffer());
pedestal.template push_ema<T>(frame.view());
frame_index++;
}
return pedestal;
}
/** @brief Return the number of image rows. */
uint32_t rows() const { return m_rows; }
/** @brief Return the number of image columns. */
uint32_t cols() const { return m_cols; }
/**
* @brief Return the initialization frame count and steady-state
* update-weight denominator.
*/
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.
*/
void update_mean() {
for (ssize_t i = 0; i < m_sum.size(); i++) {
auto &entry = m_sum[i];
m_mean[i] = static_cast<PEDESTAL_TYPE>(entry.sum * m_inv_samples);
}
}
};
} // namespace aare
+3 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/FileInterface.hpp"
#include <memory>
@@ -63,8 +64,9 @@ class File {
size_t total_frames() const;
size_t rows() const;
size_t cols() const;
Dtype dtype() const;
DetectorType detector_type() const;
};
} // namespace aare
} // namespace aare
+20 -13
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Dtype.hpp"
#include "aare/Frame.hpp"
@@ -33,15 +34,16 @@ struct FileConfig {
DetectorType detector_type{DetectorType::Unknown};
int max_frames_per_file{};
size_t total_frames{};
std::string to_string() const {
return "{ dtype: " + dtype.to_string() +
", rows: " + std::to_string(rows) +
", cols: " + std::to_string(cols) +
", geometry: " + geometry.to_string() +
", detector_type: " + ToString(detector_type) +
", max_frames_per_file: " + std::to_string(max_frames_per_file) +
", total_frames: " + std::to_string(total_frames) + " }";
}
// std::string to_string() const {
// return "{ dtype: " + dtype.to_string() +
// ", rows: " + std::to_string(rows) +
// ", cols: " + std::to_string(cols) +
// ", geometry: " + geometry.to_string() +
// ", detector_type: " + ToString(detector_type) +
// ", max_frames_per_file: " +
// std::to_string(max_frames_per_file) +
// ", total_frames: " + std::to_string(total_frames) + " }";
// }
};
/**
@@ -143,10 +145,15 @@ class FileInterface {
*/
virtual size_t bitdepth() const = 0;
virtual DetectorType detector_type() const = 0;
/**
* @brief get the data type of the pixels
* @return pixel data type
*/
virtual Dtype dtype() const {
return Dtype::from_bitdepth(static_cast<uint8_t>(bitdepth()));
}
// function to query the data type of the file
/*virtual DataType dtype = 0; */
virtual DetectorType detector_type() const = 0;
virtual ~FileInterface() = default;
@@ -166,4 +173,4 @@ class FileInterface {
// size_t current_frame{};
};
} // namespace aare
} // namespace aare
+3 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <cstdio>
#include <filesystem>
@@ -17,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) {
@@ -27,4 +29,4 @@ class FilePtr {
~FilePtr();
};
} // namespace aare
} // namespace aare
+51 -106
View File
@@ -1,120 +1,65 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <cmath>
#include <fmt/core.h>
#include <vector>
#include "aare/FitModel.hpp"
#include "aare/NDArray.hpp"
namespace aare {
namespace func {
double gaus(const double x, const double *par);
NDArray<double, 1> gaus(NDView<double, 1> x, NDView<double, 1> par);
double pol1(const double x, const double *par);
NDArray<double, 1> pol1(NDView<double, 1> x, NDView<double, 1> par);
double scurve(const double x, const double *par);
NDArray<double, 1> scurve(NDView<double, 1> x, NDView<double, 1> par);
double scurve2(const double x, const double *par);
NDArray<double, 1> scurve2(NDView<double, 1> x, NDView<double, 1> par);
} // namespace func
// ---------------------------------------------------------------------------
// Minuit2-based pixel fitting.
// Template bodies and explicit instantiations live in src/Fit.cpp.
// ---------------------------------------------------------------------------
/**
* @brief Estimate the initial parameters for a Gaussian fit
* @brief Fit a single pixel's data using Minuit2.
*
* User-precedence rules:
* - Fixed parameters: untouched (value and fixed flag preserved from model).
* - User-set start: value preserved, step size auto-filled.
* - Neither: both value and step size auto-filled from data.
*
* @tparam Model Model struct (Gaussian, RisingScurve, …).
*
* @param model The FitModel configuration (read-only).
* @param x Scan points.
* @param y Measured values for this pixel.
* @param y_err Per-point uncertainties (empty view -> unweighted fit).
*
* @return NDArray<double,1> of size:
* - compute_errors: [p0..pN, err0..errN, chi2] -> 2*npar + 1
* - otherwise: [p0..pN, chi2] -> npar + 1
*/
std::array<double, 3> gaus_init_par(const NDView<double, 1> x,
const NDView<double, 1> y);
template <typename Model>
NDArray<double, 1> fit_pixel(const FitModel<Model> &model, NDView<double, 1> x,
NDView<double, 1> y, NDView<double, 1> y_err);
std::array<double, 2> pol1_init_par(const NDView<double, 1> x,
const NDView<double, 1> y);
std::array<double, 6> scurve_init_par(const NDView<double, 1> x,
const NDView<double, 1> y);
std::array<double, 6> scurve2_init_par(const NDView<double, 1> x,
const NDView<double, 1> y);
static constexpr int DEFAULT_NUM_THREADS = 4;
// Overload: uncertainties not provided
template <typename Model>
NDArray<double, 1> fit_pixel(const FitModel<Model> &model, NDView<double, 1> x,
NDView<double, 1> y);
/**
* @brief Fit a 1D Gaussian to data.
* @param data data to fit
* @param x x values
* @brief Fit all pixels in a 3D data cube (rows x cols x n_scan).
*
* @tparam Model Model struct.
*
* @param model Fit configuration shared by all pixels.
* @param x Scan points, shape `(n_scan)`.
* @param y Measured values, shape `(rows, cols, n_scan)`.
* @param y_err Uncertainties, same shape as y, or empty for unweighted
* fits.
* @param par_out Output parameters, shape `(rows, cols, npar)`.
* @param err_out Output parameter errors, shape `(rows, cols, npar)`, if
* used.
* @param chi2_out Output chi-squared / objective values, shape `(rows,
* cols)`.
* @param n_threads Number of threads used to split rows.
*/
NDArray<double, 1> fit_gaus(NDView<double, 1> x, NDView<double, 1> y);
template <typename Model>
void fit_3d(const FitModel<Model> &model, NDView<double, 1> x,
NDView<double, 3> y, NDView<double, 3> y_err,
NDView<double, 3> par_out, NDView<double, 3> err_out,
NDView<double, 2> chi2_out, int n_threads);
/**
* @brief Fit a 1D Gaussian to each pixel. Data layout [row, col, values]
* @param x x values
* @param y y values, layout [row, col, values]
* @param n_threads number of threads to use
*/
NDArray<double, 3> fit_gaus(NDView<double, 1> x, NDView<double, 3> y,
int n_threads = DEFAULT_NUM_THREADS);
/**
* @brief Fit a 1D Gaussian with error estimates
* @param x x values
* @param y y values, layout [row, col, values]
* @param y_err error in y, layout [row, col, values]
* @param par_out output parameters
* @param par_err_out output error parameters
*/
void fit_gaus(NDView<double, 1> x, NDView<double, 1> y, NDView<double, 1> y_err,
NDView<double, 1> par_out, NDView<double, 1> par_err_out,
double &chi2);
/**
* @brief Fit a 1D Gaussian to each pixel with error estimates. Data layout
* [row, col, values]
* @param x x values
* @param y y values, layout [row, col, values]
* @param y_err error in y, layout [row, col, values]
* @param par_out output parameters, layout [row, col, values]
* @param par_err_out output parameter errors, layout [row, col, values]
* @param n_threads number of threads to use
*/
void fit_gaus(NDView<double, 1> x, NDView<double, 3> y, NDView<double, 3> y_err,
NDView<double, 3> par_out, NDView<double, 3> par_err_out,
NDView<double, 2> chi2_out, int n_threads = DEFAULT_NUM_THREADS);
NDArray<double, 1> fit_pol1(NDView<double, 1> x, NDView<double, 1> y);
NDArray<double, 3> fit_pol1(NDView<double, 1> x, NDView<double, 3> y,
int n_threads = DEFAULT_NUM_THREADS);
void fit_pol1(NDView<double, 1> x, NDView<double, 1> y, NDView<double, 1> y_err,
NDView<double, 1> par_out, NDView<double, 1> par_err_out,
double &chi2);
// TODO! not sure we need to offer the different version in C++
void fit_pol1(NDView<double, 1> x, NDView<double, 3> y, NDView<double, 3> y_err,
NDView<double, 3> par_out, NDView<double, 3> par_err_out,
NDView<double, 2> chi2_out, int n_threads = DEFAULT_NUM_THREADS);
NDArray<double, 1> fit_scurve(NDView<double, 1> x, NDView<double, 1> y);
NDArray<double, 3> fit_scurve(NDView<double, 1> x, NDView<double, 3> y,
int n_threads);
void fit_scurve(NDView<double, 1> x, NDView<double, 1> y,
NDView<double, 1> y_err, NDView<double, 1> par_out,
NDView<double, 1> par_err_out, double &chi2);
void fit_scurve(NDView<double, 1> x, NDView<double, 3> y,
NDView<double, 3> y_err, NDView<double, 3> par_out,
NDView<double, 3> par_err_out, NDView<double, 2> chi2_out,
int n_threads);
NDArray<double, 1> fit_scurve2(NDView<double, 1> x, NDView<double, 1> y);
NDArray<double, 3> fit_scurve2(NDView<double, 1> x, NDView<double, 3> y,
int n_threads);
void fit_scurve2(NDView<double, 1> x, NDView<double, 1> y,
NDView<double, 1> y_err, NDView<double, 1> par_out,
NDView<double, 1> par_err_out, double &chi2);
void fit_scurve2(NDView<double, 1> x, NDView<double, 3> y,
NDView<double, 3> y_err, NDView<double, 3> par_out,
NDView<double, 3> par_err_out, NDView<double, 2> chi2_out,
int n_threads);
} // namespace aare
} // namespace aare
+102
View File
@@ -0,0 +1,102 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Models.hpp"
#include <array>
#include <memory>
#include <stdexcept>
#include <string>
#include <vector>
namespace aare {
template <typename Model> class FitModel {
// Forward declaration only — full definition lives in src/FitModelImpl.hpp
// and is never installed. Downstream code cannot dereference this pointer.
struct FitModelImpl; // stores Minuit2 user-set parameters
std::unique_ptr<FitModelImpl> impl_;
unsigned int max_calls_;
double tolerance_;
bool compute_errors_;
std::array<bool, Model::npar> user_fixed_{};
std::array<bool, Model::npar> user_start_{};
/** @brief Safely resolve a parameter name to its index. */
unsigned int checked_index(const std::string &name) const;
public:
static constexpr std::size_t npar = Model::npar;
/**
* @brief Construct a fit model with sensible defaults.
*
* @param strategy Minuit2 strategy level (0 = fast/gradient, 1 =
* default).
* @param max_calls Maximum FCN calls per pixel minimisation.
* @param tolerance Minuit2 EDM tolerance.
* @param compute_errors If true, run MnHesse after minimisation.
*/
explicit FitModel(unsigned int strategy = 0, unsigned int max_calls = 100,
double tolerance = 0.5, bool compute_errors = false);
// Destructor must be defined in Fit.cpp where FitModelImpl is complete.
~FitModel();
FitModel(const FitModel &);
FitModel &operator=(const FitModel &);
FitModel(FitModel &&) noexcept = default;
FitModel &operator=(FitModel &&) noexcept = default;
/** @brief Set lower and upper bounds for parameter idx.*/
void SetParLimits(unsigned int idx, double lo, double hi);
/**
* @brief Fix parameter idx at value val.
*
* Excluded from minimisation. Automatic estimates will not touch it.
*/
void FixParameter(unsigned int idx, double val);
/** @brief Release a previously fixed parameter, re-enabling auto estimates.
*/
void ReleaseParameter(unsigned int idx);
void ReleaseParameter(const std::string &name);
/** @brief Set an explicit starting value for parameter idx.*/
void SetParameter(unsigned int idx, double val);
void SetParameter(const std::string &name, double val);
void FixParameter(const std::string &name, double val);
void SetParLimits(const std::string &name, double lo, double hi);
std::string GetParName(unsigned int idx) const;
std::vector<std::string> GetParNames() const;
static constexpr std::size_t GetNpar() noexcept { return npar; }
void SetMaxCalls(unsigned int n) { max_calls_ = n; }
void SetTolerance(double t) { tolerance_ = t; }
void SetComputeErrors(bool b) { compute_errors_ = b; }
unsigned int max_calls() const { return max_calls_; }
double tolerance() const { return tolerance_; }
bool compute_errors() const { return compute_errors_; }
bool is_user_fixed(unsigned int idx) const { return user_fixed_[idx]; }
bool is_user_start(unsigned int idx) const { return user_start_[idx]; }
// Returns the internal Minuit2 state. FitModelImpl is an incomplete type
// here; only callers that include src/FitModelImpl.hpp can dereference it.
FitModelImpl *impl() const { return impl_.get(); }
};
// Suppress implicit instantiation for all supported model types.
// Definitions live in src/Fit.cpp.
extern template class FitModel<model::Gaussian>;
extern template class FitModel<model::GaussianErfcPlateau>;
extern template class FitModel<model::GaussianChargeSharing>;
extern template class FitModel<model::GaussianChargeSharingKb>;
extern template class FitModel<model::Pol1>;
extern template class FitModel<model::Pol2>;
extern template class FitModel<model::RisingScurve>;
extern template class FitModel<model::FallingScurve>;
} // namespace aare
+1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Dtype.hpp"
#include "aare/NDArray.hpp"
+25 -13
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
/************************************************
* @file GainMap.hpp
* @short function to apply gain map of image size to a vector of clusters -
@@ -33,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);
}
}
@@ -65,4 +77,4 @@ class InvertedGainMap {
NDArray<double, 2> m_gain_map{};
};
} // end of namespace aare
} // end of namespace aare
+270 -68
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/CalculateEta.hpp"
@@ -16,8 +17,27 @@ struct Photon {
double energy;
};
struct Coordinate2D {
double x{};
double y{};
};
class Interpolator {
/**
* @brief
* marginal CDF of eta_x (if rosenblatt applied), conditional
* CDF of eta_x conditioned on eta_y
* value at (i, j, e): F(eta_x[i] |
*eta_y[j], energy[e])
*/
NDArray<double, 3> m_ietax;
/**
* @brief
* conditional CDF of eta_y conditioned on eta_x
* value at (i,j,e): F(eta_y[j] | eta_x[i], energy[e])
*/
NDArray<double, 3> m_ietay;
NDArray<double, 1> m_etabinsx;
@@ -25,103 +45,285 @@ class Interpolator {
NDArray<double, 1> m_energy_bins;
public:
/**
* @brief Constructor for the Interpolator class
* @param etacube joint distribution of etaX, etaY and photon energy (note
* first dimension is etaX, second etaY, third photon energy)
* @param xbins bin edges for etaX
* @param ybins bin edges for etaY
* @param ebins bin edges for photon energy
*/
Interpolator(NDView<double, 3> etacube, NDView<double, 1> xbins,
NDView<double, 1> ybins, NDView<double, 1> ebins);
/**
* @brief Constructor for the Interpolator class
* @param xbins bin edges for etaX
* @param ybins bin edges for etaY
* @param ebins bin edges for photon energy
*/
Interpolator(NDView<double, 1> xbins, NDView<double, 1> ybins,
NDView<double, 1> ebins);
/**
* @brief transforms the joint eta distribution of etaX and etaY to the two
* independant uniform distributions based on the Roseblatt transform for
* each energy level
* @param etacube joint distribution of etaX, etaY and photon energy (first
* dimension is etaX, second etaY, third photon energy)
*/
void rosenblatttransform(NDView<double, 3> etacube);
NDArray<double, 3> get_ietax() { return m_ietax; }
NDArray<double, 3> get_ietay() { return m_ietay; }
template <typename ClusterType,
/**
* @brief interpolates the cluster centers for all clusters to a better
* precision
* @tparam ClusterType Type of Clusters to interpolate
* @tparam Etafunction Function object that calculates desired eta default:
* calculate_eta2
* @return interpolated photons (photon positions are given as double but
* following row column format e.g. x=0, y=0 means top row and first column
* of frame) (An interpolated photon position of (1.5, 2.5) corresponds to
* an estimated photon hit at the pixel center of pixel (1,2))
*/
template <auto EtaFunction = calculate_eta2, typename ClusterType,
typename Eanble = std::enable_if_t<is_cluster_v<ClusterType>>>
std::vector<Photon> interpolate(const ClusterVector<ClusterType> &clusters);
std::vector<Photon>
interpolate(const ClusterVector<ClusterType> &clusters) const;
/**
* @brief interpolates the cluster centers for all clusters to a better
* precision
* @param clusters clusters of photon hits to interpolate
* @param etas precomputed eta values for each cluster (must be in the same
* order as the clusters)
* @return interpolated photons (photon positions are given as double but
* following row column format e.g. x=0, y=0 means top row and first column
* of frame) (An interpolated photon position of (1.5, 2.5) corresponds to
* an estimated photon hit at the pixel center of pixel (1,2))
*/
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType = uint16_t,
typename Enable = std::enable_if_t<is_cluster_v<
Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>>>>
std::vector<Photon> interpolate(
const ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>>
&clusters,
const std::vector<Eta2<T>> &etas) const;
/**
* @brief transforms the eta values to uniform coordinates based on the CDF
* ieta_x and ieta_y
* @tparam eta Eta to transform
* @return uniform coordinates {x,y}
*/
template <typename T>
Coordinate2D transform_eta_values(const Eta2<T> &eta) const;
private:
/**
* @brief bilinear interpolation of the transformed eta values
* @param ix index of etaX bin
* @param iy index of etaY bin
* @param ie index of energy bin
* @return pair of interpolated transformed eta values (ietax, ietay)
*/
template <typename T>
std::pair<double, double>
bilinear_interpolation(const size_t ix, const size_t iy, const size_t ie,
const Eta2<T> &eta) const;
};
// TODO: generalize to support any clustertype!!! otherwise add std::enable_if_t
// to only take Cluster2x2 and Cluster3x3
template <typename ClusterType, typename Enable>
template <typename T>
std::pair<double, double>
Interpolator::bilinear_interpolation(const size_t ix, const size_t iy,
const size_t ie,
const Eta2<T> &eta) const {
auto next_index_y = static_cast<ssize_t>(iy + 1) >= m_ietax.shape(1)
? m_ietax.shape(1) - 1
: iy + 1;
auto next_index_x = static_cast<ssize_t>(ix + 1) >= m_ietax.shape(0)
? m_ietax.shape(0) - 1
: ix + 1;
// bilinear interpolation
double ietax_interp_left = linear_interpolation(
{m_etabinsy(iy), m_etabinsy(iy + 1)},
{m_ietax(ix, iy, ie), m_ietax(ix, next_index_y, ie)}, eta.y);
double ietax_interp_right =
linear_interpolation({m_etabinsy(iy), m_etabinsy(iy + 1)},
{m_ietax(next_index_x, iy, ie),
m_ietax(next_index_x, next_index_y, ie)},
eta.y);
// transformed photon position x between [0,1]
double ietax_interpolated =
linear_interpolation({m_etabinsx(ix), m_etabinsx(ix + 1)},
{ietax_interp_left, ietax_interp_right}, eta.x);
double ietay_interp_left = linear_interpolation(
{m_etabinsx(ix), m_etabinsx(ix + 1)},
{m_ietay(ix, iy, ie), m_ietay(next_index_x, iy, ie)}, eta.x);
double ietay_interp_right =
linear_interpolation({m_etabinsx(ix), m_etabinsx(ix + 1)},
{m_ietay(ix, next_index_y, ie),
m_ietay(next_index_x, next_index_y, ie)},
eta.x);
// transformed photon position y between [0,1]
double ietay_interpolated =
linear_interpolation({m_etabinsy(iy), m_etabinsy(iy + 1)},
{ietay_interp_left, ietay_interp_right}, eta.y);
return {ietax_interpolated, ietay_interpolated};
}
template <typename T>
Coordinate2D Interpolator::transform_eta_values(const Eta2<T> &eta) const {
// Finding the index of the last element that is smaller
// should work fine as long as we have many bins
auto ie = last_smaller(m_energy_bins, static_cast<double>(eta.sum));
auto ix = last_smaller(m_etabinsx, eta.x);
auto iy = last_smaller(m_etabinsy, eta.y);
if (static_cast<ssize_t>(ix) >= m_etabinsx.size() - 1 ||
static_cast<ssize_t>(iy) >= m_etabinsy.size() - 1 ||
static_cast<ssize_t>(ie) >= m_energy_bins.size() - 1) {
throw std::runtime_error(fmt::format(
"Eta values (eta.x = {:4f}, eta.y = {:4f}, energy = {}) out of "
"bounds of eta distribution with largest values: (eta.x = {:4f}, "
"eta.y = {:4f}, energy = {:4f})",
eta.x, eta.y, eta.sum, *(m_etabinsx.end() - 1),
*(m_etabinsy.end() - 1), *(m_energy_bins.end() - 1)));
}
// TODO: bilinear interpolation only works if all bins have a size > 1 -
// otherwise bilinear interpolation with zero values which skew the
// results
// TODO: maybe trim the bins at the edges with zero values beforehand
// auto [ietax_interpolated, ietay_interpolated] =
// bilinear_interpolation(ix, iy, ie, eta);
return Coordinate2D{m_ietax(ix, iy, ie), m_ietay(ix, iy, ie)};
}
template <auto EtaFunction, typename ClusterType, typename Enable>
std::vector<Photon>
Interpolator::interpolate(const ClusterVector<ClusterType> &clusters) {
Interpolator::interpolate(const ClusterVector<ClusterType> &clusters) const {
std::vector<Photon> photons;
photons.reserve(clusters.size());
if (clusters.cluster_size_x() == 3 || clusters.cluster_size_y() == 3) {
for (const ClusterType &cluster : clusters) {
size_t cluster_index{};
for (const ClusterType &cluster : clusters) {
auto eta = calculate_eta2(cluster);
auto eta = EtaFunction(cluster);
Photon photon;
photon.x = cluster.x;
photon.y = cluster.y;
photon.energy = static_cast<decltype(photon.energy)>(eta.sum);
Photon photon;
photon.x = cluster.x;
photon.y = cluster.y;
photon.energy = static_cast<decltype(photon.energy)>(eta.sum);
// auto ie = nearest_index(m_energy_bins, photon.energy)-1;
// auto ix = nearest_index(m_etabinsx, eta.x)-1;
// auto iy = nearest_index(m_etabinsy, eta.y)-1;
// Finding the index of the last element that is smaller
// should work fine as long as we have many bins
auto ie = last_smaller(m_energy_bins, photon.energy);
auto ix = last_smaller(m_etabinsx, eta.x);
auto iy = last_smaller(m_etabinsy, eta.y);
Coordinate2D uniform_coordinates{};
// fmt::print("ex: {}, ix: {}, iy: {}\n", ie, ix, iy);
try {
// check if eta values are within bounds
uniform_coordinates = transform_eta_values(eta);
} catch (const std::runtime_error &e) {
throw std::runtime_error(
fmt::format("{} for cluster: {}", e.what(), cluster_index));
}
double dX, dY;
// cBottomLeft = 0,
// cBottomRight = 1,
// cTopLeft = 2,
// cTopRight = 3
switch (static_cast<corner>(eta.c)) {
if (EtaFunction == &calculate_eta2<typename ClusterType::value_type,
ClusterType::cluster_size_x,
ClusterType::cluster_size_y,
typename ClusterType::coord_type> ||
EtaFunction ==
&calculate_full_eta2<typename ClusterType::value_type,
ClusterType::cluster_size_x,
ClusterType::cluster_size_y,
typename ClusterType::coord_type>) {
double dX{}, dY{};
// TODO: could also chaneg the sign of the eta calculation
switch (eta.c) {
case corner::cTopLeft:
dX = -1.;
dY = 0;
dX = -1.0;
dY = -1.0;
break;
case corner::cTopRight:;
dX = 0;
dY = 0;
dX = 0.0;
dY = -1.0;
break;
case corner::cBottomLeft:
dX = -1.;
dY = -1.;
dX = -1.0;
dY = 0.0;
break;
case corner::cBottomRight:
dX = 0.;
dY = -1.;
dX = 0.0;
dY = 0.0;
break;
}
photon.x += m_ietax(ix, iy, ie) * 2 + dX;
photon.y += m_ietay(ix, iy, ie) * 2 + dY;
photons.push_back(photon);
}
} else if (clusters.cluster_size_x() == 2 ||
clusters.cluster_size_y() == 2) {
for (const ClusterType &cluster : clusters) {
auto eta = calculate_eta2(cluster);
Photon photon;
photon.x = cluster.x;
photon.y = cluster.y;
photon.energy = static_cast<decltype(photon.energy)>(eta.sum);
// Now do some actual interpolation.
// Find which energy bin the cluster is in
// auto ie = nearest_index(m_energy_bins, photon.energy)-1;
// auto ix = nearest_index(m_etabinsx, eta.x)-1;
// auto iy = nearest_index(m_etabinsy, eta.y)-1;
// Finding the index of the last element that is smaller
// should work fine as long as we have many bins
auto ie = last_smaller(m_energy_bins, photon.energy);
auto ix = last_smaller(m_etabinsx, eta.x);
auto iy = last_smaller(m_etabinsy, eta.y);
photon.x += m_ietax(ix, iy, ie) *
2; // eta goes between 0 and 1 but we could move the hit
// anywhere in the 2x2
photon.y += m_ietay(ix, iy, ie) * 2;
photons.push_back(photon);
photon.x = photon.x + 0.5 + uniform_coordinates.x +
dX; // use pixel center + 0.5
photon.y =
photon.y + 0.5 + uniform_coordinates.y +
dY; // eta2 calculates the ratio between bottom and sum of
// bottom and top shift by 1 add eta value correctly
} else {
photon.x += uniform_coordinates.x;
photon.y += uniform_coordinates.y;
}
} else {
++cluster_index;
photons.push_back(photon);
}
return photons;
}
template <typename T, uint8_t ClusterSizeX, uint8_t ClusterSizeY,
typename CoordType, typename Enable>
std::vector<Photon> Interpolator::interpolate(
const ClusterVector<Cluster<T, ClusterSizeX, ClusterSizeY, CoordType>>
&clusters,
const std::vector<Eta2<T>> &etas) const {
if (clusters.size() != etas.size()) {
throw std::runtime_error(
"Only 3x3 and 2x2 clusters are supported for interpolation");
fmt::format("Size of clusters and precomputed etas must be the "
"same, but got {} clusters and {} etas",
clusters.size(), etas.size()));
}
std::vector<Photon> photons;
photons.reserve(clusters.size());
for (size_t i = 0; i < clusters.size(); ++i) {
const auto &cluster = clusters[i];
const auto &eta = etas[i];
Photon photon;
photon.x = cluster.x;
photon.y = cluster.y;
photon.energy = static_cast<decltype(photon.energy)>(eta.sum);
Coordinate2D uniform_coordinates{};
try {
// check if eta values are within bounds
uniform_coordinates = transform_eta_values(eta);
} catch (const std::runtime_error &e) {
throw std::runtime_error(
fmt::format("{} for cluster: {}", e.what(), i));
}
photon.x += uniform_coordinates.x;
photon.y += uniform_coordinates.y;
photons.push_back(photon);
}
return photons;
+3 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <cstdint>
#include <filesystem>
@@ -48,6 +49,7 @@ class JungfrauDataFile : public FileInterface {
size_t pixels_per_frame() override;
size_t bytes_per_pixel() const;
size_t bitdepth() const override;
Dtype dtype() const override { return Dtype::UINT16; }
void seek(size_t frame_index)
override; //!< seek to the given frame index (note not byte offset)
size_t tell() override; //!< get the frame index of the file pointer
@@ -112,4 +114,4 @@ class JungfrauDataFile : public FileInterface {
std::filesystem::path fpath(size_t frame_index) const;
};
} // namespace aare
} // namespace aare
File diff suppressed because it is too large. Load diff
+104
View File
@@ -0,0 +1,104 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Dtype.hpp"
#include "aare/File.hpp"
#include <cstddef>
#include <filesystem>
#include <optional>
#include <vector>
namespace aare::experimental {
/**
* @brief Read independent chunks of a file in parallel.
*
* Each worker opens its own File instance, so seeking and reading do not share
* mutable file state. Chunks are written directly to their position in the
* destination buffer and the resulting frame order is the same as in the file.
*/
class MultiThreadedFileReader {
public:
/**
* @param fname path accepted by File
* @param n_threads maximum number of worker threads
* @param chunk_size number of frames claimed by a worker at a time
* @param total_frames number of frames to read, or all frames when omitted
*/
MultiThreadedFileReader(std::filesystem::path fname, size_t n_threads,
size_t chunk_size,
std::optional<size_t> total_frames = std::nullopt);
MultiThreadedFileReader(const MultiThreadedFileReader &) = delete;
MultiThreadedFileReader &
operator=(const MultiThreadedFileReader &) = delete;
MultiThreadedFileReader(MultiThreadedFileReader &&) noexcept = default;
MultiThreadedFileReader &
operator=(MultiThreadedFileReader &&) noexcept = default;
/**
* @brief Read one chunk per active worker into a caller-owned buffer.
*
* The buffer must hold at least next_read_bytes() bytes. The reader's
* position advances by the returned number of frames. At the end of the
* configured range this function returns zero and does not access the
* destination.
*/
size_t read_into(std::byte *destination);
/** @brief Read the next wave of chunks into an owned byte buffer. */
std::vector<std::byte> read();
/** @brief Read every frame remaining from the current position. */
std::vector<std::byte> read_all();
/** @brief Set the next frame index to read. The end position is valid. */
void seek(size_t frame_index);
/** @brief Return the next frame index to read. */
size_t tell() const noexcept { return m_current_frame; }
/** @brief Close all worker files. Safe to call more than once. */
void close() noexcept { m_files.clear(); }
/** @brief Return whether the worker files are open. */
bool is_open() const noexcept { return !m_files.empty(); }
size_t n_threads() const noexcept { return m_n_threads; }
size_t chunk_size() const noexcept { return m_chunk_size; }
size_t total_frames() const noexcept { return m_total_frames; }
size_t source_total_frames() const noexcept {
return m_source_total_frames;
}
size_t rows() const noexcept { return m_rows; }
size_t cols() const noexcept { return m_cols; }
size_t bitdepth() const noexcept { return m_bitdepth; }
Dtype dtype() const noexcept { return m_dtype; }
size_t bytes_per_frame() const noexcept { return m_bytes_per_frame; }
size_t total_bytes() const noexcept { return m_total_bytes; }
size_t remaining_frames() const noexcept;
size_t next_read_frames() const noexcept;
size_t next_read_bytes() const noexcept {
return next_read_frames() * m_bytes_per_frame;
}
private:
std::filesystem::path m_fname;
size_t m_n_threads;
size_t m_chunk_size;
size_t m_total_frames;
size_t m_source_total_frames;
size_t m_rows;
size_t m_cols;
size_t m_bitdepth;
Dtype m_dtype;
size_t m_bytes_per_frame;
size_t m_total_bytes;
size_t m_current_frame;
std::vector<File> m_files;
void ensure_open() const;
};
} // namespace aare::experimental
+433 -284
View File
@@ -1,12 +1,10 @@
// SPDX-License-Identifier: MPL-2.0
//
// Container holding image data, or a time series of image data in contigious
// memory. Used for all data processing in Aare.
//
#pragma once
/*
Container holding image data, or a time series of image data in contigious
memory.
TODO! Add expression templates for operators
*/
#include "aare/ArrayExpr.hpp"
#include "aare/NDView.hpp"
@@ -25,12 +23,17 @@ template <typename T, ssize_t Ndim = 2>
class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
std::array<ssize_t, Ndim> shape_;
std::array<ssize_t, Ndim> strides_;
size_t size_{}; //TODO! do we need to store size when we have shape?
size_t size_{}; // TODO! do we need to store size when we have shape?
T *data_;
public:
///////////////////////////////////////////////////////////////////////////////
// Constructors
//
///////////////////////////////////////////////////////////////////////////////
/**
* @brief Default constructor. Will construct an empty NDArray.
* @brief Default constructor. Constructs an empty NDArray.
*
*/
NDArray() : shape_(), strides_(c_strides<Ndim>(shape_)), data_(nullptr) {};
@@ -43,8 +46,7 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
*/
explicit NDArray(std::array<ssize_t, Ndim> shape)
: shape_(shape), strides_(c_strides<Ndim>(shape_)),
size_(num_elements(shape_)),
data_(new T[size_]) {}
size_(num_elements(shape_)), data_(new T[size_]) {}
/**
* @brief Construct a new NDArray object with a shape and value.
@@ -56,6 +58,10 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
this->operator=(value);
}
// Allow NDArray of different type and dimension to be friend classes
// This is needed for the move constructor from NDArray<T,Ndim+1>
template <typename U, ssize_t Dim> friend class NDArray;
/**
* @brief Construct a new NDArray object from a NDView.
* @note The data is copied from the view to the NDArray.
@@ -66,44 +72,67 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
std::copy(v.begin(), v.end(), begin());
}
/**
* @brief Construct a new NDArray object from an std::array.
*/
template <size_t Size>
NDArray(const std::array<T, Size> &arr) : NDArray<T, 1>({Size}) {
std::copy(arr.begin(), arr.end(), begin());
}
// Move constructor
/**
* @brief Move construct a new NDArray object. Cheap since it just
* reassigns the pointer and copy size/strides.
*
* @param other
*/
NDArray(NDArray &&other) noexcept
: shape_(other.shape_), strides_(c_strides<Ndim>(shape_)),
size_(other.size_), data_(other.data_) {
other.reset(); // TODO! is this necessary?
other.reset(); // Needed to avoid double free
}
//Move constructor from an an array with Ndim + 1
/**
* @brief Move construct a new NDArray object from an array with Ndim + 1.
* Can be used to drop a dimension cheaply.
* @param other
*/
template <ssize_t M, typename = std::enable_if_t<(M == Ndim + 1)>>
NDArray(NDArray<T, M> &&other)
NDArray(NDArray<T, M> &&other)
: shape_(drop_first_dim(other.shape())),
strides_(c_strides<Ndim>(shape_)), size_(num_elements(shape_)),
data_(other.data()) {
// For now only allow move if the size matches, to avoid unreachable data
// if the use case arises we can remove this check
if(size() != other.size()) {
data_ = nullptr; // avoid double free, other will clean up the memory in it's destructor
throw std::runtime_error(LOCATION +
"Size mismatch in move constructor of NDArray<T, Ndim-1>");
}
// For now only allow move if the size matches, to avoid unreachable
// data if the use case arises we can remove this check
if (size() != other.size()) {
data_ = nullptr; // avoid double free, other will clean up the
// memory in it's destructor
throw std::runtime_error(
LOCATION +
"Size mismatch in move constructor of NDArray<T, Ndim-1>");
}
other.reset();
}
// Copy constructor
/**
* @brief Copy construct a new NDArray object from another NDArray.
*
* @param other
*/
NDArray(const NDArray &other)
: shape_(other.shape_), strides_(c_strides<Ndim>(shape_)),
size_(other.size_), data_(new T[size_]) {
std::copy(other.data_, other.data_ + size_, data_);
}
// Conversion operator from array expression to array
/**
* @brief Conversion from a ArrayExpr to an actual NDArray. Used when
* the expression is evaluated and data needed.
*
* @tparam E
* @param expr
*/
template <typename E>
NDArray(ArrayExpr<E, Ndim> &&expr) : NDArray(expr.shape()) {
for (size_t i = 0; i < size_; ++i) {
@@ -111,23 +140,146 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
}
}
/**
* @brief Destroy the NDArray object. Frees the allocated memory.
*
*/
~NDArray() { delete[] data_; }
auto begin() { return data_; }
auto end() { return data_ + size_; }
/**
* @brief Copy data from a view of matching shape into this array without
* reallocating.
* @param v view to copy from, must have the same shape as this array
* @throws std::runtime_error if the shapes differ
*
* Use this instead of assigning a new NDArray when the buffer needs to be
* kept, for example when the array is part of a preallocated pool.
*/
void copy_from(const NDView<T, Ndim> v) {
if (v.shape() != shape_) {
throw std::runtime_error(LOCATION +
"Shape mismatch in NDArray::copy_from");
}
std::copy(v.begin(), v.end(), begin());
}
auto begin() const { return data_; }
auto end() const { return data_ + size_; }
///////////////////////////////////////////////////////////////////////////////
// Iterators and indexing
//
///////////////////////////////////////////////////////////////////////////////
auto *begin() { return data_; }
const auto *begin() const { return data_; }
auto *end() { return data_ + size_; }
const auto *end() const { return data_ + size_; }
/*
* @brief Access element at given multi-dimensional index.
* i.e. arr(i,j,k,...)
*
* @note The fast index is the last index. Please take care when iterating
* through the array.
*/
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, T &> operator()(Ix... index) {
return data_[element_offset(strides_, index...)];
}
/*
* @brief Access element at given multi-dimensional index (const version).
* i.e. arr(i,j,k,...)
*
* @note The fast index is the last index. Please take care when iterating
* through the array.
*/
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, const T &>
operator()(Ix... index) const {
return data_[element_offset(strides_, index...)];
}
/*
@brief Index the array as it would be a 1D array. To get a certain
pixel in a multidimensional array use the (i,j,k,...) operator instead.
*/
T &operator()(ssize_t i) { return data_[i]; }
/*
@brief Index the array as it would be a 1D array. To get a certain
pixel in a multidimensional array use the (i,j,k,...) operator instead.
*/
const T &operator()(ssize_t i) const { return data_[i]; }
/*
@brief Index the array as it would be a 1D array. To get a certain
pixel in a multidimensional array use the (i,j,k,...) operator instead.
*/
T &operator[](ssize_t i) { return data_[i]; }
/*
@brief Index the array as it would be a 1D array. To get a certain
pixel in a multidimensional array use the (i,j,k,...) operator instead.
*/
const T &operator[](ssize_t i) const { return data_[i]; }
/* @brief Return a raw pointer to the data */
T *data() { return data_; }
/* @brief Return a const raw pointer to the data */
const T *data() const { return data_; }
/* @brief Return a byte pointer to the data. Useful for memcpy like
* operations */
std::byte *buffer() { return reinterpret_cast<std::byte *>(data_); }
/**
* @brief Return the total number of elements in the array as a signed
* integer
*/
ssize_t size() const { return static_cast<ssize_t>(size_); }
/** @brief Return the total number of bytes in the array */
size_t total_bytes() const { return size_ * sizeof(T); }
/** @brief Return the shape of the array */
Shape<Ndim> shape() const noexcept { return shape_; }
/** @brief Return the size of dimension i */
ssize_t shape(ssize_t i) const noexcept { return shape_[i]; }
/** @brief Return the strides of the array */
std::array<ssize_t, Ndim> strides() const noexcept { return strides_; }
/**
* @brief Return the bitdepth of the array. Useful for checking that
* detector data can fit in the array type.
*/
size_t bitdepth() const noexcept { return sizeof(T) * 8; }
/**
* @brief Return the number of bytes to step in each dimension when
* traversing the array.
*/
std::array<ssize_t, Ndim> byte_strides() const noexcept {
auto byte_strides = strides_;
for (auto &val : byte_strides)
val *= sizeof(T);
return byte_strides;
}
using value_type = T;
NDArray &operator=(NDArray &&other) noexcept; // Move assign
NDArray &operator=(const NDArray &other); // Copy assign
NDArray &operator+=(const NDArray &other);
NDArray &operator-=(const NDArray &other);
NDArray &operator*=(const NDArray &other);
///////////////////////////////////////////////////////////////////////////////
// Assignments
//
///////////////////////////////////////////////////////////////////////////////
// Write directly to the data array, or create a new one
/**
* @brief Copy to the NDArray from an std::array. If the size of the array
* is different we reallocate the data.
*
*/
template <size_t Size>
NDArray<T, 1> &operator=(const std::array<T, Size> &other) {
if (Size != size_) {
@@ -141,12 +293,94 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
return *this;
}
// NDArray& operator/=(const NDArray& other);
/**
* @brief Move assignment operator.
*/
NDArray &operator=(NDArray &&other) noexcept {
// TODO! Should we use swap?
if (this != &other) {
delete[] data_;
data_ = other.data_;
shape_ = other.shape_;
size_ = other.size_;
strides_ = other.strides_;
other.reset();
}
return *this;
}
/**
* @brief Copy assignment operator.
*/
NDArray &operator=(const NDArray &other) {
if (this != &other) {
delete[] data_;
shape_ = other.shape_;
strides_ = other.strides_;
size_ = other.size_;
data_ = new T[size_];
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
///////////////////////////////////////////////////////////////////////////////
// Math operators
//
///////////////////////////////////////////////////////////////////////////////
/**
* @brief Add elementwise from another NDArray.
*/
NDArray &operator+=(const NDArray &other) {
if (shape_ != other.shape_)
throw(std::runtime_error(
"Shape of NDArray must match for operator +="));
for (size_t i = 0; i < size_; ++i) {
data_[i] += other.data_[i];
}
return *this;
}
/**
* @brief Subtract elementwise with another NDArray.
*/
NDArray &operator-=(const NDArray &other) {
if (shape_ != other.shape_)
throw(std::runtime_error(
"Shape of NDArray must match for operator -="));
for (size_t i = 0; i < size_; ++i) {
data_[i] -= other.data_[i];
}
return *this;
}
/**
* @brief Multiply elementwise with another NDArray.
*/
NDArray &operator*=(const NDArray &other) {
if (shape_ != other.shape_)
throw(std::runtime_error(
"Shape of NDArray must match for operator *="));
for (size_t i = 0; i < size_; ++i) {
data_[i] *= other.data_[i];
}
return *this;
}
/**
* @brief Divide elementwise by another NDArray. Templated to allow division
* with different types.
*
* TODO! Why is this templated when the others are not?
*/
template <typename V> NDArray &operator/=(const NDArray<V, Ndim> &other) {
// check shape
if (shape_ == other.shape()) {
for (uint32_t i = 0; i < size_; ++i) {
for (size_t i = 0; i < size_; ++i) {
data_[i] /= other(i);
}
return *this;
@@ -154,80 +388,155 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
throw(std::runtime_error("Shape of NDArray must match"));
}
NDArray<bool, Ndim> operator>(const NDArray &other);
/**
* @brief Assign a scalar value to all elements in the NDArray.
*/
NDArray &operator=(const T &value) {
std::fill_n(data_, size_, value);
return *this;
}
bool operator==(const NDArray &other) const;
bool operator!=(const NDArray &other) const;
/**
* @brief Add a scalar value to all elements in the NDArray.
*/
NDArray &operator+=(const T &value) {
for (size_t i = 0; i < size_; ++i)
data_[i] += value;
return *this;
}
NDArray &operator=(const T & /*value*/);
NDArray &operator+=(const T & /*value*/);
NDArray operator+(const T & /*value*/);
NDArray &operator-=(const T & /*value*/);
NDArray operator-(const T & /*value*/);
NDArray &operator*=(const T & /*value*/);
NDArray operator*(const T & /*value*/);
NDArray &operator/=(const T & /*value*/);
NDArray operator/(const T & /*value*/);
/**
* @brief Subtract a scalar value to all elements in the NDArray.
*/
NDArray &operator-=(const T &value) {
for (size_t i = 0; i < size_; ++i)
data_[i] -= value;
return *this;
}
NDArray &operator&=(const T & /*mask*/);
/**
* @brief Multiply all elements in the NDArray with a scalar value
*/
NDArray &operator*=(const T &value) {
for (size_t i = 0; i < size_; ++i)
data_[i] *= value;
return *this;
}
/**
* @brief Divide all elements in the NDArray with a scalar value
*/
NDArray &operator/=(const T &value) {
for (size_t i = 0; i < size_; ++i)
data_[i] /= value;
return *this;
}
/**
* @brief Bitwise AND all elements in the NDArray with a scalar mask.
* Used for example to mask out gain bits for Jungfrau detectors.
*/
NDArray &operator&=(const T &mask) {
for (auto it = begin(); it != end(); ++it)
*it &= mask;
return *this;
}
/**
* @brief Operator + with a scalar value. Returns a new NDArray.
*
* TODO! Expression template version of this?
*/
NDArray operator+(const T &value) {
NDArray result = *this;
result += value;
return result;
}
/**
* @brief Operator - with a scalar value. Returns a new NDArray.
*
* TODO! Expression template version of this?
*/
NDArray operator-(const T &value) {
NDArray result = *this;
result -= value;
return result;
}
/**
* @brief Operator * with a scalar value. Returns a new NDArray.
*
* TODO! Expression template version of this?
*/
NDArray operator*(const T &value) {
NDArray result = *this;
result *= value;
return result;
}
/**
* @brief Operator / with a scalar value. Returns a new NDArray.
*
* TODO! Expression template version of this?
*/
NDArray operator/(const T &value) {
NDArray result = *this;
result /= value;
return result;
}
/**
* @brief Compare two NDArrays elementwise for equality.
*/
bool operator==(const NDArray &other) const {
if (shape_ != other.shape_)
return false;
for (size_t i = 0; i != size_; ++i)
if (data_[i] != other.data_[i])
return false;
return true;
}
/**
* @brief Compare two NDArrays elementwise for non-equality.
*/
bool operator!=(const NDArray &other) const { return !((*this) == other); }
/**
* @brief Compute the square root of all elements in the NDArray.
*/
void sqrt() {
for (int i = 0; i < size_; ++i) {
for (size_t i = 0; i < size_; ++i) {
data_[i] = std::sqrt(data_[i]);
}
}
NDArray &operator++(); // pre inc
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, T &> operator()(Ix... index) {
return data_[element_offset(strides_, index...)];
}
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, T &> operator()(Ix... index) const {
return data_[element_offset(strides_, index...)];
}
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, T> value(Ix... index) {
return data_[element_offset(strides_, index...)];
}
// TODO! is int the right type for index?
T &operator()(ssize_t i) { return data_[i]; }
const T &operator()(ssize_t i) const { return data_[i]; }
T &operator[](ssize_t i) { return data_[i]; }
const T &operator[](ssize_t i) const { return data_[i]; }
T *data() { return data_; }
std::byte *buffer() { return reinterpret_cast<std::byte *>(data_); }
ssize_t size() const { return static_cast<ssize_t>(size_); }
size_t total_bytes() const { return size_ * sizeof(T); }
std::array<ssize_t, Ndim> shape() const noexcept { return shape_; }
ssize_t shape(ssize_t i) const noexcept { return shape_[i]; }
std::array<ssize_t, Ndim> strides() const noexcept { return strides_; }
size_t bitdepth() const noexcept { return sizeof(T) * 8; }
std::array<ssize_t, Ndim> byte_strides() const noexcept {
auto byte_strides = strides_;
for (auto &val : byte_strides)
val *= sizeof(T);
return byte_strides;
}
/**
* @brief Create a view of the NDArray.
*
* @return NDView<T, Ndim>
/*
* @brief Prefix increment operator. Increments all elements by 1.
*/
NDView<T, Ndim> view() const { return NDView<T, Ndim>{data_, shape_}; }
NDArray &operator++() {
for (size_t i = 0; i < size_; ++i)
data_[i] += T{1};
return *this;
}
void Print();
void Print_all();
void Print_some();
/** @brief Create a mutable view of the NDArray. */
NDView<T, Ndim> view() { return NDView<T, Ndim>{data_, shape_}; }
/** @brief Create a read-only view of a const NDArray. */
NDView<const T, Ndim> view() const {
return NDView<const T, Ndim>{data_, shape_};
}
private:
/**
* @brief Reset the NDArray to an empty state. Dropping the ownership of
* the data. Used internally for move operations to avoid double free or
* dangling pointers.
*/
void reset() {
data_ = nullptr;
size_ = 0;
@@ -236,167 +545,10 @@ class NDArray : public ArrayExpr<NDArray<T, Ndim>, Ndim> {
}
};
// Move assign
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &
NDArray<T, Ndim>::operator=(NDArray<T, Ndim> &&other) noexcept {
if (this != &other) {
delete[] data_;
data_ = other.data_;
shape_ = other.shape_;
size_ = other.size_;
strides_ = other.strides_;
other.reset();
}
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator+=(const NDArray<T, Ndim> &other) {
// check shape
if (shape_ == other.shape_) {
for (size_t i = 0; i < size_; ++i) {
data_[i] += other.data_[i];
}
return *this;
}
throw(std::runtime_error("Shape of ImageDatas must match"));
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator-=(const NDArray<T, Ndim> &other) {
// check shape
if (shape_ == other.shape_) {
for (uint32_t i = 0; i < size_; ++i) {
data_[i] -= other.data_[i];
}
return *this;
}
throw(std::runtime_error("Shape of ImageDatas must match"));
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator*=(const NDArray<T, Ndim> &other) {
// check shape
if (shape_ == other.shape_) {
for (uint32_t i = 0; i < size_; ++i) {
data_[i] *= other.data_[i];
}
return *this;
}
throw(std::runtime_error("Shape of ImageDatas must match"));
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator&=(const T &mask) {
for (auto it = begin(); it != end(); ++it)
*it &= mask;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<bool, Ndim> NDArray<T, Ndim>::operator>(const NDArray &other) {
if (shape_ == other.shape_) {
NDArray<bool, Ndim> result{shape_};
for (int i = 0; i < size_; ++i) {
result(i) = (data_[i] > other.data_[i]);
}
return result;
}
throw(std::runtime_error("Shape of ImageDatas must match"));
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator=(const NDArray<T, Ndim> &other) {
if (this != &other) {
delete[] data_;
shape_ = other.shape_;
strides_ = other.strides_;
size_ = other.size_;
data_ = new T[size_];
std::copy(other.data_, other.data_ + size_, data_);
}
return *this;
}
template <typename T, ssize_t Ndim>
bool NDArray<T, Ndim>::operator==(const NDArray<T, Ndim> &other) const {
if (shape_ != other.shape_)
return false;
for (uint32_t i = 0; i != size_; ++i)
if (data_[i] != other.data_[i])
return false;
return true;
}
template <typename T, ssize_t Ndim>
bool NDArray<T, Ndim>::operator!=(const NDArray<T, Ndim> &other) const {
return !((*this) == other);
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator++() {
for (uint32_t i = 0; i < size_; ++i)
data_[i] += 1;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator=(const T &value) {
std::fill_n(data_, size_, value);
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator+=(const T &value) {
for (uint32_t i = 0; i < size_; ++i)
data_[i] += value;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> NDArray<T, Ndim>::operator+(const T &value) {
NDArray result = *this;
result += value;
return result;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator-=(const T &value) {
for (uint32_t i = 0; i < size_; ++i)
data_[i] -= value;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> NDArray<T, Ndim>::operator-(const T &value) {
NDArray result = *this;
result -= value;
return result;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator/=(const T &value) {
for (uint32_t i = 0; i < size_; ++i)
data_[i] /= value;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> NDArray<T, Ndim>::operator/(const T &value) {
NDArray result = *this;
result /= value;
return result;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> &NDArray<T, Ndim>::operator*=(const T &value) {
for (uint32_t i = 0; i < size_; ++i)
data_[i] *= value;
return *this;
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> NDArray<T, Ndim>::operator*(const T &value) {
NDArray result = *this;
result *= value;
return result;
}
///////////////////////////////////////////////////////////////////////////////
// Free functions closely related to NDArray
//
///////////////////////////////////////////////////////////////////////////////
template <typename T, ssize_t Ndim>
std::ostream &operator<<(std::ostream &os, const NDArray<T, Ndim> &arr) {
@@ -410,27 +562,9 @@ std::ostream &operator<<(std::ostream &os, const NDArray<T, Ndim> &arr) {
return os;
}
template <typename T, ssize_t Ndim> void NDArray<T, Ndim>::Print_all() {
for (auto row = 0; row < shape_[0]; ++row) {
for (auto col = 0; col < shape_[1]; ++col) {
std::cout << std::setw(3);
std::cout << (*this)(row, col) << " ";
}
std::cout << "\n";
}
}
template <typename T, ssize_t Ndim> void NDArray<T, Ndim>::Print_some() {
for (auto row = 0; row < 5; ++row) {
for (auto col = 0; col < 5; ++col) {
std::cout << std::setw(7);
std::cout << (*this)(row, col) << " ";
}
std::cout << "\n";
}
}
template <typename T, ssize_t Ndim>
void save(NDArray<T, Ndim> &img, std::string &pathname) {
[[deprecated("Saving of raw arrays without metadata is deprecated")]] void
save(NDArray<T, Ndim> &img, std::string &pathname) {
std::ofstream f;
f.open(pathname, std::ios::binary);
f.write(img.buffer(), img.size() * sizeof(T));
@@ -438,8 +572,9 @@ void save(NDArray<T, Ndim> &img, std::string &pathname) {
}
template <typename T, ssize_t Ndim>
NDArray<T, Ndim> load(const std::string &pathname,
std::array<ssize_t, Ndim> shape) {
[[deprecated(
"Loading of raw arrays without metadata is deprecated")]] NDArray<T, Ndim>
load(const std::string &pathname, std::array<ssize_t, Ndim> shape) {
NDArray<T, Ndim> img{shape};
std::ifstream f;
f.open(pathname, std::ios::binary);
@@ -448,6 +583,20 @@ NDArray<T, Ndim> load(const std::string &pathname,
return img;
}
/**
* @brief Free function to safely divide two NDArrays elementwise, handling
* division by zero. Uses static_cast to convert types as needed.
*
* @tparam RT Result type
* @tparam NT Numerator type
* @tparam DT Denominator type
* @tparam Ndim Number of dimensions
* @param numerator The numerator NDArray
* @param denominator The denominator NDArray
* @return NDArray<RT, Ndim> Resulting NDArray after safe division
* @throws std::runtime_error if the shapes of the numerator and denominator do
* not match
*/
template <typename RT, typename NT, typename DT, ssize_t Ndim>
NDArray<RT, Ndim> safe_divide(const NDArray<NT, Ndim> &numerator,
const NDArray<DT, Ndim> &denominator) {
@@ -467,4 +616,4 @@ NDArray<RT, Ndim> safe_divide(const NDArray<NT, Ndim> &numerator,
return result;
}
} // namespace aare
} // namespace aare
+25 -22
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/ArrayExpr.hpp"
#include "aare/defs.hpp"
@@ -11,6 +12,7 @@
#include <iostream>
#include <numeric>
#include <stdexcept>
#include <type_traits>
#include <vector>
namespace aare {
@@ -26,15 +28,14 @@ Shape<Ndim> make_shape(const std::vector<size_t> &shape) {
return arr;
}
/**
* @brief Helper function to drop the first dimension of a shape.
* This is useful when you want to create a 2D view from a 3D array.
* @param shape The shape to drop the first dimension from.
* @return A new shape with the first dimension dropped.
*/
template<size_t Ndim>
Shape<Ndim-1> drop_first_dim(const Shape<Ndim> &shape) {
template <size_t Ndim>
Shape<Ndim - 1> drop_first_dim(const Shape<Ndim> &shape) {
static_assert(Ndim > 1, "Cannot drop first dimension from a 1D shape");
Shape<Ndim - 1> new_shape;
std::copy(shape.begin() + 1, shape.end(), new_shape.begin());
@@ -42,14 +43,13 @@ Shape<Ndim-1> drop_first_dim(const Shape<Ndim> &shape) {
}
/**
* @brief Helper function when constructing NDArray/NDView. Calculates the number
* of elements in the resulting array from a shape.
* @brief Helper function when constructing NDArray/NDView. Calculates the
* number of elements in the resulting array from a shape.
* @param shape The shape to calculate the number of elements for.
* @return The number of elements in and NDArray/NDView of that shape.
*/
template <size_t Ndim>
size_t num_elements(const Shape<Ndim> &shape) {
return std::accumulate(shape.begin(), shape.end(), 1,
template <size_t Ndim> size_t num_elements(const Shape<Ndim> &shape) {
return std::accumulate(shape.begin(), shape.end(), size_t{1},
std::multiplies<size_t>());
}
@@ -91,30 +91,35 @@ class NDView : public ArrayExpr<NDView<T, Ndim>, Ndim> {
NDView(T *buffer, std::array<ssize_t, Ndim> shape)
: buffer_(buffer), strides_(c_strides<Ndim>(shape)), shape_(shape),
size_(std::accumulate(std::begin(shape), std::end(shape), 1,
std::multiplies<>())) {}
size_(num_elements(shape)) {}
template <typename U, std::enable_if_t<
std::is_convertible_v<U (*)[], T (*)[]>, int> = 0>
NDView(const NDView<U, Ndim> &other) noexcept
: buffer_(other.buffer_), strides_(other.strides_),
shape_(other.shape_), size_(other.size_) {}
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, T &> operator()(Ix... index) {
return buffer_[element_offset(strides_, index...)];
}
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == 1 && (Ndim > 1), NDView<T, Ndim - 1>> operator()(Ix... index) {
std::enable_if_t<sizeof...(Ix) == 1 && (Ndim > 1), NDView<T, Ndim - 1>>
operator()(Ix... index) {
// return a view of the next dimension
std::array<ssize_t, Ndim - 1> new_shape{};
std::copy_n(shape_.begin() + 1, Ndim - 1, new_shape.begin());
return NDView<T, Ndim - 1>(&buffer_[element_offset(strides_, index...)],
new_shape);
}
template <typename... Ix>
std::enable_if_t<sizeof...(Ix) == Ndim, const T &> operator()(Ix... index) const {
std::enable_if_t<sizeof...(Ix) == Ndim, const T &>
operator()(Ix... index) const {
return buffer_[element_offset(strides_, index...)];
}
ssize_t size() const { return static_cast<ssize_t>(size_); }
size_t total_bytes() const { return size_ * sizeof(T); }
std::array<ssize_t, Ndim> strides() const noexcept { return strides_; }
@@ -123,15 +128,11 @@ class NDView : public ArrayExpr<NDView<T, Ndim>, Ndim> {
T *end() { return buffer_ + size_; }
T const *begin() const { return buffer_; }
T const *end() const { return buffer_ + size_; }
/**
* @brief Access element at index i.
*/
T &operator[](ssize_t i) { return buffer_[i]; }
T &operator[](ssize_t i) { return buffer_[i]; }
/**
* @brief Access element at index i.
@@ -206,7 +207,7 @@ class NDView : public ArrayExpr<NDView<T, Ndim>, Ndim> {
void print_all() const;
/**
* @brief Create a subview of a range of the first dimension.
* @brief Create a subview of a range of the first dimension.
* This is useful for splitting a batches of frames in parallel processing.
* @param first The first index of the subview (inclusive).
* @param last The last index of the subview (exclusive).
@@ -222,6 +223,8 @@ class NDView : public ArrayExpr<NDView<T, Ndim>, Ndim> {
}
private:
template <typename, ssize_t> friend class NDView;
T *buffer_{nullptr};
std::array<ssize_t, Ndim> strides_{};
std::array<ssize_t, Ndim> shape_{};
@@ -269,4 +272,4 @@ template <typename T> NDView<T, 1> make_view(std::vector<T> &vec) {
return NDView<T, 1>(vec.data(), {static_cast<ssize_t>(vec.size())});
}
} // namespace aare
} // namespace aare
+3 -2
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Dtype.hpp"
#include "aare/FileInterface.hpp"
@@ -60,7 +61,7 @@ class NumpyFile : public FileInterface {
* @brief get the data type of the numpy file
* @return DType
*/
Dtype dtype() const { return m_header.dtype; }
Dtype dtype() const override { return m_header.dtype; }
/**
* @brief get the shape of the numpy file
@@ -128,4 +129,4 @@ class NumpyFile : public FileInterface {
void write_impl(void *data, uint64_t size);
};
} // namespace aare
} // namespace aare
+1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <algorithm>
+134 -89
View File
@@ -1,16 +1,21 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#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;
@@ -19,9 +24,8 @@ 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
@@ -29,56 +33,76 @@ template <typename SUM_TYPE = double> class Pedestal {
NDArray<SUM_TYPE, 2> m_mean;
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})) {
assert(rows > 0 && cols > 0 && n_samples > 0);
m_sum = 0;
m_sum2 = 0;
m_mean = 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);
}
/** @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;
@@ -86,6 +110,10 @@ template <typename SUM_TYPE = double> class Pedestal {
m_mean = 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;
@@ -93,9 +121,13 @@ template <typename SUM_TYPE = double> class Pedestal {
m_mean(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(
@@ -110,45 +142,76 @@ template <typename SUM_TYPE = double> class Pedestal {
}
/**
* Push but don't update the cached mean. Speeds up the process
* when initializing the 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_no_update(NDView<T, 2> frame) {
assert(frame.size() == m_rows * m_cols);
template <typename T>
void push_with_threshold(const NDView<T, 2> frame,
const NDView<SUM_TYPE, 2> threshold) {
// 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");
}
if (threshold.shape() != std::array<ssize_t, 2>{m_rows, m_cols}) {
throw std::runtime_error(
"Threshold 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));
if (fabs(frame(row, col) - mean(row, col)) <
threshold(row, col)) {
push<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>());
}
/**
* @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(Frame &frame) { 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;
@@ -162,34 +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; }
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
} // namespace aare
+11
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/NDArray.hpp"
@@ -9,11 +10,21 @@ NDArray<ssize_t, 2> GenerateMoench03PixelMap();
NDArray<ssize_t, 2> GenerateMoench05PixelMap();
NDArray<ssize_t, 2> GenerateMoench05PixelMap1g();
NDArray<ssize_t, 2> GenerateMoench05PixelMapOld();
NDArray<ssize_t, 2> GenerateMoench04AnalogPixelMap();
// Matterhorn02
NDArray<ssize_t, 2> GenerateMH02SingleCounterPixelMap();
NDArray<ssize_t, 3> GenerateMH02FourCounterPixelMap();
/**
* @brief Generate pixel map for Matterhorn10 detector
* @param dynamic_range Dynamic range of the detector (16, 8, or 4)
* @param n_counters Number of counters (1 to 4)
*/
NDArray<ssize_t, 2>
GenerateMatterhorn10PixelMap(const size_t dynamic_range = 16,
const size_t n_counters = 1);
// Eiger
NDArray<ssize_t, 2> GenerateEigerFlipRowsPixelMap();
+3 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
/*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
@@ -26,6 +27,7 @@
#include <atomic>
#include <cassert>
#include <cstddef>
#include <cstdlib>
#include <memory>
#include <stdexcept>
@@ -105,7 +107,7 @@ template <class T> struct ProducerConsumerQueue {
return *this;
}
ProducerConsumerQueue() : ProducerConsumerQueue(2){};
ProducerConsumerQueue() : ProducerConsumerQueue(2) {};
// size must be >= 2.
//
// Also, note that the number of usable slots in the queue at any
+132
View File
@@ -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 &current = 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 &current = 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
+45
View File
@@ -0,0 +1,45 @@
#pragma once
#include "aare/DetectorGeometry.hpp"
#include "aare/ROI.hpp"
#include <cstdint>
#include <vector>
namespace aare {
class DetectorGeometry; // forward declaration to avoid circular dependency
/**
* @brief Class to hold the geometry of a region of interest (ROI)
*/
class ROIGeometry {
public:
/** @brief Constructor
* @param roi
* @param geometry general detector geometry
*/
ROIGeometry(const ROI &roi, DetectorGeometry &geometry);
/// @brief Get number of modules in the ROI
size_t num_modules_in_roi() const;
/// @brief Get the indices of modules in the ROI
const std::vector<size_t> &module_indices_in_roi() const;
size_t module_indices_in_roi(const size_t module_index) const;
size_t pixels_x() const;
size_t pixels_y() const;
private:
/// @brief Size of the ROI in pixels in x direction
size_t m_pixels_x{};
/// @brief Size of the ROI in pixels in y direction
size_t m_pixels_y{};
DetectorGeometry &m_geometry;
/// @brief Indices of modules included in the ROI
std::vector<size_t> m_module_indices_in_roi;
};
} // namespace aare
+94 -14
View File
@@ -1,8 +1,9 @@
// 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
#include "aare/ROIGeometry.hpp"
#include "aare/RawMasterFile.hpp"
#include "aare/RawSubFile.hpp"
@@ -22,19 +23,24 @@ namespace aare {
*/
class RawFile : public FileInterface {
std::vector<std::unique_ptr<RawSubFile>> m_subfiles;
std::vector<std::vector<std::unique_ptr<RawSubFile>>>
m_subfiles; // [ROI][modules_per_ROI]
RawMasterFile m_master;
size_t m_current_frame{};
DetectorGeometry m_geometry;
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;
@@ -42,26 +48,95 @@ class RawFile : public FileInterface {
Frame read_frame() override;
Frame read_frame(size_t frame_number) override;
std::vector<Frame> read_n(size_t n_frames) override;
/**
* @brief Read one ROI defined in the master file
* @param roi_index index of the ROI to read
* @return Frame
* @note the frame index is incremented after calling this function so
* reading rois one after the other wont work.
*/
Frame read_roi(const size_t roi_index);
/**
* @brief Read all ROIs defined in the master file
* @return vector of Frames (one Frame per ROI)
*/
std::vector<Frame> read_rois();
/**
* @brief Read n frames for the given ROI index
* @param n_frames number of frames to read
* @param roi_index index of the ROI to read
* @return vector of Frames
*/
std::vector<Frame> read_n_with_roi(const size_t n_frames,
const size_t roi_index);
void read_into(std::byte *image_buf) override;
void read_into(std::byte *image_buf, size_t n_frames) override;
// TODO! do we need to adapt the API?
void read_into(std::byte *image_buf, DetectorHeader *header);
void read_into(std::byte *image_buf, DetectorHeader *header = nullptr);
void read_into(std::byte *image_buf, size_t n_frames,
DetectorHeader *header);
void read_roi_into(std::byte *image_buf, const size_t roi_index,
const size_t frame_number,
DetectorHeader *header =
nullptr); // maybe just make get_frame_into public
size_t frame_number(size_t frame_index) override;
size_t bytes_per_frame() override;
// TODO: mmh maybe also pass roi_index in Base class File. Leave it unused
// for NumpyFile and JungfrauDataFile
/**
* @brief bytes per frame for the given ROI
* @param roi_index index of the ROI
*/
size_t bytes_per_frame(const size_t roi_index);
size_t pixels_per_frame() override;
/**
* @brief pixels per frame for the given ROI
* @param roi_index index of the ROI
*/
size_t pixels_per_frame(const size_t roi_index);
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;
/**
* @brief rows for the given ROI
* @param roi_index index of the ROI
*/
size_t rows(const size_t roi_index) const;
size_t cols() const override;
/**
* @brief cols for the given ROI
* @param roi_index index of the ROI
*/
size_t cols(const size_t roi_index) const;
size_t bitdepth() const override;
Dtype dtype() const override { return Dtype::from_bitdepth(bitdepth()); }
size_t n_modules() const;
size_t n_modules_in_roi() const;
/**
* @brief number of ROIs defined (always 1 for complete ROI)
*/
size_t num_rois() const;
/**
* @brief get the ROI geometry for the given ROI index
* @param roi_index index of the ROI
*/
const ROIGeometry &roi_geometries(size_t roi_index) const;
/**
* @brief number of modules in each ROI
*/
std::vector<size_t> n_modules_in_roi() const;
xy geometry() const;
RawMasterFile master() const;
@@ -76,23 +151,28 @@ 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_number frame number to read
* @param image_buf buffer to store the frame
* @param frame_index frame number to read
* @param frame_buffer buffer to store the frame
* @param roi_index index of the ROI to read (default is 0 e.g. full frame)
*/
void get_frame_into(size_t frame_index, std::byte *frame_buffer,
DetectorHeader *header = nullptr);
void get_frame_into(
size_t frame_index, std::byte *frame_buffer, const size_t roi_index = 0,
DetectorHeader *header = nullptr); // TODO read_into updates it!!!!
/**
* @brief get the frame at the given frame index
* @param frame_number frame number to read
* @param roi_index index of the ROI to read (default is 0 e.g. full frame)
* @return Frame
*/
Frame get_frame(size_t frame_index);
Frame get_frame(size_t frame_index, const size_t roi_index = 0);
void open_subfiles();
void open_subfiles(const size_t roi_index);
};
} // namespace aare
} // namespace aare
+69 -14
View File
@@ -1,6 +1,9 @@
// 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>
#include <fmt/format.h>
#include <fstream>
@@ -42,14 +45,16 @@ class RawFileNameComponents {
class ScanParameters {
bool m_enabled = false;
std::string m_dac;
DACIndex m_dac{};
int m_start = 0;
int m_stop = 0;
int m_step = 0;
// TODO! add settleTime, requires string to time conversion
int64_t m_settleTime = 0; // [ns]
public:
ScanParameters(const std::string &par);
ScanParameters(const bool enabled, const DACIndex dac, const int start,
const int stop, const int step, const int64_t settleTime);
ScanParameters() = default;
ScanParameters(const ScanParameters &) = default;
ScanParameters &operator=(const ScanParameters &) = default;
@@ -57,8 +62,9 @@ class ScanParameters {
int start() const;
int stop() const;
int step() const;
const std::string &dac() const;
DACIndex dac() const;
bool enabled() const;
int64_t settleTime() const;
void increment_stop();
};
@@ -80,7 +86,11 @@ class RawMasterFile {
size_t m_bitdepth{};
uint8_t m_quad = 0;
xy m_geometry{};
std::optional<std::chrono::nanoseconds> m_exptime;
std::chrono::nanoseconds m_period{0};
/// @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{};
@@ -89,9 +99,9 @@ class RawMasterFile {
size_t m_frame_padding{};
// TODO! should these be bool?
uint8_t m_analog_flag{};
uint8_t m_digital_flag{};
uint8_t m_transceiver_flag{};
bool m_analog_flag{};
bool m_digital_flag{};
bool m_transceiver_flag{};
ScanParameters m_scan_parameters;
@@ -99,11 +109,29 @@ class RawMasterFile {
std::optional<size_t> m_digital_samples;
std::optional<size_t> m_transceiver_samples;
std::optional<size_t> m_number_of_rows;
std::optional<uint8_t> m_counter_mask;
std::optional<ROI> m_roi;
/// @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;
@@ -121,23 +149,50 @@ 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;
std::optional<size_t> digital_samples() const;
std::optional<size_t> transceiver_samples() const;
std::optional<size_t> number_of_rows() const;
std::optional<uint8_t> counter_mask() const;
std::optional<ROI> roi() 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;
/// @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;
std::optional<std::chrono::nanoseconds> exptime() const {
return m_exptime;
}
std::chrono::nanoseconds period() const { return m_period; }
private:
void parse_json(const std::filesystem::path &fpath);
void parse_raw(const std::filesystem::path &fpath);
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
+8 -1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Frame.hpp"
#include "aare/defs.hpp"
@@ -83,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);
@@ -92,4 +99,4 @@ class RawSubFile {
std::filesystem::path fpath(size_t file_index) const;
};
} // namespace aare
} // namespace aare
+23 -6
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <algorithm>
@@ -44,7 +45,11 @@ template <typename T> class VarClusterFinder {
{-1, -1, 0, 1}}; // col ### 8-neighbour by scaning from top to bottom
const std::array<int, 8> di_{{0, 0, -1, 1, -1, 1, -1, 1}}; // row
const std::array<int, 8> dj_{{-1, 1, 0, 0, 1, -1, -1, 1}}; // col
std::map<int, int> child; // heirachy: key: child; val: parent
std::map<int, int> child; // heirachy: key: child; val: parent
int numberOfNeighbours = 8; // 4 or 8
bool empty_surroundingPixels =
true; // whether to set peripheral pixels to 0, to avoid potential
// influence for pedestal updating
std::unordered_map<int, Hit> h_size;
std::vector<Hit> hits;
// std::vector<std::vector<int16_t>> row
@@ -66,6 +71,16 @@ template <typename T> class VarClusterFinder {
void set_peripheralThresholdFactor(int factor) {
peripheralThresholdFactor_ = factor;
}
void set_numberOfNeighbours(int num) {
if (num == 4 || num == 8)
numberOfNeighbours = num;
else
throw std::runtime_error(
LOCATION + "number of neighbours should be either 4 or 8");
}
void set_empty_surroundingPixels(bool empty) {
empty_surroundingPixels = empty;
}
void find_clusters(NDView<T, 2> img);
void find_clusters_X(NDView<T, 2> img);
void rec_FillHit(int clusterIndex, int i, int j);
@@ -124,7 +139,7 @@ template <typename T> int VarClusterFinder<T>::check_neighbours(int i, int j) {
const auto row = i + di[k];
const auto col = j + dj[k];
if (row >= 0 && col >= 0 && row < shape_[0] && col < shape_[1]) {
auto tmp = labeled_.value(i + di[k], j + dj[k]);
auto tmp = labeled_(i + di[k], j + dj[k]);
if (tmp != 0)
neighbour_labels.push_back(tmp);
}
@@ -200,7 +215,7 @@ void VarClusterFinder<T>::rec_FillHit(int clusterIndex, int i, int j) {
}
original_(i, j) = 0;
for (int k = 0; k < 8; ++k) { // 8 for 8-neighbour
for (int k = 0; k < numberOfNeighbours; ++k) { //
const auto row = i + di_[k];
const auto col = j + dj_[k];
if (row >= 0 && col >= 0 && row < shape_[0] && col < shape_[1]) {
@@ -217,9 +232,11 @@ void VarClusterFinder<T>::rec_FillHit(int clusterIndex, int i, int j) {
// h_size[clusterIndex].enes[h_size[clusterIndex].size] =
// original_(row, col);
// }// ? weather to include peripheral pixels
original_(row, col) =
0; // remove peripheral pixels, to avoid potential influence
// for pedestal updating
if (empty_surroundingPixels) {
original_(row, col) =
0; // remove peripheral pixels, to avoid potential
// influence for pedestal updating
}
}
}
}
+16
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <aare/NDArray.hpp>
@@ -109,4 +110,19 @@ template <typename Container> bool all_equal(const Container &c) {
return false;
}
/**
* linear interpolation
* @param bin_edge left and right bin edges
* @param bin_values function values at bin edges
* @param coord coordinate to interpolate at
* @return interpolated value at coord
*/
inline double linear_interpolation(const std::pair<double, double> &bin_edge,
const std::pair<double, double> &bin_values,
const double coord) {
const double bin_width = bin_edge.second - bin_edge.first;
return bin_values.first * (1 - (coord - bin_edge.first) / bin_width) +
bin_values.second * (coord - bin_edge.first) / bin_width;
}
} // namespace aare
+1 -2
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/NDArray.hpp"
@@ -174,11 +175,9 @@ calculate_pedestal(NDView<uint16_t, 3> raw_data, ssize_t n_threads) {
count += cnt;
}
// Will move to a NDArray<T, 3 - static_cast<ssize_t>(only_gain0)>
// if only_gain0 is true
return safe_divide<T>(accumulator, count);
}
/**
+34 -1
View File
@@ -1,17 +1,50 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/defs.hpp"
#include <aare/NDView.hpp>
#include <cstdint>
#include <vector>
namespace aare {
uint16_t adc_sar_05_06_07_08decode64to16(uint64_t input);
uint16_t adc_sar_05_decode64to16(uint64_t input);
uint16_t adc_sar_04_decode64to16(uint64_t input);
void adc_sar_05_06_07_08decode64to16(NDView<uint64_t, 2> input,
NDView<uint16_t, 2> output);
void adc_sar_05_decode64to16(NDView<uint64_t, 2> input,
NDView<uint16_t, 2> output);
void adc_sar_04_decode64to16(NDView<uint64_t, 2> input,
NDView<uint16_t, 2> output);
/**
* @brief Called with a 32 bit unsigned integer, shift by offset
* and then return the lower 24 bits as an 32 bit integer
* @param input 32-ibt input value
* @param offset (should be in range 0-7 to allow for full 24 bits)
* @return uint32_t
*/
uint32_t mask32to24bits(uint32_t input, BitOffset offset = {});
/**
* @brief Expand 24 bit values in a 8bit buffer to 32bit unsigned integers
* Used for detectors with 24bit counters in combination with CTB
*
* @param input View of the 24 bit data as uint8_t (no 24bit native data type
* exists)
* @param output Destination of the expanded data (32bit, unsigned)
* @param offset Offset within the first byte to where the data starts (0-7
* bits)
*/
void expand24to32bit(NDView<const uint8_t, 1> input, NDView<uint32_t, 1> output,
BitOffset offset = {});
/**
* @brief expands the two 4 bit values of an 8 bit buffer into two 8 bit values
* @param input input buffer with 4 bit values packed into 8 bit
* @param output output buffer with 8 bit values
*/
void expand4to8bit(NDView<const uint8_t, 1> input, NDView<uint8_t, 1> output);
/**
* @brief Apply custom weights to a 16-bit input value. Will sum up
* weights[i]**i for each bit i that is set in the input value.
+206 -104
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/Dtype.hpp"
@@ -37,87 +38,6 @@ inline constexpr size_t bits_per_byte = 8;
void assert_failed(const std::string &msg);
class DynamicCluster {
public:
int cluster_sizeX;
int cluster_sizeY;
int16_t x;
int16_t y;
Dtype dt; // 4 bytes
private:
std::byte *m_data;
public:
DynamicCluster(int cluster_sizeX_, int cluster_sizeY_,
Dtype dt_ = Dtype(typeid(int32_t)))
: cluster_sizeX(cluster_sizeX_), cluster_sizeY(cluster_sizeY_),
dt(dt_) {
m_data = new std::byte[cluster_sizeX * cluster_sizeY * dt.bytes()]{};
}
DynamicCluster() : DynamicCluster(3, 3) {}
DynamicCluster(const DynamicCluster &other)
: DynamicCluster(other.cluster_sizeX, other.cluster_sizeY, other.dt) {
if (this == &other)
return;
x = other.x;
y = other.y;
memcpy(m_data, other.m_data, other.bytes());
}
DynamicCluster &operator=(const DynamicCluster &other) {
if (this == &other)
return *this;
this->~DynamicCluster();
new (this) DynamicCluster(other);
return *this;
}
DynamicCluster(DynamicCluster &&other) noexcept
: cluster_sizeX(other.cluster_sizeX),
cluster_sizeY(other.cluster_sizeY), x(other.x), y(other.y),
dt(other.dt), m_data(other.m_data) {
other.m_data = nullptr;
other.dt = Dtype(Dtype::TypeIndex::ERROR);
}
~DynamicCluster() { delete[] m_data; }
template <typename T> T get(int idx) {
(sizeof(T) == dt.bytes())
? 0
: throw std::invalid_argument("[ERROR] Type size mismatch");
return *reinterpret_cast<T *>(m_data + idx * dt.bytes());
}
template <typename T> auto set(int idx, T val) {
(sizeof(T) == dt.bytes())
? 0
: throw std::invalid_argument("[ERROR] Type size mismatch");
return memcpy(m_data + idx * dt.bytes(), &val, dt.bytes());
}
template <typename T> std::string to_string() const {
(sizeof(T) == dt.bytes())
? 0
: throw std::invalid_argument("[ERROR] Type size mismatch");
std::string s = "x: " + std::to_string(x) + " y: " + std::to_string(y) +
"\nm_data: [";
for (int i = 0; i < cluster_sizeX * cluster_sizeY; i++) {
s += std::to_string(
*reinterpret_cast<T *>(m_data + i * dt.bytes())) +
" ";
}
s += "]";
return s;
}
/**
* @brief size of the cluster in bytes when saved to a file
*/
size_t size() const { return cluster_sizeX * cluster_sizeY; }
size_t bytes() const { return cluster_sizeX * cluster_sizeY * dt.bytes(); }
auto begin() const { return m_data; }
auto end() const {
return m_data + cluster_sizeX * cluster_sizeY * dt.bytes();
}
std::byte *data() { return m_data; }
};
/**
* @brief header contained in parts of frames
*/
@@ -174,17 +94,55 @@ 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{};
/// @brief Chip specifications for Matterhorn1
struct Matterhorn10 {
constexpr static size_t nRows = 256;
constexpr static size_t nCols = 256;
};
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 Matterhorn2
struct Matterhorn02 {
constexpr static size_t nRows = 48;
constexpr static size_t nCols = 48;
constexpr static size_t nHalfCols = 24;
};
/// @brief Chip specifications for Moench04
struct Moench04 {
constexpr static size_t nRows = 400;
constexpr static size_t nCols = 400;
constexpr static std::array<int, 32>
adcNumbers =
{
9, 8, 11, 10, 13, 12, 15, 14, 1, 0, 3,
2, 5, 4, 7, 6, 23, 22, 21, 20, 19, 18,
17, 16, 31, 30, 29, 28, 27, 26, 25, 24}; // TODO : should we
// only have chip
// specifications or
// also wiring in
// chiptestboard?
constexpr static size_t nPixelsPerSuperColumn = 5000;
constexpr static size_t superColumnWidth = 25;
};
/// @brief Chip specifications for Moench05
struct Moench05 {
constexpr static size_t nRows = 160;
constexpr static size_t nCols =
150; // TODO: should probably be seperated for each adc
/// @brief used ADCs for moench given in relative numbers to the default
/// enabled blocks of 4 adcs in absolute adcs 9, 13, 1 are used
constexpr static std::array<int, 3> adcNumbers = {5, 9, 1};
};
enum ReadoutMode : uint8_t {
ANALOG_ONLY = 0,
DIGITAL_ONLY = 1,
ANALOG_AND_DIGITAL = 2,
TRANSCEIVER_ONLY = 3,
DIGITAL_AND_TRANSCEIVER = 4,
UNKNOWN = 5
};
using dynamic_shape = std::vector<ssize_t>;
@@ -215,22 +173,166 @@ enum class DetectorType {
Unknown
};
enum class TimingMode { Auto, Trigger };
/**
* @brief Enum class to define the Digital to Analog converter
* The values are the same as in slsDetectorPackage
*/
enum DACIndex {
DAC_0,
DAC_1,
DAC_2,
DAC_3,
DAC_4,
DAC_5,
DAC_6,
DAC_7,
DAC_8,
DAC_9,
DAC_10,
DAC_11,
DAC_12,
DAC_13,
DAC_14,
DAC_15,
DAC_16,
DAC_17,
VSVP,
VTRIM,
VRPREAMP,
VRSHAPER,
VSVN,
VTGSTV,
VCMP_LL,
VCMP_LR,
VCAL,
VCMP_RL,
RXB_RB,
RXB_LB,
VCMP_RR,
VCP,
VCN,
VISHAPER,
VTHRESHOLD,
IO_DELAY,
VREF_DS,
VOUT_CM,
VIN_CM,
VREF_COMP,
VB_COMP,
VDD_PROT,
VIN_COM,
VREF_PRECH,
VB_PIXBUF,
VB_DS,
VREF_H_ADC,
VB_COMP_FE,
VB_COMP_ADC,
VCOM_CDS,
VREF_RSTORE,
VB_OPA_1ST,
VREF_COMP_FE,
VCOM_ADC1,
VREF_L_ADC,
VREF_CDS,
VB_CS,
VB_OPA_FD,
VCOM_ADC2,
VCASSH,
VTH2,
VRSHAPER_N,
VIPRE_OUT,
VTH3,
VTH1,
VICIN,
VCAS,
VCAL_N,
VIPRE,
VCAL_P,
VDCSH,
VBP_COLBUF,
VB_SDA,
VCASC_SFP,
VIPRE_CDS,
IBIAS_SFP,
ADC_VPP,
HIGH_VOLTAGE,
TEMPERATURE_ADC,
TEMPERATURE_FPGA,
TEMPERATURE_FPGAEXT,
TEMPERATURE_10GE,
TEMPERATURE_DCDC,
TEMPERATURE_SODL,
TEMPERATURE_SODR,
TEMPERATURE_FPGA2,
TEMPERATURE_FPGA3,
TRIMBIT_SCAN,
V_POWER_A = 100,
V_POWER_B = 101,
V_POWER_C = 102,
V_POWER_D = 103,
V_POWER_IO = 104,
V_POWER_CHIP = 105,
I_POWER_A = 106,
I_POWER_B = 107,
I_POWER_C = 108,
I_POWER_D = 109,
I_POWER_IO = 110,
V_LIMIT = 111,
SLOW_ADC0 = 1000,
SLOW_ADC1,
SLOW_ADC2,
SLOW_ADC3,
SLOW_ADC4,
SLOW_ADC5,
SLOW_ADC6,
SLOW_ADC7,
SLOW_ADC_TEMP
};
// helper pair class to easily expose in python
template <typename T1, typename T2> struct Sum_index_pair {
T1 sum;
T2 index;
};
enum class corner : int {
cTopLeft = 0,
cTopRight = 1,
cBottomLeft = 2,
cBottomRight = 3
};
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 };
template <class T> T StringTo(const std::string &arg) { return T(arg); }
template <class T> std::string ToString(T arg) { return T(arg); }
template <> DetectorType StringTo(const std::string & /*name*/);
template <> std::string ToString(DetectorType arg);
template <> TimingMode StringTo(const std::string & /*mode*/);
template <> FrameDiscardPolicy StringTo(const std::string & /*mode*/);
using DataTypeVariants = std::variant<uint16_t, uint32_t>;
constexpr uint16_t ADC_MASK = 0x3FFF; // used to mask out the gain bits in Jungfrau
constexpr uint16_t ADC_MASK =
0x3FFF; // used to mask out the gain bits in Jungfrau
class BitOffset {
uint8_t m_offset{};
public:
BitOffset() = default;
explicit BitOffset(uint32_t offset);
uint8_t value() const { return m_offset; }
bool operator==(const BitOffset &other) const;
bool operator<(const BitOffset &other) const;
};
} // namespace aare
@@ -0,0 +1,154 @@
#pragma once
#include "aare/FastPedestal.hpp"
#include "aare/NDArray.hpp"
#include "aare/NDView.hpp"
#include "aare/Pedestal.hpp"
#include "aare/ProducerConsumerQueue.hpp"
#include "aare/hist/PixelHistogramImpl.hpp"
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <filesystem>
#include <memory>
#include <mutex>
#include <thread>
#include <vector>
namespace aare {
class PedestalTrackingPixelHistogram {
public:
using StorageType = uint16_t;
using AxisType = float; // TODO: template on pedestal type if needed
using FrameType = uint16_t;
private:
using Hist = PixelHistogramImpl<AxisType, StorageType>;
using AsyncQueue = ProducerConsumerQueue<NDArray<FrameType, 2>>;
// What kind of fan-out work the worker pool should currently do.
// Set under work_mutex_; read by worker_loop after wakeup.
enum class WorkKind { PushPedestal, UpdateMean, FillWithThreshold };
int rows_;
int cols_;
int n_threads_;
const AxisType xmin_;
const AxisType xmax_;
std::vector<int> row_offsets_;
std::vector<Hist> partial_hists_;
// Per-thread pedestal sized [local_rows x cols]. Indexed by the
// worker using the LOCAL row index (i.e. 0..row_count(t)-1), NOT the
// global row index. Owned exclusively by worker `t` during a
// dispatched fan-out.
std::vector<FastPedestal<AxisType>> partial_pedestals_;
std::vector<NDArray<AxisType, 2>> partial_std_; // cached for pedestal
// tracking
// Thread pool members
std::vector<std::thread> workers_;
std::mutex work_mutex_;
std::condition_variable work_cv_;
std::condition_variable done_cv_;
WorkKind current_work_kind_;
const NDView<FrameType, 2> *current_image_;
const std::vector<NDView<FrameType, 2>> *current_images_;
int completed_threads_;
std::atomic<bool> stop_workers_;
int work_generation_;
// Serialises all fan-outs: `push_pedestal_no_update`, `update_mean`,
// and the async coordinator's batch fill dispatches.
// Always the outermost lock; work_mutex_ is taken briefly inside it.
mutable std::mutex fill_mutex_;
// Serialises producers of async_queue_ (which is SPSC) and gives
// fill_from_file exclusive ownership of the ingestion path while its
// direct, double-buffered dispatch is active.
std::mutex ingestion_mutex_;
// Async producer/consumer pipeline. SPSC queue feeds the coordinator
// thread, which batches queued images before dispatching them.
std::unique_ptr<AsyncQueue> async_queue_;
std::thread coordinator_;
std::atomic<bool> stop_coordinator_{false};
std::atomic<bool> coordinator_busy_{false};
std::atomic<std::size_t> completed_async_fills_{0};
std::chrono::microseconds async_wait_{100};
std::size_t max_batch_size_;
std::atomic<AxisType> n_sigma_;
// Private worker thread method
void worker_loop(int thread_id);
void coordinator_loop();
int row_start(int thread_id) const;
int row_count(int thread_id) const;
// Sets up the work generation, wakes workers, and waits for them.
// Caller MUST already hold `fill_mutex_`. `image` may be nullptr
// for work kinds that don't need it (e.g. UpdateMean).
void dispatch_(WorkKind kind, const NDView<FrameType, 2> *image);
void dispatch_fill_batch_(const std::vector<NDView<FrameType, 2>> &images);
// Coordinator-facing entry point: takes fill_mutex_ and dispatches
// FillWithThreshold batches to the worker pool. Only ever called by the
// coordinator thread, on images already shape-checked by fill_async.
void fill_with_threshold_batch_(std::vector<NDArray<FrameType, 2>> &batch);
public:
PedestalTrackingPixelHistogram(int rows, int cols, int n_bins,
AxisType xmin, AxisType xmax,
int n_threads = 1,
std::size_t max_pending = 16,
AxisType n_sigma = 1.0);
~PedestalTrackingPixelHistogram();
void push_pedestal_no_update(const NDView<FrameType, 2> &frame);
void update_mean();
NDArray<AxisType, 2> pedestal_mean() const;
void fill_async(NDArray<FrameType, 2> &&image);
/**
* @brief Fill from ordered, parallel-read batches.
*
* After the first batch, reading batch N+1 overlaps histogram processing
* for batch N. Two fixed-capacity read buffers are allocated once and
* reused for the duration of the call.
*
* @param fname input file accepted by File
* @param max_frames maximum frames to process, or all frames for -1
* @param verbose print periodic progress information
* @param reader_threads number of MultiThreadedFileReader workers
* @param reader_chunk_size frames claimed per reader worker and batch
*/
void fill_from_file(const std::filesystem::path &fname,
ssize_t max_frames = -1, bool verbose = false,
std::size_t reader_threads = 2,
std::size_t reader_chunk_size = 4);
void process_pedestal_file(const std::filesystem::path &fname,
ssize_t max_frames = -1, bool verbose = false);
// Sigma multiplier for the pedestal-update gate in
// fill_async. Atomic; safe to read/write at any
// time (the new value takes effect on subsequent pixel evaluations).
PedestalTrackingPixelHistogram::AxisType n_sigma() const;
void set_n_sigma(PedestalTrackingPixelHistogram::AxisType n_sigma);
// Wait for all queued async fills to complete. Cheap when the queue
// is already drained.
void flush() const;
// Implicitly flushes pending async fills first so the snapshot is
// consistent with everything that was submitted up to the call.
NDArray<StorageType, 3> values() const;
NDArray<AxisType, 1> bin_centers() const;
NDArray<AxisType, 1> bin_edges() const;
};
} // namespace aare
+342
View File
@@ -0,0 +1,342 @@
#pragma once
#include "aare/NDArray.hpp"
#include "aare/NDView.hpp"
#include "aare/ProducerConsumerQueue.hpp"
#include "aare/hist/PixelHistogramImpl.hpp"
#include <algorithm>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <cstddef>
#include <cstdint>
#include <cstring>
#include <memory>
#include <mutex>
#include <stdexcept>
#include <thread>
#include <utility>
#include <vector>
namespace aare {
template <typename StorageType = uint16_t, typename AxisType = float>
class PixelHistogram {
private:
using Hist = PixelHistogramImpl<AxisType, StorageType>;
using AsyncQueue = ProducerConsumerQueue<NDArray<AxisType, 2>>;
int rows_;
int cols_;
int n_threads_;
const AxisType xmin_;
const AxisType xmax_;
std::vector<Hist> partial_hists_;
// Cumulative row offsets so that thread t owns rows
// [row_offsets_[t], row_offsets_[t + 1])
// Length is n_threads_ + 1; partition is balanced (the first
// rows_ % n_threads_ threads get one extra row each).
std::vector<int> row_offsets_;
// Thread pool members
std::vector<std::thread> workers_;
std::mutex work_mutex_;
std::condition_variable work_cv_;
std::condition_variable done_cv_;
const NDView<AxisType, 2> *current_image_;
int completed_threads_;
std::atomic<bool> stop_workers_;
int work_generation_;
// Async producer/consumer pipeline. SPSC queue feeds the coordinator
// thread, which fans each image out to the worker pool one at a time.
// TODO: batch processing?
// TODO: FIFO to avoid allocations?
std::unique_ptr<AsyncQueue> async_queue_;
std::thread coordinator_;
std::atomic<bool> stop_coordinator_{false};
std::atomic<bool> coordinator_busy_{false};
std::chrono::microseconds async_wait_{100};
// Private worker thread method
void worker_loop(int thread_id);
void coordinator_loop();
// Fan a single image out to the worker pool and block until every
// worker has merged its row band. Only ever called by the coordinator
// thread, so no caller-serialisation lock is needed.
void dispatch(const NDView<AxisType, 2> &image);
int row_start(int thread_id) const;
int row_count(int thread_id) const;
public:
PixelHistogram(int rows, int cols, int n_bins, AxisType xmin, AxisType xmax,
int n_threads = 1, std::size_t max_pending = 16);
~PixelHistogram();
// Asynchronous fill: takes ownership of `image`, enqueues it for the
// coordinator thread, and returns. Blocks the caller only if the queue
// is full (single-producer, single-consumer queue with a sleep-poll
// backpressure loop, matching the convention in ClusterFinderMT).
void fill_async(NDArray<AxisType, 2> &&image);
// Wait for all queued async fills to complete. Cheap when the queue
// is already drained.
void flush() const;
// Implicitly flushes pending async fills first so the snapshot is
// consistent with everything that was submitted up to the call.
NDArray<StorageType, 3> values() const;
NDArray<AxisType, 1> bin_centers() const;
NDArray<AxisType, 1> bin_edges() const;
};
template <typename StorageType, typename AxisType>
PixelHistogram<StorageType, AxisType>::PixelHistogram(int rows, int cols,
int n_bins, AxisType xmin,
AxisType xmax,
int n_threads,
std::size_t max_pending)
: rows_(rows), cols_(cols), n_threads_(n_threads), xmin_(xmin), xmax_(xmax),
current_image_(nullptr), completed_threads_(0), stop_workers_(false),
work_generation_(0) {
if (rows_ < 1 || cols_ < 1 || n_bins < 1) {
throw std::invalid_argument(
"PixelHistogram requires positive rows, cols and bins");
}
if (n_threads < 1) {
throw std::invalid_argument(
"PixelHistogram requires at least one thread");
}
if (max_pending < 1) {
throw std::invalid_argument("PixelHistogram requires max_pending >= 1");
}
n_threads_ = std::min(n_threads_, rows_);
// Build a balanced row partition. With base = rows_ / n_threads_ and
// extra = rows_ % n_threads_, the first `extra` threads get base + 1
// rows each and the rest get `base` rows. This avoids the
// ceil(rows/n_threads) scheme leaving trailing threads with zero or
// negative row counts (e.g. rows=17, n_threads=8).
row_offsets_.resize(n_threads_ + 1);
const int base = rows_ / n_threads_;
const int extra = rows_ % n_threads_;
int offset = 0;
for (int i = 0; i < n_threads_; ++i) {
row_offsets_[i] = offset;
offset += base + (i < extra ? 1 : 0);
}
row_offsets_[n_threads_] = offset; // == rows_ by construction
// Initialize partial histograms for each thread
partial_hists_.reserve(n_threads_);
for (int i = 0; i < n_threads_; ++i) {
const auto local_rows = row_count(i);
partial_hists_.emplace_back(local_rows, cols, n_bins, xmin, xmax);
}
// Spawn worker threads
for (int i = 0; i < n_threads_; ++i) {
workers_.emplace_back([this, i]() { this->worker_loop(i); });
}
// Async pipeline. The PCQ holds (size - 1) usable slots, so size up by
// one to honour the requested max_pending.
async_queue_ = std::make_unique<AsyncQueue>(
static_cast<std::uint32_t>(max_pending + 1));
coordinator_ = std::thread([this]() { this->coordinator_loop(); });
}
template <typename StorageType, typename AxisType>
PixelHistogram<StorageType, AxisType>::~PixelHistogram() {
// Drain any pending async fills before tearing down the worker pool.
// The coordinator's loop keeps processing while stop_coordinator_ is
// true as long as the queue is non-empty (mirrors ClusterFinderMT).
if (coordinator_.joinable()) {
stop_coordinator_ = true;
coordinator_.join();
}
// Signal all workers to stop
{
std::unique_lock<std::mutex> lock(work_mutex_);
stop_workers_ = true;
}
work_cv_.notify_all();
// Join all worker threads
for (auto &thread : workers_) {
if (thread.joinable()) {
thread.join();
}
}
}
template <typename StorageType, typename AxisType>
int PixelHistogram<StorageType, AxisType>::row_start(int thread_id) const {
return row_offsets_[thread_id];
}
template <typename StorageType, typename AxisType>
int PixelHistogram<StorageType, AxisType>::row_count(int thread_id) const {
return row_offsets_[thread_id + 1] - row_offsets_[thread_id];
}
template <typename StorageType, typename AxisType>
void PixelHistogram<StorageType, AxisType>::worker_loop(int thread_id) {
int last_generation = 0;
while (true) {
std::unique_lock<std::mutex> lock(work_mutex_);
work_cv_.wait(lock, [this, last_generation]() {
return work_generation_ != last_generation || stop_workers_;
});
if (stop_workers_) {
break;
}
// Get work assignment
const NDView<AxisType, 2> &image = *current_image_;
const int generation = work_generation_;
const int first_row = row_start(thread_id);
const int local_rows = row_count(thread_id);
lock.unlock();
// Do the work: fill this thread's partial histogram. The
// [xmin, xmax) range gate lives inside PixelHistogramImpl::fill.
auto &my_hist = partial_hists_[thread_id];
const auto cols = image.shape(1);
for (int local_row = 0; local_row < local_rows; ++local_row) {
const auto row = static_cast<ssize_t>(first_row + local_row);
for (ssize_t col = 0; col < cols; ++col) {
const auto val = image(row, col);
my_hist.fill_unchecked(local_row, static_cast<int>(col), val);
}
}
// Signal completion
{
std::unique_lock<std::mutex> done_lock(work_mutex_);
last_generation = generation;
completed_threads_++;
if (completed_threads_ == n_threads_) {
done_cv_.notify_one();
}
}
}
}
template <typename StorageType, typename AxisType>
NDArray<StorageType, 3> PixelHistogram<StorageType, AxisType>::values() const {
// Make sure any pending async fills are merged in before we snapshot
// the partial histograms. Cheap when the queue is already drained.
flush();
const auto first_shard_view = partial_hists_.front().view();
const auto cols = static_cast<ssize_t>(first_shard_view.shape(1));
const auto bins = static_cast<ssize_t>(first_shard_view.shape(2));
const auto rows = static_cast<ssize_t>(rows_);
NDArray<StorageType, 3> data({rows, cols, bins});
// Each thread owns a disjoint, contiguous range of rows. The shard's
// dense storage layout [local_row][col][bin] is identical to the slice
// [first_row .. first_row + local_rows)[col][bin] of `data`, so the
// merge is just one bulk copy per thread; no per-element accumulation
// and no upfront zeroing of `data` is needed.
const size_t pixel_stride = static_cast<size_t>(cols) * bins;
for (int t = 0; t < n_threads_; ++t) {
const auto first_row = static_cast<size_t>(row_start(t));
const auto local_rows = static_cast<size_t>(row_count(t));
if (local_rows == 0)
continue;
const auto shard_view = partial_hists_[t].view();
std::memcpy(data.data() + first_row * pixel_stride, shard_view.data(),
local_rows * pixel_stride * sizeof(StorageType));
}
return data;
}
template <typename StorageType, typename AxisType>
void PixelHistogram<StorageType, AxisType>::dispatch(
const NDView<AxisType, 2> &image) {
// Called only by the coordinator thread on images already shape-checked
// by fill_async, so there is no need to re-validate or to serialise
// against other callers.
// Reset counters and set work
{
std::unique_lock<std::mutex> lock(work_mutex_);
completed_threads_ = 0;
current_image_ = &image;
++work_generation_;
}
// Signal all worker threads to start
work_cv_.notify_all();
// Wait for all workers to complete
{
std::unique_lock<std::mutex> lock(work_mutex_);
done_cv_.wait(lock,
[this]() { return completed_threads_ == n_threads_; });
current_image_ = nullptr; // Clear work assignment
}
}
template <typename StorageType, typename AxisType>
void PixelHistogram<StorageType, AxisType>::fill_async(
NDArray<AxisType, 2> &&image) {
if (image.shape(0) != rows_ || image.shape(1) != cols_) {
throw std::invalid_argument(
"PixelHistogram image shape does not match constructor shape");
}
// SPSC backpressure: spin with a short sleep until a slot frees up.
// The std::move only consumes `image` on the iteration that succeeds
// (placement-new inside write() runs only when the slot is free).
while (!async_queue_->write(std::move(image))) {
std::this_thread::sleep_for(async_wait_);
}
}
template <typename StorageType, typename AxisType>
void PixelHistogram<StorageType, AxisType>::flush() const {
while (!async_queue_->isEmpty() ||
coordinator_busy_.load(std::memory_order_acquire)) {
std::this_thread::sleep_for(async_wait_);
}
}
template <typename StorageType, typename AxisType>
void PixelHistogram<StorageType, AxisType>::coordinator_loop() {
NDArray<AxisType, 2> item;
while (!stop_coordinator_.load(std::memory_order_acquire) ||
!async_queue_->isEmpty()) {
if (async_queue_->read(item)) {
coordinator_busy_.store(true, std::memory_order_release);
dispatch(item.view());
coordinator_busy_.store(false, std::memory_order_release);
} else {
std::this_thread::sleep_for(async_wait_);
}
}
}
template <typename StorageType, typename AxisType>
NDArray<AxisType, 1>
PixelHistogram<StorageType, AxisType>::bin_centers() const {
// All shards share the same value-axis configuration, so any one will
// do; pick the first.
return partial_hists_.front().bin_centers();
}
template <typename StorageType, typename AxisType>
NDArray<AxisType, 1> PixelHistogram<StorageType, AxisType>::bin_edges() const {
return partial_hists_.front().bin_edges();
}
} // namespace aare
+154
View File
@@ -0,0 +1,154 @@
#pragma once
/*
Basic pixel histogram class with templated axis and storage type.
row, col are integers and the per pixel histogram axis is AxisType.
Bin policy: regular binning on [xmin, xmax). Values outside this range are
silently dropped.
*/
#include "aare/NDArray.hpp"
#include "aare/NDView.hpp"
#include <algorithm>
#include <cstddef>
#include <limits>
#include <stdexcept>
#include <type_traits>
namespace aare {
template <typename T, typename StorageType> class PixelHistogramImpl {
static_assert(std::is_floating_point_v<T>,
"PixelHistogramImpl requires a floating-point axis type");
NDArray<StorageType, 3> m_values;
NDArray<T, 1> m_edges;
int m_rows;
int m_cols;
int m_n_bins;
T m_xmin;
T m_xmax;
// n_bins / (xmax - xmin), precomputed to keep the hot path
// division-free.
T m_scale;
public:
PixelHistogramImpl(int rows, int cols, int n_bins, T xmin, T xmax);
void fill(const NDView<T, 2> &frame);
void fill(int row, int col, T value);
void fill_unchecked(int row, int col, T value);
// Fill using a row-major pixel index, avoiding repeated 3D stride
// calculation in tiled worker loops. The index is intentionally unchecked.
void fill_flat_unchecked(std::size_t pixel, T value);
NDArray<StorageType, 3> values() const;
// Zero-copy view of the underlying [rows x cols x n_bins] storage.
// Lifetime is tied to *this. Use for low-level merge/stitching paths;
// prefer values() for the public API where you want an owned copy.
NDView<const StorageType, 3> view() const;
NDArray<T, 1> bin_centers() const;
NDArray<T, 1> bin_edges() const;
};
template <typename T, typename StorageType>
PixelHistogramImpl<T, StorageType>::PixelHistogramImpl(int rows, int cols,
int n_bins, T xmin,
T xmax)
: m_values(NDArray<StorageType, 3>({static_cast<ssize_t>(rows),
static_cast<ssize_t>(cols),
static_cast<ssize_t>(n_bins)},
StorageType{0})),
m_edges(NDArray<T, 1>({static_cast<ssize_t>(n_bins + 1)})), m_rows(rows),
m_cols(cols), m_n_bins(n_bins), m_xmin(xmin), m_xmax(xmax),
m_scale(static_cast<T>(n_bins) / (xmax - xmin)) {
if (rows < 1 || cols < 1 || n_bins < 1) {
throw std::invalid_argument(
"PixelHistogramImpl requires positive rows, cols and bins");
}
if (!(xmax > xmin)) {
throw std::invalid_argument("PixelHistogramImpl requires xmax > xmin");
}
const T range = xmax - xmin;
for (int i = 0; i <= n_bins; ++i) {
m_edges(i) =
xmin + (static_cast<T>(i) * range) / static_cast<T>(n_bins);
}
}
template <typename T, typename StorageType>
void PixelHistogramImpl<T, StorageType>::fill(const NDView<T, 2> &frame) {
if (frame.shape(0) != m_rows || frame.shape(1) != m_cols) {
throw std::invalid_argument(
"PixelHistogramImpl::fill: frame shape does not match histogram");
}
for (int row = 0; row < m_rows; ++row) {
for (int col = 0; col < m_cols; ++col) {
fill_unchecked(row, col, frame(row, col));
}
}
}
template <typename T, typename StorageType>
void PixelHistogramImpl<T, StorageType>::fill(int row, int col, T value) {
if (row < 0 || row >= m_rows || col < 0 || col >= m_cols) {
throw std::out_of_range(
"PixelHistogramImpl::fill: row or col out of range");
}
fill_unchecked(row, col, value);
}
template <typename T, typename StorageType>
void PixelHistogramImpl<T, StorageType>::fill_unchecked(int row, int col,
T value) {
const auto pixel =
static_cast<std::size_t>(row) * static_cast<std::size_t>(m_cols) +
static_cast<std::size_t>(col);
fill_flat_unchecked(pixel, value);
}
template <typename T, typename StorageType>
void PixelHistogramImpl<T, StorageType>::fill_flat_unchecked(std::size_t pixel,
T value) {
if (value < m_xmin || value >= m_xmax) {
return;
}
int bin = static_cast<int>((value - m_xmin) * m_scale);
// Guard against floating-point rounding pushing val just below
bin = std::clamp(bin, 0, m_n_bins - 1);
auto &cell = m_values.data()[pixel * static_cast<std::size_t>(m_n_bins) +
static_cast<std::size_t>(bin)];
if constexpr (std::is_integral_v<StorageType>) {
if (cell >= std::numeric_limits<StorageType>::max()) {
return;
}
}
++cell;
}
template <typename T, typename StorageType>
NDArray<StorageType, 3> PixelHistogramImpl<T, StorageType>::values() const {
return m_values;
}
template <typename T, typename StorageType>
NDView<const StorageType, 3> PixelHistogramImpl<T, StorageType>::view() const {
return m_values.view();
}
template <typename T, typename StorageType>
NDArray<T, 1> PixelHistogramImpl<T, StorageType>::bin_centers() const {
NDArray<T, 1> centers({static_cast<ssize_t>(m_n_bins)});
for (int i = 0; i < m_n_bins; ++i) {
centers(i) = (m_edges(i) + m_edges(i + 1)) / T(2);
}
return centers;
}
template <typename T, typename StorageType>
NDArray<T, 1> PixelHistogramImpl<T, StorageType>::bin_edges() const {
return m_edges;
}
} // namespace aare
+4 -3
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
/*Utility to log to console*/
@@ -66,7 +67,7 @@ class Logger {
public:
Logger() = default;
explicit Logger(TLogLevel level) : m_level(level){};
explicit Logger(TLogLevel level) : m_level(level) {};
~Logger() {
// output in the destructor to allow for << syntax
os << RESET << '\n';
@@ -105,8 +106,8 @@ class Logger {
}
std::ostringstream &Get() {
os << Color(m_level) << "- " << Timestamp() << " " << ToString(m_level)
<< ": ";
os << Color(m_level) << "- " << Timestamp() << " "
<< Logger::ToString(m_level) << ": ";
return os;
}
+98
View File
@@ -0,0 +1,98 @@
// SPDX-License-Identifier: MPL-2.0
/*
*The file to_string.hpp contains conversion to and from string for various aare
* types. It is intentionally not a part of the public API.
* Only include the conversion that are actually needed!!!
*/
#include "aare/defs.hpp" //enums
#include <chrono> //time conversions
namespace aare {
std::string remove_unit(std::string &str);
template <typename T>
T string_to(const std::string &t, const std::string &unit) {
double tval{0};
try {
tval = std::stod(t);
} catch (const std::invalid_argument &e) {
throw std::runtime_error("Could not convert string to time");
}
using std::chrono::duration;
using std::chrono::duration_cast;
if (unit == "ns") {
return duration_cast<T>(duration<double, std::nano>(tval));
} else if (unit == "us") {
return duration_cast<T>(duration<double, std::micro>(tval));
} else if (unit == "ms") {
return duration_cast<T>(duration<double, std::milli>(tval));
} else if (unit == "s" || unit.empty()) {
return duration_cast<T>(std::chrono::duration<double>(tval));
} else {
throw std::runtime_error(
"Invalid unit in conversion from string to std::chrono::duration");
}
}
// if T has a constructor that takes a string, lets use it.
// template <class T> T string_to(const std::string &arg) { return T{arg}; }
template <typename T> T string_to(const std::string &arg) {
std::string tmp{arg};
auto unit = remove_unit(tmp);
return string_to<T>(tmp, unit);
}
/**
* @brief Convert a string to DetectorType
* @param name string representation of the DetectorType
* @return DetectorType
* @throw runtime_error if the string does not match any DetectorType
*/
template <> DetectorType string_to(const std::string &arg);
/**
* @brief Convert a string to UDPPortPosition
* @param name string representation of the UDPPortPosition
* @return UDPPortPosition
* @throw runtime_error if the string does not match any UDPPortPosition
*/
template <> UDPPortPosition string_to(const std::string &arg);
/**
* @brief Convert a string to TimingMode
* @param mode string representation of the TimingMode
* @return TimingMode
* @throw runtime_error if the string does not match any TimingMode
*/
template <> TimingMode string_to(const std::string &arg);
/**
* @brief Convert a string to FrameDiscardPolicy
* @param mode string representation of the FrameDiscardPolicy
* @return FrameDiscardPolicy
* @throw runtime_error if the string does not match any FrameDiscardPolicy
*/
template <> FrameDiscardPolicy string_to(const std::string &arg);
/**
* @brief Convert a string to a DACIndex
* @param arg string representation of the dacIndex
* @return DACIndex
* @throw invalid argument error if the string does not match any DACIndex
*/
template <> DACIndex string_to(const std::string &arg);
/**
* @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
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <fstream>
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include <cstddef>
namespace aare {
/**
* @brief Compute the ceiling of the integer division of n by d.
* @param n The numerator.
* @param d The denominator.
* @return The ceiling of the integer division.
*/
constexpr size_t ceil_div(size_t n, size_t d) { return n / d + (n % d != 0); }
} // namespace aare
+4 -4
View File
@@ -1,10 +1,11 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include "aare/NDView.hpp"
#include "aare/utils/task.hpp"
#include <thread>
#include <utility>
#include <vector>
#include "aare/utils/task.hpp"
namespace aare {
template <typename F>
@@ -19,9 +20,8 @@ void RunInParallel(F func, const std::vector<std::pair<int, int>> &tasks) {
}
}
template <typename T>
std::vector<NDView<T,3>> make_subviews(NDView<T, 3> &data, ssize_t n_threads) {
std::vector<NDView<T, 3>> make_subviews(NDView<T, 3> &data, ssize_t n_threads) {
std::vector<NDView<T, 3>> subviews;
subviews.reserve(n_threads);
auto limits = split_task(0, data.shape(0), n_threads);
+1
View File
@@ -1,3 +1,4 @@
// SPDX-License-Identifier: MPL-2.0
#pragma once
#include <utility>
#include <vector>