diff --git a/common/DiffractionExperiment.cpp b/common/DiffractionExperiment.cpp index 1c2ec942b..a21b1ca1e 100644 --- a/common/DiffractionExperiment.cpp +++ b/common/DiffractionExperiment.cpp @@ -652,6 +652,7 @@ SpotFindingSettings DiffractionExperiment::DefaultDataProcessingSettings() { void DiffractionExperiment::FillMessage(StartMessage &message) const { message.images_per_file = GetImagesPerFile(); + message.detector_modules = GetModules().Get(); message.beam_center_x = GetBeamX_pxl(); message.beam_center_y = GetBeamY_pxl(); const auto direct_beam = GetDiffractionGeometry().GetDirectBeam_pxl(); diff --git a/common/JFJochMessages.h b/common/JFJochMessages.h index 449929d2f..ec9ce70d6 100644 --- a/common/JFJochMessages.h +++ b/common/JFJochMessages.h @@ -24,6 +24,7 @@ #include "CrystalLattice.h" #include "IndexingSettings.h" #include "XrayFluorescenceSpectrum.h" +#include "DetectorModules.h" #include "../gemmi_gph/gemmi/symmetry.hpp" constexpr const uint64_t user_data_release = 6; @@ -324,6 +325,10 @@ struct StartMessage { // Per-pixel ROI bitmask (converted geometry), bit i set for ROI i in rois. std::vector roi_map; + // The detector's panels (DetectorModules.h), where the image's pixels are on the detector plane. Empty + // for one flat detector, the image being the plane; then the CBOR key is absent. + std::vector detector_modules; + std::map threshold_energy; std::optional total_flux; diff --git a/common/SpotToSave.h b/common/SpotToSave.h index d866acbc1..ed935058b 100644 --- a/common/SpotToSave.h +++ b/common/SpotToSave.h @@ -18,6 +18,7 @@ struct SpotToSave { float dist_ewald_sphere = 0.0; bool ice_ring = false; bool indexed = false; + int16_t panel = -1; // index into the experiment's DetectorModules; -1 = no panel table Coord ReciprocalCoord(const DiffractionGeometry &experiment) const; }; diff --git a/docs/CBOR.md b/docs/CBOR.md index ff647958a..ddc46d4ab 100644 --- a/docs/CBOR.md +++ b/docs/CBOR.md @@ -32,6 +32,7 @@ There are minor differences at the moment: | mirror_y | bool | Whether the assembled image is mirrored in Y relative to the detector's raw readout order. True is the MX convention - row 0 at the top of the detector seen from the sample - and is what absence of the key means | | | detector_orientation_mirror_y | bool | Whether the assembled image is mirrored in Y relative to the frame the PONI angles are stated in. A different setting from `mirror_y` above, which is about the module layout; this one changes no pixel. Absence means false | | | detector_orientation_quarter_turns | int | How many multiples of 90 degrees about the beam the assembled image is turned by, relative to the frame the PONI angles are stated in (0-3). Absence means 0 | | +| detector_modules | Array(object) (optional) | Panels: where the image's pixels lie on the detector plane the geometry describes. Each has `x0`, `y0`, `width`, `height` (int, the panel's box in the image) and `ox`, `oy`, `fx`, `fy`, `sx`, `sy` (double, plane pixels): image pixel (x, y) of the panel is at `(ox, oy) + (x - x0) (fx, fy) + (y - y0) (sx, sy)`. Absent for a flat detector, the image being the plane; spot and reflection positions are always plane coordinates | | | incident_energy | float | X-ray energy \[eV\] | X | | incident_wavelength | float | X-ray wavelength \[Angstrom\] | X | | incident_wavelength_spread | float (optional) | FWHM of the X-ray wavelength distribution \[Angstrom\] (NXmx incident_wavelength_spread); omitted when the beam is monochromatic | | @@ -150,6 +151,7 @@ See [DECTRIS documentation](https://github.com/dectris/documentation/tree/main/s | - indexed | bool | indexed solution | | | | - latt | int64 | Lattice to which the peak belongs (negative number = not indexed) | | | | - image | int64 | image number the spot belongs to | | | +| - panel | int64 (optional) | panel (index into `detector_modules`) the spot was found on; absent for a detector without a panel table | | | | - h | int64 | Miller index (indexed spots only) | | | | - k | int64 | Miller index (indexed spots only) | | | | - l | int64 | Miller index (indexed spots only) | | | diff --git a/docs/HDF5.md b/docs/HDF5.md index 0bddb0b26..fa82e587b 100644 --- a/docs/HDF5.md +++ b/docs/HDF5.md @@ -342,6 +342,7 @@ In legacy/VDS mode these live in the data files and are linked/virtual-stacked i | `peakDistEwaldSphere` | Å⁻¹ | distance of the spot from the Ewald sphere | ✓ | | `peakIndexed` | | spot fits the indexing solution | ✓ | | `peakLattice` | | lattice the spot belongs to (`-1` = unindexed) | ✓ | +| `peakPanel` | | panel the spot was found on (`-1` = none); written only for a detector with a panel table | | **Per-image vectors `[n_images]`:** diff --git a/frame_serialize/CBORStream2Deserializer.cpp b/frame_serialize/CBORStream2Deserializer.cpp index 2341bbc3f..a7c0dba3f 100644 --- a/frame_serialize/CBORStream2Deserializer.cpp +++ b/frame_serialize/CBORStream2Deserializer.cpp @@ -59,6 +59,16 @@ namespace { throw JFJochException(JFJochExceptionCategory::CBORError, "Float expected"); } + double GetCBORDouble(CborValue &value) { + if (cbor_value_is_double(&value)) { + double tmp; + cborErr(cbor_value_get_double(&value, &tmp)); + cborErr(cbor_value_advance(&value)); + return tmp; + } + return GetCBORFloat(value); + } + bool GetCBORBool(CborValue &value) { if (!cbor_value_is_boolean(&value)) { throw JFJochException(JFJochExceptionCategory::CBORError, @@ -514,6 +524,8 @@ namespace { s.dist_ewald_sphere = GetCBORFloat(map_value); else if (key == "image") s.image = GetCBORInt(map_value); + else if (key == "panel") + s.panel = static_cast(GetCBORInt(map_value)); else cbor_value_advance(&map_value); } @@ -1299,6 +1311,45 @@ namespace { } } + void GetDetectorModules(CborValue &value, std::vector &modules) { + const size_t array_len = GetCBORArrayLen(value); + CborValue array_value; + cborErr(cbor_value_enter_container(&value, &array_value)); + for (size_t i = 0; i < array_len; i++) { + DetectorModule m; + CborValue map_value; + cborErr(cbor_value_enter_container(&array_value, &map_value)); + while (!cbor_value_at_end(&map_value)) { + const auto key = GetCBORString(map_value); + if (key == "x0") + m.x0 = GetCBORInt(map_value); + else if (key == "y0") + m.y0 = GetCBORInt(map_value); + else if (key == "width") + m.width = GetCBORInt(map_value); + else if (key == "height") + m.height = GetCBORInt(map_value); + else if (key == "ox") + m.ox = GetCBORDouble(map_value); + else if (key == "oy") + m.oy = GetCBORDouble(map_value); + else if (key == "fx") + m.fx = GetCBORDouble(map_value); + else if (key == "fy") + m.fy = GetCBORDouble(map_value); + else if (key == "sx") + m.sx = GetCBORDouble(map_value); + else if (key == "sy") + m.sy = GetCBORDouble(map_value); + else + cbor_value_advance(&map_value); + } + cborErr(cbor_value_leave_container(&array_value, &map_value)); + modules.push_back(m); + } + cborErr(cbor_value_leave_container(&value, &array_value)); + } + bool ProcessStartMessageElement(StartMessage &message, CborValue &value) { if (cbor_value_at_end(&value)) return false; @@ -1370,6 +1421,8 @@ namespace { ProcessAzintMapElement(message, value); else if (key == "roi_map") ProcessROIMapElement(message, value); + else if (key == "detector_modules") + GetDetectorModules(value, message.detector_modules); else if (key == "channels") GetCBORStringArray(value, message.channels); else if (key == "detector_translation") diff --git a/frame_serialize/CBORStream2Serializer.cpp b/frame_serialize/CBORStream2Serializer.cpp index eaf732fd1..07412333e 100644 --- a/frame_serialize/CBORStream2Serializer.cpp +++ b/frame_serialize/CBORStream2Serializer.cpp @@ -238,6 +238,8 @@ inline void CBOR_ENC(CborEncoder &encoder, const SpotToSave& spot) { CBOR_ENC(mapEncoder, "indexed", spot.indexed); CBOR_ENC(mapEncoder, "latt", spot.lattice); CBOR_ENC(mapEncoder, "image", spot.image); + if (spot.panel >= 0) + CBOR_ENC(mapEncoder, "panel", static_cast(spot.panel)); if (spot.indexed) { CBOR_ENC(mapEncoder, "h", spot.h); CBOR_ENC(mapEncoder, "k", spot.k); @@ -484,6 +486,33 @@ inline void CBOR_ENC_AZINT_MAP(CborEncoder &encoder, const StartMessage &msg) { CBOR_ENC_2D_TYPED_ARRAY(encoder, image); } +// Not a DECTRIS field. Absent for a flat detector (no panel table), which is what every stream written +// before the key existed means. +inline void CBOR_ENC_DETECTOR_MODULES(CborEncoder &encoder, const std::vector &modules) { + if (modules.empty()) + return; + CborEncoder arrayEncoder; + cborErr(cbor_encode_text_stringz(&encoder, "detector_modules")); + cborErr(cbor_encoder_create_array(&encoder, &arrayEncoder, modules.size())); + for (const auto &m: modules) { + CborEncoder mapEncoder; + cborErr(cbor_encoder_create_map(&arrayEncoder, &mapEncoder, 10)); + CBOR_ENC(mapEncoder, "x0", m.x0); + CBOR_ENC(mapEncoder, "y0", m.y0); + CBOR_ENC(mapEncoder, "width", m.width); + CBOR_ENC(mapEncoder, "height", m.height); + const std::pair placement[] = { + {"ox", m.ox}, {"oy", m.oy}, {"fx", m.fx}, {"fy", m.fy}, {"sx", m.sx}, {"sy", m.sy} + }; + for (const auto &[key, val]: placement) { + cborErr(cbor_encode_text_stringz(&mapEncoder, key)); + cborErr(cbor_encode_double(&mapEncoder, val)); + } + cborErr(cbor_encoder_close_container(&arrayEncoder, &mapEncoder)); + } + cborErr(cbor_encoder_close_container(&encoder, &arrayEncoder)); +} + inline void CBOR_ENC_ROI_MAP(CborEncoder &encoder, const StartMessage &msg) { if (msg.roi_map.empty()) return; @@ -835,6 +864,7 @@ void CBORStream2Serializer::SerializeSequenceStart(const StartMessage& message) CBOR_ENC_PIXEL_MASK(mapEncoder, message); CBOR_ENC_AZINT_MAP(mapEncoder, message); CBOR_ENC_ROI_MAP(mapEncoder, message); + CBOR_ENC_DETECTOR_MODULES(mapEncoder, message.detector_modules); CBOR_ENC(mapEncoder, "channels", message.channels); CBOR_ENC(mapEncoder, "max_spot_count", message.max_spot_count); diff --git a/preview/PreviewImage.cpp b/preview/PreviewImage.cpp index b53b94cef..498ac408d 100644 --- a/preview/PreviewImage.cpp +++ b/preview/PreviewImage.cpp @@ -15,6 +15,7 @@ #include "../common/JFJochMath.h" #include "../common/ThreadAffinity.h" #include "../common/DiffractionGeometry.h" +#include "../common/AssembleToPlane.h" #include "../frame_serialize/CBORStream2Deserializer.h" #include "../compression/JFJochDecompress.h" #include "../image_analysis/bragg_integration/SystematicAbsence.h" @@ -50,8 +51,10 @@ constexpr const static rgb plotly[] = {{0x1f, 0x77, 0xb4}, constexpr const static rgb gray = {.r = 0xbe, .g = 0xbe, .b = 0xbe}; void PreviewImage::color_pixel(std::vector &ret, int64_t in_xpixel, int64_t in_ypixel,const rgb &color) const { - if ((in_xpixel >= 0) && (in_xpixel < xpixel) && (in_ypixel >= 0) && (in_ypixel < ypixel)) - ret[(in_ypixel * xpixel + in_xpixel)] = color; + const int64_t x = in_xpixel - canvas_x0; + const int64_t y = in_ypixel - canvas_y0; + if ((x >= 0) && (x < canvas_width) && (y >= 0) && (y < canvas_height)) + ret[(y * canvas_width + x)] = color; } void PreviewImage::spot(std::vector &ret, int64_t in_xpixel, int64_t in_ypixel, const rgb &color) const { @@ -387,7 +390,10 @@ void PreviewImage::Configure(const DiffractionExperiment &in_experiment, const P f.get(); } -std::vector PreviewImage::GenerateRGB(const PreviewImageSettings &settings, const DataMessage &msg) const { +std::vector PreviewImage::GenerateRGB(const PreviewImageSettings &settings, const DataMessage &msg, + size_t &width, size_t &height) const { + width = msg.image.GetWidth(); + height = msg.image.GetHeight(); std::vector v(msg.image.GetWidth() * msg.image.GetHeight()); if (msg.image.GetUncompressedSize() == 0) return {}; @@ -425,6 +431,22 @@ std::vector PreviewImage::GenerateRGB(const PreviewImageSettings &settings, throw JFJochException(JFJochExceptionCategory::InputParameterInvalid, "Mode not supported"); } + // The overlays are in detector-plane coordinates, so they are drawn on the image as it lies on the plane + const DetectorModules &modules = experiment.GetModules(); + canvas_x0 = 0; + canvas_y0 = 0; + canvas_width = static_cast(xpixel); + canvas_height = static_cast(ypixel); + if (!modules.empty()) { + const PlaneRaster raster = PlaneRasterOf(modules, canvas_width, canvas_height); + v = AssembleToPlane(modules, v, canvas_width, canvas_height, raster, + scale.Apply(ColorScaleSpecial::Gap)); + canvas_x0 = raster.x0; + canvas_y0 = raster.y0; + width = canvas_width = raster.width; + height = canvas_height = raster.height; + } + if (settings.show_spots) AddSpots(v, msg.spots); @@ -448,8 +470,9 @@ std::vector PreviewImage::GenerateRGB(const PreviewImageSettings &settings, } std::string PreviewImage::GenerateImage(const PreviewImageSettings& settings, const DataMessage &msg) const { - auto v = GenerateRGB(settings, msg); - CompressedImage rgb_image(v, msg.image.GetWidth(), msg.image.GetHeight()); + size_t width, height; + auto v = GenerateRGB(settings, msg, width, height); + CompressedImage rgb_image(v, width, height); switch (settings.format) { case PreviewImageFormat::JPEG: return WriteJPEGToMem(rgb_image, settings.jpeg_quality); diff --git a/preview/PreviewImage.h b/preview/PreviewImage.h index 001847da3..f197080d7 100644 --- a/preview/PreviewImage.h +++ b/preview/PreviewImage.h @@ -39,6 +39,10 @@ class PreviewImage { std::vector spots; size_t xpixel = 0; size_t ypixel = 0; + // The picture being drawn on, in detector-plane pixels: its top-left pixel and size. The stored image + // for a flat detector, the image gathered onto the plane (AssembleToPlane) for one with a panel table. + // Set by GenerateRGB under m, and the overlays are drawn there in plane coordinates. + mutable int64_t canvas_x0 = 0, canvas_y0 = 0, canvas_width = 0, canvas_height = 0; size_t pixel_depth_bytes = 2; bool pixel_is_signed = false; @@ -54,7 +58,8 @@ class PreviewImage { int64_t sat_value, const ColorScale &scale, const PreviewImageSettings& settings) const; - std::vector GenerateRGB(const PreviewImageSettings& settings, const DataMessage &msg) const; + std::vector GenerateRGB(const PreviewImageSettings& settings, const DataMessage &msg, + size_t &width, size_t &height) const; void AddResolutionRing(std::vector &rgb_image, float d) const; void AddBeamCenter(std::vector &rgb_image) const; diff --git a/reader/HDF5MetadataSource.cpp b/reader/HDF5MetadataSource.cpp index 33b287c0f..8b2299cee 100644 --- a/reader/HDF5MetadataSource.cpp +++ b/reader/HDF5MetadataSource.cpp @@ -1291,6 +1291,13 @@ static void ReadSpotsFromFiles(HDF5Object &master_file, {master_image, 0}, {source_image, 0}, {1, spot_count} ); + // Written only for a detector with a panel table. + auto spot_panel = ReadVectorMasterFirst( + master_file, source_file, + "/entry/MX/peakPanel", + {master_image, 0}, {source_image, 0}, {1, spot_count} + ); + message.spots.reserve(message.spots.size() + spot_count); for (size_t i = 0; i < spot_count; i++) { const auto x = spot_x.at(i); @@ -1317,6 +1324,8 @@ static void ReadSpotsFromFiles(HDF5Object &master_file, s.ice_ring = (spot_ice.at(i) != 0); if (spot_lattice.size() > i) s.lattice = spot_lattice.at(i); + if (spot_panel.size() > i) + s.panel = spot_panel.at(i); message.spots.emplace_back(s); } diff --git a/rugnux/RugnuxStills.cpp b/rugnux/RugnuxStills.cpp index 8f37aee11..361bcd1ed 100644 --- a/rugnux/RugnuxStills.cpp +++ b/rugnux/RugnuxStills.cpp @@ -89,12 +89,14 @@ using namespace rugnux_internal; namespace { -// The module of each spot, by where it lies on the detector plane (spots are on the plane already). +// The module of each spot: the panel the spot finder found it on, or - where the spot carries no panel id - +// the module where it lies on the detector plane (spots are on the plane already). void AssignModules(std::vector &frames, const DetectorModules &modules) { for (auto &f: frames) for (auto *list: {&f.spots, &f.unindexed}) for (auto &s: *list) - s.module = static_cast(modules.ModuleOfPlanePoint(s.x, s.y)); + if (s.module < 0) + s.module = static_cast(modules.ModuleOfPlanePoint(s.x, s.y)); } } // namespace @@ -217,9 +219,9 @@ void Rugnux::RefineStillsGeometry(int start_image, int end_image, int images_to_ for (const auto &s : msg.spots) { if (s.indexed && s.lattice == 0) f.spots.push_back(GeomRefineSpot{s.x, s.y, - static_cast(s.h), static_cast(s.k), static_cast(s.l)}); + static_cast(s.h), static_cast(s.k), static_cast(s.l), s.panel}); else - f.unindexed.push_back(GeomRefineSpot{s.x, s.y}); + f.unindexed.push_back(GeomRefineSpot{s.x, s.y, 0, 0, 0, s.panel}); } if (f.spots.size() >= 6) { if (static_cast(f.spots.size()) >= MIN_STRONG_SPOTS) diff --git a/tests/CBORTest.cpp b/tests/CBORTest.cpp index 8df4dd5a6..05b2e1790 100644 --- a/tests/CBORTest.cpp +++ b/tests/CBORTest.cpp @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: 2024 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only +#include #include #include "../frame_serialize/CBORStream2Serializer.h" @@ -1507,3 +1508,83 @@ TEST_CASE("CBORDeserialize_Start_CompressedLookupTable", "[CBOR]") { REQUIRE(deserialized->start_message); CHECK(deserialized->start_message->countrate_correction_lookup_table == lut); } + +// The panel id of a spot is a CBOR key only for a detector with a panel table: a spot with panel -1 +// serialises to the same bytes as before the key existed. +TEST_CASE("CBORSerialize_SpotPanelId", "[CBOR][PanelId]") { + std::vector buffer(1 << 20); + const std::string key = "panel"; + std::vector test(512); + CompressedImage image(test, 256, 2); + + auto serialize = [&](int16_t p0, int16_t p1) { + CBORStream2Serializer serializer(buffer.data(), buffer.size()); + DataMessage message{ + .number = 1, + .image = image, + .spots = {SpotToSave{.x = 7, .y = 8, .intensity = 34, .panel = p0}, + SpotToSave{.x = 37, .y = 48, .intensity = 123, .panel = p1}} + }; + serializer.SerializeImage(message); + return std::vector(buffer.begin(), buffer.begin() + serializer.GetBufferSize()); + }; + + const auto absent = serialize(-1, -1); + CHECK(std::search(absent.begin(), absent.end(), key.begin(), key.end()) == absent.end()); + auto deserialized = CBORStream2Deserialize(absent.data(), absent.size()); + REQUIRE(deserialized->data_message); + REQUIRE(deserialized->data_message->spots.size() == 2); + CHECK(deserialized->data_message->spots[0].panel == -1); + CHECK(deserialized->data_message->spots[1].panel == -1); + + const auto present = serialize(3, 0); + CHECK(std::search(present.begin(), present.end(), key.begin(), key.end()) != present.end()); + deserialized = CBORStream2Deserialize(present.data(), present.size()); + REQUIRE(deserialized->data_message); + REQUIRE(deserialized->data_message->spots.size() == 2); + CHECK(deserialized->data_message->spots[0].panel == 3); + CHECK(deserialized->data_message->spots[1].panel == 0); + CHECK(deserialized->data_message->spots[1].x == 37); +} + +// The start message carries the panel table only when there is one. +TEST_CASE("CBORSerialize_StartDetectorModules", "[CBOR][PanelId]") { + std::vector buffer(8 * 1024 * 1024); + const std::string key = "detector_modules"; + + StartMessage message{}; + message.image_size_x = 256; + message.image_size_y = 128; + { + CBORStream2Serializer serializer(buffer.data(), buffer.size()); + serializer.SerializeSequenceStart(message); + CHECK(std::search(buffer.begin(), buffer.begin() + serializer.GetBufferSize(), key.begin(), key.end()) + == buffer.begin() + serializer.GetBufferSize()); + auto deserialized = CBORStream2Deserialize(buffer.data(), serializer.GetBufferSize()); + REQUIRE(deserialized->start_message); + CHECK(deserialized->start_message->detector_modules.empty()); + } + + DetectorModule turned{.x0 = 0, .y0 = 64, .width = 256, .height = 64, + .ox = 300.25, .oy = -12.5, .fx = 0, .fy = 1, .sx = -1, .sy = 0}; + message.detector_modules = {DetectorModule::AsImaged(0, 0, 256, 64), turned}; + { + CBORStream2Serializer serializer(buffer.data(), buffer.size()); + serializer.SerializeSequenceStart(message); + auto deserialized = CBORStream2Deserialize(buffer.data(), serializer.GetBufferSize()); + REQUIRE(deserialized->start_message); + const auto &m = deserialized->start_message->detector_modules; + REQUIRE(m.size() == 2); + CHECK(m[0].x0 == 0); + CHECK(m[0].height == 64); + CHECK(m[0].fx == 1); + CHECK(m[1].y0 == 64); + CHECK(m[1].width == 256); + CHECK(m[1].ox == 300.25); + CHECK(m[1].oy == -12.5); + CHECK(m[1].fx == 0); + CHECK(m[1].fy == 1); + CHECK(m[1].sx == -1); + CHECK(m[1].sy == 0); + } +} diff --git a/tests/JFJochReaderTest.cpp b/tests/JFJochReaderTest.cpp index 1c83d63f7..7b13caef3 100644 --- a/tests/JFJochReaderTest.cpp +++ b/tests/JFJochReaderTest.cpp @@ -4931,3 +4931,75 @@ TEST_CASE("JFJochXTCReader", "[portable]") { std::filesystem::remove_all("xtc_test"); } + +// The panel id of spots goes to /entry/MX/peakPanel only for a detector with a panel table; for a flat +// detector the dataset is not written, so such files are unchanged. +TEST_CASE("JFJochReader_PanelId", "[HDF5][PanelId]") { + const auto format = GENERATE(FileWriterFormat::NXmxVDS, FileWriterFormat::NXmxLegacy, + FileWriterFormat::NXmxIntegrated); + const bool panels = GENERATE(true, false); + INFO("format " << static_cast(format) << " panels " << panels); + + DiffractionExperiment x(DetJF(1)); + x.FilePrefix("test_panel_id").ImagesPerTrigger(2).ImagesPerFile(10).OverwriteExistingFiles(true) + .BitDepthImage(16).PixelSigned(true).SetFileWriterFormat(format) + .IndexingAlgorithm(IndexingAlgorithmEnum::FFT).Compression(CompressionAlgorithm::NO_COMPRESSION); + if (panels) + x.Modules(DetectorModules({DetectorModule::AsImaged(0, 0, x.GetXPixelsNum(), x.GetYPixelsNum() / 2), + DetectorModule::AsImaged(0, x.GetYPixelsNum() / 2, x.GetXPixelsNum(), + x.GetYPixelsNum() / 2)})); + const int16_t p0 = panels ? 0 : -1; + const int16_t p1 = panels ? 1 : -1; + + std::vector image(x.GetPixelsNum()); + RegisterHDF5Filter(); + { + StartMessage start_message; + x.FillMessage(start_message); + CHECK(start_message.detector_modules.size() == (panels ? 2 : 0)); + FileWriter file_set(start_message); + + for (int i = 0; i < 2; i++) { + DataMessage message{}; + message.number = i; + message.image = CompressedImage(image, x.GetXPixelsNum(), x.GetYPixelsNum()); + message.indexing_result = true; + message.indexing_lattice = CrystalLattice(40, 50, 60, 90, 90, 90); + message.spots = {SpotToSave{.x = 10, .y = 50, .intensity = 80, .panel = p0}, + SpotToSave{.x = 20, .y = 400, .intensity = 90, .panel = p1}}; + REQUIRE_NOTHROW(file_set.WriteHDF5(message)); + } + + EndMessage end_message; + end_message.max_image_number = 2; + file_set.WriteHDF5(end_message); + file_set.Finalize(); + } + { + HDF5ReadOnlyFile master("test_panel_id_master.h5"); + const bool separate_data = format != FileWriterFormat::NXmxIntegrated; + // The master of a VDS set exposes it as a virtual dataset, the integrated file holds it itself + CHECK(master.Exists("/entry/MX/peakPanel") == (panels && format != FileWriterFormat::NXmxLegacy)); + if (separate_data) { + HDF5ReadOnlyFile data("test_panel_id_data_000001.h5"); + CHECK(data.Exists("/entry/MX/peakPanel") == panels); + } + } + { + JFJochHDF5Reader reader; + REQUIRE_NOTHROW(reader.ReadFile("test_panel_id_master.h5")); + for (int i = 0; i < 2; i++) { + std::shared_ptr reader_image; + REQUIRE_NOTHROW(reader_image = reader.LoadImage(i)); + REQUIRE(reader_image); + const auto &spots = reader_image->ImageData().spots; + REQUIRE(spots.size() == 2); + CHECK(spots[0].panel == p0); + CHECK(spots[1].panel == p1); + } + } + remove("test_panel_id_master.h5"); + remove("test_panel_id_data_000001.h5"); + + REQUIRE(H5Fget_obj_count(H5F_OBJ_ALL, H5F_OBJ_ALL) == 0); +} diff --git a/tests/TIFFTest.cpp b/tests/TIFFTest.cpp index df5e13b5e..ada324a7a 100644 --- a/tests/TIFFTest.cpp +++ b/tests/TIFFTest.cpp @@ -9,6 +9,8 @@ #include "../preview/PreviewImage.h" #include "../writer/HDF5Objects.h" #include "../common/RawToConvertedGeometry.h" +#include "../frame_serialize/CBORStream2Serializer.h" +#include #include TEST_CASE("TIFFTest","[TIFF]") { @@ -140,3 +142,57 @@ TEST_CASE("TIFFTest_File_float","[TIFF]") { CompressedImage image(values, 1024, 512); REQUIRE_NOTHROW(WriteTIFFToFile("test_image_float.tiff", image)); } + +// A detector with a panel table is previewed as it lies on the plane: two panels stacked in the stored +// image, placed side by side with a gap, come out side by side, the gap in the gap colour. +TEST_CASE("PreviewImage_PanelLayout", "[TIFF][PanelId]") { + DiffractionExperiment x(DetDECTRIS(64, 32, "test", "")); + x.BitDepthImage(16).PixelSigned(false); + DetectorModule right = DetectorModule::AsImaged(0, 16, 64, 16); + right.ox = 80; + right.oy = 0; + x.Modules(DetectorModules({DetectorModule::AsImaged(0, 0, 64, 16), right})); + + std::vector pixels(64 * 32, 0); + for (int i = 64 * 16; i < 64 * 32; i++) + pixels[i] = 1000; // above the foreground: the top of the colour scale + + PreviewImage preview; + preview.Configure(x, PixelMask(x)); + + std::vector buffer(1 << 20); + CBORStream2Serializer serializer(buffer.data(), buffer.size()); + DataMessage message{.number = 0, .image = CompressedImage(pixels, 64, 32)}; + serializer.SerializeImage(message); + buffer.resize(serializer.GetBufferSize()); + + PreviewImageSettings settings{.saturation_value = 10, .show_beam_center = false, .show_spots = false, + .format = PreviewImageFormat::TIFF}; + const std::string tiff = preview.GenerateImage(settings, buffer); + { + std::ofstream f("preview_panel_layout.tiff", std::ios::binary); + f.write(tiff.data(), tiff.size()); + } + + TIFF *t = TIFFOpen("preview_panel_layout.tiff", "r"); + REQUIRE(t); + uint32_t width = 0, height = 0; + TIFFGetField(t, TIFFTAG_IMAGEWIDTH, &width); + TIFFGetField(t, TIFFTAG_IMAGELENGTH, &height); + // Plane bounds [-0.5, 143.5) x [-0.5, 15.5): raster from -1, one pixel of margin on each side + CHECK(width == 145); + CHECK(height == 17); + + std::vector row(width); + REQUIRE(TIFFReadScanline(t, row.data(), 9) == 1); // plane y = 8 + TIFFClose(t); + remove("preview_panel_layout.tiff"); + + ColorScale scale; + scale.Select(settings.scale); + const rgb gap = scale.Apply(ColorScaleSpecial::Gap); + auto same = [](const rgb &a, const rgb &b) { return a.r == b.r && a.g == b.g && a.b == b.b; }; + CHECK(same(row[1 + 10], scale.ApplyLUTIndex(0))); // left panel: zero counts + CHECK(same(row[1 + 70], gap)); // the gap between the panels + CHECK(same(row[1 + 100], scale.ApplyLUTIndex(scale.LUTData().size() - 1))); // right panel: the top of the scale +} diff --git a/viewer/JFJochHttpReader.cpp b/viewer/JFJochHttpReader.cpp index 08d5026dd..66bbd52c2 100644 --- a/viewer/JFJochHttpReader.cpp +++ b/viewer/JFJochHttpReader.cpp @@ -224,6 +224,8 @@ std::shared_ptr JFJochHttpReader::UpdateDataset_i() { detector.MinCountTime(std::chrono::microseconds(0)); detector.ReadOutTime(std::chrono::microseconds (0)); dataset->experiment.Detector(detector); + // Absent (empty) for a flat detector, the image being the detector plane + dataset->experiment.Modules(DetectorModules(msg->start_message->detector_modules)); dataset->experiment.FrameTime( std::chrono::microseconds(std::lround(msg->start_message->frame_time * 1e6)), diff --git a/viewer/JFJochImageReadingWorker.cpp b/viewer/JFJochImageReadingWorker.cpp index e826608eb..5cb5fc729 100644 --- a/viewer/JFJochImageReadingWorker.cpp +++ b/viewer/JFJochImageReadingWorker.cpp @@ -795,16 +795,14 @@ void JFJochImageReadingWorker::MaskFromSelectedROI(QString name, bool add) { auto user_mask = current_image_ptr->Dataset().pixel_mask->GetUserMask(); auto geom = exp.GetDiffractionGeometry(); - const int64_t width = exp.GetXPixelsNum(); - const int64_t height = exp.GetYPixelsNum(); - for (int64_t y = 0; y < height; y++) { - for (int64_t x = 0; x < width; x++) { - const float res = geom.PxlToRes(x, y); - const float phi = geom.Phi_rad(x, y) * 180.0f / static_cast(PI); - if (elem->CheckROI(x, y, res, phi)) - user_mask[x + y * width] = add ? 1 : 0; - } - } + // ROIs are drawn on the detector plane, so each stored pixel is tested where it is on the plane + exp.GetModules().ForEachPixel(exp.GetXPixelsNum(), exp.GetYPixelsNum(), + [&](int64_t, size_t index, double px, double py) { + const float res = geom.PxlToRes(px, py); + const float phi = geom.Phi_rad(px, py) * 180.0f / static_cast(PI); + if (elem->CheckROI(std::lround(px), std::lround(py), res, phi)) + user_mask[index] = add ? 1 : 0; + }); UpdateUserMask_i(user_mask); } diff --git a/viewer/JFJochViewerWindow.cpp b/viewer/JFJochViewerWindow.cpp index b8e80e822..dec091923 100644 --- a/viewer/JFJochViewerWindow.cpp +++ b/viewer/JFJochViewerWindow.cpp @@ -497,8 +497,8 @@ JFJochViewerWindow::JFJochViewerWindow(QWidget *parent, bool dbus, const QString magnifier->setFrame(viewer->Frame()); }); - // ... and the raw counts behind it, for the per-pixel labels. Stores a pointer, nothing more. - connect(this, &JFJochViewerWindow::imageReady, + // ... and the counts behind it, for the per-pixel labels. Stores a pointer, nothing more. + connect(viewer, &JFJochDiffractionImage::pixelsChanged, magnifier, &JFJochViewerMagnifier::setPixelValues); connect(viewer, &JFJochDiffractionImage::magnifierMoved, magnifier, &JFJochViewerMagnifier::centerAt); diff --git a/viewer/image_viewer/JFJochDiffractionImage.cpp b/viewer/image_viewer/JFJochDiffractionImage.cpp index 7a00854c1..479fec07d 100644 --- a/viewer/image_viewer/JFJochDiffractionImage.cpp +++ b/viewer/image_viewer/JFJochDiffractionImage.cpp @@ -7,6 +7,7 @@ #include "../../common/DiffractionGeometry.h" #include "../../common/JFJochMath.h" #include "../../common/ROIAzimuthal.h" +#include "../../common/AssembleToPlane.h" #include "../../image_analysis/bragg_integration/SystematicAbsence.h" #include "../widgets/ROIColorPalette.h" @@ -82,20 +83,21 @@ void JFJochDiffractionImage::azimuthalHandles(const ROIAzimuthal &az, const Diff void JFJochDiffractionImage::mouseHover(const QPointF &coord, Qt::KeyboardModifiers modifiers) { // Shift + a button is ROI drawing, not magnifying if ((modifiers & Qt::ShiftModifier) && mouse_event_type == MouseEventType::None) { - emit magnifierMoved(coord); + emit magnifierMoved(coord - origin_); SetMagnifierFrame(QRectF(coord - QPointF(magnifier_field_.width(), magnifier_field_.height()) / 2, magnifier_field_)); } else SetMagnifierFrame(QRectF()); - if (image && (coord.x() >= 0) - && (coord.x() < image->Dataset().experiment.GetXPixelsNum()) - && (coord.y() >= 0) - && (coord.y() < image->Dataset().experiment.GetYPixelsNum())) { + // Pixel of the shown image under the cursor; the scene is the detector plane + const QPointF pxl = coord - origin_; + if (image && (pxl.x() >= 0) + && (pxl.x() < W) + && (pxl.y() >= 0) + && (pxl.y() < H)) { float res = image->Dataset().experiment.GetDiffractionGeometry().PxlToRes(coord.x(), coord.y()); - int32_t intensity = image->Image()[std::floor(coord.x()) + - std::floor(coord.y()) * image->Dataset().experiment.GetXPixelsNum()]; + int32_t intensity = (*pixels_)[std::floor(pxl.x()) + std::floor(pxl.y()) * W]; QString intensity_str = QString("I=%1").arg(intensity, 9); @@ -133,13 +135,43 @@ void JFJochDiffractionImage::LoadImageInternal() { if (!image) return; - W = image->Dataset().experiment.GetXPixelsNum(); - H = image->Dataset().experiment.GetYPixelsNum(); + const auto &experiment = image->Dataset().experiment; + const DetectorModules &modules = experiment.GetModules(); + const int64_t width = experiment.GetXPixelsNum(); + const int64_t height = experiment.GetYPixelsNum(); + if (modules.empty()) { + W = width; + H = height; + origin_ = QPointF(0, 0); + pixels_ = std::shared_ptr>(image, &image->Image()); + } else { + const PlaneRaster raster = PlaneRasterOf(modules, width, height); + W = raster.width; + H = raster.height; + origin_ = QPointF(static_cast(raster.x0), static_cast(raster.y0)); + pixels_ = std::make_shared>( + AssembleToPlane(modules, image->Image(), width, height, raster, GAP_PXL_VALUE)); + } + emit pixelsChanged(pixels_); +} + +std::optional JFJochDiffractionImage::StoredPixelToScene(int64_t index) const { + const auto &experiment = image->Dataset().experiment; + const int64_t x = index % experiment.GetXPixelsNum(); + const int64_t y = index / experiment.GetXPixelsNum(); + const DetectorModules &modules = experiment.GetModules(); + if (modules.empty()) + return QPointF(x + 0.5, y + 0.5); + const int64_t panel = modules.ModuleOfImagePixel(static_cast(x), static_cast(y)); + if (panel < 0) + return std::nullopt; + const auto [px, py] = modules.ImageToPlane(panel, static_cast(x), static_cast(y)); + return QPointF(px + 0.5, py + 0.5); } void JFJochDiffractionImage::ColorRow(size_t y, const PixelColorMap &map, QRgb *out) const { - const int32_t *row = &image->Image()[y * W]; + const int32_t *row = &(*pixels_)[y * W]; for (size_t x = 0; x < W; ++x) { const int32_t v = row[x]; @@ -260,11 +292,12 @@ void JFJochDiffractionImage::DrawResolutionRings() { // position in its parent). QRectF visibleRect = mapToScene(viewport()->rect()).boundingRect(); - int startX = std::max(0, static_cast(std::floor(visibleRect.left()))); - int endX = std::min(static_cast(image->Dataset().experiment.GetXPixelsNum()), + const QRectF image_rect = ImageRect(); + int startX = std::max(static_cast(image_rect.left()), static_cast(std::floor(visibleRect.left()))); + int endX = std::min(static_cast(image_rect.right()), static_cast(std::ceil(visibleRect.right()))); - int startY = std::max(0, static_cast(std::floor(visibleRect.top()))); - int endY = std::min(static_cast(image->Dataset().experiment.GetYPixelsNum()), + int startY = std::max(static_cast(image_rect.top()), static_cast(std::floor(visibleRect.top()))); + int endY = std::min(static_cast(image_rect.bottom()), static_cast(std::ceil(visibleRect.bottom()))); auto geom = image->Dataset().experiment.GetDiffractionGeometry(); @@ -326,10 +359,10 @@ void JFJochDiffractionImage::DrawResolutionRings() { ring_cache_key_ = res_ring; ring_cache_.clear(); - float res1 = geom.PxlToRes(0,0); - float res2 = geom.PxlToRes(image->Dataset().experiment.GetXPixelsNum(),0); - float res3 = geom.PxlToRes(image->Dataset().experiment.GetXPixelsNum(),image->Dataset().experiment.GetYPixelsNum()); - float res4 = geom.PxlToRes(0,image->Dataset().experiment.GetYPixelsNum()); + float res1 = geom.PxlToRes(image_rect.left(), image_rect.top()); + float res2 = geom.PxlToRes(image_rect.right(), image_rect.top()); + float res3 = geom.PxlToRes(image_rect.right(), image_rect.bottom()); + float res4 = geom.PxlToRes(image_rect.left(), image_rect.bottom()); float min_res = std::min({res1, res2, res3, res4}); @@ -439,7 +472,7 @@ void JFJochDiffractionImage::DrawResolutionRings() { const auto map_zero = color_scale.Apply(0.0f); const double zero_luminance = 0.2126 * map_zero.r + 0.7152 * map_zero.g + 0.0722 * map_zero.b; const bool dark_under = zero_luminance <= 127.0 - && QRectF(0, 0, static_cast(W), static_cast(H)).contains(r.center()); + && ImageRect().contains(r.center()); textItem->setBrush(dark_under ? QColor(Qt::white) : QColor(0x20, 0x20, 0x20)); textItem->setPos(r.topLeft()); scene()->addItem(textItem); @@ -478,10 +511,10 @@ void JFJochDiffractionImage::DrawTopPixels() { if (i >= show_highest_pixels) break; - const int32_t idx = p.second; - const float x = idx % image->Dataset().experiment.GetXPixelsNum() + 0.5; - const float y = idx / image->Dataset().experiment.GetXPixelsNum() + 0.5; - const QRectF box(x - half_size, y - half_size, 2 * half_size, 2 * half_size); + const auto pos = StoredPixelToScene(p.second); + if (!pos) + continue; + const QRectF box(pos->x() - half_size, pos->y() - half_size, 2 * half_size, 2 * half_size); for (const QPen &p_i : {casing_pen, pen}) { // casing first, so it stays underneath auto *rect = scene()->addRect(box, p_i); rect->setZValue(1); @@ -973,7 +1006,9 @@ void JFJochDiffractionImage::loadImage(std::shared_ptr Redraw(); } else { image.reset(); + pixels_.reset(); W = 0; H = 0; + origin_ = QPointF(0, 0); ClearFrame(); // followers (magnifier) must not keep showing the old frame if (scene()) scene()->clear(); @@ -1062,17 +1097,14 @@ void JFJochDiffractionImage::DrawSaturation() { constexpr size_t max_crosses = 5000; const QRectF visibleRect = mapToScene(viewport()->geometry()).boundingRect(); - const auto x_pixels = image->Dataset().experiment.GetXPixelsNum(); - size_t drawn = 0; for (const auto &iter: image->SaturatedPixels()) { - const float x = iter % x_pixels + 0.5; - const float y = iter / x_pixels + 0.5; - if (!visibleRect.contains(QPointF{x, y})) + const auto pos = StoredPixelToScene(iter); + if (!pos || !visibleRect.contains(*pos)) continue; if (drawn++ >= max_crosses) break; - DrawCross(x, y, 20, 4); + DrawCross(pos->x(), pos->y(), 20, 4); } } @@ -1147,7 +1179,7 @@ QString JFJochDiffractionImage::PixelLabel(int x, int y) const { if (!image) return {}; - const int32_t v = image->Image()[static_cast(y) * W + x]; + const int32_t v = (*pixels_)[static_cast(y) * W + x]; if (v == GAP_PXL_VALUE) return QStringLiteral("Gap"); if (v == ERROR_PXL_VALUE) diff --git a/viewer/image_viewer/JFJochDiffractionImage.h b/viewer/image_viewer/JFJochDiffractionImage.h index 4d05280ad..5c9a2e746 100644 --- a/viewer/image_viewer/JFJochDiffractionImage.h +++ b/viewer/image_viewer/JFJochDiffractionImage.h @@ -108,6 +108,12 @@ private: void leaveEvent(QEvent *event) override; std::shared_ptr image; + // What is shown: the image itself for a flat detector, else the image gathered onto the detector + // plane (AssembleToPlane), whose top-left pixel sits at origin_. The scene is the detector plane + // either way, so spots, predictions, rings and ROIs are drawn where the geometry puts them. + std::shared_ptr> pixels_; + // Scene position of a pixel of the stored image (index into image->Image()); empty in a gap. + [[nodiscard]] std::optional StoredPixelToScene(int64_t index) const; int32_t show_highest_pixels = 0; @@ -141,7 +147,8 @@ private: void SetMagnifierFrame(const QRectF &r); signals: - void magnifierMoved(QPointF scenePos); + void magnifierMoved(QPointF scenePos); // in pixels of the shown image, as the magnifier has them + void pixelsChanged(std::shared_ptr> pixels); // the shown image changed void roiGeometryEdited(ROIDefinition rois); void roiSelected(QString name); // user picked an ROI by clicking it on the image public slots: diff --git a/viewer/image_viewer/JFJochFollowerImage.cpp b/viewer/image_viewer/JFJochFollowerImage.cpp index 9b1094acd..081304b8c 100644 --- a/viewer/image_viewer/JFJochFollowerImage.cpp +++ b/viewer/image_viewer/JFJochFollowerImage.cpp @@ -63,8 +63,8 @@ void JFJochFollowerImage::SetFrame(std::shared_ptr frame) { viewport()->update(); } -void JFJochFollowerImage::SetPixelValues(std::shared_ptr image) { - values_ = std::move(image); +void JFJochFollowerImage::SetPixelValues(std::shared_ptr> pixels) { + values_ = std::move(pixels); } void JFJochFollowerImage::CenterAt(QPointF scenePos) { @@ -104,7 +104,7 @@ void JFJochFollowerImage::drawForeground(QPainter *painter, const QRectF &rect) const int W = frame_->width(); const int H = frame_->height(); - const auto &pixels = values_->Image(); + const auto &pixels = *values_; if (static_cast(pixels.size()) < static_cast(W) * H) return; // values belong to a different frame diff --git a/viewer/image_viewer/JFJochFollowerImage.h b/viewer/image_viewer/JFJochFollowerImage.h index 5eab0ef80..9fdbac68e 100644 --- a/viewer/image_viewer/JFJochFollowerImage.h +++ b/viewer/image_viewer/JFJochFollowerImage.h @@ -29,7 +29,7 @@ class JFJochFollowerImage : public QGraphicsView { JFJochImageItem *item_ = nullptr; std::shared_ptr frame_; QSize frame_size_; // size the scene rect was set from - std::shared_ptr values_; + std::shared_ptr> values_; // the counts behind the frame, row by row double zoom_ = 12.0; int label_font_px_ = 0; // 0 = no per-pixel labels QPointF center_; @@ -42,7 +42,7 @@ public: explicit JFJochFollowerImage(QWidget *parent = nullptr); void SetFrame(std::shared_ptr frame); - void SetPixelValues(std::shared_ptr image); + void SetPixelValues(std::shared_ptr> pixels); void CenterAt(QPointF scenePos); // Screen pixels per detector pixel, and the pixel size of the value labels (0 = none) void SetZoom(double zoom, int label_font_px); diff --git a/viewer/image_viewer/JFJochImage.cpp b/viewer/image_viewer/JFJochImage.cpp index 92175aaba..068ccb035 100644 --- a/viewer/image_viewer/JFJochImage.cpp +++ b/viewer/image_viewer/JFJochImage.cpp @@ -257,7 +257,7 @@ void JFJochImage::resizeEvent(QResizeEvent *event) { QGraphicsView::resizeEvent(event); if (scene()) - scene()->setSceneRect(QRectF(0, 0, static_cast(W), static_cast(H))); + scene()->setSceneRect(ImageRect()); // Retry a deferred initial fit: fitToViewShorterSideOnce() skips fitting while the viewport has no // real size yet (before the widget is laid out/shown), leaving the view at 1:1 - a small grid-scan @@ -552,8 +552,7 @@ QImage JFJochImage::renderToImage(bool with_overlay) { img = QImage(int(W), int(H), QImage::Format_ARGB32_Premultiplied); img.fill(Qt::transparent); QPainter p(&img); - const QRectF rect(0, 0, qreal(W), qreal(H)); - scene()->render(&p, rect, rect); + scene()->render(&p, QRectF(0, 0, qreal(W), qreal(H)), ImageRect()); p.end(); } else { // The underlying rendered image (no overlay) @@ -888,7 +887,7 @@ void JFJochImage::ClearFrame() { void JFJochImage::centerOnSpot(QPointF point) { // If W or H = 0, then conditions are never satisfied - if (point.x() >= 0 && point.x() < W && point.y() >= 0 && point.y() < H) + if (ImageRect().contains(point)) centerOn(point); emitViewportChanged(); } @@ -944,7 +943,8 @@ void JFJochImage::drawPixelLabels(QPainter *painter, const QRectF &rect) { // Only the exposed area, not the whole viewport: a hover repaint dirties a couple of hundred // pixels, and laying out every visible cell for it would do thousands of mapFromScene / pixel / // drawText calls whose output is then clipped away - at up to 15 repaints a second. - const QRectF visibleRect = mapToScene(viewport()->rect()).boundingRect() & rect; + // In image pixels, i.e. relative to the scene origin of the image + const QRectF visibleRect = (mapToScene(viewport()->rect()).boundingRect() & rect).translated(-origin_); const int startX = std::max(0, static_cast(std::floor(visibleRect.left()))); const int endX = std::min(static_cast(W), static_cast(std::ceil(visibleRect.right()))); const int startY = std::max(0, static_cast(std::floor(visibleRect.top()))); @@ -965,7 +965,7 @@ void JFJochImage::drawPixelLabels(QPainter *painter, const QRectF &rect) { for (int y = startY; y < endY; y++) { for (int x = startX; x < endX; x++) { - const QRect cell = mapFromScene(QRectF(x, y, 1, 1)).boundingRect(); + const QRect cell = mapFromScene(QRectF(QPointF(x, y) + origin_, QSizeF(1, 1))).boundingRect(); // Read the colour back from the rendered image rather than keeping a full-size // mirror of it around for the few pixels that get a label. const QRgb pxl = frame_->pixel(x, y); @@ -1013,6 +1013,7 @@ void JFJochImage::updateOverlay() { image_item_->refresh(); image_dirty_ = false; } + image_item_->setPos(origin_); DrawROI(); @@ -1046,7 +1047,7 @@ void JFJochImage::fitToViewShorterSideOnce() { return; // resizeEvent / showEvent will retry once the layout has settled if (scene()) - scene()->setSceneRect(QRectF(0, 0, static_cast(W), static_cast(H))); + scene()->setSceneRect(ImageRect()); const auto oldAnchor = transformationAnchor(); setTransformationAnchor(QGraphicsView::AnchorViewCenter); @@ -1059,7 +1060,7 @@ void JFJochImage::fitToViewShorterSideOnce() { scale(1.0, pixel_aspect_); scale_factor = transform().m11(); - centerOn(QPointF(static_cast(W) * 0.5, static_cast(H) * 0.5)); + centerOn(ImageRect().center()); setTransformationAnchor(oldAnchor); initial_fit_done_ = true; diff --git a/viewer/image_viewer/JFJochImage.h b/viewer/image_viewer/JFJochImage.h index 8df28da8e..470877e0a 100644 --- a/viewer/image_viewer/JFJochImage.h +++ b/viewer/image_viewer/JFJochImage.h @@ -108,6 +108,10 @@ protected: double scale_factor = 1.0; size_t W = 0, H = 0; + // Scene position of the image's top-left pixel: the image covers [origin_, origin_ + (W, H)) of the + // scene. Zero but for a detector plane raster that starts elsewhere (JFJochDiffractionImage). + QPointF origin_{0, 0}; + [[nodiscard]] QRectF ImageRect() const { return {origin_, QSizeF(static_cast(W), static_cast(H))}; } size_t prev_W = 0, prev_H = 0; // Height of one pixel as it is drawn, in units of its width. 1.0 for a detector image, where diff --git a/viewer/widgets/JFJochViewerMagnifier.cpp b/viewer/widgets/JFJochViewerMagnifier.cpp index 9bb4cc24a..82d5035da 100644 --- a/viewer/widgets/JFJochViewerMagnifier.cpp +++ b/viewer/widgets/JFJochViewerMagnifier.cpp @@ -61,8 +61,8 @@ void JFJochViewerMagnifier::setFrame(std::shared_ptr frame) { image_->SetFrame(std::move(frame)); } -void JFJochViewerMagnifier::setPixelValues(std::shared_ptr image) { - image_->SetPixelValues(std::move(image)); +void JFJochViewerMagnifier::setPixelValues(std::shared_ptr> pixels) { + image_->SetPixelValues(std::move(pixels)); } void JFJochViewerMagnifier::centerAt(QPointF scenePos) { diff --git a/viewer/widgets/JFJochViewerMagnifier.h b/viewer/widgets/JFJochViewerMagnifier.h index 692b498a6..10196a282 100644 --- a/viewer/widgets/JFJochViewerMagnifier.h +++ b/viewer/widgets/JFJochViewerMagnifier.h @@ -30,6 +30,6 @@ public: void setPoppedOut(bool on); public slots: void setFrame(std::shared_ptr frame); - void setPixelValues(std::shared_ptr image); + void setPixelValues(std::shared_ptr> pixels); void centerAt(QPointF scenePos); }; diff --git a/writer/HDF5DataFilePluginMX.cpp b/writer/HDF5DataFilePluginMX.cpp index 3acf351ab..dfe604710 100644 --- a/writer/HDF5DataFilePluginMX.cpp +++ b/writer/HDF5DataFilePluginMX.cpp @@ -67,6 +67,7 @@ void HDF5DataFilePluginMX::OpenFile(HDF5File &data_file, const DataMessage &msg, spot_k.reserve(max_spots * images_per_file); spot_l.reserve(max_spots * images_per_file); spot_dist_ewald.reserve(max_spots * images_per_file); + spot_panel.reserve(max_spots * images_per_file); if (indexing) { spot_indexed.reserve(max_spots * images_per_file); @@ -120,6 +121,7 @@ void HDF5DataFilePluginMX::Write(const DataMessage &msg, uint64_t image_number) spot_l.resize(max_spots * (max_image_number + 1)); spot_lattice.resize(max_spots * (max_image_number + 1), -1); spot_dist_ewald.resize(max_spots * (max_image_number + 1), NAN); + spot_panel.resize(max_spots * (max_image_number + 1), -1); if (indexing) { spot_indexed.resize(max_spots * (max_image_number + 1)); @@ -134,6 +136,9 @@ void HDF5DataFilePluginMX::Write(const DataMessage &msg, uint64_t image_number) spot_x[max_spots * image_number + i] = msg.spots[i].x; spot_y[max_spots * image_number + i] = msg.spots[i].y; spot_int[max_spots * image_number + i] = msg.spots[i].intensity; + spot_panel[max_spots * image_number + i] = msg.spots[i].panel; + if (msg.spots[i].panel >= 0) + spot_panel_present = true; if (indexing) { spot_indexed[max_spots * image_number + i] = msg.spots[i].indexed; spot_lattice[max_spots * image_number + i] = msg.spots[i].lattice; @@ -213,6 +218,8 @@ void HDF5DataFilePluginMX::WriteFinal(HDF5File &data_file) { data_file.SaveVector("/entry/MX/peakTotalIntensity", spot_int, {(hsize_t) (max_image_number + 1), max_spots}); data_file.SaveVector("/entry/MX/peakIceRingRes", spot_ice_ring, {(hsize_t) (max_image_number + 1), max_spots}); data_file.SaveVector("/entry/MX/nPeaks", npeaks.vec()); + if (spot_panel_present) + data_file.SaveVector("/entry/MX/peakPanel", spot_panel, {(hsize_t) (max_image_number + 1), max_spots}); if (indexing) { data_file.SaveVector("/entry/MX/peakH", spot_h, {(hsize_t) (max_image_number + 1), max_spots}); diff --git a/writer/HDF5DataFilePluginMX.h b/writer/HDF5DataFilePluginMX.h index d369f8b0d..df418e6ff 100644 --- a/writer/HDF5DataFilePluginMX.h +++ b/writer/HDF5DataFilePluginMX.h @@ -21,6 +21,8 @@ class HDF5DataFilePluginMX : public HDF5DataFilePlugin { std::vector spot_k; std::vector spot_l; std::vector spot_dist_ewald; + std::vector spot_panel; + bool spot_panel_present = false; // written only for a detector with a panel table AutoIncrVector beam_corr_x{NAN}; AutoIncrVector beam_corr_y{NAN}; diff --git a/writer/HDF5NXmx.cpp b/writer/HDF5NXmx.cpp index 6f99af71f..d8503b112 100644 --- a/writer/HDF5NXmx.cpp +++ b/writer/HDF5NXmx.cpp @@ -132,6 +132,8 @@ void NXmx::LinkToData_VDS(const StartMessage &start, const EndMessage &end) { VDS(start, "/entry/MX/peakTotalIntensity",{total_images, start.max_spot_count}, HDF5DataType(0.0f)); VDS(start, "/entry/MX/peakIceRingRes", {total_images, start.max_spot_count}, HDF5DataType(static_cast(0))); VDS(start, "/entry/MX/nPeaks", {total_images}, HDF5DataType((uint32_t) 0)); + if (!start.detector_modules.empty()) + VDS(start, "/entry/MX/peakPanel", {total_images, start.max_spot_count}, HDF5DataType(static_cast(-1)), -1); } if (start.indexing_algorithm != IndexingAlgorithmEnum::None) {