Mantid
Loading...
Searching...
No Matches
ResampleX.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"
16
17#include <span>
18#include <sstream>
19
20namespace Mantid::Algorithms {
21using namespace API;
22using namespace DataObjects;
23using namespace Kernel;
24using HistogramData::BinEdges;
25using std::map;
26using std::string;
27using std::stringstream;
28using std::vector;
29
30// Register the algorithm into the AlgorithmFactory
31DECLARE_ALGORITHM(ResampleX)
32
33//----------------------------------------------------------------------------------------------
35const std::string ResampleX::name() const { return "ResampleX"; }
36
38int ResampleX::version() const { return 1; }
39
40const std::string ResampleX::alias() const { return ""; }
41
42//----------------------------------------------------------------------------------------------
46 declareProperty(std::make_unique<WorkspaceProperty<>>("InputWorkspace", "", Direction::Input), "An input workspace.");
47 declareProperty(std::make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output),
48 "An output workspace.");
49
50 declareProperty(std::make_unique<ArrayProperty<double>>("XMin"),
51 "A comma separated list of the XMin for every spectrum. (Optional)");
52 declareProperty(std::make_unique<ArrayProperty<double>>("XMax"),
53 "A comma separated list of the XMax for every spectrum. (Optional)");
54
55 auto min = std::make_shared<BoundedValidator<int>>();
56 min->setLower(1);
57 declareProperty("NumberBins", 0, min, "Number of bins to split up each spectrum into.");
58 declareProperty("LogBinning", false, "Use logarithmic binning. If false use constant step sizes.");
59
60 declareProperty("PreserveEvents", true,
61 "Keep the output workspace as an EventWorkspace, if the "
62 "input has events (default).\n"
63 "If the input and output EventWorkspace names are the same, "
64 "only the X bins are set, which is very quick.\n"
65 "If false, then the workspace gets converted to a "
66 "Workspace2D histogram.");
67}
68
72map<string, string> ResampleX::validateInputs() {
73 map<string, string> errors;
74 vector<double> xmins = getProperty("XMin");
75 vector<double> xmaxs = getProperty("XMax");
76 if ((!xmins.empty()) && (!xmaxs.empty())) {
77 if (xmins.size() != xmaxs.size()) {
78 stringstream msg;
79 msg << "XMin and XMax do not define same number of spectra (" << xmins.size() << " != " << xmaxs.size() << ")";
80 errors.emplace("XMax", msg.str());
81 } else {
82 size_t size = xmins.size();
83 for (size_t i = 0; i < size; ++i) {
84 if (xmins[i] >= xmaxs[i]) {
85 stringstream msg;
86 msg << "XMin (" << xmins[i] << ") cannot be greater than XMax (" << xmaxs[i] << ")";
87 errors.emplace("XMax", msg.str());
88 }
89 }
90 }
91 }
92
93 return errors;
94}
95
108string determineXMinMax(const MatrixWorkspace_sptr &inputWS, vector<double> &xmins, vector<double> &xmaxs) {
109 const size_t numSpectra = inputWS->getNumberHistograms();
110
111 // pad out the ranges by copying the first value to the rest that are needed
112 if (xmins.size() == 1 && numSpectra > xmins.size()) {
113 const double value = xmins.front();
114 xmins.insert(xmins.end(), numSpectra - xmins.size(), value);
115 }
116 if (xmaxs.size() == 1 && numSpectra > xmaxs.size()) {
117 const double value = xmaxs.front();
118 xmaxs.insert(xmaxs.end(), numSpectra - xmaxs.size(), value);
119 }
120
121 // should the individiual values be calculated?
122 const bool updateXMins = xmins.empty(); // they weren't set
123 const bool updateXMaxs = xmaxs.empty(); // they weren't set
124
125 stringstream msg;
126
127 // determine overall xmin/xmax
128 double xmin_wksp = inputWS->getXMin();
129 double xmax_wksp = inputWS->getXMax();
130 EventWorkspace_const_sptr inputEventWS = std::dynamic_pointer_cast<const EventWorkspace>(inputWS);
131 if (inputEventWS != nullptr && inputEventWS->getNumberEvents() > 0) {
132 xmin_wksp = inputEventWS->getTofMin();
133 xmax_wksp = inputEventWS->getTofMax();
134 }
135
136 for (size_t i = 0; i < numSpectra; ++i) {
137 // determine ranges if necessary
138 if (updateXMins || updateXMaxs) {
139 const auto &xvalues = inputWS->x(i);
140 if (updateXMins) {
141 const auto minimum = xvalues.front();
142 if (std::isnan(minimum) || minimum >= xmax_wksp) {
143 xmins.emplace_back(xmin_wksp);
144 } else {
145 xmins.emplace_back(minimum);
146 }
147 }
148 if (updateXMaxs) {
149 const auto maximum = xvalues.back();
150 if (std::isnan(maximum) || maximum <= xmin_wksp) {
151 xmaxs.emplace_back(xmax_wksp);
152 } else {
153 xmaxs.emplace_back(maximum);
154 }
155 }
156 }
157
158 // error check the ranges
159 if (xmins[i] >= xmaxs[i]) {
160 if (!msg.str().empty())
161 msg << ", ";
162 msg << "at wksp_index=" << i << " XMin >= XMax (" << xmins[i] << " >= " << xmaxs[i] << ")";
163 }
164 }
165
166 return msg.str(); // empty string means nothing went wrong
167}
168
177void ResampleX::setOptions(const int numBins, const bool useLogBins, const bool isDist) {
178 m_numBins = numBins;
179 m_useLogBinning = useLogBins;
180 m_isDistribution = isDist;
181}
182
192double ResampleX::determineBinning(MantidVec &xValues, const double xmin, const double xmax) {
193 xValues.clear(); // clear out the x-values
194
195 size_t numBoundaries(0);
196 size_t reqNumBoundaries(m_numBins);
197 size_t expNumBoundaries(m_numBins);
199 reqNumBoundaries -= 1; // to get the VectorHelper to do the right thing
200 else
201 expNumBoundaries += 1; // should be one more bin boundary for histograms
202
203 vector<double> params; // xmin, delta, xmax
204 params.emplace_back(xmin);
205 params.emplace_back(0.); // dummy delta value
206 params.emplace_back(xmax);
207
208 // constant binning is easy
209 if (m_useLogBinning) {
210 if (xmin == 0)
211 throw std::invalid_argument("Cannot calculate log of xmin=0");
212 if (xmax == 0)
213 throw std::invalid_argument("Cannot calculate log of xmax=0");
214 if (xmin < 0. && xmax > 0.) {
215 std::stringstream msg;
216 msg << "Cannot calculate logorithmic binning that changes sign (xmin=" << xmin << ", xmax=" << xmax << ")";
217 throw std::invalid_argument(msg.str());
218 }
219
220 const int MAX_ITER(100); // things went wrong if we get this far
221
222 // starting delta value assuming everything happens exactly
223 double delta = (log(xmax) - log(xmin)) / static_cast<double>(m_numBins);
224 double shift = .1;
225 int sign = 0;
226 for (int numIter = 0; numIter < MAX_ITER; ++numIter) {
227 params[1] = -1. * delta;
228 if (!m_isDistribution)
229 params[2] = xmax + delta;
230 numBoundaries = VectorHelper::createAxisFromRebinParams(params, xValues, true);
231
232 if (numBoundaries == expNumBoundaries) {
233 double diff = (xmax - xValues.back());
234 if (diff != 0.) {
235 g_log.debug() << "Didn't get the exact xmax value: [xmax - xValues.back()=" << diff
236 << "] [relative diff = " << fabs(100. * diff / xmax) << "%]\n";
237 g_log.debug() << "Resetting final x-value to xmax\n";
238 *(xValues.rbegin()) = xmax;
239 }
240 break;
241 } else if (numBoundaries > expNumBoundaries) // too few points
242 {
243 delta *= (1. + shift);
244 if (sign < 0)
245 shift *= .9;
246 sign = 1;
247 } else // too many points
248 {
249 delta *= (1. - shift);
250 if (sign > 0)
251 shift *= .9;
252 sign = -1;
253 }
254 }
255 } else {
256 params[1] = (xmax - xmin) / static_cast<double>(reqNumBoundaries);
257 numBoundaries = VectorHelper::createAxisFromRebinParams(params, xValues, true);
258 }
259
260 if (numBoundaries != expNumBoundaries) {
261 g_log.warning() << "Did not generate the requested number of bins: generated " << numBoundaries << " requested "
262 << expNumBoundaries << "(xmin=" << xmin << ", xmax=" << xmax << ")\n";
263 }
264
265 // return the delta value so the caller can do debug printing
266 return params[1];
267}
268
269//----------------------------------------------------------------------------------------------
273 // generically having access to the input workspace is a good idea
274 MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
275 MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
276 bool inPlace = (inputWS == outputWS); // Rebinning in-place
277 m_isDistribution = inputWS->isDistribution();
278 m_isHistogram = inputWS->isHistogramData();
279 const auto numSpectra = static_cast<int>(inputWS->getNumberHistograms());
280
281 // the easy parameters
282 m_useLogBinning = getProperty("LogBinning");
283 m_numBins = getProperty("NumberBins");
284 m_preserveEvents = getProperty("PreserveEvents");
285
286 // determine the xmin/xmax for the workspace
287 vector<double> xmins = getProperty("XMin");
288 vector<double> xmaxs = getProperty("XMax");
289 string error = determineXMinMax(inputWS, xmins, xmaxs);
290 if (!error.empty())
291 throw std::runtime_error(error);
292
293 bool common_limits = true;
294 {
295 double xmin_common = xmins[0];
296 double xmax_common = xmaxs[0];
297 for (size_t i = 1; i < xmins.size(); ++i) {
298 if (xmins[i] != xmin_common) {
299 common_limits = false;
300 break;
301 }
302 if (xmaxs[i] != xmax_common) {
303 common_limits = false;
304 break;
305 }
306 }
307 }
308 if (common_limits) {
309 g_log.debug() << "Common limits between all spectra\n";
310 } else {
311 g_log.debug() << "Does not have common limits between all spectra\n";
312 }
313
314 // start doing actual work
315 EventWorkspace_const_sptr inputEventWS = std::dynamic_pointer_cast<const EventWorkspace>(inputWS);
316 if (inputEventWS != nullptr) {
317 if (m_preserveEvents) {
318 if (inPlace) {
319 g_log.debug() << "Rebinning event workspace in place\n";
320 } else {
321 g_log.debug() << "Rebinning event workspace out of place\n";
322 outputWS = inputWS->clone();
323 }
324 auto outputEventWS = std::dynamic_pointer_cast<EventWorkspace>(outputWS);
325
326 if (common_limits) {
327 // get the delta from the first since they are all the same
328 std::vector<double> xAxisTmp;
329 const double delta = this->determineBinning(xAxisTmp, xmins[0], xmaxs[0]);
330 BinEdges xValues(std::move(xAxisTmp));
331 g_log.debug() << "delta = " << delta << "\n";
332 outputEventWS->setAllX(xValues);
333 } else {
334 // initialize progress reporting.
335 Progress prog(this, 0.0, 1.0, numSpectra);
336
337 // do the rebinning
338 PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
339 for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
341 std::vector<double> xAxisTmp;
342 const double delta = this->determineBinning(xAxisTmp, xmins[wkspIndex], xmaxs[wkspIndex]);
343 BinEdges xValues(std::move(xAxisTmp));
344 g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << " xmin=" << xmins[wkspIndex]
345 << " xmax=" << xmaxs[wkspIndex] << "\n";
346 outputEventWS->setHistogram(wkspIndex, xValues);
347 prog.report(name()); // Report progress
349 }
351 }
352 } // end if (m_preserveEvents)
353 else // event workspace -> matrix workspace
354 {
355 //--------- Different output, OR you're inplace but not preserving Events
356 g_log.information() << "Creating a Workspace2D from the EventWorkspace " << inputEventWS->getName() << ".\n";
357 outputWS = create<DataObjects::Workspace2D>(*inputWS, numSpectra, HistogramData::BinEdges(m_numBins + 1));
358
359 // Initialize progress reporting.
360 Progress prog(this, 0.0, 1.0, numSpectra);
361
362 // Go through all the histograms and set the data
363 PARALLEL_FOR_IF(Kernel::threadSafe(*inputEventWS, *outputWS))
364 for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
366
367 // Set the X axis for each output histogram
368 MantidVec xValues;
369 const double delta = this->determineBinning(xValues, xmins[wkspIndex], xmaxs[wkspIndex]);
370 g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
371 outputWS->setBinEdges(wkspIndex, xValues);
372
373 // Get a const event list reference. inputEventWS->dataY() doesn't work.
374 const EventList &el = inputEventWS->getSpectrum(wkspIndex);
375 MantidVec y_data, e_data;
376 // The EventList takes care of histogramming.
377 el.generateHistogram(xValues, y_data, e_data);
378
379 // Copy the data over.
380 outputWS->mutableY(wkspIndex) = y_data;
381 outputWS->mutableE(wkspIndex) = e_data;
382
383 // Report progress
384 prog.report(name());
386 }
388
389 // Copy all the axes
390 for (int i = 1; i < inputWS->axes(); i++) {
391 outputWS->replaceAxis(i, std::unique_ptr<Axis>(inputWS->getAxis(i)->clone(outputWS.get())));
392 outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
393 }
394
395 // Copy the units over too.
396 for (int i = 0; i < outputWS->axes(); ++i) {
397 outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
398 }
399 outputWS->setYUnit(inputEventWS->YUnit());
400 outputWS->setYUnitLabel(inputEventWS->YUnitLabel());
401 }
402 // Assign it to the output workspace property
403 setProperty("OutputWorkspace", outputWS);
404 return;
405 } else // (inputeventWS != NULL)
406 {
407 // workspace2d ----------------------------------------------------------
408 if (!m_isHistogram) {
409 g_log.information() << "Rebin: Converting Data to Histogram.\n";
410 Mantid::API::Algorithm_sptr ChildAlg = createChildAlgorithm("ConvertToHistogram");
411 ChildAlg->initialize();
412 ChildAlg->setProperty("InputWorkspace", inputWS);
413 ChildAlg->execute();
414 inputWS = ChildAlg->getProperty("OutputWorkspace");
415 }
416
417 // make output Workspace the same type is the input, but with new length of
418 // signal array
419 outputWS = API::WorkspaceFactory::Instance().create(inputWS, numSpectra, m_numBins + 1, m_numBins);
420
421 // Copy over the 'vertical' axis
422 if (inputWS->axes() > 1)
423 outputWS->replaceAxis(1, std::unique_ptr<Axis>(inputWS->getAxis(1)->clone(outputWS.get())));
424
425 Progress prog(this, 0.0, 1.0, numSpectra);
426 PARALLEL_FOR_IF(Kernel::threadSafe(*inputWS, *outputWS))
427 for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
429 // get const references to input Workspace arrays (no copying)
430 Mantid::HistogramData::HistogramX const &XValues = inputWS->x(wkspIndex);
431 Mantid::HistogramData::HistogramY const &YValues = inputWS->y(wkspIndex);
432 Mantid::HistogramData::HistogramE const &YErrors = inputWS->e(wkspIndex);
433
434 // get writable views onto the output workspace data (no copying)
435 std::span<double> const YValues_new{outputWS->mutableY(wkspIndex)};
436 std::span<double> const YErrors_new{outputWS->mutableE(wkspIndex)};
437
438 // create new output X axis
439 MantidVec XValues_new;
440 const double delta = this->determineBinning(XValues_new, xmins[wkspIndex], xmaxs[wkspIndex]);
441 g_log.debug() << "delta[wkspindex=" << wkspIndex << "] = " << delta << "\n";
442
443 // output data arrays are implicitly filled by function
444 try {
445 VectorHelper::rebin(XValues, YValues, YErrors, XValues_new, YValues_new, YErrors_new, m_isDistribution);
446 } catch (std::exception &ex) {
447 g_log.error() << "Error in rebin function: " << ex.what() << '\n';
448 throw;
449 }
450
451 // Populate the output workspace X values
452 outputWS->setBinEdges(wkspIndex, XValues_new);
453
454 prog.report(name());
456 }
458 outputWS->setDistribution(m_isDistribution);
459
460 // Now propagate any masking correctly to the output workspace
461 // More efficient to have this in a separate loop because
462 // MatrixWorkspace::maskBins blocks multi-threading
463 for (int wkspIndex = 0; wkspIndex < numSpectra; ++wkspIndex) {
464 if (inputWS->hasMaskedBins(wkspIndex)) // Does the current spectrum have any masked bins?
465 {
466 this->propagateMasks(inputWS, outputWS, wkspIndex);
467 }
468 }
469 // Copy the units over too.
470 for (int i = 0; i < outputWS->axes(); ++i) {
471 outputWS->getAxis(i)->unit() = inputWS->getAxis(i)->unit();
472 }
473
474 if (!m_isHistogram) {
475 g_log.information() << "Rebin: Converting Data back to Data Points.\n";
476 Mantid::API::Algorithm_sptr ChildAlg = createChildAlgorithm("ConvertToPointData");
477 ChildAlg->initialize();
478 ChildAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", outputWS);
479 ChildAlg->execute();
480 outputWS = ChildAlg->getProperty("OutputWorkspace");
481 }
482
483 // Assign it to the output workspace property
484 setProperty("OutputWorkspace", outputWS);
485 } // end if (inputeventWS != NULL)
486}
487
488} // namespace Mantid::Algorithms
std::string name
Definition Run.cpp:60
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:542
double value
The value of the point.
Definition FitMW.cpp:51
double error
#define fabs(x)
Definition Matrix.cpp:22
#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.
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.
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.
Helper class for reporting progress from algorithms.
Definition Progress.h:25
A property class for workspaces.
void propagateMasks(const API::MatrixWorkspace_const_sptr &inputWS, const API::MatrixWorkspace_sptr &outputWS, const int hist, const bool IgnoreBinErrors=false)
Takes the masks in the input workspace and apportions the weights into the new bins that overlap with...
Definition Rebin.cpp:438
ResampleX : TODO: DESCRIPTION.
Definition ResampleX.h:20
void setOptions(const int numBins, const bool useLogBins, const bool isDist)
MADE PUBLIC FOR TESTING ONLY - DO NOT USE.
void exec() override
Execute the algorithm.
const std::string name() const override
Algorithm's name for identification.
Definition ResampleX.cpp:35
std::map< std::string, std::string > validateInputs() override
More complicated checks of parameters and their relations.
Definition ResampleX.cpp:72
const std::string alias() const override
Algorithm's aliases.
Definition ResampleX.cpp:40
double determineBinning(MantidVec &xValues, const double xmin, const double xmax)
MADE PUBLIC FOR TESTING ONLY - DO NOT USE.
void init() override
Initialize the algorithm's properties.
Definition ResampleX.cpp:45
int version() const override
Algorithm's version for identification.
Definition ResampleX.cpp:38
A class for holding :
Definition EventList.h:58
void generateHistogram(std::span< double const > X, MantidVec &Y, MantidVec &E, bool skipError=false) const override
Generates both the Y and E (error) histograms w.r.t TOF for an EventList with or without WeightedEven...
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 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
void report()
Increments the loop counter by 1, then sends the progress notification on behalf of its algorithm.
static T & Instance()
Return a reference to the Singleton instance, creating it if it does not already exist Creation is do...
std::shared_ptr< Algorithm > Algorithm_sptr
Typedef for a shared pointer to an Algorithm.
Definition Algorithm.h:52
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
Kernel::Logger g_log("DetermineSpinStateOrder")
string determineXMinMax(const MatrixWorkspace_sptr &inputWS, vector< double > &xmins, vector< double > &xmaxs)
Determine the min and max x-values for each spectrum and error check the pairs.
std::shared_ptr< const EventWorkspace > EventWorkspace_const_sptr
shared pointer to a const Workspace2D
void MANTID_KERNEL_DLL rebin(std::span< double const > xold, std::span< double const > yold, std::span< double const > eold, std::span< double const > xnew, std::span< double > ynew, std::span< double > enew, bool distribution, bool addition=false)
The input and output ranges are taken as spans so that the size-checked histogram data types,...
std::size_t MANTID_KERNEL_DLL createAxisFromRebinParams(const std::vector< double > &params, std::vector< double > &xnew, const bool resize_xnew=true, const bool full_bins_only=false, const double xMinHint=std::nan(""), const double xMaxHint=std::nan(""), const bool useReverseLogarithmic=false, const double power=-1)
Creates a new output X array given a 'standard' set of rebinning parameters.
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.
std::vector< double > MantidVec
typedef for the data storage used in Mantid matrix workspaces
Definition cow_ptr.h:172
STL namespace.
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54