// SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute // SPDX-License-Identifier: GPL-3.0-only #include "JFJochReceiverRugnuxRotation.h" #include #include #include "spdlog/fmt/fmt.h" #include "../common/HostMemory.h" #include "../common/time_utc.h" #include "../frame_serialize/CBORStream2Deserializer.h" #include "../rugnux/RugnuxDefaults.h" #include "../rugnux/RugnuxLive.h" #include "../rugnux/ResultReport.h" #include "../writer/RugnuxResultBlocks.h" #include "RugnuxStructure.h" namespace { // Kept for the rest of the broker when the host memory rugnux plans against is decided constexpr size_t RUGNUX_HOST_MEMORY_MARGIN = 16ULL * 1024 * 1024 * 1024; // Nine tenths of the machine's total less the image buffer and the margin, at most the machine's budget // (HostMemory.h): both come off the total, as the budget's own reserve taken off twice left nothing. A tenth // stays out for the system and the other services on the host. Never 0, the whole machine's budget. size_t RugnuxHostBudget(const ImageBuffer &buffer) { const size_t total = get_host_total_memory(); const size_t taken = buffer.GetBufferSize() + RUGNUX_HOST_MEMORY_MARGIN; const size_t usable = total / 10 * 9; return usable > taken ? std::min(DefaultHostMemoryBudget(), usable - taken) : 1; } // A run reachable for Cut while it exists: registered in `slot`, cancelled at once where the cut came first class Reachable { std::mutex &slot_mutex; Rugnux *&slot; public: Reachable(std::mutex &in_mutex, Rugnux *&slot, Rugnux &run, const bool &cut, const std::atomic &cancelled) : slot_mutex(in_mutex), slot(slot) { std::unique_lock ul(slot_mutex); slot = &run; if (cut || cancelled) run.Cancel(); } ~Reachable() { std::unique_lock ul(slot_mutex); slot = nullptr; } }; // The headline numbers and the shell table of the merge: the summary's Space group, Resolution and Signal rows, // with the R-free of the model by shell where one was validated (and refined) on it void PublishMerge(RugnuxLiveStatus &status, const ProcessResult &result, const MergeStatistics &statistics, const ModelValidationResult *validation = nullptr, const RefinementResult *refinement = nullptr) { std::optional d_min, isa; if (std::isfinite(statistics.overall.d_min)) d_min = statistics.overall.d_min; if (!statistics.stills && result.error_model_isa_resolved && result.error_model_isa > 0.0) isa = result.error_model_isa; // the fit the report quotes: on the plain CC1/2 where there is one (rotation), else the applied one const auto fit = result.resolution_fit_plain_A ? result.resolution_fit_plain_A : result.resolution_fit_A; status.Headline(result.space_group ? result.space_group->xhm() : "", d_min, isa, fit); status.Shells("the collection", LiveShells(statistics, validation), LiveOverall(statistics, validation, refinement)); } // Per-image results of rugnux's canonical pass to the plots and scan result, its steps to the live status. The // pass runs behind the images, mostly after the last one: the image buffer is told, so that the viewer reads // the plots again. class LiveObserver : public RugnuxObserver { JFJochReceiverPlots &plots; ScanResultGenerator &scan_result; ImageBuffer &image_buffer; const AzimuthalIntegrationMapping &mapping; RugnuxLiveStatus &status; std::atomic canonical{false}; public: LiveObserver(JFJochReceiverPlots &plots, ScanResultGenerator &scan_result, ImageBuffer &image_buffer, const AzimuthalIntegrationMapping &mapping, RugnuxLiveStatus &status) : plots(plots), scan_result(scan_result), image_buffer(image_buffer), mapping(mapping), status(status) {} void OnImagePass(bool input) override { canonical = input; } void OnImageProcessed(const DataMessage &msg) override { if (!canonical) return; plots.Add(msg, AzimuthalIntegrationProfile(mapping)); scan_result.Add(msg); image_buffer.ResultsChanged(); } void OnProgress(uint64_t done, uint64_t total) override { status.Progress(done, total); } void OnStep(const std::string &title) override { status.Step(title); } void OnNote(const std::string &text) override { status.Note(text); // The run has its lattice (RugnuxFirstPassAccept): the probe's answer on the first degrees is overtaken if (text.starts_with("lattice ")) status.Lattice("lattice on the sweep: " + text.substr(8)); } // The merge is made: its numbers go out now, not after the model work; the end publishes them again void OnMerge(const ProcessResult &result, const MergeStatistics &statistics) override { PublishMerge(status, result, statistics); } }; std::string StateName(RugnuxLiveState state) { switch (state) { case RugnuxLiveState::Idle: return "idle"; case RugnuxLiveState::Running: return "running"; case RugnuxLiveState::Done: return "done"; case RugnuxLiveState::Failed: return "failed"; case RugnuxLiveState::Cancelled: return "cancelled"; case RugnuxLiveState::Skipped: return "skipped"; } return "unknown"; } } JFJochReceiverRugnuxRotation::JFJochReceiverRugnuxRotation(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, int in_rugnux_nthreads, std::shared_ptr 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) : 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), reader(in_image_buffer), rugnux_nthreads(in_rugnux_nthreads), host_budget(RugnuxHostBudget(in_image_buffer)), model(std::move(in_model)), deadline_s(in_deadline_s), refine_solvent(in_refine_solvent), live_status(in_live_status) { logger.Info("rugnux live: starting {} forward threads; rugnux runs on {} threads while the images arrive, " "planning against {:.1f} GB of host memory", nthreads, rugnux_nthreads, static_cast(host_budget) / 1e9); StartThreads(); } JFJochReceiverRugnuxRotation::~JFJochReceiverRugnuxRotation() { cancelled = true; reader.Ended(); { std::unique_lock ul(rugnux_mutex); if (rugnux != nullptr) rugnux->Cancel(); if (probe != nullptr) probe->Cancel(); } JoinThreads(); } void JFJochReceiverRugnuxRotation::OnStart(std::chrono::steady_clock::time_point received) { SendStartMessage(); // Rugnux reads the images back from the buffer: without one slot per image the collection is only forwarded. // The service counted the slots the same way before the start; this is repeated because the start message // sets the bit depth, so the slot size may have grown since. const int64_t slots = image_buffer.GetBufferSize() / experiment.GetImageBufferLocationSize(); // The image time as the detector produces images, summation included const double image_time_s = std::chrono::duration(experiment.GetImageTime()).count(); std::optional expected_collection_s; if (image_time_s > 0) expected_collection_s = static_cast(experiment.GetImageNum()) * image_time_s; live_status.Start(experiment.GetImageNum(), expected_collection_s, received); if (slots < experiment.GetImageNum()) { skipped_warning = fmt::format("no rugnux analysis: the image buffer holds {} images, the collection " "has {}", slots, experiment.GetImageNum()); logger.Error("{}", skipped_warning); live_status.Finish(RugnuxLiveState::Skipped, "the image buffer cannot hold the whole collection"); } else StartRugnux(); } void JFJochReceiverRugnuxRotation::OnImage(uint32_t id, DataMessage &message, std::chrono::steady_clock::time_point received) { live_status.ImageReceived(received); CountImage(message); StampImage(message, image_puller.GetCurrentFifoUtilization()); ForwardImage(message, image_buffer.GetImageSlot()); } void JFJochReceiverRugnuxRotation::FinishCollection() { reader.Ended(); // The latency runs from the last image in to every result in place const auto last_image = live_status.LastImage(); logger.Info("Receiving finished, {} images", images_collected.load()); std::optional done_s; if (rugnux_out.valid()) { // The fixed cutoff: the analysis gets deadline_s after the last image, then gives what it has. if (deadline_s > 0 && rugnux_out.wait_for(std::chrono::duration(deadline_s)) == std::future_status::timeout) Cut("deadline"); rugnux_out.wait(); if (last_image) done_s = SecondsSince(last_image.value()); } if (probe_done.valid()) probe_done.wait(); current_status.SetProgress(1.0); current_status.SetStatus(GetStatus()); SendEndMessage(); const double end_sent_s = last_image ? SecondsSince(last_image.value()) : 0.0; CheckIfImagesSent(); WriterFinalize(); if (rugnux_out.valid()) { // The run's outcome, in one line: its results are in the live status, the end message and the files. const auto live = live_status.Get(); std::string outcome = "rugnux live: " + StateName(live.state); if (!live.message.empty()) outcome += " (" + live.message + ")"; if (!live.cut.empty()) outcome += " (cut: " + live.cut + ")"; if (live.start_to_first_image_s && live.last_image_s && live.images_received > 1) outcome += fmt::format("; START -> first image {:.2f} s, {} images in {:.2f} s ({:.1f} Hz)", live.start_to_first_image_s.value(), live.images_received, live.last_image_s.value(), static_cast(live.images_received - 1) / live.last_image_s.value()); if (done_s) { const double written_s = SecondsSince(last_image.value()); live_status.Latency(written_s); outcome += fmt::format("; done {:.2f} s after the last image, last image -> all written {:.2f} s " "(end message sent at {:.2f} s)", done_s.value(), written_s, end_sent_s); } logger.Info("{}", outcome); } // The run's teardown, which went on beside the end message and the writer, then the pinned buffers its engines // kept: given back after the end message, as each cudaFreeHost takes the process's memory-map lock. if (rugnux_done.valid()) { rugnux_done.wait(); Rugnux::ReleasePinnedPool(); } end_time = std::chrono::system_clock::now(); current_status.SetProgress({}); current_status.SetStatus(GetStatus()); } void JFJochReceiverRugnuxRotation::StartRugnux() { // A failure here costs the analysis only: the images go on to the writer as they would without it. try { // The start message as the writer gets it, so rugnux sees the dataset an HDF5 master states. std::vector start_cbor; image_buffer.GetStartMessage(start_cbor); reader.Open(CBORStream2Deserialize(start_cbor)->start_message.value()); rugnux_done = std::async(std::launch::async, &JFJochReceiverRugnuxRotation::RugnuxThread, this); rugnux_out = rugnux_published.get_future(); probe_done = std::async(std::launch::async, &JFJochReceiverRugnuxRotation::ProbeThread, this); } catch (const std::exception &e) { logger.Error("rugnux live: cannot start - {}", e.what()); live_status.Finish(RugnuxLiveState::Failed, e.what()); } } void JFJochReceiverRugnuxRotation::RugnuxThread() { bool published = false; try { const auto dataset = reader.GetDataset(); RugnuxLiveSetup setup = MakeRugnuxLiveSetup(*dataset, rugnux_nthreads, model); setup.config.host_memory_budget_bytes = host_budget; setup.config.refine_solvent = refine_solvent; // Built beside the run, which waits for its first frames meanwhile; waited for when the run ends auto gpu_warm_up = std::async(std::launch::async, [this, setup] { try { const auto t0 = std::chrono::steady_clock::now(); WarmUpRugnuxLiveGPU(setup); logger.Debug("rugnux live: FFT indexers and plans ready in {:.2f} s", std::chrono::duration( std::chrono::steady_clock::now() - t0).count()); } catch (const std::exception &e) { logger.Warning("rugnux live: building the FFT indexers ahead failed, they are built when used - {}", e.what()); } }); LiveObserver observer(plots, scan_result, image_buffer, *az_int_mapping, live_status); // The run goes once its results are out (below), beside the end message; its pinned buffers after that std::optional process; process.emplace(reader, setup.experiment, *dataset->pixel_mask, setup.config); std::optional reachable; reachable.emplace(rugnux_mutex, rugnux, *process, cut, cancelled); ProcessResult result = process->Run(&observer); // The report a `rugnux` run writes, for the writer to write: its verdict and summary for the status as well. const ReportDocument doc = BuildReportDocument(experiment.GetFilePrefix(), experiment.GetFilePrefix(), setup.experiment, result); // A cancelled collection is no failed analysis, and the run stops at the images that came const int64_t images_received = live_status.Get().images_received; std::string verdict = doc.verdict; std::string verdict_text = doc.verdict_text; if (result.cancelled) { verdict = "CANCELLED"; verdict_text = fmt::format("The collection was cancelled after {} images - these results describe " "an incomplete sweep.", images_received); } const std::string cancelled_text = fmt::format("Processing was cancelled after {} images - this report " "describes an incomplete run", images_received); std::vector warnings; for (const auto &warning: doc.warnings) if (result.cancelled && warning.code == PathologyCode::CANCELLED) warnings.push_back(cancelled_text); else if (!warning.developer_only) warnings.push_back(warning.text); // The decision the summary's Anomalous row took (ResultReport.h, ANOM_*), not taken again here. bool anomalous_signal = false; for (const auto &[label, value]: doc.summary_rows) if (label == "Anomalous") anomalous_signal = value.starts_with("signal present"); live_status.Result(verdict, verdict_text, doc.summary_rows, warnings, anomalous_signal); std::vector triage = LiveTriage(doc); for (auto &t: triage) if (t.codes == std::vector{PathologyCode::CANCELLED}) t.text = t.detail = cancelled_text; live_status.Triage(triage); if (const auto live_model = LiveModel(result)) live_status.Model(*live_model); if (result.has_merge_statistics) { PublishMerge(live_status, result, result.merge_statistics, result.model_validation ? &*result.model_validation : nullptr, result.refinement ? &*result.refinement : nullptr); live_status.Frames(result.end_message.image_scale_factor, LiveFrameRanges(result.merge_statistics.sweep_quality)); plots.SetImageMerged(result.merge_statistics.image_merged); image_buffer.ResultsChanged(); } else live_status.Headline(result.space_group ? result.space_group->xhm() : "", std::nullopt, std::nullopt); // For the broker's viewer routes; a copy of the map coefficients, as the end message takes the originals if (result.outputs && result.outputs->placed_model) { const RugnuxOutputs &outputs = *result.outputs; PublishStructures(live_status, *outputs.placed_model, outputs.maps.get(), outputs.refined_model ? &*outputs.refined_model : nullptr, outputs.refined_maps.get()); } live_status.Finish(result.cancelled ? RugnuxLiveState::Cancelled : RugnuxLiveState::Done); reachable.reset(); std::string report = RenderReportText(doc, false); { std::unique_lock ul(rugnux_mutex); rugnux_result = std::move(result); rugnux_report = std::move(report); } published = true; rugnux_published.set_value(); process.reset(); } catch (const std::exception &e) { logger.Error("rugnux live: {}", e.what()); live_status.Finish(RugnuxLiveState::Failed, e.what()); } if (!published) rugnux_published.set_value(); } void JFJochReceiverRugnuxRotation::ProbeThread() { // A small run of its own on the first degrees says early whether there is a crystal; it decides nothing constexpr double PROBE_DEG = 60.0; try { const auto dataset = reader.GetDataset(); const auto gonio = dataset->experiment.GetGoniometer(); if (!gonio || gonio->GetIncrement_deg() == 0.0f) return; const int64_t frames = std::lround(PROBE_DEG / std::abs(gonio->GetIncrement_deg())); if (2 * frames > static_cast(reader.GetNumberOfImages())) return; // a sweep this short is decided on soon enough by the run itself // A quarter of the threads: it runs beside the main run, and each of its workers holds GPU memory too. RugnuxLiveSetup setup = MakeRugnuxLiveSetup(*dataset, std::max(2, rugnux_nthreads / 4), nullptr); setup.config.host_memory_budget_bytes = host_budget; // the same as the main run's: one pool for both setup.config.end_image = static_cast(frames); setup.config.rotation_postrefine_geometry = false; setup.config.run_scaling = false; // The file's centre only: the probe does not report one setup.config.beam_center_check = false; ProcessResult result; { Rugnux probe_run(reader, setup.experiment, *dataset->pixel_mask, setup.config); Reachable reachable(rugnux_mutex, probe, probe_run, cut, cancelled); result = probe_run.Run(nullptr); } if (result.consensus_cell && result.rotation_lattice_type) { const auto &cell = *result.consensus_cell; live_status.Probe(fmt::format("lattice on the first {:.0f} deg: {}-centred {}, {:.1f} {:.1f} {:.1f} " "{:.1f} {:.1f} {:.1f}, {:.0f}% of the images indexed", PROBE_DEG, result.rotation_lattice_type->centering, gemmi::crystal_system_str(result.rotation_lattice_type->crystal_system), cell.a, cell.b, cell.c, cell.alpha, cell.beta, cell.gamma, 100.0 * result.indexing_rate.value_or(0.0f))); } else live_status.Probe(fmt::format("no lattice on the first {:.0f} deg", PROBE_DEG)); } catch (const NoLatticeFound &e) { live_status.Probe(fmt::format("no lattice on the first {:.0f} deg: {}", PROBE_DEG, e.reason)); } catch (const std::exception &e) { logger.Warning("rugnux live: the lattice probe failed: {}", e.what()); } logger.Debug("rugnux live: lattice probe - {}", live_status.Get().probe); } void JFJochReceiverRugnuxRotation::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 { std::unique_lock ul(rugnux_mutex); if (!rugnux_result) return; const EndMessage &rugnux_end = rugnux_result->end_message; message.indexing_rate = rugnux_end.indexing_rate; message.bkg_estimate = rugnux_end.bkg_estimate; message.spindle_blind_fraction = rugnux_end.spindle_blind_fraction; message.ice_ring_score_mean = rugnux_end.ice_ring_score_mean; message.az_int_result = rugnux_end.az_int_result; message.rotation_lattice = rugnux_end.rotation_lattice; message.rotation_lattice_type = rugnux_end.rotation_lattice_type; message.rotation_extra_lattices = rugnux_end.rotation_extra_lattices; message.unit_cell = rugnux_end.unit_cell; message.unit_cell_esd = rugnux_end.unit_cell_esd; message.space_group_name = rugnux_end.space_group_name; message.space_group_number = rugnux_end.space_group_number; message.reindex_matrix = rugnux_end.reindex_matrix; message.refined_beam_center_x = rugnux_end.refined_beam_center_x; message.refined_beam_center_y = rugnux_end.refined_beam_center_y; message.refined_poni_rot1 = rugnux_end.refined_poni_rot1; message.refined_poni_rot2 = rugnux_end.refined_poni_rot2; message.refined_poni_rot3 = rugnux_end.refined_poni_rot3; message.refined_rotation_axis = rugnux_end.refined_rotation_axis; message.image_merged = rugnux_end.image_merged; message.report = rugnux_report; // For the writer to write beside the master; moved, the result is not read again if (!rugnux_result->outputs) return; RugnuxOutputs &outputs = *rugnux_result->outputs; if (outputs.merged) message.merged = std::move(outputs.merged->mtz); if (outputs.maps) message.map_coefficients = std::move(outputs.maps->coefficients); if (outputs.placed_model) message.placed_model = PlacedModelFromStructure(*outputs.placed_model->model, outputs.placed_model->cell, outputs.placed_model->space_group.xhm()); // And the refinement's, as the CLI writes them (_refined_model.cif, _refined_maps.mtz, _blobs.json). if (outputs.refined_model) message.refined_model = PlacedModelFromStructure(*outputs.refined_model->model, outputs.refined_model->cell, outputs.refined_model->space_group.xhm()); if (outputs.refined_maps) message.refined_map_coefficients = std::move(outputs.refined_maps->coefficients); if (outputs.blobs) message.blobs = DensityBlobsToMessage(*outputs.blobs); DropResultBlocksThatDoNotFit(message, &live_status, logger); } catch (const std::exception &e) { logger.Error("rugnux live: the end message goes without the analysis results - {}", e.what()); DropResultBlocks(message); } } void JFJochReceiverRugnuxRotation::Cut(const std::string &reason) { std::unique_lock ul(rugnux_mutex); if (cut || rugnux_result) return; cut = true; reader.Ended(); // no image is waited for any more if (rugnux != nullptr) rugnux->Cancel(); if (probe != nullptr) probe->Cancel(); live_status.Cut(reason); logger.Debug("rugnux live: analysis cut ({}) - the end message carries what is established", reason); } JFJochReceiverOutput JFJochReceiverRugnuxRotation::GetFinalStatistics() const { JFJochReceiverOutput ret = JFJochReceiver::GetFinalStatistics(); ret.analysis_warning = skipped_warning; // The rotation lattice is rugnux's: the receivers run no rotation indexer of their own. std::unique_lock ul(rugnux_mutex); if (rugnux_result) { const EndMessage &rugnux_end = rugnux_result->end_message; ret.scan_result.rotation_lattice = rugnux_end.rotation_lattice; if (rugnux_end.rotation_lattice_type) { ret.scan_result.rotation_crystal_system = rugnux_end.rotation_lattice_type->crystal_system; ret.scan_result.rotation_centering = rugnux_end.rotation_lattice_type->centering; } } return ret; }