Mantid
Loading...
Searching...
No Matches
LoadNexusLogs.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 +
10#include "MantidAPI/Run.h"
15
16#include <Poco/DateTimeFormat.h>
17#include <Poco/DateTimeFormatter.h>
18#include <Poco/DateTimeParser.h>
19#include <Poco/Glob.h>
20#include <boost/scoped_array.hpp>
21
22#include <algorithm>
23#include <locale>
24
25namespace Mantid::DataHandling {
26// Register the algorithm into the algorithm factory
27DECLARE_ALGORITHM(LoadNexusLogs)
28
29using namespace Kernel;
30using API::FileProperty;
31using API::MatrixWorkspace;
33using API::WorkspaceProperty;
34using std::size_t;
35using Types::Core::DateAndTime;
36
37// Anonymous namespace
38namespace {
45bool loadAndApplyMeasurementInfo(Nexus::File *const file, API::MatrixWorkspace &workspace) {
46
47 bool successfullyApplied = false;
48 try {
49 file->openGroup("measurement", "NXcollection");
50
51 // If we can open the measurement group. We assume that the following will
52 // be available.
53 file->openData("id");
54 workspace.mutableRun().addLogData(
55 new Mantid::Kernel::PropertyWithValue<std::string>("measurement_id", file->getStrData()));
56 file->closeData();
57 file->openData("label");
58 workspace.mutableRun().addLogData(
59 new Mantid::Kernel::PropertyWithValue<std::string>("measurement_label", file->getStrData()));
60 file->closeData();
61 file->openData("subid");
62 workspace.mutableRun().addLogData(
63 new Mantid::Kernel::PropertyWithValue<std::string>("measurement_subid", file->getStrData()));
64 file->closeData();
65 file->openData("type");
66 workspace.mutableRun().addLogData(
67 new Mantid::Kernel::PropertyWithValue<std::string>("measurement_type", file->getStrData()));
68 file->closeData();
69 file->closeGroup();
70 successfullyApplied = true;
71 } catch (Nexus::Exception const &) {
72 successfullyApplied = false;
73 }
74 return successfullyApplied;
75}
76
83bool loadAndApplyRunTitle(Nexus::File *const file, API::MatrixWorkspace &workspace) {
84
85 bool successfullyApplied = false;
86 try {
87 file->openData("title");
88 workspace.mutableRun().addLogData(
89 new Mantid::Kernel::PropertyWithValue<std::string>("run_title", file->getStrData()));
90 file->closeData();
91 successfullyApplied = true;
92 } catch (Nexus::Exception const &) {
93 successfullyApplied = false;
94 }
95 return successfullyApplied;
96}
97
111bool isControlValue(const char &c, const std::string &propName, Kernel::Logger &log) {
112 // Have to check it falls within range accepted by c style check
113 if (c <= -1) {
114 log.warning("Found an invalid character in property " + propName);
115 // Pretend this is a control value so it is sanitized
116 return true;
117 } else {
118 // Use default global c++ locale within this program
119 std::locale locale{};
120 // Use c++ style call so we don't need to cast from int to bool
121 return std::iscntrl(c, locale);
122 }
123}
124
137std::unique_ptr<Kernel::Property> createTimeSeries(Nexus::File &file, const std::string &propName,
138 const std::string &freqStart, Kernel::Logger &log) {
139 file.openData("time");
140 //----- Start time is an ISO8601 string date and time. ------
141 std::string start;
142 try {
143 file.getAttr("start", start);
144 } catch (Nexus::Exception const &) {
145 // Some logs have "offset" instead of start
146 try {
147 file.getAttr("offset", start);
148 } catch (Nexus::Exception const &) {
149 log.warning() << "Log entry has no start time indicated.\n";
150 file.closeData();
151 throw;
152 }
153 }
154 if (start == "No Time") {
155 start = freqStart;
156 }
157
158 // Convert to date and time
159 Types::Core::DateAndTime start_time = Types::Core::DateAndTime(start);
160 std::string time_units;
161 file.getAttr("units", time_units);
162 if (time_units.compare("second") < 0 && time_units != "s" &&
163 time_units != "minutes") // Can be s/second/seconds/minutes
164 {
165 file.closeData();
166 throw Nexus::Exception("Unsupported time unit '" + time_units + "'");
167 }
168 //--- Load the seconds into a double array ---
169 std::vector<double> time_double;
170 try {
171 file.getDataCoerce(time_double);
172 } catch (Nexus::Exception const &e) {
173 log.warning() << "Log entry's time field could not be loaded: '" << e.what() << "'.\n";
174 file.closeData();
175 throw;
176 }
177 file.closeData(); // Close time data
178 log.debug() << " done reading \"time\" array\n";
179
180 // Convert to seconds if needed
181 if (time_units == "minutes") {
182 using std::placeholders::_1;
183 std::transform(time_double.begin(), time_double.end(), time_double.begin(),
184 std::bind(std::multiplies<double>(), _1, 60.0));
185 }
186
187 // Now the values: Could be a string, int or double
188 file.openData("value");
189 // Get the units of the property
190 std::string value_units;
191 try {
192 file.getAttr("units", value_units);
193 } catch (Nexus::Exception const &) {
194 // Ignore missing units field.
195 value_units = "";
196 }
197
198 // Now the actual data
199 Nexus::Info info = file.getInfo();
200 if (file.isDataInt()) { // Int type
201 // Check the size
202 if (size_t(info.dims[0]) != time_double.size()) {
203 file.closeData();
204 throw Nexus::Exception("Invalid value entry for time series");
205 }
206 std::vector<int> values;
207 try {
208 file.getDataCoerce(values);
209 file.closeData();
210 } catch (Nexus::Exception const &) {
211 file.closeData();
212 throw;
213 }
214 // Make an int TSP
215 auto tsp = std::make_unique<TimeSeriesProperty<int>>(propName);
216 tsp->create(start_time, time_double, values);
217 tsp->setUnits(value_units);
218 log.debug() << " done reading \"value\" array\n";
219 return tsp;
220 } else if (info.type == NXnumtype::CHAR) {
221 std::string values;
222 // the length of each string is normally stored in the second dimension (1),
223 // but some older files (wrongly) put this in the first dimension (0) if the rank is 1
224 const int64_t item_length = (info.dims.size() > 1 ? info.dims[1] : info.dims[0]);
225 try {
226 const std::size_t total_length =
227 std::accumulate(info.dims.cbegin(), info.dims.cend(), 1, std::multiplies<int64_t>());
228 boost::scoped_array<char> val_array(new char[total_length + 1]);
229 file.getData(val_array.get());
230 file.closeData();
231 values = std::string(val_array.get(), total_length);
232 } catch (Nexus::Exception const &) {
233 file.closeData();
234 throw;
235 }
236 // The string may contain non-printable (i.e. control) characters, replace these
237 std::replace_if(values.begin(), values.end(), [&](const char &c) { return isControlValue(c, propName, log); }, ' ');
238 auto tsp = std::make_unique<TimeSeriesProperty<std::string>>(propName);
239 std::vector<DateAndTime> times;
240 DateAndTime::createVector(start_time, time_double, times);
241 const size_t ntimes = times.size();
242 for (size_t i = 0; i < ntimes; ++i) {
243 std::string value_i = std::string(values.data() + i * item_length, item_length);
244 tsp->addValue(times[i], value_i);
245 }
246 tsp->setUnits(value_units);
247 log.debug() << " done reading \"value\" array\n";
248 return tsp;
249 } else if (info.type == NXnumtype::FLOAT32 || info.type == NXnumtype::FLOAT64) {
250 std::vector<double> values;
251 try {
252 file.getDataCoerce(values);
253 file.closeData();
254 } catch (Nexus::Exception const &) {
255 file.closeData();
256 throw;
257 }
258 auto tsp = std::make_unique<TimeSeriesProperty<double>>(propName);
259 tsp->create(start_time, time_double, values);
260 tsp->setUnits(value_units);
261 log.debug() << " done reading \"value\" array\n";
262 return tsp;
263 } else {
264 throw Nexus::Exception("Invalid value type for time series. Only int, double or strings are "
265 "supported");
266 }
267}
268
279std::unique_ptr<Kernel::Property> createTimeSeriesValidityFilter(Nexus::File &file, const Kernel::Property &prop,
280 Kernel::Logger &log) {
281 const auto tsProp = dynamic_cast<const Kernel::ITimeSeriesProperty *>(&prop);
282 const auto times = tsProp->timesAsVector();
283 std::vector<int> values;
284 std::vector<bool> boolValues;
285 // Now the validity of the values
286 // this should be a match int array to the data values (or times)
287 // If not present assume all data is valid
288 if (file.hasData("value_valid")) {
289 file.openData("value_valid");
290 try {
291 // Now the validity data
292 Nexus::Info info = file.getInfo();
293 // Check the size
294 if (size_t(info.dims[0]) != times.size()) {
295 throw Nexus::Exception("Invalid value entry for validity data");
296 }
297 if (file.isDataInt()) // Int type
298 {
299 try {
300 file.getDataCoerce(values);
301 file.closeData();
302 } catch (Nexus::Exception const &) {
303 throw;
304 }
305 } else {
306 throw Nexus::Exception("Invalid value type for validity data. Only int is supported");
307 }
308 } catch (std::exception const &ex) {
309 std::string error_msg = ex.what();
310 log.warning() << error_msg << "\n";
311 file.closeData();
312 // no data found
313 return std::unique_ptr<Kernel::Property>(nullptr);
314 }
315 }
316
317 bool invalidDataFound = false;
318 boolValues.reserve(values.size());
319 // convert the integer values to boolean with 0=invalid data
320 for (size_t i = 0; i < values.size(); i++) {
321 bool isInvalidData = (values[i] == 0);
322 boolValues.emplace_back(!isInvalidData);
323 if (isInvalidData && !invalidDataFound) {
324 invalidDataFound = true;
325 }
326 }
327 if (invalidDataFound) {
328 // Prepare the TimeSeriesProperty<bool>
329 // It's name will be the name of the property plus suffix "_invalid_values"
330 const auto tspName = API::LogManager::getInvalidValuesFilterLogName(prop.name());
331 auto tsp = std::make_unique<TimeSeriesProperty<bool>>(tspName);
332 tsp->create(times, boolValues);
333 log.debug() << " done reading \"value_valid\" array\n";
334
335 return tsp;
336 } else {
337 // no data found
338 return std::unique_ptr<Kernel::Property>(nullptr);
339 }
340}
341
356void appendEndTimeLog(Kernel::Property *prop, const API::Run &run) {
357 // do not modify proton charge
358 if (prop->name() == "proton_charge")
359 return;
360
361 try {
362 auto tsLog = dynamic_cast<TimeSeriesProperty<double> *>(prop);
363 const auto endTime = run.endTime();
364
365 // First check if it is valid to append a log entry
366 if (!tsLog || tsLog->size() == 0 || endTime <= tsLog->lastTime())
367 return;
368
369 tsLog->addValue(endTime, tsLog->lastValue());
370 } catch (const Exception::NotFoundError &) {
371 // pass
372 } catch (const std::runtime_error &) {
373 // pass
374 }
375}
376
383void readStartAndEndTime(Nexus::File &file, API::Run &run) {
384 try {
385 // Read the start and end time strings
386 file.openData("start_time");
387 Types::Core::DateAndTime start(file.getStrData());
388 file.closeData();
389 file.openData("end_time");
390 Types::Core::DateAndTime end(file.getStrData());
391 file.closeData();
392 run.setStartAndEndTime(start, end);
393 } catch (Nexus::Exception const &) {
394 }
395}
396
397} // End of anonymous namespace
398
401
404 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("Workspace", "Anonymous", Direction::InOut),
405 "The name of the workspace that will be filled with the logs.");
406 const std::vector<std::string> exts{".nxs", ".n*"};
407 declareProperty(std::make_unique<FileProperty>("Filename", "", FileProperty::Load, exts),
408 "Path to the .nxs file to load. Can be an EventNeXus or a "
409 "histogrammed NeXus.");
410 declareProperty(std::make_unique<PropertyWithValue<bool>>("OverwriteLogs", true, Direction::Input),
411 "If true then some existing logs will be overwritten, if false they will "
412 "not.");
413 declareProperty(std::make_unique<PropertyWithValue<std::string>>("NXentryName", "", Direction::Input),
414 "Entry in the nexus file from which to read the logs");
415 declareProperty(std::make_unique<PropertyWithValue<std::vector<std::string>>>("AllowList", std::vector<std::string>(),
417 "If specified, only these logs will be loaded from the file (each "
418 "separated by a comma).");
419 declareProperty(std::make_unique<PropertyWithValue<std::vector<std::string>>>("BlockList", std::vector<std::string>(),
421 "If specified, logs matching one of the patterns will NOT be loaded from the file (each "
422 "separated by a comma).");
423}
424
433 std::string filename = getPropertyValue("Filename");
435
436 std::string entry_name = getPropertyValue("NXentryName");
437
438 std::vector<std::string> allow_list = getProperty("AllowList");
439 std::vector<std::string> block_list = getProperty("BlockList");
440
441 // Find the entry name to use (normally "entry" for SNS, "raw_data_1" for
442 // ISIS) if entry name is empty
443 if (entry_name.empty()) {
444 entry_name = LoadTOFRawNexus::getEntryName(filename);
445 }
446 Nexus::File file(filename);
447 // Find the root entry
448 try {
449 file.openGroup(entry_name, "NXentry");
450 } catch (Nexus::Exception const &) {
451 throw std::invalid_argument("Unknown NeXus file format found in file '" + filename + "', or '" + entry_name +
452 "' is not a valid NXentry");
453 }
454
457 try {
458 file.openAddress("DASlogs");
459 try {
460 file.openGroup("frequency", "NXlog");
461 try {
462 file.openData("time");
463
464 //----- Start time is an ISO8601 string date and time. ------
465 try {
466 file.getAttr("start", freqStart);
467
468 } catch (Nexus::Exception const &) {
469 // Some logs have "offset" instead of start
470 try {
471 file.getAttr("offset", freqStart);
472 } catch (Nexus::Exception const &) {
473 g_log.warning() << "Log entry has no start time indicated.\n";
474 file.closeData();
475 throw;
476 }
477 }
478 file.closeData();
479 } catch (Nexus::Exception const &) {
480 // No time. This is not an SNS SNAP file
481 }
482 file.closeGroup();
483 } catch (Nexus::Exception const &) {
484 // No time. This is not an SNS frequency group
485 }
486 file.closeGroup();
487 } catch (Nexus::Exception const &) {
488 // No time. This is not an SNS group
489 }
490
491 readStartAndEndTime(file, workspace->mutableRun());
492
493 if (!allow_list.empty() && !block_list.empty()) {
494 throw std::runtime_error("BlockList and AllowList are mutually exclusive! "
495 "Please only enter values for one of these fields.");
496 }
497
498 auto lf_LoadLogsByClass = [&](const std::string &group_class, const bool isLog) {
499 const std::set<std::string> &entries = file.getEntriesByClass(group_class);
500 // still a linear search
501 for (const std::string &entry : entries) {
502 // match for 2nd level entry /a/b
503 if (std::count(entry.begin(), entry.end(), '/') == 2) {
504 if (isLog) {
505 loadLogs(file, entry, group_class, workspace, allow_list, block_list);
506 } else {
507 loadNPeriods(file, workspace);
508 }
509 }
510 }
511 };
512 lf_LoadLogsByClass("IXselog", true);
513 lf_LoadLogsByClass("IXrunlog", true);
514 lf_LoadLogsByClass("IXperiods", false);
515
516 auto lf_LoadLogsByName = [&](const std::string &group_name) {
517 std::string const absoluteGroupName = "/" + entry_name + "/" + group_name;
518 if (file.hasAddress(absoluteGroupName)) {
519 std::string const &group_class = file.classForEntry(absoluteGroupName);
520 loadLogs(file, absoluteGroupName, group_class, workspace, allow_list, block_list);
521 }
522 };
523
524 lf_LoadLogsByName("DASlogs");
525 lf_LoadLogsByName("framelog");
526
527 // If there's measurement information, load that info as logs.
528 loadAndApplyMeasurementInfo(&file, *workspace);
529 // If there's title information, load that info as logs.
530 loadAndApplyRunTitle(&file, *workspace);
531
532 // Freddie Akeroyd 12/10/2011
533 // current ISIS implementation contains an additional indirection between
534 // collected frames via an
535 // "event_frame_number" array in NXevent_data (which eliminates frames with no
536 // events).
537 // the proton_log is for all frames and so is longer than the event_index
538 // array, so we need to
539 // filter the proton_charge log based on event_frame_number
540 // This difference will be removed in future for compatibility with SNS, but
541 // the code below will allow current SANS2D files to load
542 if (workspace->mutableRun().hasProperty("proton_log")) {
543 std::vector<int> event_frame_number;
544 this->getLogger().notice() << "Using old ISIS proton_log and event_frame_number indirection...\n";
545 try {
546 // Find the bank/name corresponding to the first event data entry, i.e.
547 // one with type NXevent_data.
548 file.openAddress("/" + entry_name);
549 std::set<std::string> const &events = file.getEntriesByClass("NXevent_data");
550 for (std::string const &event : events) {
551 std::string const eventEntry = event.substr(event.find_last_of("/") + 1);
552
553 this->getLogger().debug() << "Opening"
554 << " /" + entry_name + "/" + eventEntry + "/event_frame_number"
555 << " to find the event_frame_number\n";
556 file.openAddress("/" + entry_name + "/" + eventEntry + "/event_frame_number");
557 file.getData(event_frame_number);
558 }
559 } catch (Nexus::Exception const &) {
560 this->getLogger().warning() << "Unable to load event_frame_number - "
561 "filtering events by time will not work \n";
562 }
563 file.openAddress("/" + entry_name);
564 if (!event_frame_number.empty()) // ISIS indirection - see above comments
565 {
567 dynamic_cast<Kernel::TimeSeriesProperty<double> *>(workspace->mutableRun().getProperty("proton_log"));
568 if (!plog)
569 throw std::runtime_error("Could not cast (interpret) proton_log as a time "
570 "series property. Cannot continue.");
572 std::vector<double> pval;
573 std::vector<Mantid::Types::Core::DateAndTime> ptime;
574 pval.reserve(event_frame_number.size());
575 ptime.reserve(event_frame_number.size());
576 std::vector<Mantid::Types::Core::DateAndTime> plogt = plog->timesAsVector();
577 std::vector<double> plogv = plog->valuesAsVector();
578 for (auto number : event_frame_number) {
579 ptime.emplace_back(plogt[number]);
580 pval.emplace_back(plogv[number]);
581 }
582 pcharge->create(ptime, pval);
583 pcharge->setUnits("uAh");
584 workspace->mutableRun().addProperty(pcharge, true);
585 }
586 }
587
588 if (!workspace->run().hasProperty(workspace->run().getProtonChargeLogName())) {
589 try {
590 // Try pulling proton charge from the main proton_charge entry
591 file.openData("proton_charge");
592 std::vector<double> values;
593 file.getDataCoerce(values);
594 std::string units;
595 file.getAttr("units", units);
596 double charge = values.front();
597 if (units.find("picoCoulomb") != std::string::npos) {
598 charge *= 1.e-06 / 3600.;
599 }
600 workspace->mutableRun().setProtonCharge(charge);
601 } catch (Nexus::Exception const &) {
602 // Try and integrate the proton logs
603 try {
604 // Use the DAS logs to integrate the proton charge (if any).
605 workspace->mutableRun().getProtonCharge();
606 } catch (Exception::NotFoundError &) {
607 // Ignore not found property error.
608 }
609 }
610 }
611 // For period data mark proton charge log value as unfiltered to enable subsequent filtering by period.
612 if (workspace->run().hasProperty("proton_charge_by_period")) {
613 Kernel::PropertyWithValue<int> *pChargeUnfiltered =
614 new Kernel::PropertyWithValue<int>(workspace->run().getProtonChargeUnfilteredName(), 1);
615 workspace->mutableRun().addProperty(pChargeUnfiltered, true);
616 }
617
618 if (!allow_list.empty()) {
619 for (const auto &allow : allow_list) {
620 if (!workspace->run().hasProperty(allow)) {
621 g_log.notice() << "could not load entry '" << allow << "' that was specified in the allow list"
622 << "\n";
623 }
624 }
625 }
626
627 // Close the file
628 file.close();
629
630 if (m_logsWithInvalidValues.size() > 0) {
631 if (m_logsWithInvalidValues.size() == 1) {
632 g_log.warning() << "Sample Log \"" << m_logsWithInvalidValues[0]
633 << "\" contains invalid values, click \"Show Sample Logs\" "
634 "for details.\n";
635 }
636 auto other_string = (m_logsWithInvalidValues.size() < 2) ? " other " : " others";
637 g_log.warning() << "Sample Log \"" << m_logsWithInvalidValues[0] << "\" and " << m_logsWithInvalidValues.size() - 1
638 << other_string
639 << " contain invalid values, click \"Show Sample Logs\" for "
640 "details.\n";
641 }
642}
643
650void LoadNexusLogs::loadVetoPulses(Nexus::File &file, const std::shared_ptr<API::MatrixWorkspace> &workspace) const {
651 try {
652 file.openGroup("Veto_pulse", "NXgroup");
653 } catch (Nexus::Exception const &) {
654 // No group. This is common in older files
655 return;
656 }
657 file.openData("veto_pulse_time");
658
659 // Load the start date/time as ISO8601 string.
660 std::string start_time;
661 file.getAttr("start_time", start_time);
662 DateAndTime start(start_time);
663
664 // Read the offsets
665 std::vector<double> time_double;
666 file.getData(time_double);
667
668 // Fake values with zeroes.
669 std::vector<double> values(time_double.size(), 0.0);
670 TimeSeriesProperty<double> *tsp = new TimeSeriesProperty<double>("veto_pulse_time");
671 tsp->create(start, time_double, values);
672 tsp->setUnits("");
673
674 // Add the log
675 workspace->mutableRun().addProperty(tsp);
676
677 file.closeData();
678 file.closeGroup();
679}
680
689void LoadNexusLogs::loadNPeriods(Nexus::File &file, const std::shared_ptr<API::MatrixWorkspace> &workspace) const {
690 int value = 1; // Default to 1-period unless
691 try {
692 file.openGroup("periods", "IXperiods");
693 file.openData("number");
694 file.getData(&value);
695 file.closeData();
696 file.closeGroup();
697 } catch (Nexus::Exception const &) {
698 // Likely missing IXperiods.
699 return;
700 }
701
702 API::Run &run = workspace->mutableRun();
703 const std::string nPeriodsLabel = "nperiods";
704 if (!run.hasProperty(nPeriodsLabel)) {
705 run.addProperty(new PropertyWithValue<int>(nPeriodsLabel, value));
706 }
707
708 // For ISIS Nexus only, fabricate an additional log containing an array of
709 // proton charge information from the periods group.
710 try {
711 file.openGroup("periods", "IXperiods");
712
713 // Get the number of periods again
714 file.openData("number");
715 int numberOfPeriods = 0;
716 file.getData(&numberOfPeriods);
717 file.closeData();
718
719 // Get the proton charge vector
720 std::vector<double> protonChargeByPeriod(numberOfPeriods);
721 file.openData("proton_charge");
722 file.getDataCoerce(protonChargeByPeriod);
723 file.closeData();
724
725 // Add the proton charge vector
726 const std::string protonChargeByPeriodLabel = "proton_charge_by_period";
727 if (!run.hasProperty(protonChargeByPeriodLabel)) {
728 run.addProperty(new ArrayProperty<double>(protonChargeByPeriodLabel, std::move(protonChargeByPeriod)));
729 }
730 file.closeGroup();
731 } catch (Nexus::Exception const &) {
732 this->g_log.debug("Cannot read periods information from the nexus file. "
733 "This group may be absent.");
734 file.closeGroup();
735 } catch (std::runtime_error &) {
736 this->g_log.debug("Cannot read periods information from the nexus file. "
737 "This group may be absent.");
738 file.closeGroup();
739 }
740}
741
752void LoadNexusLogs::loadLogs(Nexus::File &file, const std::string &absolute_entry_name, const std::string &entry_class,
753 const std::shared_ptr<API::MatrixWorkspace> &workspace,
754 const std::vector<std::string> &allow_list,
755 const std::vector<std::string> &block_list) const {
756
757 auto lf_LoadByLogClass = [&](std::string const &logClass, const bool isNxLog) {
758 std::set<std::string> const &logsSet = file.getEntriesByClass(logClass);
759 if (logsSet.empty()) {
760 return;
761 }
762 auto itPrefixBegin = logsSet.lower_bound(absolute_entry_name);
763
764 if (allow_list.empty()) {
765 // convert the blocklist into a bunch of objects to handle globbing
766 const bool has_block_list = (!block_list.empty());
767 std::vector<std::unique_ptr<Poco::Glob>> globblock_list;
768 if (has_block_list) {
769 std::transform(block_list.cbegin(), block_list.cend(), std::back_inserter(globblock_list),
770 [](const auto &block) { return std::make_unique<Poco::Glob>(block); });
771 }
772
773 for (auto it = itPrefixBegin;
774 it != logsSet.end() && it->compare(0, absolute_entry_name.size(), absolute_entry_name) == 0; ++it) {
775 // must be third level entry
776 if (std::count(it->begin(), it->end(), '/') == 3) {
777 if (has_block_list) {
778 bool skip = false;
779 for (auto &block : globblock_list) {
780 if (block->match((*it).substr((*it).find_last_of("/") + 1))) {
781 skip = true;
782 break; // from the loop of block items
783 }
784 }
785 if (skip) {
786 continue; // go to next log
787 }
788 } // end of looping over block_list
789
790 if (isNxLog) {
791 loadNXLog(file, *it, logClass, workspace);
792 } else {
793 loadSELog(file, *it, workspace);
794 }
795 }
796 }
797 } else {
798 for (const auto &allow : allow_list) {
799 itPrefixBegin = logsSet.find(absolute_entry_name + "/" + allow);
800 if (itPrefixBegin == logsSet.end()) {
801 // don't print warning yet since it might be found in another log
802 // class
803 continue;
804 }
805 auto it = itPrefixBegin;
806 // must be third level entry
807 if (std::count(it->begin(), it->end(), '/') == 3) {
808 if (isNxLog) {
809 loadNXLog(file, *it, logClass, workspace);
810 } else {
811 loadSELog(file, *it, workspace);
812 }
813 }
814 }
815 }
816 };
817
818 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of("/") + 1);
819 file.openGroup(entry_name, entry_class);
820 lf_LoadByLogClass("NXlog", true);
821 lf_LoadByLogClass("NXpositioner", true);
822 lf_LoadByLogClass("IXseblock", false);
824
825 file.closeGroup();
826}
827
836void LoadNexusLogs::loadNXLog(Nexus::File &file, const std::string &absolute_entry_name, const std::string &entry_class,
837 const std::shared_ptr<API::MatrixWorkspace> &workspace) const {
838
839 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of("/") + 1);
840 g_log.debug() << "processing " << entry_name << ":" << entry_class << "\n";
841 file.openGroup(entry_name, entry_class);
842 // Validate the NX log class.
843 // Just verify that time and value entries exist
844 std::string const timeEntry = absolute_entry_name + "/time";
845 std::string const valueEntry = absolute_entry_name + "/value";
846 std::string const validatorEntry = absolute_entry_name + "/value_valid";
847 bool const foundValue = file.hasAddress(valueEntry);
848 bool const foundTime = file.hasAddress(timeEntry);
849 bool const foundValidator = file.hasAddress(validatorEntry);
850
851 if (!foundTime || !foundValue) {
852 g_log.warning() << "Invalid NXlog entry " << entry_name << " found. Did not contain 'value' and 'time'.\n";
853 file.closeGroup();
854 return;
855 }
856
857 // whether to overwrite logs on workspace
858 bool overwritelogs = this->getProperty("OverwriteLogs");
859 try {
860 if (overwritelogs || !(workspace->run().hasProperty(entry_name))) {
861 auto logValue = createTimeSeries(file, entry_name, freqStart, g_log);
862 // Create (possibly) a boolean time series, companion to time series `entry_name`
863 if (foundValidator) {
864 auto validityLogValue = createTimeSeriesValidityFilter(file, *logValue, g_log);
865 if (validityLogValue) {
866 appendEndTimeLog(validityLogValue.get(), workspace->run());
867 workspace->mutableRun().addProperty(std::move(validityLogValue), overwritelogs);
868 m_logsWithInvalidValues.emplace_back(entry_name);
869 }
870 }
871 appendEndTimeLog(logValue.get(), workspace->run());
872 workspace->mutableRun().addProperty(std::move(logValue), overwritelogs);
873 }
874 } catch (Nexus::Exception const &e) {
875 g_log.warning() << "NXlog entry " << entry_name << " gave an error when loading:'" << e.what() << "'.\n";
876 } catch (std::invalid_argument &e) {
877 g_log.warning() << "NXlog entry " << entry_name << " gave an error when loading:'" << e.what() << "'.\n";
878 }
879
880 file.closeGroup();
881}
882
883void LoadNexusLogs::loadSELog(Nexus::File &file, const std::string &absolute_entry_name,
884 const std::shared_ptr<API::MatrixWorkspace> &workspace) const {
885 // Open the entry
886 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of("/") + 1);
887
888 file.openGroup(entry_name, "IXseblock");
889 std::string propName = entry_name;
890 if (workspace->run().hasProperty(propName)) {
891 propName = "selog_" + propName;
892 }
893 // There are two possible entries:
894 // value_log - A time series entry. This can contain a corrupt value entry
895 // so if it does use the value one
896 // value - A single value float entry
897 std::string const valueEntry = absolute_entry_name + "/value";
898 std::string const valueLogEntry = absolute_entry_name + "/value_log";
899 bool const foundValue = file.hasAddress(valueEntry);
900 bool const foundValueLog = file.hasAddress(valueLogEntry);
901
902 std::unique_ptr<Kernel::Property> logValue;
903 if (foundValueLog) {
904 try {
905 try {
906 file.openGroup("value_log", "NXlog");
907 } catch (Nexus::Exception const &) {
908 file.closeGroup();
909 throw;
910 }
911
912 logValue = createTimeSeries(file, propName, freqStart, g_log);
913 // Create (possibly) a boolean time series, companion to time series `logValue`.
914 auto validityLogValue = createTimeSeriesValidityFilter(file, *logValue, g_log);
915 if (validityLogValue) {
916 appendEndTimeLog(validityLogValue.get(), workspace->run());
917 workspace->mutableRun().addProperty(std::move(validityLogValue));
918 m_logsWithInvalidValues.emplace_back(propName);
919 }
920 appendEndTimeLog(logValue.get(), workspace->run());
921
922 file.closeGroup();
923 } catch (std::exception &e) {
924 g_log.warning() << "IXseblock entry '" << entry_name << "' gave an error when loading "
925 << "a time series:'" << e.what() << "'. Skipping entry\n";
926 file.closeGroup(); // value_log
927 file.closeGroup(); // entry_name
928 return;
929 }
930 } else if (foundValue) {
931 try {
932 // This may have a larger dimension than 1 bit it has no time field so
933 // take the first entry
934 file.openData("value");
935 Nexus::Info info = file.getInfo();
936 if (info.type == NXnumtype::FLOAT32) {
937 boost::scoped_array<float> value(new float[info.dims[0]]);
938 file.getData(value.get());
939 file.closeData();
940 logValue = std::make_unique<Kernel::PropertyWithValue<double>>(propName, static_cast<double>(value[0]), true);
941 } else {
942 file.closeGroup();
943 return;
944 }
945 } catch (Nexus::Exception const &e) {
946 g_log.warning() << "IXseblock entry " << entry_name << " gave an error when loading "
947 << "a single value:'" << e.what() << "'.\n";
948 file.closeData();
949 file.closeGroup();
950 return;
951 }
952 } else {
953 g_log.warning() << "IXseblock entry " << entry_name << " cannot be read, skipping entry.\n";
954 file.closeGroup();
955 return;
956 }
957 workspace->mutableRun().addProperty(std::move(logValue));
958 file.closeGroup();
959}
960
961} // namespace Mantid::DataHandling
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:538
double value
The value of the point.
Definition FitMW.cpp:51
IPeaksWorkspace_sptr workspace
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.
Kernel::Logger & g_log
Definition Algorithm.h:422
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.
void addProperty(Kernel::Property *prop, bool overwrite=false)
Add data to the object in the form of a property.
Definition LogManager.h:90
static std::string getInvalidValuesFilterLogName(const std::string &logName)
Gets the correct log name for the matching invalid values log for a given log name.
This class stores information regarding an experimental run as a series of log entries.
Definition Run.h:35
A property class for workspaces.
std::vector< std::string > m_logsWithInvalidValues
void init() override
Overwrites Algorithm method.
LoadNexusLogs()
Default constructor.
void loadNXLog(Nexus::File &file, const std::string &absolute_entry_name, const std::string &entry_class, const std::shared_ptr< API::MatrixWorkspace > &workspace) const
Load an NXlog entry.
void loadNPeriods(Nexus::File &file, const std::shared_ptr< API::MatrixWorkspace > &workspace) const
For ISIS logs containing periods, retrieve the total proton charge for each period if stored in the l...
std::string freqStart
Use frequency start for Monitor19 and Special1_19 logs with "No Time" for SNAP.
void exec() override
Overwrites Algorithm method.
void loadSELog(Nexus::File &file, const std::string &absolute_entry_name, const std::shared_ptr< API::MatrixWorkspace > &workspace) const
Load an IXseblock entry.
void loadVetoPulses(Nexus::File &file, const std::shared_ptr< API::MatrixWorkspace > &workspace) const
Try to load the "Veto_pulse" field in DASLogs and convert it to a sample log.
void loadLogs(Nexus::File &file, const std::string &absolute_entry_name, const std::string &entry_class, const std::shared_ptr< API::MatrixWorkspace > &workspace, const std::vector< std::string > &allow_list, const std::vector< std::string > &block_list) const
Load log data from a group.
static std::string getEntryName(const std::string &filename)
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
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 warning(const std::string &msg)
Logs at warning level.
Definition Logger.cpp:117
The concrete, templated class for properties.
virtual void setUnits(const std::string &unit)
Sets the units of the property, as a string.
Definition Property.cpp:201
A specialised Property class for holding a series of time-value pairs.
std::vector< TYPE > valuesAsVector() const
Return the time series's values (unfiltered) as a vector<TYPE>
void create(const Types::Core::DateAndTime &start_time, const std::vector< double > &time_sec, const std::vector< TYPE > &new_values)
Clears and creates a TimeSeriesProperty from these parameters.
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.
static unsigned short constexpr CHAR
static unsigned short constexpr FLOAT32
static unsigned short constexpr FLOAT64
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
@ InOut
Both an input & output workspace.
Definition Property.h:55
@ Input
An input workspace.
Definition Property.h:53
This structure holds the type and dimensions of a primative field/array.
DimVector dims
The dimensions of the file.
NXnumtype type
The primative type for the field.