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");
79 : filter_tof_min(0), filter_tof_max(0), m_specMin(0), m_specMax(0), longest_tof(0), shortest_tof(0), bad_tofs(0),
80 discarded_events(0), compressEvents(false), m_instrument_loaded_correctly(false), loadlogs(false),
81 event_id_is_spec(false) {
95 const std::map<std::string, std::set<std::string>> &allEntries = descriptor.
getAllEntries();
96 if (allEntries.count(
"NXevent_data") == 1) {
97 if (descriptor.
isEntry(
"/entry",
"NXentry") || descriptor.
isEntry(
"/raw_data_1",
"NXentry")) {
109 const std::vector<std::string> exts{
".nxs.h5",
".nxs",
"_event.nxs"};
111 "The name of the Event NeXus file to read, including its full or "
113 "The file name is typically of the form INST_####_event.nxs (N.B. case "
114 "sensitive if running on Linux).");
117 "The name of the output EventWorkspace or WorkspaceGroup in which to "
118 "load the EventNexus file.");
121 "Optional: Name of the NXentry to load if it's not the default.");
124 "Optional: To exclude events that do not fall within a range "
125 "of times-of-flight. "
126 "This is the minimum accepted value in microseconds. Keep "
127 "blank to load all events.");
130 "Optional: To exclude events that do not fall within a range "
131 "of times-of-flight. "
132 "This is the maximum accepted value in microseconds. Keep "
133 "blank to load all events.");
136 "Optional: To only include events after the provided start "
137 "time, in seconds (relative to the start of the run).");
140 "Optional: To only include events before the provided stop "
141 "time, in seconds (relative to the start of the run).");
145 "Optional: To filter bad pulses set the Lower Cutoff percentage to use.");
147 std::string grp1 =
"Filter Events";
155 "Optional: To only include events from one bank. Any bank "
156 "whose name does not match the given string will have no "
160 "Optional: Only applies if you specified a single bank to "
161 "load with BankName. "
162 "Only pixels in the specified bank will be created if true; "
163 "all of the instrument's pixels will be created otherwise.");
166 std::string grp2 =
"Loading a Single Bank";
171 "Pre-count the number of events in each pixel before allocating memory "
172 "(optional, default True). "
173 "This can significantly reduce memory use and memory fragmentation; it "
174 "may also speed up loading.");
178 "CompressEvents while loading (optional, default: off). "
179 "This specified the tolerance to use (in microseconds) when compressing where positive is linear tolerance, "
180 "negative is logorithmic tolerance, and zero indicates that time-of-flight must be identical to compress.");
182 PropertyNames::COMPRESS_MODE, binningModeNames[
size_t(BinningMode::DEFAULT)],
183 std::make_shared<Mantid::Kernel::StringListValidator>(binningModeNames),
185 "Binning behavior can be specified in the usual way through sign of binwidth and other properties ('Default'); "
186 "or can be set to one of the allowed binning modes. "
187 "This will override all other specification or default behavior.");
189 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
190 mustBePositive->setLower(1);
192 "If loading the file by sections ('chunks'), this is the "
193 "section number of this execution of the algorithm.");
195 "If loading the file by sections ('chunks'), this is the "
196 "total number of sections.");
202 std::string grp3 =
"Reduce Memory Use";
210 "Load the monitors from the file (optional, default False).");
212 std::vector<std::string> options{
"",
"Events",
"Histogram"};
213 declareProperty(
"MonitorsLoadOnly",
"", std::make_shared<Kernel::StringListValidator>(options),
214 "If multiple repesentations exist, which one to load. "
215 "Default is to load the one that is present.");
218 "Optional: To exclude events from monitors that do not fall "
219 "within a range of times-of-flight. "
220 "This is the minimum accepted value in microseconds.");
223 "Optional: To exclude events from monitors that do not fall "
224 "within a range of times-of-flight. "
225 "This is the maximum accepted value in microseconds.");
228 "Optional: To only include events from monitors after the "
229 "provided start time, in seconds (relative to the start of "
233 "Optional: To only include events from monitors before the "
234 "provided stop time, in seconds (relative to the start of "
238 auto asEventsIsOn = [] {
239 std::unique_ptr<IPropertySettings> prop = std::make_unique<VisibleWhenProperty>(
"LoadMonitors",
IS_EQUAL_TO,
"1");
247 std::string grp4 =
"Monitors";
258 "A comma-separated list of individual spectra to read.");
261 "If true, only the meta data and sample logs will be loaded.");
264 "Load only the Sample/DAS logs from the file (default True).");
267 "Load all the logs from the nxs, without checking or processing them; if checked, LoadLogs will be "
268 "ignored; use with caution");
270 std::vector<std::string> loadType{
"Default",
"Multiprocess (experimental)"};
271 auto loadTypeValidator = std::make_shared<StringListValidator>(loadType);
273 "LoadType",
"Default", loadTypeValidator,
274 "Deprecated feature. This option has no effect on algorithm behavior and will be removed in a future release.");
277 "Reads the embedded Instrument XML from the NeXus file "
278 "(optional, default True). ");
281 "The number of bins intially defined. Use Rebin to change "
282 "the binning later. If there is no data loaded, or you "
283 "select meta data only you will only get 1 bin.");
288 "If specified, only these logs will be loaded from the file (each "
289 "separated by a space).");
292 "If specified, these logs will NOT be loaded from the file (each "
293 "separated by a space).");
300 g_log.
warning() <<
"The experimental multiprocess loader has been discontinued. The default loader will be used "
301 "instead. Please remove use of this property from all scripts.";
305 std::map<std::string, std::string> result;
307 if (!
isDefault(PropertyNames::BAD_PULSES_CUTOFF)) {
308 const double cutoff =
getProperty(PropertyNames::BAD_PULSES_CUTOFF);
309 if (cutoff < 0 || cutoff > 100)
310 result[PropertyNames::BAD_PULSES_CUTOFF] =
"Must be empty or between 0 and 100";
320 std::string nxentryProperty =
getProperty(
"NXentryName");
321 if (!nxentryProperty.empty()) {
326 std::string firstGoodEntry(
"");
327 std::set<std::string> goodEntries{
"entry",
"raw_data_1"};
328 auto allEntries =
m_file->getEntries();
329 for (std::string goodEntry : goodEntries) {
330 if (allEntries.count(goodEntry) != 0 && allEntries[goodEntry] !=
"SDS") {
331 firstGoodEntry = std::move(goodEntry);
337 g_log.
error() <<
"Unable to determine name of top level NXentry - assuming \"entry\".\n";
344 if ((!ConfigService::Instance().hasProperty(
"loadeventnexus.keeppausedevents")) &&
345 (
m_ws->run().getLogData(
"pause")->size() > 1)) {
346 g_log.
notice(
"Filtering out events when the run was marked as paused. "
347 "Set the loadeventnexus.keeppausedevents configuration "
348 "property to override this.");
351 filter->setProperty(
"InputWorkspace",
workspace);
352 filter->setProperty(
"OutputWorkspace",
workspace);
353 filter->setProperty(
"LogName",
"pause");
355 filter->setProperty(
"MinimumValue", 0.0);
356 filter->setProperty(
"MaximumValue", 0.0);
357 filter->setProperty(
"LogBoundary",
"Left");
368 using std::placeholders::_1;
369 auto func = std::bind(&LoadEventNexus::filterDuringPause<MatrixWorkspace_sptr>,
this, _1);
380 Mantid::Types::Core::DateAndTime &stopTime) {
383 filterByTime->setProperty(
"InputWorkspace",
workspace);
385 filterByTime->setProperty(
"AbsoluteStartTime", startTime.toISO8601String());
386 filterByTime->setProperty(
"AbsoluteStopTime", stopTime.toISO8601String());
387 filterByTime->execute();
388 return filterByTime->getProperty(
"OutputWorkspace");
394 Mantid::Types::Core::DateAndTime &startTime,
395 Mantid::Types::Core::DateAndTime &stopTime) {
397 using std::placeholders::_1;
398 auto func = std::bind(&LoadEventNexus::filterEventsByTime<EventWorkspace_sptr>,
this, _1, startTime, stopTime);
415 if (mode == BinningMode::LINEAR)
417 else if (mode == BinningMode::LOGARITHMIC)
424 bool load_monitors = this->
getProperty(
"LoadMonitors");
436 Progress prog(
this, 0.0, 0.3, reports);
439 m_ws = std::make_shared<EventWorkspaceCollection>();
447 <<
" events were encountered coming from pixels which "
448 "are not in the Instrument Definition File."
449 "These events were discarded.\n";
467 prog.
report(
"Loading monitors");
473 file.openData(
"event_time_zero");
478 if (!file.hasAttr(
"offset")) {
479 offset = DateAndTime(
"1970-01-01T00:00:00Z");
480 logger.
warning(
"In firstLastPulseTimes: no ISO8601 offset attribute "
481 "provided for event_time_zero, using UNIX epoch instead");
483 std::string isooffset;
484 file.getAttr(
"offset", isooffset);
485 offset = DateAndTime(isooffset);
488 if (file.hasAttr(
"units"))
489 file.getAttr(
"units", units);
491 auto pulse_times = Nexus::IOHelper::readNexusVector<double>(file,
"event_time_zero");
494 if (pulse_times.empty()) {
495 throw std::invalid_argument(
"Cannot find run start; event_time_zero contains no pulse times");
499 return std::make_pair(DateAndTime(pulse_times.front() * conv, 0.0) + offset.totalNanoseconds(),
500 DateAndTime(pulse_times.back() * conv, 0.0) + offset.totalNanoseconds());
515std::size_t
numEvents(Nexus::File &file,
bool &hasTotalCounts,
bool &oldNeXusFileNames,
const std::string &prefix,
518 if (hasTotalCounts) {
519 hasTotalCounts =
false;
520 if (descriptor.
isEntry(prefix +
"/total_counts")) {
522 file.openData(
"total_counts");
523 auto info = file.getInfo();
527 file.readData(
"total_counts", eventCount);
528 hasTotalCounts =
true;
538 if (oldNeXusFileNames)
539 file.openData(
"event_pixel_id");
541 file.openData(
"event_id");
545 file.openData(
"event_pixel_id");
546 oldNeXusFileNames =
true;
553 size_t numEvents =
static_cast<std::size_t
>(file.getInfo().dims[0]);
572std::shared_ptr<BankPulseTimes>
574 bool returnpulsetimes,
int &nPeriods,
579 std::shared_ptr<BankPulseTimes> out;
586 loadLogs->setPropertyValue(
"Filename", nexusfilename);
589 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
595 const Run &run = localWorkspace->run();
604 std::string status =
"";
605 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
612 std::vector<Types::Core::DateAndTime> temp;
613 if (localWorkspace->run().hasProperty(
"proton_charge")) {
619 if (returnpulsetimes)
620 out = std::make_shared<BankPulseTimes>(temp);
624 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
626 "sample log with invalid pulse time!\n";
628 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
633 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
635 localWorkspace->mutableRun().addProperty(
"run_start", run.
getProperty(
"start_time")->
value(),
true);
638 "not be able to filter by time.\n";
644 localWorkspace->mutableRun().setGoniometer(gm,
true);
645 }
catch (std::runtime_error &) {
652 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
653 "sample logs may be missing."
677 const std::string &nexusfilename, T localWorkspace,
API::Algorithm &alg,
bool returnpulsetimes,
int &nPeriods,
679 const std::vector<std::string> &block_list) {
683 std::shared_ptr<BankPulseTimes> out;
690 loadLogs->setPropertyValue(
"Filename", nexusfilename);
692 loadLogs->setProperty<std::vector<std::string>>(
"AllowList", allow_list);
693 loadLogs->setProperty<std::vector<std::string>>(
"BlockList", block_list);
696 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
702 const Run &run = localWorkspace->run();
710 std::string status =
"";
712 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
719 std::vector<Types::Core::DateAndTime> temp;
720 if (localWorkspace->run().hasProperty(
"proton_charge")) {
726 if (returnpulsetimes)
727 out = std::make_shared<BankPulseTimes>(temp);
731 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
733 "sample log with invalid pulse time!\n";
735 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
740 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
743 "not be able to filter by time.\n";
749 localWorkspace->mutableRun().setGoniometer(gm,
true);
750 }
catch (std::runtime_error &) {
757 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
758 "sample logs may be missing."
781 const int &nPeriods,
const std::string &nexusfilename,
782 std::string &status) {
783 const auto valuesAsVector = tempPeriodLog->valuesAsVector();
784 const auto nPeriodsInLog = *std::max_element(valuesAsVector.begin(), valuesAsVector.end());
785 int numberOfValidPeriods = nPeriodsInLog;
789 if (nPeriodsInLog == 0 && nPeriods == 1) {
792 const std::vector<int> newValues(tempPeriodLog->realSize(), 1);
793 const auto times = tempPeriodLog->timesAsVector();
795 numberOfValidPeriods = 1;
796 }
else if (nPeriodsInLog < nPeriods) {
799 "The number of periods specified in the file (%1%) is greater than the maximum period in the data (%2%).") %
800 nPeriods % nPeriodsInLog);
801 }
else if (nPeriodsInLog > nPeriods) {
807 const auto msg =
"File " + nexusfilename +
808 " has been corrupted. The log framelog/period_log/value "
810 std::to_string(nPeriodsInLog) +
" periods, but periods/number contains " +
811 std::to_string(nPeriods) +
". This file should be manually inspected and corrected.";
815 periodLog = std::make_unique<const TimeSeriesProperty<int>>(*tempPeriodLog);
816 tempPeriodLog.reset();
818 return numberOfValidPeriods;
836std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
839 auto ws = localWorkspace->getSingleHeldWorkspace();
840 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog);
861std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
864 const std::vector<std::string> &allow_list,
const std::vector<std::string> &block_list) {
865 auto ws = localWorkspace->getSingleHeldWorkspace();
866 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog,
867 allow_list, block_list);
887 std::vector<std::string> allow_list =
getProperty(
"AllowList");
888 std::vector<std::string> block_list =
getProperty(
"BlockList");
891 DateAndTime run_start(0, 0);
892 bool takeTimesFromEvents =
false;
896 auto periodLog = std::make_unique<const TimeSeriesProperty<int>>(
"period_log");
904 if (allow_list.empty() && block_list.empty()) {
906 runLoadNexusLogs<EventWorkspaceCollection_sptr>(
m_filename,
m_ws, *
this,
true, nPeriods, periodLog);
909 periodLog, allow_list, block_list);
913 run_start =
m_ws->getFirstPulseTime();
921 takeTimesFromEvents =
true;
930 g_log.
debug() <<
"Failed to open nexus file \"" <<
m_filename <<
"\" in read mode: " << e.what() <<
"\n";
935 <<
"Reading the start time directly from /" <<
m_top_entry_name <<
"/start_time\n";
943 m_ws->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
946 const std::shared_ptr<Nexus::NexusDescriptor> descriptor =
getFileInfo();
953 }
catch (std::runtime_error &e) {
955 g_log.
error() <<
"Error loading metadata: " << e.what() <<
'\n';
958 m_ws->setNPeriods(
static_cast<size_t>(nPeriods),
963 std::vector<DateAndTime> temp;
969 prog->
report(
"Loading instrument");
978 throw std::runtime_error(
"Instrument was not initialized correctly! Loading cannot continue.");
989 vector<string> bankNames;
990 vector<std::size_t> bankNumEvents;
991 std::string classType = monitors ?
"NXmonitor" :
"NXevent_data";
992 bool oldNeXusFileNames(
false);
993 bool haveWeights =
false;
994 auto firstPulseT = DateAndTime::maximum();
996 const std::map<std::string, std::set<std::string>> &allEntries = descriptor->getAllEntries();
998 auto itClassEntries = allEntries.find(classType);
1000 if (itClassEntries != allEntries.end()) {
1002 const std::set<std::string> &classEntries = itClassEntries->second;
1006 for (
const std::string &classEntry : classEntries) {
1008 if (std::regex_match(classEntry, groups, classRegex)) {
1009 const std::string entry_name(groups[2].str());
1012 if (entry_name ==
"bank_error_events" || entry_name ==
"bank_unmapped_events")
1015 m_file->openGroup(entry_name, classType);
1019 bool hasTotalCounts =
true;
1020 std::size_t num =
numEvents(*
m_file, hasTotalCounts, oldNeXusFileNames, prefix, *descriptor);
1021 bankNames.emplace_back(entry_name);
1022 bankNumEvents.emplace_back(num);
1024 if (takeTimesFromEvents && num > 0) {
1030 firstPulseT = std::min(firstPulseT, localFirstLast.first);
1034 const std::string absoluteEventWeightName = prefix +
"/event_weight";
1035 haveWeights = descriptor->isEntry(absoluteEventWeightName);
1041 if (takeTimesFromEvents)
1042 run_start = firstPulseT;
1051 if (AnalysisDataService::Instance().doesExist(outName))
1052 AnalysisDataService::Instance().remove(outName);
1056 double filter_time_start_sec, filter_time_stop_sec;
1057 filter_time_start_sec =
getProperty(
"FilterByTimeStart");
1058 filter_time_stop_sec =
getProperty(
"FilterByTimeStop");
1067 if (filter_time_start_sec !=
EMPTY_DBL()) {
1072 if (filter_time_stop_sec !=
EMPTY_DBL()) {
1079 std::string msg =
"Your ";
1082 msg +=
"filter for time's Stop value is smaller than the Start value.";
1083 throw std::invalid_argument(msg);
1091 double min_pcharge, max_pcharge;
1092 std::tie(min_pcharge, max_pcharge, std::ignore) =
1093 m_ws->run().getBadPulseRange(LOG_CHARGE_NAME,
getProperty(PropertyNames::BAD_PULSES_CUTOFF));
1095 const auto *pcharge_log =
1098 pcharge_log->makeFilterByValue(min_pcharge, max_pcharge,
false,
TimeInterval(0, 1), 0.,
true));
1103 auto axis = HistogramData::BinEdges{1,
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1 - 1};
1105 m_ws->setAllX(axis);
1112 std::vector<std::string> someBanks =
getProperty(
"BankName");
1113 const bool SingleBankPixelsOnly =
getProperty(
"SingleBankPixelsOnly");
1114 if ((!someBanks.empty()) && (!monitors)) {
1115 std::vector<std::string> eventedBanks;
1116 eventedBanks.reserve(someBanks.size());
1117 std::transform(someBanks.cbegin(), someBanks.cend(), std::back_inserter(eventedBanks),
1118 [](
const auto &bank) { return bank +
"_events"; });
1121 const auto invalidBank =
1122 std::find_if(eventedBanks.cbegin(), eventedBanks.cend(), [&bankNames](
const auto &someBank) {
1123 return std::none_of(bankNames.cbegin(), bankNames.cend(),
1124 [&someBank](const auto &name) { return name == someBank; });
1126 if (invalidBank != eventedBanks.cend()) {
1127 throw std::invalid_argument(
"No entry named '" + *invalidBank +
"' was found in the .NXS file.");
1131 bankNames.assign(eventedBanks.cbegin(), eventedBanks.cend());
1134 bankNumEvents.assign(someBanks.size(), 1);
1136 if (!SingleBankPixelsOnly)
1140 prog->report(
"Initializing all pixels");
1143 if (m_ws->getInstrument()->hasParameter(
"remove-unused-banks")) {
1144 std::vector<double> instrumentUnused = m_ws->getInstrument()->getNumberParameter(
"remove-unused-banks",
true);
1145 if (!instrumentUnused.empty()) {
1146 const auto unused =
static_cast<int>(instrumentUnused.front());
1148 deleteBanks(m_ws, bankNames);
1152 createSpectraMapping(m_filename, monitors, someBanks);
1156 for (
size_t i = 0; i < m_ws->getNumberHistograms(); i++)
1160 shortest_tof =
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1;
1163 bool precount = getProperty(
"Precount");
1164 int chunk = getProperty(
"ChunkNumber");
1165 int totalChunks = getProperty(
"TotalChunks");
1166 const auto startTime = std::chrono::high_resolution_clock::now();
1168 classType, bankNumEvents, oldNeXusFileNames, precount, chunk, totalChunks);
1169 addTimer(
"loadEvents", startTime, std::chrono::high_resolution_clock::now());
1172 const std::size_t eventsLoaded = m_ws->getNumberEvents();
1174 <<
". Shortest TOF: " << shortest_tof <<
" microsec; longest TOF: " << longest_tof
1177 if (shortest_tof < 0)
1178 g_log.
warning() <<
"The shortest TOF was negative! At least 1 event has an "
1179 "invalid time-of-flight.\n";
1182 <<
" events with TOF > 2e8. This "
1183 "may indicate errors in the raw "
1187 if (m_ws->getInstrument()->hasParameter(
"T0")) {
1188 std::vector<double> instrumentT0 = m_ws->getInstrument()->getNumberParameter(
"T0",
true);
1189 if (!instrumentT0.empty()) {
1190 const double mT0 = instrumentT0.front();
1192 auto numHistograms =
static_cast<int64_t
>(m_ws->getNumberHistograms());
1194 for (int64_t i = 0; i < numHistograms; ++i) {
1197 m_ws->getSpectrum(i).addTof(mT0);
1202 API::Run &run = m_ws->mutableRun();
1203 run.addProperty<
double>(
"T0", mT0,
true);
1208 if (eventsLoaded > 0) {
1209 int nBins = getProperty(
"NumberOfBins");
1210 auto binEdgesVec = std::vector<double>(nBins + 1);
1211 binEdgesVec[0] = shortest_tof;
1212 binEdgesVec[nBins] = longest_tof + 1;
1213 double binStep = (binEdgesVec[nBins] - binEdgesVec[0]) / nBins;
1214 for (
int binIndex = 1; binIndex < nBins; binIndex++) {
1215 binEdgesVec[binIndex] = binEdgesVec[0] + (binStep * binIndex);
1217 m_ws->setAllX(HistogramData::BinEdges{binEdgesVec});
1219 m_ws->setAllX(HistogramData::BinEdges{0.0, 1.0});
1224 if (m_is_time_filtered) {
1227 TimeROI timeroi(filter_time_start, filter_time_stop);
1228 if (filter_bad_pulses)
1229 timeroi.update_intersection(*bad_pulses_timeroi);
1230 m_ws->mutableRun().setTimeROI(timeroi);
1231 m_ws->mutableRun().removeDataOutsideTimeROI();
1232 }
else if (filter_bad_pulses) {
1233 m_ws->mutableRun().setTimeROI(*bad_pulses_timeroi);
1234 m_ws->mutableRun().removeDataOutsideTimeROI();
1250bool LoadEventNexus::runLoadIDFFromNexus<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1252 const std::string &top_entry_name,
1254 auto ws = localWorkspace->getSingleHeldWorkspace();
1255 auto hasLoaded = runLoadIDFFromNexus<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg);
1256 localWorkspace->setInstrument(ws->getInstrument());
1265 std::string instrumentName;
1267 hFile.openGroup(
"isis_vms_compat",
"IXvms");
1268 }
catch (std::runtime_error &) {
1269 return instrumentName;
1272 hFile.openData(
"NAME");
1273 }
catch (std::runtime_error &) {
1275 return instrumentName;
1278 instrumentName = hFile.getStrData();
1282 return instrumentName;
1299bool LoadEventNexus::runLoadInstrument<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1301 const std::string &top_entry_name,
Algorithm *alg,
1303 auto ws = localWorkspace->getSingleHeldWorkspace();
1304 auto hasLoaded = runLoadInstrument<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg, descriptor);
1305 localWorkspace->setInstrument(ws->getInstrument());
1316 const std::vector<std::string> &bankNames) {
1319 std::vector<std::shared_ptr<RectangularDetector>> detList;
1320 for (
int i = 0; i < inst->nelements(); i++) {
1321 std::shared_ptr<RectangularDetector> det;
1322 std::shared_ptr<ICompAssembly> assem;
1323 std::shared_ptr<ICompAssembly> assem2;
1325 det = std::dynamic_pointer_cast<RectangularDetector>((*inst)[i]);
1327 detList.emplace_back(det);
1332 assem = std::dynamic_pointer_cast<ICompAssembly>((*inst)[i]);
1334 for (
int j = 0; j < assem->nelements(); j++) {
1335 det = std::dynamic_pointer_cast<RectangularDetector>((*assem)[j]);
1337 detList.emplace_back(det);
1343 assem2 = std::dynamic_pointer_cast<ICompAssembly>((*assem)[j]);
1345 for (
int k = 0; k < assem2->nelements(); k++) {
1346 det = std::dynamic_pointer_cast<RectangularDetector>((*assem2)[k]);
1348 detList.emplace_back(det);
1357 if (detList.empty())
1359 for (
auto &det : detList) {
1361 std::string det_name = det->getName();
1362 for (
const auto &bankName : bankNames) {
1363 size_t pos = bankName.find(
"_events");
1364 if (det_name == bankName.substr(0, pos))
1370 std::shared_ptr<const IComponent> parent = inst->getComponentByName(det_name);
1371 std::vector<Geometry::IComponent_const_sptr> children;
1372 std::shared_ptr<const Geometry::ICompAssembly> asmb =
1373 std::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
1374 asmb->getChildren(children,
false);
1375 for (
auto &col : children) {
1376 std::shared_ptr<const Geometry::ICompAssembly> asmb2 =
1377 std::dynamic_pointer_cast<const Geometry::ICompAssembly>(col);
1378 std::vector<Geometry::IComponent_const_sptr> grandchildren;
1379 asmb2->getChildren(grandchildren,
false);
1381 for (
auto &row : grandchildren) {
1384 inst->removeDetector(
d);
1387 auto *comp =
dynamic_cast<IComponent *
>(det.get());
1402 const std::vector<std::string> &bankNames) {
1405 if (!monitorsOnly && !bankNames.empty()) {
1407 g_log.
warning() <<
"Spectrum min/max/list selection ignored when "
1408 "`SingleBankPixelsOnly` is enabled\n";
1410 g_log.
debug() <<
"Populated spectra map for select banks\n";
1413 g_log.
debug() <<
"Loading only monitor spectra from " << nxsfile <<
"\n";
1415 g_log.
debug() <<
"Loading only detector spectra from " << nxsfile <<
"\n";
1419 g_log.
debug() <<
"No custom spectra mapping found, continuing with default "
1420 "1:1 mapping of spectrum:detectorID\n";
1422 g_log.
debug() <<
"Populated 1:1 spectra map for the whole instrument \n";
1434 std::string mon_wsname = this->
getProperty(
"OutputWorkspace");
1435 mon_wsname.append(
"_monitors");
1439 loadMonitors->setPropertyValue(
"Filename",
m_filename);
1440 g_log.
information() <<
"New workspace name for monitors: " << mon_wsname <<
'\n';
1441 loadMonitors->setPropertyValue(
"OutputWorkspace", mon_wsname);
1442 loadMonitors->setPropertyValue(
"LoadOnly", this->
getProperty(
"MonitorsLoadOnly"));
1443 loadMonitors->setPropertyValue(
"NXentryName", this->
getProperty(
"NXentryName"));
1444 loadMonitors->execute();
1445 Workspace_sptr monsOut = loadMonitors->getProperty(
"OutputWorkspace");
1449 "Monitors from the Event NeXus file");
1456 m_ws->setMonitorWorkspace(mons);
1463 for (
int i = 0; i < monsGrp->getNumberOfEntries(); i++) {
1464 std::stringstream ssWsName;
1465 ssWsName << mon_wsname <<
"_" << i + 1;
1466 std::stringstream ssPropName;
1467 ssPropName <<
"MonitorWorkspace"
1471 "Monitors from the Event NeXus file");
1472 this->
setProperty(ssPropName.str(), monsGrp->getItem(i));
1488std::unique_ptr<std::pair<std::vector<int32_t>, std::vector<int32_t>>>
1490 const std::string vms_str =
"/isis_vms_compat";
1492 g_log.
debug() <<
"Attempting to load custom spectra mapping from '" << entry_name << vms_str <<
"'.\n";
1493 m_file->openAddress(
"/" + entry_name + vms_str);
1516 m_file->openData(
"UDET");
1517 std::vector<int32_t> udet;
1521 m_file->openData(
"SPEC");
1522 std::vector<int32_t> spec;
1533 const size_t ndets(udet.size());
1534 if (ndets != spec.size()) {
1535 std::ostringstream os;
1536 os <<
"UDET/SPEC list size mismatch. UDET=" << udet.size() <<
", SPEC=" << spec.size() <<
"\n";
1537 throw std::runtime_error(os.str());
1541 return std::make_unique<std::pair<std::vector<int32_t>, std::vector<int32_t>>>(std::move(spec), std::move(udet));
1551 std::string prefix(
"Filter");
1564 std::string msg(
"You must specify both min & max or neither TOF filters");
1566 msg =
" for the monitors.";
1567 throw std::invalid_argument(msg);
1589 file.openGroup(
"isis_vms_compat",
"IXvms");
1597 std::vector<int32_t> spb;
1598 std::vector<float> rspb;
1599 file.readData(
"SPB", spb);
1600 file.readData(
"RSPB", rspb);
1608 std::stringstream s;
1609 s <<
"Wrong definition found in isis_vms_compat :> " << ex.what();
1611 throw std::runtime_error(s.str());
1626 }
catch (std::runtime_error &e) {
1627 throw std::runtime_error(
"Severe failure when trying to open NeXus file: " + std::string(e.what()));
1631 throw std::runtime_error(
"An unexpected failure happened, unable to "
1632 "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_FILELOADER_ALGORITHM(classname)
DECLARE_NEXUS_FILELOADER_ALGORITHM should be used in place of the standard DECLARE_ALGORITHM macro wh...
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.
virtual const std::shared_ptr< Mantid::Nexus::NexusDescriptor > getFileInfo() const noexcept
Required to pass m_fileInfo to static functions Keeping it shared_ptr to match setFileInfo signature ...
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) override
Create a Child Algorithm.
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
void execLoader() override
Execution code.
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 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::NexusDescriptor &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 > settings)
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.
const std::map< std::string, std::set< std::string > > & getAllEntries() const noexcept
Returns a const reference of the internal map holding all entries in the Nexus HDF5 file.
bool isEntry(const std::string &entryName, const std::string &groupClass) const noexcept
Checks if a full-address entry exists for a particular groupClass in a Nexus dataset.
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.
void adjustTimeOfFlightISISLegacy(Nexus::File &file, T localWorkspace, const std::string &entry_name, const std::string &classType, const Nexus::NexusDescriptor *descriptor=nullptr)
ISIS specific method for dealing with wide events.
std::shared_ptr< EventWorkspaceCollection > EventWorkspaceCollection_sptr
std::pair< DateAndTime, DateAndTime > firstLastPulseTimes(Nexus::File &file, Kernel::Logger &logger)
std::size_t numEvents(Nexus::File &file, bool &hasTotalCounts, bool &oldNeXusFileNames, const std::string &prefix, const Nexus::NexusDescriptor &descriptor)
Get the number of events in the currently opened group.
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.