24#include "MantidIndexing/IndexInfo.h"
36#include "MantidNexus/NexusFile.h"
40#include <boost/format.hpp>
45using Mantid::Types::Core::DateAndTime;
54using namespace Kernel;
55using namespace DateAndTimeHelpers;
56using namespace Geometry;
58using namespace DataObjects;
59using Types::Core::DateAndTime;
62const std::vector<std::string> binningModeNames{
"Default",
"Linear",
"Logarithmic"};
66const std::string LOG_CHARGE_NAME(
"proton_charge");
69const std::string COMPRESS_TOL(
"CompressTolerance");
70const std::string COMPRESS_MODE(
"CompressBinningMode");
71const std::string BAD_PULSES_CUTOFF(
"FilterBadPulsesLowerCutoff");
76 std::string detectorEventsAddr = std::format(
"/{}/detector_1_events", topEntryName);
77 if (!file.hasAddress(detectorEventsAddr)) {
81 const std::string eventTimeShiftAddr(detectorEventsAddr +
"/event_time_offset_shift");
82 if (file.hasAddress(eventTimeShiftAddr)) {
83 std::string eventShiftType;
84 file.readData(eventTimeShiftAddr, eventShiftType);
85 return !(eventShiftType ==
"random");
88 const std::string programNameAddr = std::format(
"/{}/program_name", topEntryName);
89 if (file.hasAddress(programNameAddr)) {
90 std::string program_name;
91 file.readData(programNameAddr, program_name);
92 if (program_name ==
"ISISICP.EXE") {
103 : filter_tof_min(0), filter_tof_max(0), m_specMin(0), m_specMax(0), longest_tof(0), shortest_tof(0), bad_tofs(0),
104 discarded_events(0), compressEvents(false), m_instrument_loaded_correctly(false), loadlogs(false),
105 event_id_is_spec(false) {
119 if (descriptor.
isEntry(
"/entry",
"NXentry") || descriptor.
isEntry(
"/raw_data_1",
"NXentry")) {
131 const std::vector<std::string> exts{
".nxs.h5",
".nxs",
"_event.nxs"};
133 "The name of the Event NeXus file to read, including its full or "
135 "The file name is typically of the form INST_####_event.nxs (N.B. case "
136 "sensitive if running on Linux).");
139 "The name of the output EventWorkspace or WorkspaceGroup in which to "
140 "load the EventNexus file.");
143 "Optional: Name of the NXentry to load if it's not the default.");
146 "Optional: To exclude events that do not fall within a range "
147 "of times-of-flight. "
148 "This is the minimum accepted value in microseconds. Keep "
149 "blank to load all events.");
152 "Optional: To exclude events that do not fall within a range "
153 "of times-of-flight. "
154 "This is the maximum accepted value in microseconds. Keep "
155 "blank to load all events.");
158 "Optional: To only include events after the provided start "
159 "time, in seconds (relative to the start of the run).");
162 "Optional: To only include events before the provided stop "
163 "time, in seconds (relative to the start of the run).");
167 "Optional: To filter bad pulses set the Lower Cutoff percentage to use.");
169 std::string grp1 =
"Filter Events";
177 "Optional: To only include events from one bank. Any bank "
178 "whose name does not match the given string will have no "
182 "Optional: Only applies if you specified a single bank to "
183 "load with BankName. "
184 "Only pixels in the specified bank will be created if true; "
185 "all of the instrument's pixels will be created otherwise.");
188 std::string grp2 =
"Loading a Single Bank";
193 "Pre-count the number of events in each pixel before allocating memory "
194 "(optional, default True). "
195 "This can significantly reduce memory use and memory fragmentation; it "
196 "may also speed up loading.");
200 "CompressEvents while loading (optional, default: off). "
201 "This specified the tolerance to use (in microseconds) when compressing where positive is linear tolerance, "
202 "negative is logorithmic tolerance, and zero indicates that time-of-flight must be identical to compress.");
204 PropertyNames::COMPRESS_MODE, binningModeNames[
size_t(BinningMode::DEFAULT)],
205 std::make_shared<Mantid::Kernel::StringListValidator>(binningModeNames),
207 "Binning behavior can be specified in the usual way through sign of binwidth and other properties ('Default'); "
208 "or can be set to one of the allowed binning modes. "
209 "This will override all other specification or default behavior.");
211 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
212 mustBePositive->setLower(1);
214 "If loading the file by sections ('chunks'), this is the "
215 "section number of this execution of the algorithm.");
217 "If loading the file by sections ('chunks'), this is the "
218 "total number of sections.");
224 std::string grp3 =
"Reduce Memory Use";
232 "Load the monitors from the file (optional, default False).");
234 std::vector<std::string> options{
"",
"Events",
"Histogram"};
235 declareProperty(
"MonitorsLoadOnly",
"", std::make_shared<Kernel::StringListValidator>(options),
236 "If multiple repesentations exist, which one to load. "
237 "Default is to load the one that is present.");
240 "Optional: To exclude events from monitors that do not fall "
241 "within a range of times-of-flight. "
242 "This is the minimum accepted value in microseconds.");
245 "Optional: To exclude events from monitors that do not fall "
246 "within a range of times-of-flight. "
247 "This is the maximum accepted value in microseconds.");
250 "Optional: To only include events from monitors after the "
251 "provided start time, in seconds (relative to the start of "
255 "Optional: To only include events from monitors before the "
256 "provided stop time, in seconds (relative to the start of "
260 auto asEventsIsOn = [] {
261 std::unique_ptr<IPropertySettings> prop = std::make_unique<VisibleWhenProperty>(
"LoadMonitors",
IS_EQUAL_TO,
"1");
269 std::string grp4 =
"Monitors";
280 "A comma-separated list of individual spectra to read.");
283 "If true, only the meta data and sample logs will be loaded.");
286 "Load only the Sample/DAS logs from the file (default True).");
289 "Load all the logs from the nxs, without checking or processing them; if checked, LoadLogs will be "
290 "ignored; use with caution");
292 std::vector<std::string> loadType{
"Default",
"Multiprocess (experimental)"};
293 auto loadTypeValidator = std::make_shared<StringListValidator>(loadType);
295 "LoadType",
"Default", loadTypeValidator,
296 "Deprecated feature. This option has no effect on algorithm behavior and will be removed in a future release.");
299 "Reads the embedded Instrument XML from the NeXus file "
300 "(optional, default True). ");
303 "The number of bins intially defined. Use Rebin to change "
304 "the binning later. If there is no data loaded, or you "
305 "select meta data only you will only get 1 bin.");
310 "If specified, only these logs will be loaded from the file (each "
311 "separated by a space).");
314 "If specified, these logs will NOT be loaded from the file (each "
315 "separated by a space).");
322 g_log.
warning() <<
"The experimental multiprocess loader has been discontinued. The default loader will be used "
323 "instead. Please remove use of this property from all scripts.";
327 std::map<std::string, std::string> result;
329 if (!
isDefault(PropertyNames::BAD_PULSES_CUTOFF)) {
330 const double cutoff =
getProperty(PropertyNames::BAD_PULSES_CUTOFF);
331 if (cutoff < 0 || cutoff > 100)
332 result[PropertyNames::BAD_PULSES_CUTOFF] =
"Must be empty or between 0 and 100";
342 std::string nxentryProperty =
getProperty(
"NXentryName");
343 if (!nxentryProperty.empty()) {
348 std::string firstGoodEntry(
"");
349 std::set<std::string> goodEntries{
"entry",
"raw_data_1"};
350 auto allEntries =
m_file->getEntries();
351 for (std::string goodEntry : goodEntries) {
352 if (allEntries.count(goodEntry) != 0 && allEntries[goodEntry] !=
"SDS") {
353 firstGoodEntry = std::move(goodEntry);
359 g_log.
error() <<
"Unable to determine name of top level NXentry - assuming \"entry\".\n";
366 if ((!ConfigService::Instance().hasProperty(
"loadeventnexus.keeppausedevents")) &&
367 (
m_ws->run().getLogData(
"pause")->size() > 1)) {
368 g_log.
notice(
"Filtering out events when the run was marked as paused. "
369 "Set the loadeventnexus.keeppausedevents configuration "
370 "property to override this.");
373 filter->setProperty(
"InputWorkspace",
workspace);
374 filter->setProperty(
"OutputWorkspace",
workspace);
375 filter->setProperty(
"LogName",
"pause");
377 filter->setProperty(
"MinimumValue", 0.0);
378 filter->setProperty(
"MaximumValue", 0.0);
379 filter->setProperty(
"LogBoundary",
"Left");
390 using std::placeholders::_1;
391 auto func = std::bind(&LoadEventNexus::filterDuringPause<MatrixWorkspace_sptr>,
this, _1);
402 Mantid::Types::Core::DateAndTime &stopTime) {
405 filterByTime->setProperty(
"InputWorkspace",
workspace);
407 filterByTime->setProperty(
"AbsoluteStartTime", startTime.toISO8601String());
408 filterByTime->setProperty(
"AbsoluteStopTime", stopTime.toISO8601String());
409 filterByTime->execute();
410 return filterByTime->getProperty(
"OutputWorkspace");
416 Mantid::Types::Core::DateAndTime &startTime,
417 Mantid::Types::Core::DateAndTime &stopTime) {
419 using std::placeholders::_1;
420 auto func = std::bind(&LoadEventNexus::filterEventsByTime<EventWorkspace_sptr>,
this, _1, startTime, stopTime);
437 if (mode == BinningMode::LINEAR)
439 else if (mode == BinningMode::LOGARITHMIC)
446 bool load_monitors = this->
getProperty(
"LoadMonitors");
458 Progress prog(
this, 0.0, 0.3, reports);
461 m_ws = std::make_shared<EventWorkspaceCollection>();
469 <<
" events were encountered coming from pixels which "
470 "are not in the Instrument Definition File."
471 "These events were discarded.\n";
489 prog.
report(
"Loading monitors");
495 file.openData(
"event_time_zero");
500 if (!file.hasAttr(
"offset")) {
501 offset = DateAndTime(
"1970-01-01T00:00:00Z");
502 logger.
warning(
"In firstLastPulseTimes: no ISO8601 offset attribute "
503 "provided for event_time_zero, using UNIX epoch instead");
505 std::string isooffset;
506 file.getAttr(
"offset", isooffset);
507 offset = DateAndTime(isooffset);
510 if (file.hasAttr(
"units"))
511 file.getAttr(
"units", units);
513 auto pulse_times = Nexus::IOHelper::readNexusVector<double>(file,
"event_time_zero");
516 if (pulse_times.empty()) {
517 throw std::invalid_argument(
"Cannot find run start; event_time_zero contains no pulse times");
521 return std::make_pair(DateAndTime(pulse_times.front() * conv, 0.0) + offset.totalNanoseconds(),
522 DateAndTime(pulse_times.back() * conv, 0.0) + offset.totalNanoseconds());
536std::size_t
numEvents(Nexus::File &file,
bool &hasTotalCounts,
bool &oldNeXusFileNames,
const std::string &prefix) {
538 if (hasTotalCounts) {
539 hasTotalCounts =
false;
540 if (file.hasData(prefix +
"/total_counts")) {
542 file.openData(
"total_counts");
543 auto info = file.getInfo();
547 file.readData(
"total_counts", eventCount);
548 hasTotalCounts =
true;
558 if (oldNeXusFileNames)
559 file.openData(
"event_pixel_id");
561 file.openData(
"event_id");
565 file.openData(
"event_pixel_id");
566 oldNeXusFileNames =
true;
573 size_t numEvents =
static_cast<std::size_t
>(file.getInfo().dims[0]);
592std::shared_ptr<BankPulseTimes>
594 bool returnpulsetimes,
int &nPeriods,
599 std::shared_ptr<BankPulseTimes> out;
606 loadLogs->setPropertyValue(
"Filename", nexusfilename);
609 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
615 const Run &run = localWorkspace->run();
624 std::string status =
"";
625 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
632 std::vector<Types::Core::DateAndTime> temp;
633 if (localWorkspace->run().hasProperty(
"proton_charge")) {
639 if (returnpulsetimes)
640 out = std::make_shared<BankPulseTimes>(temp);
644 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
646 "sample log with invalid pulse time!\n";
648 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
653 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
655 localWorkspace->mutableRun().addProperty(
"run_start", run.
getProperty(
"start_time")->
value(),
true);
658 "not be able to filter by time.\n";
664 localWorkspace->mutableRun().setGoniometer(gm,
true);
665 }
catch (std::runtime_error &) {
672 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
673 "sample logs may be missing."
697 const std::string &nexusfilename, T localWorkspace,
API::Algorithm &alg,
bool returnpulsetimes,
int &nPeriods,
699 const std::vector<std::string> &block_list) {
703 std::shared_ptr<BankPulseTimes> out;
710 loadLogs->setPropertyValue(
"Filename", nexusfilename);
712 loadLogs->setProperty<std::vector<std::string>>(
"AllowList", allow_list);
713 loadLogs->setProperty<std::vector<std::string>>(
"BlockList", block_list);
716 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
722 const Run &run = localWorkspace->run();
730 std::string status =
"";
732 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
739 std::vector<Types::Core::DateAndTime> temp;
740 if (localWorkspace->run().hasProperty(
"proton_charge")) {
746 if (returnpulsetimes)
747 out = std::make_shared<BankPulseTimes>(temp);
751 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
753 "sample log with invalid pulse time!\n";
755 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
760 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
763 "not be able to filter by time.\n";
769 localWorkspace->mutableRun().setGoniometer(gm,
true);
770 }
catch (std::runtime_error &) {
777 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
778 "sample logs may be missing."
801 const int &nPeriods,
const std::string &nexusfilename,
802 std::string &status) {
803 const auto valuesAsVector = tempPeriodLog->valuesAsVector();
804 const auto nPeriodsInLog = *std::max_element(valuesAsVector.begin(), valuesAsVector.end());
805 int numberOfValidPeriods = nPeriodsInLog;
809 if (nPeriodsInLog == 0 && nPeriods == 1) {
812 const std::vector<int> newValues(tempPeriodLog->realSize(), 1);
813 const auto times = tempPeriodLog->timesAsVector();
815 numberOfValidPeriods = 1;
816 }
else if (nPeriodsInLog < nPeriods) {
819 "The number of periods specified in the file (%1%) is greater than the maximum period in the data (%2%).") %
820 nPeriods % nPeriodsInLog);
821 }
else if (nPeriodsInLog > nPeriods) {
827 const auto msg =
"File " + nexusfilename +
828 " has been corrupted. The log framelog/period_log/value "
830 std::to_string(nPeriodsInLog) +
" periods, but periods/number contains " +
831 std::to_string(nPeriods) +
". This file should be manually inspected and corrected.";
835 periodLog = std::make_unique<const TimeSeriesProperty<int>>(*tempPeriodLog);
836 tempPeriodLog.reset();
838 return numberOfValidPeriods;
856std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
859 auto ws = localWorkspace->getSingleHeldWorkspace();
860 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog);
881std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
884 const std::vector<std::string> &allow_list,
const std::vector<std::string> &block_list) {
885 auto ws = localWorkspace->getSingleHeldWorkspace();
886 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog,
887 allow_list, block_list);
907 std::vector<std::string> allow_list =
getProperty(
"AllowList");
908 std::vector<std::string> block_list =
getProperty(
"BlockList");
911 DateAndTime run_start(0, 0);
912 bool takeTimesFromEvents =
false;
916 auto periodLog = std::make_unique<const TimeSeriesProperty<int>>(
"period_log");
924 if (allow_list.empty() && block_list.empty()) {
926 runLoadNexusLogs<EventWorkspaceCollection_sptr>(
m_filename,
m_ws, *
this,
true, nPeriods, periodLog);
929 periodLog, allow_list, block_list);
933 run_start =
m_ws->getFirstPulseTime();
941 takeTimesFromEvents =
true;
950 g_log.
debug() <<
"Failed to open nexus file \"" <<
m_filename <<
"\" in read mode: " << e.what() <<
"\n";
955 <<
"Reading the start time directly from /" <<
m_top_entry_name <<
"/start_time\n";
963 m_ws->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
973 }
catch (std::runtime_error &e) {
975 g_log.
error() <<
"Error loading metadata: " << e.what() <<
'\n';
978 m_ws->setNPeriods(
static_cast<size_t>(nPeriods),
983 std::vector<DateAndTime> temp;
989 prog->
report(
"Loading instrument");
998 throw std::runtime_error(
"Instrument was not initialized correctly! Loading cannot continue.");
1004 m_file->openAddress(
"/");
1009 vector<string> bankNames;
1010 vector<std::size_t> bankNumEvents;
1011 std::string classType = monitors ?
"NXmonitor" :
"NXevent_data";
1012 bool oldNeXusFileNames(
false);
1013 bool haveWeights =
false;
1014 auto firstPulseT = DateAndTime::maximum();
1015 if (
m_file->classTypeExists(classType)) {
1016 std::map<std::string, std::string> entries =
m_file->getEntries();
1017 for (
auto entry : entries) {
1018 if (entry.second != classType) {
1023 if (entry.first ==
"bank_error_events" || entry.first ==
"bank_unmapped_events")
1026 m_file->openGroup(entry.first, classType);
1029 bool hasTotalCounts =
true;
1030 std::size_t num =
numEvents(*
m_file, hasTotalCounts, oldNeXusFileNames, prefix);
1031 bankNames.emplace_back(entry.first);
1032 bankNumEvents.emplace_back(num);
1033 if (takeTimesFromEvents && num > 0) {
1039 firstPulseT = std::min(firstPulseT, localFirstLast.first);
1042 const std::string absoluteEventWeightName = prefix +
"/event_weight";
1043 haveWeights =
m_file->hasAddress(absoluteEventWeightName);
1047 if (takeTimesFromEvents)
1048 run_start = firstPulseT;
1057 if (AnalysisDataService::Instance().doesExist(outName))
1058 AnalysisDataService::Instance().remove(outName);
1062 double filter_time_start_sec, filter_time_stop_sec;
1063 filter_time_start_sec =
getProperty(
"FilterByTimeStart");
1064 filter_time_stop_sec =
getProperty(
"FilterByTimeStop");
1073 if (filter_time_start_sec !=
EMPTY_DBL()) {
1078 if (filter_time_stop_sec !=
EMPTY_DBL()) {
1085 std::string msg =
"Your ";
1088 msg +=
"filter for time's Stop value is smaller than the Start value.";
1089 throw std::invalid_argument(msg);
1097 double min_pcharge, max_pcharge;
1098 std::tie(min_pcharge, max_pcharge, std::ignore) =
1099 m_ws->run().getBadPulseRange(LOG_CHARGE_NAME,
getProperty(PropertyNames::BAD_PULSES_CUTOFF));
1101 const auto *pcharge_log =
1104 pcharge_log->makeFilterByValue(min_pcharge, max_pcharge,
false,
TimeInterval(0, 1), 0.,
true));
1109 auto axis = HistogramData::BinEdges{1,
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1 - 1};
1111 m_ws->setAllX(axis);
1118 std::vector<std::string> someBanks =
getProperty(
"BankName");
1119 const bool SingleBankPixelsOnly =
getProperty(
"SingleBankPixelsOnly");
1120 if ((!someBanks.empty()) && (!monitors)) {
1121 std::vector<std::string> eventedBanks;
1122 eventedBanks.reserve(someBanks.size());
1123 std::transform(someBanks.cbegin(), someBanks.cend(), std::back_inserter(eventedBanks),
1124 [](
const auto &bank) { return bank +
"_events"; });
1127 const auto invalidBank =
1128 std::find_if(eventedBanks.cbegin(), eventedBanks.cend(), [&bankNames](
const auto &someBank) {
1129 return std::none_of(bankNames.cbegin(), bankNames.cend(),
1130 [&someBank](const auto &name) { return name == someBank; });
1132 if (invalidBank != eventedBanks.cend()) {
1133 throw std::invalid_argument(
"No entry named '" + *invalidBank +
"' was found in the .NXS file.");
1137 bankNames.assign(eventedBanks.cbegin(), eventedBanks.cend());
1140 bankNumEvents.assign(someBanks.size(), 1);
1142 if (!SingleBankPixelsOnly)
1146 prog->report(
"Initializing all pixels");
1149 if (m_ws->getInstrument()->hasParameter(
"remove-unused-banks")) {
1150 std::vector<double> instrumentUnused = m_ws->getInstrument()->getNumberParameter(
"remove-unused-banks",
true);
1151 if (!instrumentUnused.empty()) {
1152 const auto unused =
static_cast<int>(instrumentUnused.front());
1154 deleteBanks(m_ws, bankNames);
1158 createSpectraMapping(m_filename, monitors, someBanks);
1162 for (
size_t i = 0; i < m_ws->getNumberHistograms(); i++)
1166 shortest_tof =
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1;
1169 bool precount = getProperty(
"Precount");
1170 int chunk = getProperty(
"ChunkNumber");
1171 int totalChunks = getProperty(
"TotalChunks");
1172 const auto startTime = std::chrono::high_resolution_clock::now();
1174 classType, bankNumEvents, oldNeXusFileNames, precount, chunk, totalChunks);
1175 addTimer(
"loadEvents", startTime, std::chrono::high_resolution_clock::now());
1178 const std::size_t eventsLoaded = m_ws->getNumberEvents();
1180 <<
". Shortest TOF: " << shortest_tof <<
" microsec; longest TOF: " << longest_tof
1183 if (shortest_tof < 0)
1184 g_log.
warning() <<
"The shortest TOF was negative! At least 1 event has an "
1185 "invalid time-of-flight.\n";
1188 <<
" events with TOF > 2e8. This "
1189 "may indicate errors in the raw "
1193 if (m_ws->getInstrument()->hasParameter(
"T0")) {
1194 std::vector<double> instrumentT0 = m_ws->getInstrument()->getNumberParameter(
"T0",
true);
1195 if (!instrumentT0.empty()) {
1196 const double mT0 = instrumentT0.front();
1198 auto numHistograms =
static_cast<int64_t
>(m_ws->getNumberHistograms());
1200 for (int64_t i = 0; i < numHistograms; ++i) {
1203 m_ws->getSpectrum(i).addTof(mT0);
1208 API::Run &run = m_ws->mutableRun();
1209 run.addProperty<
double>(
"T0", mT0,
true);
1214 if (eventsLoaded > 0) {
1215 int nBins = getProperty(
"NumberOfBins");
1216 auto binEdgesVec = std::vector<double>(nBins + 1);
1217 binEdgesVec[0] = shortest_tof;
1218 binEdgesVec[nBins] = longest_tof + 1;
1219 double binStep = (binEdgesVec[nBins] - binEdgesVec[0]) / nBins;
1220 for (
int binIndex = 1; binIndex < nBins; binIndex++) {
1221 binEdgesVec[binIndex] = binEdgesVec[0] + (binStep * binIndex);
1223 m_ws->setAllX(HistogramData::BinEdges{binEdgesVec});
1225 m_ws->setAllX(HistogramData::BinEdges{0.0, 1.0});
1232 if (m_is_time_filtered) {
1235 TimeROI timeroi(filter_time_start, filter_time_stop);
1236 if (filter_bad_pulses)
1237 timeroi.update_intersection(*bad_pulses_timeroi);
1238 m_ws->mutableRun().setTimeROI(timeroi);
1239 m_ws->mutableRun().removeDataOutsideTimeROI();
1240 }
else if (filter_bad_pulses) {
1241 m_ws->mutableRun().setTimeROI(*bad_pulses_timeroi);
1242 m_ws->mutableRun().removeDataOutsideTimeROI();
1258bool LoadEventNexus::runLoadIDFFromNexus<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1260 const std::string &top_entry_name,
1262 auto ws = localWorkspace->getSingleHeldWorkspace();
1263 auto hasLoaded = runLoadIDFFromNexus<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg);
1264 localWorkspace->setInstrument(ws->getInstrument());
1273 std::string instrumentName;
1275 hFile.openGroup(
"isis_vms_compat",
"IXvms");
1276 }
catch (std::runtime_error &) {
1277 return instrumentName;
1280 hFile.openData(
"NAME");
1281 }
catch (std::runtime_error &) {
1283 return instrumentName;
1286 instrumentName = hFile.getStrData();
1290 return instrumentName;
1307bool LoadEventNexus::runLoadInstrument<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1309 const std::string &top_entry_name,
Algorithm *alg,
1311 auto ws = localWorkspace->getSingleHeldWorkspace();
1312 auto hasLoaded = runLoadInstrument<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg, descriptor);
1313 localWorkspace->setInstrument(ws->getInstrument());
1324 const std::vector<std::string> &bankNames) {
1327 std::vector<std::shared_ptr<RectangularDetector>> detList;
1328 for (
int i = 0; i < inst->nelements(); i++) {
1329 std::shared_ptr<RectangularDetector> det;
1330 std::shared_ptr<ICompAssembly> assem;
1331 std::shared_ptr<ICompAssembly> assem2;
1333 det = std::dynamic_pointer_cast<RectangularDetector>((*inst)[i]);
1335 detList.emplace_back(det);
1340 assem = std::dynamic_pointer_cast<ICompAssembly>((*inst)[i]);
1342 for (
int j = 0; j < assem->nelements(); j++) {
1343 det = std::dynamic_pointer_cast<RectangularDetector>((*assem)[j]);
1345 detList.emplace_back(det);
1351 assem2 = std::dynamic_pointer_cast<ICompAssembly>((*assem)[j]);
1353 for (
int k = 0; k < assem2->nelements(); k++) {
1354 det = std::dynamic_pointer_cast<RectangularDetector>((*assem2)[k]);
1356 detList.emplace_back(det);
1365 if (detList.empty())
1367 for (
auto &det : detList) {
1369 std::string det_name = det->getName();
1370 for (
const auto &bankName : bankNames) {
1371 size_t pos = bankName.find(
"_events");
1372 if (det_name == bankName.substr(0, pos))
1378 std::shared_ptr<const IComponent> parent = inst->getComponentByName(det_name);
1379 std::vector<Geometry::IComponent_const_sptr> children;
1380 std::shared_ptr<const Geometry::ICompAssembly> asmb =
1381 std::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
1382 asmb->getChildren(children,
false);
1383 for (
auto &col : children) {
1384 std::shared_ptr<const Geometry::ICompAssembly> asmb2 =
1385 std::dynamic_pointer_cast<const Geometry::ICompAssembly>(col);
1386 std::vector<Geometry::IComponent_const_sptr> grandchildren;
1387 asmb2->getChildren(grandchildren,
false);
1389 for (
auto &row : grandchildren) {
1392 inst->removeDetector(
d);
1395 auto *comp =
dynamic_cast<IComponent *
>(det.get());
1410 const std::vector<std::string> &bankNames) {
1413 if (!monitorsOnly && !bankNames.empty()) {
1415 g_log.
warning() <<
"Spectrum min/max/list selection ignored when "
1416 "`SingleBankPixelsOnly` is enabled\n";
1418 g_log.
debug() <<
"Populated spectra map for select banks\n";
1421 g_log.
debug() <<
"Loading only monitor spectra from " << nxsfile <<
"\n";
1423 g_log.
debug() <<
"Loading only detector spectra from " << nxsfile <<
"\n";
1427 g_log.
debug() <<
"No custom spectra mapping found, continuing with default "
1428 "1:1 mapping of spectrum:detectorID\n";
1430 g_log.
debug() <<
"Populated 1:1 spectra map for the whole instrument \n";
1442 std::string mon_wsname = this->
getProperty(
"OutputWorkspace");
1443 mon_wsname.append(
"_monitors");
1447 loadMonitors->setPropertyValue(
"Filename",
m_filename);
1448 g_log.
information() <<
"New workspace name for monitors: " << mon_wsname <<
'\n';
1449 loadMonitors->setPropertyValue(
"OutputWorkspace", mon_wsname);
1450 loadMonitors->setPropertyValue(
"LoadOnly", this->
getProperty(
"MonitorsLoadOnly"));
1451 loadMonitors->setPropertyValue(
"NXentryName", this->
getProperty(
"NXentryName"));
1452 loadMonitors->execute();
1453 Workspace_sptr monsOut = loadMonitors->getProperty(
"OutputWorkspace");
1457 "Monitors from the Event NeXus file");
1464 m_ws->setMonitorWorkspace(mons);
1471 for (
int i = 0; i < monsGrp->getNumberOfEntries(); i++) {
1472 std::stringstream ssWsName;
1473 ssWsName << mon_wsname <<
"_" << i + 1;
1474 std::stringstream ssPropName;
1475 ssPropName <<
"MonitorWorkspace"
1479 "Monitors from the Event NeXus file");
1480 this->
setProperty(ssPropName.str(), monsGrp->getItem(i));
1496std::unique_ptr<std::pair<std::vector<int32_t>, std::vector<int32_t>>>
1498 const std::string vms_str =
"/isis_vms_compat";
1500 g_log.
debug() <<
"Attempting to load custom spectra mapping from '" << entry_name << vms_str <<
"'.\n";
1501 m_file->openAddress(
"/" + entry_name + vms_str);
1524 m_file->openData(
"UDET");
1525 std::vector<int32_t> udet;
1529 m_file->openData(
"SPEC");
1530 std::vector<int32_t> spec;
1541 const size_t ndets(udet.size());
1542 if (ndets != spec.size()) {
1543 std::ostringstream os;
1544 os <<
"UDET/SPEC list size mismatch. UDET=" << udet.size() <<
", SPEC=" << spec.size() <<
"\n";
1545 throw std::runtime_error(os.str());
1549 return std::make_unique<std::pair<std::vector<int32_t>, std::vector<int32_t>>>(std::move(spec), std::move(udet));
1559 std::string prefix(
"Filter");
1572 std::string msg(
"You must specify both min & max or neither TOF filters");
1574 msg =
" for the monitors.";
1575 throw std::invalid_argument(msg);
1597 file.openGroup(
"isis_vms_compat",
"IXvms");
1605 std::vector<int32_t> spb;
1606 std::vector<float> rspb;
1607 file.readData(
"SPB", spb);
1608 file.readData(
"RSPB", rspb);
1616 std::stringstream s;
1617 s <<
"Wrong definition found in isis_vms_compat :> " << ex.what();
1619 throw std::runtime_error(s.str());
1634 }
catch (std::runtime_error &e) {
1635 throw std::runtime_error(
"Severe failure when trying to open NeXus file: " + std::string(e.what()));
1639 throw std::runtime_error(
"An unexpected failure happened, unable to "
1640 "initialize file object when trying to open NeXus "
IPeaksWorkspace_sptr workspace
#define PARALLEL_START_INTERRUPT_REGION
Begins a block to skip processing is the algorithm has been interupted Note the end of the block if n...
#define PARALLEL_END_INTERRUPT_REGION
Ends a block to skip processing is the algorithm has been interupted Note the start of the block if n...
#define PARALLEL_FOR_IF(condition)
Empty definitions - to enable set your complier to enable openMP.
#define PARALLEL_CHECK_INTERRUPT_REGION
Adds a check after a Parallel region to see if it was interupted.
#define DECLARE_NEXUS_LAZY_FILELOADER_ALGORITHM(classname)
DECLARE_NEXUS_LAZY_FILELOADER_ALGORITHM should be used in place of the standard DECLARE_ALGORITHM mac...
Base class from which all concrete algorithm classes should be derived.
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.
bool isDefault(const std::string &name) const
Kernel::Logger & getLogger() const
Returns a reference to the logger.
@ Load
allowed here which will be passed to the algorithm
bool hasProperty(const std::string &name) const
Does the property exist on the object.
Kernel::Property * getProperty(const std::string &name) const
Returns the named property as a pointer.
HeldType getPropertyValueAsType(const std::string &name) const
Get the value of a property as the given TYPE.
Helper class for reporting progress from algorithms.
void doReport(const std::string &msg="") override
Actually do the reporting, without changing the loop counter.
This class stores information regarding an experimental run as a series of log entries.
A property class for workspaces.
static void load(LoadEventNexus *alg, EventWorkspaceCollection &ws, bool haveWeights, bool event_id_is_spec, std::vector< std::string > bankNames, const std::vector< int > &periodLog, const std::string &classType, std::vector< std::size_t > bankNumEvents, const bool oldNeXusFileNames, const bool precount, const int chunk, const int totalChunks)
EventWorkspaceCollection : Collection of EventWorspaces to give backward-forward compatibility around...
void setGeometryFlag(const int flag)
void setWidth(const float flag)
void setHeight(const float flag)
void setThickness(const float flag)
Custom exception extending std::invalid_argument Thrown when nperiods does not match period_log Custo...
Helper for LoadEventNexus dealing with setting up indices (spectrum numbers an detector ID mapping) f...
Indexing::IndexInfo makeIndexInfo()
std::pair< int32_t, int32_t > eventIDLimits() const
bool m_is_time_filtered
if wall-clock filtering was requested
static int checkForCorruptedPeriods(std::unique_ptr< Kernel::TimeSeriesProperty< int > > tempPeriodLog, std::unique_ptr< const Kernel::TimeSeriesProperty< int > > &periodLog, const int &nPeriods, const std::string &nexusfilename, std::string &status)
Check for corrupted period logs If data is historical (1 periods, period is labelled 0) then change p...
std::shared_ptr< Mantid::Kernel::TimeROI > bad_pulses_timeroi
void createSpectraMapping(const std::string &nxsfile, const bool monitorsOnly, const std::vector< std::string > &bankNames=std::vector< std::string >())
Create the required spectra mapping.
static void loadSampleDataISIScompatibility(Nexus::File &file, EventWorkspaceCollection &WS)
Load information of the sample.
Mantid::Types::Core::DateAndTime filter_time_start
Filter by start time.
double filter_tof_max
Filter by a maximum time-of-flight.
void safeOpenFile(const std::string &fname)
to open the nexus file with specific exception handling/message
bool loadlogs
Do we load the sample logs?
bool event_id_is_spec
True if the event_id is spectrum no not pixel ID.
size_t discarded_events
A count of events discarded because they came from a pixel that's not in the IDF.
T filterEventsByTime(T workspace, Mantid::Types::Core::DateAndTime &startTime, Mantid::Types::Core::DateAndTime &stopTime)
Filter the events by pulse time - no in place version so have to return workspace.
std::map< std::string, std::string > validateInputs() override
Perform validation of ALL the input properties of the algorithm.
Mantid::Types::Core::DateAndTime filter_time_stop
Filter by stop time.
void init() override
Intialisation code.
int32_t m_specMax
Maximum spectrum to load.
void exec() override
Execution code.
void deleteBanks(const EventWorkspaceCollection_sptr &workspace, const std::vector< std::string > &bankNames)
Deletes banks for a workspace given the bank names.
double compressTolerance
Tolerance for CompressEvents; use -1 to mean don't compress.
std::string m_filename
The name and path of the input file.
std::shared_ptr< BankPulseTimes > m_allBanksPulseTimes
Pulse times for ALL banks, taken from proton_charge log.
static std::shared_ptr< BankPulseTimes > runLoadNexusLogs(const std::string &nexusfilename, T localWorkspace, Algorithm &alg, bool returnpulsetimes, int &nPeriods, std::unique_ptr< const Kernel::TimeSeriesProperty< int > > &periodLog)
Load the log from the nexus file.
static bool loadInstrument(const std::string &nexusfilename, T localWorkspace, const std::string &top_entry_name, Algorithm *alg, const Nexus::NexusDescriptor *descriptor=nullptr)
Load instrument from Nexus file if possible, else from IDF spacified by Nexus file.
int confidence(Nexus::NexusDescriptorLazy &descriptor) const override
Return the confidence with with this algorithm can load the file.
void runLoadMonitors()
Load the Monitors from the NeXus file into a workspace.
void filterDuringPause(T workspace)
std::unique_ptr< std::pair< std::vector< int32_t >, std::vector< int32_t > > > loadISISVMSSpectraMapping(const std::string &entry_name)
Load a spectra mapping from the given file.
bool filter_tof_range
Tof range is being filtered.
static std::string readInstrumentFromISIS_VMSCompat(Nexus::File &hFile)
method used to return instrument name for some old ISIS files where it is not written properly within...
std::unique_ptr< Nexus::File > m_file
std::shared_ptr< EventWorkspaceCollection > m_ws
The workspace being filled out.
void loadEvents(API::Progress *const prog, const bool monitors)
Load events from the file.
LoadEventNexus()
Empty default constructor.
bool m_instrument_loaded_correctly
Was the instrument loaded?
size_t bad_tofs
Count of all the "bad" tofs found.
int32_t m_specMin
Minimum spectrum to load.
void setTopEntryName()
Set the top entry field name.
double filter_tof_min
Filter by a minimum time-of-flight.
std::string m_top_entry_name
name of top level NXentry to use
void setTimeFilters(const bool monitors)
Set the filters on TOF.
This class represents a detector - i.e.
Class to represent a particular goniometer setting, which is described by the rotation matrix.
void makeUniversalGoniometer()
Make a default universal goniometer with phi,chi,omega angles according to SNS convention.
base class for Geometric IComponent
Support for a property that holds an array of values.
Exception for when an item is not found in a collection.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void setPropertySettings(const std::string &name, std::unique_ptr< IPropertySettings const > settings)
Add a PropertySettings instance to the chain of settings for a given property.
void setPropertyGroup(const std::string &name, const std::string &group)
Set the group for a given property.
The Logger class is in charge of the publishing messages from the framework through various channels.
void debug(const std::string &msg)
Logs at debug level.
void notice(const std::string &msg)
Logs at notice level.
void error(const std::string &msg)
Logs at error level.
void warning(const std::string &msg)
Logs at warning level.
void information(const std::string &msg)
Logs at information level.
void report()
Increments the loop counter by 1, then sends the progress notification on behalf of its algorithm.
The concrete, templated class for properties.
virtual std::string value() const =0
Returns the value of the property as a string.
Represents a time interval.
A specialised Property class for holding a series of time-value pairs.
std::vector< Types::Core::DateAndTime > timesAsVector() const override
Return the time series's times as a vector<DateAndTime>
Class that provides for a standard Nexus exception.
bool isEntry(std::string const &entryName, std::string const &groupClass) const
Checks if a full-address entry exists for a particular groupClass in a Nexus dataset.
bool classTypeExists(std::string const &classType) const
Query if a given type exists somewhere in the file.
static unsigned short constexpr UINT64
std::shared_ptr< WorkspaceGroup > WorkspaceGroup_sptr
shared pointer to Mantid::API::WorkspaceGroup
std::shared_ptr< Workspace > Workspace_sptr
shared pointer to Mantid::API::Workspace
Kernel::Logger g_log("ExperimentInfo")
static logger object
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
void addNexusFieldsToWsRun(Nexus::File &filehandle, API::Run &runDetails, const std::string &entryName="", bool useFullAddress=false)
Add properties from a nexus file to the workspace run.
std::size_t numEvents(Nexus::File &file, bool &hasTotalCounts, bool &oldNeXusFileNames, const std::string &prefix)
Get the number of events in the currently opened group.
std::shared_ptr< EventWorkspaceCollection > EventWorkspaceCollection_sptr
std::pair< DateAndTime, DateAndTime > firstLastPulseTimes(Nexus::File &file, Kernel::Logger &logger)
void adjustTimeOfFlightISISLegacy(Nexus::File &file, T localWorkspace, const std::string &entry_name, const std::string &classType)
ISIS specific method for dealing with wide events.
MANTID_DATAHANDLING_DLL bool doPerformISISEventShift(Nexus::File &file, std::string &topEntryName)
std::shared_ptr< Instrument > Instrument_sptr
Shared pointer to an instrument object.
MANTID_KERNEL_DLL Types::Core::DateAndTime createFromSanitizedISO8601(const std::string &date)
Creates a DateAndTime object from a date string even if the string does not exactly conform to ISO860...
MANTID_KERNEL_DLL double timeConversionValue(const std::string &input_unit, const std::string &output_unit)
std::enable_if< std::is_pointer< Arg >::value, bool >::type threadSafe(Arg workspace)
Thread-safety check Checks the workspace to ensure it is suitable for multithreaded access.
const std::string BINMODE("BinningMode")
constexpr int EMPTY_INT() noexcept
Returns what we consider an "empty" integer within a property.
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)
@ Input
An input workspace.
@ Output
An output workspace.