Mantid
Loading...
Searching...
No Matches
LoadEventNexus.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
8
9#include "MantidAPI/Axis.h"
14#include "MantidAPI/Run.h"
15#include "MantidAPI/Sample.h"
24#include "MantidIndexing/IndexInfo.h"
32#include "MantidKernel/Timer.h"
36#include "MantidNexus/NexusFile.h"
38
39#include <H5Cpp.h>
40#include <boost/format.hpp>
41#include <memory>
42
43#include <regex>
44
45using Mantid::Types::Core::DateAndTime;
46using std::map;
47using std::string;
48using std::vector;
49
50namespace Mantid::DataHandling {
51
53
54using namespace Kernel;
55using namespace DateAndTimeHelpers;
56using namespace Geometry;
57using namespace API;
58using namespace DataObjects;
59using Types::Core::DateAndTime;
60
61namespace {
62const std::vector<std::string> binningModeNames{"Default", "Linear", "Logarithmic"};
63enum class BinningMode { DEFAULT, LINEAR, LOGARITHMIC, enum_count };
65
66const std::string LOG_CHARGE_NAME("proton_charge");
67
68namespace PropertyNames {
69const std::string COMPRESS_TOL("CompressTolerance");
70const std::string COMPRESS_MODE("CompressBinningMode");
71const std::string BAD_PULSES_CUTOFF("FilterBadPulsesLowerCutoff");
72} // namespace PropertyNames
73} // namespace
74
75//----------------------------------------------------------------------------------------------
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) {
83}
84
85//----------------------------------------------------------------------------------------------
93
94 int confidence = 0;
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")) {
98 confidence = 80;
99 }
100 }
101
102 return confidence;
103}
104
105//----------------------------------------------------------------------------------------------
109 const std::vector<std::string> exts{".nxs.h5", ".nxs", "_event.nxs"};
110 this->declareProperty(std::make_unique<FileProperty>("Filename", "", FileProperty::Load, exts),
111 "The name of the Event NeXus file to read, including its full or "
112 "relative path. "
113 "The file name is typically of the form INST_####_event.nxs (N.B. case "
114 "sensitive if running on Linux).");
115
116 this->declareProperty(std::make_unique<WorkspaceProperty<Workspace>>("OutputWorkspace", "", Direction::Output),
117 "The name of the output EventWorkspace or WorkspaceGroup in which to "
118 "load the EventNexus file.");
119
120 declareProperty(std::make_unique<PropertyWithValue<string>>("NXentryName", "", Direction::Input),
121 "Optional: Name of the NXentry to load if it's not the default.");
122
123 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterByTofMin", EMPTY_DBL(), Direction::Input),
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.");
128
129 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterByTofMax", EMPTY_DBL(), Direction::Input),
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.");
134
135 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterByTimeStart", EMPTY_DBL(), Direction::Input),
136 "Optional: To only include events after the provided start "
137 "time, in seconds (relative to the start of the run).");
138
139 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterByTimeStop", EMPTY_DBL(), Direction::Input),
140 "Optional: To only include events before the provided stop "
141 "time, in seconds (relative to the start of the run).");
142
144 std::make_unique<PropertyWithValue<double>>(PropertyNames::BAD_PULSES_CUTOFF, EMPTY_DBL(), Direction::Input),
145 "Optional: To filter bad pulses set the Lower Cutoff percentage to use.");
146
147 std::string grp1 = "Filter Events";
148 setPropertyGroup("FilterByTofMin", grp1);
149 setPropertyGroup("FilterByTofMax", grp1);
150 setPropertyGroup("FilterByTimeStart", grp1);
151 setPropertyGroup("FilterByTimeStop", grp1);
152 setPropertyGroup("FilterBadPulsesLowerCutoff", grp1);
153
154 declareProperty(std::make_unique<ArrayProperty<string>>("BankName", Direction::Input),
155 "Optional: To only include events from one bank. Any bank "
156 "whose name does not match the given string will have no "
157 "events.");
158
159 declareProperty(std::make_unique<PropertyWithValue<bool>>("SingleBankPixelsOnly", true, Direction::Input),
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.");
164 setPropertySettings("SingleBankPixelsOnly", std::make_unique<VisibleWhenProperty>("BankName", IS_NOT_DEFAULT));
165
166 std::string grp2 = "Loading a Single Bank";
167 setPropertyGroup("BankName", grp2);
168 setPropertyGroup("SingleBankPixelsOnly", grp2);
169
170 declareProperty(std::make_unique<PropertyWithValue<bool>>("Precount", true, Direction::Input),
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.");
175
177 std::make_unique<PropertyWithValue<double>>(PropertyNames::COMPRESS_TOL, EMPTY_DBL(), Direction::Input),
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),
184 "Optional. "
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.");
188
189 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
190 mustBePositive->setLower(1);
191 declareProperty("ChunkNumber", EMPTY_INT(), mustBePositive,
192 "If loading the file by sections ('chunks'), this is the "
193 "section number of this execution of the algorithm.");
194 declareProperty("TotalChunks", EMPTY_INT(), mustBePositive,
195 "If loading the file by sections ('chunks'), this is the "
196 "total number of sections.");
197 // TotalChunks is only meaningful if ChunkNumber is set
198 // Would be nice to be able to restrict ChunkNumber to be <= TotalChunks at
199 // validation
200 setPropertySettings("TotalChunks", std::make_unique<VisibleWhenProperty>("ChunkNumber", IS_NOT_DEFAULT));
201
202 std::string grp3 = "Reduce Memory Use";
203 setPropertyGroup("Precount", grp3);
204 setPropertyGroup(PropertyNames::COMPRESS_TOL, grp3);
205 setPropertyGroup(PropertyNames::COMPRESS_MODE, grp3);
206 setPropertyGroup("ChunkNumber", grp3);
207 setPropertyGroup("TotalChunks", grp3);
208
209 declareProperty(std::make_unique<PropertyWithValue<bool>>("LoadMonitors", false, Direction::Input),
210 "Load the monitors from the file (optional, default False).");
211
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.");
216
217 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterMonByTofMin", EMPTY_DBL(), Direction::Input),
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.");
221
222 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterMonByTofMax", EMPTY_DBL(), Direction::Input),
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.");
226
227 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterMonByTimeStart", EMPTY_DBL(), Direction::Input),
228 "Optional: To only include events from monitors after the "
229 "provided start time, in seconds (relative to the start of "
230 "the run).");
231
232 declareProperty(std::make_unique<PropertyWithValue<double>>("FilterMonByTimeStop", EMPTY_DBL(), Direction::Input),
233 "Optional: To only include events from monitors before the "
234 "provided stop time, in seconds (relative to the start of "
235 "the run).");
236
237 setPropertySettings("MonitorsLoadOnly", std::make_unique<VisibleWhenProperty>("LoadMonitors", IS_EQUAL_TO, "1"));
238 auto asEventsIsOn = [] {
239 std::unique_ptr<IPropertySettings> prop = std::make_unique<VisibleWhenProperty>("LoadMonitors", IS_EQUAL_TO, "1");
240 return prop;
241 };
242 setPropertySettings("FilterMonByTofMin", asEventsIsOn());
243 setPropertySettings("FilterMonByTofMax", asEventsIsOn());
244 setPropertySettings("FilterMonByTimeStart", asEventsIsOn());
245 setPropertySettings("FilterMonByTimeStop", asEventsIsOn());
246
247 std::string grp4 = "Monitors";
248 setPropertyGroup("LoadMonitors", grp4);
249 setPropertyGroup("MonitorsLoadOnly", grp4);
250 setPropertyGroup("FilterMonByTofMin", grp4);
251 setPropertyGroup("FilterMonByTofMax", grp4);
252 setPropertyGroup("FilterMonByTimeStart", grp4);
253 setPropertyGroup("FilterMonByTimeStop", grp4);
254
255 declareProperty("SpectrumMin", EMPTY_INT(), mustBePositive, "The number of the first spectrum to read.");
256 declareProperty("SpectrumMax", EMPTY_INT(), mustBePositive, "The number of the last spectrum to read.");
257 declareProperty(std::make_unique<ArrayProperty<int32_t>>("SpectrumList"),
258 "A comma-separated list of individual spectra to read.");
259
260 declareProperty(std::make_unique<PropertyWithValue<bool>>("MetaDataOnly", false, Direction::Input),
261 "If true, only the meta data and sample logs will be loaded.");
262
263 declareProperty(std::make_unique<PropertyWithValue<bool>>("LoadLogs", true, Direction::Input),
264 "Load only the Sample/DAS logs from the file (default True).");
265
266 declareProperty(std::make_unique<PropertyWithValue<bool>>("LoadAllLogs", false, Direction::Input),
267 "Load all the logs from the nxs, without checking or processing them; if checked, LoadLogs will be "
268 "ignored; use with caution");
269
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.");
275
276 declareProperty(std::make_unique<PropertyWithValue<bool>>("LoadNexusInstrumentXML", true, Direction::Input),
277 "Reads the embedded Instrument XML from the NeXus file "
278 "(optional, default True). ");
279
280 declareProperty("NumberOfBins", 500, mustBePositive,
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.");
284
285 // Flexible log loading
286 declareProperty(std::make_unique<PropertyWithValue<std::vector<std::string>>>("AllowList", std::vector<std::string>(),
288 "If specified, only these logs will be loaded from the file (each "
289 "separated by a space).");
290 declareProperty(std::make_unique<PropertyWithValue<std::vector<std::string>>>("BlockList", std::vector<std::string>(),
292 "If specified, these logs will NOT be loaded from the file (each "
293 "separated by a space).");
294}
295
296std::map<std::string, std::string> LoadEventNexus::validateInputs() {
297
298 // Warn deprecated experimental feature, but do not throw error
299 if (!isDefault("LoadType")) {
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.";
302 }
303 setProperty("LoadType", "Default");
304
305 std::map<std::string, std::string> result;
306
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";
311 }
312
313 return result;
314}
315
316//----------------------------------------------------------------------------------------------
320 std::string nxentryProperty = getProperty("NXentryName");
321 if (!nxentryProperty.empty()) {
322 m_top_entry_name = nxentryProperty;
323 return;
324 }
325
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);
332 break;
333 }
334 }
335 m_top_entry_name = std::move(firstGoodEntry);
336 if (m_top_entry_name.empty()) {
337 g_log.error() << "Unable to determine name of top level NXentry - assuming \"entry\".\n";
338 m_top_entry_name = "entry";
339 }
340}
341
342template <typename T> void LoadEventNexus::filterDuringPause(T workspace) {
343 try {
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.");
349
350 auto filter = createChildAlgorithm("FilterByLogValue");
351 filter->setProperty("InputWorkspace", workspace);
352 filter->setProperty("OutputWorkspace", workspace);
353 filter->setProperty("LogName", "pause");
354 // The log value is set to 1 when the run is paused, 0 otherwise.
355 filter->setProperty("MinimumValue", 0.0);
356 filter->setProperty("MaximumValue", 0.0);
357 filter->setProperty("LogBoundary", "Left");
358 filter->execute();
359 }
360 } catch (Exception::NotFoundError &) {
361 // No "pause" log, just carry on
362 }
363}
364
365template <>
366void LoadEventNexus::filterDuringPause<EventWorkspaceCollection_sptr>(EventWorkspaceCollection_sptr workspace) {
367 // We provide a function pointer to the filter method of the object
368 using std::placeholders::_1;
369 auto func = std::bind(&LoadEventNexus::filterDuringPause<MatrixWorkspace_sptr>, this, _1);
370 workspace->applyFilterInPlace(func);
371}
372
373//-----------------------------------------------------------------------------
378template <typename T>
379T LoadEventNexus::filterEventsByTime(T workspace, Mantid::Types::Core::DateAndTime &startTime,
380 Mantid::Types::Core::DateAndTime &stopTime) {
381 auto filterByTime = createChildAlgorithm("FilterByTime");
382 g_log.information("Filtering events by time...");
383 filterByTime->setProperty("InputWorkspace", workspace);
384 // sample log already filtered by time so use absolute times to be safe
385 filterByTime->setProperty("AbsoluteStartTime", startTime.toISO8601String());
386 filterByTime->setProperty("AbsoluteStopTime", stopTime.toISO8601String());
387 filterByTime->execute();
388 return filterByTime->getProperty("OutputWorkspace");
389}
390
391template <>
393LoadEventNexus::filterEventsByTime<EventWorkspaceCollection_sptr>(EventWorkspaceCollection_sptr workspace,
394 Mantid::Types::Core::DateAndTime &startTime,
395 Mantid::Types::Core::DateAndTime &stopTime) {
396 // We provide a function pointer to the filter method of the object
397 using std::placeholders::_1;
398 auto func = std::bind(&LoadEventNexus::filterEventsByTime<EventWorkspace_sptr>, this, _1, startTime, stopTime);
399 workspace->applyFilter(func);
400 return workspace;
401}
402
403//------------------------------------------------------------------------------------------------
408 // Retrieve the filename from the properties
409 m_filename = getPropertyValue("Filename");
410
411 compressEvents = !isDefault(PropertyNames::COMPRESS_TOL);
412 compressTolerance = getProperty(PropertyNames::COMPRESS_TOL);
413 if (compressEvents) {
414 BINMODE mode = getPropertyValue(PropertyNames::COMPRESS_MODE);
415 if (mode == BinningMode::LINEAR)
417 else if (mode == BinningMode::LOGARITHMIC)
418 compressTolerance = -1. * std::fabs(compressTolerance);
419 }
420
421 loadlogs = getProperty("LoadLogs");
422
423 // Check to see if the monitors need to be loaded later
424 bool load_monitors = this->getProperty("LoadMonitors");
425
426 // this must make absolutely sure that m_file is a valid (and open)
427 // Nexus::File object
429
431
432 // Initialize progress reporting.
433 int reports = 3;
434 if (load_monitors)
435 reports++;
436 Progress prog(this, 0.0, 0.3, reports);
437
438 // Load the detector events
439 m_ws = std::make_shared<EventWorkspaceCollection>(); // Algorithm currently
440 // relies on an
441
442 // object-level workspace ptr
443 loadEvents(&prog, false); // Do not load monitor blocks
444
445 if (discarded_events > 0) {
447 << " events were encountered coming from pixels which "
448 "are not in the Instrument Definition File."
449 "These events were discarded.\n";
450 }
451
452 // If the run was paused at any point, filter out those events (SNS only, I
453 // think)
454 filterDuringPause(m_ws->getSingleHeldWorkspace());
455
456 // add filename
457 m_ws->mutableRun().addProperty("Filename", m_filename);
458 // Save output
459 this->setProperty("OutputWorkspace", m_ws->combinedWorkspace());
460
461 // close the file since LoadNexusMonitors will take care of its own file
462 // handle
463 m_file->close();
464
465 // Load the monitors with child algorithm 'LoadNexusMonitors'
466 if (load_monitors) {
467 prog.report("Loading monitors");
468 this->runLoadMonitors();
469 }
470}
471
472std::pair<DateAndTime, DateAndTime> firstLastPulseTimes(Nexus::File &file, Kernel::Logger &logger) {
473 file.openData("event_time_zero");
474 DateAndTime offset;
475 // According to the Nexus standard, if the offset is not present, it implies
476 // the offset is and absolute timestamp, which is relative to the start of
477 // Unix epoch (https://manual.nexusformat.org/classes/base_classes/NXlog.html)
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");
482 } else {
483 std::string isooffset; // ISO8601 offset
484 file.getAttr("offset", isooffset);
485 offset = DateAndTime(isooffset);
486 }
487 std::string units; // time units
488 if (file.hasAttr("units"))
489 file.getAttr("units", units);
490 // Read in the pulse times
491 auto pulse_times = Nexus::IOHelper::readNexusVector<double>(file, "event_time_zero");
492 // Remember to close the entry
493 file.closeData();
494 if (pulse_times.empty()) {
495 throw std::invalid_argument("Cannot find run start; event_time_zero contains no pulse times");
496 }
497 // Convert to seconds
498 auto conv = Kernel::Units::timeConversionValue(units, "s");
499 return std::make_pair(DateAndTime(pulse_times.front() * conv, 0.0) + offset.totalNanoseconds(),
500 DateAndTime(pulse_times.back() * conv, 0.0) + offset.totalNanoseconds());
501} // namespace DataHandling
502
515std::size_t numEvents(Nexus::File &file, bool &hasTotalCounts, bool &oldNeXusFileNames, const std::string &prefix,
516 const Nexus::NexusDescriptor &descriptor) {
517 // try getting the value of total_counts
518 if (hasTotalCounts) {
519 hasTotalCounts = false;
520 if (descriptor.isEntry(prefix + "/total_counts")) {
521 try {
522 file.openData("total_counts");
523 auto info = file.getInfo();
524 file.closeData();
525 if (info.type == NXnumtype::UINT64) {
526 uint64_t eventCount;
527 file.readData("total_counts", eventCount);
528 hasTotalCounts = true;
529 return eventCount;
530 }
531 } catch (Nexus::Exception const &) {
532 }
533 }
534 }
535
536 // just get the length of the event pixel ids
537 try {
538 if (oldNeXusFileNames)
539 file.openData("event_pixel_id");
540 else
541 file.openData("event_id");
542 } catch (Nexus::Exception const &) {
543 // Older files (before Nov 5, 2010) used this field.
544 try {
545 file.openData("event_pixel_id");
546 oldNeXusFileNames = true;
547 } catch (Nexus::Exception const &) {
548 // Some groups have neither indicating there are not events here
549 return 0;
550 }
551 }
552
553 size_t numEvents = static_cast<std::size_t>(file.getInfo().dims[0]);
554 file.closeData();
555 return numEvents;
556}
557
571template <typename T>
572std::shared_ptr<BankPulseTimes>
573LoadEventNexus::runLoadNexusLogs(const std::string &nexusfilename, T localWorkspace, API::Algorithm &alg,
574 bool returnpulsetimes, int &nPeriods,
575 std::unique_ptr<const TimeSeriesProperty<int>> &periodLog) {
576 // --------------------- Load DAS Logs -----------------
577 // The pulse times will be empty if not specified in the DAS logs.
578 // BankPulseTimes * out = NULL;
579 std::shared_ptr<BankPulseTimes> out;
580 auto loadLogs = alg.createChildAlgorithm("LoadNexusLogs");
581
582 // Now execute the Child Algorithm. Catch and log any error, but don't stop.
583 try {
584 alg.getLogger().information() << "Loading logs from NeXus file..."
585 << "\n";
586 loadLogs->setPropertyValue("Filename", nexusfilename);
587 loadLogs->setProperty<API::MatrixWorkspace_sptr>("Workspace", localWorkspace);
588 try {
589 loadLogs->setPropertyValue("NXentryName", alg.getPropertyValue("NXentryName"));
590 } catch (...) {
591 }
592
593 loadLogs->execute();
594
595 const Run &run = localWorkspace->run();
596 // Get the number of periods
597 if (run.hasProperty("nperiods")) {
598 nPeriods = run.getPropertyValueAsType<int>("nperiods");
599 }
600 // Get the period log. Map of DateAndTime to Period int values.
601 if (run.hasProperty("period_log")) {
602 const auto *temp = run.getProperty("period_log");
603 // Check for corrupted period logs
604 std::string status = "";
605 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(dynamic_cast<TimeSeriesProperty<int> *>(temp->clone()));
606 nPeriods = checkForCorruptedPeriods(std::move(tempPeriodLog), periodLog, nPeriods, nexusfilename, status);
607 if (!status.empty())
608 alg.getLogger().warning(status);
609 }
610
611 // If successful, we can try to load the pulse times
612 std::vector<Types::Core::DateAndTime> temp;
613 if (localWorkspace->run().hasProperty("proton_charge")) {
614 const auto *log =
615 dynamic_cast<Kernel::TimeSeriesProperty<double> *>(localWorkspace->mutableRun().getProperty("proton_charge"));
616 if (log)
617 temp = log->timesAsVector();
618 }
619 if (returnpulsetimes)
620 out = std::make_shared<BankPulseTimes>(temp);
621
622 // Use the first pulse as the run_start time.
623 if (!temp.empty()) {
624 if (temp[0] < Types::Core::DateAndTime("1991-01-01T00:00:00"))
625 alg.getLogger().warning() << "Found entries in the proton_charge "
626 "sample log with invalid pulse time!\n";
627
628 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
629 // add the start of the run as a ISO8601 date/time string. The start =
630 // first non-zero time.
631 // (this is used in LoadInstrument to find the right instrument file to
632 // use).
633 localWorkspace->mutableRun().addProperty("run_start", run_start.toISO8601String(), true);
634 } else if (run.hasProperty("start_time")) {
635 localWorkspace->mutableRun().addProperty("run_start", run.getProperty("start_time")->value(), true);
636 } else {
637 alg.getLogger().warning() << "Empty proton_charge sample log. You will "
638 "not be able to filter by time.\n";
639 }
641 try {
644 localWorkspace->mutableRun().setGoniometer(gm, true);
645 } catch (std::runtime_error &) {
646 }
647 } catch (const InvalidLogPeriods &) {
648 // Rethrow so LoadEventNexus fails.
649 // If we don't, Mantid will crash.
650 throw;
651 } catch (...) {
652 alg.getLogger().error() << "Error while loading Logs from SNS Nexus. Some "
653 "sample logs may be missing."
654 << "\n";
655 return out;
656 }
657 return out;
658}
659
675template <typename T>
676std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs(
677 const std::string &nexusfilename, T localWorkspace, API::Algorithm &alg, bool returnpulsetimes, int &nPeriods,
678 std::unique_ptr<const TimeSeriesProperty<int>> &periodLog, const std::vector<std::string> &allow_list,
679 const std::vector<std::string> &block_list) {
680 // --------------------- Load DAS Logs -----------------
681 // The pulse times will be empty if not specified in the DAS logs.
682 // BankPulseTimes * out = NULL;
683 std::shared_ptr<BankPulseTimes> out;
684 auto loadLogs = alg.createChildAlgorithm("LoadNexusLogs");
685
686 // Now execute the Child Algorithm. Catch and log any error, but don't stop.
687 try {
688 alg.getLogger().information() << "Loading logs from NeXus file..."
689 << "\n";
690 loadLogs->setPropertyValue("Filename", nexusfilename);
691 loadLogs->setProperty<API::MatrixWorkspace_sptr>("Workspace", localWorkspace);
692 loadLogs->setProperty<std::vector<std::string>>("AllowList", allow_list);
693 loadLogs->setProperty<std::vector<std::string>>("BlockList", block_list);
694
695 try {
696 loadLogs->setPropertyValue("NXentryName", alg.getPropertyValue("NXentryName"));
697 } catch (...) {
698 }
699
700 loadLogs->execute();
701
702 const Run &run = localWorkspace->run();
703 // Get the number of periods
704 if (run.hasProperty("nperiods")) {
705 nPeriods = run.getPropertyValueAsType<int>("nperiods");
706 }
707 // Get the period log. Map of DateAndTime to Period int values.
708 if (run.hasProperty("period_log")) {
709 auto *temp = run.getProperty("period_log");
710 std::string status = "";
711 // Check for corrupted period logs
712 std::unique_ptr<TimeSeriesProperty<int>> tempPeriodLog(dynamic_cast<TimeSeriesProperty<int> *>(temp->clone()));
713 nPeriods = checkForCorruptedPeriods(std::move(tempPeriodLog), periodLog, nPeriods, nexusfilename, status);
714 if (!status.empty())
715 alg.getLogger().warning(status);
716 }
717
718 // If successful, we can try to load the pulse times
719 std::vector<Types::Core::DateAndTime> temp;
720 if (localWorkspace->run().hasProperty("proton_charge")) {
721 auto *log =
722 dynamic_cast<Kernel::TimeSeriesProperty<double> *>(localWorkspace->mutableRun().getProperty("proton_charge"));
723 if (log)
724 temp = log->timesAsVector();
725 }
726 if (returnpulsetimes)
727 out = std::make_shared<BankPulseTimes>(temp);
728
729 // Use the first pulse as the run_start time.
730 if (!temp.empty()) {
731 if (temp[0] < Types::Core::DateAndTime("1991-01-01T00:00:00"))
732 alg.getLogger().warning() << "Found entries in the proton_charge "
733 "sample log with invalid pulse time!\n";
734
735 Types::Core::DateAndTime run_start = localWorkspace->getFirstPulseTime();
736 // add the start of the run as a ISO8601 date/time string. The start =
737 // first non-zero time.
738 // (this is used in LoadInstrument to find the right instrument file to
739 // use).
740 localWorkspace->mutableRun().addProperty("run_start", run_start.toISO8601String(), true);
741 } else {
742 alg.getLogger().warning() << "Empty proton_charge sample log. You will "
743 "not be able to filter by time.\n";
744 }
746 try {
749 localWorkspace->mutableRun().setGoniometer(gm, true);
750 } catch (std::runtime_error &) {
751 }
752 } catch (const InvalidLogPeriods &) {
753 // Rethrow so LoadEventNexus fails.
754 // If we don't, Mantid will crash.
755 throw;
756 } catch (...) {
757 alg.getLogger().error() << "Error while loading Logs from SNS Nexus. Some "
758 "sample logs may be missing."
759 << "\n";
760 return out;
761 }
762 return out;
763}
764
780 std::unique_ptr<const TimeSeriesProperty<int>> &periodLog,
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;
786 status = "";
787
788 // Check for historic files
789 if (nPeriodsInLog == 0 && nPeriods == 1) {
790 // "modernize" the local copy here by making period_log
791 // a vector of 1s
792 const std::vector<int> newValues(tempPeriodLog->realSize(), 1);
793 const auto times = tempPeriodLog->timesAsVector();
794 periodLog.reset(new const TimeSeriesProperty<int>("period_log", times, newValues));
795 numberOfValidPeriods = 1;
796 } else if (nPeriodsInLog < nPeriods) {
797 status = boost::str(
798 boost::format(
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) {
802 // Sanity check here that period_log only contains period numbers up to
803 // nperiods. These values can be different due to instrument noise, and
804 // cause undescriptive crashes if not caught.
805 // We throw here to make it clear
806 // that the file is corrupted and must be manually assessed.
807 const auto msg = "File " + nexusfilename +
808 " has been corrupted. The log framelog/period_log/value "
809 "contains " +
810 std::to_string(nPeriodsInLog) + " periods, but periods/number contains " +
811 std::to_string(nPeriods) + ". This file should be manually inspected and corrected.";
812 throw InvalidLogPeriods(msg);
813 } else {
814 // periodLog should point to a copy of the period logs
815 periodLog = std::make_unique<const TimeSeriesProperty<int>>(*tempPeriodLog);
816 tempPeriodLog.reset();
817 }
818 return numberOfValidPeriods;
819}
820
835template <>
836std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
837 const std::string &nexusfilename, EventWorkspaceCollection_sptr localWorkspace, API::Algorithm &alg,
838 bool returnpulsetimes, int &nPeriods, std::unique_ptr<const TimeSeriesProperty<int>> &periodLog) {
839 auto ws = localWorkspace->getSingleHeldWorkspace();
840 auto ret = runLoadNexusLogs<MatrixWorkspace_sptr>(nexusfilename, ws, alg, returnpulsetimes, nPeriods, periodLog);
841 return ret;
842}
843
860template <>
861std::shared_ptr<BankPulseTimes> LoadEventNexus::runLoadNexusLogs<EventWorkspaceCollection_sptr>(
862 const std::string &nexusfilename, EventWorkspaceCollection_sptr localWorkspace, API::Algorithm &alg,
863 bool returnpulsetimes, int &nPeriods, std::unique_ptr<const TimeSeriesProperty<int>> &periodLog,
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);
868 return ret;
869}
870
871//-----------------------------------------------------------------------------
880void LoadEventNexus::loadEvents(API::Progress *const prog, const bool monitors) {
881 bool metaDataOnly = getProperty("MetaDataOnly");
882
883 // Get the time filters
884 setTimeFilters(monitors);
885
886 // Get the log filter if provided
887 std::vector<std::string> allow_list = getProperty("AllowList"); // if not empty, only these logs will be loaded
888 std::vector<std::string> block_list = getProperty("BlockList"); // if not empty, these logs won't be loaded
889
890 // The run_start will be loaded from the pulse times.
891 DateAndTime run_start(0, 0);
892 bool takeTimesFromEvents = false;
893 // Initialize the counter of bad TOFs
894 bad_tofs = 0;
895 int nPeriods = 1;
896 auto periodLog = std::make_unique<const TimeSeriesProperty<int>>("period_log");
897
898 bool loadAllLogs = getProperty("LoadAllLogs"); // load all logs, not just DAS logs.
899
900 if (loadlogs) {
901 if (!loadAllLogs) {
902 prog->doReport("Loading DAS logs");
903
904 if (allow_list.empty() && block_list.empty()) {
906 runLoadNexusLogs<EventWorkspaceCollection_sptr>(m_filename, m_ws, *this, true, nPeriods, periodLog);
907 } else {
908 m_allBanksPulseTimes = runLoadNexusLogs<EventWorkspaceCollection_sptr>(m_filename, m_ws, *this, true, nPeriods,
909 periodLog, allow_list, block_list);
910 }
911
912 try {
913 run_start = m_ws->getFirstPulseTime();
915 /*
916 This is added to (a) support legacy behaviour of continuing to take
917 times from the proto_charge log, but (b) allowing a fall back of
918 getting run start and end from actual pulse times within the
919 NXevent_data group. Note that the latter is better Nexus compliant.
920 */
921 takeTimesFromEvents = true;
922 }
923 } else {
924 prog->doReport("Loading all logs");
925 try {
926 // Open NeXus file
927 Nexus::File nxHandle(m_filename, NXaccess::READ);
928 LoadHelper::addNexusFieldsToWsRun(nxHandle, m_ws->mutableRun(), "", true);
929 } catch (Nexus::Exception const &e) {
930 g_log.debug() << "Failed to open nexus file \"" << m_filename << "\" in read mode: " << e.what() << "\n";
931 }
932 }
933 } else {
934 g_log.information() << "Skipping the loading of sample logs!\n"
935 << "Reading the start time directly from /" << m_top_entry_name << "/start_time\n";
936 // start_time is read and set
937 m_file->openAddress("/");
938 m_file->openGroup(m_top_entry_name, "NXentry");
939 std::string tmp;
940 m_file->readData("start_time", tmp);
941 m_file->closeGroup();
942 run_start = createFromSanitizedISO8601(tmp);
943 m_ws->mutableRun().addProperty("run_start", run_start.toISO8601String(), true);
944 }
945 // set more properties on the workspace
946 const std::shared_ptr<Nexus::NexusDescriptor> descriptor = getFileInfo();
947
948 try {
949 // this is a static method that is why it is passing the
950 // file object and the file path
951
952 loadEntryMetadata<EventWorkspaceCollection_sptr>(m_filename, m_ws, m_top_entry_name, *descriptor);
953 } catch (std::runtime_error &e) {
954 // Missing metadata is not a fatal error. Log and go on with your life
955 g_log.error() << "Error loading metadata: " << e.what() << '\n';
956 }
957
958 m_ws->setNPeriods(static_cast<size_t>(nPeriods),
959 periodLog); // This is how many workspaces we are going to make.
960
961 // Make sure you have a non-NULL m_allBanksPulseTimes
962 if (m_allBanksPulseTimes == nullptr) {
963 std::vector<DateAndTime> temp;
964 m_allBanksPulseTimes = std::make_shared<BankPulseTimes>(temp);
965 }
966
967 if (!m_ws->getInstrument() || !m_instrument_loaded_correctly) {
968 // Load the instrument (if not loaded before)
969 prog->report("Loading instrument");
970 // Note that closing an re-opening the file is needed here for loading
971 // instruments directly from the nexus file containing the event data.
972 // This may not be needed in the future if both LoadEventNexus and
973 // LoadInstrument are made to use the same Nexus/HDF5 library
974 m_file->close();
976
978 throw std::runtime_error("Instrument was not initialized correctly! Loading cannot continue.");
979 // reopen file
981 }
982
983 // top level file information
984 m_file->openAddress("/");
985 // Start with the base entry
986 m_file->openGroup(m_top_entry_name, "NXentry");
987
988 // Now we want to go through all the bankN_event entries
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();
995
996 const std::map<std::string, std::set<std::string>> &allEntries = descriptor->getAllEntries();
997
998 auto itClassEntries = allEntries.find(classType);
999
1000 if (itClassEntries != allEntries.end()) {
1001
1002 const std::set<std::string> &classEntries = itClassEntries->second;
1003 const std::regex classRegex("(/" + m_top_entry_name + "/)([^/]*)");
1004 std::smatch groups;
1005
1006 for (const std::string &classEntry : classEntries) {
1007
1008 if (std::regex_match(classEntry, groups, classRegex)) {
1009 const std::string entry_name(groups[2].str());
1010
1011 // skip entries with junk data
1012 if (entry_name == "bank_error_events" || entry_name == "bank_unmapped_events")
1013 continue;
1014
1015 m_file->openGroup(entry_name, classType);
1016
1017 // get the number of events
1018 const std::string prefix = "/" + m_top_entry_name + "/" + entry_name;
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);
1023
1024 if (takeTimesFromEvents && num > 0) {
1025 /* If we are here, we are loading logs, but have failed to establish
1026 * the run_start from the proton_charge log. We are going to get this
1027 * from our event_time_zero instead
1028 */
1029 auto localFirstLast = firstLastPulseTimes(*m_file, this->g_log);
1030 firstPulseT = std::min(firstPulseT, localFirstLast.first);
1031 }
1032
1033 // Look for weights in simulated file
1034 const std::string absoluteEventWeightName = prefix + "/event_weight";
1035 haveWeights = descriptor->isEntry(absoluteEventWeightName);
1036 m_file->closeGroup();
1037 }
1038 }
1039 }
1040
1041 if (takeTimesFromEvents)
1042 run_start = firstPulseT;
1043
1045
1046 // Close the 'top entry' group (raw_data_1 for NexusProcessed, etc.)
1047 m_file->closeGroup();
1048
1049 // Delete the output workspace name if it existed
1050 std::string outName = getPropertyValue("OutputWorkspace");
1051 if (AnalysisDataService::Instance().doesExist(outName))
1052 AnalysisDataService::Instance().remove(outName);
1053
1054 // --------------------------- Time filtering
1055 // ------------------------------------
1056 double filter_time_start_sec, filter_time_stop_sec;
1057 filter_time_start_sec = getProperty("FilterByTimeStart");
1058 filter_time_stop_sec = getProperty("FilterByTimeStop");
1059
1060 // Default to ALL pulse times
1061 filter_time_start = Types::Core::DateAndTime::minimum();
1062 filter_time_stop = Types::Core::DateAndTime::maximum();
1063
1064 if (m_allBanksPulseTimes->numberOfPulses() > 0) {
1065 // If not specified, use the limits of doubles. Otherwise, convert from
1066 // seconds to absolute PulseTime
1067 if (filter_time_start_sec != EMPTY_DBL()) {
1068 filter_time_start = run_start + filter_time_start_sec;
1069 m_is_time_filtered = true;
1070 }
1071
1072 if (filter_time_stop_sec != EMPTY_DBL()) {
1073 filter_time_stop = run_start + filter_time_stop_sec;
1074 m_is_time_filtered = true;
1075 }
1076
1077 // Silly values?
1079 std::string msg = "Your ";
1080 if (monitors)
1081 msg += "monitor ";
1082 msg += "filter for time's Stop value is smaller than the Start value.";
1083 throw std::invalid_argument(msg);
1084 }
1085 }
1086
1087 // setup filter bad pulses
1088 filter_bad_pulses = !isDefault(PropertyNames::BAD_PULSES_CUTOFF);
1089
1090 if (filter_bad_pulses) {
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));
1094
1095 const auto *pcharge_log =
1096 dynamic_cast<Kernel::TimeSeriesProperty<double> *>(m_ws->run().getLogData(LOG_CHARGE_NAME));
1097 bad_pulses_timeroi = std::make_shared<TimeROI>(
1098 pcharge_log->makeFilterByValue(min_pcharge, max_pcharge, false, TimeInterval(0, 1), 0., true));
1099 }
1100
1101 if (metaDataOnly) {
1102 // Now, create a default X-vector for histogramming, with just 2 bins.
1103 auto axis = HistogramData::BinEdges{1, static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1 - 1};
1104 // Set the binning axis using this.
1105 m_ws->setAllX(axis);
1106
1107 createSpectraMapping(m_filename, monitors, std::vector<std::string>());
1108 return;
1109 }
1110
1111 // --------- Loading only one bank ? ----------------------------------
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"; });
1119
1120 // check that all of the requested banks are in the file
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; });
1125 });
1126 if (invalidBank != eventedBanks.cend()) {
1127 throw std::invalid_argument("No entry named '" + *invalidBank + "' was found in the .NXS file.");
1128 }
1129
1130 // change the number of banks to load
1131 bankNames.assign(eventedBanks.cbegin(), eventedBanks.cend());
1132
1133 // TODO this equally weights the banks
1134 bankNumEvents.assign(someBanks.size(), 1);
1135
1136 if (!SingleBankPixelsOnly)
1137 someBanks.clear(); // Marker to load all pixels
1138 }
1139
1140 prog->report("Initializing all pixels");
1141
1142 // Remove unused banks if parameter is set
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());
1147 if (unused == 1)
1148 deleteBanks(m_ws, bankNames);
1149 }
1150 }
1151 //----------------- Pad Empty Pixels -------------------------------
1152 createSpectraMapping(m_filename, monitors, someBanks);
1153
1154 // Set all (empty) event lists as sorted by pulse time. That way, calling
1155 // SortEvents will not try to sort these empty lists.
1156 for (size_t i = 0; i < m_ws->getNumberHistograms(); i++)
1157 m_ws->getSpectrum(i).setSortOrder(DataObjects::PULSETIME_SORT);
1158
1159 // Count the limits to time of flight
1160 shortest_tof = static_cast<double>(std::numeric_limits<uint32_t>::max()) * 0.1;
1161 longest_tof = 0.;
1162
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();
1167 DefaultEventLoader::load(this, *m_ws, haveWeights, event_id_is_spec, bankNames, periodLog->valuesAsVector(),
1168 classType, bankNumEvents, oldNeXusFileNames, precount, chunk, totalChunks);
1169 addTimer("loadEvents", startTime, std::chrono::high_resolution_clock::now());
1170
1171 // Info reporting
1172 const std::size_t eventsLoaded = m_ws->getNumberEvents();
1173 g_log.information() << "Read " << eventsLoaded << " events"
1174 << ". Shortest TOF: " << shortest_tof << " microsec; longest TOF: " << longest_tof
1175 << " microsec.\n";
1176
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";
1180 if (bad_tofs > 0)
1181 g_log.warning() << "Found " << bad_tofs
1182 << " events with TOF > 2e8. This "
1183 "may indicate errors in the raw "
1184 "TOF data.\n";
1185
1186 // Use T0 offset from TOPAZ Parameter file if it exists
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();
1191 if (mT0 != 0.0) {
1192 auto numHistograms = static_cast<int64_t>(m_ws->getNumberHistograms());
1194 for (int64_t i = 0; i < numHistograms; ++i) {
1196 // Do the offsetting
1197 m_ws->getSpectrum(i).addTof(mT0);
1199 }
1201 // set T0 in the run parameters
1202 API::Run &run = m_ws->mutableRun();
1203 run.addProperty<double>("T0", mT0, true);
1204 }
1205 }
1206 }
1207 // Now, create a default X-vector for histogramming, with just 2 bins.
1208 if (eventsLoaded > 0) {
1209 int nBins = getProperty("NumberOfBins");
1210 auto binEdgesVec = std::vector<double>(nBins + 1);
1211 binEdgesVec[0] = shortest_tof; // left edge is inclusive
1212 binEdgesVec[nBins] = longest_tof + 1; // right edge is exclusive
1213 double binStep = (binEdgesVec[nBins] - binEdgesVec[0]) / nBins;
1214 for (int binIndex = 1; binIndex < nBins; binIndex++) {
1215 binEdgesVec[binIndex] = binEdgesVec[0] + (binStep * binIndex);
1216 }
1217 m_ws->setAllX(HistogramData::BinEdges{binEdgesVec});
1218 } else
1219 m_ws->setAllX(HistogramData::BinEdges{0.0, 1.0});
1220
1221 // if there is time_of_flight load it
1222 adjustTimeOfFlightISISLegacy(*m_file, m_ws, m_top_entry_name, classType, descriptor.get());
1223
1224 if (m_is_time_filtered) {
1225 // events were filtered during read
1226 // filter the logs the same way FilterByTime does
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();
1235 }
1236}
1237
1238//-----------------------------------------------------------------------------
1249template <>
1250bool LoadEventNexus::runLoadIDFFromNexus<EventWorkspaceCollection_sptr>(const std::string &nexusfilename,
1251 EventWorkspaceCollection_sptr localWorkspace,
1252 const std::string &top_entry_name,
1253 Algorithm *alg) {
1254 auto ws = localWorkspace->getSingleHeldWorkspace();
1255 auto hasLoaded = runLoadIDFFromNexus<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg);
1256 localWorkspace->setInstrument(ws->getInstrument());
1257 return hasLoaded;
1258}
1259
1265 std::string instrumentName;
1266 try {
1267 hFile.openGroup("isis_vms_compat", "IXvms");
1268 } catch (std::runtime_error &) {
1269 return instrumentName;
1270 }
1271 try {
1272 hFile.openData("NAME");
1273 } catch (std::runtime_error &) {
1274 hFile.closeGroup();
1275 return instrumentName;
1276 }
1277
1278 instrumentName = hFile.getStrData();
1279 hFile.closeData();
1280 hFile.closeGroup();
1281
1282 return instrumentName;
1283}
1284
1285//-----------------------------------------------------------------------------
1298template <>
1299bool LoadEventNexus::runLoadInstrument<EventWorkspaceCollection_sptr>(const std::string &nexusfilename,
1300 EventWorkspaceCollection_sptr localWorkspace,
1301 const std::string &top_entry_name, Algorithm *alg,
1302 const Nexus::NexusDescriptor *descriptor) {
1303 auto ws = localWorkspace->getSingleHeldWorkspace();
1304 auto hasLoaded = runLoadInstrument<MatrixWorkspace_sptr>(nexusfilename, ws, top_entry_name, alg, descriptor);
1305 localWorkspace->setInstrument(ws->getInstrument());
1306 return hasLoaded;
1307}
1308
1309//-----------------------------------------------------------------------------
1316 const std::vector<std::string> &bankNames) {
1317 Instrument_sptr inst = std::const_pointer_cast<Instrument>(workspace->getInstrument()->baseInstrument());
1318 // Build a list of Rectangular Detectors
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;
1324
1325 det = std::dynamic_pointer_cast<RectangularDetector>((*inst)[i]);
1326 if (det) {
1327 detList.emplace_back(det);
1328 } else {
1329 // Also, look in the first sub-level for RectangularDetectors (e.g.
1330 // PG3). We are not doing a full recursive search since that will be
1331 // very long for lots of pixels.
1332 assem = std::dynamic_pointer_cast<ICompAssembly>((*inst)[i]);
1333 if (assem) {
1334 for (int j = 0; j < assem->nelements(); j++) {
1335 det = std::dynamic_pointer_cast<RectangularDetector>((*assem)[j]);
1336 if (det) {
1337 detList.emplace_back(det);
1338
1339 } else {
1340 // Also, look in the second sub-level for RectangularDetectors
1341 // (e.g. PG3). We are not doing a full recursive search since that
1342 // will be very long for lots of pixels.
1343 assem2 = std::dynamic_pointer_cast<ICompAssembly>((*assem)[j]);
1344 if (assem2) {
1345 for (int k = 0; k < assem2->nelements(); k++) {
1346 det = std::dynamic_pointer_cast<RectangularDetector>((*assem2)[k]);
1347 if (det) {
1348 detList.emplace_back(det);
1349 }
1350 }
1351 }
1352 }
1353 }
1354 }
1355 }
1356 }
1357 if (detList.empty())
1358 return;
1359 for (auto &det : detList) {
1360 bool keep = false;
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))
1365 keep = true;
1366 if (keep)
1367 break;
1368 }
1369 if (!keep) {
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);
1380
1381 for (auto &row : grandchildren) {
1382 auto *d = dynamic_cast<Detector *>(const_cast<IComponent *>(row.get()));
1383 if (d)
1384 inst->removeDetector(d);
1385 }
1386 }
1387 auto *comp = dynamic_cast<IComponent *>(det.get());
1388 inst->remove(comp);
1389 }
1390 }
1391}
1392//-----------------------------------------------------------------------------
1401void LoadEventNexus::createSpectraMapping(const std::string &nxsfile, const bool monitorsOnly,
1402 const std::vector<std::string> &bankNames) {
1403 LoadEventNexusIndexSetup indexSetup(m_ws->getSingleHeldWorkspace(), getProperty("SpectrumMin"),
1404 getProperty("SpectrumMax"), getProperty("SpectrumList"));
1405 if (!monitorsOnly && !bankNames.empty()) {
1406 if (!isDefault("SpectrumMin") || !isDefault("SpectrumMax") || !isDefault("SpectrumList"))
1407 g_log.warning() << "Spectrum min/max/list selection ignored when "
1408 "`SingleBankPixelsOnly` is enabled\n";
1409 m_ws->setIndexInfo(indexSetup.makeIndexInfo(bankNames));
1410 g_log.debug() << "Populated spectra map for select banks\n";
1411 } else if (auto mapping = loadISISVMSSpectraMapping(m_top_entry_name)) {
1412 if (monitorsOnly) {
1413 g_log.debug() << "Loading only monitor spectra from " << nxsfile << "\n";
1414 } else {
1415 g_log.debug() << "Loading only detector spectra from " << nxsfile << "\n";
1416 }
1417 m_ws->setIndexInfo(indexSetup.makeIndexInfo(*mapping, monitorsOnly));
1418 } else {
1419 g_log.debug() << "No custom spectra mapping found, continuing with default "
1420 "1:1 mapping of spectrum:detectorID\n";
1421 m_ws->setIndexInfo(indexSetup.makeIndexInfo());
1422 g_log.debug() << "Populated 1:1 spectra map for the whole instrument \n";
1423 }
1424 std::tie(m_specMin, m_specMax) = indexSetup.eventIDLimits();
1425}
1426
1427//-----------------------------------------------------------------------------
1434 std::string mon_wsname = this->getProperty("OutputWorkspace");
1435 mon_wsname.append("_monitors");
1436
1437 auto loadMonitors = createChildAlgorithm("LoadNexusMonitors");
1438 g_log.information("Loading monitors from NeXus file...");
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");
1446 // create the output workspace property on the fly
1447 this->declareProperty(
1448 std::make_unique<WorkspaceProperty<Workspace>>("MonitorWorkspace", mon_wsname, Direction::Output),
1449 "Monitors from the Event NeXus file");
1450 this->setProperty("MonitorWorkspace", monsOut);
1451
1452 // The output will either be a group workspace or a matrix workspace
1453 MatrixWorkspace_sptr mons = std::dynamic_pointer_cast<MatrixWorkspace>(monsOut);
1454 if (mons) {
1455 // Set the internal monitor workspace pointer as well
1456 m_ws->setMonitorWorkspace(mons);
1457
1458 filterDuringPause(mons);
1459 } else {
1460 WorkspaceGroup_sptr monsGrp = std::dynamic_pointer_cast<WorkspaceGroup>(monsOut);
1461 if (monsGrp) {
1462 // declare a property for each member of the group
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"
1468 << "_" << i + 1;
1469 this->declareProperty(
1470 std::make_unique<WorkspaceProperty<MatrixWorkspace>>(ssPropName.str(), ssWsName.str(), Direction::Output),
1471 "Monitors from the Event NeXus file");
1472 this->setProperty(ssPropName.str(), monsGrp->getItem(i));
1473 }
1474 }
1475 }
1476}
1477
1478//
1488std::unique_ptr<std::pair<std::vector<int32_t>, std::vector<int32_t>>>
1489LoadEventNexus::loadISISVMSSpectraMapping(const std::string &entry_name) {
1490 const std::string vms_str = "/isis_vms_compat";
1491 try {
1492 g_log.debug() << "Attempting to load custom spectra mapping from '" << entry_name << vms_str << "'.\n";
1493 m_file->openAddress("/" + entry_name + vms_str);
1494 } catch (Nexus::Exception const &) {
1495 return nullptr; // Doesn't exist
1496 }
1497
1498 // The ISIS spectrum mapping is defined by 2 arrays in isis_vms_compat
1499 // block:
1500 // UDET - An array of detector IDs
1501 // SPEC - An array of spectrum numbers
1502 // There sizes must match. Hardware allows more than one detector ID to be
1503 // mapped to a single spectrum
1504 // and this is encoded in the SPEC/UDET arrays by repeating the spectrum
1505 // number in the array
1506 // for each mapped detector, e.g.
1507 //
1508 // 1 1001
1509 // 1 1002
1510 // 2 2001
1511 // 3 3001
1512 //
1513 // defines 3 spectra, where the first spectrum contains 2 detectors
1514
1515 // UDET
1516 m_file->openData("UDET");
1517 std::vector<int32_t> udet;
1518 m_file->getData(udet);
1519 m_file->closeData();
1520 // SPEC
1521 m_file->openData("SPEC");
1522 std::vector<int32_t> spec;
1523 m_file->getData(spec);
1524 m_file->closeData();
1525 // Go up/back. this assumes one level for entry name and a second level
1526 // for /isis_vms_compat, typically: /raw_data_1/isis_vms_compat
1527 m_file->closeGroup();
1528 m_file->closeGroup();
1529
1530 // The spec array will contain a spectrum number for each udet but the
1531 // spectrum number
1532 // may be the same for more that one detector
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());
1538 }
1539 // If mapping loaded the event ID is the spectrum number and not det ID
1540 this->event_id_is_spec = true;
1541 return std::make_unique<std::pair<std::vector<int32_t>, std::vector<int32_t>>>(std::move(spec), std::move(udet));
1542}
1543
1549void LoadEventNexus::setTimeFilters(const bool monitors) {
1550 // Get the limits to the filter
1551 std::string prefix("Filter");
1552 if (monitors)
1553 prefix += "Mon";
1554
1555 filter_tof_min = getProperty(prefix + "ByTofMin");
1556 filter_tof_max = getProperty(prefix + "ByTofMax");
1557 if ((filter_tof_min == EMPTY_DBL()) && (filter_tof_max == EMPTY_DBL())) {
1558 // Nothing specified. Include everything
1559 filter_tof_range = false;
1560 } else if ((filter_tof_min != EMPTY_DBL()) && (filter_tof_max != EMPTY_DBL())) {
1561 // Both specified. Keep these values
1562 filter_tof_range = true;
1563 } else {
1564 std::string msg("You must specify both min & max or neither TOF filters");
1565 if (monitors)
1566 msg = " for the monitors.";
1567 throw std::invalid_argument(msg);
1568 }
1569}
1570
1571//-----------------------------------------------------------------------------
1572
1588 try {
1589 file.openGroup("isis_vms_compat", "IXvms");
1590 } catch (Nexus::Exception const &) {
1591 // No problem, it just means that this entry does not exist
1592 return;
1593 }
1594
1595 // read the data
1596 try {
1597 std::vector<int32_t> spb;
1598 std::vector<float> rspb;
1599 file.readData("SPB", spb);
1600 file.readData("RSPB", rspb);
1601
1602 WS.setGeometryFlag(spb[2]); // the flag is in the third value
1603 WS.setThickness(rspb[3]);
1604 WS.setHeight(rspb[4]);
1605 WS.setWidth(rspb[5]);
1606 } catch (Nexus::Exception const &ex) {
1607 // it means that the data was not as expected, report the problem
1608 std::stringstream s;
1609 s << "Wrong definition found in isis_vms_compat :> " << ex.what();
1610 file.closeGroup();
1611 throw std::runtime_error(s.str());
1612 }
1613
1614 file.closeGroup();
1615}
1616
1623void LoadEventNexus::safeOpenFile(const std::string &fname) {
1624 try {
1625 m_file = std::make_unique<Nexus::File>(m_filename, NXaccess::READ);
1626 } catch (std::runtime_error &e) {
1627 throw std::runtime_error("Severe failure when trying to open NeXus file: " + std::string(e.what()));
1628 }
1629 // make sure that by no means we could dereference NULL later on
1630 if (!m_file) {
1631 throw std::runtime_error("An unexpected failure happened, unable to "
1632 "initialize file object when trying to open NeXus "
1633 "file: " +
1634 fname);
1635 }
1636}
1637} // namespace Mantid::DataHandling
gsl_vector * tmp
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.
Definition Algorithm.h:76
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.
Definition Progress.h:25
void doReport(const std::string &msg="") override
Actually do the reporting, without changing the loop counter.
Definition Progress.cpp:70
This class stores information regarding an experimental run as a series of log entries.
Definition Run.h:35
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...
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...
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.
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.
Definition Detector.h:30
Class to represent a particular goniometer setting, which is described by the rotation matrix.
Definition Goniometer.h:55
void makeUniversalGoniometer()
Make a default universal goniometer with phi,chi,omega angles according to SNS convention.
base class for Geometric IComponent
Definition IComponent.h:53
Support for a property that holds an array of values.
Exception for when an item is not found in a collection.
Definition Exception.h:145
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.
Definition Logger.h:51
void debug(const std::string &msg)
Logs at debug level.
Definition Logger.cpp:145
void notice(const std::string &msg)
Logs at notice level.
Definition Logger.cpp:126
void error(const std::string &msg)
Logs at error level.
Definition Logger.cpp:108
void warning(const std::string &msg)
Logs at warning level.
Definition Logger.cpp:117
void information(const std::string &msg)
Logs at information level.
Definition Logger.cpp:136
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.
Definition DateAndTime.h:25
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)
Definition Unit.cpp:1430
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.
Definition EmptyValues.h:24
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
Definition EmptyValues.h:42
std::string to_string(const wide_integer< Bits, Signed > &n)
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54