25#include "MantidIndexing/IndexInfo.h"
37#include "MantidNexus/NexusFile.h"
41#include <boost/format.hpp>
46using Mantid::Types::Core::DateAndTime;
55using namespace Kernel;
56using namespace DateAndTimeHelpers;
57using namespace Geometry;
59using namespace DataObjects;
60using Types::Core::DateAndTime;
63const std::vector<std::string> binningModeNames{
"Default",
"Linear",
"Logarithmic"};
67const std::string LOG_CHARGE_NAME(
"proton_charge");
70const std::string COMPRESS_TOL(
"CompressTolerance");
71const std::string COMPRESS_MODE(
"CompressBinningMode");
72const std::string BAD_PULSES_CUTOFF(
"FilterBadPulsesLowerCutoff");
77 std::string detectorEventsAddr = std::format(
"/{}/detector_1_events", topEntryName);
78 if (!file.hasAddress(detectorEventsAddr)) {
82 const std::string eventTimeShiftAddr(detectorEventsAddr +
"/event_time_offset_shift");
83 if (file.hasAddress(eventTimeShiftAddr)) {
84 std::string eventShiftType;
85 file.readData(eventTimeShiftAddr, eventShiftType);
86 return !(eventShiftType ==
"random");
89 const std::string programNameAddr = std::format(
"/{}/program_name", topEntryName);
90 if (file.hasAddress(programNameAddr)) {
91 std::string program_name;
92 file.readData(programNameAddr, program_name);
93 if (program_name ==
"ISISICP.EXE") {
104 : filter_tof_min(0), filter_tof_max(0), m_specMin(0), m_specMax(0), longest_tof(0), shortest_tof(0), bad_tofs(0),
105 discarded_events(0), compressEvents(false), m_instrument_loaded_correctly(false), loadlogs(false),
106 event_id_is_spec(false) {
120 if (descriptor.
isEntry(
"/entry",
"NXentry") || descriptor.
isEntry(
"/raw_data_1",
"NXentry")) {
132 const std::vector<std::string> exts{
".nxs.h5",
".nxs",
"_event.nxs"};
134 "The name of the Event NeXus file to read, including its full or "
136 "The file name is typically of the form INST_####_event.nxs (N.B. case "
137 "sensitive if running on Linux).");
140 "The name of the output EventWorkspace or WorkspaceGroup in which to "
141 "load the EventNexus file.");
144 "Optional: Name of the NXentry to load if it's not the default.");
147 "Optional: To exclude events that do not fall within a range "
148 "of times-of-flight. "
149 "This is the minimum accepted value in microseconds. Keep "
150 "blank to load all events.");
153 "Optional: To exclude events that do not fall within a range "
154 "of times-of-flight. "
155 "This is the maximum accepted value in microseconds. Keep "
156 "blank to load all events.");
159 "Optional: To only include events after the provided start "
160 "time, in seconds (relative to the start of the run).");
163 "Optional: To only include events before the provided stop "
164 "time, in seconds (relative to the start of the run).");
168 "Optional: To filter bad pulses set the Lower Cutoff percentage to use.");
170 std::string grp1 =
"Filter Events";
178 "Optional: To only include events from one bank. Any bank "
179 "whose name does not match the given string will have no "
183 "Optional: Only applies if you specified a single bank to "
184 "load with BankName. "
185 "Only pixels in the specified bank will be created if true; "
186 "all of the instrument's pixels will be created otherwise.");
189 std::string grp2 =
"Loading a Single Bank";
194 "Pre-count the number of events in each pixel before allocating memory "
195 "(optional, default True). "
196 "This can significantly reduce memory use and memory fragmentation; it "
197 "may also speed up loading.");
201 "CompressEvents while loading (optional, default: off). "
202 "This specified the tolerance to use (in microseconds) when compressing where positive is linear tolerance, "
203 "negative is logorithmic tolerance, and zero indicates that time-of-flight must be identical to compress.");
205 PropertyNames::COMPRESS_MODE, binningModeNames[
size_t(BinningMode::DEFAULT)],
206 std::make_shared<Mantid::Kernel::StringListValidator>(binningModeNames),
208 "Binning behavior can be specified in the usual way through sign of binwidth and other properties ('Default'); "
209 "or can be set to one of the allowed binning modes. "
210 "This will override all other specification or default behavior.");
212 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
213 mustBePositive->setLower(1);
215 "If loading the file by sections ('chunks'), this is the "
216 "section number of this execution of the algorithm.");
218 "If loading the file by sections ('chunks'), this is the "
219 "total number of sections.");
225 std::string grp3 =
"Reduce Memory Use";
233 "Load the monitors from the file (optional, default False).");
235 std::vector<std::string> options{
"",
"Events",
"Histogram"};
236 declareProperty(
"MonitorsLoadOnly",
"", std::make_shared<Kernel::StringListValidator>(options),
237 "If multiple repesentations exist, which one to load. "
238 "Default is to load the one that is present.");
241 "Optional: To exclude events from monitors that do not fall "
242 "within a range of times-of-flight. "
243 "This is the minimum accepted value in microseconds.");
246 "Optional: To exclude events from monitors that do not fall "
247 "within a range of times-of-flight. "
248 "This is the maximum accepted value in microseconds.");
251 "Optional: To only include events from monitors after the "
252 "provided start time, in seconds (relative to the start of "
256 "Optional: To only include events from monitors before the "
257 "provided stop time, in seconds (relative to the start of "
261 auto asEventsIsOn = [] {
262 std::unique_ptr<IPropertySettings> prop = std::make_unique<VisibleWhenProperty>(
"LoadMonitors",
IS_EQUAL_TO,
"1");
270 std::string grp4 =
"Monitors";
281 "A comma-separated list of individual spectra to read.");
284 "If true, only the meta data and sample logs will be loaded.");
287 "Load only the Sample/DAS logs from the file (default True).");
290 "Load all the logs from the nxs, without checking or processing them; if checked, LoadLogs will be "
291 "ignored; use with caution");
293 std::vector<std::string> loadType{
"Default",
"Multiprocess (experimental)"};
294 auto loadTypeValidator = std::make_shared<StringListValidator>(loadType);
296 "LoadType",
"Default", loadTypeValidator,
297 "Deprecated feature. This option has no effect on algorithm behavior and will be removed in a future release.");
300 "Reads the embedded Instrument XML from the NeXus file "
301 "(optional, default True). ");
304 "The number of bins intially defined. Use Rebin to change "
305 "the binning later. If there is no data loaded, or you "
306 "select meta data only you will only get 1 bin.");
311 "If specified, only these logs will be loaded from the file (each "
312 "separated by a space).");
315 "If specified, these logs will NOT be loaded from the file (each "
316 "separated by a space).");
323 g_log.
warning() <<
"The experimental multiprocess loader has been discontinued. The default loader will be used "
324 "instead. Please remove use of this property from all scripts.";
328 std::map<std::string, std::string> result;
330 if (!
isDefault(PropertyNames::BAD_PULSES_CUTOFF)) {
331 const double cutoff =
getProperty(PropertyNames::BAD_PULSES_CUTOFF);
332 if (cutoff < 0 || cutoff > 100)
333 result[PropertyNames::BAD_PULSES_CUTOFF] =
"Must be empty or between 0 and 100";
343 std::string nxentryProperty =
getProperty(
"NXentryName");
344 if (!nxentryProperty.empty()) {
349 std::string firstGoodEntry(
"");
350 std::set<std::string> goodEntries{
"entry",
"raw_data_1"};
351 auto allEntries =
m_file->getEntries();
352 for (std::string goodEntry : goodEntries) {
353 if (allEntries.count(goodEntry) != 0 && allEntries[goodEntry] !=
"SDS") {
354 firstGoodEntry = std::move(goodEntry);
360 g_log.
error() <<
"Unable to determine name of top level NXentry - assuming \"entry\".\n";
367 if ((!ConfigService::Instance().hasProperty(
"loadeventnexus.keeppausedevents")) &&
368 (
m_ws->run().getLogData(
"pause")->size() > 1)) {
369 g_log.
notice(
"Filtering out events when the run was marked as paused. "
370 "Set the loadeventnexus.keeppausedevents configuration "
371 "property to override this.");
374 filter->setProperty(
"InputWorkspace",
workspace);
375 filter->setProperty(
"OutputWorkspace",
workspace);
376 filter->setProperty(
"LogName",
"pause");
378 filter->setProperty(
"MinimumValue", 0.0);
379 filter->setProperty(
"MaximumValue", 0.0);
380 filter->setProperty(
"LogBoundary",
"Left");
391 using std::placeholders::_1;
392 auto func = std::bind(&LoadEventNexus::filterDuringPause<MatrixWorkspace_sptr>,
this, _1);
403 Mantid::Types::Core::DateAndTime &stopTime) {
406 filterByTime->setProperty(
"InputWorkspace",
workspace);
408 filterByTime->setProperty(
"AbsoluteStartTime", startTime.toISO8601String());
409 filterByTime->setProperty(
"AbsoluteStopTime", stopTime.toISO8601String());
410 filterByTime->execute();
411 return filterByTime->getProperty(
"OutputWorkspace");
417 Mantid::Types::Core::DateAndTime &startTime,
418 Mantid::Types::Core::DateAndTime &stopTime) {
420 using std::placeholders::_1;
421 auto func = std::bind(&LoadEventNexus::filterEventsByTime<EventWorkspace_sptr>,
this, _1, startTime, stopTime);
438 if (mode == BinningMode::LINEAR)
440 else if (mode == BinningMode::LOGARITHMIC)
447 bool load_monitors = this->
getProperty(
"LoadMonitors");
459 Progress prog(
this, 0.0, 0.3, reports);
462 m_ws = std::make_shared<EventWorkspaceCollection>();
470 <<
" events were encountered coming from pixels which "
471 "are not in the Instrument Definition File."
472 "These events were discarded.\n";
490 prog.
report(
"Loading monitors");
496 file.openData(
"event_time_zero");
501 if (!file.hasAttr(
"offset")) {
502 offset = DateAndTime(
"1970-01-01T00:00:00Z");
503 logger.
warning(
"In firstLastPulseTimes: no ISO8601 offset attribute "
504 "provided for event_time_zero, using UNIX epoch instead");
506 std::string isooffset;
507 file.getAttr(
"offset", isooffset);
508 offset = DateAndTime(isooffset);
511 if (file.hasAttr(
"units"))
512 file.getAttr(
"units", units);
514 auto pulse_times = Nexus::IOHelper::readNexusVector<double>(file,
"event_time_zero");
517 if (pulse_times.empty()) {
518 throw std::invalid_argument(
"Cannot find run start; event_time_zero contains no pulse times");
522 return std::make_pair(DateAndTime(pulse_times.front() * conv, 0.0) + offset.totalNanoseconds(),
523 DateAndTime(pulse_times.back() * conv, 0.0) + offset.totalNanoseconds());
537std::size_t
numEvents(Nexus::File &file,
bool &hasTotalCounts,
bool &oldNeXusFileNames,
const std::string &prefix) {
539 if (hasTotalCounts) {
540 hasTotalCounts =
false;
541 if (file.hasData(prefix +
"/total_counts")) {
543 file.openData(
"total_counts");
544 auto info = file.getInfo();
548 file.readData(
"total_counts", eventCount);
549 hasTotalCounts =
true;
559 if (oldNeXusFileNames)
560 file.openData(
"event_pixel_id");
562 file.openData(
"event_id");
566 file.openData(
"event_pixel_id");
567 oldNeXusFileNames =
true;
574 size_t numEvents =
static_cast<std::size_t
>(file.getInfo().dims[0]);
593std::shared_ptr<BankPulseTimes>
595 bool returnpulsetimes,
int &nPeriods,
600 std::shared_ptr<BankPulseTimes> out;
607 loadLogs->setPropertyValue(
"Filename", nexusfilename);
610 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
616 const Run &run = localWorkspace->run();
625 std::string status =
"";
626 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
633 std::vector<Types::Core::DateAndTime> temp;
634 if (localWorkspace->run().hasProperty(
"proton_charge")) {
640 if (returnpulsetimes)
641 out = std::make_shared<BankPulseTimes>(temp);
645 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
647 "sample log with invalid pulse time!\n";
649 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
654 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
656 localWorkspace->mutableRun().addProperty(
"run_start", run.
getProperty(
"start_time")->
value(),
true);
659 "not be able to filter by time.\n";
665 localWorkspace->mutableRun().setGoniometer(gm,
true);
666 }
catch (std::runtime_error &) {
673 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
674 "sample logs may be missing."
698 const std::string &nexusfilename, T localWorkspace,
API::Algorithm &alg,
bool returnpulsetimes,
int &nPeriods,
700 const std::vector<std::string> &block_list) {
704 std::shared_ptr<BankPulseTimes> out;
711 loadLogs->setPropertyValue(
"Filename", nexusfilename);
713 loadLogs->setProperty<std::vector<std::string>>(
"AllowList", allow_list);
714 loadLogs->setProperty<std::vector<std::string>>(
"BlockList", block_list);
717 loadLogs->setPropertyValue(
"NXentryName", alg.
getPropertyValue(
"NXentryName"));
723 const Run &run = localWorkspace->run();
731 std::string status =
"";
733 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(
dynamic_cast<TimeSeriesProperty<int> *
>(temp->clone()));
740 std::vector<Types::Core::DateAndTime> temp;
741 if (localWorkspace->run().hasProperty(
"proton_charge")) {
747 if (returnpulsetimes)
748 out = std::make_shared<BankPulseTimes>(temp);
752 if (temp[0] < Types::Core::DateAndTime(
"1991-01-01T00:00:00"))
754 "sample log with invalid pulse time!\n";
756 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
761 localWorkspace->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
764 "not be able to filter by time.\n";
770 localWorkspace->mutableRun().setGoniometer(gm,
true);
771 }
catch (std::runtime_error &) {
778 alg.
getLogger().
error() <<
"Error while loading Logs from SNS Nexus. Some "
779 "sample logs may be missing."
802 const int &nPeriods,
const std::string &nexusfilename,
803 std::string &status) {
804 const auto valuesAsVector = tempPeriodLog->valuesAsVector();
805 const auto nPeriodsInLog = *std::max_element(valuesAsVector.begin(), valuesAsVector.end());
806 int numberOfValidPeriods = nPeriodsInLog;
810 if (nPeriodsInLog == 0 && nPeriods == 1) {
813 const std::vector<int> newValues(tempPeriodLog->realSize(), 1);
814 const auto times = tempPeriodLog->timesAsVector();
816 numberOfValidPeriods = 1;
817 }
else if (nPeriodsInLog < nPeriods) {
820 "The number of periods specified in the file (%1%) is greater than the maximum period in the data (%2%).") %
821 nPeriods % nPeriodsInLog);
822 }
else if (nPeriodsInLog > nPeriods) {
828 const auto msg =
"File " + nexusfilename +
829 " has been corrupted. The log framelog/period_log/value "
831 std::to_string(nPeriodsInLog) +
" periods, but periods/number contains " +
832 std::to_string(nPeriods) +
". This file should be manually inspected and corrected.";
836 periodLog = std::make_unique<const TimeSeriesProperty<int>>(*tempPeriodLog);
837 tempPeriodLog.reset();
839 return numberOfValidPeriods;
857std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
860 auto ws = localWorkspace->getSingleHeldWorkspace();
861 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog);
882std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
885 const std::vector<std::string> &allow_list,
const std::vector<std::string> &block_list) {
886 auto ws = localWorkspace->getSingleHeldWorkspace();
887 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog,
888 allow_list, block_list);
908 std::vector<std::string> allow_list =
getProperty(
"AllowList");
909 std::vector<std::string> block_list =
getProperty(
"BlockList");
912 DateAndTime run_start(0, 0);
913 bool takeTimesFromEvents =
false;
917 auto periodLog = std::make_unique<const TimeSeriesProperty<int>>(
"period_log");
925 if (allow_list.empty() && block_list.empty()) {
927 runLoadNexusLogs<EventWorkspaceCollection_sptr>(
m_filename,
m_ws, *
this,
true, nPeriods, periodLog);
930 periodLog, allow_list, block_list);
934 run_start =
m_ws->getFirstPulseTime();
942 takeTimesFromEvents =
true;
951 g_log.
debug() <<
"Failed to open nexus file \"" <<
m_filename <<
"\" in read mode: " << e.what() <<
"\n";
956 <<
"Reading the start time directly from /" <<
m_top_entry_name <<
"/start_time\n";
964 m_ws->mutableRun().addProperty(
"run_start", run_start.toISO8601String(),
true);
974 }
catch (std::runtime_error &e) {
976 g_log.
error() <<
"Error loading metadata: " << e.what() <<
'\n';
979 m_ws->setNPeriods(
static_cast<size_t>(nPeriods),
984 std::vector<DateAndTime> temp;
990 prog->
report(
"Loading instrument");
999 throw std::runtime_error(
"Instrument was not initialized correctly! Loading cannot continue.");
1005 m_file->openAddress(
"/");
1010 vector<string> bankNames;
1011 vector<std::size_t> bankNumEvents;
1012 std::string classType = monitors ?
"NXmonitor" :
"NXevent_data";
1013 bool oldNeXusFileNames(
false);
1014 bool haveWeights =
false;
1015 auto firstPulseT = DateAndTime::maximum();
1016 if (
m_file->classTypeExists(classType)) {
1017 std::map<std::string, std::string> entries =
m_file->getEntries();
1018 for (
auto entry : entries) {
1019 if (entry.second != classType) {
1024 if (entry.first ==
"bank_error_events" || entry.first ==
"bank_unmapped_events")
1027 m_file->openGroup(entry.first, classType);
1030 bool hasTotalCounts =
true;
1031 std::size_t num =
numEvents(*
m_file, hasTotalCounts, oldNeXusFileNames, prefix);
1032 bankNames.emplace_back(entry.first);
1033 bankNumEvents.emplace_back(num);
1034 if (takeTimesFromEvents && num > 0) {
1040 firstPulseT = std::min(firstPulseT, localFirstLast.first);
1043 const std::string absoluteEventWeightName = prefix +
"/event_weight";
1044 haveWeights =
m_file->hasAddress(absoluteEventWeightName);
1048 if (takeTimesFromEvents)
1049 run_start = firstPulseT;
1058 if (AnalysisDataService::Instance().doesExist(outName))
1059 AnalysisDataService::Instance().remove(outName);
1063 double filter_time_start_sec, filter_time_stop_sec;
1064 filter_time_start_sec =
getProperty(
"FilterByTimeStart");
1065 filter_time_stop_sec =
getProperty(
"FilterByTimeStop");
1074 if (filter_time_start_sec !=
EMPTY_DBL()) {
1079 if (filter_time_stop_sec !=
EMPTY_DBL()) {
1086 std::string msg =
"Your ";
1089 msg +=
"filter for time's Stop value is smaller than the Start value.";
1090 throw std::invalid_argument(msg);
1098 double min_pcharge, max_pcharge;
1099 std::tie(min_pcharge, max_pcharge, std::ignore) =
1100 m_ws->run().getBadPulseRange(LOG_CHARGE_NAME,
getProperty(PropertyNames::BAD_PULSES_CUTOFF));
1102 const auto *pcharge_log =
1105 pcharge_log->makeFilterByValue(min_pcharge, max_pcharge,
false,
TimeInterval(0, 1), 0.,
true));
1110 auto axis = HistogramData::BinEdges{1,
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1 - 1};
1112 m_ws->setAllX(axis);
1119 std::vector<std::string> someBanks =
getProperty(
"BankName");
1120 const bool SingleBankPixelsOnly =
getProperty(
"SingleBankPixelsOnly");
1121 if ((!someBanks.empty()) && (!monitors)) {
1122 std::vector<std::string> eventedBanks;
1123 eventedBanks.reserve(someBanks.size());
1124 std::transform(someBanks.cbegin(), someBanks.cend(), std::back_inserter(eventedBanks),
1125 [](
const auto &bank) { return bank +
"_events"; });
1128 const auto invalidBank =
1129 std::find_if(eventedBanks.cbegin(), eventedBanks.cend(), [&bankNames](
const auto &someBank) {
1130 return std::none_of(bankNames.cbegin(), bankNames.cend(),
1131 [&someBank](const auto &name) { return name == someBank; });
1133 if (invalidBank != eventedBanks.cend()) {
1134 throw std::invalid_argument(
"No entry named '" + *invalidBank +
"' was found in the .NXS file.");
1138 bankNames.assign(eventedBanks.cbegin(), eventedBanks.cend());
1141 bankNumEvents.assign(someBanks.size(), 1);
1143 if (!SingleBankPixelsOnly)
1147 prog->report(
"Initializing all pixels");
1150 if (m_ws->getInstrument()->hasParameter(
"remove-unused-banks")) {
1151 std::vector<double> instrumentUnused = m_ws->getInstrument()->getNumberParameter(
"remove-unused-banks",
true);
1152 if (!instrumentUnused.empty()) {
1153 const auto unused =
static_cast<int>(instrumentUnused.front());
1155 deleteBanks(m_ws, bankNames);
1159 createSpectraMapping(m_filename, monitors, someBanks);
1163 for (
size_t i = 0; i < m_ws->getNumberHistograms(); i++)
1167 shortest_tof =
static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1;
1170 bool precount = getProperty(
"Precount");
1171 int chunk = getProperty(
"ChunkNumber");
1172 int totalChunks = getProperty(
"TotalChunks");
1173 const auto startTime = std::chrono::high_resolution_clock::now();
1175 classType, bankNumEvents, oldNeXusFileNames, precount, chunk, totalChunks);
1176 addTimer(
"loadEvents", startTime, std::chrono::high_resolution_clock::now());
1179 const std::size_t eventsLoaded = m_ws->getNumberEvents();
1181 <<
". Shortest TOF: " << shortest_tof <<
" microsec; longest TOF: " << longest_tof
1184 if (shortest_tof < 0)
1185 g_log.
warning() <<
"The shortest TOF was negative! At least 1 event has an "
1186 "invalid time-of-flight.\n";
1189 <<
" events with TOF > 2e8. This "
1190 "may indicate errors in the raw "
1194 if (m_ws->getInstrument()->hasParameter(
"T0")) {
1195 std::vector<double> instrumentT0 = m_ws->getInstrument()->getNumberParameter(
"T0",
true);
1196 if (!instrumentT0.empty()) {
1197 const double mT0 = instrumentT0.front();
1199 auto numHistograms =
static_cast<int64_t
>(m_ws->getNumberHistograms());
1201 for (int64_t i = 0; i < numHistograms; ++i) {
1204 m_ws->getSpectrum(i).addTof(mT0);
1209 API::Run &run = m_ws->mutableRun();
1210 run.addProperty<
double>(
"T0", mT0,
true);
1215 if (eventsLoaded > 0) {
1216 int nBins = getProperty(
"NumberOfBins");
1217 auto binEdgesVec = std::vector<double>(nBins + 1);
1218 binEdgesVec[0] = shortest_tof;
1219 binEdgesVec[nBins] = longest_tof + 1;
1220 double binStep = (binEdgesVec[nBins] - binEdgesVec[0]) / nBins;
1221 for (
int binIndex = 1; binIndex < nBins; binIndex++) {
1222 binEdgesVec[binIndex] = binEdgesVec[0] + (binStep * binIndex);
1224 m_ws->setAllX(HistogramData::BinEdges{binEdgesVec});
1226 m_ws->setAllX(HistogramData::BinEdges{0.0, 1.0});
1233 if (m_is_time_filtered) {
1236 TimeROI timeroi(filter_time_start, filter_time_stop);
1237 if (filter_bad_pulses)
1238 timeroi.update_intersection(*bad_pulses_timeroi);
1239 m_ws->mutableRun().setTimeROI(timeroi);
1240 m_ws->mutableRun().removeDataOutsideTimeROI();
1241 }
else if (filter_bad_pulses) {
1242 m_ws->mutableRun().setTimeROI(*bad_pulses_timeroi);
1243 m_ws->mutableRun().removeDataOutsideTimeROI();
1259bool LoadEventNexus::runLoadIDFFromNexus<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1261 const std::string &top_entry_name,
1263 auto ws = localWorkspace->getSingleHeldWorkspace();
1264 auto hasLoaded = runLoadIDFFromNexus<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg);
1265 localWorkspace->setInstrument(ws->getInstrument());
1274 std::string instrumentName;
1276 hFile.openGroup(
"isis_vms_compat",
"IXvms");
1277 }
catch (std::runtime_error &) {
1278 return instrumentName;
1281 hFile.openData(
"NAME");
1282 }
catch (std::runtime_error &) {
1284 return instrumentName;
1287 instrumentName = hFile.getStrData();
1291 return instrumentName;
1308bool LoadEventNexus::runLoadInstrument<EventWorkspaceCollection_sptr>(
const std::string &nexusfilename,
1310 const std::string &top_entry_name,
Algorithm *alg,
1312 auto ws = localWorkspace->getSingleHeldWorkspace();
1313 auto hasLoaded = runLoadInstrument<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg, descriptor);
1314 localWorkspace->setInstrument(ws->getInstrument());
1325 const std::vector<std::string> &bankNames) {
1328 std::vector<std::shared_ptr<RectangularDetector>> detList;
1329 for (
int i = 0; i < inst->nelements(); i++) {
1330 std::shared_ptr<RectangularDetector> det;
1331 std::shared_ptr<ICompAssembly> assem;
1332 std::shared_ptr<ICompAssembly> assem2;
1334 det = std::dynamic_pointer_cast<RectangularDetector>((*inst)[i]);
1336 detList.emplace_back(det);
1341 assem = std::dynamic_pointer_cast<ICompAssembly>((*inst)[i]);
1343 for (
int j = 0; j < assem->nelements(); j++) {
1344 det = std::dynamic_pointer_cast<RectangularDetector>((*assem)[j]);
1346 detList.emplace_back(det);
1352 assem2 = std::dynamic_pointer_cast<ICompAssembly>((*assem)[j]);
1354 for (
int k = 0; k < assem2->nelements(); k++) {
1355 det = std::dynamic_pointer_cast<RectangularDetector>((*assem2)[k]);
1357 detList.emplace_back(det);
1366 if (detList.empty())
1370 auto ws =
workspace->getSingleHeldWorkspace();
1371 const auto &componentInfo = ws->componentInfo();
1373 for (
auto &det : detList) {
1375 std::string det_name = det->getName();
1376 for (
const auto &bankName : bankNames) {
1377 size_t pos = bankName.find(
"_events");
1378 if (det_name == bankName.substr(0, pos))
1384 const size_t parentIndex = componentInfo.indexOfAny(det_name);
1385 const auto children = componentInfo.children(parentIndex);
1386 for (
const auto &colIndex : children) {
1387 const auto grandchildren = componentInfo.children(colIndex);
1389 for (
const auto &rowIndex : grandchildren) {
1390 auto *
d =
dynamic_cast<Detector *
>(
const_cast<IComponent *
>(componentInfo.componentID(rowIndex)));
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_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.
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.