34#include <boost/lexical_cast.hpp>
51static bool abs_compare(
double a,
double b) {
return (std::fabs(a) < std::fabs(b)); }
74 return "Bins multidimensional data and calculate the normalization on the "
84 "An input MDEventWorkspace. Must be in Q_sample frame.");
88 "An (optional) input MDEventWorkspace for background. Must be in Q_lab frame.");
91 declareProperty(
"RLU",
true,
"Use reciprocal lattice units. If false, use Q_sample");
94 auto mustBe3D = std::make_shared<Kernel::ArrayLengthValidator<double>>(3);
95 std::vector<double> Q0(3, 0.), Q1(3, 0), Q2(3, 0);
101 "The first Q projection axis - Default is (1,0,0)");
106 "The second Q projection axis - Default is (0,1,0)");
111 "The thirdtCalculateCover Q projection axis - Default is (0,0,1)");
116 auto fluxValidator = std::make_shared<CompositeValidator>();
119 auto solidAngleValidator = fluxValidator->
clone();
122 "An input workspace containing integrated vanadium "
123 "(a measure of the solid angle).\n"
124 "Mandatory for diffraction, optional for direct geometry inelastic");
127 "An input workspace containing momentum dependent flux.\n"
128 "Mandatory for diffraction. No effect on direct geometry inelastic");
135 "An (optional) input MDEventWorkspace containing a pre-computed normalization "
136 "for monochromatic single crystal diffraction (e.g. produced by "
137 "ConvertHFIRSCDtoMDE). Must be in Q_sample frame with the same number of "
138 "dimensions as InputWorkspace. Cannot be used together with "
139 "SolidAngleWorkspace/FluxWorkspace or BackgroundWorkspace.");
143 for (std::size_t i = 0; i < 6; i++) {
146 std::string defaultName =
"";
152 auto atMost3 = std::make_shared<ArrayLengthValidator<double>>(0, 3);
153 std::vector<double> temp;
156 "- Leave blank for complete integration\n" +
157 "- One value is interpreted as step\n"
158 "- Two values are interpreted integration interval\n" +
159 "- Three values are interpreted as min, step, max");
166 "If specified the symmetry will be applied, "
167 "can be space group name, point group name, or list "
168 "individual symmetries.");
173 "An (optional) input MDHistoWorkspace used to accumulate data from "
174 "multiple MDEventWorkspaces. If unspecified a blank "
175 "MDHistoWorkspace will be created.");
178 "An (optional) input MDHistoWorkspace used to accumulate normalization "
179 "from multiple MDEventWorkspaces. If unspecified a blank "
180 "MDHistoWorkspace will be created.");
185 "An (optional) input MDHistoWorkspace used to accumulate background from "
186 "multiple background MDEventWorkspaces. If unspecified but "
187 "BackgroundWorkspace is specified, a blank "
188 "MDHistoWorkspace will be created.");
191 "An (optional) input MDHistoWorkspace used to accumulate background normalization "
192 "from multiple background MDEventWorkspaces. If unspecified but "
193 "BackgroundWorkspace is specified, a blank "
194 "MDHistoWorkspace will be created.");
197 setPropertyGroup(
"TemporaryNormalizationWorkspace",
"Temporary workspaces");
198 setPropertyGroup(
"TemporaryBackgroundDataWorkspace",
"Temporary workspaces");
199 setPropertyGroup(
"TemporaryBackgroundNormalizationWorkspace",
"Temporary workspaces");
202 "A name for the normalized output MDHistoWorkspace.");
205 "A name for the output data MDHistoWorkspace.");
207 "A name for the output normalization MDHistoWorkspace.");
210 "A name for the optional output background data MDHistoWorkspace.");
213 "A name for the optional output background normalization MDHistoWorkspace.");
215 m_progress = std::make_unique<API::Progress>(
this, 0, 1, 1);
221 std::map<std::string, std::string> errorMessage;
225 if (inputWS->getNumDims() < 3) {
226 errorMessage.emplace(
"InputWorkspace",
"The input workspace must be at least 3D");
228 for (
size_t i = 0; i < 3; i++) {
230 errorMessage.emplace(
"InputWorkspace",
"The input workspace must be in Q_sample");
238 if (bkgdWS->getNumDims() < 3) {
240 errorMessage.emplace(
"BackgroundWorkspace",
"The input background workspace must be at least 3D");
243 for (
size_t i = 0; i < 3; i++) {
245 errorMessage.emplace(
"BackgroundWorkspace",
"The input backgound workspace must be in Q_lab");
250 if (inputWS->getNumDims() > 3) {
251 if (bkgdWS->getNumDims() <= 3) {
252 errorMessage.emplace(
"BackgroundWorkspace",
"The input background workspace must have at 4 dimensions when "
253 "input workspace has more than 4 dimensions (inelastic case).");
254 }
else if (bkgdWS->getDimension(3)->getName() != inputWS->getDimension(3)->getName()) {
255 errorMessage.emplace(
"BackgroundWorkspace",
"The input background workspace 4th dimension must be DeltaE "
256 "for inelastic case.");
263 bool diffraction =
true;
264 if ((inputWS->getNumDims() > 3) && (inputWS->getDimension(3)->getName() ==
"DeltaE")) {
271 bool monochromatic = bool(monoNormWS);
277 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace can only be used for "
278 "diffraction (InputWorkspace must not have a DeltaE "
281 if (solidAngleWS || fluxWS) {
282 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace cannot be used together "
283 "with SolidAngleWorkspace/FluxWorkspace");
286 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace cannot currently be used "
287 "together with BackgroundWorkspace");
289 if (monoNormWS->getNumDims() < 3) {
290 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace must be at least 3D");
292 if (monoNormWS->getNumDims() != inputWS->getNumDims()) {
293 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace must have the same "
294 "number of dimensions as InputWorkspace");
296 for (
size_t i = 0; i < 3; i++) {
298 errorMessage.emplace(
"MonoSCDNormalizationWorkspace",
"MonoSCDNormalizationWorkspace must be in Q_sample");
302 }
else if (diffraction) {
303 if (solidAngleWS ==
nullptr) {
304 errorMessage.emplace(
"SolidAngleWorkspace",
"SolidAngleWorkspace is required for diffraction");
306 if (fluxWS ==
nullptr) {
307 errorMessage.emplace(
"FluxWorkspace",
"FluxWorkspace is required for diffraction");
312 size_t nExperimentInfos = inputWS->getNumExperimentInfo();
313 if (nExperimentInfos == 0) {
314 errorMessage.emplace(
"InputWorkspace",
"There must be at least one experiment info");
316 for (
size_t iExpInfo = 0; iExpInfo < nExperimentInfos; iExpInfo++) {
317 auto ¤tExptInfo = *(inputWS->getExperimentInfo(
static_cast<uint16_t
>(iExpInfo)));
319 if (!currentExptInfo.run().hasProperty(
"wavelength")) {
320 errorMessage.emplace(
"InputWorkspace",
"Missing wavelength log. InputWorkspace does not look like it was "
321 "produced by ConvertHFIRSCDtoMDE, as expected when "
322 "MonoSCDNormalizationWorkspace is provided");
325 if (!currentExptInfo.run().hasProperty(
"MDNorm_low")) {
326 errorMessage.emplace(
"InputWorkspace",
"Missing MDNorm_low log. Please "
327 "use CropWorkspaceForMDNorm "
328 "before converting to MD");
330 if (!currentExptInfo.run().hasProperty(
"MDNorm_high")) {
331 errorMessage.emplace(
"InputWorkspace",
"Missing MDNorm_high log. Please use "
332 "CropWorkspaceForMDNorm before converting to MD");
340 std::vector<double> Q0Basis =
getProperty(
"QDimension0");
341 std::vector<double> Q1Basis =
getProperty(
"QDimension1");
342 std::vector<double> Q2Basis =
getProperty(
"QDimension2");
347 errorMessage.emplace(
"QDimension0",
"The projection dimensions are coplanar or zero");
348 errorMessage.emplace(
"QDimension1",
"The projection dimensions are coplanar or zero");
349 errorMessage.emplace(
"QDimension2",
"The projection dimensions are coplanar or zero");
351 if (!inputWS->getExperimentInfo(0)->sample().hasOrientedLattice()) {
352 errorMessage.emplace(
"InputWorkspace",
"There is no oriented lattice "
353 "associated with the input workspace. "
354 "Use SetUB algorithm");
358 std::vector<std::string> originalDimensionNames;
359 for (
size_t i = 3; i < inputWS->getNumDims(); i++) {
360 originalDimensionNames.emplace_back(inputWS->getDimension(i)->getName());
362 originalDimensionNames.emplace_back(
"QDimension0");
363 originalDimensionNames.emplace_back(
"QDimension1");
364 originalDimensionNames.emplace_back(
"QDimension2");
365 std::vector<std::string> selectedDimensions;
366 for (std::size_t i = 0; i < 6; i++) {
370 std::vector<double> binning =
getProperty(binningName);
371 if (!dimName.empty()) {
372 auto it = std::find(originalDimensionNames.begin(), originalDimensionNames.end(), dimName);
373 if (it == originalDimensionNames.end()) {
374 errorMessage.emplace(propName,
"Name '" + dimName +
375 "' is not one of the "
376 "original workspace names or a directional dimension");
379 auto itSel = std::find(selectedDimensions.begin(), selectedDimensions.end(), dimName);
380 if (itSel == selectedDimensions.end()) {
381 selectedDimensions.emplace_back(dimName);
383 errorMessage.emplace(propName,
"Name '" + dimName +
"' was already selected");
387 if (!binning.empty()) {
388 errorMessage.emplace(binningName,
"There should be no binning if the dimension name is empty");
393 if ((std::find(selectedDimensions.begin(), selectedDimensions.end(),
"QDimension0") == selectedDimensions.end()) ||
394 (std::find(selectedDimensions.begin(), selectedDimensions.end(),
"QDimension1") == selectedDimensions.end()) ||
395 (std::find(selectedDimensions.begin(), selectedDimensions.end(),
"QDimension2") == selectedDimensions.end())) {
396 for (std::size_t i = 0; i < 6; i++) {
398 errorMessage.emplace(propName,
"All of QDimension0, QDimension1, QDimension2 must be present");
402 std::string symOps = this->
getProperty(
"SymmetryOperations");
403 if (!symOps.empty()) {
404 bool isSpaceGroup = Geometry::SpaceGroupFactory::Instance().isSubscribed(symOps);
405 bool isPointGroup = Geometry::PointGroupFactory::Instance().isSubscribed(symOps);
406 if (!isSpaceGroup && !isPointGroup) {
408 Geometry::SymmetryOperationFactory::Instance().createSymOps(symOps);
410 errorMessage.emplace(
"SymmetryOperations",
"The input is not a space group, a point group, "
411 "or a list of symmetry operations");
416 std::shared_ptr<IMDHistoWorkspace> tempNormWS = this->
getProperty(
"TemporaryNormalizationWorkspace");
420 if ((tempNormWS && !tempDataWS) || (!tempNormWS && tempDataWS)) {
421 errorMessage.emplace(
"TemporaryDataWorkspace",
"Must provide either no accumulation workspaces or,"
422 "both TemporaryNormalizationWorkspaces and TemporaryDataWorkspace");
425 if (tempNormWS && tempDataWS) {
426 size_t numNormDims = tempNormWS->getNumDims();
427 size_t numDataDims = tempDataWS->getNumDims();
428 if (numNormDims == numDataDims) {
429 for (
size_t i = 0; i < numNormDims; i++) {
430 const auto dim1 = tempNormWS->getDimension(i);
431 const auto dim2 = tempDataWS->getDimension(i);
432 if ((dim1->getMinimum() != dim2->getMinimum()) || (dim1->getMaximum() != dim2->getMaximum()) ||
433 (dim1->getNBins() != dim2->getNBins()) || (dim1->getName() != dim2->getName())) {
434 errorMessage.emplace(
"TemporaryDataWorkspace",
"Binning for TemporaryNormalizationWorkspaces "
435 "and TemporaryDataWorkspace must be the same.");
440 errorMessage.emplace(
"TemporaryDataWorkspace",
"TemporaryNormalizationWorkspace and TemporaryDataWorkspace "
441 "do not have the same number of dimensions");
450 if (tempBkgdDataWS && (!bkgdWS || !tempDataWS || !tempBkgdNormWS)) {
451 errorMessage.emplace(
"TemporaryBackgroundDataWorkspace",
"TemporaryBackgroundDataWorkspace is specified but at "
452 "least one of these is not.");
453 }
else if (tempBkgdNormWS && (!bkgdWS || !tempNormWS || !tempBkgdDataWS)) {
454 errorMessage.emplace(
"TemporaryBackgroundNormalizationWorkspace",
"TemporaryBackgroundNormalizationWorkspace is "
455 "specified but at least one of these is not.");
456 }
else if (bkgdWS && tempDataWS && !tempBkgdDataWS) {
457 errorMessage.emplace(
"TemporaryDataWorkspace",
458 "With Background is specifed and TemporaryDataWorkspace is specifed, "
459 "TemporaryBackgroundDataWorkspace must be specified.");
460 }
else if (tempBkgdDataWS && tempNormWS) {
462 size_t numBkgdDataDims = tempBkgdDataWS->getNumDims();
463 size_t numBkgdNormDims = tempBkgdNormWS->getNumDims();
464 size_t numDataDims = tempDataWS->getNumDims();
465 if (numBkgdDataDims == numBkgdNormDims && numBkgdDataDims == numDataDims) {
467 for (
size_t idim = 0; idim < numBkgdDataDims; ++idim) {
468 const auto dimB = tempBkgdDataWS->getDimension(idim);
469 const auto dimN = tempBkgdNormWS->getDimension(idim);
470 const auto dimD = tempDataWS->getDimension(idim);
471 if ((dimB->getMinimum() != dimN->getMinimum()) || (dimB->getMinimum() != dimD->getMinimum()) ||
472 (dimB->getMaximum() != dimN->getMaximum()) || (dimB->getMaximum() != dimD->getMaximum()) ||
473 (dimB->getNBins() != dimN->getNBins()) || (dimB->getNBins() != dimD->getNBins()) ||
474 (dimB->getName() != dimN->getName()) || (dimB->getName() != dimD->getName())) {
475 errorMessage.emplace(
"TemporaryBackgroundDataWorkspace",
476 "TemporaryBackgroundDataWorkspace, "
477 "TemporaryBackgroundNormalizationWorkspace and "
478 "TemporaryDataWorkspace "
479 "must have same minimum, maximum, number of bins and name.");
484 errorMessage.emplace(
"TemporaryBackgroundDataWorkspace",
"TemporaryBackgroundDataWorkspace, "
485 "TemporaryBackgroundNormalizationWorkspace and "
486 "TemporaryDataWorkspace must have same dimensions");
497 m_convention = Kernel::ConfigService::Instance().getString(
"Q.convention");
500 std::string symOps = this->
getProperty(
"SymmetryOperations");
501 std::vector<Geometry::SymmetryOperation> symmetryOps;
502 if (symOps.empty()) {
505 if (Geometry::SpaceGroupFactory::Instance().isSubscribed(symOps)) {
506 auto spaceGroup = Geometry::SpaceGroupFactory::Instance().createSpaceGroup(symOps);
507 auto pointGroup = spaceGroup->getPointGroup();
508 symmetryOps = pointGroup->getSymmetryOperations();
509 }
else if (Geometry::PointGroupFactory::Instance().isSubscribed(symOps)) {
510 auto pointGroup = Geometry::PointGroupFactory::Instance().createPointGroup(symOps);
511 symmetryOps = pointGroup->getSymmetryOperations();
513 symmetryOps = Geometry::SymmetryOperationFactory::Instance().createSymOps(symOps);
516 for (
const auto &so : symmetryOps) {
526 const auto &exptInfoZero = *(
m_inputWS->getExperimentInfo(0));
527 auto source = exptInfoZero.getInstrument()->getSource();
528 auto sample = exptInfoZero.getInstrument()->getSample();
529 if (source ==
nullptr || sample ==
nullptr) {
531 "Instrument not sufficiently defined: failed to get source and/or "
536 if ((
m_inputWS->getNumDims() > 3) && (
m_inputWS->getDimension(3)->getName() ==
"DeltaE")) {
539 if (exptInfoZero.run().hasProperty(
"Ei")) {
541 m_Ei = boost::lexical_cast<double>(eiprop->
value());
543 throw std::invalid_argument(
"Ei stored in the workspace is not positive");
546 throw std::invalid_argument(
"Could not find Ei value in the workspace.");
562 this->
setProperty(
"OutputDataWorkspace", outputDataWS);
572 this->
setProperty(
"OutputBackgroundDataWorkspace", outputBackgroundDataWS);
583 for (uint16_t expInfoIndex = 0; expInfoIndex <
m_numExptInfos; expInfoIndex++) {
584 const auto ¤tExptInfo = *(
m_inputWS->getExperimentInfo(expInfoIndex));
587 bool skipNormalization =
false;
592 if (!skipNormalization) {
593 for (
const auto &so : symmetryOps) {
594 if (currentExptInfo.run().hasProperty(
"useLogTimes")) {
602 g_log.
warning(
"Binning limits are outside the limits of the MDWorkspace. "
603 "Not applying normalization.");
609 [](
const std::atomic<signal_t> &a,
const signal_t &b) { return a + b; });
613 [](
const std::atomic<signal_t> &a,
const signal_t &b) { return a + b; });
628 const std::string normedBkgdWSName(
"_normedBkgd");
634 minusMD->setProperty(
"LHSWorkspace", out);
635 minusMD->setProperty(
"RHSWorkspace", outbkgd);
636 minusMD->setPropertyValue(
"OutputWorkspace",
getPropertyValue(
"OutputWorkspace"));
638 minusMD->executeAsChildAlg();
639 out = minusMD->getProperty(
"OutputWorkspace");
652 const double &startProgress,
const double &endProgress) {
654 divideMD->setProperty(
"LHSWorkspace", lhs);
656 divideMD->setPropertyValue(
"OutputWorkspace", outputwsname);
671 return std::string(
"Q_sample_x");
673 return std::string(
"Q_sample_y");
675 return std::string(
"Q_sample_z");
677 throw std::invalid_argument(
"Index must be 0, 1, or 2 for QDimensionNameQSample");
686 std::vector<double>::iterator result;
687 result = std::max_element(projection.begin(), projection.end(), abs_compare);
688 std::vector<char> symbol{
'H',
'K',
'L'};
689 char character = symbol[std::distance(projection.begin(), result)];
690 std::stringstream
name;
692 for (
size_t i = 0; i < 3; i++) {
693 if (projection[i] == 0) {
695 }
else if (projection[i] == 1) {
697 }
else if (projection[i] == -1) {
698 name <<
"-" << character;
700 name << std::defaultfloat << std::setprecision(3) << projection[i] << character;
715 std::map<std::string, std::string> parameters;
716 std::stringstream extents;
717 std::stringstream bins;
718 std::vector<std::string> originalDimensionNames;
719 originalDimensionNames.emplace_back(
"QDimension0");
720 originalDimensionNames.emplace_back(
"QDimension1");
721 originalDimensionNames.emplace_back(
"QDimension2");
722 for (
size_t i = 3; i <
m_inputWS->getNumDims(); i++) {
723 originalDimensionNames.emplace_back(
m_inputWS->getDimension(i)->getName());
730 m_UB =
m_inputWS->getExperimentInfo(0)->sample().getOrientedLattice().getUB() * 2 * M_PI;
750 auto &exptInfo0 = *(
m_inputWS->getExperimentInfo(
static_cast<uint16_t
>(0)));
751 auto upperLimitsVector =
754 maxQ = 2. * (*std::max_element(upperLimitsVector.begin(), upperLimitsVector.end()));
757 double maxDE = *std::max_element(upperLimitsVector.begin(), upperLimitsVector.end());
758 auto loweLimitsVector =
760 double minDE = *std::min_element(loweLimitsVector.begin(), loweLimitsVector.end());
761 if (exptInfo0.run().hasProperty(
"Ei")) {
763 Ei = boost::lexical_cast<double>(eiprop->
value());
765 throw std::invalid_argument(
"Ei stored in the workspace is not positive");
768 throw std::invalid_argument(
"Could not find Ei value in the workspace.");
770 double ki = std::sqrt(energyToK * Ei);
771 double kfmin = std::sqrt(energyToK * (Ei - minDE));
772 double kfmax = std::sqrt(energyToK * (Ei - maxDE));
774 maxQ = ki + std::max(kfmin, kfmax);
782 auto dataExtents =
m_inputWS->getMinimumExtents(4);
783 double qx = std::max(std::fabs(dataExtents[0].getMin()), std::fabs(dataExtents[0].getMax()));
784 double qy = std::max(std::fabs(dataExtents[1].getMin()), std::fabs(dataExtents[1].getMax()));
785 double qz = std::max(std::fabs(dataExtents[2].getMin()), std::fabs(dataExtents[2].getMax()));
786 maxQ = std::sqrt(qx * qx + qy * qy + qz * qz);
788 size_t basisVectorIndex = 0;
789 std::vector<coord_t> transformation;
790 for (std::size_t i = 0; i < 6; i++) {
794 std::vector<double> binning =
getProperty(binningName);
795 std::string bv =
"BasisVector";
796 if (!dimName.empty()) {
798 std::stringstream propertyValue;
799 propertyValue << dimName;
801 auto dimIndex = std::distance(originalDimensionNames.begin(),
802 std::find(originalDimensionNames.begin(), originalDimensionNames.end(), dimName));
803 auto dimension =
m_inputWS->getDimension(dimIndex);
804 propertyValue <<
"," << dimension->getMDUnits().getUnitLabel().ascii();
805 for (
size_t j = 0; j < originalDimensionNames.size(); j++) {
806 if (j ==
static_cast<size_t>(dimIndex)) {
807 propertyValue <<
",1";
808 transformation.emplace_back(1.f);
810 propertyValue <<
",0";
811 transformation.emplace_back(0.f);
814 parameters.emplace(property, propertyValue.str());
816 coord_t dimMax = dimension->getMaximum();
817 coord_t dimMin = dimension->getMinimum();
822 dimMax =
static_cast<coord_t>(ol.
a() * maxQ);
824 }
else if (dimIndex == 1) {
825 dimMax =
static_cast<coord_t>(ol.
b() * maxQ);
827 }
else if (dimIndex == 2) {
828 dimMax =
static_cast<coord_t>(ol.
c() * maxQ);
832 if (binning.size() == 0) {
834 extents << dimMin <<
"," << dimMax <<
",";
836 }
else if (binning.size() == 2) {
838 extents << binning[0] <<
"," << binning[1] <<
",";
840 }
else if (binning.size() == 1) {
841 auto step = binning[0];
842 double nsteps = (dimMax - dimMin) / step;
843 if (nsteps + 1 - std::ceil(nsteps) >= 1e-4) {
844 nsteps = std::ceil(nsteps);
846 nsteps = std::floor(nsteps);
848 bins << static_cast<int>(nsteps) <<
",";
849 extents << dimMin <<
"," << dimMin + nsteps * step <<
",";
850 }
else if (binning.size() == 3) {
851 dimMin =
static_cast<coord_t>(binning[0]);
852 auto step = binning[1];
853 dimMax =
static_cast<coord_t>(binning[2]);
854 double nsteps = (dimMax - dimMin) / step;
855 if (nsteps + 1 - std::ceil(nsteps) >= 1e-4) {
856 nsteps = std::ceil(nsteps);
858 nsteps = std::floor(nsteps);
860 bins << static_cast<int>(nsteps) <<
",";
861 extents << dimMin <<
"," << dimMin + nsteps * step <<
",";
866 parameters.emplace(
"OutputExtents", extents.str());
867 parameters.emplace(
"OutputBins", bins.str());
869 transformation,
static_cast<size_t>((transformation.size()) /
m_inputWS->getNumDims()),
m_inputWS->getNumDims());
881 std::shared_ptr<IMDHistoWorkspace>
tmp = this->
getProperty(
"TemporaryBackgroundNormalizationWorkspace");
899 const std::string numBinsStr = parameters.at(
"OutputBins");
900 const std::string extentsStr = parameters.at(
"OutputExtents");
905 size_t numDimsTemp = tempDataWS->getNumDims();
906 if ((numBins.size() != numDimsTemp) || (extents.size() != numDimsTemp * 2)) {
907 std::stringstream errorMessage;
908 errorMessage <<
"The number of dimensions in the output and ";
909 errorMessage <<
"TemporaryDataWorkspace are not the same.";
910 throw(std::invalid_argument(errorMessage.str()));
914 for (
size_t i = 0; i < numDimsTemp; i++) {
915 auto ax = tempDataWS->getDimension(i);
916 if (numBins[i] != ax->getNBins()) {
917 std::stringstream errorMessage;
918 errorMessage <<
"The number of bins output and number of bins in ";
919 errorMessage <<
"TemporaryDataWorkspace are not the same along ";
920 errorMessage <<
"dimension " << i;
921 throw(std::invalid_argument(errorMessage.str()));
923 if (std::abs(extents[2 * i] - ax->getMinimum()) > 1.e-5) {
924 std::stringstream errorMessage;
925 errorMessage <<
"The minimum binning value for the output and ";
926 errorMessage <<
"TemporaryDataWorkspace are not the same along ";
927 errorMessage <<
"dimension " << i;
928 throw(std::invalid_argument(errorMessage.str()));
930 if (std::abs(extents[2 * i + 1] - ax->getMaximum()) > 1.e-5) {
931 std::stringstream errorMessage;
932 errorMessage <<
"The maximum binning value for the output and ";
933 errorMessage <<
"TemporaryDataWorkspace are not the same along ";
934 errorMessage <<
"dimension " << i;
935 throw(std::invalid_argument(errorMessage.str()));
940 size_t parametersIndex = 0;
941 std::vector<size_t> dimensionIndex(numDimsTemp + 1, 3);
942 for (
const auto &p : parameters) {
944 auto value = p.second;
947 if (
value.find(
"QDimension0") != std::string::npos) {
948 dimensionIndex[0] = parametersIndex;
949 const std::string dimXName = tempDataWS->getDimension(parametersIndex)->getName();
952 std::stringstream errorMessage;
953 std::stringstream debugMessage;
954 errorMessage <<
"TemporaryDataWorkspace does not have the ";
955 errorMessage <<
"correct name for dimension " << parametersIndex;
957 debugMessage <<
" TemporaryDataWorkspace: " << dimXName;
959 throw(std::invalid_argument(errorMessage.str()));
963 std::stringstream errorMessage;
964 std::stringstream debugMessage;
965 errorMessage <<
"TemporaryDataWorkspace does not have the ";
966 errorMessage <<
"correct name for dimension " << parametersIndex;
968 debugMessage <<
" TemporaryDataWorkspace: " << dimXName;
970 throw(std::invalid_argument(errorMessage.str()));
973 }
else if (
value.find(
"QDimension1") != std::string::npos) {
974 dimensionIndex[1] = parametersIndex;
975 const std::string dimYName = tempDataWS->getDimension(parametersIndex)->getName();
978 std::stringstream errorMessage;
979 std::stringstream debugMessage;
980 errorMessage <<
"TemporaryDataWorkspace does not have the ";
981 errorMessage <<
"correct name for dimension " << parametersIndex;
983 debugMessage <<
" TemporaryDataWorkspace: " << dimYName;
985 throw(std::invalid_argument(errorMessage.str()));
989 std::stringstream errorMessage;
990 std::stringstream debugMessage;
991 errorMessage <<
"TemporaryDataWorkspace does not have the ";
992 errorMessage <<
"correct name for dimension " << parametersIndex;
994 debugMessage <<
" TemporaryDataWorkspace: " << dimYName;
996 throw(std::invalid_argument(errorMessage.str()));
999 }
else if (
value.find(
"QDimension2") != std::string::npos) {
1000 dimensionIndex[2] = parametersIndex;
1001 const std::string dimZName = tempDataWS->getDimension(parametersIndex)->getName();
1004 std::stringstream errorMessage;
1005 std::stringstream debugMessage;
1006 errorMessage <<
"TemporaryDataWorkspace does not have the ";
1007 errorMessage <<
"correct name for dimension " << parametersIndex;
1009 debugMessage <<
" TemporaryDataWorkspace: " << dimZName;
1011 throw(std::invalid_argument(errorMessage.str()));
1015 std::stringstream errorMessage;
1016 std::stringstream debugMessage;
1017 errorMessage <<
"TemporaryDataWorkspace does not have the ";
1018 errorMessage <<
"correct name for dimension " << parametersIndex;
1020 debugMessage <<
" TemporaryDataWorkspace: " << dimZName;
1022 throw(std::invalid_argument(errorMessage.str()));
1026 }
else if ((key !=
"OutputBins") && (key !=
"OutputExtents")) {
1028 const std::string nameData = tempDataWS->getDimension(parametersIndex)->getName();
1029 if (
value.find(nameData) != 0) {
1031 <<
" from the temporary workspace"
1032 " is not one of the binning dimensions, "
1033 " or dimensions are in the wrong order."
1035 throw(std::invalid_argument(
"Beside the Q dimensions, "
1036 "TemporaryDataWorkspace does not have the "
1037 "same dimension names as OutputWorkspace."));
1042 const auto it = std::find_if(dimensionIndex.cbegin(), dimensionIndex.cend(),
1043 [numDimsTemp](
const auto &idx) { return idx > numDimsTemp; });
1044 if (it != dimensionIndex.cend())
1045 throw(std::invalid_argument(
"Cannot find at least one of QDimension0, "
1046 "QDimension1, or QDimension2"));
1082 std::stringstream &basisVector, std::vector<size_t> &qDimensionIndices) {
1083 if (
value.find(
"QDimension0") != std::string::npos) {
1089 qDimensionIndices.emplace_back(qindex);
1090 projection[0] = Qtransform[0][0];
1091 projection[1] = Qtransform[1][0];
1092 projection[2] = Qtransform[2][0];
1095 }
else if (
value.find(
"QDimension1") != std::string::npos) {
1101 qDimensionIndices.emplace_back(qindex);
1102 projection[0] = Qtransform[0][1];
1103 projection[1] = Qtransform[1][1];
1104 projection[2] = Qtransform[2][1];
1107 }
else if (
value.find(
"QDimension2") != std::string::npos) {
1113 qDimensionIndices.emplace_back(qindex);
1114 projection[0] = Qtransform[0][2];
1115 projection[1] = Qtransform[1][2];
1116 projection[2] = Qtransform[2][2];
1119 }
else if (
value.find(
"DeltaE") != std::string::npos) {
1135 for (
size_t i : qDimensionIndices) {
1136 auto mdHistoDimension = std::const_pointer_cast<Mantid::Geometry::MDHistoDimension>(
1137 std::dynamic_pointer_cast<const Mantid::Geometry::MDHistoDimension>(outputMDHWS->getDimension(i)));
1138 mdHistoDimension->setMDFrame(*hklFrame);
1141 auto ei = outputMDHWS->getExperimentInfo(0);
1142 ei->mutableRun().addProperty(
"W_MATRIX",
m_W.
getVector(),
true);
1160 if (tempBkgdDataWS) {
1165 std::vector<size_t> qDimensionIndices;
1166 uint16_t numexpinfo =
static_cast<uint16_t
>(
m_inputWS->getNumExperimentInfo());
1168 throw std::runtime_error(
"Symmetry operation number m_umSymops is wrong!");
1170 for (uint16_t i_expinfo = 0; i_expinfo < numexpinfo; ++i_expinfo) {
1172 auto rotMatrix =
m_inputWS->getExperimentInfo(i_expinfo)->run().getGoniometerMatrix();
1177 for (
const auto &so : symmetryOps) {
1184 Qtransform = rotMatrix *
m_UB * soMatrix *
m_W;
1186 Qtransform = rotMatrix * soMatrix *
m_W;
1190 double progress_fraction = 1. /
static_cast<double>(symmetryOps.size() * numexpinfo);
1192 createChildAlgorithm(
"BinMD", soIndex * 0.3 * progress_fraction, (soIndex + 1) * 0.3 * progress_fraction);
1194 binMD->setPropertyValue(
"AxisAligned",
"0");
1196 binMD->setProperty(
"TemporaryDataWorkspace", tempBkgdDataWS);
1197 binMD->setPropertyValue(
"NormalizeBasisVectors",
"0");
1200 binMD->setPropertyValue(
"OutputWorkspace",
getPropertyValue(
"OutputBackgroundDataWorkspace"));
1203 for (
const auto &p : parameters) {
1205 auto value = p.second;
1206 std::stringstream basisVector;
1207 std::vector<double> projection(
m_inputWS->getNumDims(), 0.);
1212 if (!basisVector.str().empty()) {
1214 for (
auto proji : projection) {
1215 proji = std::abs(proji) > 1e-10 ? proji : 0.0;
1216 basisVector <<
"," << proji;
1218 value = basisVector.str();
1221 binMD->setPropertyValue(key,
value);
1225 binMD->executeAsChildAlg();
1230 outputWS = binMD->getProperty(
"OutputWorkspace");
1231 tempBkgdDataWS = std::dynamic_pointer_cast<MDHistoWorkspace>(outputWS);
1232 tempBkgdDataWS->clearOriginalWorkspaces();
1233 tempBkgdDataWS->clearTransforms();
1236 auto outputMDHWS = std::dynamic_pointer_cast<MDHistoWorkspace>(outputWS);
1239 setQUnit(qDimensionIndices, outputMDHWS);
1267 return binMDEventWorkspace(monoNormInputWS,
"TemporaryNormalizationWorkspace",
"OutputNormalizationWorkspace",
1268 symmetryOps, parameters);
1287 const std::string &outputWSPropertyName,
1288 const std::vector<Geometry::SymmetryOperation> &symmetryOps,
1289 const std::map<std::string, std::string> ¶meters) {
1298 std::vector<size_t> qDimensionIndices;
1299 for (
const auto &so : symmetryOps) {
1305 Qtransform =
m_UB * soMatrix *
m_W;
1307 Qtransform = soMatrix *
m_W;
1311 double fraction = 1. /
static_cast<double>(symmetryOps.size());
1312 auto binMD =
createChildAlgorithm(
"BinMD", soIndex * 0.3 * fraction, (soIndex + 1) * 0.3 * fraction);
1313 binMD->setPropertyValue(
"AxisAligned",
"0");
1314 binMD->setProperty(
"InputWorkspace", ws);
1315 binMD->setProperty(
"TemporaryDataWorkspace", tempWS);
1316 binMD->setPropertyValue(
"NormalizeBasisVectors",
"0");
1317 binMD->setPropertyValue(
"OutputWorkspace",
getPropertyValue(outputWSPropertyName));
1320 for (
const auto &p : parameters) {
1321 auto value = p.second;
1322 std::stringstream basisVector;
1323 std::vector<double> projection(ws->getNumDims(), 0.);
1328 if (!basisVector.str().empty()) {
1330 for (
auto proji : projection) {
1331 proji = std::abs(proji) > 1e-10 ? proji : 0.0;
1332 basisVector <<
"," << proji;
1334 value = basisVector.str();
1337 binMD->setPropertyValue(p.first,
value);
1341 binMD->executeAsChildAlg();
1342 outputWS = binMD->getProperty(
"OutputWorkspace");
1346 tempWS = std::dynamic_pointer_cast<MDHistoWorkspace>(outputWS);
1347 tempWS->clearOriginalWorkspaces();
1348 tempWS->clearTransforms();
1352 auto outputMDHWS = std::dynamic_pointer_cast<MDHistoWorkspace>(outputWS);
1355 setQUnit(qDimensionIndices, outputMDHWS);
1371 const auto ¤tRun =
m_inputWS->getExperimentInfo(expInfoIndex)->run();
1373 std::vector<coord_t> otherDimValues;
1374 for (
size_t i = 3; i <
m_inputWS->getNumDims(); i++) {
1375 const auto dimension =
m_inputWS->getDimension(i);
1376 auto inputDimMin =
static_cast<float>(dimension->getMinimum());
1377 auto inputDimMax =
static_cast<float>(dimension->getMaximum());
1378 coord_t outputDimMin(0), outputDimMax(0);
1379 bool isIntegrated =
true;
1383 isIntegrated =
false;
1384 outputDimMin =
m_normWS->getDimension(j)->getMinimum();
1385 outputDimMax =
m_normWS->getDimension(j)->getMaximum();
1388 if (dimension->getName() ==
"DeltaE") {
1389 if ((inputDimMax < outputDimMin) || (inputDimMin > outputDimMax)) {
1390 skipNormalization =
true;
1395 otherDimValues.emplace_back(
value);
1396 if (value < inputDimMin || value > inputDimMax) {
1397 skipNormalization =
true;
1399 if ((!isIntegrated) && (value < outputDimMin || value > outputDimMax)) {
1400 skipNormalization =
true;
1404 return otherDimValues;
#define DECLARE_ALGORITHM(classname)
const std::vector< double > & rhs
double value
The value of the point.
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.
A validator which provides a TENTATIVE check that a workspace contains common bins in each spectrum.
Kernel::IValidator_sptr clone() const override
Clone the current state.
A validator which checks that a workspace has a valid instrument.
A property class for workspaces.
std::unique_ptr< MDHistoWorkspace > clone() const
Returns a clone of the workspace.
static const std::string HKLName
Input argument type for MDFrameFactory chainable factory.
Class to implement UB matrix.
void setUB(const Kernel::DblMatrix &newUB)
Sets the UB matrix and recalculates lattice parameters.
static const std::string QLabName
static const std::string QSampleName
Crystallographic symmetry operations are composed of a rotational component, which is represented by ...
Kernel::V3D transformHKL(const Kernel::V3D &hkl) const
Transforms an index triplet hkl.
double a(int nd) const
Get lattice parameter a1-a3 as function of index (0-2)
double c() const
Get lattice parameter.
double b() const
Get lattice parameter.
Support for a property that holds an array of values.
Exception for errors associated with the instrument definition.
Records the filename, the description of failure and the line on which it happened.
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 error(const std::string &msg)
Logs at error level.
void warning(const std::string &msg)
Logs at warning level.
T determinant() const
Calculate the determinant.
T Invert()
LU inversion routine.
std::vector< T > getVector() const
size_t numRows() const
Return the number of rows in the matrix.
void setColumn(const size_t nCol, const std::vector< T > &newCol)
Matrix< T > & Transpose()
Transpose the matrix.
The concrete, templated class for properties.
Base class for properties.
virtual std::string value() const =0
Returns the value of the property as a string.
static const UnitLabel RLU
Reciprocal lattice units.
std::vector< std::atomic< signal_t > > m_bkgdSignalArray
API::IMDEventWorkspace_sptr m_inputWS
Input workspace.
bool m_hIntegrated
flag for integrated h,k,l, dE dimensions
void createNormalizationWS(const DataObjects::MDHistoWorkspace &dataWS)
Create & cached the normalization workspace.
bool m_diffraction
Flag indicating if the input workspace is from diffraction.
API::IMDEventWorkspace_sptr m_backgroundWS
Input background workspace.
void cacheDimensionXValues()
Stores the X values from each H,K,L,E dimension as member variables Energy dimension is transformed t...
Mantid::Kernel::DblMatrix m_W
W matrix.
void calculateNormalization(const std::vector< coord_t > &otherValues, uint16_t expInfoIndex)
Computed the normalization for the input workspace (for MDNormSCD/MDNormDirectSC).
DataObjects::MDHistoWorkspace_sptr m_normWS
Normalization workspace.
Kernel::V3D m_samplePos
Sample position.
std::vector< std::atomic< signal_t > > m_signalArray
internal array to accumulate signals to avoid copying (serial) each loop
bool m_accumulate
Flag to accumulate normalization.
DataObjects::MDHistoWorkspace_sptr binInputWS()
Runs the BinMD algorithm on the input to provide the output workspace All slicing algorithm propertie...
uint16_t m_numExptInfos
number of experiment infos
DataObjects::MDHistoWorkspace_sptr m_bkgdNormWS
Mantid::Kernel::Matrix< coord_t > m_transformation
matrix for transforming from intersections to positions in the normalization workspace
Kernel::V3D m_beamDir
Beam direction.
Mantid::Kernel::DblMatrix m_UB
UB matrix.
size_t m_hIdx
index of h,k,l, dE dimensions in the output workspaces
std::unique_ptr< API::Progress > m_progress
Progress bar.
void calculateNormContinuous(const std::vector< coord_t > &otherValues, uint16_t expInfoIndex, const Geometry::SymmetryOperation *so=nullptr)
Computes the normalization for the input workspace for the case of a continous rotation.
std::string m_convention
ki-kf for Inelastic convention; kf-ki for Crystallography convention
double m_Ei
cached values for incident energy and momentum, final momentum min/max
MDNormalization : Bin single crystal diffraction or direct geometry inelastic data and calculate the ...
size_t m_numSymmOps
number of symmetry operations
bool m_monochromatic
Flag indicating a pre-computed MonoSCDNormalizationWorkspace was provided (monochromatic single cryst...
DataObjects::MDHistoWorkspace_sptr binBackgroundWS(const std::vector< Geometry::SymmetryOperation > &symmetryOps)
Bin(MD) input Background workspace.
std::string QDimensionName(std::vector< double > projection)
Get the dimension name when using reciprocal lattice units.
void exec() override
Execute the algorithm.
std::vector< double > m_Q0Basis
The projection vectors.
const std::string summary() const override
Algorithm's summary for use in the GUI and help.
std::map< std::string, std::string > getBinParameters()
Calculate binning parameters.
API::IMDWorkspace_sptr divideMD(const API::IMDHistoWorkspace_sptr &lhs, const API::IMDHistoWorkspace_sptr &rhs, const std::string &outputwsname, const double &startProgress, const double &endProgress)
const std::string category() const override
Algorithm's category for identification.
std::vector< coord_t > getValuesFromOtherDimensions(bool &skipNormalization, uint16_t expInfoIndex=0) const
Retrieve logged values from non-HKL dimensions.
void setQUnit(const std::vector< size_t > &qDimensionIndices, const Mantid::DataObjects::MDHistoWorkspace_sptr &outputMDHWS)
Set the output Frame to HKL.
std::vector< double > m_Q1Basis
void validateBinningForTemporaryDataWorkspace(const std::map< std::string, std::string > &, const Mantid::API::IMDHistoWorkspace_sptr &)
Validates the TemporaryDataWorkspace has the same binning as the input binning parameters.
Mantid::Kernel::DblMatrix buildSymmetryMatrix(const Geometry::SymmetryOperation &so)
build symmetry matrix
DataObjects::MDHistoWorkspace_sptr binMonoSCDNormalizationWS(const std::vector< Geometry::SymmetryOperation > &symmetryOps)
Bin(MD) MonoSCDNormalizationWorkspace (monochromatic single crystal diffraction)
std::string QDimensionNameQSample(int i)
Get the dimension name when not using reciprocal lattice units.
const std::string name() const override
Algorithms name for identification.
std::vector< double > m_Q2Basis
bool m_isRLU
flag for reciprocal lattice units
DataObjects::MDHistoWorkspace_sptr binMDEventWorkspace(const API::IMDEventWorkspace_sptr &ws, const std::string &temporaryWSPropertyName, const std::string &outputWSPropertyName, const std::vector< Geometry::SymmetryOperation > &symmetryOps, const std::map< std::string, std::string > ¶meters)
Bin(MD), per symmetry operation, an MDEventWorkspace using pre-computed bin parameters.
std::map< std::string, std::string > validateInputs() override final
Validate the input workspace.
void determineBasisVector(const size_t &qindex, const std::string &value, const Kernel::DblMatrix &Qtransform, std::vector< double > &projection, std::stringstream &basisVector, std::vector< size_t > &qDimensionIndices)
MDNorm::determineBasisVector.
int version() const override
Algorithm's version for identification.
void init() override
Initialize the algorithm's properties.
void createBackgroundNormalizationWS(const DataObjects::MDHistoWorkspace &dataWS)
std::shared_ptr< IMDEventWorkspace > IMDEventWorkspace_sptr
Shared pointer to Mantid::API::IMDEventWorkspace.
std::shared_ptr< Workspace > Workspace_sptr
shared pointer to Mantid::API::Workspace
std::shared_ptr< const MatrixWorkspace > MatrixWorkspace_const_sptr
shared pointer to the matrix workspace base class (const version)
std::shared_ptr< IMDHistoWorkspace > IMDHistoWorkspace_sptr
shared pointer to Mantid::API::IMDHistoWorkspace
std::shared_ptr< IMDWorkspace > IMDWorkspace_sptr
Shared pointer to the IMDWorkspace base class.
@ NoNormalization
Don't normalize = return raw counts.
std::shared_ptr< MDHistoWorkspace > MDHistoWorkspace_sptr
A shared pointer to a MDHistoWorkspace.
std::unique_ptr< MDFrame > MDFrame_uptr
MDFrameFactory_uptr MANTID_GEOMETRY_DLL makeMDFrameFactoryChain()
Make a complete factory chain.
std::string toString(const T &value)
Convert a number to a string.
template DLLExport std::vector< size_t > splitStringIntoVector< size_t >(std::string listString, const std::string &separator)
template DLLExport std::vector< double > splitStringIntoVector< double >(std::string listString, const std::string &separator)
MANTID_KERNEL_DLL V3D normalize(V3D v)
Normalizes a V3D.
Mantid::Kernel::Matrix< double > DblMatrix
Kernel::PropertyWithValue< std::vector< double > > VectorDoubleProperty
static constexpr double NeutronMass
Mass of the neutron in kg.
static constexpr double h
Planck constant in J*s.
static constexpr double meV
1 meV in Joules.
float coord_t
Typedef for the data type to use for coordinate axes in MD objects such as MDBox, MDEventWorkspace,...
double signal_t
Typedef for the signal recorded in a MDBox, etc.
@ Input
An input workspace.
@ Output
An output workspace.