16#include <Poco/DateTimeFormat.h>
17#include <Poco/DateTimeFormatter.h>
18#include <Poco/DateTimeParser.h>
20#include <boost/scoped_array.hpp>
29using namespace Kernel;
30using API::FileProperty;
31using API::MatrixWorkspace;
33using API::WorkspaceProperty;
35using Types::Core::DateAndTime;
45bool loadAndApplyMeasurementInfo(Nexus::File *
const file, API::MatrixWorkspace &
workspace) {
47 bool successfullyApplied =
false;
49 file->openGroup(
"measurement",
"NXcollection");
57 file->openData(
"label");
61 file->openData(
"subid");
65 file->openData(
"type");
70 successfullyApplied =
true;
71 }
catch (Nexus::Exception
const &) {
72 successfullyApplied =
false;
74 return successfullyApplied;
83bool loadAndApplyRunTitle(Nexus::File *
const file, API::MatrixWorkspace &
workspace) {
85 bool successfullyApplied =
false;
87 file->openData(
"title");
91 successfullyApplied =
true;
92 }
catch (Nexus::Exception
const &) {
93 successfullyApplied =
false;
95 return successfullyApplied;
111bool isControlValue(
const char &c,
const std::string &propName, Kernel::Logger &log) {
114 log.warning(
"Found an invalid character in property " + propName);
119 std::locale locale{};
121 return std::iscntrl(c, locale);
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");
143 file.getAttr(
"start", start);
144 }
catch (Nexus::Exception
const &) {
147 file.getAttr(
"offset", start);
148 }
catch (Nexus::Exception
const &) {
149 log.warning() <<
"Log entry has no start time indicated.\n";
154 if (start ==
"No 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")
166 throw Nexus::Exception(
"Unsupported time unit '" + time_units +
"'");
169 std::vector<double> time_double;
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";
178 log.debug() <<
" done reading \"time\" array\n";
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));
188 file.openData(
"value");
190 std::string value_units;
192 file.getAttr(
"units", value_units);
193 }
catch (Nexus::Exception
const &) {
199 Nexus::Info info = file.getInfo();
200 if (file.isDataInt()) {
202 if (
size_t(info.dims[0]) != time_double.size()) {
204 throw Nexus::Exception(
"Invalid value entry for time series");
206 std::vector<int> values;
208 file.getDataCoerce(values);
210 }
catch (Nexus::Exception
const &) {
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";
224 const int64_t item_length = (info.dims.size() > 1 ? info.dims[1] : info.dims[0]);
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());
231 values = std::string(val_array.get(), total_length);
232 }
catch (Nexus::Exception
const &) {
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);
246 tsp->setUnits(value_units);
247 log.debug() <<
" done reading \"value\" array\n";
250 std::vector<double> values;
252 file.getDataCoerce(values);
254 }
catch (Nexus::Exception
const &) {
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";
264 throw Nexus::Exception(
"Invalid value type for time series. Only int, double or strings are "
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;
288 if (file.hasData(
"value_valid")) {
289 file.openData(
"value_valid");
292 Nexus::Info info = file.getInfo();
294 if (
size_t(info.dims[0]) != times.size()) {
295 throw Nexus::Exception(
"Invalid value entry for validity data");
297 if (file.isDataInt())
300 file.getDataCoerce(values);
302 }
catch (Nexus::Exception
const &) {
306 throw Nexus::Exception(
"Invalid value type for validity data. Only int is supported");
308 }
catch (std::exception
const &ex) {
309 std::string error_msg = ex.what();
310 log.warning() << error_msg <<
"\n";
313 return std::unique_ptr<Kernel::Property>(
nullptr);
317 bool invalidDataFound =
false;
318 boolValues.reserve(values.size());
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;
327 if (invalidDataFound) {
331 auto tsp = std::make_unique<TimeSeriesProperty<bool>>(tspName);
332 tsp->create(times, boolValues);
333 log.debug() <<
" done reading \"value_valid\" array\n";
338 return std::unique_ptr<Kernel::Property>(
nullptr);
356void appendEndTimeLog(Kernel::Property *prop,
const API::Run &run) {
358 if (prop->name() ==
"proton_charge")
362 auto tsLog =
dynamic_cast<TimeSeriesProperty<double> *
>(prop);
363 const auto endTime = run.endTime();
366 if (!tsLog || tsLog->size() == 0 || endTime <= tsLog->lastTime())
369 tsLog->addValue(endTime, tsLog->lastValue());
370 }
catch (
const Exception::NotFoundError &) {
372 }
catch (
const std::runtime_error &) {
383void readStartAndEndTime(Nexus::File &file, API::Run &run) {
386 file.openData(
"start_time");
387 Types::Core::DateAndTime start(file.getStrData());
389 file.openData(
"end_time");
390 Types::Core::DateAndTime end(file.getStrData());
392 run.setStartAndEndTime(start, end);
393 }
catch (Nexus::Exception
const &) {
405 "The name of the workspace that will be filled with the logs.");
406 const std::vector<std::string> exts{
".nxs",
".n*"};
408 "Path to the .nxs file to load. Can be an EventNeXus or a "
409 "histogrammed NeXus.");
411 "If true then some existing logs will be overwritten, if false they will "
414 "Entry in the nexus file from which to read the logs");
417 "If specified, only these logs will be loaded from the file (each "
418 "separated by a comma).");
421 "If specified, logs matching one of the patterns will NOT be loaded from the file (each "
422 "separated by a comma).");
438 std::vector<std::string> allow_list =
getProperty(
"AllowList");
439 std::vector<std::string> block_list =
getProperty(
"BlockList");
443 if (entry_name.empty()) {
446 Nexus::File file(filename);
449 file.openGroup(entry_name,
"NXentry");
451 throw std::invalid_argument(
"Unknown NeXus file format found in file '" + filename +
"', or '" + entry_name +
452 "' is not a valid NXentry");
458 file.openAddress(
"DASlogs");
460 file.openGroup(
"frequency",
"NXlog");
462 file.openData(
"time");
473 g_log.
warning() <<
"Log entry has no start time indicated.\n";
491 readStartAndEndTime(file,
workspace->mutableRun());
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.");
498 auto lf_LoadLogsByClass = [&](
const std::string &group_class,
const bool isLog) {
499 const std::set<std::string> &entries = file.getEntriesByClass(group_class);
501 for (
const std::string &entry : entries) {
503 if (std::count(entry.begin(), entry.end(),
'/') == 2) {
512 lf_LoadLogsByClass(
"IXselog",
true);
513 lf_LoadLogsByClass(
"IXrunlog",
true);
514 lf_LoadLogsByClass(
"IXperiods",
false);
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);
524 lf_LoadLogsByName(
"DASlogs");
525 lf_LoadLogsByName(
"framelog");
528 loadAndApplyMeasurementInfo(&file, *
workspace);
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";
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);
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);
561 "filtering events by time will not work \n";
563 file.openAddress(
"/" + entry_name);
564 if (!event_frame_number.empty())
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();
578 for (
auto number : event_frame_number) {
579 ptime.emplace_back(plogt[number]);
580 pval.emplace_back(plogv[number]);
582 pcharge->
create(ptime, pval);
584 workspace->mutableRun().addProperty(pcharge,
true);
591 file.openData(
"proton_charge");
592 std::vector<double> values;
593 file.getDataCoerce(values);
595 file.getAttr(
"units", units);
596 double charge = values.front();
597 if (units.find(
"picoCoulomb") != std::string::npos) {
598 charge *= 1.e-06 / 3600.;
600 workspace->mutableRun().setProtonCharge(charge);
605 workspace->mutableRun().getProtonCharge();
612 if (
workspace->run().hasProperty(
"proton_charge_by_period")) {
615 workspace->mutableRun().addProperty(pChargeUnfiltered,
true);
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"
633 <<
"\" contains invalid values, click \"Show Sample Logs\" "
639 <<
" contain invalid values, click \"Show Sample Logs\" for "
652 file.openGroup(
"Veto_pulse",
"NXgroup");
657 file.openData(
"veto_pulse_time");
660 std::string start_time;
661 file.getAttr(
"start_time", start_time);
662 DateAndTime start(start_time);
665 std::vector<double> time_double;
666 file.getData(time_double);
669 std::vector<double> values(time_double.size(), 0.0);
671 tsp->
create(start, time_double, values);
675 workspace->mutableRun().addProperty(tsp);
692 file.openGroup(
"periods",
"IXperiods");
693 file.openData(
"number");
694 file.getData(&
value);
703 const std::string nPeriodsLabel =
"nperiods";
711 file.openGroup(
"periods",
"IXperiods");
714 file.openData(
"number");
715 int numberOfPeriods = 0;
716 file.getData(&numberOfPeriods);
720 std::vector<double> protonChargeByPeriod(numberOfPeriods);
721 file.openData(
"proton_charge");
722 file.getDataCoerce(protonChargeByPeriod);
726 const std::string protonChargeByPeriodLabel =
"proton_charge_by_period";
732 this->
g_log.
debug(
"Cannot read periods information from the nexus file. "
733 "This group may be absent.");
735 }
catch (std::runtime_error &) {
736 this->
g_log.
debug(
"Cannot read periods information from the nexus file. "
737 "This group may be absent.");
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 {
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()) {
762 auto itPrefixBegin = logsSet.lower_bound(absolute_entry_name);
764 if (allow_list.empty()) {
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); });
773 for (
auto it = itPrefixBegin;
774 it != logsSet.end() && it->compare(0, absolute_entry_name.size(), absolute_entry_name) == 0; ++it) {
776 if (std::count(it->begin(), it->end(),
'/') == 3) {
777 if (has_block_list) {
779 for (
auto &block : globblock_list) {
780 if (block->match((*it).substr((*it).find_last_of(
"/") + 1))) {
798 for (
const auto &allow : allow_list) {
799 itPrefixBegin = logsSet.find(absolute_entry_name +
"/" + allow);
800 if (itPrefixBegin == logsSet.end()) {
805 auto it = itPrefixBegin;
807 if (std::count(it->begin(), it->end(),
'/') == 3) {
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);
837 const std::shared_ptr<API::MatrixWorkspace> &
workspace)
const {
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);
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);
851 if (!foundTime || !foundValue) {
852 g_log.
warning() <<
"Invalid NXlog entry " << entry_name <<
" found. Did not contain 'value' and 'time'.\n";
858 bool overwritelogs = this->
getProperty(
"OverwriteLogs");
860 if (overwritelogs || !(
workspace->run().hasProperty(entry_name))) {
861 auto logValue = createTimeSeries(file, entry_name,
freqStart,
g_log);
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);
871 appendEndTimeLog(logValue.get(),
workspace->run());
872 workspace->mutableRun().addProperty(std::move(logValue), overwritelogs);
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";
884 const std::shared_ptr<API::MatrixWorkspace> &
workspace)
const {
886 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of(
"/") + 1);
888 file.openGroup(entry_name,
"IXseblock");
889 std::string propName = entry_name;
890 if (
workspace->run().hasProperty(propName)) {
891 propName =
"selog_" + propName;
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);
902 std::unique_ptr<Kernel::Property> logValue;
906 file.openGroup(
"value_log",
"NXlog");
914 auto validityLogValue = createTimeSeriesValidityFilter(file, *logValue,
g_log);
915 if (validityLogValue) {
916 appendEndTimeLog(validityLogValue.get(),
workspace->run());
917 workspace->mutableRun().addProperty(std::move(validityLogValue));
920 appendEndTimeLog(logValue.get(),
workspace->run());
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";
930 }
else if (foundValue) {
934 file.openData(
"value");
937 boost::scoped_array<float>
value(
new float[info.
dims[0]]);
938 file.getData(
value.get());
940 logValue = std::make_unique<Kernel::PropertyWithValue<double>>(propName,
static_cast<double>(
value[0]),
true);
946 g_log.
warning() <<
"IXseblock entry " << entry_name <<
" gave an error when loading "
947 <<
"a single value:'" << e.what() <<
"'.\n";
953 g_log.
warning() <<
"IXseblock entry " << entry_name <<
" cannot be read, skipping entry.\n";
957 workspace->mutableRun().addProperty(std::move(logValue));
#define DECLARE_ALGORITHM(classname)
double value
The value of the point.
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 & 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.
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.
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.
void debug(const std::string &msg)
Logs at debug level.
void notice(const std::string &msg)
Logs at notice level.
void warning(const std::string &msg)
Logs at warning level.
The concrete, templated class for properties.
virtual void setUnits(const std::string &unit)
Sets the units of the property, as a string.
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.
@ Input
An input workspace.
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.