rc179: everything on rc178 after its merge into main (#88), except the CHANGELOG
The rc178 branch continued after #88 was squash-merged; this is its content fromb9ada7914(the tree #88 squashed) to094eee31a, as one change on main. The individual commits stay on the rc178 branch: - still battery: --cold evicts each set's input from the page cache; Alvra pixel masks; manifest fixes - AGIPD: converter to one rigid panel per module, int16 photons, mask folded in; still battery reads the converted sets - DetectorModules: panel look-up by id, plane -> panel, plane bounds and a per-pixel walk; mask size checked - tests: [PanelLayout] equivalence harness, stacked vs assembled panel layout - Dense per-pixel maps through the panel table (panel layout stage 1) - Panel id on spots and the panel table in the start message - Viewer and preview show a panel detector as it lies on the detector plane - Panel layout stage 3: per-panel spot finding (CPU+GPU, CCL) and raster algorithms on the plane raster - Panel layout stage 2: prediction and Bragg integration through the panel table - XTC reader: frames handed up as stored, streams indexed in parallel - XFEL reader: integer frames stay integer, one gain, placement by panel - EXTERNAL_TEST_DATA_STILLS.md: images used vs the entry for every set; drop "Not in the battery" - still battery: EuXFEL sets read the depositors' Cheetah CXI files directly; AGIPD converter removed - float32_to_int16.py: a non-finite pixel becomes -32768, the int16 error marker, not a zero count - CrystFEL geometry: read the pixel masks and bad regions instead of ignoring them - Panel layout stage 5: the XFEL reader hands up the stored frame and its panel table - Panel table persisted in NXmx; modulation grid and pre-scan memo key on the plane - still battery: Alvra sets take their pixel mask from the CrystFEL geometry, not --mask-good - still battery: take the deposited model as mmCIF where the RCSB has no PDB-format file - still battery: dimple gets PDB-format coordinates converted from an mmCIF-only deposition - stills fixed cost: geometry refinement and pre-scan do the same work in less wall time - stills geometry sample and trial spot finding run as many workers as the image pass - Stills integration: background ring reach measured on empty apertures, radial curvature from the whole frame - StillsPartialityRefine: the partiality width is the run's, measured on the crystals, not the prediction window's - MergeOnTheFly: capture term and multiplicative outlier band for the stills merge (both opt-in) - Stills given a cell: the written cell is the mean over the frames that are merged - Stills: the radial curvature correction decided per run on the same empty apertures - StillsPartialityRefine: measure the run width only on shells with signal - Stills pre-scan: report the paired z of the radial-correction comparison - module placement: the five concurrent fits each keep every thread - still battery: score R-free against the deposited data through the same dimple protocol - still battery: the R-free target is the lower of the deposition's dimple and published values - Stills: background clip follows the radial curve; signal disk from the lattice spacing - Stills keep an overloaded observation as a lower bound instead of dropping it - Stills: drop the lattice-spacing signal disk; the correction decision back on the plain clip - battery: R-free against the deposition without refinement only, one protocol for rotation and stills - still battery: EuXFEL sets run on a 2,000-image subset for now - stills geometry refinement: fit the detector distance and the cell together - stills geometry refinement: a distance given with --detector-distance is held in the joint fit - Metal integration engine: back to its panel-s5 kernels; Mac stills keep the old clip, no saturation count - Metal integration test: the CPU comparison runs on a rotation experiment - Stills: kept overloads go back to the drop where they are not concentrated at low resolution - stills distance search: an absolute 30-3000 mm scan, a sample found without d-limits, the fit iterated - battery results: XFEL still battery 20261022-1358 on rc1780cf62452c- 12 sets, cold, R_free unrefined - battery results: still summary gains the resolution of our merge and of the deposition - Pre-scan masks a pixel at the saturation limit on most frames, as one holding the error value - Stills keep an overload as a lower bound only where it has pixels at the limit; run-level gate removed - XFEL reader: a per-frame mask is read the way the frames are, its chunk inflated outside the HDF5 lock - stills distance search: every centre scanned with a wider acceptance, a larger sample where nothing indexes - rugnux usage: --beam-center-check describes the absolute 30-3000 mm stills distance scan, not the old 60-160 % grid - stills: detector tilt refined in the geometry pre-pass, kept where held-out frames agree - CLAUDE.md: the changelog is written once, just before the merge into main - condensed one-liners of what users get - broker: serve the placed model and its maps of the last rugnux live run (/rugnux/model.cif, /rugnux/map.ccp4) - frontend: Mol* viewer of the placed model and its density on the Rugnux live page - writer: _model.cif from rugnux live keeps the input model's metadata, as the served model.cif does - rugnux live maps: one unit cell centred on the model; the viewer opens on all of it - Anomalous difference map: ANOM/PHANOM in _maps.mtz, /rugnux/map.ccp4?type=anom, a magenta mesh in the viewer - Mol* viewer: open with the maps drawn within 10 A of the centre of view - Mol* viewer: aaredb's structure-viewer setup, on a black stage - rugnux: the gain of a stills file that states none is read off its single-photon peak where the background resolves photons - Mol* viewer: in line with AareDB's StructureView at its current head (8ece2c2) - ACKNOWLEDGEMENT: the web frontend's Mol* viewer follows AareDB's setup (G. Gotthard, PSI) - stills tilt decision: the modules stay where the run placed them - still battery: no distance pins and no per-set tuning flags; gain from the data except where a file's baseline hides it - battery results: rc178 6f6f69 - full still battery and full rotation battery with REFMAC - Bragg integration: a CCD rotation sweep's sigmas at the measured gain, intensities in photons - BackgroundGain: the gain of a frame that resolves photons is the spacing of its photon peaks, so a baseline left in the frame no longer hides it - ShadowFinder: measure the background's azimuthal modulation instead of predicting it from the polarization - BackgroundGain: one gain estimate for rotation and stills; the still battery no longer gives EuXFEL 152 its gain - ShadowFinder: measure the modulation robustly under a wide one-sided shadow - ShadowFinderTest: a one-sided shadow is not fitted as part of the background's modulation - ShadowFinder: back to the predicted polarization factor, in the plane the background shows - MXAnalysisAfterFPGA: the Bragg engine's edge mask in the image's layout, so raw / untransformed FPGA runs start again - battery results: still battery on rc178 e54f55 replaces the earlier rc178 still tables - XFELReader: per-frame mask and photon conversion without a library call or a branch per pixel - stills geometry trial: the hypotheses a search asks are indexed side by side - stills tilt decision: the fits start beside the pre-scan and the geometry trial - XFELReader: a deflated frame is inflated and converted a piece at a time, while it is in the cache - XFELReader: a byte-shuffled frame is unshuffled a piece at a time, a whole pixel per step - GeometryRefiner: residuals carry only the blocks a fit moves; beam and distance one block - GeometryRefiner: a spot's residual differentiates its observed and predicted halves apart - docs: EXTERNAL_TEST_DATA lists every open-arm battery set, with corrected values and counts - battery: doc_check.py cross-checks the manifests against the dataset pages - stills module placement: the placement fit gets half the threads, each held-out fit an eighth - still battery: the EuXFEL sets run on all their frames, as the published still runs did - battery results: still battery on rc178 a0ce6c, cold on a quiet machine, replaces the earlier rc178 table - macOS build: explicit size_t in the XFEL reader's row bounds; parentheses in the CPU preprocessor's select Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_015CeEGgpKdfkCTJb3YNMJcu
This commit is contained in:
1 parent
afbe844b20
commit
0a515bb086
218 files changed
+55733
-1764
No files matched your search
+437
-169
@@ -7,6 +7,8 @@
|
||||
#include <algorithm>
|
||||
#include <climits>
|
||||
#include <cmath>
|
||||
#include <type_traits>
|
||||
#include <limits>
|
||||
#include <cstring>
|
||||
#include <filesystem>
|
||||
#include <numeric>
|
||||
@@ -16,6 +18,7 @@
|
||||
#include "../common/JFJochException.h"
|
||||
#include "../common/Logger.h"
|
||||
#include "../writer/HDF5Objects.h"
|
||||
#include "../compression/JFJochDecompress.h"
|
||||
|
||||
namespace {
|
||||
|
||||
@@ -58,6 +61,33 @@ void Accumulate(HDF5ReadOnlyFile &file, const std::string &path, const std::vect
|
||||
mean.Add(v);
|
||||
}
|
||||
|
||||
// b where use_b, otherwise a - as arithmetic rather than a branch, which the compiler would move the work
|
||||
// computing a into, and then not vectorise the loop over the pixels.
|
||||
int32_t Pick(bool use_b, int32_t a, int32_t b) {
|
||||
const int32_t all = -static_cast<int32_t>(use_b);
|
||||
return (a & ~all) | (b & all);
|
||||
}
|
||||
|
||||
// Pixels are decoded and converted a piece at a time where they can be (ReadStored): a piece fits the core's
|
||||
// own cache with the window inflate keeps, so it is converted before it leaves.
|
||||
constexpr size_t PIECE_BYTES = 128 * 1024;
|
||||
|
||||
// The pixels [first, first + count) of a byte-shuffled frame of n pixels of size bytes each (byte b of pixel
|
||||
// i is shuffled[b * n + i]), into out as stored: 2 or 4 bytes (plain_type), little-endian, as the frames are read.
|
||||
void Unshuffle(const uint8_t *shuffled, size_t n, size_t size, size_t first, size_t count, uint8_t *out) {
|
||||
const uint8_t *b0 = shuffled + first, *b1 = b0 + n;
|
||||
if (size == 2) {
|
||||
auto *o = reinterpret_cast<uint16_t *>(out);
|
||||
for (size_t i = 0; i < count; i++)
|
||||
o[i] = static_cast<uint16_t>(b0[i] | b1[i] << 8);
|
||||
} else {
|
||||
const uint8_t *b2 = b1 + n, *b3 = b2 + n;
|
||||
auto *o = reinterpret_cast<uint32_t *>(out);
|
||||
for (size_t i = 0; i < count; i++)
|
||||
o[i] = b0[i] | b1[i] << 8 | b2[i] << 16 | static_cast<uint32_t>(b3[i]) << 24;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
JFJochXFELReader::JFJochXFELReader() = default;
|
||||
@@ -135,31 +165,36 @@ void JFJochXFELReader::ReadFiles(const std::vector<std::string> &files, const st
|
||||
std::string list;
|
||||
for (const auto &key: ignored)
|
||||
list += (list.empty() ? "" : ", ") + key;
|
||||
Logger("XFELReader").Info("{}: only the module geometry (and camera length) is taken; ignored: {}",
|
||||
Logger("XFELReader").Info("{}: the module geometry, camera length and masks are taken; ignored: {}",
|
||||
geometry_file, list);
|
||||
}
|
||||
Logger("XFELReader").Info("{}: {} mask array(s), {} bad region(s)", geometry_file, geom_.masks.size(),
|
||||
geom_.bad.size());
|
||||
|
||||
// What the geometry file no longer states comes from the data files themselves, where they are one of
|
||||
// What the geometry file does not state comes from the data files themselves, where they are one of
|
||||
// the layouts this reader knows: a Cheetah CXI file (photon energy, camera length, the shared mask
|
||||
// and the per-shot one) or a SACLA Cheetah file (photon energy per shot, camera length, pixel mask).
|
||||
// Otherwise the photon energy is the command line's to give, and the camera length too where the
|
||||
// geometry has none.
|
||||
// The file's own masks are taken only where the geometry names none: a geometry that does names the
|
||||
// mask arrays with the bits that matter for this detector. Otherwise the photon energy is the
|
||||
// command line's to give, and the camera length too where the geometry has none.
|
||||
{
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
HDF5ReadOnlyFile file(files[0]);
|
||||
const bool file_masks = geom_.masks.empty();
|
||||
if (file.Exists(CXI_DATA)) {
|
||||
if (file.Exists("/entry_1/instrument_1/source_1/energy"))
|
||||
geom_.photon_energy = xfel::Value{"/entry_1/instrument_1/source_1/energy", 0, 1.0 / JOULE_PER_EV};
|
||||
if (file.Exists(CXI_DETECTOR + "mask_shared"))
|
||||
if (file_masks && file.Exists(CXI_DETECTOR + "mask_shared"))
|
||||
geom_.masks.push_back({CXI_DETECTOR + "mask_shared", "", 0, CHEETAH_BAD_BITS});
|
||||
if (file.Exists("/entry_1/data_1/mask"))
|
||||
if (file_masks && file.Exists("/entry_1/data_1/mask"))
|
||||
geom_.masks.push_back({"/entry_1/data_1/mask", "", 0, CHEETAH_BAD_BITS});
|
||||
if (!geom_.panels[0].clen && file.Exists(CXI_DETECTOR + "distance"))
|
||||
for (auto &p: geom_.panels)
|
||||
p.clen = xfel::Value{CXI_DETECTOR + "distance", 0, 1.0};
|
||||
} else if (file.Exists("/metadata/distance_in_mm")) {
|
||||
geom_.photon_energy = xfel::Value{"/%/photon_energy_ev", 0, 1.0};
|
||||
geom_.masks.push_back({"/metadata/pixelmask", "", 0, 0xffffffffu});
|
||||
if (file_masks)
|
||||
geom_.masks.push_back({"/metadata/pixelmask", "", 0, 0xffffffffu});
|
||||
if (!geom_.panels[0].clen)
|
||||
for (auto &p: geom_.panels)
|
||||
p.clen = xfel::Value{"/metadata/distance_in_mm", 0, 1e-3};
|
||||
@@ -407,15 +442,38 @@ JFJochXFELReader::Layout JFJochXFELReader::ReadLayout(HDF5ReadOnlyFile &file, co
|
||||
l.stored_size = H5Tget_size(type);
|
||||
l.stored_float = H5Tget_class(type) == H5T_FLOAT;
|
||||
l.stored_signed = H5Tget_sign(type) == H5T_SGN_2;
|
||||
ok &= ((H5Tget_class(type) == H5T_INTEGER && (l.stored_size == 2 || l.stored_size == 4))
|
||||
|| (l.stored_float && l.stored_size == 4))
|
||||
&& H5Tget_order(type) == H5T_ORDER_LE;
|
||||
l.plain_type = ((H5Tget_class(type) == H5T_INTEGER && (l.stored_size == 2 || l.stored_size == 4))
|
||||
|| (l.stored_float && l.stored_size == 4))
|
||||
&& H5Tget_order(type) == H5T_ORDER_LE;
|
||||
ok &= l.plain_type;
|
||||
H5Tclose(type);
|
||||
l.deflated = deflate;
|
||||
l.direct_chunks = ok && (deflate || (bitshuffle && l.algorithm != CompressionAlgorithm::NO_COMPRESSION));
|
||||
return l;
|
||||
}
|
||||
|
||||
// A per-frame mask is read as the frames are where it is stored in plain unsigned integers - read as
|
||||
// stored, they are what HDF5 would convert them to - of the frame's size, in every file the way the
|
||||
// first file stores it. Any other is read by HDF5.
|
||||
JFJochXFELReader::Layout JFJochXFELReader::FrameMaskLayout(const xfel::Mask &m) const {
|
||||
Layout layout;
|
||||
for (size_t i = 0; i < frames_.size(); i++) {
|
||||
if (i > 0 && frames_[i].file == frames_[i - 1].file)
|
||||
continue; // a file's first frame stands for all of its frames, as for the frames themselves
|
||||
const Frame mask{frames_[i].file, ReplaceEvent(m.data, frames_[i].group), frames_[i].index, frames_[i].group};
|
||||
if (!FileAt(mask.file).Exists(mask.dataset))
|
||||
return {};
|
||||
const Layout l = ReadLayout(FileAt(mask.file), mask);
|
||||
if (i == 0)
|
||||
layout = l;
|
||||
else if (!(l == layout))
|
||||
return {};
|
||||
}
|
||||
if (layout.stored_float || layout.stored_signed || layout.height != frame_height_ || layout.width != frame_width_)
|
||||
return {};
|
||||
return layout;
|
||||
}
|
||||
|
||||
void JFJochXFELReader::Open(const std::vector<std::string> &files) {
|
||||
files_ = files;
|
||||
geom_.masks.insert(geom_.masks.end(), extra_masks_.begin(), extra_masks_.end());
|
||||
@@ -506,10 +564,13 @@ void JFJochXFELReader::Place() {
|
||||
{
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
frame_masks_.clear();
|
||||
frame_mask_layouts_.clear();
|
||||
for (const auto &m: geom_.masks) {
|
||||
std::vector<uint32_t> v;
|
||||
if (m.file.empty() && FileAt(0).GetDimension(m.data).size() == 3) {
|
||||
frame_masks_.push_back(m); // one plane per frame: applied as each frame is read
|
||||
if (m.file.empty() && (m.data.find('%') != std::string::npos
|
||||
|| FileAt(0).GetDimension(m.data).size() == 3)) {
|
||||
frame_masks_.push_back(m); // one per shot or one plane per frame: applied as each is read
|
||||
frame_mask_layouts_.push_back(FrameMaskLayout(m));
|
||||
continue;
|
||||
}
|
||||
if (!m.file.empty()) {
|
||||
@@ -517,13 +578,11 @@ void JFJochXFELReader::Place() {
|
||||
v = mask_file.ReadVector<uint32_t>(m.data, {0, 0}, {frame_height_, frame_width_});
|
||||
} else
|
||||
v = FileAt(0).ReadVector<uint32_t>(m.data, {0, 0}, {frame_height_, frame_width_});
|
||||
for (size_t i = 0; i < v.size(); i++)
|
||||
if (m.Bad(v[i]))
|
||||
masked_by_file[i] = 1;
|
||||
MarkBad(m, v.data(), 0, v.size(), masked_by_file);
|
||||
}
|
||||
}
|
||||
|
||||
// CrystFEL's laboratory frame and the flat image's (column, row, beam) are both right-handed with
|
||||
// CrystFEL's laboratory frame and the detector plane's (column, row, beam) are both right-handed with
|
||||
// the beam along z, so the point (X, Y) lies at column beam_x + X, row beam_y + Y of the detector plane
|
||||
// - and CrystFEL's horizontal x stays the image's horizontal, where the polarisation correction expects
|
||||
// it. A pixel centre is at its index. A panel set nearer or further than the plane (its own coffset)
|
||||
@@ -533,11 +592,14 @@ void JFJochXFELReader::Place() {
|
||||
return std::pair{scale * (p.corner_x + fs * p.fs_x + ss * p.ss_x),
|
||||
scale * (p.corner_y + fs * p.fs_y + ss * p.ss_y)};
|
||||
};
|
||||
// Each panel goes onto the image whole, as a block: its axes turned to the nearest image axis and its
|
||||
// first pixel put at a whole pixel. Where it really lies - the fraction of a pixel, the small turn - is
|
||||
// its module's placement (DetectorModules), so no pixel is moved on its own.
|
||||
// A detector of several panels is analysed as stored: the image is the stored frame, and each panel a
|
||||
// module that maps its box of the frame onto the detector plane exactly where the layout puts it.
|
||||
// A single panel goes onto an image of its own whole, as a block: its axes turned to the nearest image
|
||||
// axis and its first pixel put at a whole pixel. Where it really lies - the fraction of a pixel, the small
|
||||
// turn - is then its module's placement, so no pixel is moved on its own.
|
||||
const bool stored = geom_.panels.size() >= 2;
|
||||
struct Block {
|
||||
int64_t fx = 1, fy = 0, sx = 0, sy = 1; // image step per +1 fs / +1 ss
|
||||
int64_t fx = 1, fy = 0, sx = 0, sy = 1; // image step per +1 fs / +1 ss (single panel)
|
||||
double x0 = 0, y0 = 0; // plane position of the first pixel's centre, beam at 0
|
||||
};
|
||||
auto snap = [](double x, double y, int64_t &ix, int64_t &iy) {
|
||||
@@ -548,34 +610,42 @@ void JFJochXFELReader::Place() {
|
||||
double min_x = 1e9, min_y = 1e9, max_x = -1e9, max_y = -1e9;
|
||||
for (const auto &p: geom_.panels) {
|
||||
Block bl;
|
||||
snap(p.fs_x, p.fs_y, bl.fx, bl.fy);
|
||||
snap(p.ss_x, p.ss_y, bl.sx, bl.sy);
|
||||
if (bl.fx * bl.sy - bl.fy * bl.sx == 0)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Panel " + p.name + " has its fast and slow axes along the same line");
|
||||
if (!stored) {
|
||||
snap(p.fs_x, p.fs_y, bl.fx, bl.fy);
|
||||
snap(p.ss_x, p.ss_y, bl.sx, bl.sy);
|
||||
if (bl.fx * bl.sy - bl.fy * bl.sx == 0)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Panel " + p.name + " has its fast and slow axes along the same line");
|
||||
}
|
||||
std::tie(bl.x0, bl.y0) = position(p, 0.5, 0.5);
|
||||
const double w = static_cast<double>(p.max_fs - p.min_fs), h = static_cast<double>(p.max_ss - p.min_ss);
|
||||
for (double fs: {0.0, w})
|
||||
for (double ss: {0.0, h}) {
|
||||
const double x = bl.x0 + fs * static_cast<double>(bl.fx) + ss * static_cast<double>(bl.sx);
|
||||
const double y = bl.y0 + fs * static_cast<double>(bl.fy) + ss * static_cast<double>(bl.sy);
|
||||
const auto [x, y] = stored
|
||||
? position(p, fs + 0.5, ss + 0.5)
|
||||
: std::pair{bl.x0 + fs * static_cast<double>(bl.fx) + ss * static_cast<double>(bl.sx),
|
||||
bl.y0 + fs * static_cast<double>(bl.fy) + ss * static_cast<double>(bl.sy)};
|
||||
min_x = std::min(min_x, x); max_x = std::max(max_x, x);
|
||||
min_y = std::min(min_y, y); max_y = std::max(max_y, y);
|
||||
}
|
||||
blocks.push_back(bl);
|
||||
}
|
||||
// The first panel's pixel centres on whole columns and rows, two pixels of margin all round.
|
||||
// The first panel's first pixel centre on a whole column and row, two pixels of margin all round.
|
||||
const double beam_x = std::ceil(blocks[0].x0 - min_x) + 2 - blocks[0].x0;
|
||||
const double beam_y = std::ceil(blocks[0].y0 - min_y) + 2 - blocks[0].y0;
|
||||
width_ = static_cast<size_t>(std::ceil(beam_x + max_x)) + 3;
|
||||
height_ = static_cast<size_t>(std::ceil(beam_y + max_y)) + 3;
|
||||
width_ = stored ? frame_width_ : static_cast<size_t>(std::ceil(beam_x + max_x)) + 3;
|
||||
height_ = stored ? frame_height_ : static_cast<size_t>(std::ceil(beam_y + max_y)) + 3;
|
||||
|
||||
// Everything starts as a gap; the panels' pixels are put on top, less the bad regions.
|
||||
std::vector<uint32_t> mask(width_ * height_, 1u << PixelMask::ModuleGapPixelBit);
|
||||
std::vector<uint8_t> taken(width_ * height_, 0);
|
||||
destination_.assign(frame_width_ * frame_height_, -1);
|
||||
adu_per_photon_.assign(frame_width_ * frame_height_, 1.0f);
|
||||
counts_in_photons_ = true;
|
||||
blocks_.clear();
|
||||
// One gain for every panel: what the run is given (ReadFiles, ApplyGain) is set on every panel alike.
|
||||
const auto &p0 = geom_.panels[0];
|
||||
counts_in_photons_ = p0.adu_per_photon.has_value() || p0.adu_per_eV.has_value();
|
||||
const double gain = p0.adu_per_photon.has_value() ? p0.adu_per_photon.value()
|
||||
: p0.adu_per_eV.has_value() ? p0.adu_per_eV.value() * photon_energy_eV_ : 1.0;
|
||||
adu_per_photon_ = static_cast<float>(gain);
|
||||
std::optional<double> saturation;
|
||||
std::vector<DetectorModule> modules;
|
||||
|
||||
@@ -585,51 +655,63 @@ void JFJochXFELReader::Place() {
|
||||
if (p.max_fs >= static_cast<int64_t>(frame_width_) || p.max_ss >= static_cast<int64_t>(frame_height_))
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Panel " + p.name + " lies outside the stored frame");
|
||||
double gain = 1.0;
|
||||
if (p.adu_per_photon.has_value())
|
||||
gain = p.adu_per_photon.value();
|
||||
else if (p.adu_per_eV.has_value())
|
||||
gain = p.adu_per_eV.value() * photon_energy_eV_;
|
||||
else
|
||||
counts_in_photons_ = false;
|
||||
if (p.max_adu.has_value())
|
||||
saturation = std::min(saturation.value_or(INT64_MAX), p.max_adu.value() / gain);
|
||||
if (p.no_index)
|
||||
continue;
|
||||
|
||||
// The image pixel the panel's first pixel lands on, and the block it fills.
|
||||
const int64_t c0 = std::lround(beam_x + bl.x0), r0 = std::lround(beam_y + bl.y0);
|
||||
const int64_t w = p.max_fs - p.min_fs, h = p.max_ss - p.min_ss;
|
||||
const int64_t bx0 = c0 + std::min<int64_t>(0, bl.fx * w) + std::min<int64_t>(0, bl.sx * h);
|
||||
const int64_t by0 = r0 + std::min<int64_t>(0, bl.fy * w) + std::min<int64_t>(0, bl.sy * h);
|
||||
|
||||
// Its placement: the plane position of image pixel (bx0, by0), and the plane steps of +1 column
|
||||
// and +1 row - the panel's own axes, scaled by its projection, taken through the block's turn.
|
||||
const double scale = distance_mm_ / ((clen_m_ + p.coffset) * 1000.0);
|
||||
// The image pixel the panel's first pixel lands on (single panel).
|
||||
const int64_t c0 = std::lround(beam_x + bl.x0), r0 = std::lround(beam_y + bl.y0);
|
||||
DetectorModule m;
|
||||
m.x0 = bx0;
|
||||
m.y0 = by0;
|
||||
m.width = std::abs(bl.fx * w + bl.sx * h) + 1;
|
||||
m.height = std::abs(bl.fy * w + bl.sy * h) + 1;
|
||||
// image (dc, dr) = fs (fx, fy) + ss (sx, sy); the inverse of a signed permutation is its transpose.
|
||||
auto plane_of = [&](double dc, double dr) {
|
||||
const double fs = dc * static_cast<double>(bl.fx) + dr * static_cast<double>(bl.fy);
|
||||
const double ss = dc * static_cast<double>(bl.sx) + dr * static_cast<double>(bl.sy);
|
||||
const auto [x, y] = position(p, fs + 0.5, ss + 0.5);
|
||||
return std::pair{beam_x + x, beam_y + y};
|
||||
};
|
||||
std::tie(m.ox, m.oy) = plane_of(static_cast<double>(bx0 - c0), static_cast<double>(by0 - r0));
|
||||
m.fx = scale * (static_cast<double>(bl.fx) * p.fs_x + static_cast<double>(bl.sx) * p.ss_x);
|
||||
m.fy = scale * (static_cast<double>(bl.fx) * p.fs_y + static_cast<double>(bl.sx) * p.ss_y);
|
||||
m.sx = scale * (static_cast<double>(bl.fy) * p.fs_x + static_cast<double>(bl.sy) * p.ss_x);
|
||||
m.sy = scale * (static_cast<double>(bl.fy) * p.fs_y + static_cast<double>(bl.sy) * p.ss_y);
|
||||
if (stored) {
|
||||
// Its box in the stored frame, and the plane position and steps of its pixels: the panel's own axes,
|
||||
// scaled by its projection.
|
||||
m.x0 = p.min_fs;
|
||||
m.y0 = p.min_ss;
|
||||
m.width = w + 1;
|
||||
m.height = h + 1;
|
||||
m.ox = beam_x + bl.x0;
|
||||
m.oy = beam_y + bl.y0;
|
||||
m.fx = scale * p.fs_x;
|
||||
m.fy = scale * p.fs_y;
|
||||
m.sx = scale * p.ss_x;
|
||||
m.sy = scale * p.ss_y;
|
||||
} else {
|
||||
// The block it fills, and its placement: the plane position of image pixel (bx0, by0), and the
|
||||
// plane steps of +1 column and +1 row - the panel's own axes, scaled by its projection, taken
|
||||
// through the block's turn.
|
||||
const int64_t bx0 = c0 + std::min<int64_t>(0, bl.fx * w) + std::min<int64_t>(0, bl.sx * h);
|
||||
const int64_t by0 = r0 + std::min<int64_t>(0, bl.fy * w) + std::min<int64_t>(0, bl.sy * h);
|
||||
m.x0 = bx0;
|
||||
m.y0 = by0;
|
||||
m.width = std::abs(bl.fx * w + bl.sx * h) + 1;
|
||||
m.height = std::abs(bl.fy * w + bl.sy * h) + 1;
|
||||
// image (dc, dr) = fs (fx, fy) + ss (sx, sy); the inverse of a signed permutation is its transpose.
|
||||
auto plane_of = [&](double dc, double dr) {
|
||||
const double fs = dc * static_cast<double>(bl.fx) + dr * static_cast<double>(bl.fy);
|
||||
const double ss = dc * static_cast<double>(bl.sx) + dr * static_cast<double>(bl.sy);
|
||||
const auto [x, y] = position(p, fs + 0.5, ss + 0.5);
|
||||
return std::pair{beam_x + x, beam_y + y};
|
||||
};
|
||||
std::tie(m.ox, m.oy) = plane_of(static_cast<double>(bx0 - c0), static_cast<double>(by0 - r0));
|
||||
m.fx = scale * (static_cast<double>(bl.fx) * p.fs_x + static_cast<double>(bl.sx) * p.ss_x);
|
||||
m.fy = scale * (static_cast<double>(bl.fx) * p.fs_y + static_cast<double>(bl.sx) * p.ss_y);
|
||||
m.sx = scale * (static_cast<double>(bl.fy) * p.fs_x + static_cast<double>(bl.sy) * p.ss_x);
|
||||
m.sy = scale * (static_cast<double>(bl.fy) * p.fs_y + static_cast<double>(bl.sy) * p.ss_y);
|
||||
blocks_.push_back({static_cast<size_t>(p.min_ss) * frame_width_ + static_cast<size_t>(p.min_fs), w + 1,
|
||||
h + 1, r0 * static_cast<int64_t>(width_) + c0,
|
||||
bl.fy * static_cast<int64_t>(width_) + bl.fx,
|
||||
bl.sy * static_cast<int64_t>(width_) + bl.sx});
|
||||
}
|
||||
modules.push_back(m);
|
||||
|
||||
const int64_t e = p.mask_edge_pixels;
|
||||
for (int64_t ss = p.min_ss; ss <= p.max_ss; ss++) {
|
||||
for (int64_t fs = p.min_fs; fs <= p.max_fs; fs++) {
|
||||
const int64_t col = c0 + (fs - p.min_fs) * bl.fx + (ss - p.min_ss) * bl.sx;
|
||||
const int64_t row = r0 + (fs - p.min_fs) * bl.fy + (ss - p.min_ss) * bl.sy;
|
||||
const int64_t col = stored ? fs : c0 + (fs - p.min_fs) * bl.fx + (ss - p.min_ss) * bl.sx;
|
||||
const int64_t row = stored ? ss : r0 + (fs - p.min_fs) * bl.fy + (ss - p.min_ss) * bl.sy;
|
||||
const size_t dst = static_cast<size_t>(row) * width_ + static_cast<size_t>(col);
|
||||
if (taken[dst])
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
@@ -648,10 +730,7 @@ void JFJochXFELReader::Place() {
|
||||
if (bad)
|
||||
continue;
|
||||
|
||||
const size_t src = ss * frame_width_ + fs;
|
||||
destination_[src] = static_cast<int64_t>(dst);
|
||||
adu_per_photon_[src] = static_cast<float>(gain);
|
||||
mask[dst] = masked_by_file[src] ? (1u << PixelMask::ErrorPixelBit) : 0;
|
||||
mask[dst] = masked_by_file[ss * frame_width_ + fs] ? (1u << PixelMask::ErrorPixelBit) : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -668,7 +747,7 @@ void JFJochXFELReader::Place() {
|
||||
if (!saturation.has_value() && !layout_.stored_float && layout_.stored_size > 0) {
|
||||
const double type_max = std::exp2(8.0 * static_cast<double>(layout_.stored_size)
|
||||
- (layout_.stored_signed ? 1 : 0)) - 1;
|
||||
saturation = type_max / *std::max_element(adu_per_photon_.begin(), adu_per_photon_.end());
|
||||
saturation = type_max / adu_per_photon_;
|
||||
}
|
||||
if (saturation.has_value())
|
||||
detector.SaturationLimit(static_cast<int64_t>(std::floor(saturation.value())));
|
||||
@@ -688,7 +767,7 @@ void JFJochXFELReader::Place() {
|
||||
dataset_->experiment.ImagesPerTrigger(static_cast<int64_t>(frames_.size()));
|
||||
// Each panel is a module, placed where the layout puts it; one panel square with the image needs none.
|
||||
const DetectorModules placed(modules);
|
||||
if (modules.size() >= 2 || placed.Moved())
|
||||
if (stored || placed.Moved())
|
||||
dataset_->experiment.Modules(placed);
|
||||
dataset_->pixel_mask = std::make_shared<const PixelMask>(mask);
|
||||
|
||||
@@ -701,12 +780,49 @@ void JFJochXFELReader::Place() {
|
||||
SetStartMessage(dataset_);
|
||||
}
|
||||
|
||||
template <class T>
|
||||
void JFJochXFELReader::MarkBad(const xfel::Mask &m, const T *v, size_t first, size_t n, std::vector<uint8_t> &bad) const {
|
||||
int64_t min_fs = 0, max_fs = static_cast<int64_t>(frame_width_) - 1;
|
||||
int64_t min_ss = 0, max_ss = static_cast<int64_t>(frame_height_) - 1;
|
||||
for (const auto &p: geom_.panels)
|
||||
if (!m.panel.empty() && p.name == m.panel) {
|
||||
min_fs = p.min_fs; max_fs = p.max_fs;
|
||||
min_ss = p.min_ss; max_ss = p.max_ss;
|
||||
}
|
||||
// The mask's bits in locals and plain pointers, a row at a time: a byte stored through bad could otherwise
|
||||
// be m's or bad's own, every pixel would read them again, and the loop would not be vectorised.
|
||||
const uint32_t good = m.good, bad_bits = m.bad;
|
||||
const bool nonzero_good = m.nonzero_good;
|
||||
const size_t last = first + n; // the pixels [first, last) of the frame are those v holds
|
||||
for (int64_t ss = std::max<int64_t>(min_ss, first / frame_width_);
|
||||
ss <= max_ss && static_cast<size_t>(ss) * frame_width_ < last; ss++) {
|
||||
const size_t begin = std::max<size_t>(static_cast<size_t>(ss) * frame_width_ + min_fs, first);
|
||||
const size_t end = std::min<size_t>(static_cast<size_t>(ss) * frame_width_ + max_fs + 1, last);
|
||||
if (end <= begin)
|
||||
continue;
|
||||
const T *in = v + (begin - first);
|
||||
uint8_t *out = bad.data() + begin;
|
||||
for (size_t i = 0; i < end - begin; i++)
|
||||
out[i] |= xfel::Mask::Bad(in[i], good, bad_bits, nonzero_good);
|
||||
}
|
||||
}
|
||||
|
||||
void JFJochXFELReader::ApplyGain(float adu_per_photon) {
|
||||
for (auto &p: geom_.panels)
|
||||
p.adu_per_photon = adu_per_photon;
|
||||
Place();
|
||||
}
|
||||
|
||||
void JFJochXFELReader::ClearGain() {
|
||||
for (auto &p: geom_.panels)
|
||||
p.adu_per_photon.reset();
|
||||
Place();
|
||||
}
|
||||
|
||||
bool JFJochXFELReader::StoredFloat() const {
|
||||
return layout_.stored_float || !layout_.plain_type;
|
||||
}
|
||||
|
||||
bool JFJochXFELReader::HasPhotonEnergy() const {
|
||||
return photon_energy_eV_ > 0;
|
||||
}
|
||||
@@ -730,109 +846,265 @@ void JFJochXFELReader::Close() {
|
||||
dataset_.reset();
|
||||
}
|
||||
|
||||
template <class Buffer>
|
||||
void JFJochXFELReader::DecodeInto(int64_t image_number, Buffer &buffer) const {
|
||||
const auto &frame = frames_.at(image_number);
|
||||
std::vector<float> stored(frame_width_ * frame_height_);
|
||||
if (layout_.direct_chunks) {
|
||||
// Under the lock only where the chunk is (a lookup in its index); the read and the decoding not.
|
||||
std::shared_ptr<const HDF5ImageSource::RawFile> raw_file;
|
||||
uint64_t address = 0, chunk_size = 0;
|
||||
{
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
HDF5DataSet dataset(FileAt(frame.file), frame.dataset);
|
||||
const hsize_t coord_3d[3] = {static_cast<hsize_t>(frame.index), 0, 0};
|
||||
const hsize_t coord_2d[2] = {0, 0};
|
||||
unsigned filter_mask = 0;
|
||||
haddr_t addr = HADDR_UNDEF;
|
||||
hsize_t size = 0;
|
||||
if (H5Dget_chunk_info_by_coord(dataset.GetID(), frame.index >= 0 ? coord_3d : coord_2d, &filter_mask,
|
||||
&addr, &size) < 0 || addr == HADDR_UNDEF || size == 0)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"No stored chunk for " + frame.dataset + " of " + files_[frame.file]);
|
||||
raw_file = RawFileAt(frame.file);
|
||||
address = user_block_[frame.file] + addr;
|
||||
chunk_size = size;
|
||||
}
|
||||
std::vector<uint8_t> compressed(chunk_size);
|
||||
raw_file->ReadAt(compressed.data(), compressed.size(), address);
|
||||
|
||||
const size_t n = stored.size();
|
||||
const size_t size = layout_.stored_size;
|
||||
std::vector<uint8_t> raw(n * size);
|
||||
if (layout_.deflated) {
|
||||
uLongf raw_size = raw.size();
|
||||
if (uncompress(raw.data(), &raw_size, compressed.data(), compressed.size()) != Z_OK
|
||||
|| raw_size != raw.size())
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Cannot inflate " + frame.dataset + " of " + files_[frame.file]);
|
||||
} else {
|
||||
const CompressedImage image(compressed.data(), compressed.size(), frame_width_, frame_height_,
|
||||
CalcImageMode(size, layout_.stored_float, layout_.stored_signed),
|
||||
layout_.algorithm);
|
||||
std::vector<uint8_t> decoded;
|
||||
std::memcpy(raw.data(), image.GetUncompressedPtr(decoded), raw.size());
|
||||
}
|
||||
if (layout_.shuffled) {
|
||||
std::vector<uint8_t> tmp(raw.size());
|
||||
for (size_t i = 0; i < n; i++)
|
||||
for (size_t b = 0; b < size; b++)
|
||||
tmp[i * size + b] = raw[b * n + i];
|
||||
raw.swap(tmp);
|
||||
}
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
const uint8_t *v = raw.data() + i * size;
|
||||
if (layout_.stored_float) {
|
||||
float x;
|
||||
std::memcpy(&x, v, 4);
|
||||
stored[i] = x;
|
||||
} else if (size == 2) {
|
||||
uint16_t x;
|
||||
std::memcpy(&x, v, 2);
|
||||
stored[i] = layout_.stored_signed ? static_cast<float>(static_cast<int16_t>(x)) : x;
|
||||
} else {
|
||||
uint32_t x;
|
||||
std::memcpy(&x, v, 4);
|
||||
stored[i] = layout_.stored_signed ? static_cast<float>(static_cast<int32_t>(x))
|
||||
: static_cast<float>(x);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
template <class Buffer, class Piece>
|
||||
bool JFJochXFELReader::ReadStored(const Frame &frame, const Layout &layout, Buffer &stored,
|
||||
bool keep_compressed, Piece piece) const {
|
||||
constexpr bool in_pieces = !std::is_same_v<Piece, std::nullptr_t>;
|
||||
const size_t n = frame_width_ * frame_height_;
|
||||
const size_t size = layout.stored_size;
|
||||
const std::vector<hsize_t> start = frame.index >= 0
|
||||
? std::vector<hsize_t>{static_cast<hsize_t>(frame.index), 0, 0}
|
||||
: std::vector<hsize_t>{0, 0};
|
||||
const std::vector<hsize_t> count = frame.index >= 0 ? std::vector<hsize_t>{1, frame_height_, frame_width_}
|
||||
: std::vector<hsize_t>{frame_height_, frame_width_};
|
||||
// Under the lock only where the chunk is (a lookup in its index); the read and the decoding not.
|
||||
std::shared_ptr<const HDF5ImageSource::RawFile> raw_file;
|
||||
uint64_t address = 0, chunk_size = 0;
|
||||
bool read_by_hdf5 = false;
|
||||
{
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
HDF5DataSet dataset(FileAt(frame.file), frame.dataset);
|
||||
if (frame.index >= 0)
|
||||
dataset.ReadVector(stored, {static_cast<hsize_t>(frame.index), 0, 0}, {1, frame_height_, frame_width_});
|
||||
else
|
||||
dataset.ReadVector(stored, {0, 0}, {frame_height_, frame_width_});
|
||||
unsigned filter_mask = 0;
|
||||
if (layout.direct_chunks) {
|
||||
haddr_t addr = HADDR_UNDEF;
|
||||
hsize_t size = 0;
|
||||
if (H5Dget_chunk_info_by_coord(dataset.GetID(), start.data(), &filter_mask, &addr, &size) < 0
|
||||
|| addr == HADDR_UNDEF || size == 0)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"No stored chunk for " + frame.dataset + " of " + files_[frame.file]);
|
||||
address = addr;
|
||||
chunk_size = size;
|
||||
}
|
||||
// A chunk stored with one of its filters skipped (its filter mask) is not the encoding decoded
|
||||
// below: HDF5 reads it, as it reads a frame that is not stored as one chunk.
|
||||
if (!layout.direct_chunks || filter_mask != 0) {
|
||||
if (layout.plain_type)
|
||||
dataset.ReadVectorToU8(stored, start, count);
|
||||
else {
|
||||
std::vector<float> v(frame_width_ * frame_height_);
|
||||
dataset.ReadVector(v, start, count);
|
||||
stored.resize(v.size() * sizeof(float));
|
||||
std::memcpy(stored.data(), v.data(), stored.size());
|
||||
}
|
||||
read_by_hdf5 = true;
|
||||
} else {
|
||||
raw_file = RawFileAt(frame.file);
|
||||
address += user_block_[frame.file]; // HDF5's chunk addresses count from the end of the user block
|
||||
}
|
||||
}
|
||||
if (read_by_hdf5) {
|
||||
if constexpr (in_pieces)
|
||||
piece(0, stored.data(), n);
|
||||
return false;
|
||||
}
|
||||
if (keep_compressed && !layout.deflated) {
|
||||
stored.resize(chunk_size);
|
||||
raw_file->ReadAt(stored.data(), stored.size(), address);
|
||||
return true;
|
||||
}
|
||||
thread_local std::vector<uint8_t> compressed, shuffled;
|
||||
compressed.resize(chunk_size);
|
||||
raw_file->ReadAt(compressed.data(), compressed.size(), address);
|
||||
|
||||
if (layout.deflated && !layout.shuffled && in_pieces) {
|
||||
if constexpr (in_pieces)
|
||||
InflateInPieces(compressed, n * size, size, frame, piece);
|
||||
return false;
|
||||
}
|
||||
if (layout.deflated) {
|
||||
if (!layout.shuffled)
|
||||
stored.resize(n * size);
|
||||
else
|
||||
shuffled.resize(n * size);
|
||||
uint8_t *inflated = layout.shuffled ? shuffled.data() : stored.data();
|
||||
uLongf inflated_size = n * size;
|
||||
if (uncompress(inflated, &inflated_size, compressed.data(), compressed.size()) != Z_OK
|
||||
|| inflated_size != n * size)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Cannot inflate " + frame.dataset + " of " + files_[frame.file]);
|
||||
if (layout.shuffled) {
|
||||
if constexpr (in_pieces) {
|
||||
// A piece at a time, as for an unshuffled chunk.
|
||||
thread_local std::vector<uint8_t> out(PIECE_BYTES);
|
||||
const size_t piece_pixels = PIECE_BYTES / size;
|
||||
for (size_t first = 0; first < n; first += piece_pixels) {
|
||||
const size_t count = std::min(piece_pixels, n - first);
|
||||
Unshuffle(shuffled.data(), n, size, first, count, out.data());
|
||||
piece(first, out.data(), count);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
stored.resize(n * size);
|
||||
Unshuffle(shuffled.data(), n, size, 0, n, stored.data());
|
||||
}
|
||||
} else {
|
||||
stored.resize(n * size);
|
||||
JFJochDecompressPtr(stored.data(), layout.algorithm, compressed.data(), compressed.size(), n, size);
|
||||
}
|
||||
if constexpr (in_pieces)
|
||||
piece(0, stored.data(), n);
|
||||
return false;
|
||||
}
|
||||
|
||||
template <class Piece>
|
||||
void JFJochXFELReader::InflateInPieces(const std::vector<uint8_t> &compressed, size_t bytes, size_t size,
|
||||
const Frame &frame, Piece piece) const {
|
||||
thread_local std::vector<uint8_t> out(PIECE_BYTES);
|
||||
z_stream z{};
|
||||
if (inflateInit(&z) != Z_OK)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Cannot start to inflate");
|
||||
z.next_in = const_cast<uint8_t *>(compressed.data());
|
||||
z.avail_in = compressed.size();
|
||||
size_t done = 0;
|
||||
int ret = Z_OK;
|
||||
while (ret == Z_OK) {
|
||||
z.next_out = out.data();
|
||||
z.avail_out = PIECE_BYTES;
|
||||
ret = inflate(&z, Z_NO_FLUSH);
|
||||
const size_t got = PIECE_BYTES - z.avail_out;
|
||||
// A piece is whole pixels: inflate fills it before it returns, except at the end of the frame.
|
||||
if ((ret != Z_OK && ret != Z_STREAM_END) || done + got > bytes || got % size != 0)
|
||||
break;
|
||||
if (got > 0)
|
||||
piece(done / size, out.data(), got / size);
|
||||
done += got;
|
||||
}
|
||||
inflateEnd(&z);
|
||||
if (ret != Z_STREAM_END || done != bytes)
|
||||
throw JFJochException(JFJochExceptionCategory::InputParameterInvalid,
|
||||
"Cannot inflate " + frame.dataset + " of " + files_[frame.file]);
|
||||
}
|
||||
|
||||
template <class Out, class In, class Buffer, class Convert>
|
||||
void JFJochXFELReader::PlaceInto(const Frame &frame, const std::vector<uint8_t> &masked, Out err, Buffer &buffer,
|
||||
Convert convert) const {
|
||||
buffer.resize(width_ * height_ * sizeof(Out));
|
||||
auto out = reinterpret_cast<Out *>(buffer.data());
|
||||
thread_local std::vector<uint8_t> stored;
|
||||
if (blocks_.empty()) { // the stored frame, as stored: converted a piece at a time, as it is read
|
||||
ReadStored(frame, layout_, stored, false, [&](size_t first, const uint8_t *bytes, size_t n) {
|
||||
const auto *in = reinterpret_cast<const In *>(bytes);
|
||||
Out *o = out + first;
|
||||
if (masked.empty())
|
||||
for (size_t i = 0; i < n; i++)
|
||||
o[i] = static_cast<Out>(convert(in[i]));
|
||||
else {
|
||||
const uint8_t *m = masked.data() + first;
|
||||
for (size_t i = 0; i < n; i++)
|
||||
o[i] = static_cast<Out>(Pick(m[i] != 0, convert(in[i]), err));
|
||||
}
|
||||
});
|
||||
return;
|
||||
}
|
||||
ReadStored(frame, layout_, stored, false);
|
||||
const auto *in = reinterpret_cast<const In *>(stored.data());
|
||||
std::fill(out, out + width_ * height_, Out{0}); // between the panels
|
||||
for (const auto &b: blocks_)
|
||||
for (int64_t ss = 0; ss < b.height; ss++) {
|
||||
const size_t src = b.src + static_cast<size_t>(ss) * frame_width_;
|
||||
Out *dst = out + b.dst + ss * b.step_ss;
|
||||
if (masked.empty() && b.step_fs == 1)
|
||||
std::transform(in + src, in + src + b.width, dst, [&](In v) { return static_cast<Out>(convert(v)); });
|
||||
else
|
||||
for (int64_t fs = 0; fs < b.width; fs++)
|
||||
dst[fs * b.step_fs] = !masked.empty() && masked[src + fs] ? err : static_cast<Out>(convert(in[src + fs]));
|
||||
}
|
||||
}
|
||||
|
||||
template <class Buffer>
|
||||
CompressedImage JFJochXFELReader::DecodeInto(int64_t image_number, Buffer &buffer) const {
|
||||
const auto &frame = frames_.at(image_number);
|
||||
const CompressedImageMode stored_mode = CalcImageMode(layout_.stored_size, layout_.stored_float,
|
||||
layout_.stored_signed);
|
||||
// A frame of several panels in signed integers, read in its own units, goes up as stored, with no copy:
|
||||
// a bitshuffle/LZ4 chunk still compressed, to be decoded where it is analysed (on the GPU, as
|
||||
// Jungfraujoch's own images are), anything else decoded once. Its smallest value is no measurement
|
||||
// (below), which the analysis takes it as anyway.
|
||||
const bool as_stored = blocks_.empty() && layout_.plain_type && !layout_.stored_float && layout_.stored_signed
|
||||
&& adu_per_photon_ == 1.0f;
|
||||
if (as_stored && frame_masks_.empty()) {
|
||||
const bool compressed = ReadStored(frame, layout_, buffer, true);
|
||||
return CompressedImage(buffer.data(), buffer.size(), width_, height_, stored_mode,
|
||||
compressed ? layout_.algorithm : CompressionAlgorithm::NO_COMPRESSION);
|
||||
}
|
||||
// A pixel a per-frame mask marks in this frame is handed out as no measurement.
|
||||
std::vector<uint8_t> masked;
|
||||
if (!frame_masks_.empty() && frame.index >= 0) {
|
||||
masked.assign(stored.size(), 0);
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
for (const auto &m: frame_masks_) {
|
||||
const auto v = FileAt(frame.file).ReadVector<uint32_t>(m.data, {static_cast<hsize_t>(frame.index), 0, 0},
|
||||
{1, frame_height_, frame_width_});
|
||||
for (size_t i = 0; i < v.size(); i++)
|
||||
if (m.Bad(v[i]))
|
||||
masked[i] = 1;
|
||||
if (!frame_masks_.empty()) {
|
||||
masked.assign(frame_width_ * frame_height_, 0);
|
||||
for (size_t i = 0; i < frame_masks_.size(); i++) {
|
||||
const auto &m = frame_masks_[i];
|
||||
const auto &mask_layout = frame_mask_layouts_[i];
|
||||
const Frame mask{frame.file, ReplaceEvent(m.data, frame.group), frame.index, frame.group};
|
||||
if (mask_layout.plain_type) {
|
||||
thread_local std::vector<uint8_t> mask_stored;
|
||||
ReadStored(mask, mask_layout, mask_stored, false, [&](size_t first, const uint8_t *bytes, size_t n) {
|
||||
if (mask_layout.stored_size == 2)
|
||||
MarkBad(m, reinterpret_cast<const uint16_t *>(bytes), first, n, masked);
|
||||
else
|
||||
MarkBad(m, reinterpret_cast<const uint32_t *>(bytes), first, n, masked);
|
||||
});
|
||||
} else {
|
||||
std::vector<uint32_t> v;
|
||||
{
|
||||
std::unique_lock ul(hdf5_mutex);
|
||||
v = frame.index >= 0
|
||||
? FileAt(frame.file).ReadVector<uint32_t>(mask.dataset, {static_cast<hsize_t>(frame.index), 0, 0},
|
||||
{1, frame_height_, frame_width_})
|
||||
: FileAt(frame.file).ReadVector<uint32_t>(mask.dataset, {0, 0}, {frame_height_, frame_width_});
|
||||
}
|
||||
MarkBad(m, v.data(), 0, v.size(), masked);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// And so is one whose value the layout flags as no measurement.
|
||||
const auto flagged = [this](float v) {
|
||||
return (geom_.flag_lessthan && v < *geom_.flag_lessthan) || (geom_.flag_morethan && v > *geom_.flag_morethan)
|
||||
|| (geom_.flag_equal && v == *geom_.flag_equal);
|
||||
const float gain = adu_per_photon_;
|
||||
// A float that is no number (NaN, inf) is no measurement; anything past int32 is clamped to it.
|
||||
// Written without a branch or a library call, so that the loop over the pixels is vectorised. The clamp
|
||||
// keeps the sign of an infinity; std::lround is spelled out: t is c truncated, c - t is exact, and a
|
||||
// fraction of a half or more rounds away from zero.
|
||||
const auto photons = [gain](auto v) {
|
||||
const float x = static_cast<float>(v) / gain;
|
||||
constexpr float limit = 2147483520.0f;
|
||||
const float c = std::fabs(x) < limit ? x : std::copysign(limit, x);
|
||||
const auto t = static_cast<int32_t>(c);
|
||||
const float fraction = c - static_cast<float>(t);
|
||||
const int32_t rounded = t + (fraction >= 0.5f) - (fraction <= -0.5f);
|
||||
return Pick(!std::isfinite(x), rounded, INT32_MIN);
|
||||
};
|
||||
const auto as_is = [](auto v) { return v; };
|
||||
const auto image = [&](CompressedImageMode mode) {
|
||||
return CompressedImage(buffer.data(), buffer.size(), width_, height_, mode, CompressionAlgorithm::NO_COMPRESSION);
|
||||
};
|
||||
// A signed integer frame's smallest value is no measurement: what a converted file
|
||||
// (tools/battery/still/agipd_to_int16.py) writes for a masked pixel or a gap.
|
||||
const auto integers = [&](auto to_int32) {
|
||||
const auto convert = [to_int32](auto v) -> int32_t {
|
||||
if constexpr (std::is_signed_v<decltype(v)>)
|
||||
return Pick(v == std::numeric_limits<decltype(v)>::min(), to_int32(v), INT32_MIN);
|
||||
return to_int32(v);
|
||||
};
|
||||
if (layout_.stored_size == 2 && layout_.stored_signed)
|
||||
PlaceInto<int32_t, int16_t>(frame, masked, INT32_MIN, buffer, convert);
|
||||
else if (layout_.stored_size == 2)
|
||||
PlaceInto<int32_t, uint16_t>(frame, masked, INT32_MIN, buffer, convert);
|
||||
else if (layout_.stored_signed)
|
||||
PlaceInto<int32_t, int32_t>(frame, masked, INT32_MIN, buffer, convert);
|
||||
else
|
||||
PlaceInto<int32_t, uint32_t>(frame, masked, INT32_MIN, buffer, convert);
|
||||
};
|
||||
|
||||
buffer.assign(width_ * height_ * sizeof(int32_t), 0);
|
||||
auto out = reinterpret_cast<int32_t *>(buffer.data());
|
||||
for (size_t i = 0; i < stored.size(); i++)
|
||||
if (destination_[i] >= 0)
|
||||
out[destination_[i]] = (!masked.empty() && masked[i]) || flagged(stored[i])
|
||||
? INT32_MIN
|
||||
: static_cast<int32_t>(std::lround(stored[i] / adu_per_photon_[i]));
|
||||
// Floats become photons, rounded. Integers stay integers: divided only by a gain other than one, and a
|
||||
// 16-bit signed frame - as Cheetah writes - is handed out in its own type.
|
||||
if (layout_.stored_float || !layout_.plain_type)
|
||||
PlaceInto<int32_t, float>(frame, masked, INT32_MIN, buffer, photons);
|
||||
else if (gain != 1.0f)
|
||||
integers(photons);
|
||||
else if (layout_.stored_size == 2 && layout_.stored_signed) {
|
||||
PlaceInto<int16_t, int16_t>(frame, masked, INT16_MIN, buffer, as_is);
|
||||
return image(CompressedImageMode::Int16);
|
||||
} else
|
||||
integers([](auto v) { return static_cast<int32_t>(v); });
|
||||
return image(CompressedImageMode::Int32);
|
||||
}
|
||||
|
||||
bool JFJochXFELReader::LoadImage_i(std::shared_ptr<JFJochReaderDataset> &dataset,
|
||||
@@ -843,9 +1115,7 @@ bool JFJochXFELReader::LoadImage_i(std::shared_ptr<JFJochReaderDataset> &dataset
|
||||
(void) update_dataset;
|
||||
if (!dataset || image_number < 0 || static_cast<size_t>(image_number) >= frames_.size())
|
||||
return false;
|
||||
DecodeInto(image_number, buffer);
|
||||
message.image = CompressedImage(buffer.data(), buffer.size(), width_, height_,
|
||||
CompressedImageMode::Int32, CompressionAlgorithm::NO_COMPRESSION);
|
||||
message.image = DecodeInto(image_number, buffer);
|
||||
message.number = image_number;
|
||||
return true;
|
||||
}
|
||||
@@ -853,9 +1123,7 @@ bool JFJochXFELReader::LoadImage_i(std::shared_ptr<JFJochReaderDataset> &dataset
|
||||
bool JFJochXFELReader::ReadRawImage(int64_t image_number, JFJochReaderRawImage &image) {
|
||||
if (image_number < 0 || static_cast<size_t>(image_number) >= frames_.size())
|
||||
return false;
|
||||
DecodeInto(image_number, image.image_buffer);
|
||||
image.image = CompressedImage(image.image_buffer.data(), image.image_buffer.size(), width_, height_,
|
||||
CompressedImageMode::Int32, CompressionAlgorithm::NO_COMPRESSION);
|
||||
image.image = DecodeInto(image_number, image.image_buffer);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user