28using namespace Kernel;
30using namespace DataObjects;
40bool validateSingleMatrixWorkspace(std::map<std::string, std::string> &validationOutput,
const MatrixWorkspace &ws,
41 const int minIndex,
const int maxIndex,
const std::vector<int> &indices) {
43 const auto numSpectra =
static_cast<int>(ws.getNumberHistograms());
45 if (minIndex >= numSpectra) {
46 validationOutput[
"StartWorkspaceIndex"] =
"Selected minimum workspace index is greater than available "
53 if (maxIndex >= numSpectra) {
54 validationOutput[
"EndWorkspaceIndex"] =
"Selected maximum workspace index is greater than available "
61 if (std::any_of(indices.cbegin(), indices.cend(),
62 [numSpectra](
const auto index) { return (index >= numSpectra) || (index < 0); })) {
63 validationOutput[
"ListOfWorkspaceIndices"] =
"One or more indices out of range of available spectra.";
76void validateWorkspaceName(std::map<std::string, std::string> &validationOutput,
const std::string &
name,
77 const int minIndex,
const int maxIndex,
const std::vector<int> &indices) {
78 const auto &ads = AnalysisDataService::Instance();
79 if (!ads.doesExist(
name))
81 auto wsGroup = ads.retrieveWS<WorkspaceGroup>(
name);
85 for (
const auto &item : *wsGroup) {
86 auto matrixWs = std::dynamic_pointer_cast<MatrixWorkspace>(item);
88 validationOutput[
"InputWorkspace"] =
"Input group contains an invalid workspace type at item " +
92 if (!validateSingleMatrixWorkspace(validationOutput, *matrixWs, minIndex, maxIndex, indices)) {
105 std::make_shared<CommonBinsValidator>()),
106 "The workspace containing the spectra to be summed.");
108 "The name of the workspace to be created as the output of the algorithm. "
109 " A workspace of this name will be created and stored in the Analysis "
112 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
113 mustBePositive->setLower(0);
114 declareProperty(
"StartWorkspaceIndex", 0, mustBePositive,
"The first Workspace index to be included in the summing");
116 "The last Workspace index to be included in the summing");
119 "A list of workspace indices as a string with ranges, for "
120 "example: 5-10,15,20-23. \n"
121 "Optional: if not specified, then the "
122 "Start/EndWorkspaceIndex fields are used alone. "
123 "If specified, the range and the list are combined (without "
124 "duplicating indices). For example, a range of 10 to 20 and "
125 "a list '12,15,26,28' gives '10-20,26,28'.");
127 declareProperty(
"IncludeMonitors",
true,
"Whether to include monitor spectra in the summation.");
130 "Instead of the usual spectra sum, calculate the weighted "
131 "sum. This has the form: \n"
133 "\\times\\Sigma(Signal_i/Error_i^2)/\\Sigma(1/Error_i^2)`\n "
134 "This property is ignored for event workspace.\n"
135 "The sums are defined for :math:`Error_i != 0` only, so the "
136 "values with zero error are dropped from the summation. To "
137 "estimate the number of dropped values see the "
141 "If enabled floating point special values such as NaN or Inf"
142 " are removed before the spectra are summed.");
145 "For unnormalized data one should multiply the weighted sum "
146 "by the number of spectra contributing to the bin.");
150 "Normalize the output workspace to the fractional area for "
151 "RebinnedOutput workspaces.");
161 std::map<std::string, std::string> validationOutput;
164 const int minIndex =
getProperty(
"StartWorkspaceIndex");
165 const int maxIndex =
getProperty(
"EndWorkspaceIndex");
166 if (minIndex > maxIndex) {
167 validationOutput[
"StartWorkspaceIndex"] =
"Selected minimum workspace "
168 "index is greater than selected "
169 "maximum workspace index.";
170 validationOutput[
"EndWorkspaceIndex"] =
"Selected maximum workspace index "
171 "is lower than selected minimum "
174 const std::vector<int> indices =
getProperty(
"ListOfWorkspaceIndices");
176 validateSingleMatrixWorkspace(validationOutput, *singleWs, minIndex, maxIndex, indices);
178 validateWorkspaceName(validationOutput,
getPropertyValue(
"InputWorkspace"), minIndex, maxIndex, indices);
181 return validationOutput;
187bool useSpectrum(
const SpectrumInfo &spectrumInfo,
const size_t wsIndex,
const bool keepMonitors,
size_t &numMasked) {
190 if (!keepMonitors && spectrumInfo.
isMonitor(wsIndex))
193 if (spectrumInfo.
isMasked(wsIndex)) {
211 size_t numSpectra(0);
218 auto spectrumInfo = localworkspace->spectrumInfo();
238 outputWorkspace = create<EventWorkspace>(*eventW, 1, eventW->binEdges(0));
249 auto &outSpec = outputWorkspace->getSpectrum(0);
252 outSpec.setSharedX(localworkspace->sharedX(0));
256 outSpec.clearDetectorIDs();
259 outSpec.addDetectorIDs(localworkspace->getSpectrum(i).getDetectorIDs());
263 if (localworkspace->id() ==
"RebinnedOutput") {
284 outputWorkspace->mutableRun().addProperty(
"NumAllSpectra",
int(numSpectra),
"",
true);
285 outputWorkspace->mutableRun().addProperty(
"NumMaskSpectra",
int(numMasked),
"",
true);
286 outputWorkspace->mutableRun().addProperty(
"NumZeroSpectra",
int(numZeros),
"",
true);
297 const std::vector<int> indices_list =
getProperty(
"ListOfWorkspaceIndices");
298 m_indices.insert(indices_list.begin(), indices_list.end());
306 maxIndex =
static_cast<int>(numberOfSpectra - 1);
312 for (
int i = minIndex; i <= maxIndex; i++) {
315 if (useSpectrum(spectrumInfo,
static_cast<size_t>(i),
m_keepMonitors, numMasked)) {
316 m_indices.insert(
static_cast<size_t>(i));
334 size_t totalSpec = localworkspace->getNumberHistograms();
338 if (
index < totalSpec) {
339 temp = localworkspace->getSpectrum(
index).getSpectrumNo();
360 std::string outName =
"_" + wksp->getName() +
"_clean";
361 alg->setProperty(
"OutputWorkspace", outName);
362 alg->setProperty(
"NaNValue", 0.0);
363 alg->setProperty(
"NaNError", 0.0);
364 alg->setProperty(
"InfinityValue", 0.0);
365 alg->setProperty(
"InfinityError", 0.0);
366 alg->executeAsChildAlg();
367 return alg->getProperty(
"OutputWorkspace");
387 auto &YErrorSum = outSpec.
mutableE();
390 for (
size_t jbin = 0; jbin <
m_yLength; jbin++) {
392 YErrorSum[jbin] = 0.;
395 YSum[jbin] += inWS->y(iwksp)[jbin];
396 YErrorSum[jbin] += inWS->e(iwksp)[jbin] * inWS->e(iwksp)[jbin];
398 YErrorSum[jbin] = sqrt(YErrorSum[jbin]);
417 auto &YErrorSum = outSpec.
mutableE();
419 std::vector<size_t> nZeroes(YSum.size(), 0);
422 for (
size_t jbin = 0; jbin <
m_yLength; jbin++) {
423 double normalization = 0.;
425 YErrorSum[jbin] = 0.;
429 double e = inWS->e(iwksp)[jbin];
430 double y = inWS->y(iwksp)[jbin];
431 if (std::isnormal(e)) {
432 weight = 1. / (e * e);
437 normalization += weight;
438 YSum[jbin] += weight *
y;
441 if (normalization != 0.) {
442 normalization = 1. / normalization;
443 YSum[jbin] *= normalization;
445 YErrorSum[jbin] = sqrt(normalization);
449 YSum[jbin] *= double(
m_indices.size() - nZeroes[jbin]);
450 YErrorSum[jbin] *= double(
m_indices.size() - nZeroes[jbin]);
455 numZeros = std::accumulate(nZeroes.begin(), nZeroes.end(),
size_t(0));
467 Progress &progress,
size_t &numZeros) {
470 auto isFinalized = inWS->isFinalized();
473 auto &outSpec = outWS->getSpectrum(0);
474 auto &YSum = outSpec.mutableY();
475 auto &YErrorSum = outSpec.mutableE();
476 auto &FracSum = outWS->dataF(0);
479 for (
size_t jbin = 0; jbin <
m_yLength; jbin++) {
481 YErrorSum[jbin] = 0.;
486 double fracVal = (isFinalized ? inWS->readF(iwksp)[jbin] : 1.0);
487 double y = inWS->y(iwksp)[jbin] * fracVal;
488 double e = inWS->e(iwksp)[jbin] * fracVal;
491 YErrorSum[jbin] += e * e;
492 FracSum[jbin] += inWS->readF(iwksp)[jbin];
494 YErrorSum[jbin] = sqrt(YErrorSum[jbin]);
501 auto useFractionalArea =
getProperty(
"UseFractionalArea");
502 if (useFractionalArea) {
503 outWS->finalize(
false);
516 Progress &progress,
size_t &numZeros) {
519 auto isFinalized = inWS->isFinalized();
522 auto &outSpec = outWS->getSpectrum(0);
523 auto &YSum = outSpec.mutableY();
524 auto &YErrorSum = outSpec.mutableE();
525 auto &FracSum = outWS->dataF(0);
527 std::vector<size_t> nZeroes(YSum.size(), 0);
530 for (
size_t jbin = 0; jbin <
m_yLength; jbin++) {
532 YErrorSum[jbin] = 0.;
534 double normalization = 0.;
538 double fracVal = (isFinalized ? inWS->readF(iwksp)[jbin] : 1.0);
539 double y = inWS->y(iwksp)[jbin] * fracVal;
540 double e = inWS->e(iwksp)[jbin] * fracVal;
543 if (std::isnormal(e)) {
544 weight = 1. / (e * e);
549 normalization += weight;
550 YSum[jbin] += weight *
y;
551 FracSum[jbin] += inWS->readF(iwksp)[jbin];
554 if (normalization != 0.) {
555 normalization = 1. / normalization;
556 YSum[jbin] *= normalization;
558 YErrorSum[jbin] = sqrt(normalization);
562 YSum[jbin] *= double(
m_indices.size() - nZeroes[jbin]);
563 YErrorSum[jbin] *= double(
m_indices.size() - nZeroes[jbin]);
567 numZeros = std::accumulate(nZeroes.begin(), nZeroes.end(),
size_t(0));
570 auto useFractionalArea =
getProperty(
"UseFractionalArea");
571 if (useFractionalArea) {
572 outWS->finalize(
false);
587 EventWorkspace_sptr outputEventWorkspace = std::dynamic_pointer_cast<EventWorkspace>(outputWorkspace);
588 EventList &outputEL = outputEventWorkspace->getSpectrum(0);
593 std::size_t numOutputEvents{0};
595 numOutputEvents += inputWorkspace->getSpectrum(i).getNumberEvents();
597 outputEL.
switchTo(inputWorkspace->getSpectrum(0).getEventType());
598 outputEL.
reserve(numOutputEvents);
603 const EventList &inputEL = inputWorkspace->getSpectrum(i);
604 if (inputEL.
empty()) {
#define DECLARE_ALGORITHM(classname)
std::map< DeltaEMode::Type, std::string > index
void declareProperty(std::unique_ptr< Kernel::Property > p, const std::string &doc="") override
Add a property to the list of managed properties.
std::string getPropertyValue(const std::string &name) const override
Get the value of a property as a string.
TypedValue getProperty(const std::string &name) const override
Get the value of a property.
virtual std::shared_ptr< Algorithm > createChildAlgorithm(const std::string &name, const double startProgress=-1., const double endProgress=-1., const bool enableLogging=true, const int &version=-1)
Create a Child Algorithm.
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
static bool isEmpty(const NumT toCheck)
checks that the value was not set by users, uses the value in empty double/int.
A "spectrum" is an object that holds the data for a particular spectrum, in particular:
HistogramData::HistogramY & mutableY() &
void clearDetectorIDs()
Clear the detector IDs set.
void setSpectrumNo(specnum_t num)
Sets the spectrum number of this spectrum.
HistogramData::HistogramE & mutableE() &
Helper class for reporting progress from algorithms.
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.
bool hasDetectors(const size_t index) const
Returns true if the spectrum is associated with detectors in the instrument.
bool isMasked(const size_t index) const
Returns true if the detector(s) associated with the spectrum are masked.
A property class for workspaces.
void doFractionalSum(RebinnedOutput_const_sptr const &, RebinnedOutput_sptr const &, API::Progress &, size_t &)
Handle logic for RebinnedOutput workspaces.
void doSimpleWeightedSum(API::MatrixWorkspace_const_sptr const &, API::ISpectrum &, API::Progress &, size_t &)
Perform a weighted sum of the spectra in the input workspace, where values in each bin are weighted b...
size_t m_yLength
Blocksize of the input workspace.
size_t determineIndices(API::SpectrumInfo const &, const size_t numberOfSpectra)
bool m_keepMonitors
Set true to keep monitors.
void exec() override
Executes the algorithm.
std::map< std::string, std::string > validateInputs() override
Cross-input validation.
void doFractionalWeightedSum(RebinnedOutput_const_sptr const &, RebinnedOutput_sptr const &, API::Progress &, size_t &)
This function handles the logic for summing RebinnedOutput workspaces.
specnum_t m_outSpecNum
The output spectrum number.
specnum_t getOutputSpecNo(const API::MatrixWorkspace_const_sptr &localworkspace)
Determine the minimum spectrum No for summing.
void execEvent(const API::MatrixWorkspace_sptr &outputWorkspace, API::Progress &progress, size_t &numZeros)
Executes the algorithm.
bool m_calculateWeightedSum
void init() override
Initialisation method.
API::MatrixWorkspace_sptr replaceSpecialValues()
Calls an algorithm to replace special values within the workspace such as NaN or Inf to 0.
void doSimpleSum(API::MatrixWorkspace_const_sptr const &, API::ISpectrum &, API::Progress &, size_t &)
Handle logic for summing standard workspaces.
size_t m_numberOfSpectra
numberOfSpectra in the input
std::set< size_t > m_indices
Set of indices to sum.
void reserve(size_t num) override
Reserve a certain number of entries in event list of the specified eventType.
void switchTo(Mantid::API::EventType newType) override
Switch the EventList to use the given EventType (TOF, WEIGHTED, or WEIGHTED_NOTIME)
bool empty() const
Much like stl containers, returns true if there is nothing in the event list.
Support for a property that holds an array of values.
IPropertyManager * setProperty(const std::string &name, const T &value)
Templated method to set the value of a PropertyWithValue.
void setPropertySettings(const std::string &name, std::unique_ptr< IPropertySettings const > settings)
Add a PropertySettings instance to the chain of settings for a given property.
void warning(const std::string &msg)
Logs at warning level.
void information(const std::string &msg)
Logs at information level.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
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 RebinnedOutput > RebinnedOutput_const_sptr
shared pointer to a const RebinnedOutput
std::shared_ptr< const EventWorkspace > EventWorkspace_const_sptr
shared pointer to a const Workspace2D
std::shared_ptr< RebinnedOutput > RebinnedOutput_sptr
shared pointer to the RebinnedOutput class
std::shared_ptr< EventWorkspace > EventWorkspace_sptr
shared pointer to the EventWorkspace class
constexpr int EMPTY_INT() noexcept
Returns what we consider an "empty" integer within a property.
int32_t specnum_t
Typedef for a spectrum Number.
std::string to_string(const wide_integer< Bits, Signed > &n)
@ Input
An input workspace.
@ Output
An output workspace.