rugnux: log the time of each section of the run's tail at debug level

A TimingMark (common/Logger.h) logs "TIMING <section> <seconds>" at debug level when a section
ends, so the lines go to <prefix>_log.txt and stay off the terminal. Marked: each pass of
RunPipeline (pre-pass, probe, output) and its first-pass indexing, image pass, scale/merge/symmetry
phase, output files and census wait; inside the scale/merge phase every merge (labelled by its
role: P1, P1 space-group search, P1 all observations, the adopted group, P1 cross-check, quality
guard), the post-refinement, the space-group search and its two SearchSpaceGroup arms, adoption,
analyses, the P1 cross-check wait, model validation and writing; inside RotationScaleMerge the
ingest and, per arm, partial scaling, combine and fulls scaling, correction surfaces and the merge;
the console's steps; and the results report. tools/rugnux_timing.py tabulates the tail of a log.

Only the log changes: the outputs are byte-identical.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01SVmAWnzCmRKAXVUCdc4iNi
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-10-07 16:13:17 +02:00
1 parent df44edf9ee
commit 5421c569ed
8 files changed
+166 -2

No files matched your search

+24
View File
@@ -8,6 +8,7 @@
#include <iostream>
#include <mutex>
#include <memory>
#include <string>
#include <spdlog/spdlog.h>
#include <spdlog/fmt/fmt.h>
@@ -68,3 +69,26 @@ public:
static Logger Buffered();
void ReplayInto(Logger &to) const;
};
// Times one section of a run: logs "TIMING <section> <seconds>" at debug level when the section ends -
// at Stop(), or when the mark goes out of scope, whichever comes first. rugnux keeps debug lines off the
// terminal and in <prefix>_log.txt; tools/rugnux_timing.py turns them into a table.
class TimingMark {
Logger &logger;
std::string section;
std::chrono::steady_clock::time_point start = std::chrono::steady_clock::now();
bool stopped = false;
public:
TimingMark(Logger &in_logger, std::string in_section)
: logger(in_logger), section(std::move(in_section)) {}
TimingMark(const TimingMark &) = delete;
TimingMark &operator=(const TimingMark &) = delete;
~TimingMark() { Stop(); }
void Stop() {
if (stopped)
return;
stopped = true;
logger.Debug("TIMING {} {:.3f}", section,
std::chrono::duration<double>(std::chrono::steady_clock::now() - start).count());
}
};
@@ -371,6 +371,7 @@ void RotationScaleMerge::MeasureIncidentFlux(const std::vector<double> &mean_bkg
}
void RotationScaleMerge::Ingest() {
TimingMark mark(*logger, "rsm ingest");
scale_partials_choice.reset();
n_frames = static_cast<int>(partials_out.size());
partials_released = false;
@@ -6091,6 +6092,7 @@ RotationScaleMerge::Result RotationScaleMerge::Run(bool for_search, bool full_st
RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool for_search, bool full_stats,
bool measure_cc_before_corrections) {
TimingMark arm_mark(*logger, scale_partials ? "rsm arm (partials scaled)" : "rsm arm (fulls alone)");
HKLKeyGenerator keygen(merge_friedel, Group());
// Start from the corr Ingest built, so this pass runs the scaling_iter iterations it was asked for
@@ -6112,6 +6114,7 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
});
}
TimingMark section_mark(*logger, "rsm scale partials and filter frames");
// --- 1. Per-frame partial scaling (Rotation model, per-image G only). ---
const int n_groups = ComputeAsuGroups(keygen); // one ASU grouping, shared by partials and fulls
std::vector<double> partial_mean;
@@ -6417,6 +6420,8 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
}
}
section_mark.Stop();
TimingMark combine_mark(*logger, "rsm combine and scale fulls");
// --- 3. 3D combine of per-frame partials into fulls (fulls inherit their ASU group here). ---
bool fulls_csr_built = false;
bool combined_on_gpu = false;
@@ -6576,6 +6581,8 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
upload_fulls_corr();
#endif
combine_mark.Stop();
TimingMark surfaces_mark(*logger, "rsm correction surfaces and frame disposition");
// --- 4b. Optional correction surfaces (decay = resolution x time; absorption = goniometer-frame
// diffracted-beam direction), each an alternating multiplicative fit of the fulls' corr against
// the merged reference. Cheap host loops over the downloaded fulls; applied only on the final
@@ -6661,8 +6668,11 @@ RotationScaleMerge::Result RotationScaleMerge::RunArm(bool scale_partials, bool
upload_fulls_corr();
#endif
surfaces_mark.Stop();
// --- 5. Error model + merge + statistics. ---
TimingMark merge_mark(*logger, "rsm merge and statistics");
auto r = MergeAndStats(n_groups, for_search, combined_on_gpu && scaled_fulls_on_gpu, full_stats);
merge_mark.Stop();
r.scaling_iterations_partials = partial_loop.iterations;
r.scaling_iterations_fulls = fulls_loop.iterations;
r.scaling_converged = partial_loop.converged && (fulls_loop.iterations == 0 || fulls_loop.converged);
+13 -1
View File
@@ -539,6 +539,8 @@ std::vector<double> Rugnux::FirstPassInputKey() const {
ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, bool geometry_prepass) {
Logger logger("Rugnux");
ProcessResult result;
TimingMark pass_mark(logger, geometry_prepass ? "pass (geometry pre-pass)"
: write_output ? "pass (output)" : "pass (probe)");
// Only a pass that makes the result is shown as steps; a probe pass is part of the step that ran it.
steps_ = (write_output || geometry_prepass) ? observer : nullptr;
@@ -852,6 +854,7 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
indexer->ForceRotationIndexerLattice(*config_.forced_rotation_lattice);
logger.Info("Rotation indexer lattice forced externally - skipping first pass");
} else if (full && config_.rotation_indexing && config_.two_pass_rotation) {
TimingMark mark(logger, "first-pass indexing");
if (FirstPassRotationIndexing(p))
return result;
}
@@ -875,15 +878,20 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
indexer->ProbeSupercell(frames);
}
TimingMark image_pass_mark(logger, "image pass");
ImagePass(p);
image_pass_mark.Stop();
// Scaling and merging (full analysis only).
if (full && !cancelled_ && (result.indexing_rate.value_or(0.0f) > 0 || result.rotation_lattice_found)
&& (config_.run_scaling || !config_.reference_data.empty())) {
TimingMark mark(logger, "scale, merge and symmetry");
if (ScaleMergeAndSymmetry(p))
return result;
}
TimingMark output_mark(logger, "output files");
// Unmerged observations. After the merge, because that is where the space group is settled and
// the file has to be written in it, but from the integrated observations rather than the merged
// ones: the partiality and the per-image scale are left for the reading program, which fits a
@@ -983,6 +991,8 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
result.written_master_path = config_.output_prefix + "_process.h5";
}
output_mark.Stop();
if (observer)
observer->OnPhase(cancelled_ ? "Cancelled" : "Done");
@@ -1011,7 +1021,9 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b
result.used_direct_beam_x_pxl = direct.first;
result.used_direct_beam_y_pxl = direct.second;
}
if (census_future.valid())
if (census_future.valid()) {
TimingMark mark(logger, "leftover-lattice census wait");
result.leftover_lattices = census_future.get();
}
return result;
}
+6 -1
View File
@@ -203,6 +203,7 @@ void RugnuxConsole::Close(const char *how) {
Emit(INDENT + std::string(std::max(4, dashes), '-') + label + " " + dur);
}
pending_log_.push_back(std::move(log_text));
pending_timing_.push_back(fmt::format("TIMING step {} {:.3f}", step_title_, total));
warnings_held_.clear();
step_ = 0;
}
@@ -213,6 +214,7 @@ void RugnuxConsole::OnStep(const std::string &title) {
const int number = std::max(step_, last_step_) + 1;
Close("done in");
step_ = last_step_ = number;
step_title_ = title;
step_start_ = mark_ = Clock::now();
notes_ = 0;
if (!verbose_)
@@ -253,13 +255,16 @@ void RugnuxConsole::OnPhase(const std::string &phase) {
}
void RugnuxConsole::FlushLog() {
std::vector<std::string> lines;
std::vector<std::string> lines, timing;
{
std::lock_guard lock(m_);
lines.swap(pending_log_);
timing.swap(pending_timing_);
}
for (const auto &l : lines)
LogLine(l);
for (const auto &l : timing)
Logger("rugnux").Debug("{}", l);
}
void RugnuxConsole::OnProgress(uint64_t done, uint64_t total) {
+1
View File
@@ -81,6 +81,7 @@ private:
bool status_shown_ = false;
unsigned spin_ = 0;
std::vector<std::string> pending_log_;
std::vector<std::string> pending_timing_; // "TIMING step ..." lines, logged at debug level
// Warnings by kind (the text without its numbers): how often each was raised, and how many of the
// open step's repeats were held back.
std::map<std::string, int> warnings_seen_;
+21
View File
@@ -594,6 +594,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
std::optional<PostRefineObservations> prepass_postrefine_obs;
// The rotation geometry post-refinement (see its call sites below for what it is for).
const auto post_refine_geometry = [&] {
TimingMark mark(logger, "post-refinement");
const auto &outcomes = indexer->GetIntegrationOutcome();
if (geometry_prepass) {
prepass_mosaicity_.assign(outcomes.size(), NAN);
@@ -755,6 +756,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
first_part[i].reflections = std::move(reflections);
}
{
TimingMark mark(logger, "merge quality guard (pre-pass frames)");
RotationScaleMerge first_part_rsm(experiment_, first_part, result.consensus_cell,
static_cast<int>(config_.scaling_iter), config_.nthreads,
logger, "");
@@ -800,6 +802,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
bool measure_cc = false,
std::optional<RotationScaleMerge::Result> already_run = std::nullopt)
-> ScaleMergeResult {
TimingMark mark(logger, "merge " + label);
if (rsm) {
phase("Scale/combine/merge (" + label + ")");
// The geometry pre-pass merges only to choose the space group and to give the quality
@@ -1100,6 +1103,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
// above triclinic - i.e. a promotion was made, which is what makes a later "the Laue class is
// holohedral so there is no twin law" conclusion circular.
bool promoted_point_group = false;
TimingMark search_mark(logger, "space-group search");
if (search_space_group) {
SearchSpaceGroupOptions sg_opts;
sg_opts.nthreads = static_cast<size_t>(std::max(1, config_.nthreads));
@@ -1124,7 +1128,9 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
// Set per merge, not once: the two arms below are scaled separately and their ISa differ by up
// to a factor of six. 0 (b not measurable) leaves the cut as the caller set it.
sg_opts.merge_isa = result.error_model_isa;
TimingMark first_arm_mark(logger, "SearchSpaceGroup (first arm)");
auto sg_search = SearchSpaceGroup(sm.merged, sg_opts);
first_arm_mark.Stop();
// The Lorentz-filtered arm's merge, kept past the point where the all-observation one
// replaces it. The metric re-ask below is a search like any other and answers to the same
@@ -1161,7 +1167,9 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
rsm->SetSearchMinZeta(zeta);
merged_filtered_isa = sg_opts.merge_isa; // the filtered arm's, before it is replaced
sg_opts.merge_isa = result.error_model_isa; // this arm's own error model
TimingMark all_arm_mark(logger, "SearchSpaceGroup (all-observation arm)");
auto alt = SearchSpaceGroup(sm_all.merged, sg_opts);
all_arm_mark.Stop();
// The order of the point group each arm confirmed. Read from the search, not from the
// space group it went on to pick: Stage B leaves best_space_group unset when no
// candidate has enough absences to be eligible, which is common on the filtered arm
@@ -2464,6 +2472,9 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
}
}
search_mark.Stop();
TimingMark adoption_mark(logger, "adoption (setting, reference, guard)");
// The files are written on other axes than the ones the space group was determined on in two
// cases: to match something the user gave (a reference MTZ, a model, -C, -S), and to write the
// standard setting. Both are relabellings made after every decision. The group's label goes
@@ -2623,6 +2634,8 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
: std::string()));
Step("Analyses");
}
adoption_mark.Stop();
TimingMark analyses_mark(logger, "analyses");
// Whether the P1 cross-check dataset is made (see where it is written, below).
const bool p1_integration_complete =
@@ -2651,7 +2664,9 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
}
auto take_p1 = [&] {
if (!p1_ahead.valid()) return;
TimingMark wait_mark(logger, "P1 cross-check wait");
p1_merged_early = p1_ahead.get();
wait_mark.Stop();
rsm->SetLogger(logger);
rsm->SetWriteBackPerFrameScale(true);
p1_log.ReplayInto(logger);
@@ -3115,6 +3130,8 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
}
}
analyses_mark.Stop();
// Model validation runs BEFORE the reflection files are written, because it is what settles the
// frame they are written in: the enantiomorph, which merged intensities cannot choose, and -
// with no reference MTZ - the alternative indexing. Both are relabelings of the same
@@ -3124,6 +3141,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
&& !superseded) {
phase("Validating against model");
Step("Model validation");
TimingMark mark(logger, "model validation");
const auto data_sg = experiment_.GetGemmiSpaceGroup();
// With a reference MTZ the merohedral indexing was already resolved against it (rotation
// merge / stills scaling), so trust that; only probe indexing by R-free when model-only.
@@ -3238,6 +3256,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
&& !superseded) {
phase("Writing reflections");
Step("Writing files");
TimingMark writing_mark(logger, "writing reflections");
const ErrorModelReport em_report{
result.error_model_isa > 0 && result.error_model_isa_resolved
? fmt::format("{:.2f}", result.error_model_isa) : "?",
@@ -3255,6 +3274,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
WriteReflections(sm.merged, *result.consensus_cell, experiment_, sm.statistics,
em_report, result.twinning, config_.output_prefix,
static_cast<size_t>(std::max(1, config_.nthreads)), &sm.scaled_fulls);
writing_mark.Stop();
// P1 cross-check dataset. The group the files above are written in was chosen by the
// search, and if that choice is wrong nothing in them says so - every statistic was
@@ -3304,6 +3324,7 @@ bool Rugnux::ScaleMergeAndSymmetry(PipelineLocals &p) {
"merge would be missing whole centring classes");
if (p1_crosscheck) {
TimingMark mark(logger, "P1 cross-check");
// The whole GROUP, not its number: the search can adopt a non-reference setting, and
// a number only ever names the reference one - so restoring through the number would
// silently re-seat P 1 1 2(1) as P 1 2(1) 1 for everything written after this block,
+2
View File
@@ -3025,7 +3025,9 @@ static int RunRugnux(int argc, char **argv) {
// inside Rugnux::Run, so it counts neither opening the file nor setting up the analysis.
provenance.wall_time_s = std::chrono::duration<double>(
std::chrono::steady_clock::now() - invocation_start).count();
TimingMark report_mark(logger, "results report");
const ReportDocument doc = WriteResultReport(output_prefix, input_file, experiment, result, logger, provenance);
report_mark.Stop();
// The space-group search is rendered here (not in the library) so the viewer does not emit it and
// the CLI owns the format. The report carries it too, in its developer rendering.
+89
View File
@@ -0,0 +1,89 @@
#!/usr/bin/env python3
# SPDX-FileCopyrightText: 2026 Filip Leonarski, Paul Scherrer Institute <filip.leonarski@psi.ch>
# SPDX-License-Identifier: GPL-3.0-only
"""Tabulate the TIMING lines of a rugnux <prefix>_log.txt.
rugnux logs one debug line per timed section as it ends (TimingMark in common/Logger.h):
[2026-10-07 15:29:52.114] [Rugnux] [debug] TIMING merge P1 4.210
The section name is everything between TIMING and the last field, which is the seconds. Sections
nest: an "rsm ..." line is a part of the "merge <role>" line logged after it, and every section of
a pass ends before its "pass (...)" line.
The tail is the stretch from the end of the image pass of the last output pass to the last line of
the log. Its sections are listed in the order they ended, then summed by name.
tools/rugnux_timing.py p_log.txt # the tail
tools/rugnux_timing.py --all p_log.txt # every timed section of the run
"""
import argparse
import datetime
import re
import sys
LINE = re.compile(r'^\[(\d{4}-\d\d-\d\d \d\d:\d\d:\d\d\.\d+)\] \[[^\]]*\] \[[^\]]*\] (.*)$')
def read(path):
marks = [] # (end time, section, seconds)
first = last = None
with open(path, errors='replace') as f:
for line in f:
m = LINE.match(line.rstrip('\n'))
if not m:
continue
t = datetime.datetime.strptime(m.group(1), '%Y-%m-%d %H:%M:%S.%f')
first = first or t
last = t
text = m.group(2)
if text.startswith('TIMING '):
section, seconds = text[len('TIMING '):].rsplit(' ', 1)
marks.append((t, section, float(seconds)))
return first, last, marks
def main():
ap = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
ap.add_argument('log')
ap.add_argument('--all', action='store_true', help='every timed section, not only the tail')
args = ap.parse_args()
first, last, marks = read(args.log)
if not marks:
sys.exit(f'{args.log}: no TIMING lines')
start = 0
if not args.all:
output = [i for i, m in enumerate(marks) if m[1] == 'pass (output)']
if output:
image = [i for i in range(output[-1]) if marks[i][1] == 'image pass']
start = image[-1] + 1 if image else 0
tail = marks[start:]
t0 = marks[start - 1][0] if start > 0 else first
wall = (last - t0).total_seconds()
print(f'{"ends at [s]":>11} {"seconds":>9} section')
for t, section, seconds in tail:
indent = ' ' if section.startswith('rsm ') else ''
print(f'{(t - t0).total_seconds():11.2f} {seconds:9.3f} {indent}{section}')
print()
# Shares are of the wall clock above. Sections nest (a pass holds its merges, a merge its rsm
# parts), so they do not add up to 100 %.
print(f'{"count":>5} {"seconds":>9} {"share":>6} section (summed by name; nested, so shares overlap)')
totals = {}
for _, section, seconds in tail:
n, s = totals.get(section, (0, 0.0))
totals[section] = (n + 1, s + seconds)
for section, (n, s) in sorted(totals.items(), key=lambda kv: -kv[1][1]):
share = f'{100.0 * s / wall:5.1f}%' if wall > 0 else ' -'
print(f'{n:5d} {s:9.3f} {share} {section}')
print()
origin = "the end of the last output pass's image pass" if start > 0 else 'the first log line'
print(f'{"run" if args.all else "tail"} wall clock: {wall:.2f} s, from {origin} to the last log line')
if __name__ == '__main__':
main()