75const std::string LOG_CHARGE_NAME(
"proton_charge");
77const std::vector<std::string> binningModeNames{
"Logarithmic",
"Linear"};
81const std::vector<std::string> unitNames{
"dSpacing",
"TOF",
"MomentumTransfer"};
82enum class BinUnit { DSPACE,
TOF, Q, enum_count };
85const std::string ENTRY_TOP_LEVEL(
"entry");
88double getFocussedPostion(
const detid_t detid,
const std::vector<double> &difc_focus,
89 std::map<detid_t, size_t> &detIDToSpecNum) {
90 if (detIDToSpecNum.contains(detid)) {
91 return difc_focus[detIDToSpecNum[detid]];
97std::vector<double> calculate_difc_focused(
const double l1,
const std::vector<double> &l2s,
98 const std::vector<double> &polars) {
99 constexpr double deg2rad = std::numbers::pi_v<double> / 180.;
101 std::vector<double>
difc;
103 std::transform(l2s.cbegin(), l2s.cend(), polars.cbegin(), std::back_inserter(
difc),
104 [l1,
deg2rad](
const auto &
l2,
const auto &polar) {
105 return 1. / Kernel::Units::tofToDSpacingFactor(l1, l2, deg2rad * polar, 0.);
129 return "Algorithm to focus powder diffraction data into a number of histograms according to a grouping "
130 "scheme defined in a CalFile.";
139 const std::vector<std::string> exts{
".nxs.h5",
".nxs",
"_event.nxs"};
142 "The name of the Event NeXus file to read, including its full or relative path. "
143 "The file name is typically of the form INST_####_event.nxs.");
146 "To only include events after the provided start time, in seconds (relative to the start of the run).");
150 "To only include events before the provided stop time, in seconds (relative to the start of the run).");
153 "Input workspace specifying \"splitters\", i.e. time intervals and targets for event filtering. "
154 "Currently only a single output workspace is supported.");
156 "Flag indicating whether in SplitterWorkspace the times are absolute or "
157 "relative. If true, they are relative to the run start time.");
160 "For development testing. Changes how the splitters are processed. If true then use ProcessBankSplitTask "
161 "otherwise loop over ProcessBankTask.");
163 "Find time-of-flight when neutron was at the sample position. This is only necessary for fast logs "
164 "(i.e. more frequent than proton on target pulse).");
167 "If true, events will be splitting using full time values (tof+pulsetime) rather than just pulsetime.");
168 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
169 mustBePositive->setLower(0);
171 "Filter bad pulses in the same way that :ref:`algm-FilterBadPulses` does.");
172 auto range = std::make_shared<BoundedValidator<double>>();
173 range->setBounds(0., 100.);
175 "The percentage of the average to use as the lower bound when filtering bad pulses.");
178 "A GroupingWorkspace giving the grouping info. If not provided then the grouping from the "
179 "calibration file will be used if provided, else a default grouping of one group per bank.");
180 const std::vector<std::string> cal_exts{
".h5",
".hd5",
".hdf",
".cal"};
182 "The .cal file containing the position correction factors. Either this or OffsetsWorkspace needs to "
186 "Optional: A Workspace containing the calibration information. This takes precedence over the "
187 "calibration from CalFileName.");
190 "Optional: A workspace giving which detectors are masked. This takes precedence over the mask "
191 "from CalFileName.");
192 const std::vector<std::string> grp_exts{
".xml",
".h5",
".hd5",
".hdf",
".cal"};
194 "An optional file containing grouping information. Overrides grouping from CalFileName. "
195 "Supported formats: XML (from SaveDetectorsGrouping) and HDF5/cal (from LoadDiffCal).");
196 auto mustBePosArr = std::make_shared<Kernel::ArrayBoundedValidator<double>>();
197 mustBePosArr->setLower(0.0);
199 "Minimum x-value for the output binning");
201 "Bin size for output data");
203 "Minimum x-value for the output binning");
205 "The units of the input X min, max and delta values. Output will always be TOF");
207 "Specify binning behavior ('Logarithmic')");
210 "If specified, only these logs will be loaded from the file. Setting this will automatically override the "
211 "default LogBlockList");
214 std::vector<std::string>{
"Phase\\*",
"Speed\\*",
"BL\\*:Chop:\\*",
"chopper\\*TDC"}),
215 "If specified, these logs will not be loaded from the file. Set as empty list ``[]`` to disable");
218 "An output workspace.");
221 const std::string CHUNKING_PARAM_GROUP(
"Chunking-temporary");
222 auto positiveIntValidator = std::make_shared<Mantid::Kernel::BoundedValidator<int>>();
223 positiveIntValidator->setLower(1);
226 "Number of elements of time-of-flight or detector-id to read at a time. This is a maximum");
230 "Number of events to read in a single thread. Higher means less threads are created.");
236 "The bank for which to read data; if specified, others will be blank");
240 auto mandatoryDblValidator = std::make_shared<MandatoryValidator<double>>();
241 auto positiveDblValidator = std::make_shared<Mantid::Kernel::BoundedValidator<double>>();
242 positiveDblValidator->setLower(0);
243 auto l1Validator = std::make_shared<CompositeValidator>();
244 l1Validator->add(mandatoryDblValidator);
245 l1Validator->add(positiveDblValidator);
247 auto mandatoryDblArrayValidator = std::make_shared<MandatoryValidator<std::vector<double>>>();
248 auto positionArrayValidator = std::make_shared<CompositeValidator>();
249 positionArrayValidator->add(mandatoryDblArrayValidator);
250 positionArrayValidator->add(mustBePosArr);
252 "The primary distance :math:`\\ell_1` from beam to sample");
255 "The secondary distances :math:`\\ell_2` from sample to focus group");
258 "The effective polar angle (:math:`2\\theta`) of each focus group");
261 "The effective azimuthal angle :math:`\\phi` for each focus group");
265 std::map<std::string, std::string> errors;
270 if (disk_chunk < grainsize_events) {
286 const auto num_l2s = l2s.size();
289 errors[
PropertyNames::L2] = strmakef(
"L2S has inconsistent length %zu", num_l2s);
295 if (num_l2s != phi.size()) {
296 errors[
PropertyNames::L2] = strmakef(
"L2S has inconsistent length %zu", num_l2s);
307 const auto numMin = xmins.size();
308 const auto numMax = xmaxs.size();
309 const auto numDelta = deltas.size();
311 if (std::any_of(deltas.cbegin(), deltas.cend(), [](
double d) { return !std::isfinite(d) || d == 0; }))
313 else if (!(numDelta == 1 || numDelta == num_l2s))
316 if (!(numMin == 1 || numMin == num_l2s))
318 if (!(numMax == 1 || numMax == num_l2s))
331 std::vector<std::string> bankEntryNames;
332 std::vector<std::string> bankNames;
335 const std::size_t num_banks_to_read = bankEntryNames.size();
336 g_log.
debug() <<
"Total banks to read: " << num_banks_to_read <<
"\n";
345 std::map<size_t, std::set<detid_t>> grouping;
354 }
catch (std::exception &e) {
355 g_log.
warning() <<
"Error while loading meta data: " << e.what() <<
'\n';
358 auto periodLog = std::make_unique<const TimeSeriesProperty<int>>(
"period_log");
363 g_log.
information() <<
"User provided LogAllowList, default LogBlockList being ignored\n";
366 LoadEventNexus::runLoadNexusLogs<MatrixWorkspace_sptr>(filename, wksp, *
this,
false, nPeriods, periodLog, allow_logs,
369 LoadEventNexus::loadInstrument<MatrixWorkspace_sptr>(filename, wksp, ENTRY_TOP_LEVEL,
this, &descriptor);
373 if (!grp_filename.empty() && !groupingWS) {
381 if (!cal_filename.empty()) {
382 this->
loadCalFile(wksp, cal_filename, groupingWS, calibrationWS, maskWS);
386 m_masked = maskWS->getMaskedDetectors();
390 const auto groupIds = groupingWS->getGroupIDs(
false);
391 num_hist = groupIds.size();
392 g_log.
information() <<
"Using grouping workspace with " << num_hist <<
" groups\n";
393 for (
size_t outputindex = 0; outputindex < groupIds.size(); ++outputindex) {
394 const auto detids = groupingWS->getDetectorIDsOfGroup(groupIds[outputindex]);
395 grouping[outputindex] = std::set<detid_t>(detids.begin(), detids.end());
402 this->
progress(.0,
"Create output workspace");
411 std::vector<double> setPhi(l2s.size(), 0.0);
415 const std::vector<double> azimuthals(setPhi);
416 const std::vector<specnum_t> specids;
417 const auto difc_focused = calculate_difc_focused(l1, l2s, polars);
422 this->
progress(.05,
"Determining pulse indices");
424 this->
progress(.07,
"Reading events");
427 std::map<size_t, std::set<detid_t>> bank_detids;
428 for (
size_t bankIndex = 0; bankIndex < num_banks_to_read; ++bankIndex) {
430 bank_detids[bankIndex] = wksp->getInstrument()->getDetectorIDsInBank(bankNames.at(bankIndex));
431 }
catch (std::exception &e) {
432 g_log.
warning() <<
"Error getting detector IDs for " << bankNames.at(bankIndex) <<
": " << e.what() <<
"\n";
437 if (!grouping.empty()) {
438 for (
const auto &
group : grouping) {
439 for (
const auto &detid :
group.second) {
445 grouping[0] = std::set<detid_t>{};
446 for (
const auto &[i, detids] : bank_detids) {
447 grouping[0].insert(detids.begin(), detids.end());
448 for (
const auto &detid : detids) {
455 this->
progress(.1,
"Creating calibration constants");
468 this->
progress(.15,
"Set instrument geometry");
472 this->
progress(.17,
"Convert bins to TOF");
481 g_log.
debug() << (DISK_CHUNK / GRAINSIZE_EVENTS) <<
" threads per chunk\n";
485 if (!frequency_log) {
486 throw std::runtime_error(
"Frequency log not found in workspace run");
488 m_pulse_times = std::make_shared<std::vector<Mantid::Types::Core::DateAndTime>>(frequency_log->timesAsVector());
490 if (timeSplitter.empty()) {
495 auto loader = std::make_shared<NexusLoader>(
is_time_filtered, pulse_indices);
497 auto progress = std::make_shared<API::Progress>(
this, .17, .9, num_banks_to_read);
498 ProcessBankTask task(bankEntryNames, h5file, loader, processingData, calibFactory,
static_cast<size_t>(DISK_CHUNK),
499 static_cast<size_t>(GRAINSIZE_EVENTS),
progress);
501 if (num_banks_to_read > 1) {
502 tbb::parallel_for(tbb::blocked_range<size_t>(0, num_banks_to_read), task);
504 task(tbb::blocked_range<size_t>(0, 1));
514 wksp->mutableRun().setTimeROI(filterROI);
515 wksp->mutableRun().removeDataOutsideTimeROI();
520 std::vector<std::string> wsNames;
521 std::vector<int> workspaceIndices;
522 std::vector<MatrixWorkspace_sptr> workspaces;
523 std::vector<SpectraProcessingData> processingDatas;
524 for (
const int &splitter_target : timeSplitter.outputWorkspaceIndices()) {
525 std::string ws_name = ws_basename +
"_" + timeSplitter.getWorkspaceIndexName(splitter_target);
526 wsNames.push_back(std::move(ws_name));
527 workspaceIndices.push_back(splitter_target);
528 workspaces.emplace_back(wksp->clone());
532 auto progress = std::make_shared<API::Progress>(
this, .17, .9, num_banks_to_read * workspaceIndices.size());
534 g_log.
information() <<
"Using ProcessBankSplitFullTimeTask for splitter processing\n";
539 if (!filterROI.useAll()) {
540 combined_time_roi.update_intersection(filterROI);
545 auto loader = std::make_shared<NexusLoader>(
is_time_filtered, pulse_indices);
547 const auto &splitterMap = timeSplitter.getSplittersMap();
550 static_cast<size_t>(DISK_CHUNK),
static_cast<size_t>(GRAINSIZE_EVENTS),
554 if (num_banks_to_read > 1) {
555 tbb::parallel_for(tbb::blocked_range<size_t>(0, num_banks_to_read), task);
557 task(tbb::blocked_range<size_t>(0, 1));
561 g_log.
information() <<
"Using ProcessBankSplitTask for splitter processing\n";
565 std::vector<PulseROI> pulse_indices;
566 auto loader = std::make_shared<NexusLoader>(
is_time_filtered, pulse_indices, target_to_pulse_indices);
568 ProcessBankSplitTask task(bankEntryNames, h5file, loader, workspaceIndices, processingDatas, calibFactory,
569 static_cast<size_t>(DISK_CHUNK),
static_cast<size_t>(GRAINSIZE_EVENTS),
progress);
571 if (num_banks_to_read > 1) {
572 tbb::parallel_for(tbb::blocked_range<size_t>(0, num_banks_to_read), task);
574 task(tbb::blocked_range<size_t>(0, 1));
580 tbb::blocked_range<size_t>(0, workspaceIndices.size()),
581 [&](
const tbb::blocked_range<size_t> &target_indices) {
582 for (size_t target_index = target_indices.begin(); target_index != target_indices.end(); ++target_index) {
583 const int splitter_target = workspaceIndices[target_index];
585 auto splitter_roi = timeSplitter.getTimeROI(splitter_target);
587 auto target_roi = filterROI;
588 if (target_roi.useAll())
589 target_roi = std::move(splitter_roi);
590 else if (!splitter_roi.useAll())
591 target_roi.update_intersection(splitter_roi);
594 MatrixWorkspace_sptr target_wksp = workspaces[target_index];
596 const auto pulse_indices = this->determinePulseIndices(target_roi);
597 auto loader = std::make_shared<NexusLoader>(is_time_filtered, pulse_indices);
599 ProcessBankTask task(bankEntryNames, h5file, loader, processingDatas[target_index], calibFactory,
600 static_cast<size_t>(DISK_CHUNK), static_cast<size_t>(GRAINSIZE_EVENTS), progress);
602 if (num_banks_to_read > 1) {
603 tbb::parallel_for(tbb::blocked_range<size_t>(0, num_banks_to_read), task);
605 task(tbb::blocked_range<size_t>(0, 1));
615 for (
size_t idx = 0; idx < workspaceIndices.size(); ++idx) {
620 auto target_roi = timeSplitter.getTimeROI(workspaceIndices[idx]);
621 if (target_roi.useAll())
622 target_roi = filterROI;
623 else if (!filterROI.useAll())
624 target_roi.update_intersection(filterROI);
627 workspaces[idx]->mutableRun().setTimeROI(target_roi);
628 workspaces[idx]->mutableRun().removeDataOutsideTimeROI();
629 AnalysisDataService::Instance().addOrReplace(wsNames[idx], workspaces[idx]);
634 groupws->setAlwaysStoreInADS(
true);
635 groupws->setProperty(
"InputWorkspaces", wsNames);
636 groupws->setProperty(
"OutputWorkspace", ws_basename);
639 if (!groupws->isExecuted()) {
640 throw std::runtime_error(
"Failed to group output workspaces");
650 std::vector<std::string> &bankEntryNames,
651 std::vector<std::string> &bankNames) {
654 std::set<std::string>
const classEntries = descriptor.
allAddressesOfType(
"NXevent_data");
655 if (classEntries.empty()) {
656 throw std::runtime_error(
"No NXevent_data entries found in file");
659 const int bankNum = getProperty(PropertyNames::BANK_NUMBER);
661 const std::regex classRegex(
"(/entry/)([^/]*)");
663 for (
const std::string &classEntry : classEntries) {
664 if (std::regex_match(classEntry, groups, classRegex)) {
665 const std::string entry_name(groups[2].str());
666 if (classEntry.ends_with(
"bank_error_events")) {
668 }
else if (classEntry.ends_with(
"bank_unmapped_events")) {
671 auto underscore_pos = entry_name.find_first_of(
'_');
672 const auto bankName = entry_name.substr(0, underscore_pos);
678 bankEntryNames.push_back(entry_name);
679 bankNames.push_back(bankName);
688 const bool linearBins = bool(binmode == BinningMode::LINEAR);
689 const std::string binUnits = getPropertyValue(PropertyNames::BIN_UNITS);
690 std::vector<double> x_delta = getProperty(PropertyNames::X_DELTA);
691 std::vector<double> x_min = getProperty(PropertyNames::X_MIN);
692 std::vector<double> x_max = getProperty(PropertyNames::X_MAX);
693 const bool raggedBins = (x_delta.size() != 1 || x_min.size() != 1 || x_max.size() != 1);
695 constexpr bool resize_xnew{
true};
696 constexpr bool full_bins_only{
false};
699 double const binWidth = linearBins ? x_delta[0] : -1. * std::abs(x_delta[0]);
700 std::vector<double> xAxisTmp;
703 HistogramData::BinEdges XValues(std::move(xAxisTmp));
704 wksp->initialize(num_hist, HistogramData::Histogram(XValues, HistogramData::Counts(XValues.size() - 1, 0.0)));
708 if (x_delta.size() == 1)
709 x_delta.resize(num_hist, x_delta[0]);
710 if (x_min.size() == 1)
711 x_min.resize(num_hist, x_min[0]);
712 if (x_max.size() == 1)
713 x_max.resize(num_hist, x_max[0]);
715 for (
size_t i = 1; i < num_hist; ++i) {
716 double const raggedBinWidth = linearBins ? x_delta[i] : -1. * std::abs(x_delta[i]);
717 std::vector<double>
const params{x_min[i], raggedBinWidth, x_max[i]};
718 std::vector<double> xtmpragged;
720 HistogramData::BinEdges XValues_new(std::move(xtmpragged));
721 wksp->setHistogram(i, HistogramData::Histogram(XValues_new, HistogramData::Counts(XValues_new.size() - 1, 0.0)));
725 wksp->getAxis(0)->setUnit(binUnits);
726 wksp->setYUnit(
"Counts");
732 const size_t numSpectra = outputWS->getNumberHistograms();
733 for (
size_t i = 0; i < numSpectra; ++i) {
734 const auto &spectrum = outputWS->getSpectrum(i);
735 processingData.
binedges.emplace_back(&spectrum.x().rawData());
736 processingData.
counts.emplace_back(spectrum.y().size());
738 return processingData;
743 const size_t numSpectra = outputWS->getNumberHistograms();
744 for (
size_t i = 0; i < numSpectra; ++i) {
745 auto &spectrum = outputWS->getSpectrum(i);
746 auto &y_values = spectrum.mutableY();
748 processingData.
counts[i].cbegin(), processingData.
counts[i].cend(), y_values.begin(),
749 [](
const std::atomic_uint32_t &val) { return static_cast<double>(val.load(std::memory_order_relaxed)); });
750 auto &e_values = spectrum.mutableE();
751 std::transform(processingData.
counts[i].cbegin(), processingData.
counts[i].cend(), e_values.begin(),
752 [](
const std::atomic_uint32_t &val) {
753 return std::sqrt(static_cast<double>(val.load(std::memory_order_relaxed)));
759 const std::vector<double> &difc_focus) {
760 const auto detInfo = wksp->detectorInfo();
762 for (
auto iter = detInfo.cbegin(); iter != detInfo.cend(); ++iter) {
763 if (!iter->isMonitor()) {
764 const auto difc_focussed = getFocussedPostion(
static_cast<detid_t>(iter->detid()), difc_focus, detIDToSpecNum);
768 m_calibration.emplace(
static_cast<detid_t>(iter->detid()),
769 difc_focussed / detInfo.difcUncalibrated(iter->index()));
774void AlignAndFocusPowderSlim::initCalibrationConstantsFromCalWS(
const std::vector<double> &difc_focus,
776 for (
size_t row = 0; row < calibrationWS->rowCount(); ++row) {
777 const detid_t detid = calibrationWS->cell<
int>(row, 0);
778 const double detc = calibrationWS->cell<
double>(row, 1);
779 const auto difc_focussed = getFocussedPostion(detid, difc_focus, detIDToSpecNum);
783 m_calibration.emplace(detid, difc_focussed / detc);
794 const bool load_grouping = !groupingWS;
795 const bool load_calibration = !calibrationWS;
796 const bool load_mask = !maskWS;
799 if (!load_grouping && !load_calibration && !load_mask)
802 auto alg = createChildAlgorithm(
"LoadDiffCal");
803 alg->setPropertyValue(
"Filename", filename);
804 if (filename.ends_with(
".cal")) {
805 alg->setProperty(
"InputWorkspace", inputWS);
808 g_log.
debug(
"Not supplying instrument information to LoadDifCal");
810 alg->setProperty<
bool>(
"MakeCalWorkspace", load_calibration);
811 alg->setProperty<
bool>(
"MakeGroupingWorkspace", load_grouping);
812 alg->setProperty<
bool>(
"MakeMaskWorkspace", load_mask);
813 alg->setPropertyValue(
"WorkspaceName",
"temp");
814 alg->executeAsChildAlg();
817 g_log.
debug() <<
"Loading grouping workspace from calibration file\n";
818 groupingWS = alg->getProperty(
"OutputGroupingWorkspace");
820 if (load_calibration) {
821 calibrationWS = alg->getProperty(
"OutputCalWorkspace");
824 maskWS = alg->getProperty(
"OutputMaskWorkspace");
833 const std::string &filename) {
834 g_log.
debug() <<
"Loading grouping from file: " << filename <<
'\n';
837 std::string lowerFilename = filename;
838 std::transform(lowerFilename.begin(), lowerFilename.end(), lowerFilename.begin(),
839 [](
unsigned char c) { return std::tolower(c); });
842 if (lowerFilename.ends_with(
".xml")) {
847 auto alg = createChildAlgorithm(
"LoadDetectorsGroupingFile");
848 alg->setPropertyValue(
"InputFile", filename);
849 alg->executeAsChildAlg();
850 groupingWS = alg->getProperty(
"OutputWorkspace");
853 auto alg = createChildAlgorithm(
"LoadDiffCal");
854 alg->setPropertyValue(
"Filename", filename);
855 if (lowerFilename.ends_with(
".cal")) {
857 alg->setProperty(
"InputWorkspace", std::dynamic_pointer_cast<API::Workspace>(wksp));
859 alg->setProperty<
bool>(
"MakeCalWorkspace",
false);
860 alg->setProperty<
bool>(
"MakeGroupingWorkspace",
true);
861 alg->setProperty<
bool>(
"MakeMaskWorkspace",
false);
862 alg->setPropertyValue(
"WorkspaceName",
"slim_grp");
863 alg->executeAsChildAlg();
864 groupingWS = alg->getProperty(
"OutputGroupingWorkspace");
875 const auto detInfo = wksp->detectorInfo();
877 const double L1 = detInfo.l1();
879 if (this->getProperty(PropertyNames::CORRECTION_TO_SAMPLE)) {
881 for (
auto iter = detInfo.cbegin(); iter != detInfo.cend(); ++iter) {
882 if (!iter->isMonitor()) {
883 const double path_correction = L1 / (L1 + iter->l2()) * 1000.0;
884 m_scale_at_sample.emplace(
static_cast<detid_t>(iter->detid()), path_correction);
889 for (
auto iter = detInfo.cbegin(); iter != detInfo.cend(); ++iter) {
890 if (!iter->isMonitor()) {
891 m_scale_at_sample.emplace(
static_cast<detid_t>(iter->detid()), 1000.0);
899 const std::vector<specnum_t> &specids,
const std::vector<double> &l2s,
const std::vector<double> &azimuthals) {
901 editAlg->setLoggingOffset(1);
902 editAlg->setProperty(
"Workspace", wksp);
904 editAlg->setProperty(
"PrimaryFlightPath", l1);
906 editAlg->setProperty(
"Polar", polars);
907 if (!specids.empty())
908 editAlg->setProperty(
"SpectrumIDs", specids);
910 editAlg->setProperty(
"L2", l2s);
911 if (!azimuthals.empty())
912 editAlg->setProperty(
"Azimuthal", azimuthals);
913 editAlg->executeAsChildAlg();
915 wksp = editAlg->getProperty(
"Workspace");
921 if (wksp->getAxis(0)->unit()->unitID() ==
"TOF") {
927 convertUnits->setProperty(
"InputWorkspace", wksp);
928 convertUnits->setPropertyValue(
"Target",
"TOF");
929 convertUnits->executeAsChildAlg();
930 wksp = convertUnits->getProperty(
"OutputWorkspace");
944 const auto startOfRun = wksp->run().startTime();
947 double filter_time_start_sec = getProperty(PropertyNames::FILTER_TIMESTART);
948 double filter_time_stop_sec = getProperty(PropertyNames::FILTER_TIMESTOP);
950 this->progress(.15,
"Creating time filtering");
951 g_log.
information() <<
"Filtering pulses from " << filter_time_start_sec <<
" to " << filter_time_stop_sec <<
"s\n";
954 roi.
addROI(startOfRun + (filter_time_start_sec ==
EMPTY_DBL() ? 0.0 : filter_time_start_sec),
955 startOfRun + filter_time_stop_sec);
956 }
catch (
const std::runtime_error &e) {
957 throw std::invalid_argument(
"Invalid time range for filtering: " + std::string(e.what()));
962 if (getProperty(PropertyNames::FILTER_BAD_PULSES)) {
963 this->progress(.16,
"Filtering bad pulses");
966 const auto [min_pcharge, max_pcharge, mean] =
967 wksp->run().getBadPulseRange(LOG_CHARGE_NAME, getProperty(PropertyNames::FILTER_BAD_PULSES_LOWER_CUTOFF));
968 g_log.
information() <<
"Filtering bad pulses; pcharge outside of " << min_pcharge <<
" to " << max_pcharge <<
'\n';
970 const auto run_start = wksp->getFirstPulseTime();
971 const auto run_stop = wksp->getLastPulseTime();
989std::vector<PulseROI> AlignAndFocusPowderSlim::determinePulseIndices(
const TimeROI &filterROI) {
991 std::vector<PulseROI> pulse_indices;
993 pulse_indices.emplace_back(0, std::numeric_limits<size_t>::max());
995 is_time_filtered =
true;
997 if (pulse_indices.empty())
998 throw std::invalid_argument(
"No valid pulse time indices found for filtering");
1001 return pulse_indices;
1012std::vector<std::pair<int, PulseROI>>
1013AlignAndFocusPowderSlim::determinePulseIndicesTargets(
const TimeROI &filterROI,
const TimeSplitter &timeSplitter) {
1014 std::vector<PulseROI> pulse_indices;
1015 if (filterROI.
useAll()) {
1016 pulse_indices.emplace_back(0, std::numeric_limits<size_t>::max());
1019 if (pulse_indices.empty())
1020 throw std::invalid_argument(
"No valid pulse time indices found for filtering");
1026 std::vector<std::pair<int, PulseROI>> intersected_target_pulse_indices;
1027 auto pulse_it = pulse_indices.cbegin();
1028 for (
const auto &target_pair : target_to_pulse_indices) {
1030 while (pulse_it != pulse_indices.cend() && pulse_it->second <= target_pair.second.first) {
1034 auto check_it = pulse_it;
1035 while (check_it != pulse_indices.cend() && check_it->first < target_pair.second.second) {
1037 size_t start_index = std::max(check_it->first, target_pair.second.first);
1038 size_t stop_index = std::min(check_it->second, target_pair.second.second);
1039 if (start_index < stop_index) {
1040 intersected_target_pulse_indices.emplace_back(target_pair.first,
PulseROI(start_index, stop_index));
1046 return intersected_target_pulse_indices;
1050AlignAndFocusPowderSlim::timeSplitterFromSplitterWorkspace(
const Types::Core::DateAndTime &filterStartTime) {
1053 std::dynamic_pointer_cast<DataObjects::SplittersWorkspace>(tempws);
1055 std::dynamic_pointer_cast<DataObjects::TableWorkspace>(tempws);
1058 if (!splittersWorkspace && !splitterTableWorkspace && !matrixSplitterWS)
1061 const bool isSplittersRelativeTime = this->getProperty(PropertyNames::SPLITTER_RELATIVE);
1064 if (splittersWorkspace) {
1066 }
else if (splitterTableWorkspace) {
1068 TimeSplitter(splitterTableWorkspace, isSplittersRelativeTime ? filterStartTime : DateAndTime::GPS_EPOCH);
1070 time_splitter =
TimeSplitter(matrixSplitterWS, isSplittersRelativeTime ? filterStartTime : DateAndTime::GPS_EPOCH);
1073 return time_splitter;
#define DECLARE_ALGORITHM(classname)
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
virtual std::shared_ptr< Algorithm > createChildAlgorithm(const std::string &name, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true, const int &version=-1)
Create a Child Algorithm.
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
bool isDefault(const std::string &name) const
A specialized class for dealing with file properties.
@ OptionalLoad
to specify a file to read but the file doesn't have to exist
@ Load
allowed here which will be passed to the algorithm
A property class for workspaces.
Base Workspace Abstract Class.
AlignAndFocusPowderSlim : TODO: DESCRIPTION.
std::vector< int64_t > loadSize
How much to load in the file.
const std::string summary() const override
Algorithm's summary for use in the GUI and help.
DataObjects::GroupingWorkspace_sptr loadGroupingFile(const API::MatrixWorkspace_sptr &wksp, const std::string &filename)
Load a grouping workspace from an explicit grouping file.
std::vector< std::pair< size_t, size_t > > determinePulseIndices(const Kernel::TimeROI &filterROI)
Determine the pulse indices for a given workspace and time ROI.
std::map< std::string, std::string > validateInputs() override
Perform validation of ALL the input properties of the algorithm.
SpectraProcessingData initializeSpectraProcessingData(const API::MatrixWorkspace_sptr &outputWS)
std::vector< int64_t > loadStart
Index to load start at in the file.
std::shared_ptr< std::vector< Types::Core::DateAndTime > > m_pulse_times
std::map< detid_t, double > m_calibration
detid: 1/difc
void storeSpectraProcessingData(const SpectraProcessingData &processingData, const API::MatrixWorkspace_sptr &outputWS)
void init() override
Initialize the algorithm's properties.
std::set< detid_t > m_masked
DataObjects::TimeSplitter timeSplitterFromSplitterWorkspace(const Types::Core::DateAndTime &)
std::map< detid_t, size_t > detIDToSpecNum
void determineBanksToLoad(const Mantid::Nexus::NexusDescriptor &descriptor, std::vector< std::string > &bankEntryNames, std::vector< std::string > &bankNames)
std::map< detid_t, double > m_scale_at_sample
Multiplicative 0<value<1 to move neutron TOF at sample.
void initScaleAtSample(const API::MatrixWorkspace_sptr &wksp)
For fast logs, calculate the sample position correction.
const std::string category() const override
Algorithm's category for identification.
std::vector< std::pair< int, std::pair< size_t, size_t > > > determinePulseIndicesTargets(const Kernel::TimeROI &filterROI, const DataObjects::TimeSplitter &timeSplitter)
Determine the pulse indices for a given workspace, time ROI, and time splitter.
void loadCalFile(const API::Workspace_sptr &inputWS, const std::string &filename, DataObjects::GroupingWorkspace_sptr &groupingWS, API::ITableWorkspace_sptr &calibrationWS, DataObjects::MaskWorkspace_sptr &maskWS)
Load the calibration file, filling in only the workspaces (grouping, calibration, mask) that have not...
API::MatrixWorkspace_sptr editInstrumentGeometry(API::MatrixWorkspace_sptr &wksp, const double l1, const std::vector< double > &polars, const std::vector< specnum_t > &specids, const std::vector< double > &l2s, const std::vector< double > &azimuthals)
int version() const override
Algorithm's version for identification.
const std::vector< std::string > seeAlso() const override
Function to return all of the seeAlso (these are not validated) algorithms related to this algorithm....
void initializeOutputWorkspace(const API::MatrixWorkspace_sptr &wksp, size_t num_hist)
void initCalibrationConstantsFromCalWS(const std::vector< double > &difc_focus, const API::ITableWorkspace_sptr calibrationWS)
Kernel::TimeROI getFilterROI(const API::MatrixWorkspace_sptr &wksp)
Create a TimeROI based on the filtering properties set in the algorithm.
API::MatrixWorkspace_sptr convertToTOF(API::MatrixWorkspace_sptr &wksp)
void exec() override
Execute the algorithm.
void initCalibrationConstants(API::MatrixWorkspace_sptr &wksp, const std::vector< double > &difc_focus)
static void loadEntryMetadata(const std::string &nexusfilename, T WS, const std::string &entry_name)
Load the run number and other meta data from the given bank.
std::vector< std::pair< int, std::pair< size_t, size_t > > > calculate_target_indices(const std::vector< DateAndTime > ×) const
Given a list of times, calculate the corresponding indices in the TimeSplitter.
Concrete workspace implementation.
Kernel/ArrayBoundedValidator.h.
Support for a property that holds an array of values.
BoundedValidator is a validator that requires the values to be between upper or lower bounds,...
A concrete property based on user options of a finite list of strings.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void setPropertyGroup(const std::string &name, const std::string &group)
Set the group for a given property.
void debug(const std::string &msg)
Logs at debug level.
void warning(const std::string &msg)
Logs at warning level.
void information(const std::string &msg)
Logs at information level.
Validator to check that a property is not left empty.
The concrete, templated class for properties.
Represents a time interval.
TimeROI : Object that holds information about when the time measurement was active.
std::vector< std::pair< size_t, size_t > > calculate_indices(const std::vector< Types::Core::DateAndTime > ×) const
void addROI(const std::string &startTime, const std::string &stopTime)
bool useAll() const
TimeROI selects all time to be used.
A specialised Property class for holding a series of time-value pairs.
std::set< std::string > allAddressesOfType(const std::string &type) const
std::shared_ptr< IAlgorithm > IAlgorithm_sptr
shared pointer to Mantid::API::IAlgorithm
std::shared_ptr< ITableWorkspace > ITableWorkspace_sptr
shared pointer to Mantid::API::ITableWorkspace
std::shared_ptr< Workspace > Workspace_sptr
shared pointer to Mantid::API::Workspace
Mantid::Kernel::SingletonHolder< AnalysisDataServiceImpl > AnalysisDataService
Kernel::Logger g_log("ExperimentInfo")
static logger object
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
const std::string GROUPING_WS("GroupingWorkspace")
const std::string FILTER_TIMESTART("FilterByTimeStart")
const std::string AZIMUTHALS("Azimuthal")
const std::string CAL_FILE("CalFileName")
const std::string GROUP_FILE("GroupFilename")
const std::string MASK_WKSP("MaskWorkspace")
const std::string FILTER_BAD_PULSES_LOWER_CUTOFF("BadPulsesLowerCutoff")
const std::string BANK_NUMBER("BankNumber")
const std::string ALLOW_LOGS("LogAllowList")
const std::string SPLITTER_RELATIVE("RelativeTime")
const std::string PROCESS_BANK_SPLIT_TASK("ProcessBankSplitTask")
const std::string OUTPUT_WKSP("OutputWorkspace")
const std::string CORRECTION_TO_SAMPLE("CorrectionToSample")
const std::string CAL_WKSP("CalibrationWorkspace")
const std::string BIN_UNITS("BinningUnits")
const std::string FILTER_TIMESTOP("FilterByTimeStop")
const std::string L2("L2")
const std::string BLOCK_LOGS("LogBlockList")
const std::string X_DELTA("XDelta")
const std::string X_MIN("XMin")
const std::string FILENAME("Filename")
const std::string POLARS("Polar")
const std::string BINMODE("BinningMode")
const std::string SPLITTER_WS("SplitterWorkspace")
const std::string EVENTS_PER_THREAD("EventsPerThread")
const std::string FILTER_BAD_PULSES("FilterBadPulses")
const std::string X_MAX("XMax")
const std::string FULL_TIME("UseFullTime")
const std::string L1("L1")
const std::string READ_SIZE_FROM_DISK("ReadSizeFromDisk")
std::pair< size_t, size_t > PulseROI
const int64_t PULSETIME_OFFSET
constexpr double IGNORE_PIXEL
std::shared_ptr< SplittersWorkspace > SplittersWorkspace_sptr
std::shared_ptr< TableWorkspace > TableWorkspace_sptr
shared pointer to Mantid::DataObjects::TableWorkspace
std::shared_ptr< GroupingWorkspace > GroupingWorkspace_sptr
shared pointer to the GroupingWorkspace class
std::shared_ptr< MaskWorkspace > MaskWorkspace_sptr
shared pointer to the MaskWorkspace class
constexpr double deg2rad
Defines units/enum for Crystal work.
MANTID_KERNEL_DLL std::string strmakef(char const *const fmt,...)
This is the constructor that std::string needed to have.
std::size_t MANTID_KERNEL_DLL createAxisFromRebinParams(const std::vector< double > ¶ms, std::vector< double > &xnew, const bool resize_xnew=true, const bool full_bins_only=false, const double xMinHint=std::nan(""), const double xMaxHint=std::nan(""), const bool useReverseLogarithmic=false, const double power=-1)
Creates a new output X array given a 'standard' set of rebinning parameters.
MANTID_NEXUS_DLL H5::FileAccPropList defaultFileAcc()
Default file access is H5F_CLOSE_STRONG.
const std::string BINMODE("BinningMode")
constexpr int EMPTY_INT() noexcept
Returns what we consider an "empty" integer within a property.
int32_t detid_t
Typedef for a detector ID.
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
std::string to_string(const wide_integer< Bits, Signed > &n)
std::vector< std::vector< std::atomic_uint32_t > > counts
std::vector< const std::vector< double > * > binedges
Describes the direction (within an algorithm) of a Property.
@ Input
An input workspace.
@ Output
An output workspace.