Files
Jungfraujoch/receiver/JFJochReceiverRugnuxStills.cpp
leonarski_fandjungfrau 0eef505094
Build Packages / Create release (push) Successful in 8s
Build Packages / Build documentation (push) Successful in 1m44s
Build Packages / build:portable:macos-arm64:nocuda (push) Successful in 5m8s
Build Packages / build:portable:linux-x86_64:nocuda (push) Successful in 19m9s
Build Packages / build:rugnux:linux-aarch64:cuda (push) Successful in 13m32s
Build Packages / build:portable:windows-x86_64:nocuda (push) Successful in 23m14s
Build Packages / build:portable:linux-x86_64:cuda (push) Successful in 24m10s
Build Packages / build:portable:windows-x86_64:cuda (push) Successful in 27m26s
Build Packages / build:jfjoch:ubuntu2204:nocuda (push) Successful in 29m3s
Build Packages / build:jfjoch:rocky8:nocuda (push) Successful in 34m59s
Build Packages / build:jfjoch:ubuntu2404:nocuda (push) Successful in 34m39s
Build Packages / build:jfjoch:rocky9:nocuda (push) Successful in 36m45s
Build Packages / build:jfjoch:rocky8:cuda-sls9 (push) Successful in 37m51s
Build Packages / Generate python client (push) Successful in 35s
Build Packages / build:jfjoch:rocky8:cuda (push) Successful in 35m28s
Build Packages / build:jfjoch:rocky9:cuda-sls9 (push) Successful in 39m15s
Build Packages / build:jfjoch:ubuntu2204:cuda (push) Successful in 24m58s
Build Packages / Unit tests (push) Successful in 1h3m58s
Build Packages / HDF5 consumer tests (DIALS, XDS) (push) Successful in 23m15s
Build Packages / build:jfjoch:rocky9:cuda (push) Successful in 30m54s
Build Packages / build:jfjoch:ubuntu2404:cuda (push) Successful in 26m54s
Build Packages / Validation Battery (push) Successful in 33m25s
v1.0.0-rc.189 (#100)
* Rugnux: More reliable beam centre for stills and short wedges whose file centre is far off; fewer false beam-centre warnings on stills.
* Rugnux: Correct completeness and resolution shells when merging stills that each carry their own cell; the merged MTZ carries multiplicity columns N, N(+) and N(-).
* Rugnux: The space-group report warns where a higher symmetry rests on weak evidence and leaves a screw axis the data cannot test undetermined; more robust joint processing of several sweeps.
* Readers: SMV files with an ADSC header followed by a d*TREK block; NXmx files without beam centre, distance or pixel size take them from the module geometry, and micron units are accepted.
* jfjoch_broker: The JUNGFRAU timing master module is configurable (`master_module` in the detector settings); live stills count a frame as collected only once it is held for writing.
* PCIe driver: RS-FEC error correction is enabled on 100G links; the CMAC RX and RS-FEC status can be read in sysfs.

---------

Co-authored-by: jungfrau <jungfrau@mx-aare-test.psi.ch>
Reviewed-on: #100
Co-authored-by: Filip Leonarski <filip.leonarski@psi.ch>
2026-11-25 08:39:18 +01:00

257 lines
12 KiB
C++

// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
// SPDX-License-Identifier: GPL-3.0-only
#include "JFJochReceiverRugnuxStills.h"
#include <cstring>
#include <thread>
#include "../common/CUDAWrapper.h"
#include "../common/time_utc.h"
#include "../frame_serialize/CBORStream2Serializer.h"
#include "../rugnux/Rugnux.h"
#include "../rugnux/RugnuxDefaults.h"
#include "RugnuxStructure.h"
#include "StillsSelection.h"
JFJochReceiverRugnuxStills::JFJochReceiverRugnuxStills(const DiffractionExperiment &in_experiment,
const PixelMask &in_pixel_mask,
ImagePuller &in_image_puller,
ImagePusher &in_image_pusher,
Logger &in_logger,
int64_t in_forward_nthreads,
std::shared_ptr<const RugnuxModel> in_model,
double in_deadline_s,
bool in_refine_solvent,
RugnuxLiveStatus &in_live_status,
const SpotFindingSettings &in_spot_finding_settings,
JFJochReceiverCurrentStatus &in_current_status,
JFJochReceiverPlots &in_plots,
ImageBuffer &in_image_buffer,
ZMQPreviewSocket *in_zmq_preview_socket,
ZMQMetadataSocket *in_zmq_metadata_socket,
IndexerThreadPool *in_indexing_thread_pool,
int64_t in_downsample,
int64_t in_prepass_images)
: JFJochReceiverStream(in_experiment, in_pixel_mask, in_image_puller, in_image_pusher, in_logger,
in_forward_nthreads, in_spot_finding_settings, in_current_status, in_plots,
in_image_buffer, in_zmq_preview_socket, in_zmq_metadata_socket),
model(std::move(in_model)),
deadline_s(in_deadline_s),
refine_solvent(in_refine_solvent),
downsample(in_downsample),
prepass_images(in_prepass_images),
live_status(in_live_status),
indexing_thread_pool(in_indexing_thread_pool),
// As offline rugnux's per-image loop: 16 a card (fewer where a card's memory does not hold them), whatever
// the receiver's own thread count
stills_nthreads(get_gpu_count() > 0 ? GPUWorkersPerCard(in_experiment.GetPixelsNum(), 16) * get_gpu_count()
: static_cast<int>(in_forward_nthreads)) {
StartThreads();
}
JFJochReceiverRugnuxStills::~JFJochReceiverRugnuxStills() {
cancelled = true;
JoinThreads();
}
void JFJochReceiverRugnuxStills::OnStart(std::chrono::steady_clock::time_point received) {
// The frames that wait take a slot each, at most half of the slots; the other half is for those analysed, sent
// from a slot each. Nothing is sent before the pre-pass, so it holds half of the slots, whatever the frames: the
// receiver service has checked that its images fit (CheckStillsPrePassFits).
const int64_t slots = image_buffer.GetStatus().total_slots;
hold_keep_free = slots - slots / 2;
const StartMessage start = MakeStartMessage(experiment, pixel_mask, *az_int_mapping);
// The frames are shown from their arrival, on the stated geometry until the pre-pass has decided its own.
// To the image buffer only: the writer and the ZeroMQ streams get the one start message, after the pre-pass.
SaveStartMessageToImageBuffer(start);
// A rotation collection here was sent the stills way (force_still): the analysis takes its frames without the
// goniometer, as `rugnux --force-still` reads them. The writer keeps it (StillsReady).
DiffractionExperiment analysis_experiment(experiment);
StartMessage analysis_start(start);
if (RugnuxRotationData(experiment)) {
analysis_experiment.Goniometer(std::nullopt);
analysis_start.goniometer.reset();
}
auto analysis = std::make_unique<StillsGPUAnalysis>(
analysis_experiment, pixel_mask, analysis_start,
indexing_thread_pool, stills_nthreads,
prepass_images, logger,
*this, live_status, true, model, deadline_s, refine_solvent);
std::unique_lock ul(stills_mutex);
stills = std::move(analysis);
if (cut)
stills->Cut("cancel");
}
void JFJochReceiverRugnuxStills::OnImage(uint32_t id, DataMessage &message, std::chrono::steady_clock::time_point received) {
// The analysis keeps per-image results by number, for the images the collection declares; the stream is not ours.
if (message.number < 0 || message.number >= experiment.GetImageNum()) {
logger.Error("Dropping image {} - the collection has {} images", message.number, experiment.GetImageNum());
return;
}
live_status.ImageReceived(received);
const size_t size = message.image.GetCompressedSize();
// Waits for the analysis in a slot of the image buffer, where it can be seen while it waits (it is not sent from
// there). With no slot to take, the frame waits until the analysis has made room: the pre-pass's images fit the
// slots (OnStart). No frame is lost here; a source faster than the analysis loses frames at the card.
auto held = std::make_shared<HeldImage>();
held->slot = image_buffer.GetImageSlot(hold_keep_free);
while (!held->slot && !cancelled) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
held->slot = image_buffer.GetImageSlot(hold_keep_free);
}
if (!held->slot)
return; // cancelled while it waited: dropped like a frame arriving after the cancel, and not counted
CountImage(message);
// Not chosen (stills_downsample): written as it came, without its analysis
held->analyse = StillsImageSelected(message.number, downsample, prepass_images);
held->message = message;
StampImage(held->message, image_puller.GetCurrentFifoUtilization());
// In the slot as an image without analysis; the analysis reads the image where it is in the slot.
auto slot_buffer = static_cast<uint8_t *>(held->slot->GetImage());
CBORStream2Serializer serializer(slot_buffer, experiment.GetImageBufferLocationSize());
held->message.image = CompressedImage(nullptr, 0, message.image.GetWidth(), message.image.GetHeight(),
message.image.GetMode(), message.image.GetCompressionAlgorithm(),
message.image.GetChannel());
serializer.SerializeImage(held->message);
const size_t image_offset = serializer.GetImageAppendOffset();
memcpy(slot_buffer + image_offset, message.image.GetCompressed(), size);
serializer.AppendImage(size);
held->message.image = CompressedImage(slot_buffer + image_offset, size, message.image.GetWidth(),
message.image.GetHeight(), message.image.GetMode(),
message.image.GetCompressionAlgorithm(), message.image.GetChannel());
held->slot->SetImageNumber(message.number);
held->slot->SetImageSize(serializer.GetBufferSize());
held->slot->SetIndexed(false);
held->slot->ReadyToSend();
stills->Hold(held);
}
void JFJochReceiverRugnuxStills::FinishCollection() {
logger.Info("Receiving finished, {} images", images_collected.load());
// With no start message there is no end message either, and the error is the collection's result
std::exception_ptr error;
try {
stills->Finish();
if (const auto &merged = stills->GetMerged())
plots.SetImageMerged(merged->merge.statistics.image_merged);
} catch (const std::exception &) {
error = std::current_exception();
}
current_status.SetProgress(1.0);
current_status.SetStatus(GetStatus());
if (!error)
SendEndMessage();
end_time = std::chrono::system_clock::now();
CheckIfImagesSent();
if (error) {
current_status.SetProgress({});
current_status.SetStatus(GetStatus());
std::rethrow_exception(error);
}
WriterFinalize();
if (const auto last_image = live_status.LastImage())
live_status.Latency(SecondsSince(last_image.value()));
stills->ReportOutcome();
current_status.SetProgress({});
current_status.SetStatus(GetStatus());
}
void JFJochReceiverRugnuxStills::StillsReady(const StillsSetup &setup) {
// The profiles are binned on the pre-pass's geometry.
plots.Setup(setup.experiment, *setup.mapping);
DiffractionExperiment written(setup.experiment);
written.Goniometer(experiment.GetGoniometer());
// The cell as stated: the one the frames are indexed on is the analysis's, and the merge reports its own
written.SetUnitCell(experiment.GetUnitCell());
SendStartMessage(MakeStartMessage(written, setup.mask, *setup.mapping));
}
SpotFindingSettings JFJochReceiverRugnuxStills::AnalysisSettings() {
// The broker's settings, with the spot finder of the pre-pass: adaptive threshold, single-pixel spots kept.
// Every frame is integrated: integration is rugnux's, not the broker's to switch off.
SpotFindingSettings settings = GetSpotFindingSettings();
settings.adaptive_threshold = true;
settings.min_pix_per_spot = std::nullopt;
settings.quick_integration = true;
return settings;
}
// The start message did not go out (or the analysis could not be set up): nothing can be written, so the collection stops.
void JFJochReceiverRugnuxStills::StillsSetupFailed(const JFJochException &error) {
Cancel(error);
}
ZeroCopyReturnValue *JFJochReceiverRugnuxStills::AnalysedImageSlot() {
// An analysed frame waits for the writer, which lags behind the catch-up from a full buffer; this long at most
constexpr auto WRITER_WAIT = std::chrono::seconds(2);
const auto t0 = std::chrono::steady_clock::now();
auto loc = image_buffer.GetImageSlot();
while (loc == nullptr && std::chrono::steady_clock::now() - t0 < WRITER_WAIT) {
std::this_thread::sleep_for(std::chrono::milliseconds(1));
loc = image_buffer.GetImageSlot();
}
return loc;
}
void JFJochReceiverRugnuxStills::SendAnalysedImage(DataMessage &message, const AzimuthalIntegrationProfile &profile) {
try {
const auto status = image_buffer.GetSlotStatus();
message.receiver_buf_available = status.available_slots;
message.receiver_buf_in_preparation = status.preparation_slots;
message.receiver_buf_in_sending = status.sending_slots;
AddToAverages(message);
scan_result.Add(message);
if (!serialmx_filter.ApplyFilter(message))
++images_skipped;
else
ForwardImage(message, AnalysedImageSlot());
plots.Add(message, profile);
current_status.SetProgress(GetProgress());
current_status.SetStatus(GetStatus());
} catch (const JFJochException &e) {
logger.ErrorException(e);
Cancel(e);
} catch (const std::exception &e) {
const JFJochException error(JFJochExceptionCategory::WrongDAQState,
fmt::format("Image {} not written - {}", message.number, e.what()));
logger.ErrorException(error);
Cancel(error);
}
}
void JFJochReceiverRugnuxStills::AddToEndMessage(EndMessage &message) {
JFJochReceiverStream::AddToEndMessage(message);
// A failure here costs the end message the analysis only: it goes out as the receiver made it.
try {
if (stills)
stills->FillEndMessage(message);
} catch (const std::exception &e) {
logger.Error("rugnux live: the end message goes without the analysis results - {}", e.what());
DropResultBlocks(message);
}
}
void JFJochReceiverRugnuxStills::Cut(const std::string &reason) {
std::unique_lock ul(stills_mutex);
if (cut)
return;
cut = true;
if (stills) {
stills->Cut(reason);
return;
}
live_status.Cut(reason);
logger.Debug("rugnux live: analysis cut ({}) - the end message carries what is established", reason);
}