Mantid
Loading...
Searching...
No Matches
ExperimentInfo.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 +
11#include "MantidAPI/Run.h"
12#include "MantidAPI/Sample.h"
14
29
30#include "MantidBeamline/ComponentInfo.h"
31#include "MantidBeamline/DetectorInfo.h"
32#include "MantidBeamline/SpectrumInfo.h"
33
43
44#include "MantidTypes/SpectrumDefinition.h"
45
46#include <boost/algorithm/string.hpp>
47#include <boost/lexical_cast.hpp>
48#include <boost/regex.hpp>
49
50#include <Poco/Path.h>
51
52#include <algorithm>
53#include <map>
54#include <memory>
55#include <tuple>
56
57using namespace Mantid::Geometry;
58using namespace Mantid::Kernel;
59using namespace Mantid::Types::Core;
60
61namespace Mantid::API {
62namespace {
64Kernel::Logger g_log("ExperimentInfo");
65
66} // namespace
67
70ExperimentInfo::ExperimentInfo() : m_parmap(new ParameterMap()), sptr_instrument(new Instrument()) {
71 m_parmap->setInstrument(sptr_instrument.get());
73}
74
80ExperimentInfo::ExperimentInfo(const ExperimentInfo &source) { *this = source; }
81
90
91// Defined as default in source for forward declaration with std::unique_ptr.
93
99 m_sample = other->m_sample;
100 m_run = other->m_run;
101 this->setInstrument(other->getInstrument());
102 // We do not copy Beamline::SpectrumInfo (which contains detector grouping
103 // information) for now:
104 // - For MatrixWorkspace, grouping information is still stored in ISpectrum
105 // and should not be overridden (copy is done in ExperimentInfo ctor, but
106 // not here since we just copy the experiment data).
107 // - For cached groupings (for MDWorkspaces), grouping was not copied in the
108 // old implementation either.
109}
110
114
116const std::string ExperimentInfo::toString() const {
117 try {
119 } catch (std::exception &) {
120 // Catch any errors so that the string returned has as much information
121 // as possible
122 }
123
124 std::ostringstream out;
125
127 const auto instName = inst->getName();
128 out << "Instrument: ";
129 if (!instName.empty()) {
130 out << instName << " (" << inst->getValidFromDate().toFormattedString("%Y-%b-%d") << " to "
131 << inst->getValidToDate().toFormattedString("%Y-%b-%d") << ")";
132 const auto instFilename = inst->getFilename();
133 if (!instFilename.empty()) {
134 out << "Instrument from: " << instFilename;
135 out << "\n";
136 }
137 } else {
138 out << "None";
139 }
140 out << "\n";
141
142 // parameter files loaded
143 auto paramFileVector = this->constInstrumentParameters().getParameterFilenames();
144 for (auto const &itFilename : paramFileVector) {
145 out << "Parameters from: " << itFilename;
146 out << "\n";
147 }
148
149 std::string runStart = getAvailableWorkspaceStartDate();
150 std::string runEnd = getAvailableWorkspaceEndDate();
151 std::string msgNA = "not available";
152 if (runStart.empty())
153 runStart = msgNA;
154 if (runEnd.empty())
155 runEnd = msgNA;
156 out << "Run start: " << runStart << "\n";
157 out << "Run end: " << runEnd << "\n"; // note extra space for pseudo/approx-alignment
158
159 if (this->sample().hasOrientedLattice()) {
161 out << "Sample: a " << std::fixed << std::setprecision(1) << latt.a() << ", b " << latt.b() << ", c " << latt.c();
162 out << "; alpha " << std::fixed << std::setprecision(0) << latt.alpha() << ", beta " << latt.beta() << ", gamma "
163 << latt.gamma();
164 out << "\n";
165 }
166 return out.str();
167}
168
169// Helpers for setInstrument and getInstrument
170namespace {
171void checkDetectorInfoSize(const Instrument &instr, const Geometry::DetectorInfo &detInfo) {
172 const auto numDets = instr.getNumberDetectors();
173 if (numDets != detInfo.size())
174 throw std::runtime_error("ExperimentInfo: size mismatch between "
175 "DetectorInfo and number of detectors in "
176 "instrument: " +
177 std::to_string(detInfo.size()) + " vs " + std::to_string(numDets));
178}
179} // namespace
180
185 m_spectrumInfoWrapper = nullptr;
186
187 // Detector IDs that were previously dropped because they were not part of the
188 // instrument may now suddenly be valid, so we have to reinitialize the
189 // detector grouping. Also the index corresponding to specific IDs may have
190 // changed.
191 if (sptr_instrument != (instr->isParametrized() ? instr->baseInstrument() : instr)) {
193 }
194 if (instr->isParametrized()) {
195 sptr_instrument = instr->baseInstrument();
196 // We take a *copy* of the ParameterMap since we are modifying it by setting
197 // a pointer to our DetectorInfo, and in case it contains legacy parameters
198 // such as positions or rotations.
199 const auto &source = *instr->getParameterMap();
200 m_parmap = std::make_shared<ParameterMap>(source);
201 // The copy carries the source's instrument pointer, so the setInstrument() below sees no
202 // change and returns early. The beamline therefore has to be rebuilt explicitly -- this is
203 // the copy-on-write of the instrument geometry, and it used to happen implicitly inside
204 // ParameterMap's copy constructor.
205 m_parmap->rebuildBeamlineFrom(source);
206 } else {
207 sptr_instrument = instr;
208 m_parmap = std::make_shared<ParameterMap>();
209 }
210 m_parmap->setInstrument(sptr_instrument.get());
212}
213
215 m_componentInfo = m_parmap->sharedComponentInfo();
216 m_detectorInfo = m_parmap->sharedDetectorInfo();
217 m_instrumentMetadata = m_parmap->sharedInstrumentMetadata();
218}
219
230
238
246
254
255namespace {
257
261struct RTP {
262 RTP() : radius(0.0), haveRadius(false), theta(0.0), phi(0.0) {}
263 double radius;
264 bool haveRadius;
265 double theta;
266 double phi;
267};
268
269struct ParameterValue {
270 ParameterValue(const Geometry::XMLInstrumentParameter &paramInfo, const API::Run &run)
271 : info(paramInfo), runData(run) {}
272
273 operator double() {
274 if (info.m_logfileID.empty())
275 return boost::lexical_cast<double>(info.m_value);
276 else {
277 const TimeROI *roi = &runData.getTimeROI();
278 return info.createParamValue(runData.getTimeSeriesProperty<double>(info.m_logfileID), roi);
279 }
280 }
281 operator int() { return boost::lexical_cast<int>(info.m_value); }
282 operator bool() {
283 if (boost::iequals(info.m_value, "true"))
284 return true;
285 else if (boost::iequals(info.m_value, "yes"))
286 return true;
287 else
288 return false;
289 }
291 const Run &runData;
292};
294} // namespace
295
296namespace {
297bool isPositionParameter(const std::string &name) { return ParameterMap::pos() == name; }
298
299bool isRotationParameter(const std::string &name) { return ParameterMap::rot() == name; }
300
301bool isScaleParameter(const std::string &name) { return (name == "scalex" || name == "scaley"); }
302
303bool isRedundantPosOrRot(const std::string &name) {
304 // Check size first as a small optimization.
305 return (name.size() == 4) &&
306 (name == "posx" || name == "posy" || name == "posz" || name == "rotx" || name == "roty" || name == "rotz");
307}
308
309template <class T> T getParam(const std::string &paramType, const std::string &paramValue) {
310 const std::string name = "dummy";
311 auto param = ParameterFactory::create(paramType, name);
312 param->fromString(paramValue);
313 return param->value<T>();
314}
315
316void updatePosition(ComponentInfo &componentInfo, const size_t compIndex, const V3D &newRelPos) {
317 V3D position = newRelPos;
318 if (componentInfo.hasParent(compIndex)) {
319 const auto parentIndex = componentInfo.parent(compIndex);
320 componentInfo.rotation(parentIndex).rotate(position);
321 position += componentInfo.position(parentIndex);
322 }
323 componentInfo.setPosition(compIndex, position);
324}
325
326void updateRotation(ComponentInfo &componentInfo, const size_t compIndex, const Quat &newRelRot) {
327 auto rotation = newRelRot;
328 if (componentInfo.hasParent(compIndex)) {
329 const auto parentIndex = componentInfo.parent(compIndex);
330 rotation = componentInfo.rotation(parentIndex) * newRelRot;
331 }
332 componentInfo.setRotation(compIndex, rotation);
333}
334
335void adjustPositionsFromScaleFactor(ComponentInfo &componentInfo, const size_t compIndex, const std::string &paramName,
336 double factor) {
337 double ScaleX = 1.0;
338 double ScaleY = 1.0;
339 if (paramName == "scalex")
340 ScaleX = factor;
341 else
342 ScaleY = factor;
343 applyRectangularDetectorScaleToComponentInfo(componentInfo, compIndex, ScaleX, ScaleY);
344}
345} // namespace
346
355
356 // Reference to the run
357 const auto &runData = run();
358
359 // Get pointer to parameter map that we may add parameters to and information
360 // about
361 // the parameters that my be specified in the instrument definition file (IDF)
364
365 // Get instrument and sample
366 auto &compInfo = mutableComponentInfo();
367 const auto parInstrument = getInstrument();
368 const auto instrument = parInstrument->baseInstrument();
369 const auto &paramInfoFromIDF = instrument->getLogfileCache();
370
371 std::map<const IComponent *, RTP> rtpParams;
372
373 // In this loop position and rotation parameters are inserted into the
374 // temporary map paramMapForPosAndRot. In the subsequent loop, after all
375 // parameters have been parsed, we update positions and rotations in
376 // DetectorInfo and the temporary map goes out of scope. The main reason for
377 // this is that ParameterMap will then take care of assembling parameters for
378 // individual position or rotation components into a vector or quaternion. In
379 // particular, we cannot directly change DetectorInfo since the order of
380 // rotation components is not guaranteed.
381 for (const auto &item : paramInfoFromIDF) {
382 const auto &paramInfo = item.second;
383 // Use the parameter's short name (e.g. "Alpha0"), not the cache key. The cache key may be
384 // function-qualified (e.g. "IkedaCarpenterPV:Alpha0") to keep two functions on the same
385 // component from clobbering each other, but downstream consumers always look up by short name.
386 const std::string &paramN = paramInfo->m_paramName;
387
388 try {
389 // Special case where user has specified r-position,t-position, and/or
390 // p-position.
391 // We need to know all three first to calculate a set of X,Y,Z
392 if (paramN.compare(1, 9, "-position") == 0) {
393 auto &rtpValues = rtpParams[paramInfo->m_component]; // If not found,
394 // constructs
395 // default
396 double value = ParameterValue(*paramInfo, runData);
397 if (paramN.compare(0, 1, "r") == 0) {
398 rtpValues.radius = value;
399 rtpValues.haveRadius = true;
400 } else if (paramN.compare(0, 1, "t") == 0)
401 rtpValues.theta = value;
402 else if (paramN.compare(0, 1, "p") == 0)
403 rtpValues.phi = value;
404 if (rtpValues.haveRadius) {
405 V3D pos;
406 pos.spherical(rtpValues.radius, rtpValues.theta, rtpValues.phi);
407 const auto compIndex = compInfo.indexOfOrInvalid(paramInfo->m_component->getComponentID());
408 if (compIndex != Geometry::ComponentInfo::invalidIndex) {
409 posAndRot.setPosition(compIndex, pos);
410 }
411 }
412 } else {
413 populateWithParameter(paramMap, posAndRot, paramN, *paramInfo, runData);
414 }
415 } catch (std::exception &exc) {
416 g_log.information() << "Unable to add component parameter '" << paramN << "'. Error: " << exc.what();
417 continue;
418 }
419 }
420 // Each component's position and rotation is applied once, complete. The accumulator has
421 // already folded the individual x/y/z coordinates and rotx/roty/rotz angles together, so
422 // there are no partial values left to ignore here.
423 for (const auto &[compIndex, newRelPos] : posAndRot.positions()) {
424 updatePosition(compInfo, compIndex, newRelPos);
425 }
426 for (const auto &[compIndex, newRelRot] : posAndRot.rotations()) {
427 updateRotation(compInfo, compIndex, newRelRot);
428 }
429 // Special case RectangularDetector: Parameters scalex and scaley affect pixel
430 // positions.
431 for (const auto &item : paramMap.entries()) {
432 if (isScaleParameter(item.second->name())) {
433 const auto compIndex = compInfo.indexOfOrInvalid(item.first);
434 if (compIndex != Geometry::ComponentInfo::invalidIndex) {
435 adjustPositionsFromScaleFactor(compInfo, compIndex, item.second->name(), item.second->value<double>());
436 }
437 }
438 }
439 // paramMapForPosAndRot goes out of scope, dropping all position and rotation
440 // parameters of detectors (parameters for non-detector components have been
441 // inserted into paramMap via DetectorInfo::setPosition(IComponent *)).
442}
443
451 if (m_spectrumInfo)
454 m_spectrumInfo = std::make_unique<Beamline::SpectrumInfo>(count);
455 m_spectrumInfoWrapper = nullptr;
456}
457
463
468void ExperimentInfo::setDetectorGrouping(const size_t index, const std::set<detid_t> &detIDs) const {
469 SpectrumDefinition specDef;
470 for (const auto detID : detIDs) {
471 try {
472 const size_t detIndex = detectorInfo().indexOf(detID);
473 specDef.add(detIndex);
474 } catch (std::out_of_range &) {
475 // Silently strip bad detector IDs
476 }
477 }
478 m_spectrumInfo->setSpectrumDefinition(index, std::move(specDef));
480}
481
489void ExperimentInfo::updateCachedDetectorGrouping(const size_t /*unused*/) const {
490 throw std::runtime_error("ExperimentInfo::updateCachedDetectorGrouping: "
491 "Cannot update -- grouping information not "
492 "available");
493}
494
500 return *m_sample;
501}
502
512
516const Run &ExperimentInfo::run() const {
518 return *m_run;
519}
520
528 return m_run.access();
529}
530
533
536
549Kernel::Property *ExperimentInfo::getLog(const std::string &log) const {
551 try {
552 return run().getProperty(log);
554 // No log with that name
555 }
556 // If the instrument has a parameter with that name then take the value as a
557 // log name
558 const std::string logName = constInstrumentParameters().getString(sptr_instrument.get(), log);
559 if (logName.empty()) {
560 throw std::invalid_argument("ExperimentInfo::getLog - No instrument parameter named \"" + log +
561 "\". Cannot access full log name");
562 }
563 return run().getProperty(logName);
564}
565
574double ExperimentInfo::getLogAsSingleValue(const std::string &log) const {
576 try {
577 return run().getPropertyAsSingleValue(log);
579 // No log with that name
580 }
581 // If the instrument has a parameter with that name then take the value as a
582 // log name
583 const std::string logName = constInstrumentParameters().getString(sptr_instrument.get(), log);
584 if (logName.empty()) {
585 throw std::invalid_argument("ExperimentInfo::getLog - No instrument parameter named \"" + log +
586 "\". Cannot access full log name");
587 }
588 return run().getPropertyAsSingleValue(logName);
589}
590
597 const Run &thisRun = run();
598 if (!thisRun.hasProperty("run_number")) {
599 // No run_number property, default to 0
600 return 0;
601 } else {
602 Property const *prop = m_run->getProperty("run_number");
603 if (prop) {
604 // Use the string representation. That way both a string and a number
605 // property will work.
606 int val;
607 if (Strings::convert(prop->value(), val))
608 return val;
609 else
610 return 0;
611 }
612 }
613 return 0;
614}
615
626 static const char *emodeTag = "deltaE-mode";
627 std::string emodeStr;
628 if (run().hasProperty(emodeTag)) {
629 emodeStr = run().getPropertyValueAsType<std::string>(emodeTag);
630 } else if (sptr_instrument && constInstrumentParameters().contains(sptr_instrument.get(), emodeTag)) {
632 emodeStr = param->asString();
633 } else {
635 }
636 return Kernel::DeltaEMode::fromString(emodeStr);
637}
638
648double ExperimentInfo::getEFixed(const detid_t detID) const {
650 IDetector_const_sptr det = getInstrument()->getDetector(detID);
651 return getEFixed(det);
652}
653
660double ExperimentInfo::getEFixed(const std::shared_ptr<const Geometry::IDetector> &detector) const {
663 return getEFixedGivenEMode(detector, emode);
664}
665
666double ExperimentInfo::getEFixedForIndirect(const std::shared_ptr<const Geometry::IDetector> &detector,
667 const std::vector<std::string> &parameterNames) const {
668 double efixed = 0.;
669 for (auto &parameterName : parameterNames) {
670 Parameter_sptr par = constInstrumentParameters().getRecursive(detector.get(), parameterName);
671 if (par) {
672 efixed = par->value<double>();
673 } else {
674 std::vector<double> efixedVec = detector->getNumberParameter(parameterName);
675 if (efixedVec.empty()) {
676 int detid = detector->getID();
677 IDetector_const_sptr detectorSingle = getInstrument()->getDetector(detid);
678 efixedVec = detectorSingle->getNumberParameter(parameterName);
679 }
680 if (!efixedVec.empty()) {
681 efixed = efixedVec.at(0);
682 }
683 }
684 }
685 if (efixed == 0.) {
686 std::ostringstream os;
687 os << "ExperimentInfo::getEFixed - Indirect mode efixed requested but "
688 "detector has no Efixed parameter attached. ID="
689 << detector->getID();
690 throw std::runtime_error(os.str());
691 }
692 return efixed;
693}
694
702double ExperimentInfo::getEFixedGivenEMode(const std::shared_ptr<const Geometry::IDetector> &detector,
703 const Kernel::DeltaEMode::Type emode) const {
704 if (emode == Kernel::DeltaEMode::Direct) {
705 double efixed = 0.;
706 for (auto &parameterName : {"Ei", "EnergyRequested", "EnergyEstimate"}) {
707 if (run().hasProperty(parameterName)) {
708 efixed = run().getPropertyValueAsType<double>(parameterName);
709 break;
710 }
711 }
712 if (efixed == 0.) {
713 throw std::runtime_error("Experiment logs do not contain an Ei "
714 "value. Have you run GetEi?");
715 }
716 return efixed;
717 } else if (emode == Kernel::DeltaEMode::Indirect) {
718 if (!detector)
719 throw std::runtime_error("ExperimentInfo::getEFixed - Indirect mode "
720 "efixed requested without a valid detector.");
721 return getEFixedForIndirect(detector, {"Efixed", "EFixed-val"});
722 } else {
723 throw std::runtime_error("ExperimentInfo::getEFixed - EFixed requested for "
724 "elastic mode, don't know what to do!");
725 }
726}
727
728void ExperimentInfo::setEFixed(const detid_t detID, const double value) {
730 IDetector_const_sptr det = getInstrument()->getDetector(detID);
732 pmap.addDouble(det.get(), "Efixed", value);
733}
734
745 std::string date;
746 try {
747 date = run().startTime().toISO8601String();
748 } catch (std::runtime_error &) {
749 g_log.information("run_start/start_time not stored in workspace. Default "
750 "to current date.");
751 date = Types::Core::DateAndTime::getCurrentTime().toISO8601String();
752 }
753 return date;
754}
755
764 std::string date;
765 try {
766 date = run().startTime().toFormattedString();
767 } catch (std::runtime_error &) {
768 g_log.information("Note: run_start/start_time not stored in workspace.");
769 }
770 return date;
771}
772
781 std::string date;
782 try {
783 date = run().endTime().toFormattedString();
784 } catch (std::runtime_error &) {
785 g_log.information("Note: run_start/start_time not stored in workspace.");
786 }
787 return date;
788}
789
790//-----------------------------------------------------------------------------------------------------------------------
791
799 if (!m_detectorInfo) {
800 throw std::runtime_error("Cannot return reference to NULL DetectorInfo");
801 }
802 return *m_detectorInfo;
803}
804
808 if (!m_detectorInfo) {
809 throw std::runtime_error("Cannot return reference to NULL DetectorInfo");
810 }
811 return *m_detectorInfo;
812}
813
822 std::lock_guard<std::mutex> lock{m_spectrumInfoMutex};
823 if (!m_spectrumInfo) // this should happen only if not MatrixWorkspace
826 static_cast<void>(detectorInfo());
827 m_spectrumInfoWrapper = std::make_unique<SpectrumInfo>(*m_spectrumInfo, *this, m_parmap->mutableDetectorInfo());
828 }
829 }
830 // Rebuild any spectrum definitions that are out of date. Accessing
831 // `API::SpectrumInfo` will rebuild invalid spectrum definitions as it
832 // encounters them (if detector IDs in an `ISpectrum` are changed), however we
833 // need to deal with one special case here:
834 // If two algorithms (or two threads in the same algorithm) access the same
835 // workspace for reading at the same time, calls to
836 // `updateSpectrumDefinitionIfNecessary` done by `API::SpectrumInfo` break
837 // thread-safety. `Algorithm` sets a read-lock, but this lazy update method is
838 // `const` and will modify internals of the workspace nevertheless. We thus
839 // need explicit locking here. Note that we do not need extra locking in the
840 // case of `ExperimentInfo::mutableSpectrumInfo` or other calls to
841 // `updateSpectrumDefinitionIfNecessary` done by `API::SpectrumInfo`: If the
842 // workspace is only read-locked, this update will ensure that no updates will
843 // be triggered by SpectrumInfo, since changing detector IDs in an `ISpectrum`
844 // is not possible for a read-only workspace. If the workspace is write-locked
845 // detector IDs in ISpectrum may change, but the write-lock by `Algorithm`
846 // guarantees that there is no concurrent reader and thus updating is safe.
848 [](char i) { return i == 1; })) {
849 std::lock_guard<std::mutex> lock{m_spectrumInfoMutex};
851 [](char i) { return i == 1; })) {
852 auto size = static_cast<int64_t>(m_spectrumInfoWrapper->size());
853#pragma omp parallel for
854 for (int64_t i = 0; i < size; ++i) {
856 }
857 }
858 }
859 return *m_spectrumInfoWrapper;
860}
861
865 return const_cast<SpectrumInfo &>(static_cast<const ExperimentInfo &>(*this).spectrumInfo());
866}
867
869 if (!m_componentInfo) {
870 throw std::runtime_error("Cannot return reference to NULL ComponentInfo");
871 }
872 return *m_componentInfo;
873}
874
876 if (!m_componentInfo) {
877 throw std::runtime_error("Cannot return reference to NULL ComponentInfo");
878 }
879 return *m_componentInfo;
880}
881
884 throw std::runtime_error("Cannot return reference to NULL InstrumentMetadata");
885 }
886 return *m_instrumentMetadata;
887}
888
890void ExperimentInfo::setSpectrumDefinitions(Kernel::cow_ptr<std::vector<SpectrumDefinition>> spectrumDefinitions) {
891 if (spectrumDefinitions) {
892 m_spectrumInfo = std::make_unique<Beamline::SpectrumInfo>(std::move(spectrumDefinitions));
895 } else {
896 // Keep the old m_spectrumInfo which should have the correct size, but
897 // invalidate all definitions.
899 }
900 m_spectrumInfoWrapper = nullptr;
901}
902
906 Geometry::ComponentInfo const &compInfo = componentInfo();
907 return compInfo.name(compInfo.root());
908}
909
916 // This uses a vector of char, such that flags for different indices can be
917 // set from different threads (std::vector<bool> is not thread-safe).
919}
920
925
932 if (m_spectrumInfo && (m_spectrumInfo->size() != 0))
933 return;
934 const auto &detIDs = sptr_instrument->getDetectorIDs();
935 setNumberOfDetectorGroups(detIDs.size());
936 size_t specIndex = 0;
937 for (const auto detID : detIDs) {
938 m_det2group[detID] = specIndex;
939 const size_t detIndex = detectorInfo().indexOf(detID);
940 SpectrumDefinition specDef;
941 specDef.add(detIndex);
942 // cppcheck-suppress nullPointerRedundantCheck
943 m_spectrumInfo->setSpectrumDefinition(specIndex, std::move(specDef));
944 m_spectrumDefinitionNeedsUpdate.at(specIndex) = 0;
945 specIndex++;
946 }
947}
948
954
959void ExperimentInfo::saveExperimentInfoNexus(Nexus::File *file, bool saveLegacyInstrument) const {
961 if (saveLegacyInstrument) {
962 instrument->saveNexus(file, "instrument");
963 }
964 sample().saveNexus(file, "sample");
965 run().saveNexus(file, "logs");
966}
967
974void ExperimentInfo::saveExperimentInfoNexus(Nexus::File *file, bool saveInstrument, bool saveSample,
975 bool saveLogs) const {
977
978 if (saveInstrument)
979 instrument->saveNexus(file, "instrument");
980 if (saveSample)
981 sample().saveNexus(file, "sample");
982 if (saveLogs)
983 run().saveNexus(file, "logs");
984}
985
990void ExperimentInfo::loadSampleAndLogInfoNexus(Nexus::File *file, std::string const &prefix) {
991 // First, the sample and then the logs
992 int sampleVersion = mutableSample().loadNexus(file, "sample");
993 if (sampleVersion == 0) {
994 // Old-style (before Sep-9-2011) NXS processed
995 // sample field contains both the logs and the sample details
996 file->openGroup("sample", "NXsample");
997 this->mutableRun().loadNexus(file, "", prefix);
998 file->closeGroup();
999 } else {
1000 // Newer style: separate "logs" field for the Run object
1001 this->mutableRun().loadNexus(file, "logs", prefix);
1002 }
1003}
1004
1009 // First, the sample and then the logs
1010 int sampleVersion = mutableSample().loadNexus(file, "sample");
1011 if (sampleVersion == 0) {
1012 // Old-style (before Sep-9-2011) NXS processed
1013 // sample field contains both the logs and the sample details
1014 file->openGroup("sample", "NXsample");
1015 this->mutableRun().loadNexus(file, "");
1016 file->closeGroup();
1017 } else {
1018 // Newer style: separate "logs" field for the Run object
1019 this->mutableRun().loadNexus(file, "logs");
1020 }
1021}
1022
1023void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename, Nexus::File *file,
1024 std::string &parameterStr, const std::string &prefix) {
1025 // TODO load sample and log info
1026 loadSampleAndLogInfoNexus(file, prefix);
1027 loadInstrumentInfoNexus(nxFilename, file, parameterStr);
1028}
1029
1040void ExperimentInfo::loadExperimentInfoNexus(const std::string &nxFilename, Nexus::File *file,
1041 std::string &parameterStr) {
1042 // load sample and log info
1044
1045 loadInstrumentInfoNexus(nxFilename, file, parameterStr);
1046}
1047
1058void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, Nexus::File *file,
1059 std::string &parameterStr) {
1060
1061 // Open instrument group
1062 file->openGroup("instrument", "NXinstrument");
1063
1064 // Try to get the instrument embedded in the Nexus file
1065 std::string instrumentName;
1066 std::string instrumentXml;
1067 loadEmbeddedInstrumentInfoNexus(file, instrumentName, instrumentXml);
1068
1069 // load parameters if found
1070 loadInstrumentParametersNexus(file, parameterStr);
1071
1072 // Close the instrument group
1073 file->closeGroup();
1074
1075 // Set the instrument given the name and and XML obtained
1076 setInstumentFromXML(nxFilename, instrumentName, instrumentXml);
1077}
1078
1088void ExperimentInfo::loadInstrumentInfoNexus(const std::string &nxFilename, Nexus::File *file) {
1089
1090 // Open instrument group
1091 file->openGroup("instrument", "NXinstrument");
1092
1093 // Try to get the instrument embedded in the Nexus file
1094 std::string instrumentName;
1095 std::string instrumentXml;
1096 loadEmbeddedInstrumentInfoNexus(file, instrumentName, instrumentXml);
1097
1098 // Close the instrument group
1099 file->closeGroup();
1100
1101 // Set the instrument given the name and and XML obtained
1102 setInstumentFromXML(nxFilename, instrumentName, instrumentXml);
1103}
1104
1111void ExperimentInfo::loadEmbeddedInstrumentInfoNexus(Nexus::File *file, std::string &instrumentName,
1112 std::string &instrumentXml) {
1113
1114 file->readData("name", instrumentName);
1115
1116 try {
1117 file->openGroup("instrument_xml", "NXnote");
1118 file->readData("data", instrumentXml);
1119 file->closeGroup();
1120 } catch (Nexus::Exception const &ex) {
1121 g_log.debug(std::string("Unable to load instrument_xml: ") + ex.what());
1122 }
1123}
1124
1134void ExperimentInfo::setInstumentFromXML(const std::string &nxFilename, std::string &instrumentName,
1135 std::string &instrumentXml) {
1136
1137 instrumentXml = Strings::strip(instrumentXml);
1138 instrumentName = Strings::strip(instrumentName);
1139 std::string instrumentFilename;
1140 if (!instrumentXml.empty()) {
1141 // instrument xml is being loaded from the nxs file, set the
1142 // instrumentFilename
1143 // to identify the Nexus file as the source of the data
1144 instrumentFilename = nxFilename;
1145 g_log.debug() << "Using instrument IDF XML text contained in nexus file.\n";
1146 } else {
1147 // XML was not included or was empty
1148 // Use the instrument name to find the file
1149 instrumentFilename = InstrumentFileFinder::getInstrumentFilename(instrumentName, getWorkspaceStartDate());
1150 // And now load the contents
1151 instrumentXml = loadInstrumentXML(instrumentFilename);
1152 }
1153
1154 // ---------- Now parse that XML to make the instrument -------------------
1155 if (!instrumentXml.empty() && !instrumentName.empty()) {
1156 InstrumentDefinitionParser parser(instrumentFilename, instrumentName, instrumentXml);
1157
1158 std::string instrumentNameMangled = parser.getMangledName();
1159 Instrument_sptr instr;
1160 // Check whether the instrument is already in the InstrumentDataService
1161 if (InstrumentDataService::Instance().doesExist(instrumentNameMangled)) {
1162 // If it does, just use the one from the one stored there
1163 instr = InstrumentDataService::Instance().retrieve(instrumentNameMangled);
1164 } else {
1165 // Really create the instrument
1166 instr = parser.parseXML(nullptr);
1167 // Parse the instrument tree (internally create ComponentInfo and
1168 // DetectorInfo). This is an optimization that avoids duplicate parsing
1169 // of the instrument tree when loading multiple workspaces with the same
1170 // instrument. As a consequence less time is spent and less memory is
1171 // used. Note that this is only possible since the tree in `instrument`
1172 // will not be modified once we add it to the IDS.
1173 instr->parseTreeAndCacheBeamline();
1174
1175 // Add to data service for later retrieval
1176 InstrumentDataService::Instance().add(instrumentNameMangled, instr);
1177 }
1178 // Now set the instrument
1179 this->setInstrument(instr);
1180 }
1181}
1182
1189std::string ExperimentInfo::loadInstrumentXML(const std::string &filename) {
1190 try {
1191 return Strings::loadFile(filename);
1192 } catch (std::exception &e) {
1193 g_log.error() << "Error loading instrument IDF file: " << filename << ".\n";
1194 g_log.debug() << e.what() << '\n';
1195 throw;
1196 }
1197}
1198
1205void ExperimentInfo::loadInstrumentParametersNexus(Nexus::File *file, std::string &parameterStr) {
1206 try {
1207 file->openGroup("instrument_parameter_map", "NXnote");
1208 file->readData("data", parameterStr);
1209 file->closeGroup();
1210 } catch (Nexus::Exception const &ex) {
1211 g_log.debug(std::string("Unable to load instrument_parameter_map: ") + ex.what());
1212 g_log.information("Parameter map entry missing from NeXus file. Continuing without it.");
1213 }
1214}
1215
1222void ExperimentInfo::readParameterMap(const std::string &parameterStr) {
1224 auto &compInfo = mutableComponentInfo();
1225 auto &detInfo = mutableDetectorInfo();
1226 const auto parInstrument = getInstrument();
1227 const auto instr = parInstrument->baseInstrument();
1228
1231 Mantid::Kernel::StringTokenizer splitter(parameterStr, "|", options);
1232
1233 auto iend = splitter.end();
1234
1236 const std::string visibilityKey = "visible:"; // if visibility is defined, the value will follow this key
1237 // std::string prev_name;
1238 for (auto itr = splitter.begin(); itr != iend; ++itr) {
1239 tokens = Mantid::Kernel::StringTokenizer(*itr, ";");
1240 if (tokens.count() < 4)
1241 continue;
1242 std::string comp_name = tokens[0];
1243 // if( comp_name == prev_name ) continue; this blocks reading in different
1244 // parameters of the same component. RNT
1245 // prev_name = comp_name;
1246 // Resolve the component once, to an index. Both forms written by ParameterMap::asString()
1247 // are resolvable without consulting the legacy instrument tree: "detID:<id>" through
1248 // DetectorInfo, and a full path through ComponentInfo::indexOfFullName().
1249 size_t compIndex = Geometry::ComponentInfo::invalidIndex;
1250 if (comp_name.find("detID:") != std::string::npos) {
1251 const auto detID = static_cast<detid_t>(std::stoi(comp_name.substr(6)));
1252 try {
1253 // Detectors occupy the leading component indices, so a detector index is also its
1254 // component index.
1255 compIndex = detInfo.indexOf(detID);
1256 } catch (std::out_of_range &) {
1257 g_log.warning() << "Cannot find detector " << detID << '\n';
1258 continue;
1259 }
1260 } else {
1261 compIndex = compInfo.indexOfFullName(comp_name);
1262 if (compIndex == Geometry::ComponentInfo::invalidIndex) {
1263 // indexOfFullName() resolves only exact, fully-rooted paths. getComponentByName() is
1264 // more lenient -- it accepts a bare name anywhere in the tree and lets path segments be
1265 // skipped -- so fall back to it rather than rejecting strings the old code accepted.
1266 // Reproducing that leniency on ComponentInfo is its own piece of work.
1267 const auto *comp = instr->getComponentByName(comp_name).get();
1268 if (comp) {
1269 compIndex = compInfo.indexOfOrInvalid(comp->getComponentID());
1270 }
1271 if (compIndex == Geometry::ComponentInfo::invalidIndex) {
1272 g_log.warning() << "Cannot find component " << comp_name << '\n';
1273 continue;
1274 }
1275 }
1276 }
1277
1278 // create parameter's value as a sum of all tokens with index 3 or larger
1279 // this allow a parameter's value to contain ";"
1280 std::string paramValue = tokens[3];
1281 auto size = static_cast<int>(tokens.count());
1282 for (int i = 4; i < size; i++)
1283 paramValue += ";" + tokens[i];
1284 const auto &paramType = tokens[1];
1285 const auto &paramName = tokens[2];
1286 auto &paramVisibility = tokens[size - 1]; // parameter visibility, if defined, is the last token
1287 if (paramVisibility.find(visibilityKey) > paramVisibility.size())
1288 paramVisibility = "true"; // visibility not defined: default to visible
1289 else { // defined, the paramValue has one too many entries, -1 to remove also the semicolon
1290 paramVisibility =
1291 paramVisibility.substr(paramVisibility.find(visibilityKey) + visibilityKey.size(), paramVisibility.size());
1292 paramValue.erase(paramValue.find(visibilityKey) - 1, paramValue.size());
1293 }
1294 const auto paramDescr = std::string("");
1295 if (paramName == "masked") {
1296 auto value = getParam<bool>(paramType, paramValue);
1297 if (value) {
1298 // Do not add masking to ParameterMap, it is stored in DetectorInfo
1299 const auto componentIndex = compIndex;
1300 if (!compInfo.isDetector(componentIndex)) {
1301 throw std::runtime_error("Found masking for a non-detector "
1302 "component. This is not possible");
1303 } else
1304 detInfo.setMasked(componentIndex, value); // all detector indexes
1305 // have same component
1306 // index (guarantee)
1307 }
1308 } else if (isPositionParameter(paramName)) {
1309 // We are parsing a string obtained from a ParameterMap. The map may
1310 // contain posx, posy, and posz (in addition to pos). However, when these
1311 // component wise positions are set, 'pos' is updated accordingly. We are
1312 // thus ignoring position components below.
1313 const auto newRelPos = getParam<V3D>(paramType, paramValue);
1314 updatePosition(compInfo, compIndex, newRelPos);
1315 } else if (isRotationParameter(paramName)) {
1316 // We are parsing a string obtained from a ParameterMap. The map may
1317 // contain rotx, roty, and rotz (in addition to rot). However, when these
1318 // component wise rotations are set, 'rot' is updated accordingly. We are
1319 // thus ignoring rotation components below.
1320 const auto newRelRot = getParam<Quat>(paramType, paramValue);
1321 updateRotation(compInfo, compIndex, newRelRot);
1322 } else if (!isRedundantPosOrRot(paramName)) {
1323 // Special case RectangularDetector: Parameters scalex and scaley affect
1324 // pixel positions, but we must also add the parameter below.
1325 if (isScaleParameter(paramName))
1326 adjustPositionsFromScaleFactor(compInfo, compIndex, paramName, getParam<double>(paramType, paramValue));
1327 // For fitting parameters, route through addFittingParameter so that two functions on the same
1328 // component sharing a parameter short name (e.g. IkedaCarpenterPV:Gamma and
1329 // Bk2BkExpConvPV:Gamma) both survive a NeXus save/load round-trip. ParameterMap::add only
1330 // dedupes by (component, name) and would silently overwrite the first entry with the second.
1331 // The fitting-function name is embedded as the second comma-separated field of the value
1332 // string written by populateWithParameter().
1333
1334 // string from populateWithParameter() is expected to be " , " (space-comma-space) separated:
1335 // "m_value , m_fittingFunction , name , constraint[0] , constraint[1] , penaltyFactor , tie ,
1336 // formula , formulaUnit , resultUnit , interpolation"
1337 if (paramType == "fitting") {
1338 std::string fittingFunction;
1339 // Locate the second field by finding the first two commas; the fitting function is the
1340 // text between them. If there are fewer than two commas the value is malformed and
1341 // fittingFunction stays empty, falling back to the plain add() below.
1342 const auto firstComma = paramValue.find(',');
1343 if (firstComma != std::string::npos) {
1344 const auto secondComma = paramValue.find(',', firstComma + 1);
1345 if (secondComma != std::string::npos) {
1346 // Take the raw second field, e.g. " IkedaCarpenterPV " from "3.5 , IkedaCarpenterPV , ...".
1347 fittingFunction = paramValue.substr(firstComma + 1, secondComma - firstComma - 1);
1348 // Trim the surrounding spaces/tabs introduced by the " , " separator.
1349 const auto firstNonSpace = fittingFunction.find_first_not_of(" \t");
1350 if (firstNonSpace != std::string::npos) {
1351 const auto lastNonSpace = fittingFunction.find_last_not_of(" \t");
1352 fittingFunction = fittingFunction.substr(firstNonSpace, lastNonSpace - firstNonSpace + 1);
1353 } else
1354 // Field was entirely whitespace (e.g. "3.5 , , ..."): treat as no fitting function.
1355 fittingFunction.clear();
1356 }
1357 }
1358 if (!fittingFunction.empty()) {
1359 pmap.addFittingParameter(compIndex, paramName, fittingFunction, paramValue, &paramDescr, paramVisibility);
1360 } else {
1361 pmap.add(paramType, compIndex, paramName, paramValue, &paramDescr, paramVisibility);
1362 }
1363 } else {
1364 pmap.add(paramType, compIndex, paramName, paramValue, &paramDescr, paramVisibility);
1365 }
1366 }
1367 }
1368}
1369
1381 Geometry::PositionAndRotationAccumulator &posAndRot, const std::string &name,
1382 const Geometry::XMLInstrumentParameter &paramInfo, const Run &runData) {
1383 const std::string &category = paramInfo.m_type;
1384 ParameterValue paramValue(paramInfo,
1385 runData); // Defines implicit conversion operator
1386
1387 const std::string *pDescription = nullptr;
1388 if (!paramInfo.m_description.empty())
1389 pDescription = &paramInfo.m_description;
1390 std::string pVisible = "true";
1391 if (!paramInfo.m_visible.empty())
1392 pVisible = paramInfo.m_visible;
1393
1394 // Some names are special. Values should be convertible to double
1395 if (name == "masked") {
1396 bool value(paramValue);
1397 if (value) {
1398 // Do not add masking to ParameterMap, it is stored in DetectorInfo
1399
1400 const auto componentIndex = componentInfo().indexOf(paramInfo.m_component->getComponentID());
1401 if (!componentInfo().isDetector(componentIndex))
1402 throw std::runtime_error("Found masking for a non-detector component. This is not possible");
1403 mutableDetectorInfo().setMasked(componentIndex,
1404 paramValue); // all detector indexes have
1405 // same component index
1406 // (guarantee)
1407 }
1408 } else if (name == "x" || name == "y" || name == "z") {
1409 const auto compIndex = componentInfo().indexOfOrInvalid(paramInfo.m_component->getComponentID());
1410 if (compIndex != Geometry::ComponentInfo::invalidIndex) {
1411 // Seeded from the component's current position relative to its parent, so specifying one
1412 // coordinate leaves the other two alone. It must be the relative position: the accumulated
1413 // value is applied as a parent-relative one, so seeding with the absolute position would
1414 // re-apply the parent's rotation and translation on every call.
1415 posAndRot.setCoordinate(compIndex, name, paramValue, componentInfo().relativePosition(compIndex));
1416 }
1417 } else if (name == "rot" || name == "rotx" || name == "roty" || name == "rotz") {
1418 const auto compIndex = componentInfo().indexOfOrInvalid(paramInfo.m_component->getComponentID());
1419 if (compIndex != Geometry::ComponentInfo::invalidIndex &&
1420 !posAndRot.setRotationAngle(compIndex, name, paramValue)) {
1421 // "rot" itself names no axis and is deliberately dropped, as it always has been.
1422 g_log.warning() << "Ignoring instrument parameter '" << name << "': it does not name a rotation axis.\n";
1423 }
1424 } else if (category == "fitting") {
1425 std::ostringstream str;
1426 // read parameter map relies on extracting m_fittingFunction from this string - edit with care
1427 str << paramInfo.m_value << " , " << paramInfo.m_fittingFunction << " , " << name << " , "
1428 << paramInfo.m_constraint[0] << " , " << paramInfo.m_constraint[1] << " , " << paramInfo.m_penaltyFactor
1429 << " , " << paramInfo.m_tie << " , " << paramInfo.m_formula << " , " << paramInfo.m_formulaUnit << " , "
1430 << paramInfo.m_resultUnit << " , " << (*(paramInfo.m_interpolation));
1431 // Dedupe by (name, fitting function) — otherwise two functions on the same component sharing
1432 // a parameter short name (e.g. Bk2BkExpConvPV:Gamma and IkedaCarpenterPV:Gamma) would clobber
1433 // each other in the map.
1434 paramMap.addFittingParameter(paramInfo.m_component, name, paramInfo.m_fittingFunction, str.str(), pDescription,
1435 pVisible);
1436 } else if (category == "string") {
1437 paramMap.addString(paramInfo.m_component, name, paramInfo.m_value, pDescription, pVisible);
1438 } else if (category == "bool") {
1439 paramMap.addBool(paramInfo.m_component, name, paramValue, pDescription, pVisible);
1440 } else if (category == "int") {
1441 paramMap.addInt(paramInfo.m_component, name, paramValue, pDescription, pVisible);
1442 } else { // assume double
1443 paramMap.addDouble(paramInfo.m_component, name, paramValue, pDescription, pVisible);
1444 }
1445}
1446
1448 // The default implementation does nothing. Used by subclasses
1449 // (FileBackedExperimentInfo) to load content from files upon access.
1450}
1451
1452} // namespace Mantid::API
1453
1454namespace Mantid::Kernel {
1455
1456template <>
1458IPropertyManager::getValue<Mantid::API::ExperimentInfo_sptr>(const std::string &name) const {
1459 auto *prop = dynamic_cast<PropertyWithValue<Mantid::API::ExperimentInfo_sptr> *>(getPointerToProperty(name));
1460 if (prop) {
1461 return *prop;
1462 } else {
1463 std::string message =
1464 "Attempt to assign property " + name + " to incorrect type. Expected shared_ptr<ExperimentInfo>.";
1465 throw std::runtime_error(message);
1466 }
1467}
1468
1469template <>
1471IPropertyManager::getValue<Mantid::API::ExperimentInfo_const_sptr>(const std::string &name) const {
1472 auto const *prop = dynamic_cast<PropertyWithValue<Mantid::API::ExperimentInfo_sptr> *>(getPointerToProperty(name));
1473 if (prop) {
1474 return prop->operator()();
1475 } else {
1476 std::string message =
1477 "Attempt to assign property " + name + " to incorrect type. Expected const shared_ptr<ExperimentInfo>.";
1478 throw std::runtime_error(message);
1479 }
1480}
1481
1482} // namespace Mantid::Kernel
std::string name
Definition Run.cpp:60
double value
The value of the point.
Definition FitMW.cpp:51
double position
Definition GetAllEi.cpp:154
std::map< DeltaEMode::Type, std::string > index
int count
counter
Definition Matrix.cpp:37
Mantid::Kernel::Quat(ComponentInfo::* rotation)(const size_t) const
This class is shared by a few Workspace types and holds information related to a particular experimen...
void loadEmbeddedInstrumentInfoNexus(Nexus::File *file, std::string &instrumentName, std::string &instrumentXml)
Attempt to load instrument embedded in Nexus file. *file must have instrument group open.
Geometry::DetectorInfo & mutableDetectorInfo()
Return a non-const reference to the DetectorInfo object.
Run & mutableRun()
Writable version of the run object.
Kernel::cow_ptr< Sample > m_sample
The information on the sample environment.
const SpectrumInfo & spectrumInfo() const
Return a reference to the SpectrumInfo object.
Geometry::InstrumentMetadata const & instrumentMetadata() const
std::shared_ptr< Geometry::ParameterMap > m_parmap
Parameters modifying the base instrument.
ExperimentInfo()
Default constructor.
void setInstumentFromXML(const std::string &nxFilename, std::string &instrumentName, std::string &instrumentXml)
Set the instrument given the name and XML leading from IDF file if XML string is empty.
std::shared_ptr< Geometry::InstrumentMetadata > m_instrumentMetadata
Geometry::ComponentInfo & mutableComponentInfo()
const Geometry::DetectorInfo & detectorInfo() const
Return a const reference to the DetectorInfo object.
virtual ExperimentInfo * cloneExperimentInfo() const
Clone us.
std::unordered_map< detid_t, size_t > m_det2group
Detector grouping information.
std::shared_ptr< Geometry::DetectorInfo > m_detectorInfo
double getEFixed(const detid_t detID) const
Easy access to the efixed value for this run & detector ID.
void readParameterMap(const std::string &parameterStr)
Populate the parameter map given a string.
virtual void populateIfNotLoaded() const
Called as the first operation of most public methods.
void invalidateSpectrumDefinition(const size_t index)
Notifies the ExperimentInfo that a spectrum definition has changed.
void saveExperimentInfoNexus(Nexus::File *file, bool saveLegacyInstrument=true) const
Saves this experiment description to the open NeXus file.
size_t numberOfDetectorGroups() const
Returns the number of detector groups.
void updateSpectrumDefinitionIfNecessary(const size_t index) const
std::string getAvailableWorkspaceStartDate() const
Return workspace start date as a formatted string (strftime, as returned by Types::Core::DateAndTime)...
std::string loadInstrumentXML(const std::string &filename)
Loads the contents of a file and returns the string The file is assumed to be an IDF,...
virtual ~ExperimentInfo()
Virtual destructor.
std::shared_ptr< Geometry::ComponentInfo > m_componentInfo
The 2.0 instrument layers, of which this object is the primary owner.
virtual void updateCachedDetectorGrouping(const size_t index) const
Update detector grouping for spectrum with given index.
void cacheDefaultDetectorGrouping() const
Sets up a default detector grouping.
void copyExperimentInfoFrom(const ExperimentInfo *other)
Copy everything from the given experiment object.
const Run & run() const
Run details object access.
std::string getInstrumentName() const
Return the name of the instrument from the ComponentInfo object.
void loadSampleAndLogInfoNexus(Nexus::File *file, std::string const &prefix)
Load the sample and log info from an open NeXus file.
const Geometry::ParameterMap & constInstrumentParameters() const
Const version.
Geometry::Instrument_const_sptr getInstrument() const
Returns the parameterized instrument.
void populateWithParameter(Geometry::ParameterMap &paramMap, Geometry::PositionAndRotationAccumulator &posAndRot, const std::string &name, const Geometry::XMLInstrumentParameter &paramInfo, const Run &runData)
Fill with given instrument parameter.
Kernel::DeltaEMode::Type getEMode() const
Returns the emode for this run.
std::unique_ptr< Beamline::SpectrumInfo > m_spectrumInfo
void loadExperimentInfoNexus(std::string const &nxFilename, Nexus::File *file, std::string &parameterStr, std::string const &prefix)
const Sample & sample() const
Sample accessors.
void setEFixed(const detid_t detID, const double value)
Set the efixed value for a given detector ID.
double getEFixedGivenEMode(const std::shared_ptr< const Geometry::IDetector > &detector, const Kernel::DeltaEMode::Type emode) const
Easy access to the efixed value for this run & detector.
double getEFixedForIndirect(const std::shared_ptr< const Geometry::IDetector > &detector, const std::vector< std::string > &parameterNames) const
const std::string toString() const
Returns a string description of the object.
const Geometry::ParameterMap & instrumentParameters() const
Returns the set of parameters modifying the base instrument (const-version)
int getRunNumber() const
Utility method to get the run number.
std::string getAvailableWorkspaceEndDate() const
Return workspace end date as a formatted string (strftime style, as returned by Kernel::DateAdnTime) ...
const Geometry::ComponentInfo & componentInfo() const
std::string getWorkspaceStartDate() const
Returns the start date for this experiment (or current time if no info available)
void setInstrument(const Geometry::Instrument_const_sptr &instr)
Instrument accessors.
std::unique_ptr< SpectrumInfo > m_spectrumInfoWrapper
void setSharedRun(Kernel::cow_ptr< Run > run)
Set the run object. Use in particular to clear run without copying old run.
void setDetectorGrouping(const size_t index, const std::set< detid_t > &detIDs) const
Sets the detector grouping for the spectrum with the given index.
Kernel::cow_ptr< Run > sharedRun()
Return the cow ptr of the run.
ExperimentInfo & operator=(const ExperimentInfo &)
Implements the copy assignment operator.
void setSpectrumDefinitions(Kernel::cow_ptr< std::vector< SpectrumDefinition > > spectrumDefinitions)
Sets the SpectrumDefinition for all spectra.
std::vector< char > m_spectrumDefinitionNeedsUpdate
double getLogAsSingleValue(const std::string &log) const
Access a single value from a log for this experiment.
SpectrumInfo & mutableSpectrumInfo()
Return a non-const reference to the SpectrumInfo object.
void adoptBeamline()
Take co-ownership of whatever m_parmap currently holds.
void loadInstrumentParametersNexus(Nexus::File *file, std::string &parameterStr)
Load instrument parameters from an open Nexus file in Instrument group if found there.
void setNumberOfDetectorGroups(const size_t count) const
Sets the number of detector groups.
Sample & mutableSample()
Writable version of the sample object.
Geometry::Instrument_const_sptr sptr_instrument
The base (unparametrized) instrument.
void loadInstrumentInfoNexus(const std::string &nxFilename, Nexus::File *file, std::string &parameterStr)
Load the instrument from an open NeXus file.
void populateInstrumentParameters()
Add parameters to the instrument parameter map that are defined in instrument definition file or para...
Kernel::Property * getLog(const std::string &log) const
Access a log for this experiment.
void invalidateAllSpectrumDefinitions()
Sets flags for all spectrum definitions indicating that they need to be updated.
Kernel::cow_ptr< Run > m_run
The run information.
static std::string getInstrumentFilename(const std::string &instrumentName, const std::string &date="")
Get the IDF using the instrument name and date.
const Types::Core::DateAndTime endTime() const
Return the run end time.
bool hasProperty(const std::string &name) const
Does the property exist on the object.
const Types::Core::DateAndTime startTime() const
Return the run start time.
Kernel::Property * getProperty(const std::string &name) const
Returns the named property as a pointer.
double getPropertyAsSingleValue(const std::string &name, Kernel::Math::StatisticType statistic=Kernel::Math::Mean) const
Returns a property as a single double value from its name.
HeldType getPropertyValueAsType(const std::string &name) const
Get the value of a property as the given TYPE.
This class stores information regarding an experimental run as a series of log entries.
Definition Run.h:36
void saveNexus(Nexus::File *file, const std::string &group, bool keepOpen=false) const override
Save the run to a NeXus file with a given group name.
Definition Run.cpp:647
void loadNexus(Nexus::File *file, const std::string &group, const std::string &prefix, bool keepOpen=false) override
Load the run from a NeXus file with a given group name.
Definition Run.cpp:699
This class stores information about the sample used in particular run.
Definition Sample.h:33
int loadNexus(Nexus::File *file, const std::string &group)
Load the object from an open NeXus file.
Definition Sample.cpp:382
void saveNexus(Nexus::File *file, const std::string &group) const
Save the object to an open NeXus file.
Definition Sample.cpp:330
const Geometry::OrientedLattice & getOrientedLattice() const
Get a reference to the sample's OrientedLattice.
Definition Sample.cpp:198
API::SpectrumInfo is an intermediate step towards a SpectrumInfo that is part of Instrument-2....
const Kernel::cow_ptr< std::vector< SpectrumDefinition > > & sharedSpectrumDefinitions() const
std::shared_ptr< const IComponent > getComponentByName(const std::string &cname, int nlevels=0) const override
Returns a pointer to the first component of assembly encountered with the given name.
ComponentInfo : Provides a component centric view on to the instrument.
bool hasParent(const size_t componentIndex) const
void setRotation(size_t componentIndex, const Kernel::Quat &newRotation)
size_t parent(const size_t componentIndex) const
Kernel::Quat rotation(const size_t componentIndex) const
Kernel::V3D position(const size_t componentIndex) const
size_t indexOfOrInvalid(Geometry::IComponent const *id) const
The index for a component ID, or invalidIndex if it is not part of this instrument.
size_t indexOf(Geometry::IComponent const *id) const
const std::string & name(const size_t componentIndex) const
void setPosition(size_t componentIndex, const Kernel::V3D &newPosition)
static constexpr size_t invalidIndex
Returned by indexOfOrInvalid() for a component ID that is not part of this instrument.
Geometry::DetectorInfo is an intermediate step towards a DetectorInfo that is part of Instrument-2....
void setMasked(const size_t index, bool masked)
Set the mask flag of the detector with given index. Not thread safe.
size_t indexOf(const detid_t id) const
Returns the index of the detector with the given detector ID.
size_t size() const
Returns the size of the DetectorInfo, i.e., the number of detectors in the instrument.
virtual ComponentID getComponentID() const =0
Returns the ComponentID - a unique identifier of the component.
Creates an instrument data from a XML instrument description file.
std::shared_ptr< Instrument > parseXML(Kernel::ProgressBase *progressReporter)
Parse XML contents.
std::string getMangledName()
Handle used in the singleton constructor for instrument file should append the value file sha-1 check...
InstrumentMetadata : metadata related to the entire instrument.
Base Instrument Class.
Definition Instrument.h:49
std::size_t getNumberDetectors(bool skipMonitors=false) const
std::shared_ptr< const Instrument > baseInstrument() const
Pointer to the 'real' instrument, for parametrized instruments.
Class to implement UB matrix.
static std::shared_ptr< Instrument > createInstrument(const std::shared_ptr< const Instrument > &base, const std::shared_ptr< ParameterMap > &map)
Create a parameterized instrument from the given base and ParameterMap.
static std::shared_ptr< Parameter > create(const std::string &className, const std::string &name, const std::string &visible="true")
Creates an instance of a parameter.
Definition Parameter.cpp:83
Parameter map iterator typedef.
const std::vector< std::string > & getParameterFilenames() const
Returns a list of all the parameter files loaded.
bool contains(const IComponent *comp, const std::string &name, const std::string &type="") const
Does the named parameter exist for the given component and type (std::string version)
void addInt(const IComponent *comp, const std::string &name, const std::string &value, const std::string *const pDescription=nullptr, const std::string &pVisible="true")
Adds an int value to the parameter map.
std::shared_ptr< Parameter > getRecursive(const IComponent *comp, const std::string &name, const std::string &type="") const
Use get() recursively to see if can find param in all parents of comp and given type (std::string ver...
static const std::string & rot()
std::string getString(const IComponent *comp, const std::string &name, bool recursive=false) const
Return the value of a parameter as a string.
void addString(const IComponent *comp, const std::string &name, const std::string &value, const std::string *const pDescription=nullptr, const std::string &pVisible="true")
Adds a std::string value to the parameter map.
std::vector< Entry > entries() const
Every stored parameter with its owning component, in component-index order.
void addDouble(const IComponent *comp, const std::string &name, const std::string &value, const std::string *const pDescription=nullptr, const std::string &pVisible="true")
Adds a double value to the parameter map.
static const std::string & pos()
Return string to be used in the map.
void addFittingParameter(const IComponent *comp, const std::string &name, const std::string &fittingFunction, const std::string &value, const std::string *const pDescription=nullptr, const std::string &pVisible="true")
Add a fitting parameter.
void addBool(const IComponent *comp, const std::string &name, const std::string &value, const std::string *const pDescription=nullptr, const std::string &pVisible="true")
Adds a bool value to the parameter map.
std::shared_ptr< Parameter > get(const IComponent *comp, const std::string &name, const std::string &type="") const
Get a parameter with a given name and type (std::string version)
Collects the position and rotation an instrument definition specifies piecemeal, so that each can be ...
void setCoordinate(const size_t componentIndex, const std::string &axis, const double value, const Kernel::V3D &currentPosition)
Set one coordinate.
void setPosition(const size_t componentIndex, const Kernel::V3D &position)
Set the whole position at once, discarding any coordinates accumulated so far.
std::map< size_t, Kernel::V3D > positions() const
The accumulated position for each component that had any coordinate set.
bool setRotationAngle(const size_t componentIndex, const std::string &axis, const double degrees)
Set one rotation angle, in degrees.
std::map< size_t, Kernel::Quat > rotations() const
The composed rotation for each component that had any angle set.
double alpha() const
Get lattice parameter.
Definition UnitCell.cpp:133
double a(int nd) const
Get lattice parameter a1-a3 as function of index (0-2)
Definition UnitCell.cpp:94
double c() const
Get lattice parameter.
Definition UnitCell.cpp:128
double beta() const
Get lattice parameter.
Definition UnitCell.cpp:138
double b() const
Get lattice parameter.
Definition UnitCell.cpp:123
double gamma() const
Get lattice parameter.
Definition UnitCell.cpp:143
This class is used to store information about parameters in XML instrument definition files and instr...
const Geometry::IComponent * m_component
value from the log value
const std::string m_value
rather then extracting value from logfile,
const std::string m_type
type of the data, e.g. int, double or string
const std::string m_description
if present, contains help string, describing the parameter
const std::string m_visible
if present, describes whether the parameter shall be visible in InstrumentViewer
std::shared_ptr< Kernel::Interpolation > m_interpolation
evaluating the formula
const std::string m_fittingFunction
specific to fitting parameter
std::string m_penaltyFactor
parameter specify lower and upper bound in that order
const std::string m_formula
specify fitting function
const std::string m_resultUnit
expected result (output) unit from
const std::vector< std::string > m_constraint
specific to fitting
const std::string m_tie
specific to fitting parameter specify any tie
const std::string m_formulaUnit
formula to use for setting this parameter
Exception for when an item is not found in a collection.
Definition Exception.h:145
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 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
The concrete, templated class for properties.
Base class for properties.
Definition Property.h:94
virtual std::string value() const =0
Returns the value of the property as a string.
Class for quaternions.
Definition Quat.h:39
void rotate(V3D &) const
Rotate a vector.
Definition Quat.cpp:397
Iterator begin()
Iterator referring to first element in the container.
@ TOK_IGNORE_EMPTY
ignore empty tokens
@ TOK_TRIM
remove leading and trailing whitespace from tokens
Iterator end()
Iterator referring to the past-the-end element in the container.
std::size_t count() const
Get the total number of tokens.
TimeROI : Object that holds information about when the time measurement was active.
Definition TimeROI.h:18
Class for 3D vectors.
Definition V3D.h:34
void spherical(const double R, const double theta, const double phi) noexcept
Sets the vector position based on spherical coordinates.
Definition V3D.cpp:56
Implements a copy on write data template.
Definition cow_ptr.h:41
Class that provides for a standard Nexus exception.
std::shared_ptr< const ExperimentInfo > ExperimentInfo_const_sptr
Shared pointer to const ExperimentInfo.
Kernel::Logger g_log("ExperimentInfo")
static logger object
std::shared_ptr< ExperimentInfo > ExperimentInfo_sptr
Shared pointer to ExperimentInfo.
MANTID_API_DLL void applyRectangularDetectorScaleToComponentInfo(Geometry::ComponentInfo &componentInfo, Geometry::IComponent *componentId, const double scaleX, const double scaleY)
Helpers for resizing RectangularDetectors.
std::shared_ptr< Parameter > Parameter_sptr
Typedef for the shared pointer.
Definition Parameter.h:198
std::shared_ptr< const Mantid::Geometry::IDetector > IDetector_const_sptr
Shared pointer to IDetector (const version)
Definition IDetector.h:102
std::shared_ptr< const Instrument > Instrument_const_sptr
Shared pointer to an const instrument object.
std::shared_ptr< Instrument > Instrument_sptr
Shared pointer to an instrument object.
MANTID_KERNEL_DLL std::string strip(const std::string &A)
strip pre/post spaces
Definition Strings.cpp:419
MANTID_KERNEL_DLL std::string loadFile(const std::string &filename)
Loads the entire contents of a text file into a string.
Definition Strings.cpp:26
int convert(const std::string &A, T &out)
Convert a string into a number.
Definition Strings.cpp:696
int32_t detid_t
Typedef for a detector ID.
Generate a tableworkspace to store the calibration results.
std::string to_string(const wide_integer< Bits, Signed > &n)
static Type fromString(const std::string &modeStr)
Returns the emode from the given string.
Type
Define the available energy transfer modes It is important to assign enums proper numbers,...
Definition DeltaEMode.h:29