Mantid
Loading...
Searching...
No Matches
ModeratorTzeroLinear.cpp
Go to the documentation of this file.
1// Mantid Repository : https://github.com/mantidproject/mantid
2//
3// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
4// NScD Oak Ridge National Laboratory, European Spallation Source,
5// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
6// SPDX - License - Identifier: GPL - 3.0 +
8#include "MantidAPI/Axis.h"
9#include "MantidAPI/Run.h"
17#include "MantidHistogramData/Histogram.h"
20
21namespace Mantid::Algorithms {
22
23// Register the algorithm into the AlgorithmFactory
24DECLARE_ALGORITHM(ModeratorTzeroLinear)
25
26using namespace Mantid::Kernel;
27using namespace Mantid::API;
28using namespace Mantid::Geometry;
29using namespace Mantid::DataObjects;
30using namespace Mantid::HistogramData;
31
32// A reference to the logger is provided by the base class, it is called g_log.
33// It is used to print out information, warning and error messages
34
35ModeratorTzeroLinear::ModeratorTzeroLinear() : API::Algorithm(), m_gradient(0.), m_intercept(0.), m_instrument() {}
36
37const std::string ModeratorTzeroLinear::name() const { return "ModeratorTzeroLinear"; }
38
39const std::string ModeratorTzeroLinear::summary() const {
40 return "Corrects the time of flight of an indirect geometry instrument by a "
41 "time offset that is linearly dependent on the wavelength of the "
42 "neutron after passing through the moderator.";
43}
44
45int ModeratorTzeroLinear::version() const { return 1; }
46
47const std::string ModeratorTzeroLinear::category() const { return "CorrectionFunctions\\InstrumentCorrections"; }
48
50 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("InputWorkspace", "", Direction::Input,
51 std::make_shared<WorkspaceUnitValidator>("TOF")),
52 "The name of the input workspace, containing events and/or "
53 "histogram data, in units of time-of-flight");
54 declareProperty("Gradient", EMPTY_DBL(),
55 "Wavelength dependent TOF shift, units in microsec/Angstrom. "
56 "Overrides the value stored in the instrument object");
57 declareProperty("Intercept", EMPTY_DBL(),
58 "TOF shift, units in microseconds. Overrides the value"
59 "stored in the instrument object");
60 // declare the output workspace
61 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("OutputWorkspace", "", Direction::Output),
62 "The name of the output workspace");
63
64} // end of void ModeratorTzeroLinear::init()
65
67 // retrieve the input workspace.
68 const MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace");
69
70 // Get a pointer to the instrument contained in the workspace
71 m_instrument = inputWS->getInstrument();
72
73 // deltaE-mode (should be "indirect")
74 try {
75 const std::vector<std::string> Emode = m_instrument->getStringParameter("deltaE-mode");
76 if (Emode.empty())
77 throw Exception::InstrumentDefinitionError("Unable to retrieve "
78 "instrument geometry (direct "
79 "or indirect) parameter",
80 inputWS->getTitle());
81 if (Emode[0] != "indirect")
82 throw Exception::InstrumentDefinitionError("Instrument geometry must be of type indirect.");
83 } catch (Exception::NotFoundError &) {
84 g_log.error("Unable to retrieve instrument geometry (direct or indirect) "
85 "parameter");
86 throw Exception::InstrumentDefinitionError("Unable to retrieve instrument geometry (direct or indirect) parameter",
87 inputWS->getTitle());
88 }
89
90 // gradient, intercept constants
91 try {
92
93 // determine which Gradient to use
94 const std::vector<double> gradientParam = m_instrument->getNumberParameter("Moderator.TimeZero.gradient");
95 const double gradientParamManual = getProperty("Gradient");
96 if (gradientParam.empty() && gradientParamManual == EMPTY_DBL())
97 throw Exception::InstrumentDefinitionError("Unable to retrieve Moderator Time Zero parameters (gradient)",
98 inputWS->getTitle());
99 if (gradientParamManual != EMPTY_DBL()) {
100 m_gradient = gradientParamManual;
101 } else {
102 m_gradient = gradientParam[0]; //[gradient]=microsecond/Angstrom
103 }
104 // conversion factor for gradient from microsecond/Angstrom to meters
105 double convfactor = 1.0e4 * PhysicalConstants::h / PhysicalConstants::NeutronMass;
106 m_gradient *= convfactor; //[gradient] = meter
107
108 // determine which Intercept to use
109 const std::vector<double> interceptParam = m_instrument->getNumberParameter("Moderator.TimeZero.intercept");
110 const double interceptParamManual = getProperty("Intercept");
111 if (interceptParam.empty() && interceptParamManual == EMPTY_DBL())
112 throw Exception::InstrumentDefinitionError("Unable to retrieve Moderator Time Zero parameters (intercept)",
113 inputWS->getTitle());
114 if (interceptParamManual != EMPTY_DBL()) {
115 m_intercept = interceptParamManual;
116 } else {
117 m_intercept = interceptParam[0]; //[intercept]=microsecond
118 }
119
120 g_log.debug() << "Moderator Time Zero: gradient=" << m_gradient << "intercept=" << m_intercept << '\n';
121 } catch (Exception::NotFoundError &) {
122 g_log.error("Unable to retrieve Moderator Time Zero parameters (gradient "
123 "and intercept)");
124 throw Exception::InstrumentDefinitionError("Unable to retrieve Moderator "
125 "Time Zero parameters (gradient "
126 "and intercept)",
127 inputWS->getTitle());
128 }
129
130 // Run execEvent if eventWorkSpace
131 EventWorkspace_const_sptr eventWS = std::dynamic_pointer_cast<const EventWorkspace>(inputWS);
132 if (eventWS != nullptr) {
133 execEvent();
134 return;
135 }
136
137 MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
138 // Check whether input = output to see whether a new workspace is required.
139 if (outputWS != inputWS) {
140 // Create new workspace for output from old
141 outputWS = create<MatrixWorkspace>(*inputWS);
142 }
143
144 // do the shift in X
145 const auto &spectrumInfo = inputWS->spectrumInfo();
146 auto const &componentInfo = inputWS->componentInfo();
147 const size_t numHists = inputWS->getNumberHistograms();
148 Progress prog(this, 0.0, 1.0, numHists); // report progress of algorithm
149 PARALLEL_FOR_IF(Kernel::threadSafe(*inputWS, *outputWS))
150 for (int i = 0; i < static_cast<int>(numHists); ++i) {
152 double t_f, L_i;
153 auto wsIndex = static_cast<size_t>(i);
154 calculateTfLi(spectrumInfo, componentInfo, wsIndex, t_f, L_i);
155
156 outputWS->setHistogram(i, inputWS->histogram(i));
157 // shift the time of flights
158 if (t_f >= 0) // t_f < 0 when no detector info is available
159 {
160 const double scaling = L_i / (L_i + m_gradient);
161 const double offset = (1 - scaling) * t_f - scaling * m_intercept;
162 auto &outbins = outputWS->mutableX(i);
163 outbins *= scaling;
164 outbins += offset;
165 }
166 prog.report();
168 }
170
171 // Copy units
172 if (inputWS->getAxis(0)->unit()) {
173 outputWS->getAxis(0)->unit() = inputWS->getAxis(0)->unit();
174 }
175 try {
176 if (inputWS->getAxis(1)->unit()) {
177 outputWS->getAxis(1)->unit() = inputWS->getAxis(1)->unit();
178 }
179 } catch (Exception::IndexError &) {
180 // OK, so this isn't a Workspace2D
181 }
182
183 // Assign it to the output workspace property
184 setProperty("OutputWorkspace", outputWS);
185}
186
188 g_log.information("Processing event workspace");
189
190 const MatrixWorkspace_const_sptr matrixInputWS = getProperty("InputWorkspace");
191
192 // generate the output workspace pointer
193 MatrixWorkspace_sptr matrixOutputWS = getProperty("OutputWorkspace");
194 if (matrixOutputWS != matrixInputWS) {
195 matrixOutputWS = matrixInputWS->clone();
196 setProperty("OutputWorkspace", matrixOutputWS);
197 }
198 auto outputWS = std::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS);
199
200 // Loop over the spectra
201 const auto &spectrumInfo = matrixOutputWS->spectrumInfo();
202 auto const &componentInfo = matrixOutputWS->componentInfo();
203 const size_t numHists = outputWS->getNumberHistograms();
204 Progress prog(this, 0.0, 1.0, numHists); // report progress of algorithm
206 for (int i = 0; i < static_cast<int>(numHists); ++i) {
207 auto wsIndex = static_cast<size_t>(i);
209 EventList &evlist = outputWS->getSpectrum(wsIndex);
210 if (evlist.getNumberEvents() > 0) // don't bother with empty lists
211 {
212 // Calculate the time from sample to detector 'i'
213 double t_f, L_i;
214 calculateTfLi(spectrumInfo, componentInfo, wsIndex, t_f, L_i);
215 if (t_f >= 0) {
216 const double scaling = L_i / (L_i + m_gradient);
217 // Calculate new time of flight, TOF'=scaling*(TOF-t_f-intercept)+t_f =
218 // scaling*TOF + (1-scaling)*t_f - scaling*intercept
219 evlist.convertTof(scaling, (1 - scaling) * t_f - scaling * m_intercept);
220 }
221 }
222 prog.report();
224 }
226 outputWS->clearMRU(); // Clears the Most Recent Used lists */
227} // end of void ModeratorTzeroLinear::execEvent()
228
229// calculate time from sample to detector
230void ModeratorTzeroLinear::calculateTfLi(const SpectrumInfo &spectrumInfo, Geometry::ComponentInfo const &componentInfo,
231 size_t i, double &t_f, double &L_i) {
232 static const double convFact = 1.0e-6 * sqrt(2 * PhysicalConstants::meV / PhysicalConstants::NeutronMass);
233 static const double TfError = -1.0; // signal error when calculating final
234 // time
235
236 if (!spectrumInfo.hasDetectors(i)) {
237 t_f = TfError;
238 return;
239 }
240
241 if (spectrumInfo.isMonitor(i)) {
242 L_i = spectrumInfo.sourcePosition().distance(spectrumInfo.position(i));
243 t_f = 0.0; // t_f=0.0 since there is no sample to detector path
244 } else {
245 L_i = spectrumInfo.l1();
246 // Get final energy E_f, final velocity v_f
247 // A spectrum of several detectors has no parameters of its own
248 auto const wsProp = spectrumInfo.hasUniqueDetector(i)
249 ? componentInfo.getNumberParameter(spectrumInfo.firstDetectorIndex(i), "Efixed")
250 : std::vector<double>{};
251 if (!wsProp.empty()) {
252 double E_f = wsProp.at(0); //[E_f]=meV
253 double v_f = convFact * sqrt(E_f); //[v_f]=meter/microsec
254 t_f = spectrumInfo.l2(i) / v_f;
255 } else {
256 g_log.debug() << "Efixed not found for detector " << i << '\n';
257 t_f = TfError;
258 }
259 }
260}
261
262} // namespace Mantid::Algorithms
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:547
#define PARALLEL_START_INTERRUPT_REGION
Begins a block to skip processing is the algorithm has been interupted Note the end of the block if n...
#define PARALLEL_END_INTERRUPT_REGION
Ends a block to skip processing is the algorithm has been interupted Note the start of the block if n...
#define PARALLEL_FOR_IF(condition)
Empty definitions - to enable set your complier to enable openMP.
#define PARALLEL_CHECK_INTERRUPT_REGION
Adds a check after a Parallel region to see if it was interupted.
Base class from which all concrete algorithm classes should be derived.
Definition Algorithm.h:76
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
Kernel::Logger & g_log
Definition Algorithm.h:426
Helper class for reporting progress from algorithms.
Definition Progress.h:25
API::SpectrumInfo is an intermediate step towards a SpectrumInfo that is part of Instrument-2....
bool isMonitor(const size_t index) const
Returns true if the detector(s) associated with the spectrum are monitors.
Kernel::V3D sourcePosition() const
Returns the source position.
size_t firstDetectorIndex(const size_t index) const
Returns the detector index of the first detector of the spectrum with given index.
bool hasDetectors(const size_t index) const
Returns true if the spectrum is associated with detectors in the instrument.
Kernel::V3D position(const size_t index) const
Returns the position of the spectrum with given index.
double l2(const size_t index) const
Returns L2 (distance from sample to spectrum).
bool hasUniqueDetector(const size_t index) const
Returns true if the spectrum is associated with exactly one detector.
double l1() const
Returns L1 (distance from source to sample).
A property class for workspaces.
const std::string summary() const override
Summary of algorithms purpose.
void init() override
Virtual method - must be overridden by concrete algorithm.
const std::string category() const override
Algorithm's category for identification.
void exec() override
Virtual method - must be overridden by concrete algorithm.
const std::string name() const override
Algorithm's name.
void calculateTfLi(const API::SpectrumInfo &spectrumInfo, Geometry::ComponentInfo const &componentInfo, size_t i, double &t_f, double &L_i)
int version() const override
Algorithm's version.
Geometry::Instrument_const_sptr m_instrument
A class for holding :
Definition EventList.h:57
ComponentInfo : Provides a component centric view on to the instrument.
std::vector< double > getNumberParameter(const size_t componentIndex, const std::string &name, bool recursive=true) const
Exception for index errors.
Definition Exception.h:284
Exception for errors associated with the instrument definition.
Definition Exception.h:220
Exception for when an item is not found in a collection.
Definition Exception.h:145
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void 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 information(const std::string &msg)
Logs at information level.
Definition Logger.cpp:136
void report()
Increments the loop counter by 1, then sends the progress notification on behalf of its algorithm.
double distance(const V3D &v) const noexcept
Calculates the distance between two vectors.
Definition V3D.h:294
std::shared_ptr< const MatrixWorkspace > MatrixWorkspace_const_sptr
shared pointer to the matrix workspace base class (const version)
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
std::shared_ptr< const EventWorkspace > EventWorkspace_const_sptr
shared pointer to a const Workspace2D
std::enable_if< std::is_pointer< Arg >::value, bool >::type threadSafe(Arg workspace)
Thread-safety check Checks the workspace to ensure it is suitable for multithreaded access.
static constexpr double NeutronMass
Mass of the neutron in kg.
static constexpr double h
Planck constant in J*s.
static constexpr double meV
1 meV in Joules.
constexpr double EMPTY_DBL() noexcept
Returns what we consider an "empty" double within a property.
Definition EmptyValues.h:42
@ Input
An input workspace.
Definition Property.h:54
@ Output
An output workspace.
Definition Property.h:55