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(), std::size_t(1),
228 [](std::size_t acc, int64_t
x) { return acc * static_cast<std::size_t>(x); });
229 boost::scoped_array<char> val_array(
new char[total_length + 1]);
230 file.getData(val_array.get());
232 values = std::string(val_array.get(), total_length);
233 }
catch (Nexus::Exception
const &) {
238 std::replace_if(values.begin(), values.end(), [&](
const char &c) { return isControlValue(c, propName, log); },
' ');
239 auto tsp = std::make_unique<TimeSeriesProperty<std::string>>(propName);
240 std::vector<DateAndTime> times;
241 DateAndTime::createVector(start_time, time_double, times);
242 const size_t ntimes = times.size();
243 for (
size_t i = 0; i < ntimes; ++i) {
244 std::string value_i = std::string(values.data() + i * item_length, item_length);
245 tsp->addValue(times[i], value_i);
247 tsp->setUnits(value_units);
248 log.debug() <<
" done reading \"value\" array\n";
251 std::vector<double> values;
253 file.getDataCoerce(values);
255 }
catch (Nexus::Exception
const &) {
259 auto tsp = std::make_unique<TimeSeriesProperty<double>>(propName);
260 tsp->create(start_time, time_double, values);
261 tsp->setUnits(value_units);
262 log.debug() <<
" done reading \"value\" array\n";
265 throw Nexus::Exception(
"Invalid value type for time series. Only int, double or strings are "
280std::unique_ptr<Kernel::Property> createTimeSeriesValidityFilter(Nexus::File &file,
const Kernel::Property &prop,
281 Kernel::Logger &log) {
282 const auto tsProp =
dynamic_cast<const Kernel::ITimeSeriesProperty *
>(&prop);
283 const auto times = tsProp->timesAsVector();
284 std::vector<int> values;
285 std::vector<bool> boolValues;
289 if (file.hasData(
"value_valid")) {
290 file.openData(
"value_valid");
293 Nexus::Info info = file.getInfo();
295 if (
size_t(info.dims[0]) != times.size()) {
296 throw Nexus::Exception(
"Invalid value entry for validity data");
298 if (file.isDataInt())
301 file.getDataCoerce(values);
303 }
catch (Nexus::Exception
const &) {
307 throw Nexus::Exception(
"Invalid value type for validity data. Only int is supported");
309 }
catch (std::exception
const &ex) {
310 std::string error_msg = ex.what();
311 log.warning() << error_msg <<
"\n";
314 return std::unique_ptr<Kernel::Property>(
nullptr);
318 bool invalidDataFound =
false;
319 boolValues.reserve(values.size());
321 for (
size_t i = 0; i < values.size(); i++) {
322 bool isInvalidData = (values[i] == 0);
323 boolValues.emplace_back(!isInvalidData);
324 if (isInvalidData && !invalidDataFound) {
325 invalidDataFound =
true;
328 if (invalidDataFound) {
332 auto tsp = std::make_unique<TimeSeriesProperty<bool>>(tspName);
333 tsp->create(times, boolValues);
334 log.debug() <<
" done reading \"value_valid\" array\n";
339 return std::unique_ptr<Kernel::Property>(
nullptr);
357void appendEndTimeLog(Kernel::Property *prop,
const API::Run &run) {
359 if (prop->name() ==
"proton_charge")
363 auto tsLog =
dynamic_cast<TimeSeriesProperty<double> *
>(prop);
364 const auto endTime = run.endTime();
367 if (!tsLog || tsLog->size() == 0 || endTime <= tsLog->lastTime())
370 tsLog->addValue(endTime, tsLog->lastValue());
371 }
catch (
const Exception::NotFoundError &) {
373 }
catch (
const std::runtime_error &) {
384void readStartAndEndTime(Nexus::File &file, API::Run &run) {
387 file.openData(
"start_time");
388 Types::Core::DateAndTime start(file.getStrData());
390 file.openData(
"end_time");
391 Types::Core::DateAndTime end(file.getStrData());
393 run.setStartAndEndTime(start, end);
394 }
catch (Nexus::Exception
const &) {
406 "The name of the workspace that will be filled with the logs.");
407 const std::vector<std::string> exts{
".nxs",
".n*"};
409 "Path to the .nxs file to load. Can be an EventNeXus or a "
410 "histogrammed NeXus.");
412 "If true then some existing logs will be overwritten, if false they will "
415 "Entry in the nexus file from which to read the logs");
418 "If specified, only these logs will be loaded from the file (each "
419 "separated by a comma).");
422 "If specified, logs matching one of the patterns will NOT be loaded from the file (each "
423 "separated by a comma).");
439 std::vector<std::string> allow_list =
getProperty(
"AllowList");
440 std::vector<std::string> block_list =
getProperty(
"BlockList");
444 if (entry_name.empty()) {
447 Nexus::File file(filename);
450 file.openGroup(entry_name,
"NXentry");
452 throw std::invalid_argument(
"Unknown NeXus file format found in file '" + filename +
"', or '" + entry_name +
453 "' is not a valid NXentry");
459 file.openAddress(
"DASlogs");
461 file.openGroup(
"frequency",
"NXlog");
463 file.openData(
"time");
474 g_log.
warning() <<
"Log entry has no start time indicated.\n";
492 readStartAndEndTime(file,
workspace->mutableRun());
494 if (!allow_list.empty() && !block_list.empty()) {
495 throw std::runtime_error(
"BlockList and AllowList are mutually exclusive! "
496 "Please only enter values for one of these fields.");
499 auto lf_LoadLogsByClass = [&](
const std::string &group_class,
const bool isLog) {
500 const std::set<std::string> &entries = file.getEntriesByClass(group_class);
502 for (
const std::string &entry : entries) {
504 if (std::count(entry.begin(), entry.end(),
'/') == 2) {
513 lf_LoadLogsByClass(
"IXselog",
true);
514 lf_LoadLogsByClass(
"IXrunlog",
true);
515 lf_LoadLogsByClass(
"IXperiods",
false);
517 auto lf_LoadLogsByName = [&](
const std::string &group_name) {
518 std::string
const absoluteGroupName =
"/" + entry_name +
"/" + group_name;
519 if (file.hasAddress(absoluteGroupName)) {
520 std::string
const &group_class = file.classForEntry(absoluteGroupName);
521 loadLogs(file, absoluteGroupName, group_class,
workspace, allow_list, block_list);
525 lf_LoadLogsByName(
"DASlogs");
526 lf_LoadLogsByName(
"framelog");
529 loadAndApplyMeasurementInfo(&file, *
workspace);
543 if (
workspace->mutableRun().hasProperty(
"proton_log")) {
544 std::vector<int> event_frame_number;
545 this->
getLogger().
notice() <<
"Using old ISIS proton_log and event_frame_number indirection...\n";
549 file.openAddress(
"/" + entry_name);
550 std::set<std::string>
const &events = file.getEntriesByClass(
"NXevent_data");
551 for (std::string
const &event : events) {
552 std::string
const eventEntry =
event.substr(event.find_last_of(
"/") + 1);
555 <<
" /" + entry_name +
"/" + eventEntry +
"/event_frame_number"
556 <<
" to find the event_frame_number\n";
557 file.openAddress(
"/" + entry_name +
"/" + eventEntry +
"/event_frame_number");
558 file.getData(event_frame_number);
562 "filtering events by time will not work \n";
564 file.openAddress(
"/" + entry_name);
565 if (!event_frame_number.empty())
570 throw std::runtime_error(
"Could not cast (interpret) proton_log as a time "
571 "series property. Cannot continue.");
573 std::vector<double> pval;
574 std::vector<Mantid::Types::Core::DateAndTime> ptime;
575 pval.reserve(event_frame_number.size());
576 ptime.reserve(event_frame_number.size());
577 std::vector<Mantid::Types::Core::DateAndTime> plogt = plog->
timesAsVector();
579 for (
auto number : event_frame_number) {
580 ptime.emplace_back(plogt[number]);
581 pval.emplace_back(plogv[number]);
583 pcharge->
create(ptime, pval);
585 workspace->mutableRun().addProperty(pcharge,
true);
592 file.openData(
"proton_charge");
593 std::vector<double> values;
594 file.getDataCoerce(values);
596 file.getAttr(
"units", units);
597 double charge = values.front();
598 if (units.find(
"picoCoulomb") != std::string::npos) {
599 charge *= 1.e-06 / 3600.;
601 workspace->mutableRun().setProtonCharge(charge);
606 workspace->mutableRun().getProtonCharge();
613 if (
workspace->run().hasProperty(
"proton_charge_by_period")) {
616 workspace->mutableRun().addProperty(pChargeUnfiltered,
true);
619 if (!allow_list.empty()) {
620 for (
const auto &allow : allow_list) {
621 if (!
workspace->run().hasProperty(allow)) {
622 g_log.
notice() <<
"could not load entry '" << allow <<
"' that was specified in the allow list"
634 <<
"\" contains invalid values, click \"Show Sample Logs\" "
640 <<
" contain invalid values, click \"Show Sample Logs\" for "
653 file.openGroup(
"Veto_pulse",
"NXgroup");
658 file.openData(
"veto_pulse_time");
661 std::string start_time;
662 file.getAttr(
"start_time", start_time);
663 DateAndTime start(start_time);
666 std::vector<double> time_double;
667 file.getData(time_double);
670 std::vector<double> values(time_double.size(), 0.0);
672 tsp->
create(start, time_double, values);
676 workspace->mutableRun().addProperty(tsp);
693 file.openGroup(
"periods",
"IXperiods");
694 file.openData(
"number");
695 file.getData(&
value);
704 const std::string nPeriodsLabel =
"nperiods";
712 file.openGroup(
"periods",
"IXperiods");
715 file.openData(
"number");
716 int numberOfPeriods = 0;
717 file.getData(&numberOfPeriods);
721 std::vector<double> protonChargeByPeriod(numberOfPeriods);
722 file.openData(
"proton_charge");
723 file.getDataCoerce(protonChargeByPeriod);
727 const std::string protonChargeByPeriodLabel =
"proton_charge_by_period";
733 this->
g_log.
debug(
"Cannot read periods information from the nexus file. "
734 "This group may be absent.");
736 }
catch (std::runtime_error &) {
737 this->
g_log.
debug(
"Cannot read periods information from the nexus file. "
738 "This group may be absent.");
754 const std::shared_ptr<API::MatrixWorkspace> &
workspace,
755 const std::vector<std::string> &allow_list,
756 const std::vector<std::string> &block_list)
const {
758 auto lf_LoadByLogClass = [&](std::string
const &logClass,
const bool isNxLog) {
759 std::set<std::string>
const &logsSet = file.getEntriesByClass(logClass);
760 if (logsSet.empty()) {
763 auto itPrefixBegin = logsSet.lower_bound(absolute_entry_name);
765 if (allow_list.empty()) {
767 const bool has_block_list = (!block_list.empty());
768 std::vector<std::unique_ptr<Poco::Glob>> globblock_list;
769 if (has_block_list) {
770 std::transform(block_list.cbegin(), block_list.cend(), std::back_inserter(globblock_list),
771 [](
const auto &block) { return std::make_unique<Poco::Glob>(block); });
774 for (
auto it = itPrefixBegin;
775 it != logsSet.end() && it->compare(0, absolute_entry_name.size(), absolute_entry_name) == 0; ++it) {
777 if (std::count(it->begin(), it->end(),
'/') == 3) {
778 if (has_block_list) {
780 for (
auto &block : globblock_list) {
781 if (block->match((*it).substr((*it).find_last_of(
"/") + 1))) {
799 for (
const auto &allow : allow_list) {
800 itPrefixBegin = logsSet.find(absolute_entry_name +
"/" + allow);
801 if (itPrefixBegin == logsSet.end()) {
806 auto it = itPrefixBegin;
808 if (std::count(it->begin(), it->end(),
'/') == 3) {
819 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of(
"/") + 1);
820 file.openGroup(entry_name, entry_class);
821 lf_LoadByLogClass(
"NXlog",
true);
822 lf_LoadByLogClass(
"NXpositioner",
true);
823 lf_LoadByLogClass(
"IXseblock",
false);
838 const std::shared_ptr<API::MatrixWorkspace> &
workspace)
const {
840 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of(
"/") + 1);
841 g_log.
debug() <<
"processing " << entry_name <<
":" << entry_class <<
"\n";
842 file.openGroup(entry_name, entry_class);
845 std::string
const timeEntry = absolute_entry_name +
"/time";
846 std::string
const valueEntry = absolute_entry_name +
"/value";
847 std::string
const validatorEntry = absolute_entry_name +
"/value_valid";
848 bool const foundValue = file.hasAddress(valueEntry);
849 bool const foundTime = file.hasAddress(timeEntry);
850 bool const foundValidator = file.hasAddress(validatorEntry);
852 if (!foundTime || !foundValue) {
853 g_log.
warning() <<
"Invalid NXlog entry " << entry_name <<
" found. Did not contain 'value' and 'time'.\n";
859 bool overwritelogs = this->
getProperty(
"OverwriteLogs");
861 if (overwritelogs || !(
workspace->run().hasProperty(entry_name))) {
862 auto logValue = createTimeSeries(file, entry_name,
freqStart,
g_log);
864 if (foundValidator) {
865 auto validityLogValue = createTimeSeriesValidityFilter(file, *logValue,
g_log);
866 if (validityLogValue) {
867 appendEndTimeLog(validityLogValue.get(),
workspace->run());
868 workspace->mutableRun().addProperty(std::move(validityLogValue), overwritelogs);
872 appendEndTimeLog(logValue.get(),
workspace->run());
873 workspace->mutableRun().addProperty(std::move(logValue), overwritelogs);
876 g_log.
warning() <<
"NXlog entry " << entry_name <<
" gave an error when loading:'" << e.what() <<
"'.\n";
877 }
catch (std::invalid_argument &e) {
878 g_log.
warning() <<
"NXlog entry " << entry_name <<
" gave an error when loading:'" << e.what() <<
"'.\n";
885 const std::shared_ptr<API::MatrixWorkspace> &
workspace)
const {
887 const std::string entry_name = absolute_entry_name.substr(absolute_entry_name.find_last_of(
"/") + 1);
889 file.openGroup(entry_name,
"IXseblock");
890 std::string propName = entry_name;
891 if (
workspace->run().hasProperty(propName)) {
892 propName =
"selog_" + propName;
898 std::string
const valueEntry = absolute_entry_name +
"/value";
899 std::string
const valueLogEntry = absolute_entry_name +
"/value_log";
900 bool const foundValue = file.hasAddress(valueEntry);
901 bool const foundValueLog = file.hasAddress(valueLogEntry);
903 std::unique_ptr<Kernel::Property> logValue;
907 file.openGroup(
"value_log",
"NXlog");
915 auto validityLogValue = createTimeSeriesValidityFilter(file, *logValue,
g_log);
916 if (validityLogValue) {
917 appendEndTimeLog(validityLogValue.get(),
workspace->run());
918 workspace->mutableRun().addProperty(std::move(validityLogValue));
921 appendEndTimeLog(logValue.get(),
workspace->run());
924 }
catch (std::exception &e) {
925 g_log.
warning() <<
"IXseblock entry '" << entry_name <<
"' gave an error when loading "
926 <<
"a time series:'" << e.what() <<
"'. Skipping entry\n";
931 }
else if (foundValue) {
935 file.openData(
"value");
938 boost::scoped_array<float>
value(
new float[info.
dims[0]]);
939 file.getData(
value.get());
941 logValue = std::make_unique<Kernel::PropertyWithValue<double>>(propName,
static_cast<double>(
value[0]),
true);
947 g_log.
warning() <<
"IXseblock entry " << entry_name <<
" gave an error when loading "
948 <<
"a single value:'" << e.what() <<
"'.\n";
954 g_log.
warning() <<
"IXseblock entry " << entry_name <<
" cannot be read, skipping entry.\n";
958 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.