39const std::string NON_UNIFORM_GROUP =
"NonUniform Detectors";
40const std::string RECTANGULAR_GROUP =
"Rectangular Detectors";
41const std::string INPUT_WORKSPACE =
"InputWorkspace";
46 using Callable = std::function<void()>;
47 CallOnExit(Callable &&callable) noexcept :
m_callable(std::move(callable)) {}
64 std::make_shared<InstrumentValidator>()),
65 "The workspace containing the spectra to be averaged.");
67 "The name of the workspace to be created as the output of "
71 auto mustBePositiveDouble = std::make_shared<BoundedValidator<double>>();
72 mustBePositiveDouble->setLower(0.0);
75 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
76 mustBePositive->setLower(0);
78 std::vector<std::string> propOptions{
"Flat",
"Linear",
"Parabolic",
"Gaussian"};
79 declareProperty(
"WeightedSum",
"Flat", std::make_shared<StringListValidator>(propOptions),
80 "What sort of Weighting scheme to use?\n"
81 " Flat: Effectively no-weighting, all weights are 1.\n"
82 " Linear: Linear weighting 1 - r/R from origin.\n"
83 " Parabolic : Weighting as cutoff - x + cutoff - y + 1."
84 " Gaussian : Uses the absolute distance x^2 + y^2 ... "
85 "normalised by the cutoff^2");
87 declareProperty(
"Sigma", 0.5, mustBePositiveDouble,
"Sigma value for gaussian weighting schemes. Defaults to 0.5. ");
90 declareProperty(
"IgnoreMaskedDetectors",
true,
"If true, do not consider masked detectors in the NN search.");
93 "If the InputWorkspace is an "
94 "EventWorkspace, this will preserve "
95 "the full event list (warning: this "
96 "will use much more memory!).");
101 "The number of X (horizontal) adjacent pixels to average together. "
102 "Only for instruments with RectangularDetectors. ");
105 "The number of Y (vertical) adjacent pixels to average together. "
106 "Only for instruments with RectangularDetectors. ");
109 "The total number of X (horizontal) adjacent pixels to sum together. "
110 "Only for instruments with RectangularDetectors. AdjX will be ignored "
111 "if SumPixelsX > 1.");
114 "The total number of Y (vertical) adjacent pixels to sum together. "
115 "Only for instruments with RectangularDetectors. AdjY will be ignored if "
119 "The number of pixels to zero at edges. "
120 "Only for instruments with RectangularDetectors. ");
130 std::vector<std::string> radiusPropOptions{
"Meters",
"NumberOfPixels"};
131 declareProperty(
"RadiusUnits",
"Meters", std::make_shared<StringListValidator>(radiusPropOptions),
132 "Units used to specify the radius.\n"
133 " Meters : Radius is in meters.\n"
134 " NumberOfPixels : Radius is in terms of the number of pixels.");
137 "The radius cut-off around a pixel to look for nearest neighbours to "
139 "This radius cut-off is applied to a set of nearest neighbours whose "
141 "defined in the NumberOfNeighbours property. See below for more details. "
143 "If 0, will use the AdjX and AdjY parameters for rectangular detectors "
147 "Number of nearest neighbouring pixels.\n"
148 "The default is 8.");
151 "Sum nearest neighbouring pixels with same parent.\n"
152 "Number of pixels will be reduced. The default is false.");
155 "OuputWorkspace will have same number of pixels as "
156 "InputWorkspace using SumPixelsX and SumPixelsY. Individual "
157 "pixels will have averages.");
170 g_log.
debug(
"SmoothNeighbours processing assuming rectangular detectors.");
174 const auto &componentInfo =
m_inWS->componentInfo();
175 const auto &detectorInfo =
m_inWS->detectorInfo();
181 std::vector<size_t> detList;
182 for (
size_t i = 0; i < componentInfo.size(); ++i) {
183 if (componentInfo.isGridDetector(i)) {
184 detList.emplace_back(i);
188 if (detList.empty()) {
197 Progress prog(
this, 0.0, 1.0, detList.size());
207 bool sum = sumX * sumY > 1;
217 std::vector<std::pair<int, int>> idToIndexMap;
218 idToIndexMap.reserve(detList.size());
219 for (
int i = 0; i < static_cast<int>(detList.size()); i++)
220 idToIndexMap.emplace_back(detectorInfo.detid(componentInfo.detectorIndexAtXYZ(detList[i], 0, 0, 0)), i);
224 stable_sort(idToIndexMap.begin(), idToIndexMap.end());
227 for (
const auto &idIndex : idToIndexMap) {
228 const size_t bankIndex = detList[idIndex.second];
229 const auto grid = componentInfo.pixelGridComponent(bankIndex);
230 const std::string det_name = componentInfo.name(bankIndex);
231 for (
int j = 0; j < grid.nX; j += sumX) {
232 for (
int k = 0; k < grid.nY; k += sumY) {
233 double totalWeight = 0;
235 std::vector<weightedNeighbour> neighbours;
237 for (
int ix = startX; ix <= endX; ix++)
238 for (
int iy = startY; iy <= endY; iy++) {
248 int pixelID = detectorInfo.detid(componentInfo.detectorIndexAtXYZ(bankIndex, j + ix, k + iy, 0));
251 auto mapEntry = pixel_to_wi.find(pixelID);
252 if (mapEntry != pixel_to_wi.end()) {
253 size_t wi = mapEntry->second;
254 neighbours.emplace_back(wi, smweight);
256 totalWeight += smweight;
262 for (
auto &neighbour : neighbours)
263 neighbour.second /= totalWeight;
280 g_log.
debug(
"SmoothNeighbours processing NOT assuming rectangular detectors.");
283 this->
progress(0.2,
"Building Neighbour Map");
290 bool ignoreMaskedDetectors =
getProperty(
"IgnoreMaskedDetectors");
299 std::shared_ptr<const Geometry::IComponent> parent, neighbParent, grandparent, neighbGParent;
300 std::vector<bool> used(
m_inWS->getNumberHistograms(),
false);
301 const auto &detectorInfo =
m_inWS->detectorInfo();
302 for (
size_t wi = 0; wi <
m_inWS->getNumberHistograms(); wi++) {
309 const auto &dets =
m_inWS->getSpectrum(wi).getDetectorIDs();
310 const auto index = detectorInfo.indexOf(*dets.begin());
311 if (detectorInfo.isMonitor(
index))
313 if (detectorInfo.isMasked(
index)) {
321 const auto &det = detectorInfo.detector(
index);
322 parent = det.getParent();
324 grandparent = parent->getParent();
341 neighbSpectra[inSpec] =
V3D(0.0, 0.0, 0.0);
344 double totalWeight = 0;
346 std::vector<weightedNeighbour> neighbours;
349 for (
const auto &specDistance : neighbSpectra) {
353 double weight =
m_weightedSum->weightAt(specDistance.second);
357 auto mapIt = spec2index.find(spec);
358 if (mapIt != spec2index.end()) {
359 size_t neighWI = mapIt->second;
362 const std::set<detid_t> &dets =
m_inWS->getSpectrum(neighWI).getDetectorIDs();
363 const auto &det = detectorInfo.detector(*dets.begin());
364 neighbParent = det.getParent();
365 neighbGParent = neighbParent->getParent();
366 if (noNeigh >= sum || neighbParent->getName() != parent->getName() ||
367 neighbGParent->getName() != grandparent->getName() || used[neighWI])
370 used[neighWI] =
true;
372 neighbours.emplace_back(neighWI, weight);
373 totalWeight += weight;
380 for (
auto &neighbour : neighbours)
381 neighbour.second /= totalWeight;
399 if (strategyName ==
"Flat") {
401 }
else if (strategyName ==
"Linear") {
403 }
else if (strategyName ==
"Parabolic") {
404 m_weightedSum = std::make_unique<ParabolicWeighting>(cutOff);
405 }
else if (strategyName ==
"Gaussian") {
418 double translatedRadius = 0;
419 if (radiusUnits ==
"Meters") {
421 translatedRadius = enteredRadius;
422 }
else if (radiusUnits ==
"NumberOfPixels") {
424 const auto &firstDet =
m_inWS->spectrumInfo().detector(0);
427 firstDet.getBoundingBox(bbox);
430 translatedRadius = bbox.
width().
norm() * enteredRadius;
432 const std::string message =
"SmoothNeighbours::translateToMeters, Unknown Unit: " + radiusUnits;
433 throw std::invalid_argument(message);
435 return translatedRadius;
459 m_progress = std::make_unique<Progress>(
this, 0.0, 0.2,
m_inWS->getNumberHistograms());
462 CallOnExit resetInWSOnExit([
this]() {
m_inWS.reset(); });
463 CallOnExit resetNeighboursOnExit([
this]() {
474 auto wsEvent = std::dynamic_pointer_cast<EventWorkspace>(
m_inWS);
489 const size_t numberOfSpectra =
m_outWI;
491 const size_t YLength =
m_inWS->blocksize();
495 if (std::dynamic_pointer_cast<OffsetsWorkspace>(
m_inWS)) {
499 outWS = std::dynamic_pointer_cast<MatrixWorkspace>(
508 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
511 auto &outSpec = outWS->getSpectrum(outWIi);
514 auto &outY = outSpec.mutableY();
516 auto &outE = outSpec.mutableE();
518 auto &outX = outSpec.mutableX();
521 std::vector<weightedNeighbour> &neighbours =
m_neighbours[outWIi];
522 std::vector<weightedNeighbour>::iterator it;
523 for (it = neighbours.begin(); it != neighbours.end(); ++it) {
524 size_t inWI = it->first;
525 double weight = it->second;
526 double weightSquared = weight * weight;
528 const auto &inSpec =
m_inWS->getSpectrum(inWI);
529 const auto &inY = inSpec.y();
530 const auto &inE = inSpec.e();
531 const auto &inX = inSpec.x();
533 for (
size_t i = 0; i < YLength; i++) {
535 outY[i] += inY[i] * weight;
538 double errorSquared = inE[i];
539 errorSquared *= errorSquared;
540 errorSquared *= weightSquared;
541 outE[i] += errorSquared;
545 if (
m_inWS->isHistogramData()) {
546 outX[YLength] = inX[YLength];
551 for (
size_t i = 0; i < YLength; i++)
552 outE[i] = sqrt(outE[i]);
572 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
580 const auto &inSpec =
m_inWS->getSpectrum(neighbor.first);
581 outSpec.addDetectorIDs(inSpec.getDetectorIDs());
590 const size_t numberOfSpectra =
m_inWS->getNumberHistograms();
592 const size_t YLength =
m_inWS->blocksize();
596 if (std::dynamic_pointer_cast<OffsetsWorkspace>(
m_inWS)) {
598 outws2 = std::make_shared<OffsetsWorkspace>(
m_inWS->getInstrument());
600 outws2 = std::dynamic_pointer_cast<MatrixWorkspace>(
607 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
608 const auto &inSpec =
m_inWS->getSpectrum(outWIi);
609 auto &outSpec2 = outws2->getSpectrum(outWIi);
610 outSpec2.mutableX() = inSpec.x();
611 outSpec2.addDetectorIDs(inSpec.getDetectorIDs());
613 outSpec2.clearData();
617 const size_t numberOfSpectra2 = outWS->getNumberHistograms();
618 for (
int outWIi = 0; outWIi < int(numberOfSpectra2); outWIi++) {
622 outws2->setHistogram(neighbor.first, outWS->histogram(outWIi));
635 const size_t numberOfSpectra =
m_outWI;
636 const auto YLength =
static_cast<int>(
m_inWS->blocksize());
640 outWS = std::dynamic_pointer_cast<EventWorkspace>(
647 this->
setProperty(
"OutputWorkspace", std::dynamic_pointer_cast<MatrixWorkspace>(outWS));
650 std::vector<size_t> outputEvents(numberOfSpectra, 0);
651 for (
int i = 0; i < int(numberOfSpectra); i++) {
652 const std::vector<weightedNeighbour> &neighbours =
m_neighbours[i];
653 for (
const auto &neighbour : neighbours) {
654 size_t inWI = neighbour.first;
655 outputEvents[i] += ws->getSpectrum(inWI).getNumberEvents();
661 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
665 EventList &outEL = outWS->getSpectrum(outWIi);
666 outEL.
reserve(outputEvents[outWIi]);
669 std::vector<weightedNeighbour> &neighbours =
m_neighbours[outWIi];
670 std::vector<weightedNeighbour>::iterator it;
671 for (it = neighbours.begin(); it != neighbours.end(); ++it) {
672 size_t inWI = it->first;
674 double weight = it->second;
689 outWS->setAllX(
m_inWS->binEdges(0));
#define DECLARE_ALGORITHM(classname)
std::map< DeltaEMode::Type, std::string > index
#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.
const VecProperties ConstVecProperties
std::vector< Mantid::Kernel::Property * > VecProperties
Base class from which all concrete algorithm classes should be derived.
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.
void progress(double p, const std::string &msg="", double estimatedTime=0.0, int progressPrecision=0)
Sends ProgressNotification.
void clearDetectorIDs()
Clear the detector IDs set.
Base MatrixWorkspace Abstract Class.
virtual ISpectrum & getSpectrum(const size_t index)=0
Return the underlying ISpectrum ptr at the given workspace index.
virtual std::size_t getNumberHistograms() const =0
Returns the number of histograms in the workspace.
Helper class for reporting progress from algorithms.
WorkspaceNearestNeighbourInfo provides easy access to nearest-neighbour information for a workspace.
std::map< specnum_t, Kernel::V3D > getNeighboursExact(specnum_t spec) const
Queries the WorkspaceNearestNeighbours object for the selected spectrum number.
A property class for workspaces.
SpectraDistanceMap apply(SpectraDistanceMap &unfiltered) const
Apply the filtering based on radius.
void execWorkspace2D()
Execute the algorithm for a Workspace2D/don't preserve events input.
std::vector< std::vector< weightedNeighbour > > m_neighbours
Vector of list of neighbours (with weight) for each workspace index.
void setWeightingStrategy(const std::string &strategyName, double &cutOff)
Sets the weighting stragegy.
int m_edge
Edge pixels to ignore.
void init() override
Virtual method - must be overridden by concrete algorithm.
std::unique_ptr< WeightingStrategy > m_weightedSum
Weight the neighbours during summing.
void findNeighboursUbiquitous()
Use NearestNeighbours to find the neighbours for any instrument.
size_t m_outWI
number of output workspace pixels
bool m_expandSumAllPixels
expand by pixel IDs
double m_radius
Radius to search nearest neighbours.
SmoothNeighbours()
Default constructor.
void spreadPixels(const API::MatrixWorkspace_sptr &outWS)
Build the instrument/detector setup in workspace.
void setupNewInstrument(API::MatrixWorkspace &outWS) const
Build the instrument/detector setup in workspace.
double translateToMeters(const std::string &radiusUnits, const double &enteredRadius) const
Translate the entered radius into meters.
Mantid::API::MatrixWorkspace_sptr m_inWS
Input workspace.
void exec() override
Executes the algorithm.
std::unique_ptr< Mantid::API::Progress > m_progress
Progress reporter.
void findNeighboursRectangular()
Fill the neighbours list given the AdjX AdjY parameters and an instrument with rectangular detectors.
void execEvent(Mantid::DataObjects::EventWorkspace_sptr &ws)
Execute the algorithm for a EventWorkspace input.
int m_nNeighbours
Number of neighbours.
bool m_preserveEvents
PreserveEvents.
void reserve(size_t num) override
Reserve a certain number of entries in event list of the specified eventType.
An OffsetsWorkspace is a specialized Workspace2D where the Y value at each pixel is the offset to be ...
A simple structure that defines an axis-aligned cuboid shaped bounding box for a geometrical object.
Kernel::V3D width() const
Returns the width of the box.
Exception for when an item is not found in a collection.
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 setPropertyGroup(const std::string &name, const std::string &group)
Set the group for a given property.
void debug(const std::string &msg)
Logs at debug level.
void information(const std::string &msg)
Logs at information level.
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...
double norm() const noexcept
std::shared_ptr< MatrixWorkspace > MatrixWorkspace_sptr
shared pointer to the matrix workspace base class
std::map< specnum_t, Mantid::Kernel::V3D > SpectraDistanceMap
std::shared_ptr< EventWorkspace > EventWorkspace_sptr
shared pointer to the EventWorkspace class
std::unique_ptr< T > create(const P &parent, const IndexArg &indexArg, const HistArg &histArg)
This is the create() method that all the other create() methods call.
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::unordered_map< specnum_t, size_t > spec2index_map
Map with key = spectrum number, value = workspace index.
std::unordered_map< detid_t, size_t > detid2index_map
Map with key = detector ID, value = workspace index.
int32_t specnum_t
Typedef for a spectrum Number.
@ Input
An input workspace.
@ Output
An output workspace.