-
Notifications
You must be signed in to change notification settings - Fork 122
/
WeightedMeanOfWorkspace.cpp
82 lines (74 loc) · 2.75 KB
/
WeightedMeanOfWorkspace.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
#include "MantidAlgorithms/WeightedMeanOfWorkspace.h"
#include "MantidAPI/SpectrumInfo.h"
#include "MantidAPI/WorkspaceFactory.h"
#include "MantidDataObjects/EventWorkspace.h"
#include "MantidGeometry/Instrument.h"
namespace Mantid {
using namespace API;
using namespace DataObjects;
using namespace Geometry;
using namespace Kernel;
namespace Algorithms {
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(WeightedMeanOfWorkspace)
/// Algorithm's name for identification. @see Algorithm::name
const std::string WeightedMeanOfWorkspace::name() const {
return "WeightedMeanOfWorkspace";
}
/// Algorithm's version for identification. @see Algorithm::version
int WeightedMeanOfWorkspace::version() const { return 1; }
/// Algorithm's category for identification. @see Algorithm::category
const std::string WeightedMeanOfWorkspace::category() const {
return "Arithmetic";
}
/** Initialize the algorithm's properties.
*/
void WeightedMeanOfWorkspace::init() {
this->declareProperty(
make_unique<WorkspaceProperty<>>("InputWorkspace", "", Direction::Input),
"An input workspace.");
this->declareProperty(make_unique<WorkspaceProperty<>>("OutputWorkspace", "",
Direction::Output),
"An output workspace.");
}
/** Execute the algorithm.
*/
void WeightedMeanOfWorkspace::exec() {
MatrixWorkspace_sptr inputWS = this->getProperty("InputWorkspace");
// Check if it is an event workspace
EventWorkspace_const_sptr eventW =
boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
if (eventW != nullptr) {
throw std::runtime_error(
"WeightedMeanOfWorkspace cannot handle EventWorkspaces!");
}
// Create the output workspace
MatrixWorkspace_sptr singleValued =
WorkspaceFactory::Instance().create("WorkspaceSingleValue", 1, 1, 1);
// Calculate weighted mean
std::size_t numHists = inputWS->getNumberHistograms();
double averageValue = 0.0;
double weightSum = 0.0;
const auto &spectrumInfo = inputWS->spectrumInfo();
for (std::size_t i = 0; i < numHists; ++i) {
if (spectrumInfo.hasDetectors(i))
if (spectrumInfo.isMonitor(i) || spectrumInfo.isMasked(i))
continue;
auto &y = inputWS->y(i);
auto &e = inputWS->e(i);
double weight = 0.0;
for (std::size_t j = 0; j < y.size(); ++j) {
if (std::isfinite(y[j]) && std::isfinite(e[j])) {
weight = 1.0 / (e[j] * e[j]);
averageValue += (y[j] * weight);
weightSum += weight;
}
}
}
singleValued->mutableX(0)[0] = 0.0;
singleValued->mutableY(0)[0] = averageValue / weightSum;
singleValued->mutableE(0)[0] = std::sqrt(weightSum);
this->setProperty("OutputWorkspace", singleValued);
}
} // namespace Algorithms
} // namespace Mantid