/
ConvertSpectrumAxis2.cpp
378 lines (338 loc) · 15.2 KB
/
ConvertSpectrumAxis2.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
// Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidAlgorithms/ConvertSpectrumAxis2.h"
#include "MantidAPI/InstrumentValidator.h"
#include "MantidAPI/NumericAxis.h"
#include "MantidAPI/Run.h"
#include "MantidAPI/SpectraAxisValidator.h"
#include "MantidAPI/SpectrumInfo.h"
#include "MantidDataObjects/EventWorkspace.h"
#include "MantidDataObjects/WorkspaceCreation.h"
#include "MantidGeometry/Instrument.h"
#include "MantidGeometry/Instrument/DetectorInfo.h"
#include "MantidGeometry/Instrument/ReferenceFrame.h"
#include "MantidHistogramData/Histogram.h"
#include "MantidHistogramData/HistogramBuilder.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/CompositeValidator.h"
#include "MantidKernel/ListValidator.h"
#include "MantidKernel/Unit.h"
#include "MantidKernel/UnitConversion.h"
#include "MantidKernel/UnitFactory.h"
#include "MantidTypes/SpectrumDefinition.h"
#include <cfloat>
constexpr double rad2deg = 180.0 / M_PI;
namespace Mantid {
namespace Algorithms {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(ConvertSpectrumAxis2)
using namespace Kernel;
using namespace API;
using namespace Geometry;
using namespace DataObjects;
using namespace HistogramData;
void ConvertSpectrumAxis2::init() {
// Validator for Input Workspace
auto wsVal = std::make_shared<CompositeValidator>();
wsVal->add<SpectraAxisValidator>();
wsVal->add<InstrumentValidator>();
declareProperty(std::make_unique<WorkspaceProperty<>>("InputWorkspace", "", Direction::Input, wsVal),
"The name of the input workspace.");
declareProperty(std::make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output),
"The name to use for the output workspace.");
std::vector<std::string> targetOptions{
"Theta", "SignedTheta", "InPlaneTwoTheta", "SignedInPlaneTwoTheta", "ElasticQ",
"ElasticQSquared", "theta", "signed_theta", "ElasticDSpacing"};
declareProperty("Target", "", std::make_shared<StringListValidator>(targetOptions),
"The unit to which spectrum axis is converted to - \"theta\" (for the "
"angle in degrees), Q or Q^2, where elastic Q is evaluated at EFixed. "
"InPlaneTwoTheta and SignedInPlaneTwoTheta are the angle when each point "
"is projected on the horizontal plane."
"Note that 'theta' and 'signed_theta' are there for compatibility "
"purposes; they are the same as 'Theta' and 'SignedTheta' respectively");
std::vector<std::string> eModeOptions;
eModeOptions.emplace_back("Direct");
eModeOptions.emplace_back("Indirect");
declareProperty("EMode", "Direct", std::make_shared<StringListValidator>(eModeOptions),
"Some unit conversions require this value to be set "
"(\"Direct\" or \"Indirect\")");
auto mustBePositive = std::make_shared<BoundedValidator<double>>();
mustBePositive->setLower(0.0);
declareProperty("EFixed", EMPTY_DBL(), mustBePositive,
"Value of fixed energy in meV : EI (EMode=Direct) or EF "
"(EMode=Indirect))");
declareProperty("OrderAxis", true,
"Whether or not to sort the resulting"
" spectrum axis.");
}
void ConvertSpectrumAxis2::exec() {
// Get the input workspace.
API::MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
// Assign value to the member variable storing the number of histograms.
const size_t nHist = inputWS->getNumberHistograms();
// The unit to convert to.
const std::string unitTarget = getProperty("Target");
// Whether needs to be ordered
m_toOrder = getProperty("OrderAxis");
size_t nProgress = nHist;
if (m_toOrder) {
// we will need to loop twice, once to build the indexMap,
// once to copy over the spectra and set the output
nProgress *= 2;
} else {
m_axis.reserve(nHist);
}
Progress progress(this, 0.0, 1.0, nProgress);
// Call the functions to convert to the different forms of theta or Q.
if (unitTarget == "theta" || unitTarget == "Theta" || unitTarget == "signed_theta" || unitTarget == "SignedTheta" ||
unitTarget == "InPlaneTwoTheta" || unitTarget == "SignedInPlaneTwoTheta") {
createThetaMap(progress, unitTarget, inputWS);
} else if (unitTarget == "ElasticQ" || unitTarget == "ElasticQSquared" || unitTarget == "ElasticDSpacing") {
createElasticQMap(progress, unitTarget, inputWS);
}
// Create an output workspace and set the property for it.
MatrixWorkspace_sptr outputWS = createOutputWorkspace(progress, unitTarget, inputWS);
setProperty("OutputWorkspace", outputWS);
}
/** Converts X axis to theta representation
* @param progress :: Progress indicator
* @param targetUnit :: Target conversion unit
* @param inputWS :: Input Workspace
*/
void ConvertSpectrumAxis2::createThetaMap(API::Progress &progress, const std::string &targetUnit,
API::MatrixWorkspace_sptr &inputWS) {
// Not sure about default, previously there was a call to a null function?
enum thetaTypes { theta, signedTheta, inPlaneTheta, signedInPlaneTheta };
thetaTypes thetaType = theta;
if (targetUnit == "signed_theta" || targetUnit == "SignedTheta") {
thetaType = signedTheta;
} else if (targetUnit == "theta" || targetUnit == "Theta") {
thetaType = theta;
} else if (targetUnit == "InPlaneTwoTheta") {
thetaType = inPlaneTheta;
} else if (targetUnit == "SignedInPlaneTwoTheta") {
thetaType = signedInPlaneTheta;
}
bool warningGiven = false;
const auto &spectrumInfo = inputWS->spectrumInfo();
for (size_t i = 0; i < spectrumInfo.size(); ++i) {
if (!spectrumInfo.hasDetectors(i)) {
if (!warningGiven)
g_log.warning("The instrument definition is incomplete - spectra "
"dropped from output");
warningGiven = true;
continue;
}
if (!spectrumInfo.isMonitor(i)) {
switch (thetaType) {
case signedTheta:
emplaceIndexMap(spectrumInfo.signedTwoTheta(i) * rad2deg, i);
break;
case theta:
emplaceIndexMap(spectrumInfo.twoTheta(i) * rad2deg, i);
break;
case inPlaneTheta:
emplaceIndexMap(inPlaneTwoTheta(i, inputWS) * rad2deg, i);
break;
case signedInPlaneTheta:
emplaceIndexMap(signedInPlaneTwoTheta(i, inputWS) * rad2deg, i);
break;
}
} else {
emplaceIndexMap(0.0, i);
}
progress.report("Converting to theta...");
}
}
/** Returns the scattering angle projected on horizontal plane 2 theta in
* radians (angle w.r.t. to beam direction).
*
* Throws an exception if the spectrum is a monitor.
* @param index :: the index of the spectrum
* @param inputWS :: input workspace
*/
double ConvertSpectrumAxis2::inPlaneTwoTheta(const size_t index, const API::MatrixWorkspace_sptr &inputWS) const {
const auto spectrumInfo = inputWS->spectrumInfo();
const auto refFrame = inputWS->getInstrument()->getReferenceFrame();
const V3D position = spectrumInfo.position(index) - spectrumInfo.samplePosition();
double angle =
std::atan2(std::abs(position[refFrame->pointingHorizontal()]), position[refFrame->pointingAlongBeam()]);
return angle;
}
/** Returns the signed scattering angle projected on horizontal plane 2 theta in
* radians (angle w.r.t. to beam direction).
*
* Throws an exception if the spectrum is a monitor.
* @param index :: the index of the spectrum
* @param inputWS :: input workspace
*/
double ConvertSpectrumAxis2::signedInPlaneTwoTheta(const size_t index, const API::MatrixWorkspace_sptr &inputWS) const {
const auto spectrumInfo = inputWS->spectrumInfo();
const auto refFrame = inputWS->getInstrument()->getReferenceFrame();
// Get the axis defining the sign
const auto &instrumentUpAxis = refFrame->vecThetaSign();
const auto samplePos = spectrumInfo.samplePosition();
const auto beamLine = samplePos - spectrumInfo.sourcePosition();
if (beamLine.nullVector()) {
throw Kernel::Exception::InstrumentDefinitionError("Source and sample are at same position!");
}
const V3D sampleDetVec = spectrumInfo.position(index) - samplePos;
double angle = std::atan2(sampleDetVec[refFrame->pointingHorizontal()], sampleDetVec[refFrame->pointingAlongBeam()]);
const auto cross = beamLine.cross_prod(sampleDetVec);
const auto normToSurface = beamLine.cross_prod(instrumentUpAxis);
if (normToSurface.scalar_prod(cross) < 0) {
angle *= -1;
}
return angle;
}
/** Convert X axis to Elastic Q representation
* @param progress :: Progress indicator
* @param targetUnit :: Target conversion unit
* @param inputWS :: Input workspace
*/
void ConvertSpectrumAxis2::createElasticQMap(API::Progress &progress, const std::string &targetUnit,
API::MatrixWorkspace_sptr &inputWS) {
const std::string emodeStr = getProperty("EMode");
int emode = 0;
if (emodeStr == "Direct")
emode = 1;
else if (emodeStr == "Indirect")
emode = 2;
const auto &spectrumInfo = inputWS->spectrumInfo();
const auto &detectorInfo = inputWS->detectorInfo();
const size_t nHist = spectrumInfo.size();
for (size_t i = 0; i < nHist; i++) {
double theta(0.0), efixed(0.0);
if (!spectrumInfo.isMonitor(i)) {
theta = 0.5 * spectrumInfo.twoTheta(i);
/*
* Two assumptions made in the following code.
* 1. Getting the detector index of the first detector in the spectrum
* definition is enough (this should be completely safe).
* 2. That the time index is not important (first element of pair only
* accessed). i.e we are not performing scanning. Step scanning is not
* supported at the time of writing.
*/
const auto detectorIndex = spectrumInfo.spectrumDefinition(i)[0].first;
efixed = getEfixed(detectorIndex, detectorInfo, *inputWS,
emode); // get efixed
} else {
theta = DBL_MIN;
efixed = DBL_MIN;
}
// Convert to MomentumTransfer
double elasticQInAngstroms = Kernel::UnitConversion::convertToElasticQ(theta, efixed);
if (targetUnit == "ElasticQ") {
emplaceIndexMap(elasticQInAngstroms, i);
} else if (targetUnit == "ElasticQSquared") {
// The QSquared value.
double elasticQSquaredInAngstroms = elasticQInAngstroms * elasticQInAngstroms;
emplaceIndexMap(elasticQSquaredInAngstroms, i);
} else if (targetUnit == "ElasticDSpacing") {
double elasticDSpacing = 2 * M_PI / elasticQInAngstroms;
emplaceIndexMap(elasticDSpacing, i);
}
progress.report("Converting to " + targetUnit);
}
}
/** Create the final output workspace after converting the X axis
* @returns the final output workspace
*
* @param progress :: Progress indicator
* @param targetUnit :: Target conversion unit
* @param inputWS :: Input workspace
*/
MatrixWorkspace_sptr ConvertSpectrumAxis2::createOutputWorkspace(API::Progress &progress, const std::string &targetUnit,
API::MatrixWorkspace_sptr &inputWS) {
MatrixWorkspace_sptr outputWorkspace = nullptr;
std::unique_ptr<NumericAxis> newAxis = nullptr;
EventWorkspace_sptr eventWS = std::dynamic_pointer_cast<EventWorkspace>(inputWS);
if (m_toOrder) {
// Can not re-use the input one because the spectra are re-ordered.
const Histogram hist = eventWS ? Histogram(inputWS->binEdges(0)) : inputWS->histogram(0);
outputWorkspace = create<MatrixWorkspace>(*inputWS, m_indexMap.size(), hist);
std::vector<double> axis;
axis.reserve(m_indexMap.size());
std::transform(m_indexMap.begin(), m_indexMap.end(), std::back_inserter(axis),
[](const auto &it) { return it.first; });
newAxis = std::make_unique<NumericAxis>(std::move(axis));
} else {
// If there is no reordering we can simply clone.
outputWorkspace = inputWS->clone();
newAxis = std::make_unique<NumericAxis>(m_axis);
}
// Set the units of the axis.
if (targetUnit == "theta" || targetUnit == "Theta" || targetUnit == "signed_theta" || targetUnit == "SignedTheta" ||
targetUnit == "InPlaneTwoTheta" || targetUnit == "SignedInPlaneTwoTheta") {
newAxis->unit() = std::make_shared<Units::Degrees>();
} else if (targetUnit == "ElasticQ") {
newAxis->unit() = UnitFactory::Instance().create("MomentumTransfer");
} else if (targetUnit == "ElasticQSquared") {
newAxis->unit() = UnitFactory::Instance().create("QSquared");
} else if (targetUnit == "ElasticDSpacing") {
newAxis->unit() = UnitFactory::Instance().create("dSpacing");
}
outputWorkspace->replaceAxis(1, std::move(newAxis));
// Note that this is needed only for ordered case
if (m_toOrder) {
size_t currentIndex = 0;
std::multimap<double, size_t>::const_iterator it;
for (it = m_indexMap.begin(); it != m_indexMap.end(); ++it) {
// Copy over the data.
outputWorkspace->getSpectrum(currentIndex).copyDataFrom(inputWS->getSpectrum(it->second));
// We can keep the spectrum numbers etc.
outputWorkspace->getSpectrum(currentIndex).copyInfoFrom(inputWS->getSpectrum(it->second));
++currentIndex;
progress.report("Setting output spectrum #" + std::to_string(currentIndex));
}
}
return outputWorkspace;
}
double ConvertSpectrumAxis2::getEfixed(const size_t detectorIndex, const Geometry::DetectorInfo &detectorInfo,
const Mantid::API::MatrixWorkspace &inputWS, const int emode) const {
double efixed(0);
double efixedProp = getProperty("Efixed");
Mantid::detid_t detectorID = detectorInfo.detectorIDs()[detectorIndex];
if (efixedProp != EMPTY_DBL()) {
efixed = efixedProp;
g_log.debug() << "Detector: " << detectorID << " Efixed: " << efixed << "\n";
} else {
if (emode == 1) {
if (inputWS.run().hasProperty("Ei")) {
efixed = inputWS.run().getLogAsSingleValue("Ei");
} else {
throw std::invalid_argument("Could not retrieve Efixed from the "
"workspace. Please provide a value.");
}
} else if (emode == 2) {
const auto &detectorSingle = detectorInfo.detector(detectorIndex);
std::vector<double> efixedVec = detectorSingle.getNumberParameter("Efixed");
if (!efixedVec.empty()) {
efixed = efixedVec.at(0);
g_log.debug() << "Detector: " << detectorID << " EFixed: " << efixed << "\n";
} else {
g_log.warning() << "Efixed could not be found for detector " << detectorID << ", please provide a value\n";
throw std::invalid_argument("Could not retrieve Efixed from the "
"detector. Please provide a value.");
}
}
}
return efixed;
}
/** Emplaces inside the ordered or unordered index registry
* @param value :: value to insert
* @param wsIndex :: workspace index
*/
void ConvertSpectrumAxis2::emplaceIndexMap(double value, size_t wsIndex) {
if (m_toOrder) {
m_indexMap.emplace(value, wsIndex);
} else {
m_axis.emplace_back(value);
}
}
} // namespace Algorithms
} // namespace Mantid