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");
300 std::vector<bool> used(
m_inWS->getNumberHistograms(),
false);
301 const auto &componentInfo =
m_inWS->componentInfo();
302 const auto &detectorInfo =
m_inWS->detectorInfo();
303 for (
size_t wi = 0; wi <
m_inWS->getNumberHistograms(); wi++) {
310 const auto &dets =
m_inWS->getSpectrum(wi).getDetectorIDs();
311 const auto index = detectorInfo.indexOf(*dets.begin());
312 if (detectorInfo.isMonitor(
index))
314 if (detectorInfo.isMasked(
index)) {
322 if (componentInfo.hasParent(
index)) {
323 parent = componentInfo.parent(
index);
324 if (componentInfo.hasParent(parent))
325 grandparent = componentInfo.parent(parent);
343 neighbSpectra[inSpec] =
V3D(0.0, 0.0, 0.0);
346 double totalWeight = 0;
348 std::vector<weightedNeighbour> neighbours;
351 for (
const auto &specDistance : neighbSpectra) {
355 double weight =
m_weightedSum->weightAt(specDistance.second);
359 auto mapIt = spec2index.find(spec);
360 if (mapIt != spec2index.end()) {
361 size_t neighWI = mapIt->second;
364 const std::set<detid_t> &dets =
m_inWS->getSpectrum(neighWI).getDetectorIDs();
365 const auto neighbParent = componentInfo.parent(detectorInfo.indexOf(*dets.begin()));
366 const auto neighbGParent = componentInfo.parent(neighbParent);
367 if (noNeigh >= sum || componentInfo.name(neighbParent) != componentInfo.name(parent) ||
368 componentInfo.name(neighbGParent) != componentInfo.name(grandparent) || used[neighWI])
371 used[neighWI] =
true;
373 neighbours.emplace_back(neighWI, weight);
374 totalWeight += weight;
381 for (
auto &neighbour : neighbours)
382 neighbour.second /= totalWeight;
400 if (strategyName ==
"Flat") {
402 }
else if (strategyName ==
"Linear") {
404 }
else if (strategyName ==
"Parabolic") {
405 m_weightedSum = std::make_unique<ParabolicWeighting>(cutOff);
406 }
else if (strategyName ==
"Gaussian") {
419 double translatedRadius = 0;
420 if (radiusUnits ==
"Meters") {
422 translatedRadius = enteredRadius;
423 }
else if (radiusUnits ==
"NumberOfPixels") {
425 const auto &firstDet =
m_inWS->spectrumInfo().detector(0);
428 firstDet.getBoundingBox(bbox);
431 translatedRadius = bbox.
width().
norm() * enteredRadius;
433 const std::string message =
"SmoothNeighbours::translateToMeters, Unknown Unit: " + radiusUnits;
434 throw std::invalid_argument(message);
436 return translatedRadius;
460 m_progress = std::make_unique<Progress>(
this, 0.0, 0.2,
m_inWS->getNumberHistograms());
463 CallOnExit resetInWSOnExit([
this]() {
m_inWS.reset(); });
464 CallOnExit resetNeighboursOnExit([
this]() {
475 auto wsEvent = std::dynamic_pointer_cast<EventWorkspace>(
m_inWS);
490 const size_t numberOfSpectra =
m_outWI;
492 const size_t YLength =
m_inWS->blocksize();
496 if (std::dynamic_pointer_cast<OffsetsWorkspace>(
m_inWS)) {
500 outWS = std::dynamic_pointer_cast<MatrixWorkspace>(
509 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
512 auto &outSpec = outWS->getSpectrum(outWIi);
515 auto &outY = outSpec.mutableY();
517 auto &outE = outSpec.mutableE();
519 auto &outX = outSpec.mutableX();
522 std::vector<weightedNeighbour> &neighbours =
m_neighbours[outWIi];
523 std::vector<weightedNeighbour>::iterator it;
524 for (it = neighbours.begin(); it != neighbours.end(); ++it) {
525 size_t inWI = it->first;
526 double weight = it->second;
527 double weightSquared = weight * weight;
529 const auto &inSpec =
m_inWS->getSpectrum(inWI);
530 const auto &inY = inSpec.y();
531 const auto &inE = inSpec.e();
532 const auto &inX = inSpec.x();
534 for (
size_t i = 0; i < YLength; i++) {
536 outY[i] += inY[i] * weight;
539 double errorSquared = inE[i];
540 errorSquared *= errorSquared;
541 errorSquared *= weightSquared;
542 outE[i] += errorSquared;
546 if (
m_inWS->isHistogramData()) {
547 outX[YLength] = inX[YLength];
552 for (
size_t i = 0; i < YLength; i++)
553 outE[i] = sqrt(outE[i]);
573 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
581 const auto &inSpec =
m_inWS->getSpectrum(neighbor.first);
582 outSpec.addDetectorIDs(inSpec.getDetectorIDs());
591 const size_t numberOfSpectra =
m_inWS->getNumberHistograms();
593 const size_t YLength =
m_inWS->blocksize();
597 if (std::dynamic_pointer_cast<OffsetsWorkspace>(
m_inWS)) {
599 outws2 = std::make_shared<OffsetsWorkspace>(
m_inWS->getInstrument());
601 outws2 = std::dynamic_pointer_cast<MatrixWorkspace>(
608 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
609 const auto &inSpec =
m_inWS->getSpectrum(outWIi);
610 auto &outSpec2 = outws2->getSpectrum(outWIi);
611 outSpec2.mutableX() = inSpec.x();
612 outSpec2.addDetectorIDs(inSpec.getDetectorIDs());
614 outSpec2.clearData();
618 const size_t numberOfSpectra2 = outWS->getNumberHistograms();
619 for (
int outWIi = 0; outWIi < int(numberOfSpectra2); outWIi++) {
623 outws2->setHistogram(neighbor.first, outWS->histogram(outWIi));
636 const size_t numberOfSpectra =
m_outWI;
637 const auto YLength =
static_cast<int>(
m_inWS->blocksize());
641 outWS = std::dynamic_pointer_cast<EventWorkspace>(
648 this->
setProperty(
"OutputWorkspace", std::dynamic_pointer_cast<MatrixWorkspace>(outWS));
651 std::vector<size_t> outputEvents(numberOfSpectra, 0);
652 for (
int i = 0; i < int(numberOfSpectra); i++) {
653 const std::vector<weightedNeighbour> &neighbours =
m_neighbours[i];
654 for (
const auto &neighbour : neighbours) {
655 size_t inWI = neighbour.first;
656 outputEvents[i] += ws->getSpectrum(inWI).getNumberEvents();
662 for (
int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
666 EventList &outEL = outWS->getSpectrum(outWIi);
667 outEL.
reserve(outputEvents[outWIi]);
670 std::vector<weightedNeighbour> &neighbours =
m_neighbours[outWIi];
671 std::vector<weightedNeighbour>::iterator it;
672 for (it = neighbours.begin(); it != neighbours.end(); ++it) {
673 size_t inWI = it->first;
675 double weight = it->second;
690 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.
static constexpr size_t invalidIndex
Returned by indexOfOrInvalid() for a component ID that is not part of this instrument.
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.