diff --git a/Framework/API/inc/MantidAPI/IMDEventWorkspace.h b/Framework/API/inc/MantidAPI/IMDEventWorkspace.h index 5c4051aa3637c25cbacc0bff509acee6bf483d60..b202d235d853d225385a0b1f7846606be040a8e0 100644 --- a/Framework/API/inc/MantidAPI/IMDEventWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMDEventWorkspace.h @@ -65,9 +65,6 @@ public: /// Refresh the cache (integrated signal of each box) virtual void refreshCache() = 0; - /// Return true if there is any mask on the workspace - virtual bool hasMask() = 0; - /// Recurse down to a minimum depth virtual void setMinRecursionDepth(size_t depth) = 0; diff --git a/Framework/API/inc/MantidAPI/IMDIterator.h b/Framework/API/inc/MantidAPI/IMDIterator.h index bc5aff4008d809b2b2075d901ff3d29273de7327..f857d9a3ff586a0eee75c31ac5851017f345282d 100644 --- a/Framework/API/inc/MantidAPI/IMDIterator.h +++ b/Framework/API/inc/MantidAPI/IMDIterator.h @@ -76,9 +76,6 @@ public: /// Returns the normalized error for this box virtual signal_t getNormalizedError() const = 0; - /// Returns the normalized signal or mask value for this box - virtual signal_t getNormalizedSignalWithMask() const = 0; - /// Returns the total signal for this box virtual signal_t getSignal() const = 0; diff --git a/Framework/API/inc/MantidAPI/IMDNode.h b/Framework/API/inc/MantidAPI/IMDNode.h index 0eb1d5e7d105ebd3cfd35bf771a389f0dc9bc375..887defa8d30a8e1f4d44bb74810c735fdee39aad 100644 --- a/Framework/API/inc/MantidAPI/IMDNode.h +++ b/Framework/API/inc/MantidAPI/IMDNode.h @@ -264,13 +264,6 @@ public: virtual uint32_t getDepth() const = 0; virtual signal_t getSignalNormalized() const = 0; - virtual signal_t getSignalWithMask() const = 0; - virtual signal_t getSignalNormalizedWithMask() const = 0; - virtual signal_t getSignalByNEventsWithMask() const { - return this->getSignalWithMask() / - static_cast<signal_t>(this->getNPoints()); - } - virtual void calcVolume() = 0; virtual void setInverseVolume(const coord_t) = 0; virtual void setSignal(const signal_t) = 0; diff --git a/Framework/API/inc/MantidAPI/IMDWorkspace.h b/Framework/API/inc/MantidAPI/IMDWorkspace.h index 00cebc88e57addd85abaa89efae917d01b91b302..5b20b6c774dd95f0c50e52ede3da6286fc2f922c 100644 --- a/Framework/API/inc/MantidAPI/IMDWorkspace.h +++ b/Framework/API/inc/MantidAPI/IMDWorkspace.h @@ -33,7 +33,7 @@ enum MDNormalization { NumEventsNormalization = 2 }; -static const signal_t MDMaskValue = 0.0; +static const signal_t MDMaskValue = std::numeric_limits<double>::quiet_NaN(); /** Basic MD Workspace Abstract Class. * diff --git a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h index aadaf1abb81960fed4600cbe308bc4859a249bc6..a9c7d075e515c9930565609bbe8592360dbc33f0 100644 --- a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h +++ b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h @@ -56,8 +56,6 @@ public: virtual signal_t getNormalizedError() const; - virtual signal_t getNormalizedSignalWithMask() const; - virtual signal_t getSignal() const; virtual signal_t getError() const; diff --git a/Framework/API/src/MatrixWorkspaceMDIterator.cpp b/Framework/API/src/MatrixWorkspaceMDIterator.cpp index 528359492d8b1fefa4a69ef621c76006fc66fb7d..bf818a20ec115b3cfcb205bd453267d58f57d697 100644 --- a/Framework/API/src/MatrixWorkspaceMDIterator.cpp +++ b/Framework/API/src/MatrixWorkspaceMDIterator.cpp @@ -184,11 +184,6 @@ signal_t MatrixWorkspaceMDIterator::getNormalizedError() const { return std::numeric_limits<signal_t>::quiet_NaN(); } -/// Returns the normalized signal for this box -signal_t MatrixWorkspaceMDIterator::getNormalizedSignalWithMask() const { - return this->getNormalizedSignal(); -} - /// Returns the signal for this box, same as innerSignal signal_t MatrixWorkspaceMDIterator::getSignal() const { return m_Y[m_xIndex]; } diff --git a/Framework/API/test/MatrixWorkspaceMDIteratorTest.h b/Framework/API/test/MatrixWorkspaceMDIteratorTest.h index 172f54c6b6d1a489f4754e2d507364899ccaad4a..c5a0abfaf9650e4e5ca8cf64b773c71972efe263 100644 --- a/Framework/API/test/MatrixWorkspaceMDIteratorTest.h +++ b/Framework/API/test/MatrixWorkspaceMDIteratorTest.h @@ -126,54 +126,6 @@ public: } delete it; } - - /* - * For MatrixWorkspaces, masks are applied by setting the actual data to 0 - * rather than just returning 0 for masked data with - * getNormalizedSignalWithMask, therefore getNormalizedSignal and - * getNormalizedSignalWithMask should always return the same value. - */ - void test_getNormalizedSignalWithMask() { - boost::shared_ptr<MatrixWorkspace> ws = makeFakeWS(); - - // Mask a bin - ws->maskBin(0, 4, 1); - - IMDIterator *it = NULL; - TS_ASSERT_THROWS_NOTHING(it = ws->createIterator(NULL)); - - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - it->next(); - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - - it->setNormalization(NoNormalization); - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - // Area of each bin is 4.0 - it->setNormalization(VolumeNormalization); - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - it->setNormalization(NumEventsNormalization); - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - - it->next(); - it->next(); - it->next(); - // This one is masked, the two functions should still return the same - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - TS_ASSERT_DELTA(it->getNormalizedSignalWithMask(), 0.0, 1e-5); - it->next(); - it->next(); - // Workspace index 1, x index 1 - TS_ASSERT_DELTA(it->getNormalizedSignal(), - it->getNormalizedSignalWithMask(), 1e-5); - - delete it; - } }; #endif /* MANTID_API_MATRIXWORKSPACEMDITERATORTEST_H_ */ diff --git a/Framework/Algorithms/inc/MantidAlgorithms/FitPeak.h b/Framework/Algorithms/inc/MantidAlgorithms/FitPeak.h index 2ed8d511dc87e7edfec46190ddb4fc22a0392ed5..8dadd2b9d86471521af700b945cf0fdb50c183c9 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/FitPeak.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/FitPeak.h @@ -111,7 +111,12 @@ private: /// Fit function in single domain double fitFunctionSD(API::IFunction_sptr fitfunc, API::MatrixWorkspace_sptr dataws, size_t wsindex, - double xmin, double xmax, bool calmode); + double xmin, double xmax); + + /// Calculate chi-square of a single domain function + double calChiSquareSD(API::IFunction_sptr fitfunc, + API::MatrixWorkspace_sptr dataws, size_t wsindex, + double xmin, double xmax); /// Fit peak and background composite function double fitCompositeFunction(API::IPeakFunction_sptr peakfunc, diff --git a/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h b/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h index 4468af4fc6bc2f24b4b92f229d6dedbc036c589b..bf81711a25809fdbcba7d796386843968672ab02 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h @@ -109,6 +109,9 @@ private: void verifySpectrumMaps(API::MatrixWorkspace_const_sptr ws1, API::MatrixWorkspace_const_sptr ws2, const bool severe = false); + /// returns angle for source rotation + double getAngleForSourceRotation(API::MatrixWorkspace_sptr toConvert, + double thetaOut); }; } // namespace Algorithms diff --git a/Framework/Algorithms/src/FindPeaks.cpp b/Framework/Algorithms/src/FindPeaks.cpp index 67fd790e406c8bf64bd03f63717d3ab4d602638b..bd0b90c1e3e05b6be022ceaed975ce34df5c2e35 100644 --- a/Framework/Algorithms/src/FindPeaks.cpp +++ b/Framework/Algorithms/src/FindPeaks.cpp @@ -1559,6 +1559,7 @@ FindPeaks::callFitPeak(const MatrixWorkspace_sptr &dataws, int wsindex, bool fitwithsteppedfwhm = (guessedFWHMStep > 0); FitOneSinglePeak fitpeak; + fitpeak.setChild(true); fitpeak.setWorskpace(dataws, wsindex); fitpeak.setFitWindow(vec_fitwindow[0], vec_fitwindow[1]); fitpeak.setFittingMethod(m_minimizer, m_costFunction); diff --git a/Framework/Algorithms/src/FitPeak.cpp b/Framework/Algorithms/src/FitPeak.cpp index 06da542ed09419de0656d6f29611f339695892ba..0e7e377b2d57c7cf5d2852f57735753f7f869502 100644 --- a/Framework/Algorithms/src/FitPeak.cpp +++ b/Framework/Algorithms/src/FitPeak.cpp @@ -331,8 +331,8 @@ bool FitOneSinglePeak::simpleFit() { m_peakFunc->setFwhm(m_vecFWHM[i]); // fit and process result - double goodndess = fitFunctionSD(compfunc, m_dataWS, m_wsIndex, m_minFitX, - m_maxFitX, false); + double goodndess = + fitFunctionSD(compfunc, m_dataWS, m_wsIndex, m_minFitX, m_maxFitX); processNStoreFitResult(goodndess, true); // restore the function parameters @@ -468,8 +468,7 @@ double FitOneSinglePeak::fitPeakFunction(API::IPeakFunction_sptr peakfunc, m_sstream << "Function (to fit): " << peakfunc->asString() << " From " << startx << " to " << endx << ".\n"; - double goodness = - fitFunctionSD(peakfunc, dataws, wsindex, startx, endx, false); + double goodness = fitFunctionSD(peakfunc, dataws, wsindex, startx, endx); return goodness; } @@ -637,6 +636,62 @@ void FitOneSinglePeak::pop(const std::map<std::string, double> &funcparammap, return; } +//---------------------------------------------------------------------------------------------- +/** Calcualte chi-square for single domain data + * @brief FitOneSinglePeak::calChiSquareSD + * @param fitfunc + * @param dataws + * @param wsindex + * @param xmin + * @param xmax + * @return + */ +double FitOneSinglePeak::calChiSquareSD(IFunction_sptr fitfunc, + MatrixWorkspace_sptr dataws, + size_t wsindex, double xmin, + double xmax) { + // Set up sub algorithm fit + IAlgorithm_sptr fit; + try { + fit = createChildAlgorithm("CalculateChiSquared", -1, -1, false); + } catch (Exception::NotFoundError &) { + std::stringstream errss; + errss << "The FitPeak algorithm requires the CurveFitting library"; + g_log.error(errss.str()); + throw std::runtime_error(errss.str()); + } + + // Set the properties + fit->setProperty("Function", fitfunc); + fit->setProperty("InputWorkspace", dataws); + fit->setProperty("WorkspaceIndex", static_cast<int>(wsindex)); + fit->setProperty("StartX", xmin); + fit->setProperty("EndX", xmax); + + fit->executeAsChildAlg(); + if (!fit->isExecuted()) { + g_log.error("Fit for background is not executed. "); + throw std::runtime_error("Fit for background is not executed. "); + } + + // Retrieve result + const double chi2 = fit->getProperty("ChiSquaredWeightedDividedByNData"); + // g_log.notice() << "[DELETE DB]" + // << " Chi2/NParam = " << + // fit->getPropertyValue("ChiSquaredDividedByNData") + // << " Chi2/DOF = " << + // fit->getPropertyValue("ChiSquaredDividedByDOF") + // << " Chi2 = " << fit->getPropertyValue("ChiSquared") + // << " Chi2W/NParam = " << + // fit->getPropertyValue("ChiSquaredWeightedDividedByNData") + // << " Chi2W/DOF = " << + // fit->getPropertyValue("ChiSquaredWeightedDividedByDOF") + // << " Chi2W = " << fit->getPropertyValue("ChiSquaredWeighted") + // << "\n"; + + return chi2; +} + //---------------------------------------------------------------------------------------------- /** Fit function in single domain * @exception :: (1) Fit cannot be called. (2) Fit.isExecuted is false (cannot @@ -646,24 +701,8 @@ void FitOneSinglePeak::pop(const std::map<std::string, double> &funcparammap, */ double FitOneSinglePeak::fitFunctionSD(IFunction_sptr fitfunc, MatrixWorkspace_sptr dataws, - size_t wsindex, double xmin, double xmax, - bool calmode) { - // Set up calculation mode: for pure chi-square/Rwp - int maxiteration = 50; - vector<string> parnames; - if (calmode) { - // Fix all parameters - parnames = fitfunc->getParameterNames(); - for (size_t i = 0; i < parnames.size(); ++i) - fitfunc->fix(i); - - maxiteration = 1; - } else { - // Unfix all parameters - for (size_t i = 0; i < fitfunc->nParams(); ++i) - fitfunc->unfix(i); - } - + size_t wsindex, double xmin, + double xmax) { // Set up sub algorithm fit IAlgorithm_sptr fit; try { @@ -679,7 +718,7 @@ double FitOneSinglePeak::fitFunctionSD(IFunction_sptr fitfunc, fit->setProperty("Function", fitfunc); fit->setProperty("InputWorkspace", dataws); fit->setProperty("WorkspaceIndex", static_cast<int>(wsindex)); - fit->setProperty("MaxIterations", maxiteration); + fit->setProperty("MaxIterations", 50); // magic number fit->setProperty("StartX", xmin); fit->setProperty("EndX", xmax); fit->setProperty("Minimizer", m_minimizer); @@ -699,17 +738,11 @@ double FitOneSinglePeak::fitFunctionSD(IFunction_sptr fitfunc, // Retrieve result std::string fitStatus = fit->getProperty("OutputStatus"); double chi2 = EMPTY_DBL(); - if (fitStatus == "success" || calmode) { + if (fitStatus == "success") { chi2 = fit->getProperty("OutputChi2overDoF"); fitfunc = fit->getProperty("Function"); } - // Release the ties - if (calmode) { - for (size_t i = 0; i < parnames.size(); ++i) - fitfunc->unfix(i); - } - // Debug information m_sstream << "[F1201] FitSingleDomain Fitted-Function " << fitfunc->asString() << ": Fit-status = " << fitStatus << ", chi^2 = " << chi2 << ".\n"; @@ -820,12 +853,10 @@ double FitOneSinglePeak::fitCompositeFunction( // Do calculation for starting chi^2/Rwp: as the assumption that the input the // so far the best Rwp - bool modecal = true; // FIXME - This is not a good practise... - double backRwp = - fitFunctionSD(bkgdfunc, dataws, wsindex, startx, endx, modecal); + double backRwp = calChiSquareSD(bkgdfunc, dataws, wsindex, startx, endx); m_sstream << "Background: Pre-fit Goodness = " << backRwp << "\n"; - m_bestRwp = fitFunctionSD(compfunc, dataws, wsindex, startx, endx, modecal); + m_bestRwp = calChiSquareSD(compfunc, dataws, wsindex, startx, endx); m_sstream << "Peak+Background: Pre-fit Goodness = " << m_bestRwp << "\n"; map<string, double> bkuppeakmap, bkupbkgdmap; @@ -835,9 +866,7 @@ double FitOneSinglePeak::fitCompositeFunction( storeFunctionError(bkgdfunc, m_fitErrorBkgdFunc); // Fit - modecal = false; - double goodness = - fitFunctionSD(compfunc, dataws, wsindex, startx, endx, modecal); + double goodness = fitFunctionSD(compfunc, dataws, wsindex, startx, endx); string errorreason; // Check fit result diff --git a/Framework/Algorithms/src/NormaliseByCurrent.cpp b/Framework/Algorithms/src/NormaliseByCurrent.cpp index b6575d508ff8f6a742de7739f01d3102a6531780..4b53628dcada8012a7291bb4b004f76354f1d7f4 100644 --- a/Framework/Algorithms/src/NormaliseByCurrent.cpp +++ b/Framework/Algorithms/src/NormaliseByCurrent.cpp @@ -32,10 +32,15 @@ void NormaliseByCurrent::init() { } /** -Extract a value for the charge from the input workspace. Handles either single -period or multi-period data. -@param inputWS :: The input workspace to extract the log details from. -*/ + * Extract a value for the charge from the input workspace. Handles either + * single period or multi-period data. + * + * @param inputWS :: The input workspace to extract the log details from. + * + * @throws Exception::NotFoundError, std::domain_error or + * std::runtime_error if the charge value(s) are not set in the + * workspace logs or if the values are invalid (0) + */ double NormaliseByCurrent::extractCharge( boost::shared_ptr<Mantid::API::MatrixWorkspace> inputWS) const { // Get the good proton charge and check it's valid @@ -55,7 +60,7 @@ double NormaliseByCurrent::extractCharge( if (nPeriods > 1) { // Fetch the period property Property *currentPeriodNumberProperty = run.getLogData("current_period"); - int periodNumber = atoi(currentPeriodNumberProperty->value().c_str()); + int periodNumber = std::atoi(currentPeriodNumberProperty->value().c_str()); // Fetch the charge property Property *chargeProperty = run.getLogData("proton_charge_by_period"); @@ -64,8 +69,22 @@ double NormaliseByCurrent::extractCharge( if (chargePropertyArray) { charge = chargePropertyArray->operator()()[periodNumber - 1]; } else { - throw std::runtime_error("Proton charge log not found."); + throw Exception::NotFoundError( + "Proton charge log (proton_charge_by_period) not found for this " + "multiperiod data workspace", + "proton_charge_by_period"); } + + if (charge == 0) { + throw std::domain_error("The proton charge found for period number " + + std::to_string(periodNumber) + + " in the input workspace " + "run information is zero. When applying " + "NormaliseByCurrent on multiperiod data, a " + "non-zero value is required for every period in " + "the proton_charge_by_period log."); + } + } else { try { charge = inputWS->run().getProtonCharge(); @@ -74,6 +93,11 @@ double NormaliseByCurrent::extractCharge( "this workspace\n"; throw; } + + if (charge == 0) { + throw std::domain_error("The proton charge found in the input workspace " + "run information is zero"); + } } return charge; } @@ -86,10 +110,6 @@ void NormaliseByCurrent::exec() { // Get the good proton charge and check it's valid double charge = extractCharge(inputWS); - if (charge == 0) { - throw std::domain_error("The proton charge is zero"); - } - g_log.information() << "Normalisation current: " << charge << " uamps" << std::endl; diff --git a/Framework/Algorithms/src/ReflectometryReductionOne.cpp b/Framework/Algorithms/src/ReflectometryReductionOne.cpp index 05e19b0ae0aefe74b1b7286b08a2f7b89e0229c1..9640658dc1d9c71f12e6e02c8c958cbb29d152c2 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOne.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOne.cpp @@ -300,6 +300,29 @@ ReflectometryReductionOne::correctPosition(API::MatrixWorkspace_sptr &toCorrect, return corrected; } +/** +* @param toConvert : workspace used to get instrument components +* @param thetaOut : angle between sample and detectors (in Degrees) +* @return Theta : the value by which we rotate the source (in Degrees) +*/ +double ReflectometryReductionOne::getAngleForSourceRotation( + MatrixWorkspace_sptr toConvert, double thetaOut) { + auto instrument = toConvert->getInstrument(); + auto instrumentUpVector = instrument->getReferenceFrame()->vecPointingUp(); + // check to see if calculated theta is the same as theta from instrument setup + auto instrumentBeamDirection = instrument->getBeamDirection(); + double currentThetaInFromInstrument = + instrumentUpVector.angle(instrumentBeamDirection) * (180 / M_PI) - 90; + bool isInThetaEqualToOutTheta = + std::abs(currentThetaInFromInstrument - thetaOut) < + Mantid::Kernel::Tolerance; + // the angle by which we rotate the source + double rotationTheta = 0.0; + if (!isInThetaEqualToOutTheta /*source needs rotation*/) { + rotationTheta = thetaOut - currentThetaInFromInstrument; + } + return rotationTheta; +} /** * Convert an input workspace into an IvsQ workspace. @@ -349,23 +372,16 @@ Mantid::API::MatrixWorkspace_sptr ReflectometryReductionOne::toIvsQ( } else if (bCorrectPosition) { toConvert = correctPosition(toConvert, thetaInDeg.get(), isPointDetector); } - - auto instrument = toConvert->getInstrument(); - auto instrumentSourcePosition = - toConvert->getInstrument()->getSource()->getPos(); - auto instrumentUpVector = - toConvert->getInstrument()->getReferenceFrame()->vecPointingUp(); - bool isSourcePerpendicularToUpVec = - instrumentSourcePosition.scalar_prod(instrumentUpVector) == 0; - - if (isSourcePerpendicularToUpVec /*source hasn't rotated*/) { + double rotationTheta = getAngleForSourceRotation(toConvert, thetaInDeg.get()); + if (rotationTheta != 0.0) { auto rotateSource = this->createChildAlgorithm("RotateSource"); rotateSource->setChild(true); rotateSource->initialize(); rotateSource->setProperty("Workspace", toConvert); - rotateSource->setProperty("Angle", thetaInDeg.get()); + rotateSource->setProperty("Angle", rotationTheta); rotateSource->execute(); } + // Always convert units. auto convertUnits = this->createChildAlgorithm("ConvertUnits"); convertUnits->initialize(); diff --git a/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp b/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp index 17104a9e4b23dd8223a42f8cc5647bc397ee9d10..3d3c2c6a52806eb810030e5cc81c8a2d8a95eae1 100644 --- a/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp +++ b/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp @@ -80,6 +80,10 @@ void CalculateChiSquared::initConcrete() { "number of degrees of freedom (NofData " "- nOfParams).", Direction::Output); + declareProperty("ChiSquaredDividedByNData", 0.0, + "Output value of chi squared divided by the " + "number of data points).", + Direction::Output); declareProperty("ChiSquaredWeighted", 0.0, "Output value of weighted chi squared.", Direction::Output); declareProperty("ChiSquaredWeightedDividedByDOF", 0.0, @@ -87,6 +91,10 @@ void CalculateChiSquared::initConcrete() { "number of degrees of freedom (NofData " "- nOfParams).", Direction::Output); + declareProperty("ChiSquaredWeightedDividedByNData", 0.0, + "Output value of weighted chi squared divided by the " + "number of data points).", + Direction::Output); declareProperty("Output", "", "A base name for output workspaces."); declareProperty("Weighted", false, "Option to use the weighted chi squared " "in error estimation. Default is false."); @@ -122,29 +130,41 @@ void CalculateChiSquared::execConcrete() { double dof = 0.0; calcChiSquared(*m_function, nParams, *domain, *values, chiSquared, chiSquaredWeighted, dof); - g_log.notice() << "Chi squared " << chiSquared << std::endl; - g_log.notice() << "Chi squared weighted " << chiSquaredWeighted << std::endl; + g_log.notice() << "Chi squared " << chiSquared << "\n" + << "Chi squared weighted " << chiSquaredWeighted << "\n"; // Store the result. setProperty("ChiSquared", chiSquared); setProperty("chiSquaredWeighted", chiSquaredWeighted); - // Divide by the DOF + // Divided by NParams + double nData = dof + static_cast<double>(nParams); + const double chiSquaredNData = chiSquared / nData; + const double chiSquaredWeightedNData = chiSquaredWeighted / nData; + g_log.notice() << "Chi squared / NData " << chiSquaredNData << "\n" + << "Chi squared weighed / NData " << chiSquaredWeightedNData + << "\n" + << "NParams " << nParams << "\n"; + + // Store the result. + setProperty("ChiSquaredDividedByNData", chiSquaredNData); + setProperty("ChiSquaredWeightedDividedByNData", chiSquaredWeightedNData); + + // Divided by the DOF if (dof <= 0.0) { dof = 1.0; - g_log.warning() << "DOF has a non-positive value, changing to 1.0." - << std::endl; + g_log.warning("DOF has a non-positive value, changing to 1.0"); } - chiSquared /= dof; - chiSquaredWeighted /= dof; - g_log.notice() << "Chi squared / DOF " << chiSquared << std::endl; - g_log.notice() << "Chi squared weighed / DOF " << chiSquaredWeighted - << std::endl; - g_log.notice() << "DOF " << dof << std::endl; + const double chiSquaredDOF = chiSquared / dof; + const double chiSquaredWeightedDOF = chiSquaredWeighted / dof; + g_log.notice() << "Chi squared / DOF " << chiSquaredDOF << "\n" + << "Chi squared weighed / DOF " << chiSquaredWeightedDOF + << "\n" + << "DOF " << dof << "\n"; // Store the result. - setProperty("ChiSquaredDividedByDOF", chiSquared); - setProperty("ChiSquaredWeightedDividedByDOF", chiSquaredWeighted); + setProperty("ChiSquaredDividedByDOF", chiSquaredDOF); + setProperty("ChiSquaredWeightedDividedByDOF", chiSquaredWeightedDOF); std::string baseName = getProperty("Output"); if (!baseName.empty()) { diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDBox.tcc b/Framework/DataObjects/inc/MantidDataObjects/MDBox.tcc index 2b9ca29de1b3af05929c6e08526cbd8475e61b89..7c469e20bc10b157225b3591c47e3c6ad2f33792 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDBox.tcc +++ b/Framework/DataObjects/inc/MantidDataObjects/MDBox.tcc @@ -704,7 +704,11 @@ TMDE(void MDBox)::transformDimensions(std::vector<double> &scaling, } /// Setter for masking the box -TMDE(void MDBox)::mask() { m_bIsMasked = true; } +TMDE(void MDBox)::mask() { + this->setSignal(MDMaskValue); + this->setErrorSquared(MDMaskValue); + m_bIsMasked = true; +} /// Setter for unmasking the box TMDE(void MDBox)::unmask() { m_bIsMasked = false; } diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDBoxBase.h b/Framework/DataObjects/inc/MantidDataObjects/MDBoxBase.h index 8a90d73aec558a7d68464f81cadf785a59ad0795..985985c09c37d842b5ded8b01951e239bd3a92f5 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDBoxBase.h +++ b/Framework/DataObjects/inc/MantidDataObjects/MDBoxBase.h @@ -254,16 +254,6 @@ public: */ virtual signal_t getError() const { return sqrt(m_errorSquared); } - //----------------------------------------------------------------------------------------------- - /** Returns the integrated signal from all points within or mask value. - */ - virtual signal_t getSignalWithMask() const { - if (this->getIsMasked()) { - return Mantid::API::MDMaskValue; - } - return m_signal; - } - //----------------------------------------------------------------------------------------------- /** Returns the integrated error squared from all points within. */ @@ -313,17 +303,6 @@ public: return m_errorSquared * m_inverseVolume; } - //----------------------------------------------------------------------------------------------- - /** Returns the integrated signal from all points within, normalized for the - * cell volume - */ - virtual signal_t getSignalNormalizedWithMask() const { - if (this->getIsMasked()) { - return Mantid::API::MDMaskValue; - } - return m_signal * m_inverseVolume; - } - //----------------------------------------------------------------------------------------------- /** For testing, mostly: return the recursion depth of this box. * 0 is the top-level box, 1 is one deeper, etc. diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.h b/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.h index 48b5f760cff0c2229d72c34e98c3f0f1ccccb8f4..fe6e414c2105a239ffa37208dfa5eebd2b8b9d29 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.h +++ b/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.h @@ -50,8 +50,6 @@ public: signal_t getNormalizedError() const; - signal_t getNormalizedSignalWithMask() const; - signal_t getSignal() const; signal_t getError() const; diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.tcc b/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.tcc index f85c39d5d9e977e2fbdfbd2c1020440d3bd1df45..e475db612dec99b96b1b997ecda001addaf4ce51 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.tcc +++ b/Framework/DataObjects/inc/MantidDataObjects/MDBoxIterator.tcc @@ -253,23 +253,6 @@ TMDE(signal_t MDBoxIterator)::getNormalizedError() const { return std::numeric_limits<signal_t>::quiet_NaN(); } -/// Returns the normalized signal for this box -TMDE(signal_t MDBoxIterator)::getNormalizedSignalWithMask() const { - if (this->getIsMasked()) { - return MDMaskValue; - } - // What is our normalization factor? - switch (m_normalization) { - case NoNormalization: - return m_current->getSignal(); - case VolumeNormalization: - return m_current->getSignal() * m_current->getInverseVolume(); - case NumEventsNormalization: - return m_current->getSignal() / double(m_current->getNPoints()); - } - return std::numeric_limits<signal_t>::quiet_NaN(); -} - /// Returns the signal for this box TMDE(signal_t MDBoxIterator)::getSignal() const { return m_current->getSignal(); diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h b/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h index 4e21fbf000883e42f21ba931ec29718de18db5f3..f6ba4709928de513bd3403985bcf6604ec9338e3 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h +++ b/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.h @@ -172,9 +172,6 @@ public: /// Clear masking void clearMDMasking(); - /// Return true if there is any mask on the workspace - bool hasMask(); - /// Get the coordinate system. Kernel::SpecialCoordinateSystem getSpecialCoordinateSystem() const; /// Set the coordinate system. diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.tcc b/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.tcc index fabb4d85c77d76247462e3ccebae607825a0aaed..fbf7de056d82eec9085e702f6205c4bbe14eb76a 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.tcc +++ b/Framework/DataObjects/inc/MantidDataObjects/MDEventWorkspace.tcc @@ -832,22 +832,6 @@ TMDE(void MDEventWorkspace)::clearMDMasking() { } } -/** -Return true if there is any mask on the workspace -*/ -TMDE(bool MDEventWorkspace)::hasMask() { - auto *it = this->createIterator(); - size_t counter = 0; - for (; counter < it->getDataSize(); ++counter) { - if (it->getIsMasked()) { - delete it; - return true; - } - } - delete it; - return false; -} - /** Get the coordinate system (if any) to use. @return An enumeration specifying the coordinate system if any. diff --git a/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h b/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h index 0e008b9e5a8f691e739f7a50164ba2e48d961035..e3aa76c7c983a16ac669a710f51dec8abe289db4 100644 --- a/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h +++ b/Framework/DataObjects/inc/MantidDataObjects/MDHistoWorkspaceIterator.h @@ -91,8 +91,6 @@ public: virtual signal_t getNormalizedError() const; - virtual signal_t getNormalizedSignalWithMask() const; - virtual signal_t getSignal() const; virtual signal_t getError() const; diff --git a/Framework/DataObjects/src/MDHistoWorkspace.cpp b/Framework/DataObjects/src/MDHistoWorkspace.cpp index 895c2e81ce998f2c81d4ec17e0b0f46002a1a786..15b6e08e45047807174a4a7ae84d6317f6a5d386 100644 --- a/Framework/DataObjects/src/MDHistoWorkspace.cpp +++ b/Framework/DataObjects/src/MDHistoWorkspace.cpp @@ -1219,7 +1219,7 @@ void MDHistoWorkspace::setMDMasking( // If the function masks the point, then mask it, otherwise leave it as it // is. if (maskingRegion->isPointContained(this->getCenter(i))) { - m_masks[i] = true; + this->setMDMaskAt(i, true); } } delete maskingRegion; @@ -1233,9 +1233,18 @@ void MDHistoWorkspace::setMDMasking( */ void MDHistoWorkspace::setMDMaskAt(const size_t &index, bool mask) { m_masks[index] = mask; + if (mask) { + // Set signal and error of masked points to the value of MDMaskValue + this->setSignalAt(index, MDMaskValue); + this->setErrorSquaredAt(index, MDMaskValue); + } } -/// Clear any existing masking. +/** + * Clear any existing masking. + * Note that this clears the mask flag but does not restore the data + * which was set to NaN when it was masked. + */ void MDHistoWorkspace::clearMDMasking() { for (size_t i = 0; i < this->getNPoints(); ++i) { m_masks[i] = false; diff --git a/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp b/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp index e5f9f6c3b73ded46c80fe3e0be4b8068556b86db..9f8016d0feb9a7e1296f88983287b1e64dd9e2a1 100644 --- a/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp +++ b/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp @@ -371,25 +371,6 @@ signal_t MDHistoWorkspaceIterator::getNormalizedError() const { return std::numeric_limits<signal_t>::quiet_NaN(); } -//---------------------------------------------------------------------------------------------- -/// Returns the normalized signal for this box -signal_t MDHistoWorkspaceIterator::getNormalizedSignalWithMask() const { - if (this->getIsMasked()) { - return MDMaskValue; - } - // What is our normalization factor? - switch (m_normalization) { - case NoNormalization: - return m_ws->getSignalAt(m_pos); - case VolumeNormalization: - return m_ws->getSignalAt(m_pos) * m_ws->getInverseVolume(); - case NumEventsNormalization: - return m_ws->getSignalAt(m_pos) / m_ws->getNumEventsAt(m_pos); - } - // Should not reach here - return std::numeric_limits<signal_t>::quiet_NaN(); -} - //---------------------------------------------------------------------------------------------- /// Returns the signal for this box, same as innerSignal signal_t MDHistoWorkspaceIterator::getSignal() const { diff --git a/Framework/DataObjects/test/MDBoxIteratorTest.h b/Framework/DataObjects/test/MDBoxIteratorTest.h index 5a04aa07dd32cc1acc755933032019c87e66b571..df2ece87914aa656a99b8fb947e45bcfa6dc394f 100644 --- a/Framework/DataObjects/test/MDBoxIteratorTest.h +++ b/Framework/DataObjects/test/MDBoxIteratorTest.h @@ -13,6 +13,7 @@ #include "MantidTestHelpers/MDEventsTestHelper.h" #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> +#include <boost/math/special_functions/fpclassify.hpp> using namespace Mantid::DataObjects; using namespace Mantid::API; @@ -622,26 +623,22 @@ public: testing::Mock::VerifyAndClearExpectations(mockPolicy)); } - void test_getNormalizedSignalWithMask_returns_zero_for_masked() { + void test_getNormalizedSignal_with_mask() { // Make a MDBox with 10 events ibox_t *A = MDEventsTestHelper::makeMDBox1(); MDEventsTestHelper::feedMDBox<1>(A, 1, 10, 0.5, 1.0); MDBoxIterator<MDLeanEvent<1>, 1> *it = new MDBoxIterator<MDLeanEvent<1>, 1>(A, 20, true); - // Mask box 0, unmask box 1 and mask box 2. - // For masked boxes, getNormalizedSignalWithMask() should return 0. - it->getBox()->mask(); - TS_ASSERT_DELTA(it->getNormalizedSignalWithMask(), 0.0, 1e-5); - TS_ASSERT_DELTA(it->getNormalizedSignal(), 1.0, 1e-5); - it->next(); - it->getBox()->unmask(); - TS_ASSERT_DELTA(it->getNormalizedSignalWithMask(), 1.0, 1e-5); + // Initially the box is unmasked TS_ASSERT_DELTA(it->getNormalizedSignal(), 1.0, 1e-5); + it->next(); + + // Now mask the box it->getBox()->mask(); - TS_ASSERT_DELTA(it->getNormalizedSignalWithMask(), 0.0, 1e-5); - TS_ASSERT_DELTA(it->getNormalizedSignal(), 1.0, 1e-5); + // For masked boxes, getNormalizedSignal() should return NaN. + TS_ASSERT(boost::math::isnan(it->getNormalizedSignal())); delete it; } diff --git a/Framework/DataObjects/test/MDEventWorkspaceTest.h b/Framework/DataObjects/test/MDEventWorkspaceTest.h index 946b474a0b50af5d19eec21a58f47e9ca6aae159..4f14dcfd9867efefe308eeb5c653bb7167198089 100644 --- a/Framework/DataObjects/test/MDEventWorkspaceTest.h +++ b/Framework/DataObjects/test/MDEventWorkspaceTest.h @@ -321,29 +321,9 @@ public: TSM_ASSERT_DELTA( "Value ignoring mask is 1.0", ew->getSignalAtCoord(coords1, Mantid::API::NoNormalization), 1.0, 1e-5); - TSM_ASSERT_DELTA( - "Masked returns 0", - ew->getSignalWithMaskAtCoord(coords1, Mantid::API::NoNormalization), - 0.0, 1e-5); - } - - //------------------------------------------------------------------------------------- - /** hasMask should return true when the workspace has a mask */ - void test_hasMask() { - MDEventWorkspace3Lean::sptr ew = - MDEventsTestHelper::makeMDEW<3>(4, 0.0, 4.0, 1); - - TSM_ASSERT("Should return false as the workspace does not have a mask", - !ew->hasMask()); - - std::vector<coord_t> min{0, 0, 0}; - std::vector<coord_t> max{1.5, 1.5, 1.5}; - - // Create a function to mask some of the workspace. - MDImplicitFunction *function = new MDBoxImplicitFunction(min, max); - ew->setMDMasking(function); - - TSM_ASSERT("Should return true as the workspace has a mask", ew->hasMask()); + TSM_ASSERT("Masked returns NaN", + boost::math::isnan(ew->getSignalWithMaskAtCoord( + coords1, Mantid::API::NoNormalization))); } //------------------------------------------------------------------------------------- @@ -606,8 +586,8 @@ public: std::vector<signal_t> y, e; ew->getLinePlot(start, end, NoNormalization, x, y, e); TS_ASSERT_EQUALS(y.size(), 200); - TS_ASSERT_EQUALS(y[60], 0.0); // Masked data is zero - TS_ASSERT_EQUALS(y[180], 3.0); // Unmasked data + TS_ASSERT(boost::math::isnan(y[60])); // Masked data is NaN + TS_ASSERT_EQUALS(y[180], 3.0); // Unmasked data } void test_that_sets_default_normalization_flags_to_volume_normalization() { diff --git a/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h b/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h index 52524fede41969ae88cd0c43936721a5da89f1af..8ece796f936b93688de8189b7176122a3947c187 100644 --- a/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h +++ b/Framework/DataObjects/test/MDHistoWorkspaceIteratorTest.h @@ -15,6 +15,7 @@ #include <boost/function.hpp> #include <boost/bind.hpp> #include <boost/scoped_ptr.hpp> +#include <boost/math/special_functions/fpclassify.hpp> using namespace Mantid; using namespace Mantid::DataObjects; @@ -140,7 +141,7 @@ public: delete histoIt; } - void test_getNormalizedSignalWIthMask() { + void test_getNormalizedSignal_with_mask() { // std::vector<coord_t> normal_vector{1.}; // std::vector<coord_t> bound_vector{3.}; @@ -159,11 +160,11 @@ public: ws->setSignalAt(3, 3.0); ws->setSignalAt(4, 3.0); - ws->setMaskValueAt(0, false); // Unmasked - ws->setMaskValueAt(1, false); // Unmasked - ws->setMaskValueAt(2, true); // Masked - ws->setMaskValueAt(3, false); // Unmasked - ws->setMaskValueAt(4, true); // Masked + ws->setMDMaskAt(0, false); // Unmasked + ws->setMDMaskAt(1, false); // Unmasked + ws->setMDMaskAt(2, true); // Masked + ws->setMDMaskAt(3, false); // Unmasked + ws->setMDMaskAt(4, true); // Masked Mantid::DataObjects::MDHistoWorkspace_sptr ws_sptr(ws); @@ -172,14 +173,14 @@ public: TSM_ASSERT_EQUALS("Should get the signal value here as data at the iterator" " are unmasked", - 3.0, histoIt->getNormalizedSignalWithMask()); + 3.0, histoIt->getNormalizedSignal()); histoIt->jumpTo(2); - TSM_ASSERT_EQUALS("Should return 0 here as data at the iterator are masked", - 0.0, histoIt->getNormalizedSignalWithMask()); + TSM_ASSERT("Should return NaN here as data at the iterator are masked", + boost::math::isnan(histoIt->getNormalizedSignal())); histoIt->jumpTo(3); TSM_ASSERT_EQUALS("Should get the signal value here as data at the iterator" " are unmasked", - 3.0, histoIt->getNormalizedSignalWithMask()); + 3.0, histoIt->getNormalizedSignal()); delete histoIt; } diff --git a/Framework/DataObjects/test/MDHistoWorkspaceTest.h b/Framework/DataObjects/test/MDHistoWorkspaceTest.h index b1de71e1e94827688871508ee3c152136a3a7ba7..0ad54996f3231fdbcf1073453dff4d301441b239 100644 --- a/Framework/DataObjects/test/MDHistoWorkspaceTest.h +++ b/Framework/DataObjects/test/MDHistoWorkspaceTest.h @@ -535,14 +535,18 @@ public: ws->setMDMasking(function); IMDWorkspace_sptr iws(ws); - TS_ASSERT_DELTA(iws->getSignalAtVMD(VMD(0.5, 0.5)), 0.0, 1e-6); - TS_ASSERT_DELTA(iws->getSignalWithMaskAtVMD(VMD(0.5, 0.5)), 0.0, 1e-6); - TS_ASSERT_DELTA(iws->getSignalAtVMD(VMD(3.5, 0.5), VolumeNormalization), - 0.25, 1e-6); - TS_ASSERT_DELTA( - iws->getSignalWithMaskAtVMD(VMD(3.5, 0.5), VolumeNormalization), 0.0, - 1e-6); + // Testing with isnan() as following commented line doesn't work + // when MDMaskValue is NaN. + // TS_ASSERT_DELTA(iws->getSignalWithMaskAtVMD(VMD(0.5, 0.5)), MDMaskValue, + // 1e-6); + TS_ASSERT(boost::math::isnan(iws->getSignalAtVMD(VMD(0.5, 0.5)))); + TS_ASSERT(boost::math::isnan(iws->getSignalWithMaskAtVMD(VMD(0.5, 0.5)))); + + TS_ASSERT(boost::math::isnan( + iws->getSignalAtVMD(VMD(3.5, 0.5), VolumeNormalization))); + TS_ASSERT(boost::math::isnan( + iws->getSignalWithMaskAtVMD(VMD(3.5, 0.5), VolumeNormalization))); } //--------------------------------------------------------------------------------------------------- @@ -594,7 +598,7 @@ public: TS_ASSERT_EQUALS(y.size(), 10); // Masked value should be zero - TS_ASSERT_DELTA(y[2], 0.0, 1e-5); + TS_ASSERT(boost::math::isnan(y[2])); // Unmasked value TS_ASSERT_DELTA(y[9], 9.0, 1e-5); } diff --git a/Framework/MDAlgorithms/test/ConvertEventsToMDTest.h b/Framework/MDAlgorithms/test/ConvertEventsToMDTest.h index bf61dee718d5683c7ac77f833172e140aa9d9996..cdb87dc224c44e87dc0d61f64a23f9d2713ac496 100644 --- a/Framework/MDAlgorithms/test/ConvertEventsToMDTest.h +++ b/Framework/MDAlgorithms/test/ConvertEventsToMDTest.h @@ -46,7 +46,7 @@ public: pAlg->setRethrows(false); pAlg->execute(); - TSM_ASSERT("Shoud finish succesfully", pAlg->isExecuted()); + TSM_ASSERT("Should finish succesfully", pAlg->isExecuted()); Mantid::API::Workspace_sptr spws; TS_ASSERT_THROWS_NOTHING( spws = AnalysisDataService::Instance().retrieve("testMDEvWorkspace")); @@ -55,7 +55,7 @@ public: boost::shared_ptr<DataObjects::MDEventWorkspace<DataObjects::MDEvent<3>, 3>> ws = boost::dynamic_pointer_cast< DataObjects::MDEventWorkspace<DataObjects::MDEvent<3>, 3>>(spws); - TSM_ASSERT("It shoudl be 3D MD workspace", ws.get()); + TSM_ASSERT("It should be 3D MD workspace", ws.get()); if (ws.get()) { TS_ASSERT_EQUALS(900, ws->getNPoints()); diff --git a/Framework/MDAlgorithms/test/FitMDTest.h b/Framework/MDAlgorithms/test/FitMDTest.h index cb96da80e5088f1b26e6379bf24a98d15a31cef0..b793882ad79fab6abe7657c91d9216790723bdd2 100644 --- a/Framework/MDAlgorithms/test/FitMDTest.h +++ b/Framework/MDAlgorithms/test/FitMDTest.h @@ -31,7 +31,6 @@ public: virtual void jumpTo(size_t index); virtual bool next(); virtual bool next(size_t) { return false; } - virtual signal_t getNormalizedSignalWithMask() const; virtual signal_t getNormalizedSignal() const; virtual signal_t getNormalizedError() const; virtual signal_t getSignal() const { return 0; } @@ -93,10 +92,6 @@ bool IMDWorkspaceTesterIterator::next() { return true; } -signal_t IMDWorkspaceTesterIterator::getNormalizedSignalWithMask() const { - return signal_t(m_ws->readY(iy)[ix]); -} - signal_t IMDWorkspaceTesterIterator::getNormalizedSignal() const { return signal_t(m_ws->readY(iy)[ix]); } diff --git a/Framework/MDAlgorithms/test/ReplicateMDTest.h b/Framework/MDAlgorithms/test/ReplicateMDTest.h index e327e40f9ba391f91990182a202d56842e3ce88a..4b415bad15fa53a470d07d97ff6b67620212dbc0 100644 --- a/Framework/MDAlgorithms/test/ReplicateMDTest.h +++ b/Framework/MDAlgorithms/test/ReplicateMDTest.h @@ -253,11 +253,11 @@ public: // increasing TSM_ASSERT_EQUALS( - "Neighours vertical. Should be the same.", outWS->getSignalAt(0), - outWS->getSignalAt(shapeShape[0] /*one row verically down*/)); - TSM_ASSERT_DIFFERS("Neighours horizontal. Should be different.", + "Neighbours vertical. Should be the same.", outWS->getSignalAt(0), + outWS->getSignalAt(shapeShape[0] /*one row vertically down*/)); + TSM_ASSERT_DIFFERS("Neighbours horizontal. Should be different.", outWS->getSignalAt(0), outWS->getSignalAt(1)); - TSM_ASSERT_EQUALS("Horzontal points should be same in data and output", + TSM_ASSERT_EQUALS("Horizontal points should be same in data and output", dataWS->getSignalAt(1), outWS->getSignalAt(1)); } diff --git a/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index 792dc96d7813e7d1e279b94f1b2c94d0994402f7..e919b750834b6cd45b02eb537c75da831f8e8def 100644 --- a/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -30,6 +30,7 @@ #include "MantidKernel/TimeSeriesProperty.h" #include "MantidKernel/UnitFactory.h" #include "MantidKernel/VectorHelper.h" +#include "MantidKernel/make_unique.h" #include <cmath> #include <sstream> @@ -68,9 +69,14 @@ Workspace2D_sptr Create1DWorkspaceRand(int size) { MantidVecPtr x1, y1, e1; x1.access().resize(size, 1); y1.access().resize(size); - std::generate(y1.access().begin(), y1.access().end(), rand); + + MersenneTwister randomGen(DateAndTime::getCurrentTime().nanoseconds(), 0, + std::numeric_limits<int>::max()); + auto randFunc = [&randomGen] { return randomGen.nextValue(); }; + + std::generate(y1.access().begin(), y1.access().end(), randFunc); e1.access().resize(size); - std::generate(e1.access().begin(), e1.access().end(), rand); + std::generate(e1.access().begin(), e1.access().end(), randFunc); Workspace2D_sptr retVal(new Workspace2D); retVal->initialize(1, size, size); retVal->setX(0, x1); @@ -760,13 +766,16 @@ EventWorkspace_sptr CreateRandomEventWorkspace(size_t numbins, size_t numpixels, } pAxis0->setUnit("TOF"); + MersenneTwister randomGen(DateAndTime::getCurrentTime().nanoseconds(), 0, + std::numeric_limits<int>::max()); // Make up some data for each pixels for (size_t i = 0; i < numpixels; i++) { // Create one event for each bin EventList &events = retVal->getEventList(static_cast<detid_t>(i)); for (std::size_t ie = 0; ie < numbins; ie++) { // Create a list of events, randomize - events += TofEvent(std::rand(), std::rand()); + events += TofEvent(static_cast<double>(randomGen.nextValue()), + static_cast<int64_t>(randomGen.nextValue())); } events.addDetectorID(detid_t(i)); } @@ -882,9 +891,9 @@ void AddTSPEntry(Run &runInfo, std::string name, double val) { */ void SetOrientedLattice(Mantid::API::MatrixWorkspace_sptr ws, double a, double b, double c) { - OrientedLattice *latt = new OrientedLattice(a, b, c, 90., 90., 90.); - ws->mutableSample().setOrientedLattice(latt); - delete latt; + auto latt = + Mantid::Kernel::make_unique<OrientedLattice>(a, b, c, 90., 90., 90.); + ws->mutableSample().setOrientedLattice(latt.release()); } // ===================================================================================== @@ -924,9 +933,9 @@ createProcessedWorkspaceWithCylComplexInstrument(size_t numPixels, pAxis0->setUnit("DeltaE"); ws->replaceAxis(0, pAxis0); if (has_oriented_lattice) { - OrientedLattice *latt = new OrientedLattice(1, 1, 1, 90., 90., 90.); - ws->mutableSample().setOrientedLattice(latt); - delete latt; + auto latt = + Mantid::Kernel::make_unique<OrientedLattice>(1, 1, 1, 90., 90., 90.); + ws->mutableSample().setOrientedLattice(latt.release()); AddTSPEntry(ws->mutableRun(), "phi", 0); AddTSPEntry(ws->mutableRun(), "chi", 0); @@ -1001,9 +1010,9 @@ createProcessedInelasticWS(const std::vector<double> &L2, ws->replaceAxis(0, pAxis0); // define oriented lattice which requested for processed ws - OrientedLattice *latt = new OrientedLattice(1, 1, 1, 90., 90., 90.); - ws->mutableSample().setOrientedLattice(latt); - delete latt; + auto latt = + Mantid::Kernel::make_unique<OrientedLattice>(1, 1, 1, 90., 90., 90.); + ws->mutableSample().setOrientedLattice(latt.release()); // TODO: clarify if this property indeed goes there; ws->mutableRun().addProperty(new PropertyWithValue<double>("Ei", Ei), true); diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.h index c7c43630b3564730e70f037edbf564c2e34d02ef..dc6fe695064761c28e90132105c53e6ff81d1b18 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.h @@ -32,6 +32,8 @@ namespace IDA void calculateBinning(); private: + QString makePyPlotSource(const int &index); + Ui::Iqt m_uiForm; QtTreePropertyBrowser* m_furTree; bool m_furyResFileType; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.ui index 409072ced09994b2ac8ca26040ecebce11fccfb4..2c21355239dddb5dcb3815451e86c961e6085bf2 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/Iqt.ui @@ -141,6 +141,13 @@ </property> </widget> </item> + <item> + <widget class="QCheckBox" name="ckTile"> + <property name="text"> + <string>TilePlot</string> + </property> + </widget> + </item> <item> <spacer name="horizontalSpacer_1"> <property name="orientation"> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflPresenter.h index 9acf1b47564a38313f2d7b1cdeecaf941a68f1a2..355b63f70cd5931f21019aeae49c1102eb49fa5a 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflPresenter.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/IReflPresenter.h @@ -8,70 +8,68 @@ #include <QVariant> -namespace MantidQt -{ - namespace CustomInterfaces - { - /** @class IReflPresenter +namespace MantidQt { +namespace CustomInterfaces { +/** @class IReflPresenter - IReflPresenter is an interface which defines the functions any reflectometry interface presenter needs to support. +IReflPresenter is an interface which defines the functions any reflectometry +interface presenter needs to support. - Copyright © 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge National Laboratory & European Spallation Source +Copyright © 2011-14 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge +National Laboratory & European Spallation Source - This file is part of Mantid. +This file is part of Mantid. - Mantid is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 3 of the License, or - (at your option) any later version. +Mantid is free software; you can redistribute it and/or modify +it under the terms of the GNU General Public License as published by +the Free Software Foundation; either version 3 of the License, or +(at your option) any later version. - Mantid is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. +Mantid is distributed in the hope that it will be useful, +but WITHOUT ANY WARRANTY; without even the implied warranty of +MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program. If not, see <http://www.gnu.org/licenses/>. +You should have received a copy of the GNU General Public License +along with this program. If not, see <http://www.gnu.org/licenses/>. - File change history is stored at: <https://github.com/mantidproject/mantid>. - Code Documentation is available at: <http://doxygen.mantidproject.org> - */ - class IReflPresenter - { - public: - virtual ~IReflPresenter() {}; +File change history is stored at: <https://github.com/mantidproject/mantid>. +Code Documentation is available at: <http://doxygen.mantidproject.org> +*/ +class IReflPresenter { +public: + virtual ~IReflPresenter(){}; - enum Flag - { - SaveFlag, - SaveAsFlag, - AppendRowFlag, - PrependRowFlag, - DeleteRowFlag, - ProcessFlag, - GroupRowsFlag, - OpenTableFlag, - NewTableFlag, - TableUpdatedFlag, - ExpandSelectionFlag, - OptionsDialogFlag, - ClearSelectedFlag, - CopySelectedFlag, - CutSelectedFlag, - PasteSelectedFlag, - SearchFlag, - TransferFlag, - ImportTableFlag, - ExportTableFlag, - PlotRowFlag, - PlotGroupFlag - }; + enum Flag { + SaveFlag, + SaveAsFlag, + AppendRowFlag, + PrependRowFlag, + DeleteRowFlag, + ProcessFlag, + GroupRowsFlag, + OpenTableFlag, + NewTableFlag, + TableUpdatedFlag, + ExpandSelectionFlag, + OptionsDialogFlag, + ClearSelectedFlag, + CopySelectedFlag, + CutSelectedFlag, + PasteSelectedFlag, + SearchFlag, + TransferFlag, + ImportTableFlag, + ExportTableFlag, + PlotRowFlag, + PlotGroupFlag + }; - //Tell the presenter something happened - virtual void notify(IReflPresenter::Flag flag) = 0; - virtual const std::map<std::string,QVariant>& options() const = 0; - virtual void setOptions(const std::map<std::string,QVariant>& options) = 0; - }; - } + // Tell the presenter something happened + virtual void notify(IReflPresenter::Flag flag) = 0; + virtual const std::map<std::string, QVariant> &options() const = 0; + virtual void setOptions(const std::map<std::string, QVariant> &options) = 0; +}; } -#endif +} +#endif \ No newline at end of file diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/QtReflMainView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/QtReflMainView.h index 390ac4cda71fbf71195758a0d9c4485fa0d13317..89d0e2ac2acedeef27d743e2c05e34a15906127d 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/QtReflMainView.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/QtReflMainView.h @@ -37,9 +37,9 @@ GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. - File change history is stored at: <https://github.com/mantidproject/mantid> - Code Documentation is available at: <http://doxygen.mantidproject.org> - */ +File change history is stored at: <https://github.com/mantidproject/mantid> +Code Documentation is available at: <http://doxygen.mantidproject.org> +*/ class DLLExport QtReflMainView : public MantidQt::API::UserSubWindow, public ReflMainView, public ProgressableView { @@ -158,4 +158,4 @@ private slots: } // namespace Mantid } // namespace CustomInterfaces -#endif /* MANTID_CUSTOMINTERFACES_QTREFLMAINVIEW_H_ */ +#endif /* MANTID_CUSTOMINTERFACES_QTREFLMAINVIEW_H_ */ \ No newline at end of file diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainView.h index 0306655ad6b84cd9ccf8807466f30b80e8499db7..592ee4424593ffbaad2bb4a456765cf2f87f76a8 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainView.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainView.h @@ -96,4 +96,4 @@ public: }; } } -#endif +#endif \ No newline at end of file diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainViewPresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainViewPresenter.h index 435e12de6e70744d9ce83f1e1aa16b3dc1db7920..21502680bae1a4383bee2428d670b44fa3f7ba04 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainViewPresenter.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Reflectometry/ReflMainViewPresenter.h @@ -154,4 +154,4 @@ private: }; } } -#endif +#endif \ No newline at end of file diff --git a/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp b/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp index 2e04453f403787db3e9dc1245a088e3391dceb62..c1d76afc4e0118edb605a3b69ed0928de1baf406 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/Iqt.cpp @@ -125,13 +125,34 @@ namespace IDA * * @param error If the algorithm failed */ - void Iqt::algorithmComplete(bool error) - { - if(error) + void Iqt::algorithmComplete(bool error) { + if (error) return; - if(m_uiForm.ckPlot->isChecked()) + // Regular Plot + if (m_uiForm.ckPlot->isChecked()) plotSpectrum(QString::fromStdString(m_pythonExportWsName)); + + // Tile plot + if (m_uiForm.ckTile->isChecked()) { + MatrixWorkspace_const_sptr outWs = + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + m_pythonExportWsName); + const size_t nPlots = outWs->getNumberHistograms(); + if (nPlots == 0) + return; + QString pyInput = "from mantidplot import newTiledWindow\n"; + pyInput += "newTiledWindow(sources=["; + for (size_t index = 0; index < nPlots; ++index) { + if (index > 0) { + pyInput += ","; + } + const std::string pyInStr = "(['" + m_pythonExportWsName + "'], " + std::to_string(index) + ")"; + pyInput += QString::fromStdString(pyInStr); + } + pyInput += "])\n"; + runPythonCode(pyInput); + } } /** diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/QtReflMainView.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/QtReflMainView.cpp index 25a627696f2f3b6611ee9adad522a0f82ae23f6a..db1de97053737b7e6d141f00f05c4d817a24e625 100644 --- a/MantidQt/CustomInterfaces/src/Reflectometry/QtReflMainView.cpp +++ b/MantidQt/CustomInterfaces/src/Reflectometry/QtReflMainView.cpp @@ -76,9 +76,9 @@ void QtReflMainView::setModel(QString name) { } /** - * Set all possible tranfer methods - * @param methods : All possible transfer methods. - */ +* Set all possible tranfer methods +* @param methods : All possible transfer methods. +*/ void QtReflMainView::setTransferMethods(const std::set<std::string> &methods) { for (auto method = methods.begin(); method != methods.end(); ++method) { ui.comboTransferMethod->addItem((*method).c_str()); @@ -498,9 +498,9 @@ std::string QtReflMainView::requestNotebookPath() { } /** - Save settings - @param options : map of user options to save - */ +Save settings +@param options : map of user options to save +*/ void QtReflMainView::saveSettings( const std::map<std::string, QVariant> &options) { QSettings settings; @@ -511,9 +511,9 @@ void QtReflMainView::saveSettings( } /** - Load settings - @param options : map of user options to load into - */ +Load settings +@param options : map of user options to load into +*/ void QtReflMainView::loadSettings(std::map<std::string, QVariant> &options) { QSettings settings; settings.beginGroup(ReflSettingsGroup); @@ -559,9 +559,9 @@ void QtReflMainView::setProgress(int progress) { } /** - Get status of checkbox which determines whether an ipython notebook is produced - @return true if a notebook should be output on process, false otherwise - */ +Get status of checkbox which determines whether an ipython notebook is produced +@return true if a notebook should be output on process, false otherwise +*/ bool QtReflMainView::getEnableNotebook() { return ui.checkEnableNotebook->isChecked(); } @@ -698,16 +698,16 @@ std::string QtReflMainView::getSearchString() const { } /** - * Clear the progress - */ +* Clear the progress +*/ void QtReflMainView::clearProgress() { ui.progressBar->reset(); } /** - * @return the transfer method selected. - */ +* @return the transfer method selected. +*/ std::string QtReflMainView::getTransferMethod() const { return ui.comboTransferMethod->currentText().toStdString(); } } // namespace CustomInterfaces -} // namespace Mantid +} // namespace Mantid \ No newline at end of file diff --git a/MantidQt/CustomInterfaces/src/Reflectometry/ReflMainViewPresenter.cpp b/MantidQt/CustomInterfaces/src/Reflectometry/ReflMainViewPresenter.cpp index 485f9a59d43e65c14f5200fe0d21b27fc0123208..8b9e8973ee92ae74ef7a27bd0016536dc488122e 100644 --- a/MantidQt/CustomInterfaces/src/Reflectometry/ReflMainViewPresenter.cpp +++ b/MantidQt/CustomInterfaces/src/Reflectometry/ReflMainViewPresenter.cpp @@ -147,9 +147,9 @@ ReflMainViewPresenter::ReflMainViewPresenter( // TODO. Select strategy. /* std::unique_ptr<CatalogConfigService> catConfigService( - makeCatalogConfigServiceAdapter(ConfigService::Instance())); + makeCatalogConfigServiceAdapter(ConfigService::Instance())); UserCatalogInfo catalogInfo( - ConfigService::Instance().getFacility().catalogInfo(), *catConfigService); + ConfigService::Instance().getFacility().catalogInfo(), *catConfigService); */ // Initialise options @@ -228,8 +228,8 @@ ReflMainViewPresenter::ReflMainViewPresenter( ReflMainViewPresenter::~ReflMainViewPresenter() {} /** - * Finds the first unused group id - */ +* Finds the first unused group id +*/ int ReflMainViewPresenter::getUnusedGroup(std::set<int> ignoredRows) const { std::set<int> usedGroups; @@ -597,11 +597,11 @@ ReflMainViewPresenter::prepareRunWorkspace(const std::string &runStr) { return AnalysisDataService::Instance().retrieveWS<Workspace>(outputName); /* Ideally, this should be executed as a child algorithm to keep the ADS tidy, - * but - * that doesn't preserve history nicely, so we'll just take care of tidying up - * in - * the event of failure. - */ + * but + * that doesn't preserve history nicely, so we'll just take care of tidying up + * in + * the event of failure. + */ IAlgorithm_sptr algPlus = AlgorithmManager::Instance().create("Plus"); algPlus->initialize(); algPlus->setProperty("LHSWorkspace", loadRun(runs[0], instrument)->name()); @@ -1323,9 +1323,9 @@ void ReflMainViewPresenter::afterReplaceHandle( } /** Returns how many rows there are in a given group - @param groupId : The id of the group to count the rows of - @returns The number of rows in the group - */ +@param groupId : The id of the group to count the rows of +@returns The number of rows in the group +*/ size_t ReflMainViewPresenter::numRowsInGroup(int groupId) const { size_t count = 0; for (int i = 0; i < m_model->rowCount(); ++i) @@ -1403,7 +1403,7 @@ void ReflMainViewPresenter::cutSelected() { } /** Paste the contents of the clipboard into the currently selected rows, or - * append new rows */ +* append new rows */ void ReflMainViewPresenter::pasteSelected() { const std::string text = m_view->getClipboard(); std::vector<std::string> lines; @@ -1548,8 +1548,8 @@ void ReflMainViewPresenter::transfer() { } /* Set the scale to 1.0 for new rows. If there's a columnHeading specified - otherwise, - it will be overwritten below. + otherwise, + it will be overwritten below. */ m_model->setData(m_model->index(rowIndex, ReflTableSchema::COL_SCALE), 1.0); auto colIndexLookup = ReflTableSchema::makeColumnNameMap(); @@ -1664,15 +1664,15 @@ void ReflMainViewPresenter::showOptionsDialog() { } /** Gets the options used by the presenter - @returns The options used by the presenter - */ +@returns The options used by the presenter +*/ const std::map<std::string, QVariant> &ReflMainViewPresenter::options() const { return m_options; } /** Sets the options used by the presenter - @param options : The new options for the presenter to use - */ +@param options : The new options for the presenter to use +*/ void ReflMainViewPresenter::setOptions( const std::map<std::string, QVariant> &options) { // Overwrite the given options @@ -1705,12 +1705,12 @@ void ReflMainViewPresenter::initOptions() { } /** - * Select and make a transfer strategy on demand based. Pick up the - *user-provided - * transfer strategy to do this. - * - * @return new TransferStrategy - */ +* Select and make a transfer strategy on demand based. Pick up the +*user-provided +* transfer strategy to do this. +* +* @return new TransferStrategy +*/ std::unique_ptr<ReflTransferStrategy> ReflMainViewPresenter::getTransferStrategy() { const std::string currentMethod = m_view->getTransferMethod(); @@ -1746,4 +1746,4 @@ ReflMainViewPresenter::getTransferStrategy() { const std::string ReflMainViewPresenter::MeasureTransferMethod = "Measurement"; const std::string ReflMainViewPresenter::LegacyTransferMethod = "Description"; } -} +} \ No newline at end of file diff --git a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py index b3d002f3236ead1c0c7535d1bf012be7101e0343..2dc3da6a51200cc1f3be7ff9ad6cfba5d0abe62c 100644 --- a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py +++ b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py @@ -93,7 +93,7 @@ class ImagingIMATTomoTests(unittest.TestCase): # In the Mantid workspaces we have the usual double/float64 values # but reconstruction tools effectively work on float32 - return data_vol.astype(dtype='float32') + return data_vol.astype('float32') def test_scale_down_errors(self): import IMAT.prep as iprep diff --git a/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5 b/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5 index 8f1721b5c127074349117f9449a69af66a2d8770..60824d46b88b9aea4dbd7c433b67f669b50200f1 100644 --- a/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5 +++ b/Testing/SystemTests/tests/analysis/reference/PG3_4866_reference.gsa.md5 @@ -1 +1 @@ -8261ed33ddc2ab2852617857621673e8 +6828b70f8518e4b96263e3faf0d0bc70 diff --git a/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5 b/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5 index b013011ae5da64e25b7405855baf0c5b3ba82167..c8d859e8aa4cecd9bf28fe995d7205c274354ccc 100644 --- a/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5 +++ b/Testing/SystemTests/tests/analysis/reference/PG3_golden.cal.md5 @@ -1 +1 @@ -fd5f2397fec8c4ff6af5c68a42ce936b +70c959be6264a3780ab5ce31a9e3711c diff --git a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlay.nxs.md5 b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlay.nxs.md5 index c1179a49b5d6f83d21172e92c434efa03bafde4e..afb48b3abc56b4f3592f33476a059331c0652639 100644 --- a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlay.nxs.md5 +++ b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlay.nxs.md5 @@ -1 +1 @@ -744094b86db4a744a53f5a7a87e60f6c +06bad59bb4095b0c7ba8c98a9111f639 diff --git a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlayAndTimeShifts.nxs.md5 b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlayAndTimeShifts.nxs.md5 index cdf5a103e3b3bd29903e883dbc8ed4361419fbf5..f727452e67097e1d64ec1636c5673a9d20dbd2ae 100644 --- a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlayAndTimeShifts.nxs.md5 +++ b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithOverlayAndTimeShifts.nxs.md5 @@ -1 +1 @@ -66e5cfb9114f6e7450a71032e29199bd +50477136165faff22e2b6480880ad621 diff --git a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithoutOverlay.nxs.md5 b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithoutOverlay.nxs.md5 index 4fc6ec306e8853d46771678d3f1cca3bebc75d9d..f5b4326c1912a6c102596be8ec0f8d73984ae417 100644 --- a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithoutOverlay.nxs.md5 +++ b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_AddedEventFilesWithoutOverlay.nxs.md5 @@ -1 +1 @@ -ba0b31c40025c4a89cb4a2ab2f374146 +e0daf21666ebb113591ae2f66d1ecd30 diff --git a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_Merged_Reduction.nxs.md5 b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_Merged_Reduction.nxs.md5 index 4482087905162b17aed2436fe25f595bea35a8d9..31ba4555d70d41650ae4ca88c134283dcc320e34 100644 --- a/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_Merged_Reduction.nxs.md5 +++ b/Testing/SystemTests/tests/analysis/reference/SANS2DTUBES_Merged_Reduction.nxs.md5 @@ -1 +1 @@ -0e5a84b8ee0fc24a80cf03a34ee14435 +e23450bf4cf9a4a3306b6b86993dc2d2 diff --git a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.cxx b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.cxx index 7a60a3852bef3d1482bc4c830864cd7eaeed2067..0f8d24d273b32d82510de53c4679d1aa81080c65 100644 --- a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.cxx +++ b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.cxx @@ -6,6 +6,7 @@ #include "vtkUnstructuredGridAlgorithm.h" #include "vtkUnstructuredGrid.h" #include "vtkFieldData.h" +#include "vtkSmartPointer.h" #include "MantidGeometry/MDGeometry/MDGeometryXMLDefinitions.h" #include "MantidVatesAPI/ADSWorkspaceProvider.h" @@ -22,19 +23,15 @@ using namespace Mantid::VATES; vtkStandardNewMacro(vtkSplatterPlot) -/// Constructor -vtkSplatterPlot::vtkSplatterPlot() : m_numberPoints(0), m_topPercentile(0.0), - m_presenter(NULL), m_wsName(""), m_time(0) -{ + /// Constructor + vtkSplatterPlot::vtkSplatterPlot() + : m_numberPoints(0), m_topPercentile(0.0), m_wsName(""), m_time(0) { this->SetNumberOfInputPorts(1); this->SetNumberOfOutputPorts(1); } /// Destructor -vtkSplatterPlot::~vtkSplatterPlot() -{ - delete m_presenter; -} +vtkSplatterPlot::~vtkSplatterPlot() {} /** * Sets number of points. @@ -48,8 +45,7 @@ void vtkSplatterPlot::SetNumberOfPoints(int nPoints) if(m_numberPoints != temp) { m_numberPoints = temp; - if (NULL != m_presenter) - { + if (nullptr != m_presenter) { m_presenter->SetNumberOfPoints(m_numberPoints); } this->Modified(); @@ -68,8 +64,7 @@ void vtkSplatterPlot::SetTopPercentile(double topPercentile) if (m_topPercentile != topPercentile) { m_topPercentile = topPercentile; - if (NULL != m_presenter) - { + if (nullptr != m_presenter) { m_presenter->SetPercentToUse(m_topPercentile); } this->Modified(); @@ -90,11 +85,11 @@ int vtkSplatterPlot::RequestData(vtkInformation *, vtkInformationVector **inputVector, vtkInformationVector *outputVector) { - if (NULL != m_presenter) - { + if (nullptr != m_presenter) { // Get the info objects vtkInformation *outInfo = outputVector->GetInformationObject(0); - vtkDataSet *output = vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); + vtkDataSet *output = + vtkDataSet::SafeDownCast(outInfo->Get(vtkDataObject::DATA_OBJECT())); if (outInfo->Has(vtkStreamingDemandDrivenPipeline::UPDATE_TIME_STEP())) { @@ -109,7 +104,7 @@ int vtkSplatterPlot::RequestData(vtkInformation *, FilterUpdateProgressAction<vtkSplatterPlot> drawUpdateProgress(this, "Drawing..."); - vtkDataSet* product = m_presenter->create(drawUpdateProgress); + auto product = m_presenter->create(drawUpdateProgress); // Extract the relevant metadata from the underlying source m_presenter->setMetadata(input->GetFieldData(), product); @@ -135,12 +130,11 @@ int vtkSplatterPlot::RequestInformation(vtkInformation *, vtkInformationVector **inputVector, vtkInformationVector *) { - if (NULL == m_presenter) - { + if (nullptr == m_presenter) { std::string scalarName = "signal"; - m_presenter = new vtkSplatterPlotFactory(ThresholdRange_scptr(new NoThresholdRange), - scalarName, m_numberPoints, - m_topPercentile); + m_presenter = Mantid::Kernel::make_unique<vtkSplatterPlotFactory>( + boost::make_shared<NoThresholdRange>(), scalarName, m_numberPoints, + m_topPercentile); // Get the info objects vtkInformation *inInfo = inputVector[0]->GetInformationObject(0); @@ -179,12 +173,10 @@ void vtkSplatterPlot::updateAlgorithmProgress(double progress, const std::string */ double vtkSplatterPlot::GetMinValue() { - if (NULL == m_presenter) - { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMinValue(); } catch (std::runtime_error &) @@ -200,12 +192,10 @@ double vtkSplatterPlot::GetMinValue() */ double vtkSplatterPlot::GetMaxValue() { - if (NULL == m_presenter) - { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMaxValue(); } catch (std::runtime_error &) @@ -220,12 +210,10 @@ double vtkSplatterPlot::GetMaxValue() */ const char* vtkSplatterPlot::GetInstrument() { - if (NULL == m_presenter) - { + if (nullptr == m_presenter) { return ""; } - try - { + try { return m_presenter->getInstrument().c_str(); } catch (std::runtime_error &) diff --git a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h index f44ef1e8f50c427e07569f932631a1cddd0c8860..775505053bbc012a666fd5629ae908a6a6f46f6d 100644 --- a/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h +++ b/Vates/ParaviewPlugins/ParaViewFilters/SplatterPlot/vtkSplatterPlot.h @@ -1,6 +1,7 @@ #ifndef _vtkSplatterPlot_h #define _vtkSplatterPlot_h +#include "MantidKernel/make_unique.h" #include "vtkUnstructuredGridAlgorithm.h" #include <string> @@ -41,7 +42,7 @@ private: /// Percent of densest boxes to keep double m_topPercentile; /// MVP presenter - Mantid::VATES::vtkSplatterPlotFactory *m_presenter; + std::unique_ptr<Mantid::VATES::vtkSplatterPlotFactory> m_presenter; /// Holder for the workspace name std::string m_wsName; /// Time. diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx index fa7d6097eb44d07a5f83a5858725cbb64c6134a3..d40a192624ef8e4575dd6196a7f9c6c601c185b2 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx +++ b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.cxx @@ -12,6 +12,7 @@ #include "vtkPVInformationKeys.h" #include "vtkBox.h" #include "vtkUnstructuredGrid.h" +#include "vtkNew.h" #include "MantidVatesAPI/vtkMDHexFactory.h" #include "MantidVatesAPI/vtkMDQuadFactory.h" @@ -28,23 +29,16 @@ using namespace Mantid::VATES; using Mantid::Geometry::IMDDimension_sptr; using Mantid::Geometry::IMDDimension_sptr; - -vtkMDEWNexusReader::vtkMDEWNexusReader() : - m_presenter(NULL), - m_loadInMemory(false), - m_depth(1), - m_time(0), - m_normalization(NoNormalization) -{ +vtkMDEWNexusReader::vtkMDEWNexusReader() + : m_loadInMemory(false), m_depth(1), m_time(0), + m_normalization(NoNormalization) { this->FileName = NULL; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); - } vtkMDEWNexusReader::~vtkMDEWNexusReader() { - delete m_presenter; this->SetFileName(0); } @@ -91,18 +85,13 @@ void vtkMDEWNexusReader::SetInMemory(bool inMemory) Gets the geometry xml from the workspace. Allows object panels to configure themeselves. @return geometry xml const * char reference. */ -const char* vtkMDEWNexusReader::GetInputGeometryXML() -{ - if(m_presenter == NULL) - { +const char *vtkMDEWNexusReader::GetInputGeometryXML() { + if (m_presenter == nullptr) { return ""; } - try - { + try { return m_presenter->getGeometryXML().c_str(); - } - catch(std::runtime_error&) - { + } catch (std::runtime_error &) { return ""; } } @@ -133,22 +122,27 @@ int vtkMDEWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf FilterUpdateProgressAction<vtkMDEWNexusReader> loadingProgressAction(this, "Loading..."); FilterUpdateProgressAction<vtkMDEWNexusReader> drawingProgressAction(this, "Drawing..."); - ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange()); - vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, m_normalization); - vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, m_normalization); - vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, m_normalization); - - hexahedronFactory->SetSuccessor(quadFactory); - quadFactory->SetSuccessor(lineFactory); + ThresholdRange_scptr thresholdRange = + boost::make_shared<IgnoreZerosThresholdRange>(); + auto hexahedronFactory = Mantid::Kernel::make_unique<vtkMDHexFactory>( + thresholdRange, m_normalization); + auto quadFactory = Mantid::Kernel::make_unique<vtkMDQuadFactory>( + thresholdRange, m_normalization); + auto lineFactory = Mantid::Kernel::make_unique<vtkMDLineFactory>( + thresholdRange, m_normalization); + + hexahedronFactory->SetSuccessor(std::move(quadFactory)); + quadFactory->SetSuccessor(std::move(lineFactory)); hexahedronFactory->setTime(m_time); - vtkDataSet* product = m_presenter->execute(hexahedronFactory, loadingProgressAction, drawingProgressAction); - + vtkDataSet *product = m_presenter->execute( + hexahedronFactory.get(), loadingProgressAction, drawingProgressAction); + //-------------------------------------------------------- Corrects problem whereby boundaries not set propertly in PV. - vtkBox* box = vtkBox::New(); + vtkNew<vtkBox> box; box->SetBounds(product->GetBounds()); - vtkPVClipDataSet* clipper = vtkPVClipDataSet::New(); + vtkNew<vtkPVClipDataSet> clipper; clipper->SetInputData(0, product); - clipper->SetClipFunction(box); + clipper->SetClipFunction(box.GetPointer()); clipper->SetInsideOut(true); clipper->Update(); vtkDataSet* clipperOutput = clipper->GetOutput(); @@ -159,20 +153,20 @@ int vtkMDEWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf output->ShallowCopy(clipperOutput); m_presenter->setAxisLabels(output); - - clipper->Delete(); return 1; } int vtkMDEWNexusReader::RequestInformation( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - if(m_presenter == NULL) - { - m_presenter = new MDEWEventNexusLoadingPresenter(new MDLoadingViewAdapter<vtkMDEWNexusReader>(this), FileName); + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { + if (m_presenter == nullptr) { + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDEWNexusReader>>( + this); + m_presenter = Mantid::Kernel::make_unique<MDEWEventNexusLoadingPresenter>( + std::move(view), FileName); m_presenter->executeLoadMetadata(); setTimeRange(outputVector); } @@ -186,7 +180,10 @@ void vtkMDEWNexusReader::PrintSelf(ostream& os, vtkIndent indent) int vtkMDEWNexusReader::CanReadFile(const char* fname) { - MDEWEventNexusLoadingPresenter temp(new MDLoadingViewAdapter<vtkMDEWNexusReader>(this), fname); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDEWNexusReader>>( + this); + MDEWEventNexusLoadingPresenter temp(std::move(view), fname); return temp.canReadFile(); } diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h index 2bb5d1ff675091d08a4a008012daddb9c4f29261..7a48f813c5d718c4fbb09a5e41c3a5d755d8f524 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h +++ b/Vates/ParaviewPlugins/ParaViewReaders/MDEWNexusReader/vtkMDEWNexusReader.h @@ -4,6 +4,7 @@ #include "MantidVatesAPI/Normalization.h" #include "MantidVatesAPI/MDEWEventNexusLoadingPresenter.h" #include "MantidKernel/MultiThreaded.h" +#include "MantidKernel/make_unique.h" class vtkImplicitFunction; // cppcheck-suppress class_X_Y @@ -57,7 +58,7 @@ private: char *FileName; /// Controller/Presenter. - Mantid::VATES::MDEWEventNexusLoadingPresenter* m_presenter; + std::unique_ptr<Mantid::VATES::MDEWEventNexusLoadingPresenter> m_presenter; /// Flag indicating that file loading algorithm should attempt to fully load the file into memory. bool m_loadInMemory; diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx b/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx index c781ebe3bf3eac17f1056065fe625678b245eb4e..8359d2bd428e9ffca1bb46de346f16cde8639300 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx +++ b/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.cxx @@ -25,23 +25,15 @@ vtkStandardNewMacro(vtkMDHWNexusReader) using namespace Mantid::VATES; using Mantid::Geometry::IMDDimension_sptr; -vtkMDHWNexusReader::vtkMDHWNexusReader() : - m_presenter(NULL), - m_loadInMemory(false), - m_depth(1), - m_time(0), - m_normalizationOption(AutoSelect) -{ +vtkMDHWNexusReader::vtkMDHWNexusReader() + : m_loadInMemory(false), m_depth(1), m_time(0), + m_normalizationOption(AutoSelect) { this->FileName = NULL; this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } -vtkMDHWNexusReader::~vtkMDHWNexusReader() -{ - delete m_presenter; - this->SetFileName(0); -} +vtkMDHWNexusReader::~vtkMDHWNexusReader() { this->SetFileName(0); } void vtkMDHWNexusReader::SetDepth(int depth) { @@ -85,18 +77,13 @@ void vtkMDHWNexusReader::SetInMemory(bool inMemory) * Gets the geometry xml from the workspace. Allows object panels to configure themeselves. * @return geometry xml const * char reference. */ -const char* vtkMDHWNexusReader::GetInputGeometryXML() -{ - if(m_presenter == NULL) - { +const char *vtkMDHWNexusReader::GetInputGeometryXML() { + if (m_presenter == nullptr) { return ""; } - try - { + try { return m_presenter->getGeometryXML().c_str(); - } - catch(std::runtime_error&) - { + } catch (std::runtime_error &) { return ""; } } @@ -128,19 +115,23 @@ int vtkMDHWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf FilterUpdateProgressAction<vtkMDHWNexusReader> loadingProgressAction(this, "Loading..."); FilterUpdateProgressAction<vtkMDHWNexusReader> drawingProgressAction(this, "Drawing..."); - ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange()); + ThresholdRange_scptr thresholdRange = + boost::make_shared<IgnoreZerosThresholdRange>(); // Will attempt to handle drawing in 4D case and then in 3D case // if that fails. - vtkMDHistoHexFactory* successor = new vtkMDHistoHexFactory(thresholdRange, m_normalizationOption); - vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, m_normalizationOption, m_time); - factory->SetSuccessor(successor); + auto successor = Mantid::Kernel::make_unique<vtkMDHistoHexFactory>( + thresholdRange, m_normalizationOption); + auto factory = + Mantid::Kernel::make_unique<vtkMDHistoHex4DFactory<TimeToTimeStep>>( + thresholdRange, m_normalizationOption, m_time); + factory->SetSuccessor(std::move(successor)); + + auto product = m_presenter->execute(factory.get(), loadingProgressAction, + drawingProgressAction); - vtkDataSet* product = m_presenter->execute(factory, loadingProgressAction, drawingProgressAction); - vtkDataSet* output = vtkDataSet::GetData(outInfo); output->ShallowCopy(product); - product->Delete(); try { @@ -158,36 +149,33 @@ int vtkMDHWNexusReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInf } int vtkMDHWNexusReader::RequestInformation( - vtkInformation *vtkNotUsed(request), - vtkInformationVector **vtkNotUsed(inputVector), - vtkInformationVector *outputVector) -{ - if(m_presenter == NULL) - { - m_presenter = new MDHWNexusLoadingPresenter(new MDLoadingViewAdapter<vtkMDHWNexusReader>(this), FileName); + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { + if (m_presenter == nullptr) { + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDHWNexusReader>>( + this); + m_presenter = Mantid::Kernel::make_unique<MDHWNexusLoadingPresenter>( + std::move(view), FileName); } - if (m_presenter == NULL) - { - // updater information has been called prematurely. We will reexecute once all attributes are setup. + if (m_presenter == nullptr) { + // updater information has been called prematurely. We will reexecute once + // all attributes are setup. return 1; } - if(!m_presenter->canReadFile()) - { - vtkErrorMacro(<<"Cannot fetch the specified workspace from Mantid ADS."); + if (!m_presenter->canReadFile()) { + vtkErrorMacro(<< "Cannot fetch the specified workspace from Mantid ADS."); return 0; } - + m_presenter->executeLoadMetadata(); setTimeRange(outputVector); - MDHWNexusLoadingPresenter *castPresenter = - dynamic_cast<MDHWNexusLoadingPresenter *>(m_presenter); - if (castPresenter) { - std::vector<int> extents = castPresenter->getExtents(); - outputVector->GetInformationObject(0) - ->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), &extents[0], - static_cast<int>(extents.size())); - } + std::vector<int> extents = m_presenter->getExtents(); + outputVector->GetInformationObject(0) + ->Set(vtkStreamingDemandDrivenPipeline::WHOLE_EXTENT(), &extents[0], + static_cast<int>(extents.size())); return 1; } @@ -198,7 +186,10 @@ void vtkMDHWNexusReader::PrintSelf(ostream& os, vtkIndent indent) int vtkMDHWNexusReader::CanReadFile(const char* fname) { - MDHWNexusLoadingPresenter temp(new MDLoadingViewAdapter<vtkMDHWNexusReader>(this), fname); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDHWNexusReader>>( + this); + MDHWNexusLoadingPresenter temp(std::move(view), fname); return temp.canReadFile(); } diff --git a/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h b/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h index 12861a5f883f738df2bf70b3adbc66e9ef5725e0..f92716b4a30121963cda82974f5fcfc6d3df5961 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h +++ b/Vates/ParaviewPlugins/ParaViewReaders/MDHWNexusReader/vtkMDHWNexusReader.h @@ -6,6 +6,7 @@ #include "MantidVatesAPI/MDHWNexusLoadingPresenter.h" #include "MantidVatesAPI/Normalization.h" #include "MantidKernel/MultiThreaded.h" +#include "MantidKernel/make_unique.h" class vtkImplicitFunction; // cppcheck-suppress class_X_Y @@ -59,7 +60,7 @@ private: char *FileName; /// Controller/Presenter. - Mantid::VATES::MDHWNexusLoadingPresenter* m_presenter; + std::unique_ptr<Mantid::VATES::MDHWNexusLoadingPresenter> m_presenter; /// Flag indicating that file loading algorithm should attempt to fully load the file into memory. bool m_loadInMemory; diff --git a/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.cxx b/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.cxx index 0fbc7e02b3e8f92313db2f4eadc4cf7191f4f414..e379c05f3e833a6c4398279bc89e5826499beb60 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.cxx +++ b/Vates/ParaviewPlugins/ParaViewReaders/NexusPeaksReader/vtkNexusPeaksReader.cxx @@ -11,6 +11,8 @@ #include <vtkSphereSource.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> +#include <vtkNew.h> +#include <vtkSmartPointer.h> #include "MantidVatesAPI/FilteringUpdateProgressAction.h" #include "MantidVatesAPI/vtkPeakMarkerFactory.h" @@ -80,14 +82,16 @@ int vtkNexusPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkIn case 3: dim = vtkPeakMarkerFactory::Peak_in_HKL; break; default: dim = vtkPeakMarkerFactory::Peak_in_Q_lab; break; } - vtkPeakMarkerFactory * p_peakFactory = new vtkPeakMarkerFactory("peaks", dim); + auto p_peakFactory = + Mantid::Kernel::make_unique<vtkPeakMarkerFactory>("peaks", dim); p_peakFactory->initialize(m_PeakWS); FilterUpdateProgressAction<vtkNexusPeaksReader> drawingProgressUpdate(this, "Drawing..."); - vtkDataSet * structuredMesh = p_peakFactory->create(drawingProgressUpdate); + auto structuredMesh = vtkSmartPointer<vtkDataSet>::Take( + p_peakFactory->create(drawingProgressUpdate)); - vtkPolyDataAlgorithm* shapeMarker = NULL; + vtkSmartPointer<vtkPolyDataAlgorithm> shapeMarker; if(p_peakFactory->isPeaksWorkspaceIntegrated()) { double peakRadius = p_peakFactory->getIntegrationRadius(); @@ -96,28 +100,28 @@ int vtkNexusPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkIn sphere->SetRadius(peakRadius); sphere->SetPhiResolution(resolution); sphere->SetThetaResolution(resolution); - shapeMarker = sphere; + shapeMarker.TakeReference(sphere); } else { - vtkAxes* axis = vtkAxes::New(); + vtkNew<vtkAxes> axis; axis->SymmetricOn(); axis->SetScaleFactor(m_uintPeakMarkerSize); - vtkTransform* transform = vtkTransform::New(); + vtkNew<vtkTransform> transform; const double rotationDegrees = 45; transform->RotateX(rotationDegrees); transform->RotateY(rotationDegrees); transform->RotateZ(rotationDegrees); vtkTransformPolyDataFilter* transformFilter = vtkTransformPolyDataFilter::New(); - transformFilter->SetTransform(transform); + transformFilter->SetTransform(transform.GetPointer()); transformFilter->SetInputConnection(axis->GetOutputPort()); transformFilter->Update(); - shapeMarker = transformFilter; + shapeMarker.TakeReference(transformFilter); } - vtkPVGlyphFilter *glyphFilter = vtkPVGlyphFilter::New(); + vtkNew<vtkPVGlyphFilter> glyphFilter; glyphFilter->SetInputData(structuredMesh); glyphFilter->SetSourceConnection(shapeMarker->GetOutputPort()); glyphFilter->Update(); @@ -125,8 +129,6 @@ int vtkNexusPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkIn output->ShallowCopy(glyphed); - glyphFilter->Delete(); - return 1; } diff --git a/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.cxx b/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.cxx index 4de24194283e2f1cc8f93fb920b7736279b894ae..24a9ac5b7874f78cf61f223c5ed866021d6bccba 100644 --- a/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.cxx +++ b/Vates/ParaviewPlugins/ParaViewReaders/PeaksReader/vtkPeaksReader.cxx @@ -11,6 +11,8 @@ #include <vtkSphereSource.h> #include <vtkTransform.h> #include <vtkTransformPolyDataFilter.h> +#include <vtkNew.h> +#include <vtkSmartPointer.h> #include "MantidVatesAPI/FilteringUpdateProgressAction.h" #include "MantidVatesAPI/vtkPeakMarkerFactory.h" @@ -79,14 +81,15 @@ int vtkPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInforma case 3: dim = vtkPeakMarkerFactory::Peak_in_HKL; break; default: dim = vtkPeakMarkerFactory::Peak_in_Q_lab; break; } - vtkPeakMarkerFactory * p_peakFactory = new vtkPeakMarkerFactory("peaks", dim); + auto p_peakFactory = + Mantid::Kernel::make_unique<vtkPeakMarkerFactory>("peaks", dim); p_peakFactory->initialize(m_PeakWS); FilterUpdateProgressAction<vtkPeaksReader> drawingProgressUpdate(this, "Drawing..."); vtkDataSet * structuredMesh = p_peakFactory->create(drawingProgressUpdate); - vtkPolyDataAlgorithm* shapeMarker = NULL; + vtkSmartPointer<vtkPolyDataAlgorithm> shapeMarker; if(p_peakFactory->isPeaksWorkspaceIntegrated()) { double peakRadius = p_peakFactory->getIntegrationRadius(); @@ -95,28 +98,28 @@ int vtkPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInforma sphere->SetRadius(peakRadius); sphere->SetPhiResolution(resolution); sphere->SetThetaResolution(resolution); - shapeMarker = sphere; + shapeMarker.TakeReference(sphere); } else { - vtkAxes* axis = vtkAxes::New(); + vtkNew<vtkAxes> axis; axis->SymmetricOn(); axis->SetScaleFactor(m_uintPeakMarkerSize); - vtkTransform* transform = vtkTransform::New(); + vtkNew<vtkTransform> transform; const double rotationDegrees = 45; transform->RotateX(rotationDegrees); transform->RotateY(rotationDegrees); transform->RotateZ(rotationDegrees); vtkTransformPolyDataFilter* transformFilter = vtkTransformPolyDataFilter::New(); - transformFilter->SetTransform(transform); + transformFilter->SetTransform(transform.GetPointer()); transformFilter->SetInputConnection(axis->GetOutputPort()); transformFilter->Update(); - shapeMarker = transformFilter; + shapeMarker.TakeReference(transformFilter); } - vtkPVGlyphFilter *glyphFilter = vtkPVGlyphFilter::New(); + vtkNew<vtkPVGlyphFilter> glyphFilter; glyphFilter->SetInputData(structuredMesh); glyphFilter->SetSourceConnection(shapeMarker->GetOutputPort()); glyphFilter->Update(); @@ -124,8 +127,6 @@ int vtkPeaksReader::RequestData(vtkInformation * vtkNotUsed(request), vtkInforma output->ShallowCopy(glyphed); - glyphFilter->Delete(); - return 1; } diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx index 8efd3d1c49054489709171495ddd94cbf2b4ed1a..663cea6977e02c0cee3aa9caf515c33706e765ca 100644 --- a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx +++ b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.cxx @@ -9,6 +9,7 @@ #include "vtkUnstructuredGridAlgorithm.h" #include "vtkUnstructuredGrid.h" #include "vtkStreamingDemandDrivenPipeline.h" +#include "vtkNew.h" #include "MantidVatesAPI/BoxInfo.h" #include "MantidAPI/IMDWorkspace.h" @@ -29,18 +30,15 @@ using namespace Mantid::VATES; vtkStandardNewMacro(vtkMDEWSource) -/// Constructor -vtkMDEWSource::vtkMDEWSource() : m_wsName(""), m_depth(1000), m_time(0), m_presenter(NULL), m_normalization(AutoSelect) -{ + /// Constructor + vtkMDEWSource::vtkMDEWSource() + : m_wsName(""), m_depth(1000), m_time(0), m_normalization(AutoSelect) { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } /// Destructor -vtkMDEWSource::~vtkMDEWSource() -{ - delete m_presenter; -} +vtkMDEWSource::~vtkMDEWSource() {} /* Setter for the recursion depth @@ -70,21 +68,17 @@ void vtkMDEWSource::SetWsName(std::string name) } /** - Gets the geometry xml from the workspace. Allows object panels to configure themeselves. + Gets the geometry xml from the workspace. Allows object panels to configure + themeselves. @return geometry xml const * char reference. */ -const char* vtkMDEWSource::GetInputGeometryXML() -{ - if(m_presenter == NULL) - { +const char *vtkMDEWSource::GetInputGeometryXML() { + if (m_presenter == nullptr) { return ""; } - try - { + try { return m_presenter->getGeometryXML().c_str(); - } - catch(std::runtime_error&) - { + } catch (std::runtime_error &) { return ""; } } @@ -94,60 +88,45 @@ const char* vtkMDEWSource::GetInputGeometryXML() * workspace. * @return the special coordinates value */ -int vtkMDEWSource::GetSpecialCoordinates() -{ - if (NULL == m_presenter) - { +int vtkMDEWSource::GetSpecialCoordinates() { + if (nullptr == m_presenter) { return 0; } - try - { + try { return m_presenter->getSpecialCoordinates(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0; } } /** - * Gets the minimum value of the data associated with the + * Gets the minimum value of the data associated with the * workspace. * @return The minimum value of the workspace data. */ -double vtkMDEWSource::GetMinValue() -{ - if (NULL == m_presenter) - { +double vtkMDEWSource::GetMinValue() { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMinValue(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0; } } /** - * Gets the maximum value of the data associated with the + * Gets the maximum value of the data associated with the * workspace. * @return The maximum value of the workspace data. */ -double vtkMDEWSource::GetMaxValue() -{ - if (NULL == m_presenter) - { +double vtkMDEWSource::GetMaxValue() { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMaxValue(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0; } } @@ -156,18 +135,13 @@ double vtkMDEWSource::GetMaxValue() * Gets the (first) instrument which is associated with the workspace. * @return The name of the instrument. */ -const char* vtkMDEWSource::GetInstrument() -{ - if (NULL == m_presenter) - { +const char *vtkMDEWSource::GetInstrument() { + if (nullptr == m_presenter) { return ""; } - try - { + try { return m_presenter->getInstrument().c_str(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return ""; } } @@ -200,28 +174,35 @@ int vtkMDEWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf FilterUpdateProgressAction<vtkMDEWSource> loadingProgressUpdate(this, "Loading..."); FilterUpdateProgressAction<vtkMDEWSource> drawingProgressUpdate(this, "Drawing..."); - ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange()); - vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory; - vtkMDHexFactory* hexahedronFactory = new vtkMDHexFactory(thresholdRange, m_normalization); - vtkMDQuadFactory* quadFactory = new vtkMDQuadFactory(thresholdRange, m_normalization); - vtkMDLineFactory* lineFactory = new vtkMDLineFactory(thresholdRange, m_normalization); + ThresholdRange_scptr thresholdRange = + boost::make_shared<IgnoreZerosThresholdRange>(); + auto zeroDFactory = Mantid::Kernel::make_unique<vtkMD0DFactory>(); + auto hexahedronFactory = Mantid::Kernel::make_unique<vtkMDHexFactory>( + thresholdRange, m_normalization); + auto quadFactory = Mantid::Kernel::make_unique<vtkMDQuadFactory>( + thresholdRange, m_normalization); + auto lineFactory = Mantid::Kernel::make_unique<vtkMDLineFactory>( + thresholdRange, m_normalization); - hexahedronFactory->SetSuccessor(quadFactory); - quadFactory->SetSuccessor(lineFactory); - lineFactory->SetSuccessor(zeroDFactory); + hexahedronFactory->SetSuccessor(std::move(quadFactory)); + quadFactory->SetSuccessor(std::move(lineFactory)); + lineFactory->SetSuccessor(std::move(zeroDFactory)); hexahedronFactory->setTime(m_time); - vtkDataSet* product = m_presenter->execute(hexahedronFactory, loadingProgressUpdate, drawingProgressUpdate); + vtkSmartPointer<vtkDataSet> product; + product = m_presenter->execute( + hexahedronFactory.get(), loadingProgressUpdate, drawingProgressUpdate); //-------------------------------------------------------- Corrects problem whereby boundaries not set propertly in PV. - vtkBox* box = vtkBox::New(); + vtkNew<vtkBox> box; box->SetBounds(product->GetBounds()); - vtkPVClipDataSet* clipper = vtkPVClipDataSet::New(); + vtkNew<vtkPVClipDataSet> clipper; clipper->SetInputData(product); - clipper->SetClipFunction(box); + clipper->SetClipFunction(box.GetPointer()); clipper->SetInsideOut(true); clipper->Update(); - vtkDataSet* clipperOutput = clipper->GetOutput(); + auto clipperOutput = + vtkSmartPointer<vtkDataSet>::Take(clipper->GetOutput()); //-------------------------------------------------------- vtkUnstructuredGrid *output = vtkUnstructuredGrid::SafeDownCast( @@ -241,26 +222,30 @@ int vtkMDEWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf m_presenter->setDefaultCOBandBoundaries(output); } m_presenter->setAxisLabels(output); - - clipper->Delete(); } return 1; } +// clang-format off GCC_DIAG_OFF(strict-aliasing) -int vtkMDEWSource::RequestInformation(vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) -{ - if(m_presenter == NULL && !m_wsName.empty()) - { - m_presenter = new MDEWInMemoryLoadingPresenter(new MDLoadingViewAdapter<vtkMDEWSource>(this), new ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>, m_wsName); - if(!m_presenter->canReadFile()) - { - vtkErrorMacro(<<"Cannot fetch the specified workspace from Mantid ADS."); - } - else - { - // If the MDEvent workspace has had top level splitting applied to it, then use the a depth of 1 - if (auto split = Mantid::VATES::findRecursionDepthForTopLevelSplitting(m_wsName)) { +// clang-format on +int vtkMDEWSource::RequestInformation( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { + if (m_presenter == NULL && !m_wsName.empty()) { + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDEWSource>>(this); + m_presenter = Mantid::Kernel::make_unique<MDEWInMemoryLoadingPresenter>( + std::move(view), + new ADSWorkspaceProvider<Mantid::API::IMDEventWorkspace>, m_wsName); + if (!m_presenter->canReadFile()) { + vtkErrorMacro(<< "Cannot fetch the specified workspace from Mantid ADS."); + } else { + // If the MDEvent workspace has had top level splitting applied to it, + // then use the a depth of 1 + if (auto split = + Mantid::VATES::findRecursionDepthForTopLevelSplitting(m_wsName)) { SetDepth(split.get()); } @@ -337,21 +322,16 @@ void vtkMDEWSource::updateAlgorithmProgress(double progress, const std::string& /* Getter for the workspace type name. */ -char* vtkMDEWSource::GetWorkspaceTypeName() -{ - if(m_presenter == NULL) - { - return const_cast<char*>(""); +char *vtkMDEWSource::GetWorkspaceTypeName() { + if (m_presenter == nullptr) { + return const_cast<char *>(""); } - try - { - //Forward request on to MVP presenter + try { + // Forward request on to MVP presenter typeName = m_presenter->getWorkspaceTypeName(); - return const_cast<char*>(typeName.c_str()); - } - catch(std::runtime_error&) - { - return const_cast<char*>(""); + return const_cast<char *>(typeName.c_str()); + } catch (std::runtime_error &) { + return const_cast<char *>(""); } } diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h index fdde75d5a911e18b92425c24383a47b69f60c0cd..dcc313013b22bce3d79721c360b1511f1d4e22e2 100644 --- a/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h +++ b/Vates/ParaviewPlugins/ParaViewSources/MDEWSource/vtkMDEWSource.h @@ -2,6 +2,7 @@ #define _vtkMDEWSource_h #include "vtkUnstructuredGridAlgorithm.h" +#include "MantidKernel/make_unique.h" #include "MantidVatesAPI/Normalization.h" #include "MantidVatesAPI/vtkDataSetFactory.h" #include <string> @@ -95,7 +96,7 @@ private: double m_time; /// MVP presenter. - Mantid::VATES::MDLoadingPresenter* m_presenter; + std::unique_ptr<Mantid::VATES::MDLoadingPresenter> m_presenter; /// Cached typename. std::string typeName; diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx index 9d878c5079651f8ecae76758f8030094a3eb7bf7..34ab784dd92cf2c8a62299f532cc9ee8490b9fb3 100644 --- a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx +++ b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.cxx @@ -26,18 +26,15 @@ using namespace Mantid::VATES; vtkStandardNewMacro(vtkMDHWSource) -/// Constructor -vtkMDHWSource::vtkMDHWSource() : m_wsName(""), m_time(0), m_presenter(NULL), m_normalizationOption(AutoSelect) -{ + /// Constructor + vtkMDHWSource::vtkMDHWSource() + : m_wsName(""), m_time(0), m_normalizationOption(AutoSelect) { this->SetNumberOfInputPorts(0); this->SetNumberOfOutputPorts(1); } /// Destructor -vtkMDHWSource::~vtkMDHWSource() -{ - delete m_presenter; -} +vtkMDHWSource::~vtkMDHWSource() {} /* Setter for the workspace name. @@ -56,18 +53,13 @@ void vtkMDHWSource::SetWsName(std::string name) Gets the geometry xml from the workspace. Allows object panels to configure themeselves. @return geometry xml const * char reference. */ -const char* vtkMDHWSource::GetInputGeometryXML() -{ - if(m_presenter == NULL) - { +const char *vtkMDHWSource::GetInputGeometryXML() { + if (m_presenter == nullptr) { return ""; } - try - { + try { return m_presenter->getGeometryXML().c_str(); - } - catch(std::runtime_error&) - { + } catch (std::runtime_error &) { return ""; } } @@ -77,18 +69,13 @@ const char* vtkMDHWSource::GetInputGeometryXML() * workspace. * @return the special coordinates value */ -int vtkMDHWSource::GetSpecialCoordinates() -{ - if (NULL == m_presenter) - { +int vtkMDHWSource::GetSpecialCoordinates() { + if (nullptr == m_presenter) { return 0; } - try - { + try { return m_presenter->getSpecialCoordinates(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0; } } @@ -98,18 +85,13 @@ int vtkMDHWSource::GetSpecialCoordinates() * workspace. * @return The minimum value of the workspace data. */ -double vtkMDHWSource::GetMinValue() -{ - if (NULL == m_presenter) - { +double vtkMDHWSource::GetMinValue() { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMinValue(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0.0; } } @@ -119,18 +101,13 @@ double vtkMDHWSource::GetMinValue() * workspace. * @return The maximum value of the workspace data. */ -double vtkMDHWSource::GetMaxValue() -{ - if (NULL == m_presenter) - { +double vtkMDHWSource::GetMaxValue() { + if (nullptr == m_presenter) { return 0.0; } - try - { + try { return m_presenter->getMaxValue(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return 0.0; } } @@ -139,18 +116,13 @@ double vtkMDHWSource::GetMaxValue() * Gets the (first) instrument which is associated with the workspace. * @return The name of the instrument. */ -const char* vtkMDHWSource::GetInstrument() -{ - if (NULL == m_presenter) - { +const char *vtkMDHWSource::GetInstrument() { + if (nullptr == m_presenter) { return ""; } - try - { + try { return m_presenter->getInstrument().c_str(); - } - catch (std::runtime_error &) - { + } catch (std::runtime_error &) { return ""; } } @@ -183,27 +155,33 @@ int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf FilterUpdateProgressAction<vtkMDHWSource> loadingProgressUpdate(this, "Loading..."); FilterUpdateProgressAction<vtkMDHWSource> drawingProgressUpdate(this, "Drawing..."); - ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange()); + ThresholdRange_scptr thresholdRange = + boost::make_shared<IgnoreZerosThresholdRange>(); /* Will attempt to handle drawing in 4D case and then in 3D case if that fails, and so on down to 1D */ - vtkMD0DFactory* zeroDFactory = new vtkMD0DFactory; - vtkMDHistoLineFactory* lineFactory = new vtkMDHistoLineFactory(thresholdRange, m_normalizationOption); - vtkMDHistoQuadFactory* quadFactory = new vtkMDHistoQuadFactory(thresholdRange, m_normalizationOption); - vtkMDHistoHexFactory* hexFactory = new vtkMDHistoHexFactory(thresholdRange, m_normalizationOption); - vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, m_normalizationOption, m_time); - - factory->SetSuccessor(hexFactory); - hexFactory->SetSuccessor(quadFactory); - quadFactory->SetSuccessor(lineFactory); - lineFactory->SetSuccessor(zeroDFactory); - - vtkDataSet* product = m_presenter->execute(factory, loadingProgressUpdate, drawingProgressUpdate); - + auto zeroDFactory = Mantid::Kernel::make_unique<vtkMD0DFactory>(); + auto lineFactory = Mantid::Kernel::make_unique<vtkMDHistoLineFactory>( + thresholdRange, m_normalizationOption); + auto quadFactory = Mantid::Kernel::make_unique<vtkMDHistoQuadFactory>( + thresholdRange, m_normalizationOption); + auto hexFactory = Mantid::Kernel::make_unique<vtkMDHistoHexFactory>( + thresholdRange, m_normalizationOption); + auto factory = + Mantid::Kernel::make_unique<vtkMDHistoHex4DFactory<TimeToTimeStep>>( + thresholdRange, m_normalizationOption, m_time); + + factory->SetSuccessor(std::move(hexFactory)); + hexFactory->SetSuccessor(std::move(quadFactory)); + quadFactory->SetSuccessor(std::move(lineFactory)); + lineFactory->SetSuccessor(std::move(zeroDFactory)); + + auto product = m_presenter->execute(factory.get(), loadingProgressUpdate, + drawingProgressUpdate); + vtkDataSet* output = vtkDataSet::GetData(outInfo); output->ShallowCopy(product); - product->Delete(); try { @@ -222,13 +200,16 @@ int vtkMDHWSource::RequestData(vtkInformation *, vtkInformationVector **, vtkInf return 1; } -int vtkMDHWSource::RequestInformation(vtkInformation *vtkNotUsed(request), vtkInformationVector **vtkNotUsed(inputVector), vtkInformationVector *outputVector) -{ - if(m_presenter == NULL && !m_wsName.empty()) - { - m_presenter = new MDHWInMemoryLoadingPresenter(new MDLoadingViewAdapter<vtkMDHWSource>(this), - new ADSWorkspaceProvider<Mantid::API::IMDHistoWorkspace>, - m_wsName); +int vtkMDHWSource::RequestInformation( + vtkInformation *vtkNotUsed(request), + vtkInformationVector **vtkNotUsed(inputVector), + vtkInformationVector *outputVector) { + if (m_presenter == nullptr && !m_wsName.empty()) { + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MDLoadingViewAdapter<vtkMDHWSource>>(this); + m_presenter = Mantid::Kernel::make_unique<MDHWInMemoryLoadingPresenter>( + std::move(view), + new ADSWorkspaceProvider<Mantid::API::IMDHistoWorkspace>, m_wsName); } if (m_presenter) { if (!m_presenter->canReadFile()) { @@ -238,7 +219,7 @@ int vtkMDHWSource::RequestInformation(vtkInformation *vtkNotUsed(request), vtkIn m_presenter->executeLoadMetadata(); setTimeRange(outputVector); MDHWInMemoryLoadingPresenter *castPresenter = - dynamic_cast<MDHWInMemoryLoadingPresenter *>(m_presenter); + dynamic_cast<MDHWInMemoryLoadingPresenter *>(m_presenter.get()); if (castPresenter) { std::vector<int> extents = castPresenter->getExtents(); outputVector->GetInformationObject(0) @@ -253,7 +234,6 @@ int vtkMDHWSource::RequestInformation(vtkInformation *vtkNotUsed(request), vtkIn // all attributes are setup. return 1; } - } void vtkMDHWSource::PrintSelf(ostream& os, vtkIndent indent) @@ -324,12 +304,10 @@ Getter for the workspace type name. */ char* vtkMDHWSource::GetWorkspaceTypeName() { - if(m_presenter == NULL) - { - return const_cast<char*>(""); + if (m_presenter == nullptr) { + return const_cast<char *>(""); } - try - { + try { //Forward request on to MVP presenter typeName = m_presenter->getWorkspaceTypeName(); return const_cast<char*>(typeName.c_str()); diff --git a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h index 53472e4902e8072c4aa9ac3a4447296e909d0046..3be70d5c4f061752f2797cabfff3a1b23d8b5c75 100644 --- a/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h +++ b/Vates/ParaviewPlugins/ParaViewSources/MDHWSource/vtkMDHWSource.h @@ -1,6 +1,7 @@ #ifndef _vtkMDHWSource_h #define _vtkMDHWSource_h +#include "MantidKernel/make_unique.h" #include "MantidVatesAPI/Normalization.h" #include "vtkStructuredGridAlgorithm.h" @@ -91,7 +92,7 @@ private: double m_time; /// MVP presenter. - Mantid::VATES::MDLoadingPresenter* m_presenter; + std::unique_ptr<Mantid::VATES::MDLoadingPresenter> m_presenter; /// Cached typename. std::string typeName; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h index b117f1e3b156574bdf2f83196279cb4ceadcdbff..9c43b7348cbea20d828baaba22f4b5d7699e0db0 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/EventNexusLoadingPresenter.h @@ -37,8 +37,11 @@ namespace Mantid class DLLExport EventNexusLoadingPresenter : public MDEWLoadingPresenter { public: - EventNexusLoadingPresenter(MDLoadingView* view, const std::string fileName); - virtual vtkDataSet* execute(vtkDataSetFactory* factory, ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate); + EventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view, + const std::string fileName); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, ProgressAction &loadingProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void executeLoadMetadata(); virtual bool hasTDimensionAvailable() const; virtual std::vector<double> getTimeStepValues() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h index 31ebc34dee814d96956d08deba85409735c38a0e..30fc63f6f40a4b9bf091467148ee7810bf749cb7 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWEventNexusLoadingPresenter.h @@ -38,8 +38,12 @@ namespace Mantid class DLLExport MDEWEventNexusLoadingPresenter : public MDEWLoadingPresenter { public: - MDEWEventNexusLoadingPresenter(MDLoadingView* view, const std::string fileName); - virtual vtkDataSet* execute(vtkDataSetFactory* factory, ProgressAction& rebinningProgressUpdate, ProgressAction& drawingProgressUpdate); + MDEWEventNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view, + const std::string fileName); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, + ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void executeLoadMetadata(); virtual ~MDEWEventNexusLoadingPresenter(); virtual bool canReadFile() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h index 831690601406b3dfd2686be7c2d1614b2e2ec44c..b18f925374c54638bf1391e43370b65d4cf73019 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWInMemoryLoadingPresenter.h @@ -44,8 +44,13 @@ namespace Mantid class DLLExport MDEWInMemoryLoadingPresenter : public MDEWLoadingPresenter { public: - MDEWInMemoryLoadingPresenter(MDLoadingView* view, WorkspaceProvider* repository, std::string wsName); - virtual vtkDataSet* execute(vtkDataSetFactory* factory, ProgressAction& rebinningProgressUpdate, ProgressAction& drawingProgressUpdate); + MDEWInMemoryLoadingPresenter(std::unique_ptr<MDLoadingView> view, + WorkspaceProvider *repository, + std::string wsName); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, + ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void executeLoadMetadata(); virtual ~MDEWInMemoryLoadingPresenter(); virtual bool canReadFile() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h index 7b3b1ebb2f8ba9b94b658f8ec6530b760094581e..03983bcc18134b13571f4bfd88defd6c92f77916 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDEWLoadingPresenter.h @@ -46,8 +46,8 @@ namespace Mantid class DLLExport MDEWLoadingPresenter : public MDLoadingPresenter { public: - MDEWLoadingPresenter(MDLoadingView* view); - const std::string& getGeometryXML() const; + MDEWLoadingPresenter(std::unique_ptr<MDLoadingView> view); + const std::string &getGeometryXML() const; virtual bool hasTDimensionAvailable() const; virtual std::vector<double> getTimeStepValues() const; virtual std::string getTimeStepLabel() const; @@ -61,7 +61,7 @@ namespace Mantid /*--------------------------------------------------------------------------- Common/shared operations and members for all MDEW file-type loading. ---------------------------------------------------------------------------*/ - MDLoadingView* m_view; + std::unique_ptr<MDLoadingView> m_view; Mantid::Geometry::MDGeometryBuilderXML<Mantid::Geometry::NoDimensionPolicy> xmlBuilder; Mantid::Geometry::IMDDimension_sptr tDimension; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h index 892ee4a88158fcec943a9cfd67a25a82adee626f..a80d6fd026d2af2ceee67dcc7348d25167246c26 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWInMemoryLoadingPresenter.h @@ -46,12 +46,12 @@ class vtkDataSetFactory; class DLLExport MDHWInMemoryLoadingPresenter : public MDHWLoadingPresenter { public: - MDHWInMemoryLoadingPresenter(MDLoadingView *view, + MDHWInMemoryLoadingPresenter(std::unique_ptr<MDLoadingView> view, WorkspaceProvider *repository, std::string wsName); - virtual vtkDataSet *execute(vtkDataSetFactory *factory, - ProgressAction &rebinningProgressUpdate, - ProgressAction &drawingProgressUpdate); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void executeLoadMetadata(); virtual ~MDHWInMemoryLoadingPresenter(); virtual bool canReadFile() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h index 682c7b81f0731379a4f3a96e6206cf81a9d8119a..e8777a7b7bb184df9574c674e0b4dfebf52a4ccc 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWLoadingPresenter.h @@ -45,7 +45,7 @@ Code Documentation is available at: <http://doxygen.mantidproject.org> class MDLoadingView; class DLLExport MDHWLoadingPresenter : public MDLoadingPresenter { public: - MDHWLoadingPresenter(MDLoadingView *view); + MDHWLoadingPresenter(std::unique_ptr<MDLoadingView> view); const std::string &getGeometryXML() const; virtual bool hasTDimensionAvailable() const; virtual std::vector<double> getTimeStepValues() const; @@ -65,7 +65,7 @@ protected: /*--------------------------------------------------------------------------- Common/shared operations and members for all MDHW file-type loading. ---------------------------------------------------------------------------*/ - MDLoadingView *m_view; + std::unique_ptr<MDLoadingView> m_view; Mantid::Geometry::MDGeometryBuilderXML<Mantid::Geometry::NoDimensionPolicy> xmlBuilder; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h index ab67efc78e2fec669d34fb0f9c9ab8b261585e2e..f2b3dd5983c6ea098b348483614336876eaade49 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDHWNexusLoadingPresenter.h @@ -39,11 +39,11 @@ class MDLoadingView; class DLLExport MDHWNexusLoadingPresenter : public MDHWLoadingPresenter { public: - MDHWNexusLoadingPresenter(MDLoadingView* view, + MDHWNexusLoadingPresenter(std::unique_ptr<MDLoadingView> view, const std::string fileName); - virtual vtkDataSet* execute(vtkDataSetFactory* factory, - ProgressAction& rebinningProgressUpdate, - ProgressAction& drawingProgressUpdate); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void executeLoadMetadata(); virtual ~MDHWNexusLoadingPresenter(); virtual bool canReadFile() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h index 8981ca3f844eb64d59e54cd389c49e9714b5f7d8..eb54f1c94a656400cbbddc59d65b4c9e0d0f48d5 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/MDLoadingPresenter.h @@ -52,7 +52,10 @@ namespace Mantid class DLLExport MDLoadingPresenter { public: - virtual vtkDataSet* execute(vtkDataSetFactory* factory, ProgressAction& rebinningProgressUpdate, ProgressAction& drawingProgressUpdate) = 0; + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, + ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate) = 0; virtual void executeLoadMetadata() = 0; virtual bool hasTDimensionAvailable() const = 0; virtual std::vector<double> getTimeStepValues() const = 0; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h b/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h index 2290c01f3e8cccb0234b4529c8e136ff5fa8abe1..fe5a61c391235cfb98b072c9134e9505be593d3a 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/Normalization.h @@ -42,10 +42,9 @@ typedef Mantid::signal_t (Mantid::API::IMDNode::*NormFuncIMDNodePtr)() const; /** Determine which normalization function will be called on an IMDNode */ -NormFuncIMDNodePtr -makeMDEventNormalizationFunction(VisualNormalization normalizationOption, - Mantid::API::IMDEventWorkspace const *const ws, - const bool hasMask); +NormFuncIMDNodePtr makeMDEventNormalizationFunction( + VisualNormalization normalizationOption, + Mantid::API::IMDEventWorkspace const *const ws); /** Determine which normalization function will be called on an IMDIterator of an diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h b/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h index b60e758c9be8a117096b32cf8a30f3bd7f4bc1eb..35ee070e48bdf00e587f9f59d62c95cb66dfd4bb 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/SQWLoadingPresenter.h @@ -37,8 +37,12 @@ namespace Mantid class DLLExport SQWLoadingPresenter : public MDEWLoadingPresenter { public: - SQWLoadingPresenter(MDLoadingView* view, const std::string fileName); - virtual vtkDataSet* execute(vtkDataSetFactory* factory, ProgressAction& rebinningProgressUpdate, ProgressAction& drawingProgressUpdate); + SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view, + const std::string fileName); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *factory, + ProgressAction &rebinningProgressUpdate, + ProgressAction &drawingProgressUpdate); virtual void extractMetadata(Mantid::API::IMDEventWorkspace_sptr eventWs); virtual void executeLoadMetadata(); virtual ~SQWLoadingPresenter(); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h index 5872db7286071ecbf885f853be9ce1ea3113caf3..f6490e42a4c800c25b4df6b3f126e17fc8a7ffdb 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetFactory.h @@ -6,7 +6,9 @@ #include "MantidAPI/IMDWorkspace.h" #include "MantidAPI/Workspace_fwd.h" #include "MantidKernel/System.h" +#include "MantidKernel/make_unique.h" #include "vtkDataSet.h" +#include "vtkSmartPointer.h" #include <boost/shared_ptr.hpp> #include <boost/tuple/tuple.hpp> #include <string> @@ -71,16 +73,17 @@ public: virtual ~vtkDataSetFactory()=0; /// Factory Method. Should also handle delegation to successors. - virtual vtkDataSet* create(ProgressAction&) const=0; + virtual vtkSmartPointer<vtkDataSet> create(ProgressAction &) const = 0; /// Initalize with a target workspace. virtual void initialize(Mantid::API::Workspace_sptr)=0; /// Create the product in one step. - virtual vtkDataSet* oneStepCreate(Mantid::API::Workspace_sptr,ProgressAction&); + virtual vtkSmartPointer<vtkDataSet> oneStepCreate(Mantid::API::Workspace_sptr, + ProgressAction &); /// Add a chain-of-responsibility successor to this factory. Handle case where the factory cannot render the MDWorkspace owing to its dimensionality. - virtual void SetSuccessor(vtkDataSetFactory* pSuccessor); + virtual void SetSuccessor(std::unique_ptr<vtkDataSetFactory> pSuccessor); /// Determine whether a successor factory has been provided. virtual bool hasSuccessor() const; @@ -191,9 +194,11 @@ protected: @param bExactMatch : Check for an exact match if true. @return TRUE if delegation to successors has occured. Otherwise returns false. */ - template<typename IMDWorkspaceType, size_t ExpectedNDimensions> - vtkDataSet* tryDelegatingCreation(Mantid::API::Workspace_sptr workspace, ProgressAction& progressUpdate, bool bExactMatch=true) const - { + template <typename IMDWorkspaceType, size_t ExpectedNDimensions> + vtkSmartPointer<vtkDataSet> + tryDelegatingCreation(Mantid::API::Workspace_sptr workspace, + ProgressAction &progressUpdate, + bool bExactMatch = true) const { boost::shared_ptr<IMDWorkspaceType> imdws = castAndCheck<IMDWorkspaceType, ExpectedNDimensions>(workspace, bExactMatch); if(!imdws) { @@ -207,11 +212,11 @@ protected: throw std::runtime_error(message); } } - return NULL; + return nullptr; } - /// Typedef for internal unique shared pointer for successor types. - typedef boost::shared_ptr<vtkDataSetFactory> SuccessorType; + /// Typedef for internal unique pointer for successor types. + typedef std::unique_ptr<vtkDataSetFactory> SuccessorType; vtkDataSetFactory::SuccessorType m_successor; @@ -228,7 +233,7 @@ private: }; typedef boost::shared_ptr<vtkDataSetFactory> vtkDataSetFactory_sptr; - +typedef std::unique_ptr<vtkDataSetFactory> vtkDataSetFactory_uptr; } } diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h index 827a741ddecc265d406080505c7ab408bfd64505..5bc776c701e877d2ed803c40c446cbe9e0721449 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkDataSetToPeaksFilteredDataSet.h @@ -5,6 +5,7 @@ #include "MantidKernel/V3D.h" #include "MantidAPI/IPeaksWorkspace.h" #include "MantidVatesAPI/ProgressAction.h" +#include "vtkSmartPointer.h" #include <string> class vtkUnstructuredGrid; @@ -43,7 +44,9 @@ namespace VATES class DLLExport vtkDataSetToPeaksFilteredDataSet { public: - vtkDataSetToPeaksFilteredDataSet(vtkUnstructuredGrid *input, vtkUnstructuredGrid *output); + vtkDataSetToPeaksFilteredDataSet( + vtkSmartPointer<vtkUnstructuredGrid> input, + vtkSmartPointer<vtkUnstructuredGrid> output); virtual ~vtkDataSetToPeaksFilteredDataSet(); /// Set the name of the peaks workspace void initialize(std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces, double radiusNoShape, int radiusType, int coordinateSystem); @@ -57,8 +60,8 @@ namespace VATES vtkDataSetToPeaksFilteredDataSet& operator=(const vtkDataSetToPeaksFilteredDataSet& other); std::vector<std::pair<Mantid::Kernel::V3D, double>> getPeaksInfo(std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces); void addSinglePeak(Mantid::Geometry::IPeak* peak, const Mantid::Kernel::SpecialCoordinateSystem coordinateSystem, std::vector<std::pair<Mantid::Kernel::V3D, double>>& peaksInfo); - vtkUnstructuredGrid *m_inputData; ///< Data to peak filter - vtkUnstructuredGrid *m_outputData; ///< Peak filtered data + vtkSmartPointer<vtkUnstructuredGrid> m_inputData; ///< Data to peak filter + vtkSmartPointer<vtkUnstructuredGrid> m_outputData; ///< Peak filtered data std::vector<Mantid::API::IPeaksWorkspace_sptr> m_peaksWorkspaces; ///< A list of peaks workspace names. bool m_isInitialised; ///<Flag if the filter is initialized double m_radiusNoShape; ///< The radius for peaks with no peak shape. diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h index 910fedff15bcb42d079c1dd6100e99027bdd4788..6f42cedec588e734377bb4b21423b5b11de41b28 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMD0DFactory.h @@ -45,7 +45,8 @@ namespace Mantid virtual ~vtkMD0DFactory(); /// Factory Method. - virtual vtkDataSet* create(ProgressAction& progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; virtual void initialize(Mantid::API::Workspace_sptr); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h index 56357f33e1c63e00a5e2f97d297e2f3316bd1885..88becb18f633b379d3b77926dd62a53793431b77 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHWSignalArray.h @@ -248,7 +248,7 @@ template <class Scalar> void vtkMDHWSignalArray<Scalar>::ClearLookup() { template <class Scalar> double *vtkMDHWSignalArray<Scalar>::GetTuple(vtkIdType i) { m_iterator->jumpTo(m_offset + i); - m_temporaryTuple[0] = m_iterator->getNormalizedSignalWithMask(); + m_temporaryTuple[0] = m_iterator->getNormalizedSignal(); return &m_temporaryTuple[0]; } @@ -256,7 +256,7 @@ double *vtkMDHWSignalArray<Scalar>::GetTuple(vtkIdType i) { template <class Scalar> void vtkMDHWSignalArray<Scalar>::GetTuple(vtkIdType i, double *tuple) { m_iterator->jumpTo(m_offset + i); - tuple[0] = m_iterator->getNormalizedSignalWithMask(); + tuple[0] = m_iterator->getNormalizedSignal(); } //------------------------------------------------------------------------------ @@ -294,13 +294,13 @@ vtkIdType vtkMDHWSignalArray<Scalar>::Lookup(const Scalar &val, template <class Scalar> Scalar vtkMDHWSignalArray<Scalar>::GetValue(vtkIdType idx) { m_iterator->jumpTo(m_offset + idx); - return m_iterator->getNormalizedSignalWithMask(); + return m_iterator->getNormalizedSignal(); } //------------------------------------------------------------------------------ template <class Scalar> Scalar &vtkMDHWSignalArray<Scalar>::GetValueReference(vtkIdType idx) { m_iterator->jumpTo(m_offset + idx); - m_temporaryTuple[0] = m_iterator->getNormalizedSignalWithMask(); + m_temporaryTuple[0] = m_iterator->getNormalizedSignal(); return m_temporaryTuple[0]; } @@ -309,7 +309,7 @@ template <class Scalar> void vtkMDHWSignalArray<Scalar>::GetTupleValue(vtkIdType tupleId, Scalar *tuple) { m_iterator->jumpTo(m_offset + tupleId); - tuple[0] = m_iterator->getNormalizedSignalWithMask(); + tuple[0] = m_iterator->getNormalizedSignal(); } //------------------------------------------------------------------------------ diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h index 91f287eeee9fa57c8ca61baf26556e162f034c2d..588caa22f3aee283b05ffd44ddb9fca8467656d6 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHexFactory.h @@ -9,8 +9,9 @@ #include "MantidVatesAPI/TimeToTimeStep.h" #include "MantidVatesAPI/vtkDataSetFactory.h" - +#include <vtkNew.h> #include <boost/shared_ptr.hpp> +#include <vector> using Mantid::DataObjects::MDEventWorkspace; @@ -58,8 +59,9 @@ public: virtual ~vtkMDHexFactory(); /// Factory Method. Should also handle delegation to successors. - virtual vtkDataSet* create(ProgressAction& progressUpdate) const; - + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdate) const; + /// Initalize with a target workspace. virtual void initialize(Mantid::API::Workspace_sptr); @@ -95,16 +97,17 @@ private: size_t m_maxDepth; /// Data set that will be generated - mutable vtkDataSet * dataSet; + mutable vtkSmartPointer<vtkDataSet> dataSet; /// We are slicing down from > 3 dimensions mutable bool slice; /// Mask for choosing along which dimensions to slice - mutable bool * sliceMask; + mutable std::unique_ptr<bool[]> sliceMask; /// Implicit function to define which boxes to render. - mutable Mantid::Geometry::MDImplicitFunction * sliceImplicitFunction; + mutable boost::shared_ptr<Mantid::Geometry::MDImplicitFunction> + sliceImplicitFunction; /// Time value. double m_time; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h index 39e1506fd6dff46709c345f64f76185015cb0cf0..c4e1711096dc1ab0a5b9344ef53f82e49bff1bab 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHex4DFactory.h @@ -65,7 +65,7 @@ public: virtual void initialize(Mantid::API::Workspace_sptr workspace); /// Factory method - vtkDataSet* create(ProgressAction& progressUpdating) const; + vtkSmartPointer<vtkDataSet> create(ProgressAction &progressUpdating) const; virtual std::string getFactoryTypeName() const { diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h index 6e5b9c27979bf2037e1d1e04a1be79ae8362918a..f141f41472bf62ab340baad752556ed752b03fb2 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoHexFactory.h @@ -62,7 +62,7 @@ public: virtual void initialize(Mantid::API::Workspace_sptr workspace); /// Factory method - vtkDataSet* create(ProgressAction& progressUpdating) const; + vtkSmartPointer<vtkDataSet> create(ProgressAction &progressUpdating) const; virtual std::string getFactoryTypeName() const { @@ -73,7 +73,8 @@ protected: virtual void validate() const; - vtkDataSet* create3Dor4D(size_t timestep, ProgressAction & update) const; + vtkSmartPointer<vtkDataSet> create3Dor4D(size_t timestep, + ProgressAction &update) const; void validateWsNotNull() const; diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h index 2c9dfd9509f4cb738fac755a483ec7a062771a54..e321b73d5b0a4e84d7bb2ea5b7b93c8b3f6597bd 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoLineFactory.h @@ -8,6 +8,7 @@ #include "MantidVatesAPI/Normalization.h" #include "MantidVatesAPI/ThresholdRange.h" #include "MantidDataObjects/MDHistoWorkspace.h" +#include <vtkNew.h> namespace Mantid { @@ -56,7 +57,8 @@ namespace Mantid virtual ~vtkMDHistoLineFactory(); /// Factory Method. - virtual vtkDataSet* create(ProgressAction& progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; virtual void initialize(Mantid::API::Workspace_sptr); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h index 59eba17ad789cc0382f21c5fac59335703f68b65..c4514bbeff75a96e5da8e4c86c4a20a947f3da57 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDHistoQuadFactory.h @@ -58,7 +58,8 @@ however, some visualisation frameworks won't be able to treat these factories in virtual ~vtkMDHistoQuadFactory(); /// Factory Method. - virtual vtkDataSet* create(ProgressAction& progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; virtual void initialize(Mantid::API::Workspace_sptr); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h index ace2b631230dd32e529f5b94f1cd1e117e348d92..d2373557eefbb3cbb765dfbdc3154807e6ab33c3 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDLineFactory.h @@ -47,7 +47,8 @@ namespace Mantid virtual ~vtkMDLineFactory(); /// Factory Method. Should also handle delegation to successors. - virtual vtkDataSet* create(ProgressAction& progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; /// Initalize with a target workspace. virtual void initialize(Mantid::API::Workspace_sptr); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h index b7f8a428ddd8c0dabd54e14fc6a0717af52d9b82..b939ebbabb9cc02443f11d800f965d565b492e62 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkMDQuadFactory.h @@ -48,7 +48,8 @@ namespace Mantid virtual ~vtkMDQuadFactory(); /// Factory Method. Should also handle delegation to successors. - virtual vtkDataSet* create(ProgressAction& progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; /// Initalize with a target workspace. virtual void initialize(Mantid::API::Workspace_sptr); diff --git a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h index e044608500577ac5e9f66960739ce4638a5375cd..c9b3190af9bdfc1b9eff0eace0458c70f4e2d143 100644 --- a/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h +++ b/Vates/VatesAPI/inc/MantidVatesAPI/vtkSplatterPlotFactory.h @@ -64,7 +64,8 @@ public: virtual ~vtkSplatterPlotFactory(); /// Factory Method. Should also handle delegation to successors. - virtual vtkDataSet *create(ProgressAction &progressUpdating) const; + virtual vtkSmartPointer<vtkDataSet> + create(ProgressAction &progressUpdating) const; /// Initalize with a target workspace. virtual void initialize(Mantid::API::Workspace_sptr); @@ -138,16 +139,16 @@ private: mutable std::string m_wsName; /// Data set that will be generated - mutable vtkDataSet *dataSet; + mutable vtkSmartPointer<vtkDataSet> dataSet; /// We are slicing down from > 3 dimensions mutable bool slice; /// Mask for choosing along which dimensions to slice - mutable bool *sliceMask; + mutable std::unique_ptr<bool[]> sliceMask; /// Implicit function to define which boxes to render. - mutable Mantid::Geometry::MDImplicitFunction *sliceImplicitFunction; + mutable boost::shared_ptr<Mantid::Geometry::MDImplicitFunction> sliceImplicitFunction; /// Variable to hold sorted list, so sort doesn't have to be repeated mutable std::vector<Mantid::API::IMDNode *> m_sortedBoxes; diff --git a/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp index 1501c4fe6529238bf4df1804fbc9bff6139e1ddf..aafb733936da7e8138d7ff86dc45f5da3ade03ef 100644 --- a/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/EventNexusLoadingPresenter.cpp @@ -25,67 +25,59 @@ namespace Mantid @throw invalid_arument if view is null @throw logic_error if cannot use the reader-presenter for this filetype. */ - EventNexusLoadingPresenter::EventNexusLoadingPresenter(MDLoadingView* view, - const std::string filename) : - MDEWLoadingPresenter(view), m_filename(filename), m_wsTypeName("") - { - if (this->m_filename.empty()) - { - throw std::invalid_argument("File name is an empty string."); - } - if (NULL == this->m_view) - { - throw std::invalid_argument("View is NULL."); - } + EventNexusLoadingPresenter::EventNexusLoadingPresenter( + std::unique_ptr<MDLoadingView> view, const std::string filename) + : MDEWLoadingPresenter(std::move(view)), m_filename(filename), + m_wsTypeName("") { + if (this->m_filename.empty()) { + throw std::invalid_argument("File name is an empty string."); + } + if (nullptr == this->m_view) { + throw std::invalid_argument("View is NULL."); } + } - /* - Indicates whether this presenter is capable of handling the type of file that is attempted to be loaded. - @return false if the file cannot be read. - */ - bool EventNexusLoadingPresenter::canReadFile() const - { - if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) - { + /* + Indicates whether this presenter is capable of handling the type of file that + is attempted to be loaded. + @return false if the file cannot be read. + */ + bool EventNexusLoadingPresenter::canReadFile() const { + if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) { + return 0; + } + + ::NeXus::File *file = NULL; + try { + file = new ::NeXus::File(this->m_filename); + // All SNS (event or histo) nxs files have an entry named "entry" + try { + file->openGroup("entry", "NXentry"); + } catch (::NeXus::Exception &) { + file->close(); return 0; } - - ::NeXus::File * file = NULL; - try - { - file = new ::NeXus::File(this->m_filename); - // All SNS (event or histo) nxs files have an entry named "entry" - try - { - file->openGroup("entry", "NXentry"); - } catch (::NeXus::Exception &) - { - file->close(); - return 0; + // But only eventNexus files have bank123_events as a group name + std::map<std::string, std::string> entries = file->getEntries(); + bool hasEvents = false; + std::map<std::string, std::string>::iterator it; + for (it = entries.begin(); it != entries.end(); ++it) { + if (it->first.find("_events") != std::string::npos) { + hasEvents = true; + break; } - // But only eventNexus files have bank123_events as a group name - std::map<std::string, std::string> entries = file->getEntries(); - bool hasEvents = false; - std::map<std::string, std::string>::iterator it; - for (it = entries.begin(); it != entries.end(); ++it) - { - if (it->first.find("_events") != std::string::npos) - { - hasEvents = true; - break; - } - } - file->close(); - return hasEvents ? 1 : 0; - } catch (std::exception & e) - { - std::cerr << "Could not open " << this->m_filename - << " as an EventNexus file because of exception: " << e.what() << std::endl; - // Clean up, if possible - if (file) - file->close(); } - return 0; + file->close(); + return hasEvents ? 1 : 0; + } catch (std::exception &e) { + std::cerr << "Could not open " << this->m_filename + << " as an EventNexus file because of exception: " << e.what() + << std::endl; + // Clean up, if possible + if (file) + file->close(); + } + return 0; } /* @@ -94,9 +86,10 @@ namespace Mantid @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ - vtkDataSet* EventNexusLoadingPresenter::execute(vtkDataSetFactory* factory, - ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate) - { + vtkSmartPointer<vtkDataSet> + EventNexusLoadingPresenter::execute(vtkDataSetFactory *factory, + ProgressAction &loadingProgressUpdate, + ProgressAction &drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; @@ -142,7 +135,9 @@ namespace Mantid m_wsTypeName = eventWs->id(); factory->setRecursionDepth(this->m_view->getRecursionDepth()); - vtkDataSet* visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); //HACK: progressUpdate should be argument for drawing! + auto visualDataSet = factory->oneStepCreate( + eventWs, drawingProgressUpdate); // HACK: progressUpdate should be + // argument for drawing! this->extractMetadata(eventWs); this->appendMetadata(visualDataSet, eventWs->getName()); @@ -168,11 +163,8 @@ namespace Mantid throw std::runtime_error("Does not have a 4th Dimension, so can be no T-axis"); } - ///Destructor - EventNexusLoadingPresenter::~EventNexusLoadingPresenter() - { - delete m_view; - } + /// Destructor + EventNexusLoadingPresenter::~EventNexusLoadingPresenter() {} /** Executes any meta-data loading required. diff --git a/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp index 79592b54bd18a6dfb3934b6c4b6cb3be35a78970..8be0aca5afd15190ca8e350ad9ab533133b60bc2 100644 --- a/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDEWEventNexusLoadingPresenter.cpp @@ -24,48 +24,44 @@ namespace Mantid @throw invalid_arument if view is null @throw logic_error if cannot use the reader-presenter for this filetype. */ - MDEWEventNexusLoadingPresenter::MDEWEventNexusLoadingPresenter(MDLoadingView* view, const std::string filename) : MDEWLoadingPresenter(view), m_filename(filename), m_wsTypeName("") - { - if(this->m_filename.empty()) - { - throw std::invalid_argument("File name is an empty string."); - } - if(NULL == this->m_view) - { - throw std::invalid_argument("View is NULL."); - } + MDEWEventNexusLoadingPresenter::MDEWEventNexusLoadingPresenter( + std::unique_ptr<MDLoadingView> view, const std::string filename) + : MDEWLoadingPresenter(std::move(view)), m_filename(filename), + m_wsTypeName("") { + if (this->m_filename.empty()) { + throw std::invalid_argument("File name is an empty string."); } + if (nullptr == this->m_view) { + throw std::invalid_argument("View is NULL."); + } + } - /* - Indicates whether this presenter is capable of handling the type of file that is attempted to be loaded. - @return false if the file cannot be read. - */ - bool MDEWEventNexusLoadingPresenter::canReadFile() const - { - // Quick check based on extension. - if(!canLoadFileBasedOnExtension(m_filename, ".nxs")) - { - return 0; - } - - ::NeXus::File * file = NULL; + /* + Indicates whether this presenter is capable of handling the type of file that + is attempted to be loaded. + @return false if the file cannot be read. + */ + bool MDEWEventNexusLoadingPresenter::canReadFile() const { + // Quick check based on extension. + if (!canLoadFileBasedOnExtension(m_filename, ".nxs")) { + return 0; + } - file = new ::NeXus::File(this->m_filename); - // MDEventWorkspace file has a different name for the entry - try - { - file->openGroup("MDEventWorkspace", "NXentry"); - file->close(); - return 1; - } - catch(::NeXus::Exception &) - { - // If the entry name does not match, then it can't read the file. - file->close(); - return 0; - } + ::NeXus::File *file = NULL; + + file = new ::NeXus::File(this->m_filename); + // MDEventWorkspace file has a different name for the entry + try { + file->openGroup("MDEventWorkspace", "NXentry"); + file->close(); + return 1; + } catch (::NeXus::Exception &) { + // If the entry name does not match, then it can't read the file. + file->close(); return 0; } + return 0; + } /* Executes the underlying algorithm to create the MVP model. @@ -73,8 +69,9 @@ namespace Mantid @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ - vtkDataSet* MDEWEventNexusLoadingPresenter::execute(vtkDataSetFactory* factory, ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate) - { + vtkSmartPointer<vtkDataSet> MDEWEventNexusLoadingPresenter::execute( + vtkDataSetFactory *factory, ProgressAction &loadingProgressUpdate, + ProgressAction &drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; @@ -98,7 +95,7 @@ namespace Mantid factory->setRecursionDepth(this->m_view->getRecursionDepth()); //Create visualisation in one-shot. - vtkDataSet* visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); + auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions have proper range extents set. @@ -135,16 +132,13 @@ namespace Mantid AnalysisDataService::Instance().remove("MD_EVENT_WS_ID"); } - ///Destructor - MDEWEventNexusLoadingPresenter::~MDEWEventNexusLoadingPresenter() - { - delete m_view; - } + /// Destructor + MDEWEventNexusLoadingPresenter::~MDEWEventNexusLoadingPresenter() {} - /* - Getter for the workspace type name. - @return Workspace Type Name - */ + /* +Getter for the workspace type name. +@return Workspace Type Name +*/ std::string MDEWEventNexusLoadingPresenter::getWorkspaceTypeName() { return m_wsTypeName; diff --git a/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp b/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp index 4dbaf48cbfc4108a7225a72d79f5f991237be28d..5eb4e0508dc6f456cc5511b6d119ce9f8144b1c2 100644 --- a/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDEWInMemoryLoadingPresenter.cpp @@ -22,46 +22,43 @@ namespace Mantid @throw invalid_argument if the repository is null @throw invalid_arument if view is null */ - MDEWInMemoryLoadingPresenter::MDEWInMemoryLoadingPresenter(MDLoadingView* view, WorkspaceProvider* repository, std::string wsName) : MDEWLoadingPresenter(view), - m_repository(repository), m_wsName(wsName), m_wsTypeName(""), m_specialCoords(-1) - { - if(m_wsName.empty()) - { - throw std::invalid_argument("The workspace name is empty."); - } - if(NULL == repository) - { - throw std::invalid_argument("The repository is NULL"); - } - if(NULL == m_view) - { - throw std::invalid_argument("View is NULL."); - } + MDEWInMemoryLoadingPresenter::MDEWInMemoryLoadingPresenter( + std::unique_ptr<MDLoadingView> view, WorkspaceProvider *repository, + std::string wsName) + : MDEWLoadingPresenter(std::move(view)), m_repository(repository), + m_wsName(wsName), m_wsTypeName(""), m_specialCoords(-1) { + if (m_wsName.empty()) { + throw std::invalid_argument("The workspace name is empty."); + } + if (nullptr == repository) { + throw std::invalid_argument("The repository is NULL"); + } + if (nullptr == m_view) { + throw std::invalid_argument("View is NULL."); } + } - /* - Indicates whether this presenter is capable of handling the type of file that is attempted to be loaded. - @return false if the file cannot be read. - */ - bool MDEWInMemoryLoadingPresenter::canReadFile() const - { - bool bCanReadIt = true; - if(!m_repository->canProvideWorkspace(m_wsName)) - { - //The workspace does not exist. - bCanReadIt = false; - } - else if(NULL == boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(m_repository->fetchWorkspace(m_wsName)).get()) - { - //The workspace can be found, but is not an IMDEventWorkspace. - bCanReadIt = false; - } - else - { - //The workspace is present, and is of the correct type. - bCanReadIt = true; - } - return bCanReadIt; + /* + Indicates whether this presenter is capable of handling the type of file that + is attempted to be loaded. + @return false if the file cannot be read. + */ + bool MDEWInMemoryLoadingPresenter::canReadFile() const { + bool bCanReadIt = true; + if (!m_repository->canProvideWorkspace(m_wsName)) { + // The workspace does not exist. + bCanReadIt = false; + } else if (nullptr == + boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>( + m_repository->fetchWorkspace(m_wsName)) + .get()) { + // The workspace can be found, but is not an IMDEventWorkspace. + bCanReadIt = false; + } else { + // The workspace is present, and is of the correct type. + bCanReadIt = true; + } + return bCanReadIt; } /* @@ -70,8 +67,9 @@ namespace Mantid @param : Handler for GUI updates while algorithm progresses. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ - vtkDataSet* MDEWInMemoryLoadingPresenter::execute(vtkDataSetFactory* factory, ProgressAction&, ProgressAction& drawingProgressUpdate) - { + vtkSmartPointer<vtkDataSet> MDEWInMemoryLoadingPresenter::execute( + vtkDataSetFactory *factory, ProgressAction &, + ProgressAction &drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; @@ -79,7 +77,7 @@ namespace Mantid IMDEventWorkspace_sptr eventWs = boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws); factory->setRecursionDepth(this->m_view->getRecursionDepth()); - vtkDataSet* visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); + auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions have proper range extents set. @@ -127,16 +125,13 @@ namespace Mantid this->extractMetadata(eventWs); } - ///Destructor - MDEWInMemoryLoadingPresenter::~MDEWInMemoryLoadingPresenter() - { - delete m_view; - } + /// Destructor + MDEWInMemoryLoadingPresenter::~MDEWInMemoryLoadingPresenter() {} - /* - Getter for the workspace type name. - @return Workspace Type Name - */ + /* + Getter for the workspace type name. + @return Workspace Type Name + */ std::string MDEWInMemoryLoadingPresenter::getWorkspaceTypeName() { return m_wsTypeName; diff --git a/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp b/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp index e551f06583c79fc46c076c2086e53dc4ba0aebce..6e8dd863192b78df0ba1c30780bbfc2ccc9730f2 100644 --- a/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDEWLoadingPresenter.cpp @@ -21,74 +21,66 @@ namespace Mantid { namespace VATES { - /// Constructor - MDEWLoadingPresenter::MDEWLoadingPresenter(MDLoadingView* view) : - m_view(view), - m_isSetup(false), - m_time(-1), - m_recursionDepth(0), - m_loadInMemory(false), - m_firstLoad(true), - m_metadataJsonManager(new MetadataJsonManager()), - m_metaDataExtractor(new MetaDataExtractorUtils()), - m_vatesConfigurations(new VatesConfigurations()) - { - Mantid::API::FrameworkManager::Instance(); - } + /// Constructor + MDEWLoadingPresenter::MDEWLoadingPresenter( + std::unique_ptr<MDLoadingView> view) + : m_view(std::move(view)), m_isSetup(false), m_time(-1), + m_recursionDepth(0), m_loadInMemory(false), m_firstLoad(true), + m_metadataJsonManager(new MetadataJsonManager()), + m_metaDataExtractor(new MetaDataExtractorUtils()), + m_vatesConfigurations(new VatesConfigurations()) { + Mantid::API::FrameworkManager::Instance(); + } - /// Destructor - MDEWLoadingPresenter::~MDEWLoadingPresenter() - { - } + /// Destructor + MDEWLoadingPresenter::~MDEWLoadingPresenter() {} - /* - Extract the geometry and function information - @param eventWs : event workspace to get the information from. - */ - void MDEWLoadingPresenter::extractMetadata(Mantid::API::IMDEventWorkspace_sptr eventWs) - { - using namespace Mantid::Geometry; - MDGeometryBuilderXML<NoDimensionPolicy> refresh; - xmlBuilder= refresh; //Reassign. - std::vector<MDDimensionExtents<coord_t> > ext = eventWs->getMinimumExtents(5); - std::vector<IMDDimension_sptr> dimensions; - size_t nDimensions = eventWs->getNumDims(); - for (size_t d=0; d<nDimensions; d++) - { - IMDDimension_const_sptr inDim = eventWs->getDimension(d); - coord_t min = ext[d].getMin(); - coord_t max = ext[d].getMax(); - if (min > max) - { - min = 0.0; - max = 1.0; - } - //std::cout << "dim " << d << min << " to " << max << std::endl; - axisLabels.push_back(makeAxisTitle(inDim)); - MDHistoDimension_sptr dim(new MDHistoDimension(inDim->getName(), inDim->getName(), inDim->getMDFrame(), min, max, inDim->getNBins())); - dimensions.push_back(dim); + /* + Extract the geometry and function information + @param eventWs : event workspace to get the information from. + */ + void MDEWLoadingPresenter::extractMetadata( + Mantid::API::IMDEventWorkspace_sptr eventWs) { + using namespace Mantid::Geometry; + MDGeometryBuilderXML<NoDimensionPolicy> refresh; + xmlBuilder = refresh; // Reassign. + std::vector<MDDimensionExtents<coord_t>> ext = + eventWs->getMinimumExtents(5); + std::vector<IMDDimension_sptr> dimensions; + size_t nDimensions = eventWs->getNumDims(); + for (size_t d = 0; d < nDimensions; d++) { + IMDDimension_const_sptr inDim = eventWs->getDimension(d); + coord_t min = ext[d].getMin(); + coord_t max = ext[d].getMax(); + if (min > max) { + min = 0.0; + max = 1.0; } + // std::cout << "dim " << d << min << " to " << max << std::endl; + axisLabels.push_back(makeAxisTitle(inDim)); + MDHistoDimension_sptr dim(new MDHistoDimension( + inDim->getName(), inDim->getName(), inDim->getMDFrame(), min, max, + inDim->getNBins())); + dimensions.push_back(dim); + } - //Configuring the geometry xml builder allows the object panel associated with this reader to later - //determine how to display all geometry related properties. - if(nDimensions > 0) - { - xmlBuilder.addXDimension( dimensions[0] ); - } - if(nDimensions > 1) - { - xmlBuilder.addYDimension( dimensions[1] ); - } - if(nDimensions > 2) - { - xmlBuilder.addZDimension( dimensions[2] ); - } - if(nDimensions > 3) - { - tDimension = dimensions[3]; - xmlBuilder.addTDimension(tDimension); - } - m_isSetup = true; + // Configuring the geometry xml builder allows the object panel associated + // with this reader to later + // determine how to display all geometry related properties. + if (nDimensions > 0) { + xmlBuilder.addXDimension(dimensions[0]); + } + if (nDimensions > 1) { + xmlBuilder.addYDimension(dimensions[1]); + } + if (nDimensions > 2) { + xmlBuilder.addZDimension(dimensions[2]); + } + if (nDimensions > 3) { + tDimension = dimensions[3]; + xmlBuilder.addTDimension(tDimension); + } + m_isSetup = true; } /** @@ -153,7 +145,7 @@ namespace Mantid { using namespace Mantid::API; - vtkFieldData* outputFD = vtkFieldData::New(); + vtkNew<vtkFieldData> outputFD; //Serialize metadata VatesKnowledgeSerializer serializer; @@ -167,10 +159,9 @@ namespace Mantid //Add metadata to dataset. MetadataToFieldData convert; - convert(outputFD, xmlString, XMLDefinitions::metaDataId().c_str()); - convert(outputFD, jsonString, m_vatesConfigurations->getMetadataIdJson().c_str()); - visualDataSet->SetFieldData(outputFD); - outputFD->Delete(); + convert(outputFD.GetPointer(), xmlString, XMLDefinitions::metaDataId().c_str()); + convert(outputFD.GetPointer(), jsonString, m_vatesConfigurations->getMetadataIdJson().c_str()); + visualDataSet->SetFieldData(outputFD.GetPointer()); } /** diff --git a/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp index cd33892016a552eaa9ad50da8706884293732f4d..95f22a20e84e401be168b6f9770ebfd4a87f6761 100644 --- a/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDHWInMemoryLoadingPresenter.cpp @@ -23,16 +23,17 @@ Constructor @throw invalid_arument if view is null */ MDHWInMemoryLoadingPresenter::MDHWInMemoryLoadingPresenter( - MDLoadingView *view, WorkspaceProvider *repository, std::string wsName) - : MDHWLoadingPresenter(view), m_repository(repository), m_wsName(wsName), - m_wsTypeName(""), m_specialCoords(-1) { + std::unique_ptr<MDLoadingView> view, WorkspaceProvider *repository, + std::string wsName) + : MDHWLoadingPresenter(std::move(view)), m_repository(repository), + m_wsName(wsName), m_wsTypeName(""), m_specialCoords(-1) { if (m_wsName.empty()) { throw std::invalid_argument("The workspace name is empty."); } if (NULL == repository) { throw std::invalid_argument("The repository is NULL"); } - if (NULL == m_view) { + if (nullptr == m_view) { throw std::invalid_argument("View is NULL."); } } @@ -67,7 +68,7 @@ Executes the underlying algorithm to create the MVP model. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ -vtkDataSet * +vtkSmartPointer<vtkDataSet> MDHWInMemoryLoadingPresenter::execute(vtkDataSetFactory *factory, ProgressAction &, ProgressAction &drawingProgressUpdate) { @@ -81,9 +82,10 @@ MDHWInMemoryLoadingPresenter::execute(vtkDataSetFactory *factory, MDHWLoadingPresenter::transposeWs(histoWs, m_cachedVisualHistoWs); // factory->setRecursionDepth(this->m_view->getRecursionDepth()); - vtkDataSet *visualDataSet = factory->oneStepCreate( - m_cachedVisualHistoWs, drawingProgressUpdate); // HACK: progressUpdate should be - // argument for drawing! + auto visualDataSet = factory->oneStepCreate( + m_cachedVisualHistoWs, + drawingProgressUpdate); // HACK: progressUpdate should be + // argument for drawing! /*extractMetaData needs to be re-run here because the first execution of this from ::executeLoadMetadata will not have ensured that all dimensions @@ -138,7 +140,7 @@ void MDHWInMemoryLoadingPresenter::executeLoadMetadata() { } /// Destructor -MDHWInMemoryLoadingPresenter::~MDHWInMemoryLoadingPresenter() { delete m_view; } +MDHWInMemoryLoadingPresenter::~MDHWInMemoryLoadingPresenter() {} /* * Getter for the workspace type name. diff --git a/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp index 9db9b9dd4bed614e691c755f2e3ffa5b149cb533..1e8bfbdd904c7fa5350b083f7fb851a8eb7b0f89 100644 --- a/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDHWLoadingPresenter.cpp @@ -91,9 +91,10 @@ void MDHWLoadingPresenter::transposeWs(Mantid::API::IMDHistoWorkspace_sptr &inHi } /// Constructor -MDHWLoadingPresenter::MDHWLoadingPresenter(MDLoadingView *view) - : m_view(view), m_isSetup(false), m_time(-1), m_loadInMemory(false), - m_firstLoad(true), m_metadataJsonManager(new MetadataJsonManager()), +MDHWLoadingPresenter::MDHWLoadingPresenter(std::unique_ptr<MDLoadingView> view) + : m_view(std::move(view)), m_isSetup(false), m_time(-1), + m_loadInMemory(false), m_firstLoad(true), + m_metadataJsonManager(new MetadataJsonManager()), m_metaDataExtractor(new MetaDataExtractorUtils()), m_vatesConfigurations(new VatesConfigurations()) { Mantid::API::FrameworkManager::Instance(); @@ -201,7 +202,7 @@ void MDHWLoadingPresenter::appendMetadata(vtkDataSet *visualDataSet, const std::string &wsName) { using namespace Mantid::API; - vtkFieldData *outputFD = vtkFieldData::New(); + vtkNew<vtkFieldData> outputFD; // Serialize metadata VatesKnowledgeSerializer serializer; @@ -216,11 +217,10 @@ void MDHWLoadingPresenter::appendMetadata(vtkDataSet *visualDataSet, // Add metadata to dataset. MetadataToFieldData convert; - convert(outputFD, xmlString, XMLDefinitions::metaDataId().c_str()); - convert(outputFD, jsonString, + convert(outputFD.GetPointer(), xmlString, XMLDefinitions::metaDataId().c_str()); + convert(outputFD.GetPointer(), jsonString, m_vatesConfigurations->getMetadataIdJson().c_str()); - visualDataSet->SetFieldData(outputFD); - outputFD->Delete(); + visualDataSet->SetFieldData(outputFD.GetPointer()); } diff --git a/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp b/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp index eec4a5a3b109997953895099faaf9fbbb78300cf..c5776b15c7942328b07065e0e9ac0a74cfa8155e 100644 --- a/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/MDHWNexusLoadingPresenter.cpp @@ -24,14 +24,14 @@ namespace VATES * @throw invalid_arument if view is null * @throw logic_error if cannot use the reader-presenter for this filetype. */ -MDHWNexusLoadingPresenter::MDHWNexusLoadingPresenter(MDLoadingView* view, const std::string filename) : MDHWLoadingPresenter(view), m_filename(filename), m_wsTypeName("") -{ - if(this->m_filename.empty()) - { +MDHWNexusLoadingPresenter::MDHWNexusLoadingPresenter( + std::unique_ptr<MDLoadingView> view, const std::string filename) + : MDHWLoadingPresenter(std::move(view)), m_filename(filename), + m_wsTypeName("") { + if (this->m_filename.empty()) { throw std::invalid_argument("File name is an empty string."); } - if(NULL == this->m_view) - { + if (nullptr == this->m_view) { throw std::invalid_argument("View is NULL."); } } @@ -72,8 +72,10 @@ bool MDHWNexusLoadingPresenter::canReadFile() const * @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses. * @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ -vtkDataSet* MDHWNexusLoadingPresenter::execute(vtkDataSetFactory* factory, ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate) -{ +vtkSmartPointer<vtkDataSet> +MDHWNexusLoadingPresenter::execute(vtkDataSetFactory *factory, + ProgressAction &loadingProgressUpdate, + ProgressAction &drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; @@ -81,7 +83,7 @@ vtkDataSet* MDHWNexusLoadingPresenter::execute(vtkDataSetFactory* factory, Progr this->loadWorkspace(loadingProgressUpdate); // Create visualisation in one-shot. - vtkDataSet* visualDataSet = factory->oneStepCreate(m_histoWs, drawingProgressUpdate); + auto visualDataSet = factory->oneStepCreate(m_histoWs, drawingProgressUpdate); // extractMetaData needs to be re-run here because the first execution // of this from ::executeLoadMetadata will not have ensured that all @@ -113,10 +115,7 @@ void MDHWNexusLoadingPresenter::executeLoadMetadata() * Destructor * @return */ -MDHWNexusLoadingPresenter::~MDHWNexusLoadingPresenter() -{ - delete m_view; -} +MDHWNexusLoadingPresenter::~MDHWNexusLoadingPresenter() {} /** * Getter for the workspace type name. diff --git a/Vates/VatesAPI/src/MetadataToFieldData.cpp b/Vates/VatesAPI/src/MetadataToFieldData.cpp index 1ca4cfb1005ee8d3e3f30e24727b22765716f4ca..c98cf40a19f6aa2f4ab4b8e9e656946a3065979e 100644 --- a/Vates/VatesAPI/src/MetadataToFieldData.cpp +++ b/Vates/VatesAPI/src/MetadataToFieldData.cpp @@ -1,6 +1,7 @@ #include "MantidVatesAPI/MetadataToFieldData.h" #include "vtkCharArray.h" #include "vtkFieldData.h" +#include "vtkNew.h" namespace Mantid { @@ -21,16 +22,15 @@ void MetadataToFieldData::execute(vtkFieldData* fieldData, std::string metaData, fieldData->RemoveArray(id.c_str()); } //create new. - vtkCharArray* newArry = vtkCharArray::New(); + vtkNew<vtkCharArray> newArry; newArry->Allocate(metaData.size()); newArry->SetName(id.c_str()); - fieldData->AddArray(newArry); + fieldData->AddArray(newArry.GetPointer()); for(unsigned int i = 0 ; i < metaData.size(); i++) { newArry->InsertNextValue(metaData.at(i)); } - newArry->Delete(); } } diff --git a/Vates/VatesAPI/src/Normalization.cpp b/Vates/VatesAPI/src/Normalization.cpp index a0c5d76360f8ba134c1d2c5fbc5c07d0cd32b92e..bea3316f82ca7756f1490c8f45693544f775f67c 100644 --- a/Vates/VatesAPI/src/Normalization.cpp +++ b/Vates/VatesAPI/src/Normalization.cpp @@ -12,13 +12,11 @@ requested normalisation. This is used for visualisation of IMDEventWorkspaces. @param normalizationOption : Visual Normalization option desired @param ws : workspace to fetch defaults from if needed -@param hasMask : true if the workspace has a mask @return member function to use on IMDNodes */ -NormFuncIMDNodePtr -makeMDEventNormalizationFunction(VisualNormalization normalizationOption, - Mantid::API::IMDEventWorkspace const *const ws, - const bool hasMask) { +NormFuncIMDNodePtr makeMDEventNormalizationFunction( + VisualNormalization normalizationOption, + Mantid::API::IMDEventWorkspace const *const ws) { using namespace Mantid::API; @@ -31,24 +29,12 @@ makeMDEventNormalizationFunction(VisualNormalization normalizationOption, NormFuncIMDNodePtr normalizationFunction; - // Avoid checking every box for a mask if there is no mask in the workspace - // by using different functions - if (hasMask) { - if (normalizationOption == Mantid::VATES::NumEventsNormalization) { - normalizationFunction = &IMDNode::getSignalByNEventsWithMask; - } else if (normalizationOption == Mantid::VATES::NoNormalization) { - normalizationFunction = &IMDNode::getSignalWithMask; - } else { - normalizationFunction = &IMDNode::getSignalNormalizedWithMask; - } + if (normalizationOption == Mantid::VATES::NumEventsNormalization) { + normalizationFunction = &IMDNode::getSignalByNEvents; + } else if (normalizationOption == Mantid::VATES::NoNormalization) { + normalizationFunction = &IMDNode::getSignal; } else { - if (normalizationOption == Mantid::VATES::NumEventsNormalization) { - normalizationFunction = &IMDNode::getSignalByNEvents; - } else if (normalizationOption == Mantid::VATES::NoNormalization) { - normalizationFunction = &IMDNode::getSignal; - } else { - normalizationFunction = &IMDNode::getSignalNormalized; - } + normalizationFunction = &IMDNode::getSignalNormalized; } return normalizationFunction; diff --git a/Vates/VatesAPI/src/SQWLoadingPresenter.cpp b/Vates/VatesAPI/src/SQWLoadingPresenter.cpp index 7e51bd61e9fdca7df18444499b3b213ed9480cf1..c9eb3d4543a09370a6e9c0c8dfb8c7660149250c 100644 --- a/Vates/VatesAPI/src/SQWLoadingPresenter.cpp +++ b/Vates/VatesAPI/src/SQWLoadingPresenter.cpp @@ -21,26 +21,28 @@ namespace Mantid @throw invalid_arument if view is null @throw logic_error if cannot use the reader-presenter for this filetype. */ - SQWLoadingPresenter::SQWLoadingPresenter(MDLoadingView* view, const std::string filename) : MDEWLoadingPresenter(view), m_filename(filename), m_wsTypeName("") - { - if(this->m_filename.empty()) - { - throw std::invalid_argument("File name is an empty string."); - } - if(NULL == this->m_view) - { - throw std::invalid_argument("View is NULL."); - } + SQWLoadingPresenter::SQWLoadingPresenter(std::unique_ptr<MDLoadingView> view, + const std::string filename) + : MDEWLoadingPresenter(std::move(view)), m_filename(filename), + m_wsTypeName("") { + if (this->m_filename.empty()) { + throw std::invalid_argument("File name is an empty string."); } - - /* - Indicates whether this presenter is capable of handling the type of file that is attempted to be loaded. - @return false if the file cannot be read. - */ - bool SQWLoadingPresenter::canReadFile() const - { - boost::regex expression(".*sqw$", boost::regex_constants::icase); //check that the file ends with sqw. - return boost::regex_match(this->m_filename, expression); + if (nullptr == this->m_view) { + throw std::invalid_argument("View is NULL."); + } + } + + /* + Indicates whether this presenter is capable of handling the type of file that + is attempted to be loaded. + @return false if the file cannot be read. + */ + bool SQWLoadingPresenter::canReadFile() const { + boost::regex expression( + ".*sqw$", + boost::regex_constants::icase); // check that the file ends with sqw. + return boost::regex_match(this->m_filename, expression); } @@ -50,8 +52,10 @@ namespace Mantid @param loadingProgressUpdate : Handler for GUI updates while algorithm progresses. @param drawingProgressUpdate : Handler for GUI updates while vtkDataSetFactory::create occurs. */ - vtkDataSet* SQWLoadingPresenter::execute(vtkDataSetFactory* factory, ProgressAction& loadingProgressUpdate, ProgressAction& drawingProgressUpdate) - { + vtkSmartPointer<vtkDataSet> + SQWLoadingPresenter::execute(vtkDataSetFactory *factory, + ProgressAction &loadingProgressUpdate, + ProgressAction &drawingProgressUpdate) { using namespace Mantid::API; using namespace Mantid::Geometry; @@ -82,7 +86,7 @@ namespace Mantid factory->setRecursionDepth(this->m_view->getRecursionDepth()); - vtkDataSet* visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); + auto visualDataSet = factory->oneStepCreate(eventWs, drawingProgressUpdate); this->appendMetadata(visualDataSet, eventWs->getName()); @@ -162,10 +166,7 @@ namespace Mantid } ///Destructor - SQWLoadingPresenter::~SQWLoadingPresenter() - { - delete m_view; - } + SQWLoadingPresenter::~SQWLoadingPresenter() {} /* Getter for the workspace type name. diff --git a/Vates/VatesAPI/src/vtkDataSetFactory.cpp b/Vates/VatesAPI/src/vtkDataSetFactory.cpp index c85c163a027920ea6b37b74d2f22ae7aa8740983..d737473e32c937fdeb2f28607beeb51e52fe0d2a 100644 --- a/Vates/VatesAPI/src/vtkDataSetFactory.cpp +++ b/Vates/VatesAPI/src/vtkDataSetFactory.cpp @@ -18,16 +18,22 @@ vtkDataSetFactory::~vtkDataSetFactory() /** Set the successor factory for the chain-of-responsibility. @param pSuccessor :: pointer to the successor. Note RAII is used. - @return true if addition was successful. + @throw std::runtime_error if types are the same + @throw std::invalid_argument if successor is nullptr */ -void vtkDataSetFactory::SetSuccessor(vtkDataSetFactory* pSuccessor) -{ - //Assigment peformed first (RAII) to guarentee no side effects. - m_successor = vtkDataSetFactory::SuccessorType(pSuccessor); - //Unless overriden, successors should not be the same type as the present instance. - if(pSuccessor->getFactoryTypeName() == this->getFactoryTypeName()) - { - throw std::runtime_error("Cannot assign a successor to vtkDataSetFactory with the same type as the present vtkDataSetFactory type."); +void vtkDataSetFactory::SetSuccessor(vtkDataSetFactory_uptr pSuccessor) { + if (pSuccessor) { + // Assignment peformed first (RAII) to guarantee no side effects. + m_successor = std::move(pSuccessor); + // Unless overriden, successors should not be the same type as the present + // instance. + if (m_successor->getFactoryTypeName() == this->getFactoryTypeName()) { + throw std::runtime_error("Cannot assign a successor to vtkDataSetFactory " + "with the same type as the present " + "vtkDataSetFactory type."); + } + } else { + throw std::invalid_argument("Null pointer passed as successor"); } } @@ -66,8 +72,9 @@ Convenience function. Creates an output visualisation data set in one-shot. @param progressUpdater : object used to update the progress action. @result vtkDataSet* interpreted from input. */ -vtkDataSet* vtkDataSetFactory::oneStepCreate(Mantid::API::Workspace_sptr ws, ProgressAction& progressUpdater) -{ +vtkSmartPointer<vtkDataSet> +vtkDataSetFactory::oneStepCreate(Mantid::API::Workspace_sptr ws, + ProgressAction &progressUpdater) { this->initialize(ws); return this->create(progressUpdater); } diff --git a/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp b/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp index 628a229023f4cb5d1022bed7ddcb8938c129e7d1..9ec7e3523fd02a05f8cbb0ea560b4a2fdc5efa05 100644 --- a/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp +++ b/Vates/VatesAPI/src/vtkDataSetToImplicitFunction.cpp @@ -4,6 +4,7 @@ #include "MantidGeometry/MDGeometry/MDGeometryXMLDefinitions.h" #include "MantidAPI/ImplicitFunctionFactory.h" #include "MantidGeometry/MDGeometry/NullImplicitFunction.h" +#include "MantidKernel/make_unique.h" #include <vtkDataSet.h> namespace Mantid @@ -42,7 +43,8 @@ namespace Mantid { using Mantid::Geometry::NullImplicitFunction; using Mantid::Geometry::MDGeometryXMLDefinitions; - Mantid::Geometry::MDImplicitFunction* function = new NullImplicitFunction; + std::unique_ptr<Mantid::Geometry::MDImplicitFunction> function = + Mantid::Kernel::make_unique<NullImplicitFunction>(); FieldDataToMetadata convert; std::string xmlString = convert(m_dataset->GetFieldData(), XMLDefinitions::metaDataId()); @@ -54,11 +56,14 @@ namespace Mantid Poco::XML::Element* functionElem = pRootElem->getChildElement(MDGeometryXMLDefinitions::functionElementName()); if(NULL != functionElem) { - delete function; - function = Mantid::API::ImplicitFunctionFactory::Instance().createUnwrapped(functionElem); + auto existingFunction = + std::unique_ptr<Mantid::Geometry::MDImplicitFunction>( + Mantid::API::ImplicitFunctionFactory::Instance() + .createUnwrapped(functionElem)); + function.swap(existingFunction); } } - return function; + return function.release(); } /// Destructor. diff --git a/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp b/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp index faa0fc5c470adf24849821ff85a6e82eb40f1da8..d18e4ad62a5501298922d2c33c0d3b04f916ca94 100644 --- a/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp +++ b/Vates/VatesAPI/src/vtkDataSetToPeaksFilteredDataSet.cpp @@ -40,166 +40,175 @@ namespace VATES * @param input : The dataset to peaks filter * @param output : The resulting peaks filtered dataset */ - vtkDataSetToPeaksFilteredDataSet::vtkDataSetToPeaksFilteredDataSet(vtkUnstructuredGrid *input, - vtkUnstructuredGrid *output) : - m_inputData(input), - m_outputData(output), - m_isInitialised(false), - m_radiusNoShape(0.2), - m_radiusType(0), - m_radiusFactor(2), - m_defaultRadius(0.1), - m_coordinateSystem(0) - { - if (NULL == m_inputData) - { - throw std::runtime_error("Cannot construct vtkDataSetToPeaksFilteredDataSet with NULL input vtkUnstructuredGrid"); - } - if (NULL == m_outputData) - { - throw std::runtime_error("Cannot construct vtkDataSetToPeaksFilteredDataSet with NULL output vtkUnstructuredGrid"); - } +vtkDataSetToPeaksFilteredDataSet::vtkDataSetToPeaksFilteredDataSet( + vtkSmartPointer<vtkUnstructuredGrid> input, + vtkSmartPointer<vtkUnstructuredGrid> output) + : m_inputData(input), m_outputData(output), m_isInitialised(false), + m_radiusNoShape(0.2), m_radiusType(0), m_radiusFactor(2), + m_defaultRadius(0.1), m_coordinateSystem(0) { + if (nullptr == input) { + throw std::runtime_error("Cannot construct " + "vtkDataSetToPeaksFilteredDataSet with NULL input " + "vtkUnstructuredGrid"); + } + if (nullptr == output) { + throw std::runtime_error("Cannot construct " + "vtkDataSetToPeaksFilteredDataSet with NULL " + "output vtkUnstructuredGrid"); } +} +vtkDataSetToPeaksFilteredDataSet::~vtkDataSetToPeaksFilteredDataSet() {} - vtkDataSetToPeaksFilteredDataSet::~vtkDataSetToPeaksFilteredDataSet() - { - - } +/** + * Set the value for the underlying peaks workspace + * @param peaksWorkspaces : A list of peak workspace names. + * @param radiusNoShape : The peak radius for no shape. + * @param radiusType : The type of the radius: Radius(0), Outer Radius(10, + * Inner Radius(1) + * @param coordinateSystem: A coordinate system. + */ +void vtkDataSetToPeaksFilteredDataSet::initialize( + std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces, + double radiusNoShape, int radiusType, int coordinateSystem) { + m_peaksWorkspaces = peaksWorkspaces; + m_radiusNoShape = radiusNoShape; + m_radiusType = radiusType; + m_isInitialised = true; + m_coordinateSystem = coordinateSystem; +} - /** - * Set the value for the underlying peaks workspace - * @param peaksWorkspaces : A list of peak workspace names. - * @param radiusNoShape : The peak radius for no shape. - * @param radiusType : The type of the radius: Radius(0), Outer Radius(10, Inner Radius(1) - * @param coordinateSystem: A coordinate system. - */ - void vtkDataSetToPeaksFilteredDataSet::initialize(std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces, double radiusNoShape, int radiusType, int coordinateSystem) - { - m_peaksWorkspaces = peaksWorkspaces; - m_radiusNoShape = radiusNoShape; - m_radiusType = radiusType; - m_isInitialised = true; - m_coordinateSystem = coordinateSystem; +/** + * Process the input data. First, get all the peaks and their associated + * geometry. Then filter + * through the input to find the peaks which lie within a peak. Then apply then + * to the output data. + * Then update the metadata. See + * http://www.vtk.org/Wiki/VTK/Examples/Cxx/PolyData/ExtractSelection + * @param progressUpdating The handle for the progress bar. + */ +void vtkDataSetToPeaksFilteredDataSet::execute( + ProgressAction &progressUpdating) { + if (!m_isInitialised) { + throw std::runtime_error("vtkDataSetToPeaksFilteredDataSet needs " + "initialize run before executing"); } - /** - * Process the input data. First, get all the peaks and their associated geometry. Then filter - * through the input to find the peaks which lie within a peak. Then apply then to the output data. - * Then update the metadata. See http://www.vtk.org/Wiki/VTK/Examples/Cxx/PolyData/ExtractSelection - * @param progressUpdating The handle for the progress bar. - */ - void vtkDataSetToPeaksFilteredDataSet::execute(ProgressAction& progressUpdating) - { - if (!m_isInitialised) - { - throw std::runtime_error("vtkDataSetToPeaksFilteredDataSet needs initialize run before executing"); - } + // Get the peaks location and the radius information + std::vector<std::pair<Mantid::Kernel::V3D, double>> peaksInfo = + getPeaksInfo(m_peaksWorkspaces); - // Get the peaks location and the radius information - std::vector<std::pair<Mantid::Kernel::V3D, double>> peaksInfo = getPeaksInfo(m_peaksWorkspaces); + // Compare each element of the vtk data set and check which ones to keep + vtkPoints *points = m_inputData->GetPoints(); - // Compare each element of the vtk data set and check which ones to keep - vtkPoints *points = m_inputData->GetPoints(); + vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New(); + ids->SetNumberOfComponents(1); - vtkSmartPointer<vtkIdTypeArray> ids = vtkSmartPointer<vtkIdTypeArray>::New(); - ids->SetNumberOfComponents(1); + double progressFactor = 1.0 / double(points->GetNumberOfPoints()); + for (int i = 0; i < points->GetNumberOfPoints(); i++) { + progressUpdating.eventRaised(double(i) * progressFactor); + double point[3]; + points->GetPoint(i, point); - double progressFactor = 1.0/double(points->GetNumberOfPoints()); - for(int i = 0; i < points->GetNumberOfPoints(); i++) - { - progressUpdating.eventRaised(double(i)*progressFactor); - double point[3]; - points->GetPoint(i, point); - - // Compare to Peaks - const size_t numberOfPeaks = peaksInfo.size(); - size_t counter = 0; - while (counter < numberOfPeaks) - { - // Calcuate the differnce between the vtkDataSet point and the peak. Needs to be smaller than the radius - double squaredDifference = 0; - for (int k = 0; k <3; k++) - { - squaredDifference += (point[k] - peaksInfo[counter].first[k])* (point[k] - peaksInfo[counter].first[k]); - } - - if (squaredDifference <= (peaksInfo[counter].second*peaksInfo[counter].second)) - { - ids->InsertNextValue(i); - break; - } - counter++; + // Compare to Peaks + const size_t numberOfPeaks = peaksInfo.size(); + size_t counter = 0; + while (counter < numberOfPeaks) { + // Calcuate the differnce between the vtkDataSet point and the peak. Needs + // to be smaller than the radius + double squaredDifference = 0; + for (int k = 0; k < 3; k++) { + squaredDifference += (point[k] - peaksInfo[counter].first[k]) * + (point[k] - peaksInfo[counter].first[k]); } + + if (squaredDifference <= + (peaksInfo[counter].second * peaksInfo[counter].second)) { + ids->InsertNextValue(i); + break; + } + counter++; } + } - // Now we have all ids for the points, we need to retrieve the ids of the cells - std::map<vtkIdType, vtkIdType> uniqueCellTester; - vtkSmartPointer<vtkIdTypeArray> cellIds = vtkSmartPointer<vtkIdTypeArray>::New(); + // Now we have all ids for the points, we need to retrieve the ids of the + // cells + std::map<vtkIdType, vtkIdType> uniqueCellTester; + vtkSmartPointer<vtkIdTypeArray> cellIds = + vtkSmartPointer<vtkIdTypeArray>::New(); - for (int i = 0; i < ids->GetNumberOfTuples(); i++) { - vtkIdType pId = ids->GetValue(i); + for (int i = 0; i < ids->GetNumberOfTuples(); i++) { + vtkIdType pId = ids->GetValue(i); - vtkSmartPointer<vtkIdList> cIdList = vtkSmartPointer<vtkIdList>::New(); - cIdList->Initialize(); - - m_inputData->GetPointCells(pId, cIdList); - - if (cIdList->GetNumberOfIds() == 0) { - continue; - } + vtkSmartPointer<vtkIdList> cIdList = vtkSmartPointer<vtkIdList>::New(); + cIdList->Initialize(); - vtkIdType cId = cIdList->GetId(0); + m_inputData->GetPointCells(pId, cIdList); - if (uniqueCellTester.count(cId) == 0) { - cellIds->InsertNextValue(cId); - uniqueCellTester.insert(std::pair<vtkIdType, vtkIdType>(cId, cId)); - } + if (cIdList->GetNumberOfIds() == 0) { + continue; } - // Create the selection node and tell it the type of selection - vtkSmartPointer<vtkSelectionNode> selectionNode = vtkSmartPointer<vtkSelectionNode>::New(); - selectionNode->SetFieldType(vtkSelectionNode::CELL); - selectionNode->SetContentType(vtkSelectionNode::INDICES); - selectionNode->SetSelectionList(cellIds); - - vtkSmartPointer<vtkSelection> selection = vtkSmartPointer<vtkSelection>::New(); - selection->AddNode(selectionNode); - - // We are not setting up a pipeline here, cannot access vtkAlgorithmOutput - vtkSmartPointer<vtkExtractSelection> extractSelection = vtkSmartPointer<vtkExtractSelection>::New(); - extractSelection->SetInputData(0,m_inputData); - extractSelection->SetInputData(1, selection); - extractSelection->Update(); - - //Extract - m_outputData->ShallowCopy(extractSelection->GetOutput()); + vtkIdType cId = cIdList->GetId(0); + + if (uniqueCellTester.count(cId) == 0) { + cellIds->InsertNextValue(cId); + uniqueCellTester.insert(std::pair<vtkIdType, vtkIdType>(cId, cId)); + } } - /** - * Get the peaks information which is the position and the largest radius of the peak. - * @param peaksWorkspaces A list of peaks workspaces - * @returns A list of pair information which contains the position and the radius. - */ - std::vector<std::pair<Mantid::Kernel::V3D, double>> vtkDataSetToPeaksFilteredDataSet::getPeaksInfo(std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces) - { - std::vector<std::pair<Mantid::Kernel::V3D, double>> peaksInfo; - // Iterate over all peaksworkspaces and add the their info to the output vector - for (std::vector<Mantid::API::IPeaksWorkspace_sptr>::iterator it = peaksWorkspaces.begin(); it != peaksWorkspaces.end(); ++it) - { - const Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = static_cast<Mantid::Kernel::SpecialCoordinateSystem>(m_coordinateSystem); - int numPeaks = (*it)->getNumberPeaks(); - - // Iterate over all peaks for the workspace - for (int i = 0; i < numPeaks ; i++) - { - Mantid::Geometry::IPeak* peak = (*it)->getPeakPtr(i); + // Create the selection node and tell it the type of selection + vtkSmartPointer<vtkSelectionNode> selectionNode = + vtkSmartPointer<vtkSelectionNode>::New(); + selectionNode->SetFieldType(vtkSelectionNode::CELL); + selectionNode->SetContentType(vtkSelectionNode::INDICES); + selectionNode->SetSelectionList(cellIds); - addSinglePeak(peak, coordinateSystem, peaksInfo); - } + vtkSmartPointer<vtkSelection> selection = + vtkSmartPointer<vtkSelection>::New(); + selection->AddNode(selectionNode); + + // We are not setting up a pipeline here, cannot access vtkAlgorithmOutput + vtkSmartPointer<vtkExtractSelection> extractSelection = + vtkSmartPointer<vtkExtractSelection>::New(); + extractSelection->SetInputData(0, m_inputData); + extractSelection->SetInputData(1, selection); + extractSelection->Update(); + + // Extract + m_outputData->ShallowCopy(extractSelection->GetOutput()); +} + +/** + * Get the peaks information which is the position and the largest radius of the + * peak. + * @param peaksWorkspaces A list of peaks workspaces + * @returns A list of pair information which contains the position and the + * radius. + */ +std::vector<std::pair<Mantid::Kernel::V3D, double>> +vtkDataSetToPeaksFilteredDataSet::getPeaksInfo( + std::vector<Mantid::API::IPeaksWorkspace_sptr> peaksWorkspaces) { + std::vector<std::pair<Mantid::Kernel::V3D, double>> peaksInfo; + // Iterate over all peaksworkspaces and add the their info to the output + // vector + for (std::vector<Mantid::API::IPeaksWorkspace_sptr>::iterator it = + peaksWorkspaces.begin(); + it != peaksWorkspaces.end(); ++it) { + const Mantid::Kernel::SpecialCoordinateSystem coordinateSystem = + static_cast<Mantid::Kernel::SpecialCoordinateSystem>( + m_coordinateSystem); + int numPeaks = (*it)->getNumberPeaks(); + + // Iterate over all peaks for the workspace + for (int i = 0; i < numPeaks; i++) { + Mantid::Geometry::IPeak *peak = (*it)->getPeakPtr(i); + + addSinglePeak(peak, coordinateSystem, peaksInfo); } - return peaksInfo; } + return peaksInfo; +} GCC_DIAG_OFF(strict-aliasing) /** diff --git a/Vates/VatesAPI/src/vtkMD0DFactory.cpp b/Vates/VatesAPI/src/vtkMD0DFactory.cpp index 7a46febd652aa0895e3dae3d58f71608031f0eb0..788dc392728779a28e9000093e6fcf1743a93ff2 100644 --- a/Vates/VatesAPI/src/vtkMD0DFactory.cpp +++ b/Vates/VatesAPI/src/vtkMD0DFactory.cpp @@ -32,11 +32,11 @@ namespace Mantid @param progressUpdating: Reporting object to pass progress information up the stack. @return fully constructed vtkDataSet. */ - vtkDataSet* vtkMD0DFactory::create(ProgressAction&) const - { + vtkSmartPointer<vtkDataSet> vtkMD0DFactory::create(ProgressAction &) const { g_log.warning() << "Factory " << this->getFactoryTypeName() << " is being used. You are viewing data with less than three dimensions in the VSI. \n"; vtkNullUnstructuredGrid nullGrid; - vtkUnstructuredGrid *visualDataSet = nullGrid.createNullData(); + auto visualDataSet = + vtkSmartPointer<vtkDataSet>::Take(nullGrid.createNullData()); return visualDataSet; } diff --git a/Vates/VatesAPI/src/vtkMDHexFactory.cpp b/Vates/VatesAPI/src/vtkMDHexFactory.cpp index 5000871e63eed1fef721d80aa04163cc10f025e4..a2423275bd9f74435e19c01f6a4d4e6840f49512 100644 --- a/Vates/VatesAPI/src/vtkMDHexFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDHexFactory.cpp @@ -14,6 +14,7 @@ #include <vtkPoints.h> #include <vtkUnstructuredGrid.h> #include "MantidKernel/ReadLock.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::API; using namespace Mantid::DataObjects; @@ -36,8 +37,7 @@ vtkMDHexFactory::vtkMDHexFactory(ThresholdRange_scptr thresholdRange, const size_t maxDepth) : m_thresholdRange(thresholdRange), m_normalizationOption(normalizationOption), m_maxDepth(maxDepth), - dataSet(NULL), slice(false), sliceMask(NULL), sliceImplicitFunction(NULL), - m_time(0) {} + slice(false), m_time(0) {} /// Destructor vtkMDHexFactory::~vtkMDHexFactory() {} @@ -64,7 +64,7 @@ void vtkMDHexFactory::doCreate( std::vector<API::IMDNode *> boxes; if (this->slice) ws->getBox()->getBoxes(boxes, m_maxDepth, true, - this->sliceImplicitFunction); + this->sliceImplicitFunction.get()); else ws->getBox()->getBoxes(boxes, m_maxDepth, true); @@ -76,34 +76,35 @@ void vtkMDHexFactory::doCreate( << " boxes down to depth " << m_maxDepth << std::endl; // Create 8 points per box. - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->Allocate(numBoxes * 8); points->SetNumberOfPoints(numBoxes * 8); // One scalar per box - vtkFloatArray *signals = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signals; signals->Allocate(numBoxes); signals->SetName(ScalarName.c_str()); signals->SetNumberOfComponents(1); - // signals->SetNumberOfValues(numBoxes); // To cache the signal - float *signalArray = new float[numBoxes]; + std::vector<float> signalCache(numBoxes, 0); // True for boxes that we will use - bool *useBox = new bool[numBoxes]; - memset(useBox, 0, sizeof(bool) * numBoxes); + // We do not use vector<bool> here because of the parallelization below + // Simultaneous access to different elements of vector<bool> is not safe + auto useBox = Mantid::Kernel::make_unique<bool[]>(numBoxes); + memset(useBox.get(), 0, sizeof(bool) * numBoxes); - // Create the data set - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + // Create the data set (will outlive this object - output of create) + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); this->dataSet = visualDataSet; visualDataSet->Allocate(numBoxes); - vtkIdList *hexPointList = vtkIdList::New(); + vtkNew<vtkIdList> hexPointList; hexPointList->SetNumberOfIds(8); NormFuncIMDNodePtr normFunction = makeMDEventNormalizationFunction( - m_normalizationOption, ws.get(), ws.get()->hasMask()); + m_normalizationOption, ws.get()); // This can be parallelized // cppcheck-suppress syntaxError @@ -117,39 +118,41 @@ void vtkMDHexFactory::doCreate( if (!isSpecial(signal_normalized) && m_thresholdRange->inRange(signal_normalized)) { // Cache the signal and using of it - signalArray[i] = float(signal_normalized); + signalCache[i] = float(signal_normalized); useBox[i] = true; // Get the coordinates. size_t numVertexes = 0; - coord_t *coords; + std::unique_ptr<coord_t> coords; // If slicing down to 3D, specify which dimensions to keep. - if (this->slice) - coords = box->getVertexesArray(numVertexes, 3, this->sliceMask); - else - coords = box->getVertexesArray(numVertexes); + if (this->slice) { + coords = std::unique_ptr<coord_t>( + box->getVertexesArray(numVertexes, 3, this->sliceMask.get())); + } else { + coords = + std::unique_ptr<coord_t>(box->getVertexesArray(numVertexes)); + } if (numVertexes == 8) { // Iterate through all coordinates. Candidate for speed improvement. for (size_t v = 0; v < numVertexes; v++) { - coord_t *coord = coords + v * 3; + coord_t *coord = coords.get() + v * 3; // Set the point at that given ID points->SetPoint(i * 8 + v, coord[0], coord[1], coord[2]); std::string msg; } } // valid number of vertexes returned - - // Free memory - delete[] coords; + } else { + useBox[i] = false; } } // For each box if (VERBOSE) std::cout << tim << " to create the necessary points." << std::endl; // Add points - visualDataSet->SetPoints(points); + visualDataSet->SetPoints(points.GetPointer()); for (size_t i = 0; i < boxes.size(); i++) { if (useBox[i]) { @@ -157,7 +160,7 @@ void vtkMDHexFactory::doCreate( vtkIdType pointIds = i * 8; // Add signal - signals->InsertNextValue(signalArray[i]); + signals->InsertNextValue(signalCache[i]); hexPointList->SetId(0, pointIds + 0); // xyx hexPointList->SetId(1, pointIds + 1); // dxyz @@ -169,7 +172,8 @@ void vtkMDHexFactory::doCreate( hexPointList->SetId(7, pointIds + 6); // xdydz // Add cells - visualDataSet->InsertNextCell(VTK_HEXAHEDRON, hexPointList); + visualDataSet->InsertNextCell(VTK_HEXAHEDRON, + hexPointList.GetPointer()); double bounds[6]; @@ -182,19 +186,15 @@ void vtkMDHexFactory::doCreate( } } // for each box. - delete[] signalArray; - delete[] useBox; - // Shrink to fit signals->Squeeze(); visualDataSet->Squeeze(); // Add scalars - visualDataSet->GetCellData()->SetScalars(signals); + visualDataSet->GetCellData()->SetScalars(signals.GetPointer()); // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullUnstructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); this->dataSet = visualDataSet; @@ -213,7 +213,8 @@ stack. @Return a fully constructed vtkUnstructuredGrid containing geometric and scalar data. */ -vtkDataSet *vtkMDHexFactory::create(ProgressAction &progressUpdating) const { +vtkSmartPointer<vtkDataSet> +vtkMDHexFactory::create(ProgressAction &progressUpdating) const { this->dataSet = tryDelegatingCreation<IMDEventWorkspace, 3>( m_workspace, progressUpdating, false); if (this->dataSet != NULL) { @@ -226,8 +227,8 @@ vtkDataSet *vtkMDHexFactory::create(ProgressAction &progressUpdating) const { if (nd > 3) { // Slice from >3D down to 3D this->slice = true; - this->sliceMask = new bool[nd]; - this->sliceImplicitFunction = new MDImplicitFunction(); + this->sliceMask = Mantid::Kernel::make_unique<bool[]>(nd); + this->sliceImplicitFunction = boost::make_shared<MDImplicitFunction>(); // Make the mask of dimensions // TODO: Smarter mapping @@ -261,12 +262,6 @@ vtkDataSet *vtkMDHexFactory::create(ProgressAction &progressUpdating) const { CALL_MDEVENT_FUNCTION(this->doCreate, imdws); progressUpdating.eventRaised(1.0); - // Clean up - if (this->slice) { - delete[] this->sliceMask; - delete this->sliceImplicitFunction; - } - // The macro does not allow return calls, so we used a member variable. return this->dataSet; } diff --git a/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp index 8a849bbe88b45b4003907f6f267497598c441d24..2351d0e36574e7e137e436aa584969481b1aac65 100644 --- a/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDHistoHex4DFactory.cpp @@ -85,11 +85,10 @@ namespace VATES @return fully constructed vtkDataSet. */ template<typename TimeMapper> - vtkDataSet* vtkMDHistoHex4DFactory<TimeMapper>::create(ProgressAction& progressUpdating) const + vtkSmartPointer<vtkDataSet> vtkMDHistoHex4DFactory<TimeMapper>::create(ProgressAction& progressUpdating) const { - vtkDataSet* product = tryDelegatingCreation<MDHistoWorkspace, 4>(m_workspace, progressUpdating); - if(product != NULL) - { + auto product = tryDelegatingCreation<MDHistoWorkspace, 4>(m_workspace, progressUpdating); + if (product != nullptr) { return product; } else diff --git a/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp index 3653973f9d2ab305a922958ad86f159caaa6bea2..d08b83764dc49727c964e177d871863de56961ce 100644 --- a/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDHistoHexFactory.cpp @@ -13,7 +13,6 @@ #include "MantidKernel/ReadLock.h" #include "vtkNew.h" -#include "vtkSmartPointer.h" #include "vtkStructuredGrid.h" #include "vtkFloatArray.h" #include "vtkDoubleArray.h" @@ -84,8 +83,8 @@ void vtkMDHistoHexFactory::validate() const { validateWsNotNull(); } *stack. * @return the vtkDataSet created */ -vtkDataSet * -vtkMDHistoHexFactory::create3Dor4D(size_t timestep, +vtkSmartPointer<vtkDataSet> +vtkMDHistoHexFactory::create3Dor4D(size_t timestep, ProgressAction &progressUpdate) const { // Acquire a scoped read-only lock to the workspace (prevent segfault from // algos modifying ws) @@ -109,8 +108,8 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep, const int imageSize = (nBinsX) * (nBinsY) * (nBinsZ); - //vtkSmartPointer<vtkStructuredGrid> visualDataSet = vtkSmartPointer<vtkStructuredGrid>::New(); - vtkStructuredGrid* visualDataSet = vtkStructuredGrid::New(); + vtkSmartPointer<vtkStructuredGrid> visualDataSet = + vtkSmartPointer<vtkStructuredGrid>::New(); visualDataSet->SetDimensions(nBinsX+1,nBinsY+1,nBinsZ+1); // Array with true where the voxel should be shown @@ -195,12 +194,12 @@ vtkMDHistoHexFactory::create3Dor4D(size_t timestep, // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullStructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); } - return visualDataSet; + vtkSmartPointer<vtkDataSet> dataset = visualDataSet; + return dataset; } @@ -210,9 +209,9 @@ Create the vtkStructuredGrid from the provided workspace stack. @return fully constructed vtkDataSet. */ -vtkDataSet * +vtkSmartPointer<vtkDataSet> vtkMDHistoHexFactory::create(ProgressAction &progressUpdating) const { - vtkDataSet *product = + auto product = tryDelegatingCreation<MDHistoWorkspace, 3>(m_workspace, progressUpdating); if (product != NULL) { return product; diff --git a/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp index 296f744cafc12311ed586a2089c603e137e72804..a8f7983e118cdabddcb4fea33f8eaa719bc0fd10 100644 --- a/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDHistoLineFactory.cpp @@ -5,7 +5,6 @@ #include "vtkCellArray.h" #include "vtkCellData.h" #include "vtkFloatArray.h" -#include "vtkSmartPointer.h" #include "vtkLine.h" #include <vector> #include "MantidAPI/IMDWorkspace.h" @@ -66,11 +65,11 @@ namespace Mantid @param progressUpdating: Reporting object to pass progress information up the stack. @return fully constructed vtkDataSet. */ - vtkDataSet* vtkMDHistoLineFactory::create(ProgressAction& progressUpdating) const - { - vtkDataSet* product = tryDelegatingCreation<MDHistoWorkspace, 1>(m_workspace, progressUpdating); - if(product != NULL) - { + vtkSmartPointer<vtkDataSet> + vtkMDHistoLineFactory::create(ProgressAction &progressUpdating) const { + auto product = tryDelegatingCreation<MDHistoWorkspace, 1>( + m_workspace, progressUpdating); + if (product != nullptr) { return product; } else @@ -86,10 +85,10 @@ namespace Mantid coord_t incrementX = (maxX - minX) / coord_t(nBinsX-1); const int imageSize = nBinsX; - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->Allocate(static_cast<int>(imageSize)); - vtkFloatArray * signal = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signal; signal->Allocate(imageSize); signal->SetName(vtkDataSetFactory::ScalarName.c_str()); signal->SetNumberOfComponents(1); @@ -138,10 +137,10 @@ namespace Mantid points->Squeeze(); signal->Squeeze(); - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); visualDataSet->Allocate(imageSize); - visualDataSet->SetPoints(points); - visualDataSet->GetCellData()->SetScalars(signal); + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signal.GetPointer()); for (int i = 0; i < nBinsX - 1; i++) { @@ -156,19 +155,17 @@ namespace Mantid } } - points->Delete(); - signal->Delete(); visualDataSet->Squeeze(); // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullUnstructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); } - return visualDataSet; + vtkSmartPointer<vtkDataSet> dataset = visualDataSet; + return dataset; } } diff --git a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp index 5413e173b246519bac7a43cb2f923107b971d8ea..5b98e3afd04a2454088467c5346ce76915da6791 100644 --- a/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDHistoQuadFactory.cpp @@ -11,11 +11,11 @@ #include "vtkCellData.h" #include "vtkFloatArray.h" #include "vtkQuad.h" -#include "vtkSmartPointer.h" +#include "vtkNew.h" #include <vector> #include "MantidKernel/ReadLock.h" #include "MantidKernel/Logger.h" - +#include "MantidKernel/make_unique.h" using Mantid::API::IMDWorkspace; using Mantid::Kernel::CPUTimer; @@ -68,11 +68,11 @@ namespace Mantid @param progressUpdating: Reporting object to pass progress information up the stack. @return fully constructed vtkDataSet. */ - vtkDataSet* vtkMDHistoQuadFactory::create(ProgressAction& progressUpdating) const - { - vtkDataSet* product = tryDelegatingCreation<MDHistoWorkspace, 2>(m_workspace, progressUpdating); - if(product != NULL) - { + vtkSmartPointer<vtkDataSet> + vtkMDHistoQuadFactory::create(ProgressAction &progressUpdating) const { + auto product = tryDelegatingCreation<MDHistoWorkspace, 2>( + m_workspace, progressUpdating); + if (product != nullptr) { return product; } else @@ -99,10 +99,10 @@ namespace Mantid } const int imageSize = (nBinsX ) * (nBinsY ); - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->Allocate(static_cast<int>(imageSize)); - vtkFloatArray * signal = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signal; signal->Allocate(imageSize); signal->SetName(vtkDataSetFactory::ScalarName.c_str()); signal->SetNumberOfComponents(1); @@ -118,10 +118,9 @@ namespace Mantid is set so that all required vertices are marked, and created in a second step. */ // Array of the points that should be created, set to false - bool * pointNeeded = new bool[nPointsX*nPointsY]; - memset(pointNeeded, 0, nPointsX*nPointsY*sizeof(bool)); + auto pointNeeded = std::vector<bool>(nPointsX * nPointsY, false); // Array with true where the voxel should be shown - bool * voxelShown = new bool[nBinsX*nBinsY]; + auto voxelShown = std::vector<bool>(nBinsX * nBinsY); double progressFactor = 0.5/double(nBinsX); double progressOffset = 0.5; @@ -169,7 +168,7 @@ namespace Mantid in[2] = 0; // Array with the point IDs (only set where needed) - vtkIdType * pointIDs = new vtkIdType[nPointsX*nPointsY]; + std::vector<vtkIdType> pointIDs(nPointsX * nPointsY, 0); index = 0; for (int i = 0; i < nPointsX; i++) { @@ -195,13 +194,15 @@ namespace Mantid std::cout << tim << " to create the needed points." << std::endl; - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); visualDataSet->Allocate(imageSize); - visualDataSet->SetPoints(points); - visualDataSet->GetCellData()->SetScalars(signal); + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signal.GetPointer()); // ------ Quad creation ---------------- - vtkQuad* quad = vtkQuad::New(); // Significant speed increase by creating ONE quad + vtkNew<vtkQuad> quad; // Significant speed increase by creating ONE quad + // (assume vtkNew doesn't add significant + // overhead) index = 0; for (int i = 0; i < nBinsX; i++) { @@ -219,26 +220,20 @@ namespace Mantid index++; } } - quad->Delete(); std::cout << tim << " to create and add the quads." << std::endl; - points->Delete(); - signal->Delete(); visualDataSet->Squeeze(); - delete [] pointIDs; - delete [] voxelShown; - delete [] pointNeeded; // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullUnstructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); } - return visualDataSet; + vtkSmartPointer<vtkDataSet> dataSet = visualDataSet; + return dataSet; } } diff --git a/Vates/VatesAPI/src/vtkMDLineFactory.cpp b/Vates/VatesAPI/src/vtkMDLineFactory.cpp index 12bad1745a0fae2ec523c00b7bcd99ad0080005e..8bc5aa03b77fca40a62d523d90a00762724783fa 100644 --- a/Vates/VatesAPI/src/vtkMDLineFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDLineFactory.cpp @@ -12,8 +12,10 @@ #include <vtkFloatArray.h> #include <vtkLine.h> #include <vtkCellData.h> +#include <vtkNew.h> #include "MantidKernel/ReadLock.h" #include "MantidKernel/Logger.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::API; @@ -43,10 +45,11 @@ Create the vtkStructuredGrid from the provided workspace stack. @return fully constructed vtkDataSet. */ -vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { - vtkDataSet *product = tryDelegatingCreation<IMDEventWorkspace, 1>( - m_workspace, progressUpdating); - if (product != NULL) { +vtkSmartPointer<vtkDataSet> +vtkMDLineFactory::create(ProgressAction &progressUpdating) const { + auto product = tryDelegatingCreation<IMDEventWorkspace, 1>(m_workspace, + progressUpdating); + if (product != nullptr) { return product; } else { g_log.warning() << "Factory " << this->getFactoryTypeName() @@ -65,7 +68,7 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { /* Write mask array with correct order for each internal dimension. */ - bool *masks = new bool[nDims]; + auto masks = Mantid::Kernel::make_unique<bool[]>(nDims); for (size_t i_dim = 0; i_dim < nDims; ++i_dim) { bool bIntegrated = imdws->getDimension(i_dim)->getIsIntegrated(); masks[i_dim] = @@ -77,21 +80,21 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { createIteratorWithNormalization(m_normalizationOption, imdws.get())); // Create 2 points per box. - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->SetNumberOfPoints(it->getDataSize() * 2); // One scalar per box - vtkFloatArray *signals = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signals; signals->Allocate(it->getDataSize()); signals->SetName(vtkDataSetFactory::ScalarName.c_str()); signals->SetNumberOfComponents(1); size_t nVertexes; - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); visualDataSet->Allocate(it->getDataSize()); - vtkIdList *linePointList = vtkIdList::New(); + vtkNew<vtkIdList> linePointList; linePointList->SetNumberOfIds(2); Mantid::API::CoordTransform const *transform = NULL; @@ -100,7 +103,7 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { } Mantid::coord_t out[1]; - bool *useBox = new bool[it->getDataSize()]; + auto useBox = std::vector<bool>(it->getDataSize()); double progressFactor = 0.5 / double(it->getDataSize()); double progressOffset = 0.5; @@ -109,20 +112,18 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { do { progressUpdating.eventRaised(double(iBox) * progressFactor); - Mantid::signal_t signal_normalized = it->getNormalizedSignalWithMask(); + Mantid::signal_t signal_normalized = it->getNormalizedSignal(); if (!isSpecial(signal_normalized) && m_thresholdRange->inRange(signal_normalized)) { useBox[iBox] = true; signals->InsertNextValue(static_cast<float>(signal_normalized)); - coord_t *coords = - it->getVertexesArray(nVertexes, nNonIntegrated, masks); - delete[] coords; - coords = it->getVertexesArray(nVertexes, nNonIntegrated, masks); + auto coords = std::unique_ptr<coord_t>( + it->getVertexesArray(nVertexes, nNonIntegrated, masks.get())); // Iterate through all coordinates. Candidate for speed improvement. for (size_t v = 0; v < nVertexes; ++v) { - coord_t *coord = coords + v * 1; + coord_t *coord = coords.get() + v * 1; size_t id = iBox * 2 + v; if (m_useTransform) { transform->apply(coord, out); @@ -131,8 +132,6 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { points->SetPoint(id, coord[0], 0, 0); } } - // Free memory - delete[] coords; } // valid number of vertexes returned else { useBox[iBox] = false; @@ -140,7 +139,6 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { ++iBox; } while (it->next()); - delete[] masks; for (size_t ii = 0; ii < it->getDataSize(); ++ii) { progressUpdating.eventRaised((double(ii) * progressFactor) + progressOffset); @@ -150,31 +148,25 @@ vtkDataSet *vtkMDLineFactory::create(ProgressAction &progressUpdating) const { linePointList->SetId(0, pointIds + 0); // xyx linePointList->SetId(1, pointIds + 1); // dxyz - visualDataSet->InsertNextCell(VTK_LINE, linePointList); + visualDataSet->InsertNextCell(VTK_LINE, linePointList.GetPointer()); } // valid number of vertexes returned } - delete[] useBox; - signals->Squeeze(); points->Squeeze(); - visualDataSet->SetPoints(points); - visualDataSet->GetCellData()->SetScalars(signals); + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signals.GetPointer()); visualDataSet->Squeeze(); - signals->Delete(); - points->Delete(); - linePointList->Delete(); - // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullUnstructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); } - return visualDataSet; + vtkSmartPointer<vtkDataSet> dataset = visualDataSet; + return dataset; } } diff --git a/Vates/VatesAPI/src/vtkMDQuadFactory.cpp b/Vates/VatesAPI/src/vtkMDQuadFactory.cpp index 23421ff26b764661ea3489fdc7342f9c066f10af..f04a602f2df38b9ab81c7093ceaed2386fe5fc97 100644 --- a/Vates/VatesAPI/src/vtkMDQuadFactory.cpp +++ b/Vates/VatesAPI/src/vtkMDQuadFactory.cpp @@ -12,8 +12,10 @@ #include <vtkFloatArray.h> #include <vtkQuad.h> #include <vtkCellData.h> +#include <vtkNew.h> #include "MantidKernel/ReadLock.h" #include "MantidKernel/Logger.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::API; @@ -39,10 +41,11 @@ Create the vtkStructuredGrid from the provided workspace stack. @return fully constructed vtkDataSet. */ -vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { - vtkDataSet *product = tryDelegatingCreation<IMDEventWorkspace, 2>( - m_workspace, progressUpdating); - if (product != NULL) { +vtkSmartPointer<vtkDataSet> +vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { + auto product = tryDelegatingCreation<IMDEventWorkspace, 2>(m_workspace, + progressUpdating); + if (product != nullptr) { return product; } else { g_log.warning() << "Factory " << this->getFactoryTypeName() @@ -61,7 +64,7 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { /* Write mask array with correct order for each internal dimension. */ - bool *masks = new bool[nDims]; + auto masks = Mantid::Kernel::make_unique<bool[]>(nDims); for (size_t i_dim = 0; i_dim < nDims; ++i_dim) { bool bIntegrated = imdws->getDimension(i_dim)->getIsIntegrated(); masks[i_dim] = @@ -74,21 +77,21 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { createIteratorWithNormalization(m_normalizationOption, imdws.get())); // Create 4 points per box. - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->SetNumberOfPoints(it->getDataSize() * 4); // One scalar per box - vtkFloatArray *signals = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signals; signals->Allocate(it->getDataSize()); signals->SetName(vtkDataSetFactory::ScalarName.c_str()); signals->SetNumberOfComponents(1); size_t nVertexes; - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); visualDataSet->Allocate(it->getDataSize()); - vtkIdList *quadPointList = vtkIdList::New(); + vtkNew<vtkIdList> quadPointList; quadPointList->SetNumberOfIds(4); Mantid::API::CoordTransform const *transform = NULL; @@ -97,7 +100,7 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { } Mantid::coord_t out[2]; - bool *useBox = new bool[it->getDataSize()]; + auto useBox = std::vector<bool>(it->getDataSize()); double progressFactor = 0.5 / double(it->getDataSize()); double progressOffset = 0.5; @@ -106,19 +109,17 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { do { progressUpdating.eventRaised(progressFactor * double(iBox)); - Mantid::signal_t signal = it->getNormalizedSignalWithMask(); + Mantid::signal_t signal = it->getNormalizedSignal(); if (!isSpecial(signal) && m_thresholdRange->inRange(signal)) { useBox[iBox] = true; signals->InsertNextValue(static_cast<float>(signal)); - coord_t *coords = - it->getVertexesArray(nVertexes, nNonIntegrated, masks); - delete[] coords; - coords = it->getVertexesArray(nVertexes, nNonIntegrated, masks); + auto coords = std::unique_ptr<coord_t>( + it->getVertexesArray(nVertexes, nNonIntegrated, masks.get())); // Iterate through all coordinates. Candidate for speed improvement. for (size_t v = 0; v < nVertexes; ++v) { - coord_t *coord = coords + v * 2; + coord_t *coord = coords.get() + v * 2; size_t id = iBox * 4 + v; if (m_useTransform) { transform->apply(coord, out); @@ -127,8 +128,6 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { points->SetPoint(id, coord[0], coord[1], 0); } } - // Free memory - delete[] coords; } // valid number of vertexes returned else { useBox[iBox] = false; @@ -136,7 +135,6 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { ++iBox; } while (it->next()); - delete[] masks; for (size_t ii = 0; ii < it->getDataSize(); ++ii) { progressUpdating.eventRaised((progressFactor * double(ii)) + progressOffset); @@ -148,31 +146,25 @@ vtkDataSet *vtkMDQuadFactory::create(ProgressAction &progressUpdating) const { quadPointList->SetId(1, pointIds + 1); // dxyz quadPointList->SetId(2, pointIds + 3); // dxdyz quadPointList->SetId(3, pointIds + 2); // xdyz - visualDataSet->InsertNextCell(VTK_QUAD, quadPointList); + visualDataSet->InsertNextCell(VTK_QUAD, quadPointList.GetPointer()); } // valid number of vertexes returned } - delete[] useBox; - signals->Squeeze(); points->Squeeze(); - visualDataSet->SetPoints(points); - visualDataSet->GetCellData()->SetScalars(signals); + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signals.GetPointer()); visualDataSet->Squeeze(); - signals->Delete(); - points->Delete(); - quadPointList->Delete(); - // Hedge against empty data sets if (visualDataSet->GetNumberOfPoints() <= 0) { - visualDataSet->Delete(); vtkNullUnstructuredGrid nullGrid; visualDataSet = nullGrid.createNullData(); } - return visualDataSet; + vtkSmartPointer<vtkDataSet> dataSet = visualDataSet; + return dataSet; } } diff --git a/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp b/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp index c1d170f5911e45540ce653ab46d74e781c7f5544..ced7bba4f138f067b1a9c091a91ed76751cbac2a 100644 --- a/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp +++ b/Vates/VatesAPI/src/vtkSplatterPlotFactory.cpp @@ -5,6 +5,7 @@ #include "MantidAPI/IMDHistoWorkspace.h" #include "MantidKernel/CPUTimer.h" #include "MantidKernel/ReadLock.h" +#include "MantidKernel/make_unique.h" #include "MantidDataObjects/MDEventFactory.h" #include "MantidGeometry/MDGeometry/MDHistoDimension.h" #include "MantidVatesAPI/ProgressAction.h" @@ -25,6 +26,7 @@ #include <vtkPolyVertex.h> #include <vtkSystemIncludes.h> #include <vtkUnstructuredGrid.h> +#include <vtkNew.h> #include <algorithm> #include <boost/math/special_functions/fpclassify.hpp> @@ -50,8 +52,7 @@ vtkSplatterPlotFactory::vtkSplatterPlotFactory( const size_t numPoints, const double percentToUse) : m_thresholdRange(thresholdRange), m_scalarName(scalarName), m_numPoints(numPoints), m_percentToUse(percentToUse), - m_buildSortedList(true), m_wsName(""), dataSet(NULL), slice(false), - sliceMask(NULL), sliceImplicitFunction(NULL), m_time(0.0), + m_buildSortedList(true), m_wsName(""), slice(false), m_time(0.0), m_minValue(0.1), m_maxValue(0.1), m_metaDataExtractor(new MetaDataExtractorUtils()), m_metadataJsonManager(new MetadataJsonManager()), @@ -77,13 +78,7 @@ void vtkSplatterPlotFactory::doCreate( // from algos modifying ws) ReadLock lock(*ws); - // Avoid checking if each box is masked if there is no mask on the workspace - SigFuncIMDNodePtr getSignalFunction; - if (ws->hasMask()) { - getSignalFunction = &IMDNode::getSignalNormalizedWithMask; - } else { - getSignalFunction = &IMDNode::getSignalNormalized; - } + SigFuncIMDNodePtr getSignalFunction = &IMDNode::getSignalNormalized; // Find out how many events to plot, and the percentage of the largest // boxes to use. @@ -108,7 +103,7 @@ void vtkSplatterPlotFactory::doCreate( // slice function std::vector<API::IMDNode *> boxes; if (this->slice) { - ws->getBox()->getBoxes(boxes, 1000, true, this->sliceImplicitFunction); + ws->getBox()->getBoxes(boxes, 1000, true, this->sliceImplicitFunction.get()); } else { ws->getBox()->getBoxes(boxes, 1000, true); } @@ -246,21 +241,21 @@ void vtkSplatterPlotFactory::doCreate( } // Create the point list, one position for each point actually used - vtkPoints *points = vtkPoints::New(); + auto points = vtkSmartPointer<vtkPoints>::New(); points->Allocate(numPoints); points->SetNumberOfPoints(numPoints); // The list of IDs of points used, one ID per point, since points // are not reused to form polygon facets, etc. - vtkIdType *ids = new vtkIdType[numPoints]; + std::vector<vtkIdType> ids(numPoints, 0); // Only one scalar for each cell, NOT one per point - vtkFloatArray *signal = vtkFloatArray::New(); + auto signal = vtkSmartPointer<vtkFloatArray>::New(); signal->Allocate(numCells); signal->SetName(m_scalarName.c_str()); // Create the data set. Need space for each cell, not for each point - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); this->dataSet = visualDataSet; visualDataSet->Allocate(numCells); // Now copy the saved point, cell and signal info into vtk data structures @@ -275,7 +270,7 @@ void vtkSplatterPlotFactory::doCreate( } signal->InsertNextTuple1(saved_signals[cell_i]); visualDataSet->InsertNextCell( - VTK_POLY_VERTEX, saved_n_points_in_cell[cell_i], ids + startPointIndex); + VTK_POLY_VERTEX, saved_n_points_in_cell[cell_i], &ids[startPointIndex]); } if (VERBOSE) { @@ -290,8 +285,6 @@ void vtkSplatterPlotFactory::doCreate( // Add points and scalars visualDataSet->SetPoints(points); visualDataSet->GetCellData()->SetScalars(signal); - - delete[] ids; } /** @@ -351,22 +344,22 @@ void vtkSplatterPlotFactory::doCreateMDHisto( const int imageSize = (nBinsX) * (nBinsY) * (nBinsZ); // VTK structures - vtkFloatArray *signal = vtkFloatArray::New(); + vtkNew<vtkFloatArray> signal; signal->Allocate(imageSize); signal->SetName(m_scalarName.c_str()); signal->SetNumberOfComponents(1); - vtkPoints *points = vtkPoints::New(); + vtkNew<vtkPoints> points; points->Allocate(static_cast<int>(imageSize)); // Set up the actual vtkDataSet, here the vtkUnstructuredGrid, the cell type // we choose here is the vtk_poly_vertex - vtkUnstructuredGrid *visualDataSet = vtkUnstructuredGrid::New(); + auto visualDataSet = vtkSmartPointer<vtkUnstructuredGrid>::New(); this->dataSet = visualDataSet; visualDataSet->Allocate(imageSize); // Create the vertex structure. - vtkVertex *vertex = vtkVertex::New(); + vtkNew<vtkVertex> vertex; // Check if the workspace requires 4D handling. bool do4D = doMDHisto4D(workspace); @@ -424,13 +417,8 @@ void vtkSplatterPlotFactory::doCreateMDHisto( } } - vertex->Delete(); - - visualDataSet->SetPoints(points); - visualDataSet->GetCellData()->SetScalars(signal); - - points->Delete(); - signal->Delete(); + visualDataSet->SetPoints(points.GetPointer()); + visualDataSet->GetCellData()->SetScalars(signal.GetPointer()); visualDataSet->Squeeze(); } @@ -488,7 +476,7 @@ bool vtkSplatterPlotFactory::doMDHisto4D( * the stack. * @return fully constructed vtkDataSet. */ -vtkDataSet * +vtkSmartPointer<vtkDataSet> vtkSplatterPlotFactory::create(ProgressAction &progressUpdating) const { UNUSED_ARG(progressUpdating); @@ -504,8 +492,8 @@ vtkSplatterPlotFactory::create(ProgressAction &progressUpdating) const { if (nd > 3) { // Slice from >3D down to 3D this->slice = true; - this->sliceMask = new bool[nd]; - this->sliceImplicitFunction = new MDImplicitFunction(); + this->sliceMask = Mantid::Kernel::make_unique<bool[]>(nd); + this->sliceImplicitFunction = boost::make_shared<MDImplicitFunction>(); // Make the mask of dimensions // TODO: Smarter mapping for (size_t d = 0; d < nd; d++) @@ -536,7 +524,7 @@ vtkSplatterPlotFactory::create(ProgressAction &progressUpdating) const { // Set the instrument m_instrument = m_metaDataExtractor->extractInstrument(m_workspace); - double *range = NULL; + double *range = nullptr; if (dataSet) { range = dataSet->GetScalarRange(); @@ -560,12 +548,6 @@ vtkSplatterPlotFactory::create(ProgressAction &progressUpdating) const { this->doCreateMDHisto(histoWorkspace); } - // Clean up - if (this->slice) { - delete[] this->sliceMask; - delete this->sliceImplicitFunction; - } - // Add metadata in json format this->addMetadata(); @@ -618,7 +600,7 @@ void vtkSplatterPlotFactory::addMetadata() const { const double defaultValue = 0.1; if (this->dataSet) { - double *range = NULL; + double *range = nullptr; range = dataSet->GetScalarRange(); if (range) { @@ -638,15 +620,13 @@ void vtkSplatterPlotFactory::addMetadata() const { // Append metadata std::string jsonString = m_metadataJsonManager->getSerializedJson(); - vtkFieldData *outputFD = vtkFieldData::New(); + vtkNew<vtkFieldData> outputFD; // Add metadata to dataset. MetadataToFieldData convert; - convert(outputFD, jsonString, + convert(outputFD.GetPointer(), jsonString, m_vatesConfigurations->getMetadataIdJson().c_str()); - dataSet->SetFieldData(outputFD); - - outputFD->Delete(); + dataSet->SetFieldData(outputFD.GetPointer()); } } @@ -667,13 +647,13 @@ void vtkSplatterPlotFactory::setMetadata(vtkFieldData *fieldData, // Create a new field data array MetadataToFieldData convertMtoF; - vtkFieldData *outputFD = vtkFieldData::New(); + vtkNew<vtkFieldData> outputFD; outputFD->ShallowCopy(fieldData); - convertMtoF(outputFD, xmlString, XMLDefinitions::metaDataId().c_str()); - convertMtoF(outputFD, jsonString, + convertMtoF(outputFD.GetPointer(), xmlString, + XMLDefinitions::metaDataId().c_str()); + convertMtoF(outputFD.GetPointer(), jsonString, m_vatesConfigurations->getMetadataIdJson().c_str()); - dataSet->SetFieldData(outputFD); - outputFD->Delete(); + dataSet->SetFieldData(outputFD.GetPointer()); } /** diff --git a/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h index f6927da802b4726ea8b769069ba8ad994d2df05d..c8275d4c2be6046b54cb732f33d82d383d0db07b 100644 --- a/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/EventNexusLoadingPresenterTest.h @@ -3,6 +3,7 @@ #include <cxxtest/TestSuite.h> #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> #include <gmock/gmock.h> #include <gtest/gtest.h> @@ -11,6 +12,7 @@ #include "MantidAPI/FileFinder.h" #include "MantidVatesAPI/EventNexusLoadingPresenter.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::VATES; using namespace testing; @@ -38,35 +40,46 @@ public: void testConstructWithEmptyFileThrows() { - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", EventNexusLoadingPresenter(new MockMDLoadingView, ""), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw if an empty file string is given.", + EventNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), ""), + std::invalid_argument); } void testConstructWithNullViewThrows() { - MockMDLoadingView* pView = NULL; - - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", EventNexusLoadingPresenter(pView, "some_file"), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw if a null view is given.", + EventNexusLoadingPresenter(nullptr, "some_file"), + std::invalid_argument); } void testConstruct() { - TSM_ASSERT_THROWS_NOTHING("Object should be created without exception.", EventNexusLoadingPresenter(new MockMDLoadingView, getSuitableFile())); + TSM_ASSERT_THROWS_NOTHING( + "Object should be created without exception.", + EventNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile())); } void testCanReadFile() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getUnhandledFile()); - TSM_ASSERT("A file of this type cannot and should not be read by this presenter!.", !presenter.canReadFile()); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile()); + TSM_ASSERT( + "A file of this type cannot and should not be read by this presenter!.", + !presenter.canReadFile()); } void testExecution() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)); - EXPECT_CALL(*view, getTime()).Times(AtLeast(1)); - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + auto mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, getLoadInMemory()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, getTime()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; @@ -78,9 +91,9 @@ void testExecution() MockProgressAction mockDrawingProgressUpdate; //Create the presenter and runit! - EventNexusLoadingPresenter presenter(view, getSuitableFile()); + EventNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressUpdate, mockDrawingProgressUpdate); + vtkSmartPointer<vtkDataSet> product = presenter.execute(&factory, mockLoadingProgressUpdate, mockDrawingProgressUpdate); TSM_ASSERT("Should have generated a vtkDataSet", NULL != product); TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName())); @@ -90,33 +103,38 @@ void testExecution() TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testGetTDimension() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT("EventNexus MDEW are created in fixed 3D.", !presenter.hasTDimensionAvailable()); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT("EventNexus MDEW are created in fixed 3D.", + !presenter.hasTDimensionAvailable()); } void testCallGetTDimensionValuesThrows() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getGeometryXML(), std::runtime_error); } void testExecuteLoadMetadata() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); presenter.executeLoadMetadata(); TSM_ASSERT_THROWS("Should always throw. Algorithm fixed to create 3 dimensions.", presenter.getTimeStepValues(), std::runtime_error); TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable()); @@ -125,8 +143,10 @@ void testExecuteLoadMetadata() void testGetWorkspaceTypeName() { - EventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); + EventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_EQUALS("Characterisation Test Failed", "", + presenter.getWorkspaceTypeName()); } diff --git a/Vates/VatesAPI/test/FieldDataToMetadataTest.h b/Vates/VatesAPI/test/FieldDataToMetadataTest.h index 2e90ada79ee1f017dcad595b580dd9a8837070bb..92c7ddeb3f038da34f00948aa515e455d8201625 100644 --- a/Vates/VatesAPI/test/FieldDataToMetadataTest.h +++ b/Vates/VatesAPI/test/FieldDataToMetadataTest.h @@ -5,6 +5,7 @@ #include <vtkCharArray.h> #include <vtkFieldData.h> #include "MantidVatesAPI/FieldDataToMetadata.h" +#include <vtkSmartPointer.h> using Mantid::VATES::FieldDataToMetadata; @@ -17,7 +18,7 @@ private: static vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id) { vtkFieldData* fieldData = vtkFieldData::New(); - vtkCharArray* charArray = vtkCharArray::New(); + auto charArray = vtkSmartPointer<vtkCharArray>::New(); charArray->SetName(id.c_str()); charArray->Allocate(100); for(unsigned int i = 0; i < testData.size(); i++) @@ -29,8 +30,7 @@ private: } } - fieldData->AddArray(charArray); - charArray->Delete(); + fieldData->AddArray(charArray.GetPointer()); return fieldData; } @@ -40,35 +40,35 @@ public: { const std::string id = "1"; const std::string testData = "abc"; - vtkFieldData* fieldData = createFieldDataWithCharArray(testData, id); + vtkSmartPointer<vtkFieldData> fieldData = + createFieldDataWithCharArray(testData, id); FieldDataToMetadata function; std::string metadata = function.execute(fieldData, id); TSM_ASSERT_EQUALS("The Function failed to properly convert field data to metadata", testData, metadata); - fieldData->Delete(); } void testOperatorOverload() { const std::string id = "1"; const std::string testData = "abc"; - vtkFieldData* fieldData = createFieldDataWithCharArray(testData, id); + vtkSmartPointer<vtkFieldData> fieldData = + createFieldDataWithCharArray(testData, id); FieldDataToMetadata function; TSM_ASSERT_EQUALS("Results from two equivalent methods differ.", function(fieldData, id), function.execute(fieldData, id)); - fieldData->Delete(); } void testThrowsIfNotFound() { const std::string id = "1"; const std::string testData = "abc"; - vtkFieldData* fieldData = createFieldDataWithCharArray(testData, id); + vtkSmartPointer<vtkFieldData> fieldData = + createFieldDataWithCharArray(testData, id); FieldDataToMetadata function; TSM_ASSERT_THROWS("Unknown id requested. Should have thrown.", function.execute(fieldData, "x"), std::runtime_error ); - fieldData->Delete(); } void testThrowsIfNullFieldData() diff --git a/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h index c3109fb2f995f8cd462e4689d536dac65479a771..5ee24e12f022b9adf3ee6b7b2bf2abdc307842c6 100644 --- a/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDEWEventNexusLoadingPresenterTest.h @@ -3,6 +3,7 @@ #include <cxxtest/TestSuite.h> #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> #include <gmock/gmock.h> #include <gtest/gtest.h> @@ -11,6 +12,7 @@ #include "MantidAPI/FileFinder.h" #include "MantidVatesAPI/MDEWEventNexusLoadingPresenter.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::VATES; using namespace testing; @@ -40,39 +42,53 @@ public: void testConstructWithEmptyFileThrows() { - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", MDEWEventNexusLoadingPresenter(new MockMDLoadingView, ""), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw if an empty file string is given.", + MDEWEventNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), ""), + std::invalid_argument); } void testConstructWithNullViewThrows() { - MockMDLoadingView* pView = NULL; - - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", MDEWEventNexusLoadingPresenter(pView, "some_file"), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw if a null view is given.", + MDEWEventNexusLoadingPresenter(nullptr, "some_file"), + std::invalid_argument); } void testConstruct() { - TSM_ASSERT_THROWS_NOTHING("Object should be created without exception.", MDEWEventNexusLoadingPresenter(new MockMDLoadingView, getSuitableFile())); + TSM_ASSERT_THROWS_NOTHING( + "Object should be created without exception.", + MDEWEventNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile())); } void testCanReadFile() { - MDEWEventNexusLoadingPresenter presenter(new MockMDLoadingView, getUnhandledFile()); - TSM_ASSERT("A file of this type cannot and should not be read by this presenter!.", !presenter.canReadFile()); + MDEWEventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile()); + TSM_ASSERT( + "A file of this type cannot and should not be read by this presenter!.", + !presenter.canReadFile()); } void testExecution() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + auto mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(testing::Return(true)); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -82,9 +98,10 @@ void testExecution() MockProgressAction mockDrawingProgressAction; //Create the presenter and runit! - MDEWEventNexusLoadingPresenter presenter(view, getSuitableFile()); + MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + vtkSmartPointer<vtkDataSet> product = presenter.execute( + &factory, mockLoadingProgressAction, mockDrawingProgressAction); TSM_ASSERT("Should have generated a vtkDataSet", NULL != product); TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName())); @@ -94,48 +111,59 @@ void testExecution() TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testCallHasTDimThrows() { - MDEWEventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable(), std::runtime_error); + MDEWEventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.hasTDimensionAvailable(), std::runtime_error); } void testCallGetTDimensionValuesThrows() { - MDEWEventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); + MDEWEventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - MDEWEventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); + MDEWEventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getGeometryXML(), std::runtime_error); } void testGetWorkspaceTypeName() { - MDEWEventNexusLoadingPresenter presenter(new MockMDLoadingView, getSuitableFile()); - TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); + MDEWEventNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); + TSM_ASSERT_EQUALS("Characterisation Test Failed", "", + presenter.getWorkspaceTypeName()); } void testTimeLabel() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + auto mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(testing::Return(true)); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -145,30 +173,34 @@ void testTimeLabel() MockProgressAction mockDrawingProgressAction; //Create the presenter and runit! - MDEWEventNexusLoadingPresenter presenter(view, getSuitableFile()); + MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + vtkSmartPointer<vtkDataSet> product = presenter.execute( + &factory, mockLoadingProgressAction, mockDrawingProgressAction); TSM_ASSERT_EQUALS("Time label should be exact.", presenter.getTimeStepLabel(), "D (En)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testAxisLabels() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + auto mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(1)); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(testing::Return(true)); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -178,9 +210,10 @@ void testAxisLabels() MockProgressAction mockDrawingProgressAction; //Create the presenter and runit! - MDEWEventNexusLoadingPresenter presenter(view, getSuitableFile()); + MDEWEventNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + vtkSmartPointer<vtkDataSet> product = presenter.execute( + &factory, mockLoadingProgressAction, mockDrawingProgressAction); TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product)); TSM_ASSERT_EQUALS("X Label should match exactly", getStringFieldDataValue(product, "AxisTitleForX"), @@ -192,10 +225,8 @@ void testAxisLabels() getStringFieldDataValue(product, "AxisTitleForZ"), "C ($\\AA$)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } }; diff --git a/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h index 0ba528b9861c14e086d6d5eed40ef6441784f324..98b85200a19268e38955eab1a5532468b10f15b4 100644 --- a/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDEWInMemoryLoadingPresenterTest.h @@ -10,7 +10,9 @@ #include "MantidAPI/ITableWorkspace.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" #include "MantidVatesAPI/MDEWInMemoryLoadingPresenter.h" +#include "MantidKernel/make_unique.h" #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> using namespace Mantid::VATES; using namespace Mantid::API; @@ -56,75 +58,90 @@ public: void testConstructWithNullViewThrows() { - MockMDLoadingView* pNullView = NULL; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDEWInMemoryLoadingPresenter(pNullView, new MockWorkspaceProvider, "_"), std::invalid_argument); + TSM_ASSERT_THROWS( + "Should throw with null view.", + MDEWInMemoryLoadingPresenter(nullptr, new MockWorkspaceProvider, "_"), + std::invalid_argument); } void testConstructWithNullRepositoryThrows() { - MockWorkspaceProvider* pNullRepository = NULL; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDEWInMemoryLoadingPresenter(new MockMDLoadingView, pNullRepository, "_"), std::invalid_argument); - } + TSM_ASSERT_THROWS( + "Should throw with null repository.", + MDEWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), nullptr, "_"), + std::invalid_argument); + } void testConstructWithEmptyWsNameThrows() { std::string emptyName = ""; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDEWInMemoryLoadingPresenter(new MockMDLoadingView, new MockWorkspaceProvider, emptyName), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw with empty Workspace name.", + MDEWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, emptyName), + std::invalid_argument); } void testConstruction() { - TS_ASSERT_THROWS_NOTHING(MDEWInMemoryLoadingPresenter(new MockMDLoadingView, new MockWorkspaceProvider, "_")); + TS_ASSERT_THROWS_NOTHING(MDEWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_")); } void testCanLoadWithInvalidName() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(false)); //No matter what the argument, always returns false. //Give a dummy name corresponding to the workspace. - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); TSM_ASSERT("Should indicate that the workspace cannot be read-out since the name is not in the Repository.", !presenter.canReadFile()); } void testCanLoadWithWrongWsType() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr badWs = getBadWorkspace(); // Not an IMDEventWorkspace. EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true. EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(badWs)); //Give a dummy name corresponding to the workspace. - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); TSM_ASSERT("Should indicate that the workspace cannot be read-out since it is not of the right type.", !presenter.canReadFile()); } void testCanLoadSucceeds() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr goodWs = getReal4DWorkspace(); EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true. EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs)); //Give a dummy name corresponding to the workspace. - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), "_"); TSM_ASSERT("Should have worked! Workspace is of correct type and repository says ws is present.!", presenter.canReadFile()); } void testExtractMetadata() { - //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr ws = getReal4DWorkspace(); EXPECT_CALL(*repository, fetchWorkspace(_)).Times(1).WillRepeatedly(Return(ws)); - MDEWInMemoryLoadingPresenter presenter(view, repository, "_"); - + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); + //Test that it doesn't work when not setup. TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should throw if not run first.", presenter.getGeometryXML(), std::runtime_error); @@ -138,18 +155,22 @@ public: void testExecution() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(1); - EXPECT_CALL(*view, getLoadInMemory()).Times(0); //Not a question that needs asking for this presenter type. - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + auto mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(1); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(0); // Not a question that needs asking for this presenter type. + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr ws = getReal4DWorkspace(); EXPECT_CALL(*repository, fetchWorkspace(_)).Times(2).WillRepeatedly(Return(ws)); @@ -158,9 +179,11 @@ public: MockProgressAction mockDrawingProgressAction; //Create the presenter and run it! - MDEWInMemoryLoadingPresenter presenter(view, repository, "_"); + MDEWInMemoryLoadingPresenter presenter(std::move(view), + repository.release(), "_"); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + vtkSmartPointer<vtkDataSet> product = presenter.execute( + &factory, mockLoadingProgressAction, mockDrawingProgressAction); TSM_ASSERT("Should have generated a vtkDataSet", NULL != product); TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName())); @@ -170,40 +193,52 @@ public: TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); TSM_ASSERT("Special coordinate metadata failed.", -1 < presenter.getSpecialCoordinates()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testCallHasTDimThrows() { - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable(), std::runtime_error); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.hasTDimensionAvailable(), std::runtime_error); } void testCallGetTDimensionValuesThrows() { - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getGeometryXML(), std::runtime_error); } void testGetWorkspaceTypeName() { - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); } void testGetSpecialCoordinates() { - MDEWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_EQUALS("Characterisation Test Failed", -1, presenter.getSpecialCoordinates()); + MDEWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_EQUALS("Characterisation Test Failed", -1, + presenter.getSpecialCoordinates()); } diff --git a/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h b/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h index 6a54996be770745cd4596b60372c4fbccab382e4..a9445afd5b35f77eaa2b4ac5b1d080aa8d527cd5 100644 --- a/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDEWLoadingPresenterTest.h @@ -3,6 +3,7 @@ #include <cxxtest/TestSuite.h> #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> #include <gmock/gmock.h> #include <gtest/gtest.h> @@ -11,6 +12,7 @@ #include "MantidVatesAPI/MDLoadingView.h" #include "MantidAPI/IMDEventWorkspace.h" #include "MantidAPI/ITableWorkspace.h" +#include "MantidKernel/make_unique.h" #include "MockObjects.h" @@ -41,16 +43,15 @@ private: { return MDEWLoadingPresenter::extractMetadata(eventWs); } - - ConcreteMDEWLoadingPresenter(MockMDLoadingView* view) : MDEWLoadingPresenter(view) - { - } - virtual vtkDataSet* execute(vtkDataSetFactory*, ProgressAction&, ProgressAction&) - { - return vtkUnstructuredGrid::New(); + ConcreteMDEWLoadingPresenter(std::unique_ptr<MDLoadingView> view) + : MDEWLoadingPresenter(std::move(view)) {} + + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *, ProgressAction &, ProgressAction &) { + return vtkSmartPointer<vtkUnstructuredGrid>::New(); } - + virtual void executeLoadMetadata() { } @@ -80,91 +81,107 @@ public: void testShouldLoadFirstTimeRound() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(2); - EXPECT_CALL(view, getLoadInMemory()).Times(2); - EXPECT_CALL(view, getTime()).Times(2); - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDEWLoadingPresenter presenter(&view); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(2); + EXPECT_CALL(*mockView, getLoadInMemory()).Times(2); + EXPECT_CALL(*mockView, getTime()).Times(2); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0); + + ConcreteMDEWLoadingPresenter presenter(std::move(view)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); TSM_ASSERT("Should NOT request load on second usage. Should have it's state syncrhonised with view and the view hasn't changed!", !presenter.shouldLoad()); - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(mockView)); } void testTimeChanged() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(2); - EXPECT_CALL(view, getLoadInMemory()).Times(2); - EXPECT_CALL(view, getTime()).Times(2) - .WillOnce(Return(0)) - .WillOnce(Return(1));// Time has changed on 2nd call - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDEWLoadingPresenter presenter(&view); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(2); + EXPECT_CALL(*mockView, getLoadInMemory()).Times(2); + EXPECT_CALL(*mockView, getTime()) + .Times(2) + .WillOnce(Return(0)) + .WillOnce(Return(1)); // Time has changed on 2nd call + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0); + + ConcreteMDEWLoadingPresenter presenter(std::move(view)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); - TSM_ASSERT("Time has changed, but that shouldn't trigger load", !presenter.shouldLoad()); - - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("Time has changed, but that shouldn't trigger load", + !presenter.shouldLoad()); + + TSM_ASSERT("View not used as expected.", + Mock::VerifyAndClearExpectations(mockView)); } void testLoadInMemoryChanged() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(2); - EXPECT_CALL(view, getLoadInMemory()).Times(2) - .WillOnce(Return(true)) - .WillOnce(Return(false)); // Load in memory changed - EXPECT_CALL(view, getTime()).Times(2); - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDEWLoadingPresenter presenter(&view); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(2); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(2) + .WillOnce(Return(true)) + .WillOnce(Return(false)); // Load in memory changed + EXPECT_CALL(*mockView, getTime()).Times(2); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0); + + ConcreteMDEWLoadingPresenter presenter(std::move(view)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); - TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load", presenter.shouldLoad()); - - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load", + presenter.shouldLoad()); + + TSM_ASSERT("View not used as expected.", + Mock::VerifyAndClearExpectations(mockView)); } void testDepthChanged() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(2) - .WillOnce(Return(10)) - .WillOnce(Return(100)); // Recursion depth changed. - EXPECT_CALL(view, getLoadInMemory()).Times(2); - EXPECT_CALL(view, getTime()).Times(2); - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDEWLoadingPresenter presenter(&view); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()) + .Times(2) + .WillOnce(Return(10)) + .WillOnce(Return(100)); // Recursion depth changed. + EXPECT_CALL(*mockView, getLoadInMemory()).Times(2); + EXPECT_CALL(*mockView, getTime()).Times(2); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(0); + + ConcreteMDEWLoadingPresenter presenter(std::move(view)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); - TSM_ASSERT("Depth has changed, but that shouldn't trigger load", !presenter.shouldLoad()); - - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("Depth has changed, but that shouldn't trigger load", + !presenter.shouldLoad()); + + TSM_ASSERT("View not used as expected.", + Mock::VerifyAndClearExpectations(mockView)); } - void testhasTDimensionWhenIntegrated() - { - //Setup view - MockMDLoadingView* view = new MockMDLoadingView; +void testhasTDimensionWhenIntegrated() { + // Setup view + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); - ConcreteMDEWLoadingPresenter presenter(view); - - //Test that it does work when setup. - Mantid::API::Workspace_sptr ws = get3DWorkspace(true, true); //Integrated T Dimension - presenter.extractMetadata(boost::dynamic_pointer_cast<IMDEventWorkspace>(ws)); + // Test that it does work when setup. + Mantid::API::Workspace_sptr ws = + get3DWorkspace(true, true); // Integrated T Dimension + presenter.extractMetadata(boost::dynamic_pointer_cast<IMDEventWorkspace>(ws)); - TSM_ASSERT("This is a 4D workspace with an integrated T dimension", !presenter.hasTDimensionAvailable()); + TSM_ASSERT("This is a 4D workspace with an integrated T dimension", + !presenter.hasTDimensionAvailable()); } void testHasTDimensionWhenNotIntegrated() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); - ConcreteMDEWLoadingPresenter presenter(view); - //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true); //Non-integrated T Dimension presenter.extractMetadata(boost::dynamic_pointer_cast<IMDEventWorkspace>(ws)); @@ -175,9 +192,8 @@ void testDepthChanged() void testHasTimeLabelWithTDimension() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - - ConcreteMDEWLoadingPresenter presenter(view); + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true); //Non-integrated T Dimension @@ -189,14 +205,13 @@ void testDepthChanged() void testCanSetAxisLabelsFrom3DData() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - - ConcreteMDEWLoadingPresenter presenter(view); + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(true, true); presenter.extractMetadata(boost::dynamic_pointer_cast<IMDEventWorkspace>(ws)); - vtkDataSet *ds = vtkUnstructuredGrid::New(); + auto ds = vtkSmartPointer<vtkDataSet>::Take(vtkUnstructuredGrid::New()); TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds)); TSM_ASSERT_EQUALS("X Label should match exactly", getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)"); @@ -209,14 +224,13 @@ void testDepthChanged() void testCanSetAxisLabelsFrom4DData() { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - - ConcreteMDEWLoadingPresenter presenter(view); + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, true); presenter.extractMetadata(boost::dynamic_pointer_cast<IMDEventWorkspace>(ws)); - vtkDataSet *ds = vtkUnstructuredGrid::New(); + auto ds = vtkSmartPointer<vtkDataSet>::Take(vtkUnstructuredGrid::New()); TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(ds)); TSM_ASSERT_EQUALS("X Label should match exactly", getStringFieldDataValue(ds, "AxisTitleForX"), "A ($A$)"); @@ -228,9 +242,8 @@ void testDepthChanged() void testCanLoadFileBasedOnExtension() { - MockMDLoadingView* view = new MockMDLoadingView; - - ConcreteMDEWLoadingPresenter presenter(view); + ConcreteMDEWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>()); // constructive tests TSM_ASSERT("Should be an exact match", presenter.canLoadFileBasedOnExtension("somefile.nxs", ".nxs")); @@ -238,8 +251,6 @@ void testDepthChanged() TSM_ASSERT("Should strip off whitespace", presenter.canLoadFileBasedOnExtension("somefile.nxs ", ".nxs")); // destructive tests TSM_ASSERT("Extensions do not match, should return false.", !presenter.canLoadFileBasedOnExtension("somefile.nx", ".nxs")); - - delete view; } diff --git a/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h index 461b007f8f7cea3fd0dc2864d2fd8050eb1b474a..c118957cc8507fef784ab50fd46f9029ffff36ef 100644 --- a/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDHWInMemoryLoadingPresenterTest.h @@ -10,7 +10,9 @@ #include "MantidTestHelpers/MDEventsTestHelper.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" #include "MantidVatesAPI/MDHWInMemoryLoadingPresenter.h" +#include "MantidKernel/make_unique.h" #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> using namespace Mantid::VATES; using namespace Mantid::API; @@ -49,75 +51,96 @@ public: void testConstructWithNullViewThrows() { - MockMDLoadingView* pNullView = NULL; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDHWInMemoryLoadingPresenter(pNullView, new MockWorkspaceProvider, "_"), std::invalid_argument); + TSM_ASSERT_THROWS( + "Should throw with null view.", + MDHWInMemoryLoadingPresenter(nullptr, new MockWorkspaceProvider, "_"), + std::invalid_argument); } void testConstructWithNullRepositoryThrows() { - MockWorkspaceProvider* pNullRepository = NULL; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDHWInMemoryLoadingPresenter(new MockMDLoadingView, pNullRepository, "_"), std::invalid_argument); - } + TSM_ASSERT_THROWS( + "Should throw with null repository.", + MDHWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), nullptr, "_"), + std::invalid_argument); + } void testConstructWithEmptyWsNameThrows() { std::string emptyName = ""; - TSM_ASSERT_THROWS("Should throw with empty Workspace name.", MDHWInMemoryLoadingPresenter(new MockMDLoadingView, new MockWorkspaceProvider, emptyName), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw with empty Workspace name.", + MDHWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, emptyName), + std::invalid_argument); } void testConstruction() { - TS_ASSERT_THROWS_NOTHING(MDHWInMemoryLoadingPresenter(new MockMDLoadingView, new MockWorkspaceProvider, "_")); + TS_ASSERT_THROWS_NOTHING(MDHWInMemoryLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_")); } void testCanLoadWithInvalidName() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; - EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(false)); //No matter what the argument, always returns false. + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); + EXPECT_CALL(*repository, canProvideWorkspace(_)) + .WillOnce(Return( + false)); // No matter what the argument, always returns false. - //Give a dummy name corresponding to the workspace. - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + // Give a dummy name corresponding to the workspace. + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); TSM_ASSERT("Should indicate that the workspace cannot be read-out since the name is not in the Repository.", !presenter.canReadFile()); } void testCanLoadWithWrongWsType() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; - Mantid::API::Workspace_sptr badWs = getBadWorkspace(); // Not an IMDHistoWorkspace. - EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true. - EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(badWs)); + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); + Mantid::API::Workspace_sptr badWs = + getBadWorkspace(); // Not an IMDHistoWorkspace. + EXPECT_CALL(*repository, canProvideWorkspace(_)) + .WillOnce( + Return(true)); // No matter what the argument, always returns true. + EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(badWs)); - //Give a dummy name corresponding to the workspace. - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + // Give a dummy name corresponding to the workspace. + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); TSM_ASSERT("Should indicate that the workspace cannot be read-out since it is not of the right type.", !presenter.canReadFile()); } void testCanLoadSucceeds() { - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr goodWs = getGoodWorkspace(); EXPECT_CALL(*repository, canProvideWorkspace(_)).WillOnce(Return(true)); //No matter what the argument, always returns true. - EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs)); + EXPECT_CALL(*repository, fetchWorkspace(_)).WillOnce(Return(goodWs)); - //Give a dummy name corresponding to the workspace. - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, repository, "_"); + // Give a dummy name corresponding to the workspace. + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); TSM_ASSERT("Should have worked! Workspace is of correct type and repository says ws is present.!", presenter.canReadFile()); } void testExtractMetadata() { - //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr ws = getGoodWorkspace(); EXPECT_CALL(*repository, fetchWorkspace(_)).Times(1).WillRepeatedly(Return(ws)); - MDHWInMemoryLoadingPresenter presenter(view, repository, "_"); - + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), repository.release(), + "_"); + //Test that it doesn't work when not setup. TSM_ASSERT_THROWS("::executeLoadMetadata is critical to setup, should throw if not run first.", presenter.getGeometryXML(), std::runtime_error); @@ -135,17 +158,21 @@ public: { //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(0); - EXPECT_CALL(*view, getLoadInMemory()).Times(0); //Not a question that needs asking for this presenter type. - EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(0); + EXPECT_CALL(*mockView, getLoadInMemory()) + .Times(0); // Not a question that needs asking for this presenter type. + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); - MockWorkspaceProvider* repository = new MockWorkspaceProvider; + auto repository = Mantid::Kernel::make_unique<MockWorkspaceProvider>(); Mantid::API::Workspace_sptr ws = getGoodWorkspace(); EXPECT_CALL(*repository, fetchWorkspace(_)).Times(2).WillRepeatedly(Return(ws)); @@ -154,9 +181,11 @@ public: MockProgressAction mockDrawingProgressAction; //Create the presenter and run it! - MDHWInMemoryLoadingPresenter presenter(view, repository, "_"); + MDHWInMemoryLoadingPresenter presenter(std::move(view), + repository.release(), "_"); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); TSM_ASSERT("Should have generated a vtkDataSet", NULL != product); TSM_ASSERT_EQUALS("Wrong type of output generated", "vtkUnstructuredGrid", std::string(product->GetClassName())); @@ -166,40 +195,53 @@ public: TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); TSM_ASSERT("Special coordinate metadata failed.", -1 < presenter.getSpecialCoordinates()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testCallHasTDimThrows() { - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable(), std::runtime_error); + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.hasTDimensionAvailable(), std::runtime_error); } void testCallGetTDimensionValuesThrows() { - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getGeometryXML(), std::runtime_error); } void testGetWorkspaceTypeName() { - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_EQUALS("Characterisation Test Failed", "", + presenter.getWorkspaceTypeName()); } void testGetSpecialCoordinates() { - MDHWInMemoryLoadingPresenter presenter(new MockMDLoadingView, new MockWorkspaceProvider, "_"); - TSM_ASSERT_EQUALS("Characterisation Test Failed", -1, presenter.getSpecialCoordinates()); + MDHWInMemoryLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + new MockWorkspaceProvider, "_"); + TSM_ASSERT_EQUALS("Characterisation Test Failed", -1, + presenter.getSpecialCoordinates()); } }; diff --git a/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h index ae3bad717a5192129305de70f560a33573465bd6..4549527520376bca063d1d507e46361cec36e5fc 100644 --- a/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDHWLoadingPresenterTest.h @@ -10,6 +10,7 @@ #include "MantidVatesAPI/MDHWLoadingPresenter.h" #include "MantidVatesAPI/MDLoadingView.h" #include "MantidDataObjects/MDHistoWorkspace.h" +#include "MantidKernel/make_unique.h" #include "MockObjects.h" @@ -34,20 +35,19 @@ private: private: typedef MDHWLoadingPresenter BaseClass; public: - ConcreteMDHWLoadingPresenter(MockMDLoadingView* view) : MDHWLoadingPresenter(view) - { - } + ConcreteMDHWLoadingPresenter(std::unique_ptr<MDLoadingView> view) + : MDHWLoadingPresenter(std::move(view)) {} virtual void extractMetadata(Mantid::API::IMDHistoWorkspace_sptr histoWs) { MDHWLoadingPresenter::extractMetadata(histoWs); } - virtual vtkDataSet* execute(vtkDataSetFactory*, ProgressAction&, ProgressAction&) - { - return vtkUnstructuredGrid::New(); + virtual vtkSmartPointer<vtkDataSet> + execute(vtkDataSetFactory *, ProgressAction &, ProgressAction &) { + return vtkSmartPointer<vtkUnstructuredGrid>::New(); } - + virtual void executeLoadMetadata() { } @@ -71,104 +71,105 @@ public: void testShouldLoadFirstTimeRound() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(0); - EXPECT_CALL(view, getLoadInMemory()).Times(2); - EXPECT_CALL(view, getTime()).Times(2).WillRepeatedly(Return(0)); - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDHWLoadingPresenter presenter(&view); + auto view = new MockMDLoadingView(); + EXPECT_CALL(*view, getRecursionDepth()).Times(0); + EXPECT_CALL(*view, getLoadInMemory()).Times(2); + EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0)); + EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0); + + std::unique_ptr<MDLoadingView> uniqueView( + dynamic_cast<MDLoadingView *>(view)); + ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); TSM_ASSERT("Should NOT request load on second usage. Should have it's state syncrhonised with view and the view hasn't changed!", !presenter.shouldLoad()); - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(view)); } void testTimeChanged() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(0); - EXPECT_CALL(view, getLoadInMemory()).Times(2); - EXPECT_CALL(view, getTime()).Times(2) - .WillOnce(Return(0)) - .WillOnce(Return(1));// Time has changed on 2nd call - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDHWLoadingPresenter presenter(&view); + auto view = new MockMDLoadingView(); + EXPECT_CALL(*view, getRecursionDepth()).Times(0); + EXPECT_CALL(*view, getLoadInMemory()).Times(2); + EXPECT_CALL(*view, getTime()) + .Times(2) + .WillOnce(Return(0)) + .WillOnce(Return(1)); // Time has changed on 2nd call + EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0); + + std::unique_ptr<MDLoadingView> uniqueView( + dynamic_cast<MDLoadingView *>(view)); + ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); - TSM_ASSERT("Time has changed, but that shouldn't trigger load", !presenter.shouldLoad()); - - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("Time has changed, but that shouldn't trigger load", + !presenter.shouldLoad()); + + TSM_ASSERT("View not used as expected.", + Mock::VerifyAndClearExpectations(view)); } void testLoadInMemoryChanged() { - MockMDLoadingView view; - EXPECT_CALL(view, getRecursionDepth()).Times(0); - EXPECT_CALL(view, getLoadInMemory()).Times(2) - .WillOnce(Return(true)) - .WillOnce(Return(false)); // Load in memory changed - EXPECT_CALL(view, getTime()).Times(2).WillRepeatedly(Return(0)); - EXPECT_CALL(view, updateAlgorithmProgress(_,_)).Times(0); - - ConcreteMDHWLoadingPresenter presenter(&view); + auto view = new MockMDLoadingView(); + EXPECT_CALL(*view, getRecursionDepth()).Times(0); + EXPECT_CALL(*view, getLoadInMemory()) + .Times(2) + .WillOnce(Return(true)) + .WillOnce(Return(false)); // Load in memory changed + EXPECT_CALL(*view, getTime()).Times(2).WillRepeatedly(Return(0)); + EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(0); + + std::unique_ptr<MDLoadingView> uniqueView( + dynamic_cast<MDLoadingView *>(view)); + ConcreteMDHWLoadingPresenter presenter(std::move(uniqueView)); TSM_ASSERT("Should request load on first usage.", presenter.shouldLoad()); - TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load", presenter.shouldLoad()); - - TSM_ASSERT("View not used as expected.", Mock::VerifyAndClearExpectations(&view)); + TSM_ASSERT("Load in memory changed. this SHOULD trigger re-load", + presenter.shouldLoad()); + + TSM_ASSERT("View not used as expected.", + Mock::VerifyAndClearExpectations(view)); } void testhasTDimensionWhenIntegrated() { - //Setup view - auto * view = new NiceMock<MockMDLoadingView>(); - - ConcreteMDHWLoadingPresenter presenter(view); + ConcreteMDHWLoadingPresenter presenter( + Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(true, false); //Integrated T Dimension presenter.extractMetadata(boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws)); TSM_ASSERT("This is a 4D workspace with an integrated T dimension", !presenter.hasTDimensionAvailable()); - delete view; } void testHasTDimensionWhenNotIntegrated() { - //Setup view - auto * view = new NiceMock<MockMDLoadingView>(); - - ConcreteMDHWLoadingPresenter presenter(view); + ConcreteMDHWLoadingPresenter presenter( + Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false); //Non-integrated T Dimension presenter.extractMetadata(boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws)); TSM_ASSERT("This is a 4D workspace with an integrated T dimension", presenter.hasTDimensionAvailable()); - delete view; } void testHasTimeLabelWithTDimension() { - //Setup view - auto * view = new NiceMock<MockMDLoadingView>(); - - ConcreteMDHWLoadingPresenter presenter(view); + ConcreteMDHWLoadingPresenter presenter( + Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false); //Non-integrated T Dimension presenter.extractMetadata(boost::dynamic_pointer_cast<Mantid::API::IMDHistoWorkspace>(ws)); TSM_ASSERT_EQUALS("This is a 4D workspace with a T dimension", "D (A)", presenter.getTimeStepLabel()); - delete view; } void testCanSetAxisLabelsFrom3DData() { - //Setup view - auto * view = new NiceMock<MockMDLoadingView>(); - - ConcreteMDHWLoadingPresenter presenter(view); + ConcreteMDHWLoadingPresenter presenter( + Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(true, false); @@ -181,15 +182,12 @@ void testCanSetAxisLabelsFrom3DData() getStringFieldDataValue(ds, "AxisTitleForY"), "B ($A$)"); TSM_ASSERT_EQUALS("Z Label should match exactly", getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)"); - delete view; } void testCanSetAxisLabelsFrom4DData() { - //Setup view - auto * view = new NiceMock<MockMDLoadingView>(); - - ConcreteMDHWLoadingPresenter presenter(view); + ConcreteMDHWLoadingPresenter presenter( + Mantid::Kernel::make_unique<NiceMock<MockMDLoadingView>>()); //Test that it does work when setup. Mantid::API::Workspace_sptr ws = get3DWorkspace(false, false); @@ -203,7 +201,6 @@ void testCanSetAxisLabelsFrom4DData() TSM_ASSERT_EQUALS("Z Label should match exactly", getStringFieldDataValue(ds, "AxisTitleForZ"), "C ($A$)"); - delete view; } Mantid::API::IMDHistoWorkspace_sptr makeHistoWorkspace(const std::vector<int> &shape){ diff --git a/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h b/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h index 04109bca40c6d3ebc9a197c9194cc99d76783f12..751846ffaa9c8bf785d8f744a5ecc19fbfb607de 100644 --- a/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDHWNexusLoadingPresenterTest.h @@ -22,6 +22,7 @@ #include "MantidAPI/FileFinder.h" #include "MantidVatesAPI/MDHWNexusLoadingPresenter.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" +#include "MantidKernel/make_unique.h" #include <limits> @@ -49,30 +50,33 @@ private: return temp; } - vtkDataSet *doExecute(std::string filename, bool performAsserts = true) { + vtkSmartPointer<vtkDataSet> doExecute(std::string filename, + bool performAsserts = true) { // Setup view - MockMDLoadingView *view = new MockMDLoadingView; - EXPECT_CALL(*view, getTime()).WillRepeatedly(Return(0)); - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(0)); - EXPECT_CALL(*view, getLoadInMemory()) + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getTime()).WillRepeatedly(Return(0)); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(0)); + EXPECT_CALL(*mockView, getLoadInMemory()) .Times(AtLeast(1)) .WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber()); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); // Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); EXPECT_CALL(factory, create(_)) - .WillOnce(testing::Return(vtkUnstructuredGrid::New())); + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); // Setup progress updates objects MockProgressAction mockLoadingProgressAction; MockProgressAction mockDrawingProgressAction; // Create the presenter and runit! - MDHWNexusLoadingPresenter presenter(view, filename); + MDHWNexusLoadingPresenter presenter(std::move(view), filename); presenter.executeLoadMetadata(); - vtkDataSet *product = presenter.execute(&factory, mockLoadingProgressAction, + auto product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); TSM_ASSERT("Should have generated a vtkDataSet", NULL != product); @@ -87,7 +91,7 @@ private: TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); } return product; @@ -96,27 +100,28 @@ private: public: void testConstructWithEmptyFileThrows() { TSM_ASSERT_THROWS("Should throw if an empty file string is given.", - MDHWNexusLoadingPresenter(new MockMDLoadingView, ""), + MDHWNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), ""), std::invalid_argument); } void testConstructWithNullViewThrows() { - MockMDLoadingView *pView = NULL; - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", - MDHWNexusLoadingPresenter(pView, "some_file"), + MDHWNexusLoadingPresenter(nullptr, "some_file"), std::invalid_argument); } void testConstruct() { TSM_ASSERT_THROWS_NOTHING( "Object should be created without exception.", - MDHWNexusLoadingPresenter(new MockMDLoadingView, getSuitableFile())); + MDHWNexusLoadingPresenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFile())); } void testCanReadFile() { - MDHWNexusLoadingPresenter presenter(new MockMDLoadingView, - getUnhandledFile()); + MDHWNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getUnhandledFile()); TSM_ASSERT( "A file of this type cannot and should not be read by this presenter!.", !presenter.canReadFile()); @@ -124,8 +129,8 @@ public: void testExecution() { auto filename = getSuitableFile(); - auto product = doExecute(filename); - product->Delete(); + vtkSmartPointer<vtkDataSet> product; + product = doExecute(filename); } void testExecutionWithLegacyFile() { @@ -141,7 +146,7 @@ public: NiceMock<MockProgressAction> mockDrawingProgressAction; // Setup view - MockMDLoadingView *view = new MockMDLoadingView; + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); EXPECT_CALL(*view, getTime()).WillRepeatedly(Return(0)); EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(0)); EXPECT_CALL(*view, getLoadInMemory()) @@ -149,31 +154,31 @@ public: .WillRepeatedly(testing::Return(true)); EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber()); - ThresholdRange_scptr thresholdRange(new IgnoreZerosThresholdRange()); + ThresholdRange_scptr thresholdRange = + boost::make_shared<IgnoreZerosThresholdRange>(); // Create the presenter as in the vtkMDHWSource auto normalizationOption = Mantid::VATES::VisualNormalization::AutoSelect; - MDHWNexusLoadingPresenter presenter(view, filename); + MDHWNexusLoadingPresenter presenter(std::move(view), filename); const double time = 0.0; - vtkMD0DFactory *zeroDFactory = new vtkMD0DFactory; - vtkMDHistoLineFactory *lineFactory = - new vtkMDHistoLineFactory(thresholdRange, normalizationOption); - vtkMDHistoQuadFactory *quadFactory = - new vtkMDHistoQuadFactory(thresholdRange, normalizationOption); - vtkMDHistoHexFactory *hexFactory = - new vtkMDHistoHexFactory(thresholdRange, normalizationOption); - vtkMDHistoHex4DFactory<TimeToTimeStep> *factory = - new vtkMDHistoHex4DFactory<TimeToTimeStep>(thresholdRange, - normalizationOption, time); - - factory->SetSuccessor(hexFactory); - hexFactory->SetSuccessor(quadFactory); - quadFactory->SetSuccessor(lineFactory); - lineFactory->SetSuccessor(zeroDFactory); + auto zeroDFactory = Mantid::Kernel::make_unique<vtkMD0DFactory>(); + auto lineFactory = Mantid::Kernel::make_unique<vtkMDHistoLineFactory>( + thresholdRange, normalizationOption); + auto quadFactory = Mantid::Kernel::make_unique<vtkMDHistoQuadFactory>( + thresholdRange, normalizationOption); + auto hexFactory = Mantid::Kernel::make_unique<vtkMDHistoHexFactory>( + thresholdRange, normalizationOption); + auto factory = boost::make_shared<vtkMDHistoHex4DFactory<TimeToTimeStep>>( + thresholdRange, normalizationOption, time); + + lineFactory->SetSuccessor(std::move(zeroDFactory)); + quadFactory->SetSuccessor(std::move(lineFactory)); + hexFactory->SetSuccessor(std::move(quadFactory)); + factory->SetSuccessor(std::move(hexFactory)); presenter.executeLoadMetadata(); - vtkDataSet *product = presenter.execute(factory, mockLoadingProgressAction, - mockDrawingProgressAction); + auto product = presenter.execute(factory.get(), mockLoadingProgressAction, + mockDrawingProgressAction); // Set the COB try { @@ -227,99 +232,97 @@ public: std::numeric_limits<double>::epsilon()); TS_ASSERT_DELTA(cobMatrix->GetElement(3, 3), expectedElements[15], std::numeric_limits<double>::epsilon()); - product->Delete(); - // Deleting factory should delete the whole chain since it is connected - // via smart pointers - delete factory; } void testCallHasTDimThrows() { - MDHWNexusLoadingPresenter presenter(new MockMDLoadingView, - getSuitableFile()); + MDHWNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable(), std::runtime_error); } void testCallGetTDimensionValuesThrows() { - MDHWNexusLoadingPresenter presenter(new MockMDLoadingView, - getSuitableFile()); + MDHWNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - MDHWNexusLoadingPresenter presenter(new MockMDLoadingView, - getSuitableFile()); + MDHWNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); } void testGetWorkspaceTypeName() { - MDHWNexusLoadingPresenter presenter(new MockMDLoadingView, - getSuitableFile()); + MDHWNexusLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), getSuitableFile()); TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); } void testTimeLabel() { // Setup view - MockMDLoadingView *view = new MockMDLoadingView; - EXPECT_CALL(*view, getTime()).WillRepeatedly(Return(0)); - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(0)); - EXPECT_CALL(*view, getLoadInMemory()) + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getTime()).WillRepeatedly(Return(0)); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(0)); + EXPECT_CALL(*mockView, getLoadInMemory()) .Times(AtLeast(1)) .WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber()); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); // Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); EXPECT_CALL(factory, create(_)) - .WillOnce(testing::Return(vtkUnstructuredGrid::New())); + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); // Setup progress updates objects MockProgressAction mockLoadingProgressAction; MockProgressAction mockDrawingProgressAction; // Create the presenter and runit! - MDHWNexusLoadingPresenter presenter(view, getSuitableFile()); + MDHWNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet *product = presenter.execute(&factory, mockLoadingProgressAction, - mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); TSM_ASSERT_EQUALS("Time label should be exact.", presenter.getTimeStepLabel(), "DeltaE (DeltaE)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } void testAxisLabels() { // Setup view - MockMDLoadingView *view = new MockMDLoadingView; - EXPECT_CALL(*view, getTime()).WillRepeatedly(Return(0)); - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(0)); - EXPECT_CALL(*view, getLoadInMemory()) + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + MockMDLoadingView *mockView = dynamic_cast<MockMDLoadingView *>(view.get()); + EXPECT_CALL(*mockView, getTime()).WillRepeatedly(Return(0)); + EXPECT_CALL(*mockView, getRecursionDepth()).Times(AtLeast(0)); + EXPECT_CALL(*mockView, getLoadInMemory()) .Times(AtLeast(1)) .WillRepeatedly(testing::Return(true)); - EXPECT_CALL(*view, updateAlgorithmProgress(_, _)).Times(AnyNumber()); + EXPECT_CALL(*mockView, updateAlgorithmProgress(_, _)).Times(AnyNumber()); // Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); EXPECT_CALL(factory, create(_)) - .WillOnce(testing::Return(vtkUnstructuredGrid::New())); + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); // Setup progress updates objects MockProgressAction mockLoadingProgressAction; MockProgressAction mockDrawingProgressAction; // Create the presenter and runit! - MDHWNexusLoadingPresenter presenter(view, getSuitableFile()); + MDHWNexusLoadingPresenter presenter(std::move(view), getSuitableFile()); presenter.executeLoadMetadata(); - vtkDataSet *product = presenter.execute(&factory, mockLoadingProgressAction, - mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product)); TSM_ASSERT_EQUALS("X Label should match exactly", @@ -332,10 +335,8 @@ public: getStringFieldDataValue(product, "AxisTitleForZ"), "[0,0,L] ($in$ $1.087$ $\\AA^{-1}$)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(mockView)); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); - - product->Delete(); } }; #endif diff --git a/Vates/VatesAPI/test/MDLoadingPresenterTest.h b/Vates/VatesAPI/test/MDLoadingPresenterTest.h index d571b3769a79887625939938c846469b1899644d..48391a5a4880837f26646681256b7eea2d990c8b 100644 --- a/Vates/VatesAPI/test/MDLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/MDLoadingPresenterTest.h @@ -28,7 +28,11 @@ class MOCKMDLoadingPresenter : public Mantid::VATES::MDLoadingPresenter { public: MOCKMDLoadingPresenter(){} ~MOCKMDLoadingPresenter(){} - vtkDataSet* execute(Mantid::VATES::vtkDataSetFactory*, Mantid::VATES::ProgressAction&, Mantid::VATES::ProgressAction&) { return NULL;} + vtkSmartPointer<vtkDataSet> execute(Mantid::VATES::vtkDataSetFactory *, + Mantid::VATES::ProgressAction &, + Mantid::VATES::ProgressAction &) { + return nullptr; + } void executeLoadMetadata() {} bool hasTDimensionAvailable(void) const {return true;} std::vector<double> getTimeStepValues() const {return std::vector<double>();} @@ -43,20 +47,23 @@ public: class MDLoadingPresenterTest : public CxxTest::TestSuite { private: - vtkUnstructuredGrid *makeDataSet() { + vtkSmartPointer<vtkUnstructuredGrid> makeDataSet() { FakeProgressAction progressUpdate; MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(8, -10.0, 10.0, 1); Mantid::VATES::vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VolumeNormalization); factory.initialize(ws); - return vtkUnstructuredGrid::SafeDownCast(factory.create(progressUpdate)); + auto dataset = factory.create(progressUpdate); + auto grid = vtkUnstructuredGrid::SafeDownCast(dataset.Get()); + return vtkSmartPointer<vtkUnstructuredGrid>(grid); } public: void test_that_non_default_cob_is_created() { // Arrange MOCKMDLoadingPresenter presenter; - auto dataSet = makeDataSet(); + vtkSmartPointer<vtkUnstructuredGrid> dataSet; + dataSet = makeDataSet(); // Act presenter.setDefaultCOBandBoundaries(dataSet); // Assert @@ -91,8 +98,6 @@ public: TS_ASSERT_EQUALS(10.0, bounds[3]); TS_ASSERT_EQUALS(-10.0, bounds[4]); TS_ASSERT_EQUALS(10.0, bounds[5]); - - dataSet->Delete(); } }; diff --git a/Vates/VatesAPI/test/MetadataToFieldDataTest.h b/Vates/VatesAPI/test/MetadataToFieldDataTest.h index 93e9c05ffbe5e06a0dbd263f53980b5e9190c464..9b7cbaf05cc8588527a09c08a30e66ae2b510494 100644 --- a/Vates/VatesAPI/test/MetadataToFieldDataTest.h +++ b/Vates/VatesAPI/test/MetadataToFieldDataTest.h @@ -6,6 +6,7 @@ #include <vtkFieldData.h> #include "MantidVatesAPI/MetadataToFieldData.h" #include <boost/algorithm/string.hpp> +#include <vtkNew.h> using Mantid::VATES::MetadataToFieldData; @@ -36,20 +37,18 @@ public: std::string testData = "<test data/>%s"; const std::string id = "1"; - vtkFieldData* fieldData = vtkFieldData::New(); - vtkCharArray* charArray = vtkCharArray::New(); + vtkNew<vtkFieldData> fieldData; + vtkNew<vtkCharArray> charArray; charArray->SetName(id.c_str()); - fieldData->AddArray(charArray); + fieldData->AddArray(charArray.GetPointer()); MetadataToFieldData function; - function(fieldData, testData, id); + function(fieldData.GetPointer(), testData, id); //convert vtkchararray back into a string. vtkCharArray* carry = dynamic_cast<vtkCharArray*> (fieldData->GetArray(id.c_str())); TSM_ASSERT_EQUALS("The result does not match the input. Metadata not properly converted.", testData, convertCharArrayToString(carry)); - charArray->Delete(); - fieldData->Delete(); } void testMetaDataToFieldDataWithEmptyFieldData() @@ -57,15 +56,14 @@ public: std::string testData = "<test data/>%s"; const std::string id = "1"; - vtkFieldData* emptyFieldData = vtkFieldData::New(); + vtkNew<vtkFieldData> emptyFieldData; MetadataToFieldData function; - function(emptyFieldData, testData.c_str(), id.c_str()); + function(emptyFieldData.GetPointer(), testData.c_str(), id.c_str()); //convert vtkchararray back into a string. vtkCharArray* carry = dynamic_cast<vtkCharArray*> (emptyFieldData->GetArray(id.c_str())); TSM_ASSERT_EQUALS("The result does not match the input. Metadata not properly converted.", testData, convertCharArrayToString(carry)); - emptyFieldData->Delete(); } }; diff --git a/Vates/VatesAPI/test/MockObjects.h b/Vates/VatesAPI/test/MockObjects.h index a067bc94f348b35dc30a8dde0b7ed949f4706d11..20556dd6c2e79469eb5e35d8a978bae9b3ff8635 100644 --- a/Vates/VatesAPI/test/MockObjects.h +++ b/Vates/VatesAPI/test/MockObjects.h @@ -132,13 +132,23 @@ private: /// Mock to allow the behaviour of the chain of responsibility to be tested. class MockvtkDataSetFactory : public Mantid::VATES::vtkDataSetFactory { public: - MOCK_CONST_METHOD1(create, vtkDataSet *(Mantid::VATES::ProgressAction &)); - MOCK_CONST_METHOD0(createMeshOnly, vtkDataSet *()); - MOCK_CONST_METHOD0(createScalarArray, vtkFloatArray *()); - MOCK_METHOD1(initialize, void(Mantid::API::Workspace_sptr)); - MOCK_METHOD1(SetSuccessor, void(vtkDataSetFactory *pSuccessor)); + /// This is necessary as Google Mock can't mock functions that take + /// non-copyable params. + virtual void SetSuccessor(std::unique_ptr<vtkDataSetFactory> successor) { + setSuccessorProxy(successor.get()); + } + MOCK_CONST_METHOD1( + create, vtkSmartPointer<vtkDataSet>(Mantid::VATES::ProgressAction &)); + MOCK_CONST_METHOD0(createMeshOnly, + vtkDataSet*()); + MOCK_CONST_METHOD0(createScalarArray, + vtkFloatArray*()); + MOCK_METHOD1(initialize, + void(Mantid::API::Workspace_sptr)); + MOCK_METHOD1(setSuccessorProxy, void(vtkDataSetFactory *)); MOCK_CONST_METHOD0(hasSuccessor, bool()); - MOCK_CONST_METHOD0(validate, void()); + MOCK_CONST_METHOD0(validate, + void()); MOCK_CONST_METHOD0(getFactoryTypeName, std::string()); MOCK_METHOD1(setRecursionDepth, void(size_t)); }; diff --git a/Vates/VatesAPI/test/SQWLoadingPresenterTest.h b/Vates/VatesAPI/test/SQWLoadingPresenterTest.h index 682c63ed286759b4453d4fc0469eb04143db2b9d..57b5dbaa423095c3a5ae3d12b5467e70fd83c9a0 100644 --- a/Vates/VatesAPI/test/SQWLoadingPresenterTest.h +++ b/Vates/VatesAPI/test/SQWLoadingPresenterTest.h @@ -3,6 +3,7 @@ #include <cxxtest/TestSuite.h> #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> #include <gmock/gmock.h> #include <gtest/gtest.h> @@ -12,6 +13,7 @@ #include "MantidAPI/FileFinder.h" #include "MantidVatesAPI/SQWLoadingPresenter.h" #include "MantidVatesAPI/FilteringUpdateProgressAction.h" +#include "MantidKernel/make_unique.h" using namespace Mantid::VATES; @@ -51,54 +53,70 @@ void setUp() void testConstructWithEmptyFileThrows() { - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", SQWLoadingPresenter(new MockMDLoadingView, ""), std::invalid_argument); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + TSM_ASSERT_THROWS("Should throw if an empty file string is given.", + SQWLoadingPresenter(std::move(view), ""), + std::invalid_argument); } void testConstructWithNullViewThrows() { - MockMDLoadingView* pView = NULL; - TSM_ASSERT_THROWS("Should throw if an empty file string is given.", SQWLoadingPresenter(pView, "some_file"), std::invalid_argument); + TSM_ASSERT_THROWS("Should throw if an empty file string is given.", + SQWLoadingPresenter(nullptr, "some_file"), + std::invalid_argument); } void testConstruct() { - TSM_ASSERT_THROWS_NOTHING("Object should be created without exception.", SQWLoadingPresenter(new MockMDLoadingView, getSuitableFileNamePath())); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + TSM_ASSERT_THROWS_NOTHING( + "Object should be created without exception.", + SQWLoadingPresenter(std::move(view), getSuitableFileNamePath())); } void testCanReadFile() { - MockMDLoadingView view; - - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); + std::unique_ptr<MDLoadingView> view = + Mantid::Kernel::make_unique<MockMDLoadingView>(); + SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath()); TSM_ASSERT("Should be readable, valid SQW file.", presenter.canReadFile()); } void testCanReadFileWithDifferentCaseExtension() { - SQWLoadingPresenter presenter(new MockMDLoadingView, "other.Sqw"); - TSM_ASSERT("Should be readable, only different in case.", presenter.canReadFile()); + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); + SQWLoadingPresenter presenter(std::move(view), "other.Sqw"); + TSM_ASSERT("Should be readable, only different in case.", + presenter.canReadFile()); } void testCannotReadFileWithWrongExtension() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getUnhandledFileNamePath()); - TSM_ASSERT("Should NOT be readable, completely wrong file type.", !presenter.canReadFile()); + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); + SQWLoadingPresenter presenter(std::move(view), getUnhandledFileNamePath()); + TSM_ASSERT("Should NOT be readable, completely wrong file type.", + !presenter.canReadFile()); } void testExecutionInMemory() { using namespace testing; //Setup view - MockMDLoadingView* view = new MockMDLoadingView; - EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(Return(true)); // View setup to request loading in memory. + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); + EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); + EXPECT_CALL(*view, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(Return(true)); // View setup to request loading in memory. EXPECT_CALL(*view, getTime()).Times(AtLeast(1)); EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -108,9 +126,10 @@ void testExecutionInMemory() EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1)); //Create the presenter and runit! - SQWLoadingPresenter presenter(view, getSuitableFileNamePath()); + SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); std::string fileNameIfGenerated = getFileBackend(getSuitableFileNamePath()); std::ifstream fileExists(fileNameIfGenerated.c_str(), ifstream::in); @@ -124,35 +143,44 @@ void testExecutionInMemory() TS_ASSERT_THROWS_NOTHING(presenter.getGeometryXML()); TS_ASSERT(!presenter.getWorkspaceTypeName().empty()); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(view.get())); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction)); - - product->Delete(); } void testCallHasTDimThrows() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable(), std::runtime_error); + SQWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFileNamePath()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.hasTDimensionAvailable(), std::runtime_error); } void testCallGetTDimensionValuesThrows() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getTimeStepValues(), std::runtime_error); + SQWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFileNamePath()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getTimeStepValues(), std::runtime_error); } void testCallGetGeometryThrows() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); - TSM_ASSERT_THROWS("Should throw. Execute not yet run.", presenter.getGeometryXML(), std::runtime_error); + SQWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFileNamePath()); + TSM_ASSERT_THROWS("Should throw. Execute not yet run.", + presenter.getGeometryXML(), std::runtime_error); } void testExecuteLoadMetadata() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); + SQWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFileNamePath()); presenter.executeLoadMetadata(); TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.getTimeStepValues()); TSM_ASSERT_THROWS_NOTHING("Should throw. Execute not yet run.", presenter.hasTDimensionAvailable()); @@ -161,24 +189,30 @@ void testExecuteLoadMetadata() void testGetWorkspaceTypeName() { - SQWLoadingPresenter presenter(new MockMDLoadingView, getSuitableFileNamePath()); - TSM_ASSERT_EQUALS("Characterisation Test Failed", "", presenter.getWorkspaceTypeName()); + SQWLoadingPresenter presenter( + Mantid::Kernel::make_unique<MockMDLoadingView>(), + getSuitableFileNamePath()); + TSM_ASSERT_EQUALS("Characterisation Test Failed", "", + presenter.getWorkspaceTypeName()); } void testTimeLabel() { using namespace testing; //Setup view - MockMDLoadingView* view = new MockMDLoadingView; + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(Return(true)); // View setup to request loading in memory. + EXPECT_CALL(*view, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(Return(true)); // View setup to request loading in memory. EXPECT_CALL(*view, getTime()).Times(AtLeast(1)); EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -188,34 +222,36 @@ void testTimeLabel() EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1)); //Create the presenter and runit! - SQWLoadingPresenter presenter(view, getSuitableFileNamePath()); + SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); TSM_ASSERT_EQUALS("Time label should be exact.", presenter.getTimeStepLabel(), "en (meV)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(view.get())); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction)); - - product->Delete(); } void testAxisLabels() { using namespace testing; //Setup view - MockMDLoadingView* view = new MockMDLoadingView; + auto view = Mantid::Kernel::make_unique<MockMDLoadingView>(); EXPECT_CALL(*view, getRecursionDepth()).Times(AtLeast(1)); - EXPECT_CALL(*view, getLoadInMemory()).Times(AtLeast(1)).WillRepeatedly(Return(true)); // View setup to request loading in memory. + EXPECT_CALL(*view, getLoadInMemory()) + .Times(AtLeast(1)) + .WillRepeatedly(Return(true)); // View setup to request loading in memory. EXPECT_CALL(*view, getTime()).Times(AtLeast(1)); EXPECT_CALL(*view, updateAlgorithmProgress(_,_)).Times(AnyNumber()); //Setup rendering factory MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(_)).WillOnce(testing::Return(vtkUnstructuredGrid::New())); + EXPECT_CALL(factory, create(_)) + .WillOnce(testing::Return(vtkSmartPointer<vtkUnstructuredGrid>::New())); EXPECT_CALL(factory, setRecursionDepth(_)).Times(1); //Setup progress updates objects @@ -225,9 +261,10 @@ void testAxisLabels() EXPECT_CALL(mockLoadingProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1)); //Create the presenter and runit! - SQWLoadingPresenter presenter(view, getSuitableFileNamePath()); + SQWLoadingPresenter presenter(std::move(view), getSuitableFileNamePath()); presenter.executeLoadMetadata(); - vtkDataSet* product = presenter.execute(&factory, mockLoadingProgressAction, mockDrawingProgressAction); + auto product = presenter.execute(&factory, mockLoadingProgressAction, + mockDrawingProgressAction); TSM_ASSERT_THROWS_NOTHING("Should pass", presenter.setAxisLabels(product)); TSM_ASSERT_EQUALS("X Label should match exactly", getStringFieldDataValue(product, "AxisTitleForX"), @@ -239,11 +276,9 @@ void testAxisLabels() getStringFieldDataValue(product, "AxisTitleForZ"), "qz ($\\AA^{-1}$)"); - TS_ASSERT(Mock::VerifyAndClearExpectations(view)); + TS_ASSERT(Mock::VerifyAndClearExpectations(view.get())); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); TSM_ASSERT("Bad usage of loading algorithm progress updates", Mock::VerifyAndClearExpectations(&mockLoadingProgressAction)); - - product->Delete(); } }; diff --git a/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h b/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h index 5591b78a523dcd5f5f729cd2bea9b8c865c7aa45..1a68d91dd652abcc3e64f4975b0e71a7276a9715 100644 --- a/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h +++ b/Vates/VatesAPI/test/UserDefinedThresholdRangeTest.h @@ -37,12 +37,11 @@ public : void testClone() { Mantid::VATES::UserDefinedThresholdRange original(1, 2); - Mantid::VATES::UserDefinedThresholdRange* cloned = original.clone(); + auto cloned = std::unique_ptr<Mantid::VATES::UserDefinedThresholdRange>( + original.clone()); TS_ASSERT_EQUALS(original.getMaximum(), cloned->getMaximum()); TS_ASSERT_EQUALS(original.getMinimum(), cloned->getMinimum()); - - delete cloned; } void testInRange() diff --git a/Vates/VatesAPI/test/vtkDataSetFactoryTest.h b/Vates/VatesAPI/test/vtkDataSetFactoryTest.h index f53e677e6a94f90496dd3f09af0bc014afd7b643..5cbcee9af7c02786a6068486a645d13705097b09 100644 --- a/Vates/VatesAPI/test/vtkDataSetFactoryTest.h +++ b/Vates/VatesAPI/test/vtkDataSetFactoryTest.h @@ -12,12 +12,14 @@ #include "vtkFloatArray.h" #include "MantidAPI/Workspace.h" #include "MantidAPI/IMDHistoWorkspace.h" +#include "MantidKernel/make_unique.h" #include "MantidTestHelpers/MDEventsTestHelper.h" #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" using namespace Mantid::API; using namespace Mantid::DataObjects; using namespace testing; +using Mantid::VATES::vtkDataSetFactory; class vtkDataSetFactoryTest : public CxxTest::TestSuite { @@ -27,19 +29,17 @@ private: class MockvtkDataSetFactory : public Mantid::VATES::vtkDataSetFactory { public: - MOCK_CONST_METHOD1(create, - vtkDataSet*(Mantid::VATES::ProgressAction&)); + MOCK_CONST_METHOD1( + create, vtkSmartPointer<vtkDataSet>(Mantid::VATES::ProgressAction &)); MOCK_METHOD1(initialize, void(boost::shared_ptr<Mantid::API::Workspace>)); MOCK_CONST_METHOD0(validate, void()); MOCK_CONST_METHOD0(getFactoryTypeName, std::string()); - void SetSuccessorConcrete(vtkDataSetFactory* pSuccessor) - { - return vtkDataSetFactory::SetSuccessor(pSuccessor); + void SetSuccessorConcrete(std::unique_ptr<vtkDataSetFactory> pSuccessor) { + vtkDataSetFactory::SetSuccessor(std::move(pSuccessor)); } - bool hasSuccessorConcrete() const - { + bool hasSuccessorConcrete() const { return vtkDataSetFactory::hasSuccessor(); } }; @@ -53,30 +53,35 @@ private: }; public: - - void testSetSuccessor() - { + void testSetSuccessor() { MockvtkDataSetFactory factory; - MockvtkDataSetFactory* pSuccessor = new MockvtkDataSetFactory; - - EXPECT_CALL(factory, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); - EXPECT_CALL(*pSuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeB")); //Different type name, so setting the successor should work. - factory.SetSuccessor(pSuccessor); + auto successor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + + EXPECT_CALL(factory, getFactoryTypeName()) + .WillOnce(testing::Return("TypeA")); + EXPECT_CALL(*successor, getFactoryTypeName()) + .WillOnce(testing::Return("TypeB")); // Different type name, so setting + // the successor should work. + factory.SetSuccessor(std::move(successor)); TSM_ASSERT("Successor should have been set", factory.hasSuccessor()); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&factory)); - TS_ASSERT(testing::Mock::VerifyAndClearExpectations(pSuccessor)); + TS_ASSERT(testing::Mock::VerifyAndClearExpectations(successor.get())); } - void testSetSuccessorThrows() - { + void testSetSuccessorThrows() { MockvtkDataSetFactory factory; - MockvtkDataSetFactory* pSuccessor = new MockvtkDataSetFactory; - EXPECT_CALL(factory, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); - EXPECT_CALL(*pSuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Same type name. should NOT work. - TSM_ASSERT_THROWS("By default, should throw when successor type is the same as the container.", factory.SetSuccessor(pSuccessor), std::runtime_error); + auto successor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + EXPECT_CALL(factory, getFactoryTypeName()) + .WillOnce(testing::Return("TypeA")); + EXPECT_CALL(*successor, getFactoryTypeName()) + .WillOnce(testing::Return("TypeA")); // Same type name. should NOT work. + TSM_ASSERT_THROWS("By default, should throw when successor type is the " + "same as the container.", + factory.SetSuccessor(std::move(successor)), + std::runtime_error); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&factory)); - TS_ASSERT(testing::Mock::VerifyAndClearExpectations(pSuccessor)); + TS_ASSERT(testing::Mock::VerifyAndClearExpectations(successor.get())); } void testEnumValues() @@ -113,11 +118,13 @@ public: MockvtkDataSetFactory factory; EXPECT_CALL(factory, initialize(_)).Times(1); - EXPECT_CALL(factory, create(Ref(progressUpdater))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); + EXPECT_CALL(factory, create(Ref(progressUpdater))) + .Times(1) + .WillOnce(Return(vtkSmartPointer<vtkStructuredGrid>::New())); IMDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - vtkDataSet* product = factory.oneStepCreate(ws_sptr, progressUpdater); - TS_ASSERT(product != NULL); + auto product = factory.oneStepCreate(ws_sptr, progressUpdater); + TS_ASSERT(product != nullptr); TSM_ASSERT_EQUALS("Output not wired up correctly to ::create() method", "vtkStructuredGrid", std::string(product->GetClassName())); TS_ASSERT(Mock::VerifyAndClearExpectations(&factory)); } diff --git a/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h b/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h index 66c7e23ade2a58dcc802bd19f9c83622d116d454..c08b849c060d6bb86ce7c800dd783074304fb0bb 100644 --- a/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToGeometryTest.h @@ -8,6 +8,7 @@ #include "vtkFieldData.h" #include "vtkCharArray.h" +#include "vtkNew.h" #include "MantidVatesAPI/vtkRectilinearGrid_Silent.h" #include "MantidVatesAPI/VatesXMLDefinitions.h" @@ -81,7 +82,7 @@ private: static vtkFieldData* createFieldDataWithCharArray(std::string testData, std::string id) { vtkFieldData* fieldData = vtkFieldData::New(); - vtkCharArray* charArray = vtkCharArray::New(); + vtkNew<vtkCharArray> charArray; charArray->SetName(id.c_str()); charArray->Allocate(100); for(unsigned int i = 0; i < testData.size(); i++) @@ -93,8 +94,7 @@ static vtkFieldData* createFieldDataWithCharArray(std::string testData, std::str } } - fieldData->AddArray(charArray); - charArray->Delete(); + fieldData->AddArray(charArray.GetPointer()); return fieldData; } @@ -103,10 +103,10 @@ public: void testNoDimensionMappings() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // No mappings - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension()); @@ -114,16 +114,15 @@ public: TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension()); TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension()); TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 5, xmlParser.getNonMappedDimensions().size()); - data->Delete(); } void testGetXDimension() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("en", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only x - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension should have been extracted via its mappings", xmlParser.hasXDimension()); @@ -131,16 +130,15 @@ public: TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension()); TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension()); TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size()); - data->Delete(); } void testGetYDimension() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("", "en", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only y - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension()); @@ -148,16 +146,15 @@ public: TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension()); TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension()); TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size()); - data->Delete(); } void testGetZDimension() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "en", ""), Mantid::VATES::XMLDefinitions::metaDataId())); // Only z - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension()); @@ -165,16 +162,15 @@ public: TSM_ASSERT("Z dimension should have been extracted via its mappings", xmlParser.hasZDimension()); TSM_ASSERT("T dimension mappings are absent. No dimension should have been set.", !xmlParser.hasTDimension()); TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size()); - data->Delete(); } void testGetTDimension() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", "en"), Mantid::VATES::XMLDefinitions::metaDataId())); // Only t - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension mappings are absent. No dimension should have been set.", !xmlParser.hasXDimension()); @@ -182,16 +178,15 @@ public: TSM_ASSERT("Z dimension mappings are absent. No dimension should have been set.", !xmlParser.hasZDimension()); TSM_ASSERT("T dimension should have been extracted via its mappings", xmlParser.hasTDimension()); TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 4, xmlParser.getNonMappedDimensions().size()); - data->Delete(); } void testAllDimensions() { using namespace Mantid::VATES; - vtkRectilinearGrid* data = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> data; data->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId())); // All configured. - vtkDataSetToGeometry xmlParser(data); + vtkDataSetToGeometry xmlParser(data.GetPointer()); xmlParser.execute(); TSM_ASSERT("X dimension should have been extracted via its mappings", xmlParser.hasXDimension()); @@ -206,8 +201,6 @@ public: TSM_ASSERT_EQUALS("Wrong number of non-mapped dimensions", 1, xmlParser.getNonMappedDimensions().size()); TSM_ASSERT_EQUALS("Wrong non-mapped dimension found", "other" ,xmlParser.getNonMappedDimensions()[0]->getDimensionId()); - - data->Delete(); } void testAssignment() @@ -215,14 +208,14 @@ public: using namespace Mantid::VATES; using namespace Mantid::VATES; - vtkRectilinearGrid* dataA = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> dataA; dataA->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId())); - vtkRectilinearGrid* dataB = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> dataB; dataB->SetFieldData(createFieldDataWithCharArray(constructXML("", "", "", ""), Mantid::VATES::XMLDefinitions::metaDataId())); - vtkDataSetToGeometry A(dataA); - vtkDataSetToGeometry B(dataB); + vtkDataSetToGeometry A(dataA.GetPointer()); + vtkDataSetToGeometry B(dataB.GetPointer()); B = A; A.execute(); B.execute(); @@ -243,10 +236,10 @@ public: using namespace Mantid::VATES; using namespace Mantid::VATES; - vtkRectilinearGrid* dataA = vtkRectilinearGrid::New(); + vtkNew<vtkRectilinearGrid> dataA; dataA->SetFieldData(createFieldDataWithCharArray(constructXML("qy", "qx", "en", "qz"), Mantid::VATES::XMLDefinitions::metaDataId())); - vtkDataSetToGeometry A(dataA); + vtkDataSetToGeometry A(dataA.GetPointer()); vtkDataSetToGeometry B = A; A.execute(); B.execute(); diff --git a/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h b/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h index 20cd3bb175b242787987ccc36105c2574575c8f1..481cada11222ab9795c317b00cd584ce195c832e 100644 --- a/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToImplicitFunctionTest.h @@ -7,6 +7,7 @@ #include "MockObjects.h" #include <vtkDataSet.h> #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include <vtkNew.h> using namespace Mantid::VATES; @@ -25,44 +26,28 @@ public: TS_ASSERT_THROWS(vtkDataSetToImplicitFunction temp(nullArg), std::runtime_error); } - //void testExecution() - //{ - // vtkStructuredGrid* ds = vtkStructuredGrid::New(); - // ds->SetFieldData(createFieldDataWithCharArray(constructXML())); - - // vtkDataSetToImplicitFunction extractor(ds); - // Mantid::Geometry::MDImplicitFunction* func = NULL; - // TS_ASSERT_THROWS_NOTHING(func = extractor.execute()); - // TS_ASSERT_EQUALS("PlaneImplicitFunction", func->getName()); - // ds->Delete(); - // delete func; - //} - - void testNoImplcitFunction() - { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + void testNoImplcitFunction() { + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray("<MDInstruction/>")); - vtkDataSetToImplicitFunction extractor(ds); - Mantid::Geometry::MDImplicitFunction* func = NULL; - TS_ASSERT_THROWS_NOTHING(func = extractor.execute()); + vtkDataSetToImplicitFunction extractor(ds.GetPointer()); + std::unique_ptr<Mantid::Geometry::MDImplicitFunction> func; + TS_ASSERT_THROWS_NOTHING( + func = std::unique_ptr<Mantid::Geometry::MDImplicitFunction>( + extractor.execute())); TS_ASSERT_EQUALS("NullImplicitFunction", func->getName()); - ds->Delete(); - delete func; } - void testStaticUsage() - { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + void testStaticUsage() { + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray("<MDInstruction/>")); - Mantid::Geometry::MDImplicitFunction* func = NULL; - TS_ASSERT_THROWS_NOTHING(func = vtkDataSetToImplicitFunction::exec(ds)); + std::unique_ptr<Mantid::Geometry::MDImplicitFunction> func; + TS_ASSERT_THROWS_NOTHING( + func = std::unique_ptr<Mantid::Geometry::MDImplicitFunction>( + vtkDataSetToImplicitFunction::exec(ds.GetPointer()))); TS_ASSERT_EQUALS("NullImplicitFunction", func->getName()); - ds->Delete(); - delete func; } - }; #endif diff --git a/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h index a3061c905bee51731cefacf4af0305dc7872246f..069968ecaae37b87971f6e8fbc73c07c01996024 100644 --- a/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToNonOrthogonalDataSetTest.h @@ -20,6 +20,8 @@ #include <vtkPoints.h> #include "MantidVatesAPI/vtkRectilinearGrid_Silent.h" #include <vtkUnstructuredGrid.h> +#include <vtkNew.h> +#include <vtkSmartPointer.h> using namespace Mantid::API; using namespace Mantid::Kernel; @@ -231,81 +233,79 @@ public: std::runtime_error); } - void testThrowsIfWorkspaceNameEmpty() - { - vtkUnstructuredGrid *dataset = vtkUnstructuredGrid::New(); - TS_ASSERT_THROWS(vtkDataSetToNonOrthogonalDataSet temp(dataset, ""), - std::runtime_error); - dataset->Delete(); + void testThrowsIfWorkspaceNameEmpty() { + vtkNew<vtkUnstructuredGrid> dataset; + TS_ASSERT_THROWS( + vtkDataSetToNonOrthogonalDataSet temp(dataset.GetPointer(), ""), + std::runtime_error); } - void testThrowIfVtkDatasetWrongType() - { - vtkRectilinearGrid *grid = vtkRectilinearGrid::New(); - vtkDataSetToNonOrthogonalDataSet converter(grid, "name"); + void testThrowIfVtkDatasetWrongType() { + vtkNew<vtkRectilinearGrid> grid; + vtkDataSetToNonOrthogonalDataSet converter(grid.GetPointer(), "name"); TS_ASSERT_THROWS(converter.execute(), std::runtime_error); - grid->Delete(); } void testSimpleDataset() { std::string wsName = createMantidWorkspace(false); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS_NOTHING(converter.execute()); this->checkUnityTransformation(ds); - ds->Delete(); } void testThrowsSimpleDatasetWrongCoords() { std::string wsName = createMantidWorkspace(false, true); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS(converter.execute(), std::invalid_argument); - ds->Delete(); } void testThrowsSimpleDatasetNoUB() { std::string wsName = createMantidWorkspace(false, false, true); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS(converter.execute(), std::invalid_argument); - ds->Delete(); } void testThrowsSimpleDatasetNoWMatrix() { std::string wsName = createMantidWorkspace(false, false, false, true); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS(converter.execute(), std::invalid_argument); - ds->Delete(); } void testNoThrowsSimpleDataSetNoAffineMatrix() { std::string wsName = createMantidWorkspace(false, false, false, false, true); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS_NOTHING(converter.execute()); - ds->Delete(); } void testStaticUseForSimpleDataSet() { std::string wsName = createMantidWorkspace(false); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); - TS_ASSERT_THROWS_NOTHING(vtkDataSetToNonOrthogonalDataSet::exec(ds, - wsName)); - ds->Delete(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); + TS_ASSERT_THROWS_NOTHING( + vtkDataSetToNonOrthogonalDataSet::exec(ds, wsName)); } void testNonUnitySimpleDataset() { std::string wsName = createMantidWorkspace(true); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS_NOTHING(converter.execute()); // Now, check some values @@ -344,24 +344,23 @@ public: TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps); TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps); TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps); - - ds->Delete(); } void testScaledSimpleDataset() { std::string wsName = createMantidWorkspace(false, false, false, false, false, 2.0); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS_NOTHING(converter.execute()); this->checkUnityTransformation(ds); - ds->Delete(); } void testScaledNonUnitySimpleDataset() { std::string wsName = createMantidWorkspace(true, false, false, false, false, 2.0); - vtkUnstructuredGrid *ds = createSingleVoxelPoints(); + vtkSmartPointer<vtkUnstructuredGrid> ds; + ds.TakeReference(createSingleVoxelPoints()); vtkDataSetToNonOrthogonalDataSet converter(ds, wsName); TS_ASSERT_THROWS_NOTHING(converter.execute()); // Now, check some values @@ -400,8 +399,6 @@ public: TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps); TS_ASSERT_DELTA(basisMatrix[index++], 0.0, eps); TS_ASSERT_DELTA(basisMatrix[index++], 1.0, eps); - - ds->Delete(); } }; diff --git a/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h index a238bfa66872bd46a7b0400340aca94c6bd7c5a8..bcf942a9a1336a0188a1962c3d04491dcd59cf5c 100644 --- a/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToPeaksFilteredDataSetTest.h @@ -29,6 +29,8 @@ #include <vtkFloatArray.h> #include <vtkUnsignedCharArray.h> #include <vtkUnstructuredGrid.h> +#include <vtkSmartPointer.h> +#include <vtkNew.h> #include <boost/shared_ptr.hpp> @@ -62,16 +64,16 @@ struct PeaksFilterDataContainer { class vtkDataSetToPeaksFilteredDataSetTest : public CxxTest::TestSuite { private: - vtkUnstructuredGrid* makeSplatterSourceGrid() - { + vtkSmartPointer<vtkUnstructuredGrid> makeSplatterSourceGrid() { FakeProgressAction progressUpdate; MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, -10.0, 10.0, 1); vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal"); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); - vtkUnstructuredGrid* splatData = vtkUnstructuredGrid::SafeDownCast(product); - return splatData; + auto splatData = vtkUnstructuredGrid::SafeDownCast(product.Get()); + vtkSmartPointer<vtkUnstructuredGrid> grid(splatData); + return grid; } public: @@ -113,11 +115,12 @@ public: } } - void do_test_peaks(vtkUnstructuredGrid* in, vtkUnstructuredGrid* out, std::vector<PeaksFilterDataContainer> peakData) - { - vtkPoints* inPoints = in->GetPoints(); - vtkPoints* outPoints = out->GetPoints(); - + void do_test_peaks(vtkSmartPointer<vtkUnstructuredGrid> in, + vtkSmartPointer<vtkUnstructuredGrid> out, + std::vector<PeaksFilterDataContainer> peakData) { + vtkPoints *inPoints = in->GetPoints(); + vtkPoints *outPoints = out->GetPoints(); + int numberOfInPoints = static_cast<int>(inPoints->GetNumberOfPoints()); int numberOfOutPoints = static_cast<int>(outPoints->GetNumberOfPoints()); @@ -174,22 +177,22 @@ public: void testThrowIfInputNull() { - vtkUnstructuredGrid *in = NULL; - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + vtkUnstructuredGrid *in = nullptr; + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out), std::runtime_error); } void testThrowIfOutputNull() { - vtkUnstructuredGrid *in = vtkUnstructuredGrid::New(); - vtkUnstructuredGrid *out = NULL; + auto in = vtkSmartPointer<vtkUnstructuredGrid>::New(); + vtkUnstructuredGrid *out = nullptr; TS_ASSERT_THROWS(vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out), std::runtime_error); } void testExecThrowIfNoInit() { - vtkUnstructuredGrid *in = vtkUnstructuredGrid::New(); - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + auto in = vtkSmartPointer<vtkUnstructuredGrid>::New(); + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out); FakeProgressAction updateProgress; TS_ASSERT_THROWS(peaksFilter.execute(updateProgress), std::runtime_error); @@ -198,8 +201,8 @@ public: void testExecutionWithSingleSphericalPeakInQSample() { // Arrange - vtkUnstructuredGrid *in = makeSplatterSourceGrid(); - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + auto in = makeSplatterSourceGrid(); + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out); Mantid::Kernel::V3D coordinate(0,0,0); @@ -226,16 +229,13 @@ public: // Assert do_test_peaks(in, out, peakData); - - in->Delete(); - out->Delete(); } void testExecutionWithSingleEllipsoidPeakInQSample() { // Arrange - vtkUnstructuredGrid *in = makeSplatterSourceGrid(); - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + auto in = makeSplatterSourceGrid(); + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out); Mantid::Kernel::V3D coordinate(0,0,0); @@ -270,16 +270,13 @@ public: // Assert do_test_peaks(in, out, peakData); - - in->Delete(); - out->Delete(); } void testExecutionWithSingleNoShapePeakInQSample() { // Arrange - vtkUnstructuredGrid *in = makeSplatterSourceGrid(); - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + auto in = makeSplatterSourceGrid(); + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out); Mantid::Kernel::V3D coordinate(0,0,0); @@ -305,15 +302,12 @@ public: // Assert do_test_peaks(in, out, peakData); - - in->Delete(); - out->Delete(); } void testExecutionWithTwoWorkspacesWithSingleSphericalShapesInQSample() { // Arrange - vtkUnstructuredGrid *in = makeSplatterSourceGrid(); - vtkUnstructuredGrid *out = vtkUnstructuredGrid::New(); + auto in = makeSplatterSourceGrid(); + auto out = vtkSmartPointer<vtkUnstructuredGrid>::New(); vtkDataSetToPeaksFilteredDataSet peaksFilter(in, out); // Peak 1 @@ -353,9 +347,6 @@ public: // Assert do_test_peaks(in, out, peakData); - - in->Delete(); - out->Delete(); } }; #endif diff --git a/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h b/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h index 4da62208f916d60e7574f4e4bbca0e97e105e3a8..a92082be238f9065c68f86ceb39e06684479c1b9 100644 --- a/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToScaledDataSetTest.h @@ -23,23 +23,28 @@ #include <vtkUnsignedCharArray.h> #include <vtkUnstructuredGrid.h> #include <vtkPointSet.h> +#include <vtkNew.h> +#include <vtkSmartPointer.h> using namespace Mantid::DataObjects; using namespace Mantid::VATES; class vtkDataSetToScaledDataSetTest : public CxxTest::TestSuite { private: - vtkUnstructuredGrid *makeDataSet() { + vtkSmartPointer<vtkUnstructuredGrid> makeDataSet() { FakeProgressAction progressUpdate; MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(8, -10.0, 10.0, 1); vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VolumeNormalization); factory.initialize(ws); - return vtkUnstructuredGrid::SafeDownCast(factory.create(progressUpdate)); + auto product = factory.create(progressUpdate); + auto data = vtkUnstructuredGrid::SafeDownCast(product.Get()); + vtkSmartPointer<vtkUnstructuredGrid> grid(data); + return grid; } - vtkUnstructuredGrid *makeDataSetWithNonOrthogonal() { + vtkSmartPointer<vtkUnstructuredGrid> makeDataSetWithNonOrthogonal() { auto grid = makeDataSet(); auto u = vtkVector3d(4, 4, 0); auto v = vtkVector3d(-2, 2, 0); @@ -56,8 +61,8 @@ private: return grid; } - vtkUnstructuredGrid *makeDataSetWithJsonMetadata() { - vtkUnstructuredGrid *data = makeDataSet(); + vtkSmartPointer<vtkUnstructuredGrid> makeDataSetWithJsonMetadata() { + auto data = makeDataSet(); MetadataJsonManager manager; std::string instrument = "OSIRIS"; @@ -96,8 +101,9 @@ public: void testExecution() { vtkDataSetToScaledDataSet scaler; - vtkUnstructuredGrid *in = makeDataSet(); - vtkPointSet* out = scaler.execute(0.1, 0.5, 0.2,in); + auto in = makeDataSet(); + auto out = + vtkSmartPointer<vtkPointSet>::Take(scaler.execute(0.1, 0.5, 0.2, in)); // Check bounds are scaled double *bb = out->GetBounds(); @@ -141,20 +147,18 @@ public: TS_ASSERT_EQUALS(10.0, bounds[3]); TS_ASSERT_EQUALS(-10.0, bounds[4]); TS_ASSERT_EQUALS(10.0, bounds[5]); - - in->Delete(); - out->Delete(); } void testJsonMetadataExtractionFromScaledDataSet() { // Arrange - vtkUnstructuredGrid *in = makeDataSetWithJsonMetadata(); + auto in = makeDataSetWithJsonMetadata(); // Act vtkDataSetToScaledDataSet scaler; - vtkPointSet* out = scaler.execute(0.1, 0.5, 0.2, in); + auto out = + vtkSmartPointer<vtkPointSet>::Take(scaler.execute(0.1, 0.5, 0.2, in)); - vtkFieldData *fieldData = out->GetFieldData(); + auto fieldData = out->GetFieldData(); MetadataJsonManager manager; VatesConfigurations config; FieldDataToMetadata convert; @@ -164,16 +168,14 @@ public: // Assert TS_ASSERT("OSIRIS" == manager.getInstrument()); - - in->Delete(); - out->Delete(); } void testExecutionWithNonOrthogonalDataSet() { vtkDataSetToScaledDataSet scaler; - vtkUnstructuredGrid *in = makeDataSetWithNonOrthogonal(); - vtkPointSet* out = scaler.execute(0.25, 0.5, 0.125, in); + auto in = makeDataSetWithNonOrthogonal(); + auto out = vtkSmartPointer<vtkPointSet>::Take( + scaler.execute(0.25, 0.5, 0.125, in)); // Check bounds are scaled double *bb = out->GetBounds(); @@ -216,9 +218,6 @@ public: TS_ASSERT_EQUALS(10.0, bounds[3]); TS_ASSERT_EQUALS(-10.0, bounds[4]); TS_ASSERT_EQUALS(10.0, bounds[5]); - - in->Delete(); - out->Delete(); } }; diff --git a/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h b/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h index d401782fa3b30656d76981e1637fd9426fb085b8..1383d32900527c2372dd8d0be5ae54602c8da195 100644 --- a/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToWsLocationTest.h @@ -6,6 +6,7 @@ #include <vtkDataSet.h> #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" #include "MockObjects.h" +#include <vtkNew.h> using namespace Mantid::VATES; @@ -37,22 +38,21 @@ public: void testExecution() { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray(constructXML())); - vtkDataSetToWsLocation extractor(ds); + vtkDataSetToWsLocation extractor(ds.GetPointer()); TS_ASSERT_EQUALS("WS_LOCATION", extractor.execute()); - ds->Delete(); } void testStaticUsage() { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray(constructXML())); - TS_ASSERT_EQUALS("WS_LOCATION", vtkDataSetToWsLocation::exec(ds)); + TS_ASSERT_EQUALS("WS_LOCATION", + vtkDataSetToWsLocation::exec(ds.GetPointer())); } - }; #endif diff --git a/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h b/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h index e9c1a00c063d2f6b33b4d1035dc88cf0fbfabc60..67d2eb49e14be61a4715f29daa6d64c34ed06cbc 100644 --- a/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h +++ b/Vates/VatesAPI/test/vtkDataSetToWsNameTest.h @@ -5,6 +5,7 @@ #include "MantidVatesAPI/vtkDataSetToWsName.h" #include "MockObjects.h" #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include <vtkNew.h> using namespace Mantid::VATES; @@ -37,22 +38,20 @@ public: void testExecution() { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray(constructXML())); - vtkDataSetToWsName extractor(ds); + vtkDataSetToWsName extractor(ds.GetPointer()); TS_ASSERT_EQUALS("WS_NAME", extractor.execute()); - ds->Delete(); } void testStaticUsage() { - vtkStructuredGrid* ds = vtkStructuredGrid::New(); + vtkNew<vtkStructuredGrid> ds; ds->SetFieldData(createFieldDataWithCharArray(constructXML())); - TS_ASSERT_EQUALS("WS_NAME", vtkDataSetToWsName::exec(ds)); + TS_ASSERT_EQUALS("WS_NAME", vtkDataSetToWsName::exec(ds.GetPointer())); } - }; #endif diff --git a/Vates/VatesAPI/test/vtkMD0DFactoryTest.h b/Vates/VatesAPI/test/vtkMD0DFactoryTest.h index 4041fd870aab3edf0ffc69d5ae6c7b499fc9b7f0..e425c548c6ac8a81d2766e872be5c54e2a707d19 100644 --- a/Vates/VatesAPI/test/vtkMD0DFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMD0DFactoryTest.h @@ -17,10 +17,12 @@ public: FakeProgressAction progressUpdater; vtkMD0DFactory factory; - vtkDataSet* dataSet = NULL; + vtkSmartPointer<vtkDataSet> dataSet; // Assert - TSM_ASSERT_THROWS_NOTHING("0D factory should create data set without exceptions", dataSet = factory.create(progressUpdater)); + TSM_ASSERT_THROWS_NOTHING( + "0D factory should create data set without exceptions", + dataSet = factory.create(progressUpdater)); TSM_ASSERT("Should have exactly one point", dataSet->GetNumberOfPoints() == 1); TSM_ASSERT("Should have exactly one cell", dataSet->GetNumberOfCells() == 1); } diff --git a/Vates/VatesAPI/test/vtkMDHWSignalArrayTest.h b/Vates/VatesAPI/test/vtkMDHWSignalArrayTest.h index 56de313aa496fc7bad45859339a28f4084ef783f..dcf1ecb227bd881f68404880602884808029dd3a 100644 --- a/Vates/VatesAPI/test/vtkMDHWSignalArrayTest.h +++ b/Vates/VatesAPI/test/vtkMDHWSignalArrayTest.h @@ -125,10 +125,6 @@ public: vtkNew<vtkIdList> idList1, idList2; - signal->LookupValue(0.0, idList1.GetPointer()); - TSM_ASSERT_EQUALS("IDs for the 3 masked points should have been found", - idList1->GetNumberOfIds(), 3); - signal->LookupTypedValue(1.0, idList2.GetPointer()); TSM_ASSERT_EQUALS("IDs for the 61 unmasked points should have been found", idList2->GetNumberOfIds(), 61); diff --git a/Vates/VatesAPI/test/vtkMDHexFactoryTest.h b/Vates/VatesAPI/test/vtkMDHexFactoryTest.h index 8244231bc1cfb14474cb492b01334b516db70b7e..d5925b151c5a20daee674cc9a5b672f911069c19 100644 --- a/Vates/VatesAPI/test/vtkMDHexFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDHexFactoryTest.h @@ -2,6 +2,7 @@ #define VTK_MD_HEX_FACTORY_TEST #include "MantidAPI/IMDEventWorkspace.h" +#include "MantidKernel/make_unique.h" #include "MantidDataObjects/MDEventFactory.h" #include "MantidDataObjects/MDEventWorkspace.h" #include "MantidDataObjects/MDHistoWorkspace.h" @@ -17,6 +18,7 @@ #include <vtkCellData.h> #include <vtkDataArray.h> #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include <vtkSmartPointer.h> using namespace Mantid; using namespace Mantid::VATES; @@ -48,7 +50,8 @@ private: Workspace_sptr binned_ws = AnalysisDataService::Instance().retrieve("binned"); FakeProgressAction progressUpdater; - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); factory.setCheckDimensionality(doCheckDimensionality); if(doCheckDimensionality) { @@ -57,9 +60,8 @@ private: else { TS_ASSERT_THROWS_NOTHING(factory.initialize(binned_ws)); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdater)); - product->Delete(); } } @@ -70,13 +72,15 @@ public: void testCreateWithoutInitalizeThrows() { FakeProgressAction progressUpdater; - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); TSM_ASSERT_THROWS("Have NOT initalized object. Should throw.", factory.create(progressUpdater), std::runtime_error); } void testInitalizeWithNullWorkspaceThrows() { - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); IMDEventWorkspace* ws = NULL; TSM_ASSERT_THROWS("This is a NULL workspace. Should throw.", factory.initialize( Workspace_sptr(ws) ), std::invalid_argument); @@ -85,47 +89,55 @@ public: void testGetFactoryTypeName() { - vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<NoThresholdRange>(), + VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDHexFactory", factory.getFactoryTypeName()); } void testInitializeDelegatesToSuccessor() { - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDHexFactory factory(boost::make_shared<NoThresholdRange>(), + VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testCreateDelegatesToSuccessor() { FakeProgressAction progressUpdater; - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); - EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdater))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); + EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdater))) + .Times(1) + .WillOnce(Return(vtkSmartPointer<vtkStructuredGrid>::New())); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDHexFactory factory(boost::make_shared<NoThresholdRange>(), + VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdater)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testOnInitaliseCannotDelegateToSuccessor() { FakeProgressAction progressUpdater; - vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<NoThresholdRange>(), + VATES::VolumeNormalization); //factory.SetSuccessor(mockSuccessor); No Successor set. ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); @@ -135,7 +147,8 @@ public: void testCreateWithoutInitializeThrows() { FakeProgressAction progressUpdater; - vtkMDHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<NoThresholdRange>(), + VATES::VolumeNormalization); //initialize not called! TS_ASSERT_THROWS(factory.create(progressUpdater), std::runtime_error); } @@ -156,9 +169,10 @@ public: FakeProgressAction progressUpdate; Mantid::DataObjects::MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 1); - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -180,8 +194,6 @@ public: TS_ASSERT_EQUALS(10, bounds[3]); TS_ASSERT_EQUALS(0, bounds[4]); TS_ASSERT_EQUALS(10, bounds[5]); - - product->Delete(); } void test_4DWorkspace() @@ -190,9 +202,10 @@ public: EXPECT_CALL(mockProgressAction, eventRaised(_)).Times(AtLeast(1)); Mantid::DataObjects::MDEventWorkspace4Lean::sptr ws = MDEventsTestHelper::makeMDEW<4>(5, -10.0, 10.0, 1); - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(mockProgressAction)); @@ -216,8 +229,6 @@ public: TS_ASSERT_EQUALS(10, bounds[5]); TSM_ASSERT("Progress reporting has not been conducted as expected", Mock::VerifyAndClearExpectations(&mockProgressAction)); - - product->Delete(); } @@ -247,9 +258,10 @@ public : { FakeProgressAction progressUpdate; - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); factory.initialize(m_ws3); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -274,18 +286,16 @@ public : TS_ASSERT_EQUALS(0, bounds[4]); TS_ASSERT_EQUALS(100, bounds[5]); } - - - product->Delete(); } /* Create 1E6 cells*/ void test_CreateDataSet_from4D() { FakeProgressAction progressUpdate; - vtkMDHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), VATES::VolumeNormalization); + vtkMDHexFactory factory(boost::make_shared<UserDefinedThresholdRange>(0, 1), + VATES::VolumeNormalization); factory.initialize(m_ws4); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -298,8 +308,6 @@ public : TSM_ASSERT_EQUALS("Wrong number of points to cells. Hexahedron has 8 vertexes.", expected_n_cells * 8, product->GetNumberOfPoints()); TSM_ASSERT_EQUALS("No signal Array", "signal", std::string(product->GetCellData()->GetArray(0)->GetName())); TSM_ASSERT_EQUALS("Wrong sized signal Array", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize()); - - product->Delete(); } }; diff --git a/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h index cacd884f38e46ad3c519bf50652c30b3b836825b..d2500fcc306138ac7294ef8546d313a10f07301a 100644 --- a/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDHistoHex4DFactoryTest.h @@ -11,6 +11,8 @@ #include "MockObjects.h" #include <cxxtest/TestSuite.h> #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include <vtkSmartPointer.h> +#include "MantidKernel/make_unique.h" using namespace Mantid; using namespace Mantid::DataObjects; @@ -39,18 +41,18 @@ public: vtkMDHistoHex4DFactory<TimeStepToTimeStep> inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization, 0); inside.initialize(ws_sptr); - vtkStructuredGrid *insideProduct = - dynamic_cast<vtkStructuredGrid *>(inside.create(progressAction)); + auto insideData = inside.create(progressAction); + auto insideProduct = vtkStructuredGrid::SafeDownCast(insideData.Get()); vtkMDHistoHex4DFactory<TimeStepToTimeStep> below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization, 0); below.initialize(ws_sptr); - vtkStructuredGrid *belowProduct = - dynamic_cast<vtkStructuredGrid *>(below.create(progressAction)); + auto belowData = below.create(progressAction); + auto belowProduct = vtkStructuredGrid::SafeDownCast(belowData.Get()); vtkMDHistoHex4DFactory<TimeStepToTimeStep> above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), Mantid::VATES::VolumeNormalization, 0); above.initialize(ws_sptr); - vtkStructuredGrid *aboveProduct = - dynamic_cast<vtkStructuredGrid *>(above.create(progressAction)); + auto aboveData = above.create(progressAction); + auto aboveProduct = vtkStructuredGrid::SafeDownCast(aboveData.Get()); TS_ASSERT_EQUALS((10*10*10), insideProduct->GetNumberOfCells()); for (auto i = 0; i < insideProduct->GetNumberOfCells(); ++i) { @@ -79,34 +81,41 @@ public: vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization, 0); factory.initialize(ws_sptr); - vtkDataSet* product= factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); - product->Delete(); } - void testSignalAspects() - { + void testSignalAspects() { FakeProgressAction progressUpdate; // Workspace with value 1.0 everywhere - MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4); + MDHistoWorkspace_sptr ws_sptr = + MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4); ws_sptr->setTransformFromOriginal(new NullCoordTransform); - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); - //Constructional method ensures that factory is only suitable for providing mesh information. + // Constructional method ensures that factory is only suitable for providing + // mesh information. vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory = - vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 0); + vtkMDHistoHex4DFactory<TimeStepToTimeStep>( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, 0); factory.initialize(ws_sptr); - vtkDataSet* product = factory.create(progressUpdate); - TSM_ASSERT_EQUALS("A single array should be present on the product dataset.", 1, product->GetCellData()->GetNumberOfArrays()); - vtkDataArray* signalData = product->GetCellData()->GetArray(0); - TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), std::string(signalData->GetName())); - const int correctCellNumber = 10*10*10; - TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", correctCellNumber, signalData->GetSize()); - - product->Delete(); + auto product = factory.create(progressUpdate); + TSM_ASSERT_EQUALS( + "A single array should be present on the product dataset.", 1, + product->GetCellData()->GetNumberOfArrays()); + auto signalData = vtkSmartPointer<vtkDataArray>::Take( + product->GetCellData()->GetArray(0)); + TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", + std::string("signal"), + std::string(signalData->GetName())); + const int correctCellNumber = 10 * 10 * 10; + TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", + correctCellNumber, signalData->GetSize()); } void testIsValidThrowsWhenNoWorkspace() @@ -124,8 +133,11 @@ public: { FakeProgressAction progressAction; - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); - vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 1); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); + vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, 1); TS_ASSERT_THROWS(factory.create(progressAction), std::runtime_error); } @@ -135,22 +147,27 @@ public: // 2D workspace MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. - EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); + EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); //Constructional method ensures that factory is only suitable for providing mesh information. vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory = - vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0); + vtkMDHistoHex4DFactory<TimeStepToTimeStep>( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, (double)0); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testInitializationDelegatesThrows() @@ -159,11 +176,14 @@ public: // 2D workspace MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); //Constructional method ensures that factory is only suitable for providing mesh information. vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory = - vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0); + vtkMDHistoHex4DFactory<TimeStepToTimeStep>( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, (double)0); TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error); } @@ -176,34 +196,47 @@ public: // 2D workspace MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; + auto pMockFactorySuccessor = Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. - EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); //expect it then to call create on the successor. - EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); - - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); + EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce( + Return(vtkSmartPointer<vtkStructuredGrid>::New())); // expect it + // then to call + // create on the + // successor. + EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); + + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); //Constructional method ensures that factory is only suitable for providing mesh information. vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory = - vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0); + vtkMDHistoHex4DFactory<TimeStepToTimeStep>( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, (double)0); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); factory.create(progressUpdate); // should be called on successor. - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testTypeName() { using namespace Mantid::VATES; - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100); vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory = - vtkMDHistoHex4DFactory<TimeStepToTimeStep> (ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, (double)0); + vtkMDHistoHex4DFactory<TimeStepToTimeStep>( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, (double)0); TS_ASSERT_EQUALS("vtkMDHistoHex4DFactory", factory.getFactoryTypeName()); } @@ -231,8 +264,11 @@ public: { FakeProgressAction progressUpdate; - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100000); - vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization, 0); + auto pRange = + Mantid::Kernel::make_unique<UserDefinedThresholdRange>(0, 100000); + vtkMDHistoHex4DFactory<TimeStepToTimeStep> factory( + ThresholdRange_scptr(pRange.release()), + Mantid::VATES::VolumeNormalization, 0); factory.initialize(m_ws_sptr); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); } diff --git a/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h index b3bb0d8578d76d66bc672c110ddcd9138a15cc94..12bff11581670aff895f700eeee688c156ab42c3 100644 --- a/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDHistoHexFactoryTest.h @@ -1,6 +1,7 @@ #ifndef VTK_MD_HISTO_HEX_FACTORY_TEST_H_ #define VTK_MD_HISTO_HEX_FACTORY_TEST_H_ +#include "MantidKernel/make_unique.h" #include "MantidDataObjects/MDHistoWorkspace.h" #include "MantidTestHelpers/MDEventsTestHelper.h" #include "MantidVatesAPI/UserDefinedThresholdRange.h" @@ -13,6 +14,7 @@ #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" #include "vtkStructuredGrid.h" #include "vtkUnsignedCharArray.h" +#include "vtkSmartPointer.h" using namespace Mantid; using namespace Mantid::API; @@ -37,20 +39,26 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3); ws_sptr->setTransformFromOriginal(new NullCoordTransform); - vtkMDHistoHexFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory inside( + boost::make_shared<UserDefinedThresholdRange>(0, 2), + Mantid::VATES::VolumeNormalization); inside.initialize(ws_sptr); - vtkStructuredGrid *insideProduct = - dynamic_cast<vtkStructuredGrid *>(inside.create(progressUpdate)); + auto insideData = inside.create(progressUpdate); + auto insideProduct = vtkStructuredGrid::SafeDownCast(insideData.Get()); - vtkMDHistoHexFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory below( + boost::make_shared<UserDefinedThresholdRange>(0, 0.5), + Mantid::VATES::VolumeNormalization); below.initialize(ws_sptr); - vtkStructuredGrid *belowProduct = - dynamic_cast<vtkStructuredGrid *>(below.create(progressUpdate)); + auto belowData = below.create(progressUpdate); + auto belowProduct = vtkStructuredGrid::SafeDownCast(belowData.Get()); - vtkMDHistoHexFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(2, 3)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory above( + boost::make_shared<UserDefinedThresholdRange>(2, 3), + Mantid::VATES::VolumeNormalization); above.initialize(ws_sptr); - vtkStructuredGrid *aboveProduct = - dynamic_cast<vtkStructuredGrid *>(above.create(progressUpdate)); + auto aboveData = above.create(progressUpdate); + auto aboveProduct = vtkStructuredGrid::SafeDownCast(aboveData.Get()); TS_ASSERT_EQUALS((10*10*10), insideProduct->GetNumberOfCells()); for (auto i = 0; i < insideProduct->GetNumberOfCells(); ++i) { @@ -78,16 +86,17 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite ws_sptr->setTransformFromOriginal(new NullCoordTransform); //Constructional method ensures that factory is only suitable for providing mesh information. - vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); factory.initialize(ws_sptr); - vtkDataSet* product = factory.create(progressUpdate); + auto product = factory.create(progressUpdate); TSM_ASSERT_EQUALS("A single array should be present on the product dataset.", 1, product->GetCellData()->GetNumberOfArrays()); vtkDataArray* signalData = product->GetCellData()->GetArray(0); TSM_ASSERT_EQUALS("The obtained cell data has the wrong name.", std::string("signal"), std::string(signalData->GetName())); const int correctCellNumber = 10 * 10 * 10; TSM_ASSERT_EQUALS("The number of signal values generated is incorrect.", correctCellNumber, signalData->GetSize()); - product->Delete(); } void testProgressUpdating() @@ -97,21 +106,23 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite EXPECT_CALL(mockProgressAction, eventRaised(AllOf(Le(100),Ge(0)))).Times(AtLeast(1)); MDHistoWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3); - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); factory.initialize(ws_sptr); - vtkDataSet* product= factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); - product->Delete(); } void testIsValidThrowsWhenNoWorkspace() { IMDWorkspace* nullWorkspace = NULL; Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace); - - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument); } @@ -119,7 +130,9 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite void testCreateWithoutInitializeThrows() { FakeProgressAction progressUpdate; - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } @@ -128,19 +141,23 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite //If the workspace provided is not a 4D imdworkspace, it should call the successor's initalization Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Constructional method ensures that factory is only suitable for providing mesh information. - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testInitializationDelegatesThrows() @@ -149,7 +166,9 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); //Constructional method ensures that factory is only suitable for providing mesh information. - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); TSM_ASSERT_THROWS("Should have thrown an execption given that no successor was available.", factory.initialize(ws_sptr), std::runtime_error); } @@ -161,28 +180,40 @@ class vtkMDHistoHexFactoryTest: public CxxTest::TestSuite //2 dimensions on the workspace. Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. - EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); //expect it then to call create on the successor. + EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce( + Return(vtkSmartPointer<vtkStructuredGrid>::New())); // expect it + // then to call + // create on the + // successor. EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Constructional method ensures that factory is only suitable for providing mesh information. - vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); factory.create(progressUpdate); // should be called on successor. - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testTypeName() { using namespace Mantid::VATES; - vtkMDHistoHexFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDHistoHexFactory", factory.getFactoryTypeName()); } @@ -211,7 +242,9 @@ public: FakeProgressAction progressUpdate; //Create the factory. - vtkMDHistoHexFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); + vtkMDHistoHexFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); factory.initialize(m_ws_sptr); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); diff --git a/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h index 806d9a412aed3b1a6b50566993e9ed23b13c027e..a0c9cd58830443f81e7658b87c9e0f213a124ded 100644 --- a/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDHistoLineFactoryTest.h @@ -11,6 +11,8 @@ #include <gmock/gmock.h> #include <gtest/gtest.h> #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include <vtkSmartPointer.h> +#include "MantidKernel/make_unique.h" using namespace Mantid; using namespace Mantid::DataObjects; @@ -54,7 +56,8 @@ public: //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2. vtkMDHistoLineFactory inside(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)), Mantid::VATES::VolumeNormalization); inside.initialize(ws_sptr); - vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressUpdate)); + auto insideData = inside.create(progressUpdate); + auto insideProduct = vtkUnstructuredGrid::SafeDownCast(insideData.Get()); TS_ASSERT_EQUALS(9, insideProduct->GetNumberOfCells()); TS_ASSERT_EQUALS(10, insideProduct->GetNumberOfPoints()); @@ -72,7 +75,8 @@ public: //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall above and outside the minimum 0 and maximum 0.5. vtkMDHistoLineFactory above(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 0.5)), Mantid::VATES::VolumeNormalization); above.initialize(ws_sptr); - vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressUpdate)); + auto aboveData = above.create(progressUpdate); + auto aboveProduct = vtkUnstructuredGrid::SafeDownCast(aboveData.Get()); TS_ASSERT_EQUALS(0, aboveProduct->GetNumberOfCells()); TS_ASSERT_EQUALS(10, aboveProduct->GetNumberOfPoints()); @@ -87,7 +91,8 @@ public: //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall below and outside the minimum 1.5 and maximum 2. vtkMDHistoLineFactory below(ThresholdRange_scptr(new UserDefinedThresholdRange(1.5, 2)), Mantid::VATES::VolumeNormalization); below.initialize(ws_sptr); - vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressUpdate)); + auto belowData = below.create(progressUpdate); + auto belowProduct = vtkUnstructuredGrid::SafeDownCast(belowData.Get()); TS_ASSERT_EQUALS(0, belowProduct->GetNumberOfCells()); TS_ASSERT_EQUALS(10, belowProduct->GetNumberOfPoints()); @@ -103,10 +108,9 @@ public: vtkMDHistoLineFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); factory.initialize(ws_sptr); - vtkDataSet* product= factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); - product->Delete(); } void testInitializationDelegates() @@ -115,18 +119,21 @@ public: // 3 dimensions on the workspace Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; - EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + EXPECT_CALL(*pMockFactorySuccessor, initialize(_)) + .Times(1); // expect it then to call initialize on the successor. EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Constructional method ensures that factory is only suitable for providing mesh information. vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)), Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testInitializationDelegatesThrows() @@ -148,26 +155,39 @@ public: // 3 dimensions on the workspace Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; - EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. - EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); //expect it then to call create on the successor. + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + EXPECT_CALL(*pMockFactorySuccessor, initialize(_)) + .Times(1); // expect it then to call initialize on the successor. + EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce( + Return(vtkSmartPointer<vtkStructuredGrid>::New())); // expect it + // then to call + // create on the + // successor. EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Constructional method ensures that factory is only suitable for providing mesh information. - vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),Mantid::VATES::VolumeNormalization); + vtkMDHistoLineFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); + factory.SetSuccessor(std::move(pMockFactorySuccessor)); factory.initialize(ws_sptr); factory.create(progressUpdate); // should be called on successor. - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testTypeName() { - vtkMDHistoLineFactory factory (ThresholdRange_scptr(new UserDefinedThresholdRange(0, 10000)),Mantid::VATES::VolumeNormalization); + vtkMDHistoLineFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 10000), + Mantid::VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDHistoLineFactory", factory.getFactoryTypeName()); } @@ -193,7 +213,9 @@ public: { FakeProgressAction progressUpdate; //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2. - vtkMDHistoLineFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 2)),Mantid::VATES::VolumeNormalization); + vtkMDHistoLineFactory factory( + boost::make_shared<UserDefinedThresholdRange>(0, 2), + Mantid::VATES::VolumeNormalization); factory.initialize(m_ws_sptr); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); } diff --git a/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h b/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h index 95fb9d02c33d36dd5a1b55843c4cd7b67c5cf785..2395223d1bec1af44226c2efcf3b4621e417ae17 100644 --- a/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDHistoQuadFactoryTest.h @@ -2,6 +2,7 @@ #define VTK_MD_QUAD_FACTORY_TEST_H_ #include "MantidAPI/IMDIterator.h" +#include "MantidKernel/make_unique.h" #include "MantidTestHelpers/MDEventsTestHelper.h" #include "MantidVatesAPI/UserDefinedThresholdRange.h" #include "MantidVatesAPI/NoThresholdRange.h" @@ -11,6 +12,7 @@ #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" #include <gmock/gmock.h> #include <gtest/gtest.h> +#include <vtkSmartPointer.h> using namespace Mantid; using namespace Mantid::DataObjects; @@ -37,8 +39,8 @@ public: IMDWorkspace* nullWorkspace = NULL; Mantid::API::IMDWorkspace_sptr ws_sptr(nullWorkspace); - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 100); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); TSM_ASSERT_THROWS("No workspace, so should not be possible to complete initialization.", factory.initialize(ws_sptr), std::invalid_argument); } @@ -47,8 +49,8 @@ public: { FakeProgressAction progressUpdate; - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 100); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 100); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } @@ -59,11 +61,14 @@ public: // WS with 2 dimensions Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 2); - vtkMDHistoQuadFactory inside(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + // Thresholds have been set such that the signal values (hard-coded to 1, + // see above) will fall between the minimum 0 and maximum 2. + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 2); + vtkMDHistoQuadFactory inside(pRange, Mantid::VATES::VolumeNormalization); inside.initialize(ws_sptr); - vtkUnstructuredGrid* insideProduct = dynamic_cast<vtkUnstructuredGrid*>(inside.create(progressUpdate)); + auto product = inside.create(progressUpdate); + auto data = vtkDataSet::SafeDownCast(product.Get()); + vtkSmartPointer<vtkDataSet> insideProduct(data); TS_ASSERT_EQUALS((10*10), insideProduct->GetNumberOfCells()); TS_ASSERT_EQUALS((11*11), insideProduct->GetNumberOfPoints()); @@ -75,11 +80,14 @@ public: // WS with 2 dimensions Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall above and outside the minimum 0 and maximum 0.5. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 0.5); - vtkMDHistoQuadFactory above(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + // Thresholds have been set such that the signal values (hard-coded to 1, + // see above) will fall above and outside the minimum 0 and maximum 0.5. + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 0.5); + vtkMDHistoQuadFactory above(pRange, Mantid::VATES::VolumeNormalization); above.initialize(ws_sptr); - vtkUnstructuredGrid* aboveProduct = dynamic_cast<vtkUnstructuredGrid*>(above.create(progressUpdate)); + auto product = above.create(progressUpdate); + auto data = vtkDataSet::SafeDownCast(product.Get()); + vtkSmartPointer<vtkDataSet> aboveProduct(data); // This changed from previously, in order to ensure that we do not pass on empty // workspaces. A single point is created in the center by the vtkNullUnstructuredGrid @@ -93,12 +101,15 @@ public: // WS with 2 dimensions Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 2); - //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall below and outside the minimum 1.5 and maximum 2. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(1.5, 2); - vtkMDHistoQuadFactory below(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + // Thresholds have been set such that the signal values (hard-coded to 1, + // see above) will fall below and outside the minimum 1.5 and maximum 2. + auto pRange = boost::make_shared<UserDefinedThresholdRange>(1.5, 2); + vtkMDHistoQuadFactory below(pRange, Mantid::VATES::VolumeNormalization); below.initialize(ws_sptr); - vtkUnstructuredGrid* belowProduct = dynamic_cast<vtkUnstructuredGrid*>(below.create(progressUpdate)); + auto product = below.create(progressUpdate); + auto data = vtkUnstructuredGrid::SafeDownCast(product.Get()); + vtkSmartPointer<vtkDataSet> belowProduct(data); // This changed from previously, in order to ensure that we do not pass on empty // workspaces. A single point is created in the center by the vtkNullUnstructuredGrid @@ -112,20 +123,23 @@ public: // WS with 1 dimension Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; - EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()) + .WillOnce(testing::Return("TypeA")); EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. //Constructional method ensures that factory is only suitable for providing mesh information. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange),Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); - + factory.SetSuccessor(std::move(pMockFactorySuccessor)); + factory.initialize(ws_sptr); - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testInitializationDelegatesThrows() @@ -148,29 +162,38 @@ public: // WS with 1 dimension Mantid::API::IMDWorkspace_sptr ws_sptr = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 1); - MockvtkDataSetFactory* pMockFactorySuccessor = new MockvtkDataSetFactory; - EXPECT_CALL(*pMockFactorySuccessor, initialize(_)).Times(1); //expect it then to call initialize on the successor. - EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); //expect it then to call create on the successor. + auto pMockFactorySuccessor = + Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); + EXPECT_CALL(*pMockFactorySuccessor, initialize(_)) + .Times(1); // expect it then to call initialize on the successor. + EXPECT_CALL(*pMockFactorySuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce( + Return(vtkSmartPointer<vtkStructuredGrid>::New())); // expect it + // then to call + // create on the + // successor. EXPECT_CALL(*pMockFactorySuccessor, getFactoryTypeName()).WillOnce(testing::Return("TypeA")); //Constructional method ensures that factory is only suitable for providing mesh information. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); //Successor is provided. - factory.SetSuccessor(pMockFactorySuccessor); - + factory.SetSuccessor(std::move(pMockFactorySuccessor)); + factory.initialize(ws_sptr); factory.create(progressUpdate); // should be called on successor. - TSM_ASSERT("successor factory not used as expected.", Mock::VerifyAndClearExpectations(pMockFactorySuccessor)); + TSM_ASSERT("successor factory not used as expected.", + Mock::VerifyAndClearExpectations(pMockFactorySuccessor.get())); } void testTypeName() { - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDHistoQuadFactory", factory.getFactoryTypeName()); } @@ -184,10 +207,9 @@ public: vtkMDHistoQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); factory.initialize(ws_sptr); - vtkDataSet* product= factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); - product->Delete(); } }; @@ -213,8 +235,8 @@ public: { FakeProgressAction progressUpdate; //Thresholds have been set such that the signal values (hard-coded to 1, see above) will fall between the minimum 0 and maximum 2. - UserDefinedThresholdRange* pRange = new UserDefinedThresholdRange(0, 1); - vtkMDHistoQuadFactory factory(ThresholdRange_scptr(pRange), Mantid::VATES::VolumeNormalization); + auto pRange = boost::make_shared<UserDefinedThresholdRange>(0, 1); + vtkMDHistoQuadFactory factory(pRange, Mantid::VATES::VolumeNormalization); factory.initialize(m_ws_sptr); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); } diff --git a/Vates/VatesAPI/test/vtkMDLineFactoryTest.h b/Vates/VatesAPI/test/vtkMDLineFactoryTest.h index 2974c77e2c797ca6c8593fb9bd5a0c8278780c83..d698163f3544b8189da2e63ceb5d85531b1e9a28 100644 --- a/Vates/VatesAPI/test/vtkMDLineFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDLineFactoryTest.h @@ -2,6 +2,7 @@ #define VTK_MD_LINE_FACTORY_TEST #include <cxxtest/TestSuite.h> +#include "MantidKernel/make_unique.h" #include "MantidDataObjects/TableWorkspace.h" #include "MantidVatesAPI/vtkMDLineFactory.h" #include "MantidVatesAPI/NoThresholdRange.h" @@ -10,6 +11,7 @@ #include "vtkCellType.h" #include "vtkUnstructuredGrid.h" #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include "vtkSmartPointer.h" using namespace Mantid::VATES; using namespace Mantid::API; @@ -25,50 +27,60 @@ public: void testGetFactoryTypeName() { - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDLineFactory", factory.getFactoryTypeName()); } void testInitializeDelegatesToSuccessor() { - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); - ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); + ITableWorkspace_sptr ws = + boost::make_shared<Mantid::DataObjects::TableWorkspace>(); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testCreateDelegatesToSuccessor() { FakeProgressAction progressUpdate; - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); - EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); + EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce(Return(vtkSmartPointer<vtkStructuredGrid>::New())); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testOnInitaliseCannotDelegateToSuccessor() { - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); //factory.SetSuccessor(mockSuccessor); No Successor set. - ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); + ITableWorkspace_sptr ws = + boost::make_shared<Mantid::DataObjects::TableWorkspace>(); TS_ASSERT_THROWS(factory.initialize(ws), std::runtime_error); } @@ -76,7 +88,8 @@ public: { FakeProgressAction progressUpdate; - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); //initialize not called! TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } @@ -101,17 +114,18 @@ public: Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned"); - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); factory.initialize(binned); - vtkDataSet* product = factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); - TS_ASSERT(dynamic_cast<vtkUnstructuredGrid*>(product) != NULL); + TS_ASSERT(dynamic_cast<vtkUnstructuredGrid *>(product.GetPointer()) != + NULL); TS_ASSERT_EQUALS(100, product->GetNumberOfCells()); TS_ASSERT_EQUALS(200, product->GetNumberOfPoints()); TS_ASSERT_EQUALS(VTK_LINE, product->GetCellType(0)); - product->Delete(); AnalysisDataService::Instance().remove("binned"); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); } @@ -151,17 +165,16 @@ public: Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned"); - vtkMDLineFactory factory(ThresholdRange_scptr(new NoThresholdRange),Mantid::VATES::VolumeNormalization); + vtkMDLineFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); factory.initialize(binned); - vtkDataSet* product = factory.create(progressAction); + auto product = factory.create(progressAction); - TS_ASSERT(dynamic_cast<vtkUnstructuredGrid*>(product) != NULL); + TS_ASSERT(dynamic_cast<vtkUnstructuredGrid *>(product.GetPointer()) != + NULL); TS_ASSERT_EQUALS(200000, product->GetNumberOfCells()); - TS_ASSERT_EQUALS(400000, product->GetNumberOfPoints()); - - product->Delete(); - + TS_ASSERT_EQUALS(400000, product->GetNumberOfPoints()); } }; diff --git a/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h b/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h index 75e7e93d70cde146aee182af5339efd6582e0c7c..091ca2c0fa41f1dae5b703cd362891f070259d8d 100644 --- a/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h +++ b/Vates/VatesAPI/test/vtkMDQuadFactoryTest.h @@ -2,6 +2,7 @@ #define VTK_MD_QUAD_FACTORY_TEST #include <cxxtest/TestSuite.h> +#include "MantidKernel/make_unique.h" #include "MantidDataObjects/TableWorkspace.h" #include "MantidVatesAPI/vtkMDQuadFactory.h" #include "MantidVatesAPI/NoThresholdRange.h" @@ -10,6 +11,7 @@ #include "vtkCellType.h" #include "vtkUnstructuredGrid.h" #include "MantidVatesAPI/vtkStructuredGrid_Silent.h" +#include "vtkSmartPointer.h" using namespace Mantid::VATES; using namespace Mantid::API; @@ -26,50 +28,61 @@ public: void testGetFactoryTypeName() { - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); TS_ASSERT_EQUALS("vtkMDQuadFactory", factory.getFactoryTypeName()); } void testInitializeDelegatesToSuccessor() { - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); - ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); + ITableWorkspace_sptr ws = + boost::make_shared<Mantid::DataObjects::TableWorkspace>(); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testCreateDelegatesToSuccessor() { FakeProgressAction progressUpdate; - MockvtkDataSetFactory* mockSuccessor = new MockvtkDataSetFactory; + auto mockSuccessor = Mantid::Kernel::make_unique<MockvtkDataSetFactory>(); EXPECT_CALL(*mockSuccessor, initialize(_)).Times(1); - EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))).Times(1).WillOnce(Return(vtkStructuredGrid::New())); + EXPECT_CALL(*mockSuccessor, create(Ref(progressUpdate))) + .Times(1) + .WillOnce(Return(vtkSmartPointer<vtkStructuredGrid>::New())); EXPECT_CALL(*mockSuccessor, getFactoryTypeName()).Times(1); - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); - factory.SetSuccessor(mockSuccessor); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); + factory.SetSuccessor(std::move(mockSuccessor)); - ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); + ITableWorkspace_sptr ws = + boost::make_shared<Mantid::DataObjects::TableWorkspace>(); TS_ASSERT_THROWS_NOTHING(factory.initialize(ws)); TS_ASSERT_THROWS_NOTHING(factory.create(progressUpdate)); - TSM_ASSERT("Successor has not been used properly.", Mock::VerifyAndClearExpectations(mockSuccessor)); + TSM_ASSERT("Successor has not been used properly.", + Mock::VerifyAndClearExpectations(mockSuccessor.get())); } void testOnInitaliseCannotDelegateToSuccessor() { - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); //factory.SetSuccessor(mockSuccessor); No Successor set. - ITableWorkspace_sptr ws(new Mantid::DataObjects::TableWorkspace); + ITableWorkspace_sptr ws = + boost::make_shared<Mantid::DataObjects::TableWorkspace>(); TS_ASSERT_THROWS(factory.initialize(ws), std::runtime_error); } @@ -77,7 +90,8 @@ public: { FakeProgressAction progressUpdate; - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); //initialize not called! TS_ASSERT_THROWS(factory.create(progressUpdate), std::runtime_error); } @@ -103,18 +117,19 @@ public: Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned"); - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); factory.initialize(binned); - vtkDataSet* product = factory.create(mockProgressAction); + auto product = factory.create(mockProgressAction); - TS_ASSERT(dynamic_cast<vtkUnstructuredGrid*>(product) != NULL); + TS_ASSERT(dynamic_cast<vtkUnstructuredGrid *>(product.GetPointer()) != + NULL); TS_ASSERT_EQUALS(100, product->GetNumberOfCells()); TS_ASSERT_EQUALS(400, product->GetNumberOfPoints()); TS_ASSERT_EQUALS(VTK_QUAD, product->GetCellType(0)); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgressAction)); - product->Delete(); AnalysisDataService::Instance().remove("binned"); } @@ -153,17 +168,16 @@ public: FakeProgressAction progressUpdate; Workspace_sptr binned = Mantid::API::AnalysisDataService::Instance().retrieve("binned"); - vtkMDQuadFactory factory(ThresholdRange_scptr(new NoThresholdRange), Mantid::VATES::VolumeNormalization); + vtkMDQuadFactory factory(boost::make_shared<NoThresholdRange>(), + Mantid::VATES::VolumeNormalization); factory.initialize(binned); - vtkDataSet* product = factory.create(progressUpdate); + auto product = factory.create(progressUpdate); - TS_ASSERT(dynamic_cast<vtkUnstructuredGrid*>(product) != NULL); + TS_ASSERT(dynamic_cast<vtkUnstructuredGrid *>(product.GetPointer()) != + NULL); TS_ASSERT_EQUALS(160000, product->GetNumberOfCells()); - TS_ASSERT_EQUALS(640000, product->GetNumberOfPoints()); - - product->Delete(); - + TS_ASSERT_EQUALS(640000, product->GetNumberOfPoints()); } }; diff --git a/Vates/VatesAPI/test/vtkNullStructuredGridTest.h b/Vates/VatesAPI/test/vtkNullStructuredGridTest.h index 64a31dfec1469d20dff5306a94db7d4f0529d546..a70b5a79d6ac13cc1382de8dd7ffd51cdc15dcea 100644 --- a/Vates/VatesAPI/test/vtkNullStructuredGridTest.h +++ b/Vates/VatesAPI/test/vtkNullStructuredGridTest.h @@ -9,6 +9,7 @@ #include <vtkStructuredGrid.h> #include <vtkPoints.h> +#include <vtkSmartPointer.h> using namespace Mantid::VATES; @@ -17,11 +18,11 @@ public: void testCorrectVtkDataSetIsReturned() { vtkNullStructuredGrid grid; - vtkStructuredGrid *ugrid = NULL; + vtkSmartPointer<vtkStructuredGrid> ugrid; TSM_ASSERT_THROWS_NOTHING( "Should create the unstructured grid without problems.", - ugrid = grid.createNullData()); + ugrid.TakeReference(grid.createNullData())); TSM_ASSERT("Should have exactly one point", ugrid->GetNumberOfPoints() == 1); TSM_ASSERT("Should have exactly one cell", ugrid->GetNumberOfCells() == 1); @@ -30,7 +31,6 @@ public: TSM_ASSERT("X should be in the center", coord[0] == 0.0); TSM_ASSERT("X should be in the center", coord[1] == 0.0); TSM_ASSERT("X should be in the center", coord[2] == 0.0); - ugrid->Delete(); } }; #endif diff --git a/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h b/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h index 90a2caa797d411652125172142f53225b9571179..088ec8b27259ca2dde6292e1d1db9bbe3ec5e684 100644 --- a/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h +++ b/Vates/VatesAPI/test/vtkPeakMarkerFactoryTest.h @@ -7,6 +7,7 @@ #include "MockObjects.h" #include <vtkPolyData.h> +#include <vtkSmartPointer.h> #include <cxxtest/TestSuite.h> #include <gmock/gmock.h> @@ -61,7 +62,8 @@ public: vtkPeakMarkerFactory factory("signal", dims); factory.initialize(pw_ptr); - vtkPolyData * set = factory.create(updateProgress); + auto set = + vtkSmartPointer<vtkPolyData>::Take(factory.create(updateProgress)); // As the marker type are three axes(2 points), we expect 5*2*3 points // The angle is 45degrees and the size is 0.3 @@ -71,7 +73,6 @@ public: TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&pw)); TS_ASSERT(testing::Mock::VerifyAndClearExpectations(&peak1)); - set->Delete(); } void test_progress_updates() @@ -94,8 +95,7 @@ public: vtkPeakMarkerFactory factory("signal", vtkPeakMarkerFactory::Peak_in_Q_lab); factory.initialize(pw_ptr); - vtkPolyData * set = factory.create(mockProgress); - set->Delete(); + auto set = vtkSmartPointer<vtkPolyData>::Take(factory.create(mockProgress)); TSM_ASSERT("Progress Updates not used as expected.", Mock::VerifyAndClearExpectations(&mockProgress)); } diff --git a/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h b/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h index 550f65988cad1aff6ab4a27ae22faea67dbbf407..41dece63c10ee47177cdf0e83b166f067924f374 100644 --- a/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h +++ b/Vates/VatesAPI/test/vtkSplatterPlotFactoryTest.h @@ -18,6 +18,7 @@ #include <gtest/gtest.h> #include <vtkCellData.h> #include <vtkDataArray.h> +#include <vtkSmartPointer.h> using namespace Mantid; using namespace Mantid::VATES; @@ -59,7 +60,7 @@ public: MDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 3, binning); vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal"); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -76,8 +77,6 @@ public: TSM_ASSERT_EQUALS("Should have signal flag", "signal", std::string(product->GetCellData()->GetArray(0)->GetName())); TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize()); TSM_ASSERT_EQUALS("Should have a signal which is normalized to the 3D volume", expected_signal_value, range[0]); - - product->Delete(); } void test_4DHistoWorkspace() @@ -89,7 +88,7 @@ public: IMDHistoWorkspace_sptr ws = MDEventsTestHelper::makeFakeMDHistoWorkspace(1.0, 4, binning); vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal"); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -106,8 +105,6 @@ public: TSM_ASSERT_EQUALS("Should have signal flag", "signal", std::string(product->GetCellData()->GetArray(0)->GetName())); TSM_ASSERT_EQUALS("Should have one signal per bin", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize()); TSM_ASSERT_EQUALS("Should have a signal which is normalized to the 4D volume", expected_signal_value, range[0]); - - product->Delete(); } void test_3DWorkspace() @@ -117,7 +114,7 @@ public: MDEventWorkspace3Lean::sptr ws = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 1); vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal"); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -137,8 +134,6 @@ public: TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells, product->GetNumberOfCells()); TSM_ASSERT_EQUALS("No signal Array", "signal", std::string(product->GetCellData()->GetArray(0)->GetName())); TSM_ASSERT_EQUALS("Wrong sized signal Array", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize()); - - product->Delete(); } void test_4DWorkspace() @@ -148,7 +143,7 @@ public: MDEventWorkspace4Lean::sptr ws = MDEventsTestHelper::makeMDEW<4>(5, -10.0, 10.0, 1); vtkSplatterPlotFactory factory(ThresholdRange_scptr(new UserDefinedThresholdRange(0, 1)), "signal"); factory.initialize(ws); - vtkDataSet* product = NULL; + vtkSmartPointer<vtkDataSet> product; TS_ASSERT_THROWS_NOTHING(product = factory.create(progressUpdate)); @@ -161,8 +156,6 @@ public: TSM_ASSERT_EQUALS("Wrong number of cells", expected_n_cells, product->GetNumberOfCells()); TSM_ASSERT_EQUALS("No signal Array", "signal", std::string(product->GetCellData()->GetArray(0)->GetName())); TSM_ASSERT_EQUALS("Wrong sized signal Array", expected_n_signals, product->GetCellData()->GetArray(0)->GetSize()); - - product->Delete(); } void test_MetadataIsAddedCorrectly() diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp index b7e54f944db15f908213287b56490016c2d38420..daa53311d69200aba9f99d2b08db01b1fd5ee088 100644 --- a/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp +++ b/Vates/VatesSimpleGui/ViewWidgets/src/RebinnedSourcesManager.cpp @@ -497,11 +497,10 @@ namespace Mantid dest->Copy(source, "vtkSMProxyProperty"); // handle proxy properties. - vtkSMPropertyIterator* destIter = dest->NewPropertyIterator(); - for (destIter->Begin(); !destIter->IsAtEnd(); destIter->Next()) - { - if (vtkSMInputProperty::SafeDownCast(destIter->GetProperty())) - { + auto destIter = vtkSmartPointer<vtkSMPropertyIterator>::Take( + dest->NewPropertyIterator()); + for (destIter->Begin(); !destIter->IsAtEnd(); destIter->Next()) { + if (vtkSMInputProperty::SafeDownCast(destIter->GetProperty())) { // skip input properties. continue; } @@ -554,7 +553,6 @@ namespace Mantid } } - destIter->Delete(); dest->UpdateVTKObjects(); END_UNDO_SET(); } diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp index 05f5c76ed5729da8ab53f48ec25e3ed5b8bc0e5b..0af06e51c0bfd0028da9ada20e7853bc57fe1281 100644 --- a/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp +++ b/Vates/VatesSimpleGui/ViewWidgets/src/SaveScreenshotReaction.cpp @@ -120,10 +120,9 @@ void SaveScreenshotReaction::saveScreenshot() colorPalette->GetXMLName())); clone->Copy(colorPalette); - vtkSMProxy *chosenPalette = pxm->NewProxy("palettes", - palette.toLatin1().data()); + auto chosenPalette = vtkSmartPointer<vtkSMProxy>::Take( + pxm->NewProxy("palettes", palette.toLatin1().data())); colorPalette->Copy(chosenPalette); - chosenPalette->Delete(); } int stereo = ssDialog.getStereoMode(); diff --git a/docs/source/algorithms/CalculateChiSquared-v1.rst b/docs/source/algorithms/CalculateChiSquared-v1.rst index 09ed39f9e11693adff30cc350d25c32f65cf750e..922343f84c3d269504815376d5d5460c94f316bc 100644 --- a/docs/source/algorithms/CalculateChiSquared-v1.rst +++ b/docs/source/algorithms/CalculateChiSquared-v1.rst @@ -80,24 +80,28 @@ Usage func = 'name=LinearBackground,A0=1.1,A1=1.9' # Calculate the chi squared - chi2,chi2dof,chi2W,chi2Wdof = CalculateChiSquared(func,ws) + chi2,chi2dof,chi2ndata,chi2W,chi2Wdof,chi2Wndata = CalculateChiSquared(func,ws) print 'Chi squared is %s' % chi2 print 'Chi squared / DOF is %s' % chi2dof + print 'Chi squared / NDATA is %s' % chi2ndata print 'Chi squared weighted is %s' % chi2W print 'Chi squared weighted / DOF is %s' % chi2Wdof - print + print 'Chi squared weighted / NDATA is %s' % chi2Wndata + print # Define a function that models the data exactly func = 'name=LinearBackground,A0=1.0,A1=2.0' # Calculate the chi squared - chi2,chi2dof,chi2W,chi2Wdof = CalculateChiSquared(func,ws) + chi2,chi2dof,chi2ndata,chi2W,chi2Wdof,chi2Wndata = CalculateChiSquared(func,ws) print 'Chi squared is %s' % chi2 print 'Chi squared / DOF is %s' % chi2dof + print 'Chi squared / NDATA is %s' % chi2ndata print 'Chi squared weighted is %s' % chi2W print 'Chi squared weighted / DOF is %s' % chi2Wdof + print 'Chi squared weighted / NDATA is %s' % chi2Wndata Output: @@ -105,18 +109,22 @@ Output: Chi squared is 0.0351851851852 Chi squared / DOF is 0.00439814814815 + Chi squared / NDATA is 0.00351851851852 Chi squared weighted is 0.0266028783977 Chi squared weighted / DOF is 0.00332535979971 + Chi squared weighted / NDATA is 0.00266028783977 Chi squared is 0.0 Chi squared / DOF is 0.0 + Chi squared / NDATA is 0.0 Chi squared weighted is 0.0 Chi squared weighted / DOF is 0.0 - + Chi squared weighted / NDATA is 0.0 + **Example 2** .. testcode:: - + import numpy as np # Create a workspace and fill it with some gaussian data and some noise n = 100 @@ -125,7 +133,7 @@ Output: e = [1] * n ws = CreateWorkspace(x,y,e) - # Gefine a Gaussian with exactly the same parameters that were used to + # Gefine a Gaussian with exactly the same parameters that were used to # generate the data fun_t = 'name=Gaussian,Height=%s,PeakCentre=%s,Sigma=%s' fun = fun_t % (1, 0, 1) @@ -143,9 +151,8 @@ Output: # Test the chi squared. CalculateChiSquared(fun,ws,Output='Test1') # Check the Test1_errors table and see that the parameters are at minimum now - - + + .. categories:: .. sourcelink:: - diff --git a/docs/source/algorithms/EVSDiffractionReduction-v1.rst b/docs/source/algorithms/EVSDiffractionReduction-v1.rst index dc0d7280562ed5a1347a8dbe09b21ef2c3e6cc9d..0bc9887e90ca755b8b28ad3633bd95c982b06cda 100644 --- a/docs/source/algorithms/EVSDiffractionReduction-v1.rst +++ b/docs/source/algorithms/EVSDiffractionReduction-v1.rst @@ -14,6 +14,12 @@ A version of :ref:`ISISIndirectDiffractionReduction data, the reduction is performed in the same way however there is the additional option to load a PAR file. +Workflow +-------- + +.. diagram:: EVSDiffractionReduction-v1_wkflw.dot + + Usage ----- diff --git a/docs/source/algorithms/EnggCalibrate-v1.rst b/docs/source/algorithms/EnggCalibrate-v1.rst index c4627c82b1b22c5eb9bc069f3cf969a03a5316e3..a9ec18f688593b9f8c3aab14c640be96502d9e25 100644 --- a/docs/source/algorithms/EnggCalibrate-v1.rst +++ b/docs/source/algorithms/EnggCalibrate-v1.rst @@ -106,9 +106,9 @@ Output: .. testoutput:: ExampleCalib - Difc1: 18400.71 - Zero1: -3.17 + Difc1: 18400.19 + Zero1: -2.06 The output table has 1 row(s) - Parameters from the table, Difc1: 18400.71, Zero1: -3.17 + Parameters from the table, Difc1: 18400.19, Zero1: -2.06 Output GSAS iparam file was written? True Number of lines of the GSAS iparam file: 35 diff --git a/docs/source/algorithms/IndirectFlatPlateAbsorption-v1.rst b/docs/source/algorithms/IndirectFlatPlateAbsorption-v1.rst index 69ff254aa4f4335945a43e75e31879c2e9d2ba51..a5195e6168a3ebf06bca855b90395b44d8590fe5 100644 --- a/docs/source/algorithms/IndirectFlatPlateAbsorption-v1.rst +++ b/docs/source/algorithms/IndirectFlatPlateAbsorption-v1.rst @@ -17,6 +17,12 @@ The correction factor workspace is a workspace group containing the correction factors in the Paalman and Pings format, note that only :math:`{A_{s,s}}` and :math:`A_{c,c}` factors are calculated by thsi algorithm. +Workflow +-------- + +.. diagram:: IndirectFlatPlateAbsorption-v1_wkflw.dot + + Usage ----- diff --git a/docs/source/algorithms/LoadEventNexus-v1.rst b/docs/source/algorithms/LoadEventNexus-v1.rst index df478f2857e59748cabda76545a5e320f16e825c..659192340dbb995c7eadf75fb2eb6c519b717ddb 100644 --- a/docs/source/algorithms/LoadEventNexus-v1.rst +++ b/docs/source/algorithms/LoadEventNexus-v1.rst @@ -1,4 +1,4 @@ -.. algorithm:: +.. algorithm:: .. summary:: @@ -50,6 +50,18 @@ Veto pulses can be filtered out in a separate step using ``FilterByLogValue(InputWorkspace="ws", OutputWorkspace="ws", LogName="veto_pulse_time", PulseFilter="1")`` +Data Loaded from Nexus File +########################### + +The nexus file must have ``/raw_data_1`` or ``/entry`` as its main group and +that group be of type ``NXentry``. It also needs a group of type ``NXevent_data``. + +The data is read from each group of type ``NXevent_data``. + +If the file has an ``isis_vms_compat`` then it is taken to be an ISIS file and +the data will be modified according to the information obtained from this group. + + Usage ----- diff --git a/docs/source/algorithms/LoadISISNexus-v2.rst b/docs/source/algorithms/LoadISISNexus-v2.rst index 8edce491dba00f9be23c9a7e8ecfe0d956e97699..05a5551d3e67a9c9a4394f5e1e92c9d25f4ecb5e 100644 --- a/docs/source/algorithms/LoadISISNexus-v2.rst +++ b/docs/source/algorithms/LoadISISNexus-v2.rst @@ -11,6 +11,18 @@ Description Loads a Nexus file created from an ISIS instrument. +Data loaded from Nexus File +########################### + +The nexus file must have ``/raw_data_1`` as its main group and +contain a ``/isis_vms_compat`` group to be loaded. + +The workspace data is loaded from ``/raw_data_1/Detector_1``. +Instrument information is loaded ``/raw_data_1/Instrument``, if available there and not overriden. +Also the ``NSP1``, ``UDET``, ``SPEC``, ``HDR``, ``IRPB``, ``RRPB``, ``SPB`` and ``RSPB`` sections of +``/raw_data_1/isis_vms_compat`` are read. + + Usage ----- diff --git a/docs/source/algorithms/SofQW-v1.rst b/docs/source/algorithms/SofQW-v1.rst index d782c732c02a2411261a80b187c9c65c8f219323..883e430151ea929aaff131b7c3393ac9f0e67719 100644 --- a/docs/source/algorithms/SofQW-v1.rst +++ b/docs/source/algorithms/SofQW-v1.rst @@ -10,7 +10,7 @@ Description ----------- This algorithm is for use by inelastic instruments and takes as its -input a workspace where the data's been reduced to be in `units <http://www.mantidproject.org/Units>`_ +input a workspace where the data's been reduced to be in `units <http://www.mantidproject.org/Units>`_ of **energy transfer** against spectrum number (which can be seen as equivalent to angle, with the angle being taken from the detector(s) to which the spectrum pertains). @@ -26,11 +26,15 @@ workspace should already have the desired bins (though this axis can be rebinned afterwards if desired). The EMode and EFixed parameters are used for the calculation of :math:`Q`. - If the input workspace is a distribution (i.e. **counts/meV** ) then the output workspace will similarly be divided by the bin width in both directions (i.e. will contain **counts/meV/(1/Angstrom)** ). +Workflow +######## + +.. diagram:: SofQW-v1_wkflw.dot + Usage ----- @@ -40,31 +44,31 @@ Usage # create sample inelastic workspace for MARI instrument containing 1 at all spectra values ws=CreateSimulationWorkspace(Instrument='MAR',BinParams='-10,1,10') - # convert workspace into MD workspace + # convert workspace into MD workspace ws=SofQW(InputWorkspace=ws,QAxisBinning='-3,0.1,3',Emode='Direct',EFixed=12) - + print "The converted X values are:" print ws.readX(59)[0:10] - print ws.readX(59)[10:21] - + print ws.readX(59)[10:21] + print "The converted Y values are:" print ws.readY(59)[0:10] - print ws.readY(59)[10:21] + print ws.readY(59)[10:21] .. testcleanup:: SofQW DeleteWorkspace(ws) - + **Output:** .. testoutput:: SofQW - The converted X values are: + The converted X values are: [-10. -9. -8. -7. -6. -5. -4. -3. -2. -1.] - [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] - The converted Y values are: + [ 0. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.] + The converted Y values are: [ 12. 18. 18. 18. 18. 21. 18. 18. 21. 12.] [ 18. 21. 24. 24. 24. 21. 24. 33. 39. 45.] diff --git a/docs/source/diagrams/EVSDiffractionReduction-v1_wkflw.dot b/docs/source/diagrams/EVSDiffractionReduction-v1_wkflw.dot new file mode 100644 index 0000000000000000000000000000000000000000..3b94a129c30339c2d4f10ff3dbb941a4f4643be9 --- /dev/null +++ b/docs/source/diagrams/EVSDiffractionReduction-v1_wkflw.dot @@ -0,0 +1,56 @@ +digraph EVSDiffractionReduction { + label="EVSDiffractionReduction Flowchart" + $global_style + + subgraph process { + $process_style + ScaleMonitor [label="Scale data and detectors by monitor intensities"] + } + + subgraph params { + $param_style + InputFiles + InstrumentParFile + DataWorkspaces + MonitorWorkspaces + MonitorWorkspace + SumFiles + SpectraRange + RebinParam + GroupingPolicy + OutputWorkspace + } + + subgraph algorithms { + $algorithm_style + LoadFiles + Rebin + GroupWorkspaces + ConvertUnits + GroupSpectra + } + + subgraph decisions { + $decision_style + allProcessed [label="Processed all workspaces?"] + } + + InputFiles -> LoadFiles + SpectraRange -> LoadFiles + SumFiles -> LoadFiles + InstrumentParFile -> LoadFiles + LoadFiles -> DataWorkspaces + LoadFiles -> MonitorWorkspaces + MonitorWorkspaces -> MonitorWorkspace [label="Select next monitor workspace to process"] + MonitorWorkspace -> ScaleMonitor + ScaleMonitor -> DataWorkspaces + DataWorkspaces -> ConvertUnits [label="ConvertTo dSpacing"] + ConvertUnits -> Rebin + RebinParam -> Rebin + Rebin -> GroupSpectra + GroupingPolicy -> GroupSpectra + GroupSpectra -> allProcessed + allProcessed -> ScaleMonitor [label="No: repeat process with next monitor"] + allProcessed -> GroupWorkspaces [label="Yes: Group all processed workspaces"] + GroupWorkspaces -> OutputWorkspace +} diff --git a/docs/source/diagrams/IndirectFlatPlateAbsorption-v1_wkflw.dot b/docs/source/diagrams/IndirectFlatPlateAbsorption-v1_wkflw.dot new file mode 100644 index 0000000000000000000000000000000000000000..97d95cf8fece2fb71a56500eb583ce6114625d40 --- /dev/null +++ b/docs/source/diagrams/IndirectFlatPlateAbsorption-v1_wkflw.dot @@ -0,0 +1,110 @@ +digraph IndirectFlatePlateAbsorption { + label="IndirectFlatePlateAbsorption Flowchart" + $global_style + + subgraph params { + $param_style + SampleWorkspace1 [label="SampleWorkspace"] + SampleWorkspace2 [label="SampleWorkspace"] + SampleWorkspace_Wave + SampleWorkspace_Wave2 [label="SampleWorkspace_Wave"] + SampleWorkspace_Wave3 [label="SampleWorkspace_Wave"] + SampleChemicalFormula + SampleNumberDensity + SampleHeight1 [label="SampleHeight"] + SampleWidth1 [label="SampleWidth"] + SampleThickness + AbsWorkspace1 [label="AbsorptionWorkspace"] + AbsWorkspace2 [label="AbsorptionWorkspace"] + CanWorkspace + CanWorkspace_Wave + CanScale + CanChemicalFormula + CanNumberDensity + CanFrontThickness + CanBackThickness + CanScale + ElementSize1 [label="ElementSize"] + SampleLogs + EFixed1 [label="eFixed"] + EFixed2 [label="eFixed"] + OutputWorkspace + } + + subgraph algorithms { + $algorithm_style + GetEFixed + ConvertUnits1 [label="ConvertUnits"] + ConvertUnits2 [label="ConvertUnits"] + ConvertUnits3 [label="ConvertUnits"] + SetSampleMaterial1 [label="SetSampleMaterial"] + SetSampleMaterial2 [label="SetSampleMaterial"] + FlatPlateAbsorption1 [label="FlatePlatAbsorption"] + FlatPlateAbsorption2 [label="FlatePlatAbsorption"] + Scale + Divide1 [label="Divide"] + Divide2 [label="Divide"] + Divide3 [label="Divide"] + Minus1 [label="Minus"] + Minus2 [label="Minus"] + AddSampleLogMultiple + GroupWorkspaces + } + + subgraph decisions { + $decision_style + canGiven [label="Can Workspace?"] + canScale [label="Can Scale?"] + useCorrections [label="Can Corrections?"] + } + + SampleWorkspace1 -> GetEFixed + GetEFixed -> EFixed1 + EFixed1 -> ConvertUnits1 + SampleWorkspace1 -> ConvertUnits1 + ConvertUnits1 -> SampleWorkspace_Wave [label="Convert input workspace into Wavelength"] + SampleWorkspace_Wave -> SetSampleMaterial1 + SampleChemicalFormula -> SetSampleMaterial1 + SampleNumberDensity -> SetSampleMaterial1 + SetSampleMaterial1 -> FlatPlateAbsorption1 + SampleHeight1 -> FlatPlateAbsorption1 + SampleWidth1 -> FlatPlateAbsorption1 + SampleThickness -> FlatPlateAbsorption1 + ElementSize1 -> FlatPlateAbsorption1 + EFixed1 -> FlatPlateAbsorption1 + FlatPlateAbsorption1 -> AbsWorkspace1 + AbsWorkspace1 -> canGiven + canGiven -> CanWorkspace [label="Yes"] + CanWorkspace -> ConvertUnits2 + EFixed2 -> ConvertUnits2 + ConvertUnits2 -> CanWorkspace_Wave [label="Convert can workspace into Wavelength"] + CanWorkspace_Wave -> canScale + canScale -> Scale [label="Not equal to 1"] + CanScale -> Scale + Scale -> useCorrections + canScale -> useCorrections [label="Equal to 1"] + useCorrections -> SetSampleMaterial2 [label="Yes"] + CanChemicalFormula -> SetSampleMaterial2 + CanNumberDensity -> SetSampleMaterial2 + SetSampleMaterial2 -> FlatPlateAbsorption2 + CanFrontThickness -> FlatPlateAbsorption2 + CanBackThickness -> FlatPlateAbsorption2 + FlatPlateAbsorption2 -> Divide1 + SetSampleMaterial2 -> Divide1 + Divide1 -> Minus1 + SampleWorkspace2 -> Minus1 + useCorrections -> Minus2 [label="No"] + SampleWorkspace2 -> Minus2 + Minus2 -> Divide2 + AbsWorkspace2 -> Divide2 + canGiven -> Divide3 [label="No"] + SampleWorkspace_Wave3 -> Divide3 + Minus1 -> SampleWorkspace_Wave2 + Divide2 -> SampleWorkspace_Wave2 + Divide3 -> SampleWorkspace_Wave2 + SampleWorkspace_Wave2 -> ConvertUnits3 [label="Convert back to DeltaE"] + ConvertUnits3 -> AddSampleLogMultiple + SampleLogs -> AddSampleLogMultiple + AddSampleLogMultiple -> GroupWorkspaces + GroupWorkspaces -> OutputWorkspace +} diff --git a/docs/source/diagrams/SofQW-v1_wkflw.dot b/docs/source/diagrams/SofQW-v1_wkflw.dot new file mode 100644 index 0000000000000000000000000000000000000000..bca7a548d8cf1b7b5041afb9b08c82ca157a73e5 --- /dev/null +++ b/docs/source/diagrams/SofQW-v1_wkflw.dot @@ -0,0 +1,32 @@ +digraph { + $global_style + + subgraph params { + $param_style + Method + InputWorkspace + QAxisBinning + EMode + EFixed + } + + subgraph algorithms { + $algorithm_style + SofQW + SofQWCentre + SofQWPolygon + SofQWNormalisedPolygon + } + + Method -> SofQW + + InputWorkspace -> SofQW + QAxisBinning -> SofQW + EMode -> SofQW + EFixed -> SofQW + + SofQW -> SofQWCentre [label="Method=Centre"] + SofQW -> SofQWPolygon [label="Method=Polygon"] + SofQW -> SofQWNormalisedPolygon [label="Method=NormalisedPolygon"] + +} diff --git a/scripts/SANS/isis_reducer.py b/scripts/SANS/isis_reducer.py index ea848550a1331b41d2723989448780a9df7ca012..baacbd68961ef775b2298cbe376ae5e8970d83c1 100644 --- a/scripts/SANS/isis_reducer.py +++ b/scripts/SANS/isis_reducer.py @@ -1,4 +1,4 @@ -#pylint: disable=invalid-name +#pylint: disable=invalid-name """ ISIS-specific implementation of the SANS Reducer. @@ -101,12 +101,6 @@ class Can(Sample): super(Can, self).set_run(run, reload, period, reducer) - # currently, no slices will be applied to Can #8535 - for period in reversed(range(self.loader.periods_in_file)): - self.loader.move2ws(period) - name = self.loader.wksp_name - if su.isEventWorkspace(name): - su.fromEvent2Histogram(mtd[name], self.get_monitor()) class ISISReducer(Reducer): """ diff --git a/scripts/SANS/isis_reduction_steps.py b/scripts/SANS/isis_reduction_steps.py index f5ec10c7e792bdb56d2c7f3995fcee29be428827..0fc36d5f89c760c9c26790a77762809a5b19d615 100644 --- a/scripts/SANS/isis_reduction_steps.py +++ b/scripts/SANS/isis_reduction_steps.py @@ -2385,7 +2385,15 @@ class SliceEvent(ReductionStep): if not isinstance(ws_pointer, IEventWorkspace): self.scale = 1 return - start, stop = reducer.getCurrSliceLimit() + + # If a sample data set is converted then we want to be able to slice + # If a can data set is being converted, the slice limits should not be applied + # but rather the full data set should be used. -1 is the no limit signal + if not reducer.is_can(): + start, stop = reducer.getCurrSliceLimit() + else: + start = -1 + stop = -1 _monitor = reducer.get_sample().get_monitor()