Mantid
Loading...
Searching...
No Matches
SmoothNeighbours.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 +
22
23using namespace Mantid::Kernel;
24using namespace Mantid::Geometry;
25using namespace Mantid::API;
26using namespace Mantid::DataObjects;
27
28using VecProperties = std::vector<Mantid::Kernel::Property *>;
30
31namespace Mantid::Algorithms {
32
33// Register the class into the algorithm factory
34DECLARE_ALGORITHM(SmoothNeighbours)
35
36namespace {
37// Used in custom GUI. Make sure you change them in SmoothNeighboursDialog.cpp
38// as well.
39const std::string NON_UNIFORM_GROUP = "NonUniform Detectors";
40const std::string RECTANGULAR_GROUP = "Rectangular Detectors";
41const std::string INPUT_WORKSPACE = "InputWorkspace";
42
45struct CallOnExit {
46 using Callable = std::function<void()>;
47 CallOnExit(Callable &&callable) noexcept : m_callable(std::move(callable)) {}
48 ~CallOnExit() {
49 try {
50 m_callable();
51 } catch (...) {
52 };
53 }
54
55private:
56 Callable m_callable;
57};
58} // namespace
59
60SmoothNeighbours::SmoothNeighbours() : API::Algorithm(), m_weightedSum(std::make_unique<NullWeighting>()) {}
61
63 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>(INPUT_WORKSPACE, "", Direction::Input,
64 std::make_shared<InstrumentValidator>()),
65 "The workspace containing the spectra to be averaged.");
66 declareProperty(std::make_unique<WorkspaceProperty<MatrixWorkspace>>("OutputWorkspace", "", Direction::Output),
67 "The name of the workspace to be created as the output of "
68 "the algorithm.");
69
70 // Unsigned double
71 auto mustBePositiveDouble = std::make_shared<BoundedValidator<double>>();
72 mustBePositiveDouble->setLower(0.0);
73
74 // Unsigned int.
75 auto mustBePositive = std::make_shared<BoundedValidator<int>>();
76 mustBePositive->setLower(0);
77
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");
86
87 declareProperty("Sigma", 0.5, mustBePositiveDouble, "Sigma value for gaussian weighting schemes. Defaults to 0.5. ");
88 setPropertySettings("Sigma", std::make_unique<EnabledWhenProperty>("WeightedSum", IS_EQUAL_TO, "Gaussian"));
89
90 declareProperty("IgnoreMaskedDetectors", true, "If true, do not consider masked detectors in the NN search.");
91
92 declareProperty("PreserveEvents", true,
93 "If the InputWorkspace is an "
94 "EventWorkspace, this will preserve "
95 "the full event list (warning: this "
96 "will use much more memory!).");
97
98 // -- Rectangular properties --
99
100 declareProperty("AdjX", 1, mustBePositive,
101 "The number of X (horizontal) adjacent pixels to average together. "
102 "Only for instruments with RectangularDetectors. ");
103
104 declareProperty("AdjY", 1, mustBePositive,
105 "The number of Y (vertical) adjacent pixels to average together. "
106 "Only for instruments with RectangularDetectors. ");
107
108 declareProperty("SumPixelsX", 1, mustBePositive,
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.");
112
113 declareProperty("SumPixelsY", 1, mustBePositive,
114 "The total number of Y (vertical) adjacent pixels to sum together. "
115 "Only for instruments with RectangularDetectors. AdjY will be ignored if "
116 "SumPixelsY > 1");
117
118 declareProperty("ZeroEdgePixels", 0, mustBePositive,
119 "The number of pixels to zero at edges. "
120 "Only for instruments with RectangularDetectors. ");
121
122 setPropertyGroup("AdjX", RECTANGULAR_GROUP);
123 setPropertyGroup("AdjY", RECTANGULAR_GROUP);
124 setPropertyGroup("SumPixelsX", RECTANGULAR_GROUP);
125 setPropertyGroup("SumPixelsY", RECTANGULAR_GROUP);
126 setPropertyGroup("ZeroEdgePixels", RECTANGULAR_GROUP);
127
128 // -- Non-uniform properties --
129
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.");
135
136 declareProperty("Radius", 0.0, mustBePositiveDouble,
137 "The radius cut-off around a pixel to look for nearest neighbours to "
138 "average. \n"
139 "This radius cut-off is applied to a set of nearest neighbours whose "
140 "number is "
141 "defined in the NumberOfNeighbours property. See below for more details. "
142 "\n"
143 "If 0, will use the AdjX and AdjY parameters for rectangular detectors "
144 "instead.");
145
146 declareProperty("NumberOfNeighbours", 8, mustBePositive,
147 "Number of nearest neighbouring pixels.\n"
148 "The default is 8.");
149
150 declareProperty("SumNumberOfNeighbours", 1,
151 "Sum nearest neighbouring pixels with same parent.\n"
152 "Number of pixels will be reduced. The default is false.");
153
154 declareProperty("ExpandSumAllPixels", false,
155 "OuputWorkspace will have same number of pixels as "
156 "InputWorkspace using SumPixelsX and SumPixelsY. Individual "
157 "pixels will have averages.");
158
159 setPropertyGroup("RadiusUnits", NON_UNIFORM_GROUP);
160 setPropertyGroup("Radius", NON_UNIFORM_GROUP);
161 setPropertyGroup("NumberOfNeighbours", NON_UNIFORM_GROUP);
162 setPropertyGroup("SumNumberOfNeighbours", NON_UNIFORM_GROUP);
163}
164
165//--------------------------------------------------------------------------------------------
170 g_log.debug("SmoothNeighbours processing assuming rectangular detectors.");
171
172 m_progress->resetNumSteps(m_inWS->getNumberHistograms(), 0.2, 0.5);
173
174 const auto &componentInfo = m_inWS->componentInfo();
175 const auto &detectorInfo = m_inWS->detectorInfo();
176
177 // To get the workspace index from the detector ID
178 const detid2index_map pixel_to_wi = m_inWS->getDetectorIDToWorkspaceIndexMap(true, true);
179
180 // Build a list of Rectangular/Grid Detectors (as component indices)
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);
185 }
186 }
187
188 if (detList.empty()) {
189 // Not rectangular so use Nearest Neighbours
190 m_radius = translateToMeters("NumberOfPixels", std::max(m_adjX, m_adjY));
194 return;
195 }
196
197 Progress prog(this, 0.0, 1.0, detList.size());
198
199 // Resize the vector we are setting
200 m_neighbours.resize(m_inWS->getNumberHistograms());
201 int startX = -m_adjX;
202 int startY = -m_adjY;
203 int endX = m_adjX;
204 int endY = m_adjY;
205 const int sumX = getProperty("SumPixelsX");
206 const int sumY = getProperty("SumPixelsY");
207 bool sum = sumX * sumY > 1;
208 if (sum) {
209 startX = 0;
210 startY = 0;
211 endX = sumX - 1;
212 endY = sumY - 1;
213 }
214
215 m_outWI = 0;
216 // Build a map to sort by the detectorID
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);
221
222 // To sort in descending order
223 if (sum)
224 stable_sort(idToIndexMap.begin(), idToIndexMap.end());
225
226 // Loop through the RectangularDetector's we listed before.
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;
234 // Neighbours and weights
235 std::vector<weightedNeighbour> neighbours;
236
237 for (int ix = startX; ix <= endX; ix++)
238 for (int iy = startY; iy <= endY; iy++) {
239 // Weights for corners=1; higher for center and adjacent pixels
240 double smweight = m_weightedSum->weightAt(m_adjX, ix, m_adjY, iy);
241
242 // Find the pixel ID at that XY position on the rectangular
243 // detector
244 if (j + ix >= grid.nX - m_edge || j + ix < m_edge)
245 continue;
246 if (k + iy >= grid.nY - m_edge || k + iy < m_edge)
247 continue;
248 int pixelID = detectorInfo.detid(componentInfo.detectorIndexAtXYZ(bankIndex, j + ix, k + iy, 0));
249
250 // Find the corresponding workspace index, if any
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);
255 // Count the total weight
256 totalWeight += smweight;
257 }
258 }
259
260 // Adjust the weights of each neighbour to normalize to unity
261 if (!sum || m_expandSumAllPixels)
262 for (auto &neighbour : neighbours)
263 neighbour.second /= totalWeight;
264
265 // Save the list of neighbours for this output workspace index.
266 m_neighbours[m_outWI] = neighbours;
267 m_outWI++;
268
269 m_progress->report("Finding Neighbours");
270 }
271 }
272 prog.report(det_name);
273 }
274}
275
276//--------------------------------------------------------------------------------------------
280 g_log.debug("SmoothNeighbours processing NOT assuming rectangular detectors.");
281
282 m_progress->resetNumSteps(m_inWS->getNumberHistograms(), 0.2, 0.5);
283 this->progress(0.2, "Building Neighbour Map");
284
285 const spec2index_map spec2index = m_inWS->getSpectrumToWorkspaceIndexMap();
286
287 // Resize the vector we are setting
288 m_neighbours.resize(m_inWS->getNumberHistograms());
289
290 bool ignoreMaskedDetectors = getProperty("IgnoreMaskedDetectors");
291 WorkspaceNearestNeighbourInfo neighbourInfo(*m_inWS, ignoreMaskedDetectors, m_nNeighbours);
292
293 // Cull by radius
294 RadiusFilter radiusFilter(m_radius);
295
296 // Go through every input workspace pixel
297 m_outWI = 0;
298 int sum = getProperty("SumNumberOfNeighbours");
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++) {
303 if (sum > 1)
304 if (used[wi])
305 continue;
306 // We want to skip monitors
307 try {
308 // Get the list of detectors in this pixel
309 const auto &dets = m_inWS->getSpectrum(wi).getDetectorIDs();
310 const auto index = detectorInfo.indexOf(*dets.begin());
311 if (detectorInfo.isMonitor(index))
312 continue; // skip monitor
313 if (detectorInfo.isMasked(index)) {
314 // Calibration masks many detectors, but there should be 0s after
315 // smoothing
316 if (sum == 1)
317 m_outWI++;
318 continue; // skip masked detectors
319 }
320 if (sum > 1) {
321 const auto &det = detectorInfo.detector(index);
322 parent = det.getParent();
323 if (parent)
324 grandparent = parent->getParent();
325 }
327 continue; // skip missing detector
328 }
329
330 specnum_t inSpec = m_inWS->getSpectrum(wi).getSpectrumNo();
331
332 // Step one - Get the number of specified neighbours
333 SpectraDistanceMap insideGrid = neighbourInfo.getNeighboursExact(inSpec);
334
335 // Step two - Filter the results by the radius cut off.
336 SpectraDistanceMap neighbSpectra = radiusFilter.apply(insideGrid);
337
338 // Force the central pixel to always be there
339 // There seems to be a bug in nearestNeighbours, returns distance != 0.0 for
340 // the central pixel. So we force distance = 0
341 neighbSpectra[inSpec] = V3D(0.0, 0.0, 0.0);
342
343 // Neighbours and weights list
344 double totalWeight = 0;
345 int noNeigh = 0;
346 std::vector<weightedNeighbour> neighbours;
347
348 // Convert from spectrum numbers to workspace indices
349 for (const auto &specDistance : neighbSpectra) {
350 specnum_t spec = specDistance.first;
351
352 // Use the weighting strategy to calculate the weight.
353 double weight = m_weightedSum->weightAt(specDistance.second);
354
355 if (weight > 0) {
356 // Find the corresponding workspace index
357 auto mapIt = spec2index.find(spec);
358 if (mapIt != spec2index.end()) {
359 size_t neighWI = mapIt->second;
360 if (sum > 1) {
361 // Get the list of detectors in this pixel
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])
368 continue;
369 noNeigh++;
370 used[neighWI] = true;
371 }
372 neighbours.emplace_back(neighWI, weight);
373 totalWeight += weight;
374 }
375 }
376 }
377
378 // Adjust the weights of each neighbour to normalize to unity
379 if (sum == 1)
380 for (auto &neighbour : neighbours)
381 neighbour.second /= totalWeight;
382
383 // Save the list of neighbours for this output workspace index.
384 m_neighbours[m_outWI] = neighbours;
385 m_outWI++;
386
387 m_progress->report("Finding Neighbours");
388 } // each workspace index
389}
390
398void SmoothNeighbours::setWeightingStrategy(const std::string &strategyName, double &cutOff) {
399 if (strategyName == "Flat") {
400 m_weightedSum = std::make_unique<FlatWeighting>();
401 } else if (strategyName == "Linear") {
402 m_weightedSum = std::make_unique<LinearWeighting>(cutOff);
403 } else if (strategyName == "Parabolic") {
404 m_weightedSum = std::make_unique<ParabolicWeighting>(cutOff);
405 } else if (strategyName == "Gaussian") {
406 m_weightedSum = std::make_unique<GaussianWeightingnD>(cutOff, getProperty("Sigma"));
407 }
408 g_log.information() << "Smoothing with " << strategyName << " Weighting\n";
409}
410
417double SmoothNeighbours::translateToMeters(const std::string &radiusUnits, const double &enteredRadius) const {
418 double translatedRadius = 0;
419 if (radiusUnits == "Meters") {
420 // Nothing more to do.
421 translatedRadius = enteredRadius;
422 } else if (radiusUnits == "NumberOfPixels") {
423 // Get the first idetector from the workspace index 0.
424 const auto &firstDet = m_inWS->spectrumInfo().detector(0);
425 // Find the bounding box of that detector
426 BoundingBox bbox;
427 firstDet.getBoundingBox(bbox);
428 // Multiply (meters/pixels) by number of pixels, note that enteredRadius
429 // takes on meaning of the number of pixels.
430 translatedRadius = bbox.width().norm() * enteredRadius;
431 } else {
432 const std::string message = "SmoothNeighbours::translateToMeters, Unknown Unit: " + radiusUnits;
433 throw std::invalid_argument(message);
434 }
435 return translatedRadius;
436}
437
442 m_inWS = getProperty("InputWorkspace");
443
444 m_preserveEvents = getProperty("PreserveEvents");
445 m_expandSumAllPixels = getProperty("ExpandSumAllPixels");
446
447 // Use the unit type to translate the entered radius into meters.
448 m_radius = translateToMeters(getProperty("RadiusUnits"), getProperty("Radius"));
449
451
452 m_adjX = getProperty("AdjX");
453 m_adjY = getProperty("AdjY");
454 m_edge = getProperty("ZeroEdgePixels");
455
456 m_nNeighbours = getProperty("NumberOfNeighbours");
457
458 // Progress reporting, first for the sorting
459 m_progress = std::make_unique<Progress>(this, 0.0, 0.2, m_inWS->getNumberHistograms());
460
461 // Clean up when we are done
462 CallOnExit resetInWSOnExit([this]() { m_inWS.reset(); });
463 CallOnExit resetNeighboursOnExit([this]() {
464 m_neighbours.clear();
465 m_neighbours.shrink_to_fit();
466 });
467
468 // Run the appropriate method depending on the type of the instrument
469 if (m_inWS->getInstrument()->containsRectDetectors() == Instrument::ContainsState::Full)
471 else
473
474 auto wsEvent = std::dynamic_pointer_cast<EventWorkspace>(m_inWS);
475 if (wsEvent)
476 wsEvent->sortAll(TOF_SORT, m_progress.get());
477 if (wsEvent && m_preserveEvents)
478 this->execEvent(wsEvent);
479 else
480 this->execWorkspace2D();
481}
482
483//--------------------------------------------------------------------------------------------
486 m_progress->resetNumSteps(m_inWS->getNumberHistograms(), 0.5, 1.0);
487
488 // Get some stuff from the input workspace
489 const size_t numberOfSpectra = m_outWI;
490
491 const size_t YLength = m_inWS->blocksize();
492
494 // Make a brand new Workspace2D
495 if (std::dynamic_pointer_cast<OffsetsWorkspace>(m_inWS)) {
496 g_log.information() << "Creating new OffsetsWorkspace\n";
497 outWS = MatrixWorkspace_sptr(new OffsetsWorkspace(m_inWS->getInstrument()));
498 } else {
499 outWS = std::dynamic_pointer_cast<MatrixWorkspace>(
500 API::WorkspaceFactory::Instance().create("Workspace2D", numberOfSpectra, YLength + 1, YLength));
501 }
502 this->setProperty("OutputWorkspace", outWS);
503
504 setupNewInstrument(*outWS);
505
506 // Go through all the output workspace
508 for (int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
510
511 auto &outSpec = outWS->getSpectrum(outWIi);
512 // Reset the Y and E vectors
513 outSpec.clearData();
514 auto &outY = outSpec.mutableY();
515 // We will temporarily carry the squared error
516 auto &outE = outSpec.mutableE();
517 // tmp to carry the X Data.
518 auto &outX = outSpec.mutableX();
519
520 // Which are the neighbours?
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;
527
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();
532
533 for (size_t i = 0; i < YLength; i++) {
534 // Add the weighted signal
535 outY[i] += inY[i] * weight;
536 // Square the error, scale by weight (which you have to square too),
537 // then add in quadrature
538 double errorSquared = inE[i];
539 errorSquared *= errorSquared;
540 errorSquared *= weightSquared;
541 outE[i] += errorSquared;
542 // Copy the X values as well
543 outX[i] = inX[i];
544 }
545 if (m_inWS->isHistogramData()) {
546 outX[YLength] = inX[YLength];
547 }
548 } //(each neighbour)
549
550 // Now un-square the error, since we summed it in quadrature
551 for (size_t i = 0; i < YLength; i++)
552 outE[i] = sqrt(outE[i]);
553
554 m_progress->report("Summing");
556 }
559 spreadPixels(outWS);
560}
561
562//--------------------------------------------------------------------------------------------
566 // Copy geometry over.
567 API::WorkspaceFactory::Instance().initializeFromParent(*m_inWS, outWS, false);
568
569 // Go through all the output workspace
570 size_t numberOfSpectra = outWS.getNumberHistograms();
571
572 for (int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
573 auto &outSpec = outWS.getSpectrum(outWIi);
574
575 // Reset detectors
576 outSpec.clearDetectorIDs();
577
578 // Which are the neighbours?
579 for (const auto &neighbor : m_neighbours[outWIi]) {
580 const auto &inSpec = m_inWS->getSpectrum(neighbor.first);
581 outSpec.addDetectorIDs(inSpec.getDetectorIDs());
582 }
583 }
584}
585//--------------------------------------------------------------------------------------------
589 // Get some stuff from the input workspace
590 const size_t numberOfSpectra = m_inWS->getNumberHistograms();
591
592 const size_t YLength = m_inWS->blocksize();
593
595 // Make a brand new Workspace2D
596 if (std::dynamic_pointer_cast<OffsetsWorkspace>(m_inWS)) {
597 g_log.information() << "Creating new OffsetsWorkspace\n";
598 outws2 = std::make_shared<OffsetsWorkspace>(m_inWS->getInstrument());
599 } else {
600 outws2 = std::dynamic_pointer_cast<MatrixWorkspace>(
601 API::WorkspaceFactory::Instance().create("Workspace2D", numberOfSpectra, YLength + 1, YLength));
602 }
603
604 // Copy geometry over.
605 API::WorkspaceFactory::Instance().initializeFromParent(*m_inWS, *outws2, false);
606 // Go through all the input workspace
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());
612 // Zero the Y and E vectors
613 outSpec2.clearData();
614 }
615
616 // Go through all the output workspace
617 const size_t numberOfSpectra2 = outWS->getNumberHistograms();
618 for (int outWIi = 0; outWIi < int(numberOfSpectra2); outWIi++) {
619
620 // Which are the neighbours?
621 for (const auto &neighbor : m_neighbours[outWIi]) {
622 outws2->setHistogram(neighbor.first, outWS->histogram(outWIi));
623 }
624 }
625 this->setProperty("OutputWorkspace", outws2);
626}
627//--------------------------------------------------------------------------------------------
632 m_progress->resetNumSteps(m_inWS->getNumberHistograms(), 0.5, 1.0);
633
634 // Get some stuff from the input workspace
635 const size_t numberOfSpectra = m_outWI;
636 const auto YLength = static_cast<int>(m_inWS->blocksize());
637
639 // Make a brand new EventWorkspace
640 outWS = std::dynamic_pointer_cast<EventWorkspace>(
641 API::WorkspaceFactory::Instance().create("EventWorkspace", numberOfSpectra, YLength + 1, YLength));
642 // Copy geometry over.
643 API::WorkspaceFactory::Instance().initializeFromParent(*ws, *outWS, false);
644 // Ensure thread-safety
645 outWS->sortAll(TOF_SORT, nullptr);
646
647 this->setProperty("OutputWorkspace", std::dynamic_pointer_cast<MatrixWorkspace>(outWS));
648
649 // Calculate total number of events for each EventList
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();
656 }
657 }
658
659 // Go through all the output workspace
661 for (int outWIi = 0; outWIi < int(numberOfSpectra); outWIi++) {
663
664 // Create the output event list (empty)
665 EventList &outEL = outWS->getSpectrum(outWIi);
666 outEL.reserve(outputEvents[outWIi]);
667
668 // Which are the neighbours?
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;
673 // if(sum)outEL.copyInfoFrom(*ws->getSpectrum(inWI));
674 double weight = it->second;
675 // Copy the event list
676 EventList tmpEL = ws->getSpectrum(inWI);
677 // Scale it
678 tmpEL *= weight;
679 // Add it
680 outEL += tmpEL;
681 }
682
683 m_progress->report("Summing");
685 }
687
688 // Give the 0-th X bins to all the output spectra.
689 outWS->setAllX(m_inWS->binEdges(0));
691 spreadPixels(outWS);
692}
693
694} // namespace Mantid::Algorithms
#define DECLARE_ALGORITHM(classname)
Definition Algorithm.h:542
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
Callable m_callable
Base class from which all concrete algorithm classes should be derived.
Definition Algorithm.h:76
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.
Kernel::Logger & g_log
Definition Algorithm.h:423
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.
Definition Progress.h:25
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.
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.
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.
A class for holding :
Definition EventList.h:58
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.
Definition BoundingBox.h:33
Kernel::V3D width() const
Returns the width of the box.
Definition BoundingBox.h:97
Exception for when an item is not found in a collection.
Definition Exception.h:145
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.
Definition Logger.cpp:145
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...
Class for 3D vectors.
Definition V3D.h:34
double norm() const noexcept
Definition V3D.h:269
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.
Definition IDTypes.h:14
STL namespace.
@ Input
An input workspace.
Definition Property.h:53
@ Output
An output workspace.
Definition Property.h:54