diff --git a/image_analysis/scale_merge/AnisotropyAnalysis.cpp b/image_analysis/scale_merge/AnisotropyAnalysis.cpp index 18d4adfd7..15813d1dc 100644 --- a/image_analysis/scale_merge/AnisotropyAnalysis.cpp +++ b/image_analysis/scale_merge/AnisotropyAnalysis.cpp @@ -1132,33 +1132,53 @@ std::vector ScaledObservations(const std::vector(r.I) * pc; - sum_var += static_cast(r.sigma) * r.sigma * pc * pc; - p_g += r.partiality * g[parts[m].image]; - } - const Reflection &first = *parts[i].r; - i = j; - // The scale is the rocking curve's own weighted mean over the frames the event spans; the - // partiality divisor only corrects an event the sweep cut short, since a complete one sums - // to 1 by construction. - if (!(sum_p >= min_partiality) || !(p_g > 0.0)) - continue; - const double scale = p_g / sum_p; // partiality-weighted mean G - const double corr = 1.0 / (sum_p * scale); - out.push_back({first.h, first.k, first.l, static_cast(sum_I * corr), - static_cast(std::sqrt(sum_var) * corr), first.d}); + // The events, walked in blocks on all threads and joined in block order. A block starts where the + // hkl changes, and an event never spans two hkl, so every block holds whole events and the joined + // list is the serial one - each event summed over the same parts in the same order. + const size_t n_block = ThreadsForWork(parts.size(), nthreads); + std::vector cut(n_block + 1, parts.size()); + cut[0] = 0; + for (size_t b = 1; b < n_block; ++b) { + size_t c = std::max(cut[b - 1], b * parts.size() / n_block); + while (c > 0 && c < parts.size() && parts[c].h == parts[c - 1].h && parts[c].k == parts[c - 1].k + && parts[c].l == parts[c - 1].l) + ++c; + cut[b] = c; } + std::vector> block_out(n_block); + ParallelFor(static_cast(n_block), nthreads, [&](int b) { + auto &bout = block_out[b]; + const size_t end = cut[b + 1]; + for (size_t i = cut[b]; i < end;) { + size_t j = i + 1; + while (j < end && parts[j].h == parts[i].h && parts[j].k == parts[i].k + && parts[j].l == parts[i].l + && parts[j].image_number - parts[j - 1].image_number <= max_frame_gap) + ++j; + double sum_p = 0.0, sum_I = 0.0, sum_var = 0.0, p_g = 0.0; + for (size_t m = i; m < j; ++m) { + const Reflection &r = *parts[m].r; + sum_p += r.partiality; + const float pc = r.prescaling_corr * r.qe_corr * r.flight_corr; + sum_I += static_cast(r.I) * pc; + sum_var += static_cast(r.sigma) * r.sigma * pc * pc; + p_g += r.partiality * g[parts[m].image]; + } + const Reflection &first = *parts[i].r; + i = j; + // The scale is the rocking curve's own weighted mean over the frames the event spans; the + // partiality divisor only corrects an event the sweep cut short, since a complete one sums + // to 1 by construction. + if (!(sum_p >= min_partiality) || !(p_g > 0.0)) + continue; + const double scale = p_g / sum_p; // partiality-weighted mean G + const double corr = 1.0 / (sum_p * scale); + bout.push_back({first.h, first.k, first.l, static_cast(sum_I * corr), + static_cast(std::sqrt(sum_var) * corr), first.d}); + } + }); + for (auto &v : block_out) + out.insert(out.end(), v.begin(), v.end()); return out; } diff --git a/image_analysis/scale_merge/ErrorModel.cpp b/image_analysis/scale_merge/ErrorModel.cpp index 4e68cdac6..1204d2b01 100644 --- a/image_analysis/scale_merge/ErrorModel.cpp +++ b/image_analysis/scale_merge/ErrorModel.cpp @@ -80,7 +80,7 @@ ErrorModelFit FitErrorModel(const std::vector &pool, std::vect // the median normalised squared deviation, expressed as the sum it stands for. Reordering inside // a bin does not change which samples it holds. One bin per task, so the result does not depend // on threads. - ParallelChunks(n_bins, ThreadsForWork(smp.size(), nthreads, 8 * 32768), [&](int blo, int bhi) { + ParallelChunks(n_bins, ThreadsForWork(smp.size(), nthreads), [&](int blo, int bhi) { for (int bin = blo; bin < bhi; ++bin) { double s = 0.0, I = 0.0; for (size_t i = bin_lo(bin); i < bin_hi(bin); ++i) { diff --git a/image_analysis/scale_merge/RotationScaleMerge.cpp b/image_analysis/scale_merge/RotationScaleMerge.cpp index 08c5a2fc0..5fbf95262 100644 --- a/image_analysis/scale_merge/RotationScaleMerge.cpp +++ b/image_analysis/scale_merge/RotationScaleMerge.cpp @@ -390,8 +390,9 @@ void RotationScaleMerge::Ingest() { // counted per chunk of FRAMES first; a frame's reflections are consecutive in the key numbering, so // the chunks are consecutive index ranges and the scatter lands each bucket in index order - the // same array an index-order copy scattered afterwards gave, without that copy (24 bytes a partial, - // gigabytes on a long axis, at the top of the pass's memory). - std::vector keys(total); + // gigabytes on a long axis, at the top of the pass's memory). A plain array: the scatter writes every + // key, so the zeroing a sized vector does first - on one thread - would only be overwritten. + std::unique_ptr keys(new SortKey[total]); { // Bucket by h first, then sort each bucket. h is the comparator's leading key, so the sorted // array is exactly the buckets laid end to end - and because the order is total (see above) @@ -442,7 +443,7 @@ void RotationScaleMerge::Ingest() { }); ParallelFor(H, nthreads, [&](int oi) { const int b = order[oi]; - std::sort(keys.begin() + bstart[b], keys.begin() + bstart[b + 1], key_less); + std::sort(keys.get() + bstart[b], keys.get() + bstart[b + 1], key_less); }); // The runs never cross an h boundary, so each bucket owns its own and they can be counted, @@ -490,7 +491,7 @@ void RotationScaleMerge::Ingest() { } }); } - BuildInRangeObservations(keys); + BuildInRangeObservations(keys, static_cast(total)); rawrun_group.assign(rawrun_start.size(), -1); logger.Info("RotationScaleMerge: ingested {} partial observations from {} frames ({} distinct hkl)", n_partials_obs, n_frames, rawrun_start.size()); @@ -593,10 +594,10 @@ void RotationScaleMerge::Ingest() { partials_released = true; } #endif - std::vector().swap(ingest_delta_phi); - std::vector().swap(ingest_partiality); - std::vector().swap(ingest_image_number); - std::vector().swap(ingest_rock_ok); + ingest_delta_phi.reset(); + ingest_partiality.reset(); + ingest_image_number.reset(); + ingest_rock_ok.reset(); std::vector().swap(ingest_keep); std::vector().swap(ingest_src_start); } @@ -609,9 +610,8 @@ void RotationScaleMerge::Ingest() { // // It has to come after the incident flux has been measured (the flux meter is the frame's mean background // over ALL its reflections) and after the sort (which is what defines a raw-hkl run in the first place). -void RotationScaleMerge::BuildInRangeObservations(std::vector &keys) { +void RotationScaleMerge::BuildInRangeObservations(std::unique_ptr &keys, int n_obs) { const int n_run = static_cast(rawrun_start.size()); - const int n_obs = static_cast(keys.size()); const bool limited = d_min_limit.has_value() || d_max_limit.has_value(); std::vector keep_run(n_run, 1); @@ -662,7 +662,7 @@ void RotationScaleMerge::BuildInRangeObservations(std::vector &keys) { // before anything eighty bytes wide exists. The remap below is then free to consume `keys` - the // one other reader of these indices - so the key array is gone before the observation array is // built, instead of the two coexisting at another third of its size. - std::vector new_idx(n_obs); // only written where keep[i] + std::unique_ptr new_idx(new int32_t[n_obs]); // only written, and read, where keep[i] ParallelFor(n_frames, nthreads, [&](int o) { int32_t src = src_start[o]; int32_t at = frame_start[o]; @@ -696,12 +696,13 @@ void RotationScaleMerge::BuildInRangeObservations(std::vector &keys) { }); rawrun_start.swap(ns); rawrun_count.swap(nc); rawrun_h.swap(nh); rawrun_k.swap(nk); rawrun_l.swap(nl); rawrun_d.swap(nd); - std::vector().swap(keys); // consumed (see the header) + keys.reset(); // consumed (see the header) // Everything above that only served the remap - the old runs now in ns..nd, the per-run maps and // new_idx - is handed back before the observation array below is built, not at the end of the // function: on a long axis it is a gigabyte beside the largest array of the ingest. - for (auto *v : {&ns, &nc, &nh, &nk, &nl, &dst_run, &dst_start, &new_idx}) + for (auto *v : {&ns, &nc, &nh, &nk, &nl, &dst_run, &dst_start}) std::vector().swap(*v); + new_idx.reset(); std::vector().swap(nd); std::vector().swap(keep_run); @@ -709,16 +710,16 @@ void RotationScaleMerge::BuildInRangeObservations(std::vector &keys) { // finiteness (immutable) - it lets ComputeAsuGroups stamp the ASU-group id per obs from a flat // 1-byte array instead of re-reading the fat Obs struct for every space group. finite_ok.assign(n_keep, 0); - ingest_delta_phi.resize(n_keep); - ingest_partiality.resize(n_keep); - ingest_image_number.resize(n_keep); + ingest_delta_phi.reset(new float[n_keep]); + ingest_partiality.reset(new float[n_keep]); + ingest_image_number.reset(new float[n_keep]); #ifdef JFJOCH_USE_CUDA if (resident_ingest) { // The resident path: fill the ingest arrays, then stage every immutable per-obs field to the // device straight from the source reflections, in frame-aligned bounded slices. The 80-byte // Obs is never materialised here - beside the source reflections it was another copy of the // whole payload - and the slice buffers are bounded whatever the run. - ingest_rock_ok.resize(n_keep); + ingest_rock_ok.reset(new uint8_t[n_keep]); corr_ingested.resize(n_keep); ParallelFor(n_frames, nthreads, [&](int o) { int32_t src = src_start[o]; @@ -1240,7 +1241,9 @@ int RotationScaleMerge::ComputeAsuGroups(const HKLKeyGenerator &keygen) { #else true; #endif - std::vector group_ids(n_partials_obs); + // Plain arrays, here and for gperm below: every element is written, and a sized vector would + // first zero all of them on one thread - once per merge, a sweep's worth of observations. + std::unique_ptr group_ids(new int32_t[n_partials_obs]); // Parallel over raw-hkl runs: distinct runs own disjoint perm ranges, hence disjoint observations. ParallelChunks(n_run, nthreads, [&](int rlo, int rhi) { for (int r = rlo; r < rhi; ++r) { @@ -1310,7 +1313,7 @@ int RotationScaleMerge::ComputeAsuGroups(const HKLKeyGenerator &keygen) { // Pass 2 (parallel): each chunk fills its obs into gperm at its per-group base (stable). The // bases are advanced in the chunk's own row, which nothing else reads from here on - it used to // take a private copy of the whole row, which is the same quarter of a gigabyte again. - std::vector gperm(acc); + std::unique_ptr gperm(new int32_t[acc]); std::vector> f2; for (int t = 0; t < n_hist; ++t) { const int lo = t * chunk, hi = std::min(n, lo + chunk); @@ -1322,7 +1325,7 @@ int RotationScaleMerge::ComputeAsuGroups(const HKLKeyGenerator &keygen) { for (auto &f : f2) f.get(); #ifdef JFJOCH_USE_CUDA if (gpu_active_) { - gpu_->SetGroups(n_groups, group_ids.data(), gperm.data(), acc, gstart.data(), gcount.data()); + gpu_->SetGroups(n_groups, group_ids.get(), gperm.get(), acc, gstart.data(), gcount.data()); return n_groups; } #endif @@ -2446,27 +2449,40 @@ int RotationScaleMerge::RockingEventFrames() const { template int RotationScaleMerge::RockingEventFramesOver(UsableFn usable, ImgFn img) const { + // Blocks of runs on all threads, each counting into a histogram of its own. The counts are + // integers, so the blocks add up to the serial histogram whatever the split. + constexpr int RUNS_PER_BLOCK = 16384; + const int n_run = static_cast(rawrun_start.size()); + const int n_block = (n_run + RUNS_PER_BLOCK - 1) / RUNS_PER_BLOCK; + std::vector> block_hist(n_block, std::vector(n_frames + 2, 0)); + ParallelFor(n_block, nthreads, [&](int b) { + std::vector &hist = block_hist[b]; + std::vector im; + for (int r = b * RUNS_PER_BLOCK; r < std::min(n_run, (b + 1) * RUNS_PER_BLOCK); ++r) { + const int lo = rawrun_start[r], hi = lo + rawrun_count[r]; + im.clear(); + for (int p = lo; p < hi; ++p) { + const int i = perm[p]; + if (usable(i)) + im.push_back(img(i)); + } + for (size_t i = 0; i < im.size();) { + size_t k = i + 1; + float last = im[i]; + while (k < im.size() && im[k] - last <= max_frame_gap) { last = im[k]; ++k; } + const int span = static_cast(std::lround(last) - std::lround(im[i])) + 1; + ++hist[std::min(span, n_frames + 1)]; + i = k; + } + } + }); std::vector hist(n_frames + 2, 0); - std::vector im; - int n_event = 0; - for (size_t r = 0; r < rawrun_start.size(); ++r) { - const int lo = rawrun_start[r], hi = lo + rawrun_count[r]; - im.clear(); - for (int p = lo; p < hi; ++p) { - const int i = perm[p]; - if (usable(i)) - im.push_back(img(i)); + int n_event = 0; // every event lands in exactly one bin + for (const auto &h : block_hist) + for (int w = 0; w < n_frames + 2; ++w) { + hist[w] += h[w]; + n_event += h[w]; } - for (size_t i = 0; i < im.size();) { - size_t k = i + 1; - float last = im[i]; - while (k < im.size() && im[k] - last <= max_frame_gap) { last = im[k]; ++k; } - const int span = static_cast(std::lround(last) - std::lround(im[i])) + 1; - ++hist[std::min(span, n_frames + 1)]; - ++n_event; - i = k; - } - } int acc = 0; for (int w = 1; w <= n_frames + 1; ++w) if ((acc += hist[w]) * 2 >= n_event) @@ -2518,22 +2534,32 @@ void RotationScaleMerge::MeasureBatchDeltaCCHalf(int n_groups) { // The observations, once: scaled intensity, ASU group (-1 = not in this merge, the same test the // merge itself applies), and the frame order that makes any frame range a contiguous span. std::vector obs_I(n_full), obs_info(n_full); - std::vector obs_group(n_full), order(n_full), fstart(n_frames + 1, 0); + std::vector obs_group(n_full), obs_frame(n_full), order(n_full), fstart(n_frames + 1, 0); + // The three fields everything below reads, taken out of the eighty-byte records once and on all + // threads; the walks after this one read only these. A usable full always has a group, so + // obs_group >= 0 is UsableFull. + ParallelChunks(n_full, ThreadsForWork(fulls.size(), nthreads), [&](int lo, int hi) { + for (int i = lo; i < hi; ++i) { + const Obs &o = fulls[i]; + obs_I[i] = o.I * o.corr; + obs_group[i] = UsableFull(o) ? o.group : -1; + obs_frame[i] = o.frame; + } + }); std::vector n_obs_frame(n_frames, 0); - for (int i = 0; i < n_full; ++i) - if (UsableFull(fulls[i])) ++n_obs_frame[fulls[i].frame]; - const std::vector frame_factor = CCHalfFrameFactors(frame_scale_fulls, n_obs_frame); for (int i = 0; i < n_full; ++i) { - const Obs &o = fulls[i]; - obs_I[i] = o.I * o.corr; - obs_group[i] = UsableFull(o) ? o.group : -1; - obs_info[i] = 1.0 / frame_factor[o.frame]; // the information the observation carries, <= 1 - ++fstart[o.frame + 1]; + if (obs_group[i] >= 0) ++n_obs_frame[obs_frame[i]]; + ++fstart[obs_frame[i] + 1]; } + const std::vector frame_factor = CCHalfFrameFactors(frame_scale_fulls, n_obs_frame); + ParallelChunks(n_full, ThreadsForWork(fulls.size(), nthreads), [&](int lo, int hi) { + for (int i = lo; i < hi; ++i) + obs_info[i] = 1.0 / frame_factor[obs_frame[i]]; // the information the observation carries, <= 1 + }); for (int f = 0; f < n_frames; ++f) fstart[f + 1] += fstart[f]; { std::vector fill(fstart.begin(), fstart.end() - 1); - for (int i = 0; i < n_full; ++i) order[fill[fulls[i].frame]++] = i; + for (int i = 0; i < n_full; ++i) order[fill[obs_frame[i]]++] = i; } // Per-reflection totals over the frames still in, and the per-reflection contribution of one frame @@ -2560,7 +2586,7 @@ void RotationScaleMerge::MeasureBatchDeltaCCHalf(int n_groups) { std::fill(tot_w.begin(), tot_w.end(), 0.0); for (int i = 0; i < n_full; ++i) { const int g = obs_group[i]; - if (g < 0 || frame_rejected[fulls[i].frame]) continue; + if (g < 0 || frame_rejected[obs_frame[i]]) continue; tot_n[g] += 1; tot_s1[g] += obs_I[i]; tot_s2[g] += obs_I[i] * obs_I[i]; tot_w[g] += obs_info[i]; } @@ -4241,11 +4267,19 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool merge_friedel ? group_has_hands.data() : nullptr, em_mean.data(), cnt.data(), gs2.data(), gI2.data(), gdev2.data(), gvalid.data()); - samples.reserve(nf); + // Which fulls give a sample, in order, and then each sample on its own - on all threads. + std::vector valid; for (int i = 0; i < nf; ++i) - if (gvalid[i]) - samples.push_back({counting_variance(fulls[i], em_mean[fulls[i].group], gs2[i]), - gI2[i], gdev2[i], mf.d[i]}); + if (gvalid[i]) valid.push_back(i); + samples.resize(valid.size()); + ParallelChunks(static_cast(valid.size()), ThreadsForWork(valid.size(), nthreads), + [&](int lo, int hi) { + for (int j = lo; j < hi; ++j) { + const int i = valid[j]; + samples[j] = {counting_variance(fulls[i], em_mean[fulls[i].group], gs2[i]), + gI2[i], gdev2[i], mf.d[i]}; + } + }); did_gpu = true; } #endif @@ -4258,17 +4292,26 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool const size_t n_hand = merge_friedel ? 2 * static_cast(n_groups) : 0; std::vector swh(n_hand, 0.0), swIh(n_hand, 0.0); std::vector cnth(n_hand, 0); - for (const auto &o : fulls) { - if (!usable_merge(o)) continue; - const double sigma_corr = static_cast(o.sigma) * o.corr; - const double w = 1.0 / (sigma_corr * sigma_corr); - const double wI = w * (static_cast(o.I) * o.corr); - sw[o.group] += w; swI[o.group] += wI; cnt[o.group]++; - if (n_hand && group_has_hands[o.group]) { - const size_t s = 2 * static_cast(o.group) + obs_hand[&o - fulls.data()]; - swh[s] += w; swIh[s] += wI; cnth[s]++; + // The threads split the GROUPS (mf.group is usable_merge's verdict): each walks every full + // and takes only its own groups', so every group is still summed in index order. + const int nt = static_cast(ThreadsForWork(fulls.size(), nthreads)); + ParallelFor(nt, nt, [&](int t) { + const int g0 = static_cast(static_cast(n_groups) * t / nt); + const int g1 = static_cast(static_cast(n_groups) * (t + 1) / nt); + for (int i = 0; i < n_full; ++i) { + const int g = mf.group[i]; + if (g < g0 || g >= g1) continue; + const Obs &o = fulls[i]; + const double sigma_corr = static_cast(o.sigma) * o.corr; + const double w = 1.0 / (sigma_corr * sigma_corr); + const double wI = w * (static_cast(o.I) * o.corr); + sw[g] += w; swI[g] += wI; cnt[g]++; + if (n_hand && group_has_hands[g]) { + const size_t s = 2 * static_cast(g) + obs_hand[i]; + swh[s] += w; swIh[s] += wI; cnth[s]++; + } } - } + }); for (int g = 0; g < n_groups; ++g) if (cnt[g] >= 2 && sw[g] > 0.0) em_mean[g] = swI[g] / sw[g]; @@ -4414,21 +4457,30 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool // would make the written merge depend on how many merges the pipeline happened to run first. if (reject_outliers && error_model_active && merge_friedel && n_groups > 0) { std::vector sw_h(2 * static_cast(n_groups), 0.0), swI_h(2 * static_cast(n_groups), 0.0); - float d_lo = INFINITY, d_hi = 0.0f; - for (int i = 0; i < n_full; ++i) { - const int g = mf.group[i]; - if (g < 0 || !group_has_hands[g]) continue; - const Obs &o = fulls[i]; - const float I_corr = o.I * o.corr; - const float sigma_corr = corrected_sigma(o, I_corr, o.sigma * o.corr); - if (!(sigma_corr > 0.0f) || !std::isfinite(sigma_corr)) continue; - const double w = 1.0 / (static_cast(sigma_corr) * sigma_corr); - const size_t t = 2 * static_cast(g) + obs_hand[i]; - sw_h[t] += w; swI_h[t] += w * I_corr; - if (std::isfinite(mf.d[i]) && mf.d[i] > 0.0f) { - d_lo = std::min(d_lo, mf.d[i]); d_hi = std::max(d_hi, mf.d[i]); + // The threads split the GROUPS: each walks every full and takes only its own groups', so each + // (group, hand) is still summed over its fulls in index order. + const int nt = static_cast(ThreadsForWork(fulls.size(), nthreads)); + std::vector t_lo(nt, INFINITY), t_hi(nt, 0.0f); + ParallelFor(nt, nt, [&](int t) { + const int g0 = static_cast(static_cast(n_groups) * t / nt); + const int g1 = static_cast(static_cast(n_groups) * (t + 1) / nt); + for (int i = 0; i < n_full; ++i) { + const int g = mf.group[i]; + if (g < g0 || g >= g1 || !group_has_hands[g]) continue; + const Obs &o = fulls[i]; + const float I_corr = o.I * o.corr; + const float sigma_corr = corrected_sigma(o, I_corr, o.sigma * o.corr); + if (!(sigma_corr > 0.0f) || !std::isfinite(sigma_corr)) continue; + const double w = 1.0 / (static_cast(sigma_corr) * sigma_corr); + const size_t s = 2 * static_cast(g) + obs_hand[i]; + sw_h[s] += w; swI_h[s] += w * I_corr; + if (std::isfinite(mf.d[i]) && mf.d[i] > 0.0f) { + t_lo[t] = std::min(t_lo[t], mf.d[i]); t_hi[t] = std::max(t_hi[t], mf.d[i]); + } } - } + }); + const float d_lo = *std::min_element(t_lo.begin(), t_lo.end()); + const float d_hi = *std::max_element(t_hi.begin(), t_hi.end()); if (std::isfinite(d_lo) && d_hi > d_lo) { const ResolutionShells v_shells(d_lo * 0.999f, d_hi, report_shell_count); std::vector> excess(report_shell_count); @@ -4546,17 +4598,21 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool if (wilson_test) { // Each observation with its OWN sigma, the error model evaluated at its own intensity: the // reflection's mean, which the merge weights use, is exactly what an artefact inflates. - std::vector wobs; + // Which fulls take part, in order, and then each one's record on its own - on all threads. wilson_full.clear(); - for (int i = 0; i < n_full; ++i) { - const int g = mf.group[i]; - if (g < 0) continue; - const Obs &o = fulls[i]; - const float I_corr = o.I * o.corr; - wobs.push_back({I_corr, model_sigma(o, I_corr, o.sigma * o.corr), o.d, group_epsilon[g], - group_centric[g] != 0, o.clipped != 0, merge_friedel ? g : pair_of_group[g]}); - wilson_full.push_back(i); - } + for (int i = 0; i < n_full; ++i) + if (mf.group[i] >= 0) wilson_full.push_back(i); + std::vector wobs(wilson_full.size()); + ParallelChunks(static_cast(wobs.size()), ThreadsForWork(wobs.size(), nthreads), + [&](int lo, int hi) { + for (int j = lo; j < hi; ++j) { + const int g = mf.group[wilson_full[j]]; + const Obs &o = fulls[wilson_full[j]]; + const float I_corr = o.I * o.corr; + wobs[j] = {I_corr, model_sigma(o, I_corr, o.sigma * o.corr), o.d, group_epsilon[g], + group_centric[g] != 0, o.clipped != 0, merge_friedel ? g : pair_of_group[g]}; + } + }); wilson = WilsonOutliers(wobs, WILSON_ALPHA, nthreads); for (size_t j = 0; j < wobs.size(); ++j) if (wilson.rejected[j]) rejected_obs[wilson_full[j]] = 1; @@ -4731,16 +4787,22 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool if (full_stats && error_model_active) { std::vector &gs = asymptote_scatter; gs.assign(n_groups, GroupScatter{}); - for (int i = 0; i < n_full; ++i) { - const int gi = mf.group[i]; - if (gi < 0) continue; - const double I_corr = static_cast(mf.I[i]) * mf.corr[i]; - const double sigma_corr = static_cast(mf.sigma[i]) * mf.corr[i]; - auto &g = gs[gi]; - g.sum += I_corr; g.sum_sq += I_corr * I_corr; - g.sum_var += counting_variance(fulls[i], em_mean[gi], sigma_corr * sigma_corr); - ++g.n; - } + // Split by groups, as the Bijvoet sums above: every group is still summed in index order. + const int nt = static_cast(ThreadsForWork(fulls.size(), nthreads)); + ParallelFor(nt, nt, [&](int t) { + const int g0 = static_cast(static_cast(n_groups) * t / nt); + const int g1 = static_cast(static_cast(n_groups) * (t + 1) / nt); + for (int i = 0; i < n_full; ++i) { + const int gi = mf.group[i]; + if (gi < g0 || gi >= g1) continue; + const double I_corr = static_cast(mf.I[i]) * mf.corr[i]; + const double sigma_corr = static_cast(mf.sigma[i]) * mf.corr[i]; + auto &g = gs[gi]; + g.sum += I_corr; g.sum_sq += I_corr * I_corr; + g.sum_var += counting_variance(fulls[i], em_mean[gi], sigma_corr * sigma_corr); + ++g.n; + } + }); // Per-group counting-subtracted fractional systematic variance, paired with the group's I/sigma. // Two conventions decide whether this measures anything: // * the counting term is the error model's OWN, a*sigma^2. Subtracting the raw sigma^2 while the @@ -5065,31 +5127,42 @@ RotationScaleMerge::Result RotationScaleMerge::MergeAndStats(int n_groups, bool // it correlates one half's I(+)-I(-) against the other's, so each hand separately needs both // of its halves filled, and a mate left entirely in one half loses the whole pair rather than // half of it. So the cell here is (pair, hand), where the merge above used the reflection. + // Each observation's cell on its own, so on all threads (the key generator is const). std::vector anom_cell(fulls.size(), -1); - for (size_t i = 0; i < fulls.size(); ++i) { - const Obs &o = fulls[i]; - if (!usable_merge(o) || rejected_obs[i]) continue; // as the merge saw it - if (acc[o.group].d < d_floor) continue; - const int hand = merge_friedel ? (anom_keygen(o.h, o.k, o.l).plus ? 0 : 1) - : hand_of_group[o.group]; - anom_cell[i] = pair_of_group[o.group] * 2 + hand; - } + ParallelChunks(n_full, ThreadsForWork(fulls.size(), nthreads), [&](int lo, int hi) { + for (int i = lo; i < hi; ++i) { + const Obs &o = fulls[i]; + if (!usable_merge(o) || rejected_obs[i]) continue; // as the merge saw it + if (acc[o.group].d < d_floor) continue; + const int hand = merge_friedel ? (anom_keygen(o.h, o.k, o.l).plus ? 0 : 1) + : hand_of_group[o.group]; + anom_cell[i] = pair_of_group[o.group] * 2 + hand; + } + }); std::vector anom_half; AssignHalvesByRank(obs_key, anom_cell, static_cast(pair_hkl.size()) * 2, anom_half, nthreads); - for (size_t i = 0; i < fulls.size(); ++i) { - const int cell = anom_cell[i]; - if (cell < 0) continue; - const Obs &o = fulls[i]; - const float I_corr = o.I * o.corr; - const float sigma_corr = corrected_sigma(o, I_corr, o.sigma * o.corr); - if (!(sigma_corr > 0.0f) || !std::isfinite(sigma_corr)) continue; - const double w = 1.0 / (static_cast(sigma_corr) * sigma_corr); - AnomAcc &a = anom[cell >> 1]; - a.d = acc[o.group].d; - a.swI[cell & 1][anom_half[i]] += w * static_cast(I_corr); - a.sw[cell & 1][anom_half[i]] += w; - a.nh[cell & 1][anom_half[i]]++; - } + // The threads split the PAIRS: each walks every full and takes only its own pairs', so every + // pair is still summed in index order. + const int n_pair = static_cast(anom.size()); + const int nt = static_cast(ThreadsForWork(fulls.size(), nthreads)); + ParallelFor(nt, nt, [&](int t) { + const int p0 = static_cast(static_cast(n_pair) * t / nt); + const int p1 = static_cast(static_cast(n_pair) * (t + 1) / nt); + for (int i = 0; i < n_full; ++i) { + const int cell = anom_cell[i]; + if (cell < 0 || (cell >> 1) < p0 || (cell >> 1) >= p1) continue; + const Obs &o = fulls[i]; + const float I_corr = o.I * o.corr; + const float sigma_corr = corrected_sigma(o, I_corr, o.sigma * o.corr); + if (!(sigma_corr > 0.0f) || !std::isfinite(sigma_corr)) continue; + const double w = 1.0 / (static_cast(sigma_corr) * sigma_corr); + AnomAcc &a = anom[cell >> 1]; + a.d = acc[o.group].d; + a.swI[cell & 1][anom_half[i]] += w * static_cast(I_corr); + a.sw[cell & 1][anom_half[i]] += w; + a.nh[cell & 1][anom_half[i]]++; + } + }); // The per-hand table's rows: one mean per (pair, hand), or one per centric pair. Filled in // the pair walk below and read back by the R_meas walk after it; row_of_cell folds a // centric's two cells onto its single row. diff --git a/image_analysis/scale_merge/RotationScaleMerge.h b/image_analysis/scale_merge/RotationScaleMerge.h index f92255874..ebef3de15 100644 --- a/image_analysis/scale_merge/RotationScaleMerge.h +++ b/image_analysis/scale_merge/RotationScaleMerge.h @@ -231,12 +231,14 @@ private: // field it reads - hkl, frame, d, zeta - is read from the source reflection itself (ForEachKeptIn), // so on the resident path no per-observation record is built at all: on a fine-sliced long axis // that record was gigabytes, held beside the source reflections it was copied from. Filled by - // BuildInRangeObservations and handed back at the end of Ingest. - std::vector ingest_delta_phi, ingest_partiality, ingest_image_number; + // BuildInRangeObservations and handed back at the end of Ingest. Plain arrays, not sized vectors, for + // the reason the staging buffers are (see Ingest): the build writes every element, and a sized vector + // would first zero all of them on one thread. + std::unique_ptr ingest_delta_phi, ingest_partiality, ingest_image_number; // The rocking-event usability test (RockingEventFrames) on the ingest-time values - which is what // that walk reads on the resident path, where the host corr is never refreshed (see // partials_released). Resident path only. - std::vector ingest_rock_ok; + std::unique_ptr ingest_rock_ok; // Which source reflections the resolution range kept (indexed like the sort keys: frame by frame, // from ingest_src_start), so that the i-th kept one of a frame can be found again. std::vector ingest_keep; @@ -432,7 +434,7 @@ private: // `keys` is CONSUMED: it is freed as soon as the permutation has been remapped, before the // observation array is built, so the two never coexist - together they would be another third of // the payload on top of it. - void BuildInRangeObservations(std::vector &keys); + void BuildInRangeObservations(std::unique_ptr &keys, int n_obs); // Compute the dense ASU-group id for the current space group by grouping the (pre-sorted) raw-hkl // runs by their ASU key - one gemmi ASU reduction per distinct raw hkl, not per observation. Fills @@ -441,7 +443,8 @@ private: // Without a GPU: the partials by group, in observation order (a CSR - start and count per group), // which ComputeAsuGroups builds for the GPU reduction anyway. ReducePartialGroupMeans sums each // group over it, on all threads and in the order the serial loop would. - std::vector partial_group_start, partial_group_count, partial_group_perm; + std::vector partial_group_start, partial_group_count; + std::unique_ptr partial_group_perm; // The observation's inverse-variance weight in the scaling reference, and its scaled intensity; // 0 when the observation is not in the reference at all. diff --git a/image_analysis/scale_merge/WilsonOutliers.cpp b/image_analysis/scale_merge/WilsonOutliers.cpp index 215b22e9a..cfaaf8117 100644 --- a/image_analysis/scale_merge/WilsonOutliers.cpp +++ b/image_analysis/scale_merge/WilsonOutliers.cpp @@ -41,7 +41,18 @@ WilsonOutlierResult WilsonOutliers(const std::vector &obs, do return obs[a].d != obs[b].d ? obs[a].d > obs[b].d : a < b; }); const size_t n_shells = std::max(1, idx.size() / OBS_PER_SHELL); - const auto shell_of = [&](size_t j) { return j * n_shells / idx.size(); }; + // The observations in that order, so the walks below read them one after another instead of each + // through idx, and where each shell starts: shell s is the j with j * n_shells / N == s, which begins + // at the first j with j * n_shells >= s * N. Each shell is then one task, and every sum below is still + // taken over its shell in the order of j, so the split changes no rounding. + std::vector so(idx.size()); + ParallelChunks(static_cast(idx.size()), nthreads, [&](int lo, int hi) { + for (int j = lo; j < hi; ++j) so[j] = obs[idx[j]]; + }); + std::vector shell_start(n_shells + 1); + for (size_t sh = 0; sh <= n_shells; ++sh) + shell_start[sh] = (sh * idx.size() + n_shells - 1) / n_shells; + const int n_shell_tasks = static_cast(n_shells); const auto lower_e2 = [&](const WilsonObservation &o, double mu) { return (o.I - z * o.sigma) / (o.epsilon * mu); }; @@ -50,34 +61,31 @@ WilsonOutlierResult WilsonOutliers(const std::vector &obs, do // measured , nothing in the shell can be called improbable against it. std::vector mu(n_shells, 0.0); std::vector shell_valid(n_shells, 0); - { - std::vector sum(n_shells, 0.0); - std::vector cnt(n_shells, 0); - for (size_t j = 0; j < idx.size(); ++j) { - sum[shell_of(j)] += obs[idx[j]].I / obs[idx[j]].epsilon; - ++cnt[shell_of(j)]; + ParallelFor(n_shell_tasks, nthreads, [&](int sh) { + double sum = 0.0; + size_t cnt = 0; + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) { + sum += so[j].I / so[j].epsilon; + ++cnt; } // Once more without the observations the plain Wilson bound already calls improbable: a single // artefact thousands of times would otherwise raise the mean of its own shell several-fold // and hide the smaller artefacts sharing it. - std::vector sum_kept(n_shells, 0.0), sum2_kept(n_shells, 0.0); - std::vector cnt_kept(n_shells, 0); - for (size_t j = 0; j < idx.size(); ++j) { - const auto &o = obs[idx[j]]; - const size_t s = shell_of(j); - if (sum[s] > 0.0 && lower_e2(o, sum[s] / cnt[s]) > wilson_bound(o)) + double sum_kept = 0.0, sum2_kept = 0.0; + size_t cnt_kept = 0; + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) { + const auto &o = so[j]; + if (sum > 0.0 && lower_e2(o, sum / cnt) > wilson_bound(o)) continue; const double x = o.I / o.epsilon; - sum_kept[s] += x; sum2_kept[s] += x * x; ++cnt_kept[s]; + sum_kept += x; sum2_kept += x * x; ++cnt_kept; } - for (size_t s = 0; s < n_shells; ++s) { - if (cnt_kept[s] < 2) continue; - const double n = static_cast(cnt_kept[s]); - mu[s] = sum_kept[s] / n; - const double var = std::max(0.0, (sum2_kept[s] - n * mu[s] * mu[s]) / (n - 1.0)); - shell_valid[s] = mu[s] > 0.0 && mu[s] > z * std::sqrt(var / n); - } - } + if (cnt_kept < 2) return; + const double n = static_cast(cnt_kept); + mu[sh] = sum_kept / n; + const double var = std::max(0.0, (sum2_kept - n * mu[sh] * mu[sh]) / (n - 1.0)); + shell_valid[sh] = mu[sh] > 0.0 && mu[sh] > z * std::sqrt(var / n); + }); // The tail's scale, peaks over threshold: above any threshold an exponential's excess is the same // exponential, so the median excess of the acentric observations over a common threshold u is @@ -85,30 +93,32 @@ WilsonOutlierResult WilsonOutliers(const std::vector &obs, do // typical observation is significant at u take part: where sigma is comparable to u , what // exceeds u is the noise tail, and it would read as a heavy intensity tail. size_t n_acentric = 0; - for (size_t j = 0; j < idx.size(); ++j) - if (!obs[idx[j]].centric && shell_valid[shell_of(j)]) ++n_acentric; + for (size_t sh = 0; sh < n_shells; ++sh) + if (shell_valid[sh]) + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) + if (!so[j].centric) ++n_acentric; const double u = std::max(0.0, std::log(static_cast(n_acentric) / 100.0)); std::vector shell_measures_tail(n_shells, 0); - { - std::vector> noise(n_shells); // sigma / (epsilon ) - for (size_t j = 0; j < idx.size(); ++j) { - const auto &o = obs[idx[j]]; - if (shell_valid[shell_of(j)]) noise[shell_of(j)].push_back(o.sigma / (o.epsilon * mu[shell_of(j)])); - } - for (size_t s = 0; s < n_shells; ++s) { - auto &v = noise[s]; - if (v.empty()) continue; - const size_t mid = v.size() / 2; - std::nth_element(v.begin(), v.begin() + mid, v.end()); - shell_measures_tail[s] = z * v[mid] <= u; - } - } + ParallelFor(n_shell_tasks, nthreads, [&](int sh) { + if (!shell_valid[sh]) return; + std::vector v; // sigma / (epsilon ) + v.reserve(shell_start[sh + 1] - shell_start[sh]); + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) + v.push_back(so[j].sigma / (so[j].epsilon * mu[sh])); + if (v.empty()) return; + const size_t mid = v.size() / 2; + std::nth_element(v.begin(), v.begin() + mid, v.end()); + shell_measures_tail[sh] = z * v[mid] <= u; + }); std::vector excess; - for (size_t j = 0; j < idx.size(); ++j) { - const auto &o = obs[idx[j]]; - if (o.centric || !shell_measures_tail[shell_of(j)]) continue; - const double e2 = o.I / (o.epsilon * mu[shell_of(j)]); - if (e2 > u) excess.push_back(e2 - u); + for (size_t sh = 0; sh < n_shells; ++sh) { + if (!shell_measures_tail[sh]) continue; + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) { + const auto &o = so[j]; + if (o.centric) continue; + const double e2 = o.I / (o.epsilon * mu[sh]); + if (e2 > u) excess.push_back(e2 - u); + } } if (!excess.empty()) { const size_t mid = excess.size() / 2; @@ -118,19 +128,23 @@ WilsonOutlierResult WilsonOutliers(const std::vector &obs, do out.bound = out.tail_scale * t; // Which observations are improbable, and the observations of each reflection (in valid shells). + // Each observation is written once, at its own index, so the shells can do it side by side; the + // reflections are then formed by a sort on a total order, whatever order tested was filled in. std::vector improbable(obs.size(), 0); + ParallelFor(n_shell_tasks, nthreads, [&](int sh) { + if (!shell_valid[sh]) return; + for (size_t j = shell_start[sh]; j < shell_start[sh + 1]; ++j) { + const auto &o = so[j]; + out.e2[idx[j]] = static_cast(o.I / (o.epsilon * mu[sh])); + improbable[idx[j]] = lower_e2(o, mu[sh]) > out.tail_scale * wilson_bound(o); + } + }); std::vector tested; - for (size_t j = 0; j < idx.size(); ++j) { - const size_t i = idx[j]; - if (!shell_valid[shell_of(j)]) continue; - const auto &o = obs[i]; - const double m = mu[shell_of(j)]; - out.e2[i] = static_cast(o.I / (o.epsilon * m)); - improbable[i] = lower_e2(o, m) > out.tail_scale * wilson_bound(o); - tested.push_back(i); - } + for (size_t sh = 0; sh < n_shells; ++sh) + if (shell_valid[sh]) + tested.insert(tested.end(), idx.begin() + shell_start[sh], idx.begin() + shell_start[sh + 1]); out.n_tested = tested.size(); - std::sort(tested.begin(), tested.end(), [&](size_t a, size_t b) { + ParallelSort(tested.begin(), tested.end(), nthreads, [&](size_t a, size_t b) { return obs[a].unit != obs[b].unit ? obs[a].unit < obs[b].unit : a < b; }); diff --git a/rugnux/Rugnux.cpp b/rugnux/Rugnux.cpp index 67e279c98..7a10e1c44 100644 --- a/rugnux/Rugnux.cpp +++ b/rugnux/Rugnux.cpp @@ -7165,22 +7165,34 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b // declared, so the L-test can be repaired for it, and - the merge being in P1 - without the // reflections the lattice centring extinguishes, which an R lattice in its hexagonal cell // still carries (two thirds of them, and every axis step lands on one). - TranslationalNCSResult pre_tncs; - if (result.consensus_cell) { - pre_tncs = AnalyzeTranslationalNCS(sm.merged, gemmi::UnitCell(*result.consensus_cell), nullptr, 30, 0, - config_.nthreads); - result.pre_promotion_tncs_measured = pre_tncs.measurable; - } + // + // Nothing reads these before the adopted group's merge below, and nothing writes this merge + // until that merge replaces it, so they are measured beside it rather than ahead of it. The + // cell is taken now: a change of basis committed below replaces it. const char lattice_centring = end_msg.rotation_lattice_type.has_value() ? end_msg.rotation_lattice_type->centering : 'P'; - const auto pre_promotion_twinning = AnalyzeTwinning( - sm.merged, nullptr, 20, TranslationalNCSVectorForLTest(pre_tncs), lattice_centring); - result.pre_promotion_twinning = pre_promotion_twinning; - if (pre_promotion_twinning.twinning_suspected) - logger.Warning("Twinning indicators BEFORE the space-group decision (subgroup merge): " - "<|L|> = {:.3f}, second moment = {:.3f} (untwinned 0.500 / 2.00) - if the " - "search promoted the point group, treat the promotion with suspicion", - pre_promotion_twinning.mean_abs_l, pre_promotion_twinning.second_moment); + auto pre_promotion = std::async(std::launch::async, + [&merged = sm.merged, cell = result.consensus_cell, + lattice_centring, nthreads = config_.nthreads] { + TranslationalNCSResult tncs; + if (cell) + tncs = AnalyzeTranslationalNCS(merged, gemmi::UnitCell(*cell), nullptr, 30, 0, nthreads); + auto twinning = AnalyzeTwinning(merged, nullptr, 20, TranslationalNCSVectorForLTest(tncs), + lattice_centring); + return std::make_pair(tncs, twinning); + }); + TranslationalNCSResult pre_tncs; + const auto join_pre_promotion = [&] { + auto [tncs, twinning] = pre_promotion.get(); + pre_tncs = tncs; + result.pre_promotion_tncs_measured = tncs.measurable; + result.pre_promotion_twinning = twinning; + if (twinning.twinning_suspected) + logger.Warning("Twinning indicators BEFORE the space-group decision (subgroup merge): " + "<|L|> = {:.3f}, second moment = {:.3f} (untwinned 0.500 / 2.00) - if the " + "search promoted the point group, treat the promotion with suspicion", + twinning.mean_abs_l, twinning.second_moment); + }; promoted_point_group = !sg_search.point_group_hm.empty() && sg_search.point_group_hm != "1"; if (!sg_search.refused_point_group_hm.empty()) logger.Warning("Higher symmetry {} was confirmed by the operator correlations but refused: " @@ -7901,7 +7913,9 @@ ProcessResult Rugnux::RunPipeline(RugnuxObserver *observer, bool write_output, b end_msg.space_group_number = static_cast(sg.number); result.space_group = sg; phase("Re-scaling in space group " + sg.short_name()); - sm = scale_and_merge(sg.short_name(), false); + auto adopted = scale_and_merge(sg.short_name(), false); + join_pre_promotion(); + sm = std::move(adopted); // A promotion the operator correlations CONFIRMED and Stage A then refused, put to // the merge. Every gate that can refuse one is a ratio against another operator or