diff --git a/Framework/API/inc/MantidAPI/WorkspaceGroup.h b/Framework/API/inc/MantidAPI/WorkspaceGroup.h index 235df0520541ab78122eee0e36ea65165192ac52..c4ef3930b6dd03f414250a3e27291eb8220abdc1 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceGroup.h +++ b/Framework/API/inc/MantidAPI/WorkspaceGroup.h @@ -131,19 +131,22 @@ private: void observeADSNotifications(const bool observeADS); /// Check if a workspace is included in any child groups and groups in them. bool isInChildGroup(const Workspace &workspaceToCheck) const; + /// Callback when a delete notification is received void workspaceDeleteHandle( Mantid::API::WorkspacePostDeleteNotification_ptr notice); - /// Observer for workspace delete notfications - Poco::NObserver<WorkspaceGroup, Mantid::API::WorkspacePostDeleteNotification> - m_deleteObserver; + /// Callback when a before-replace notification is received - void workspaceReplaceHandle( + void workspaceBeforeReplaceHandle( Mantid::API::WorkspaceBeforeReplaceNotification_ptr notice); - /// Observer for workspace before-replace notfications + + /// Observer for workspace delete notifications + Poco::NObserver<WorkspaceGroup, Mantid::API::WorkspacePostDeleteNotification> + m_deleteObserver; + /// Observer for workspace before-replace notifications Poco::NObserver<WorkspaceGroup, Mantid::API::WorkspaceBeforeReplaceNotification> - m_replaceObserver; + m_beforeReplaceObserver; /// The list of workspace pointers in the group std::vector<Workspace_sptr> m_workspaces; /// Flag as to whether the observers have been added to the ADS diff --git a/Framework/API/src/WorkspaceGroup.cpp b/Framework/API/src/WorkspaceGroup.cpp index cddf9eb04d5153309c450c17bf0073c7915185d0..cf5e9a08a39e170196caeecdd650cec5b301371d 100644 --- a/Framework/API/src/WorkspaceGroup.cpp +++ b/Framework/API/src/WorkspaceGroup.cpp @@ -17,7 +17,8 @@ Kernel::Logger g_log("WorkspaceGroup"); WorkspaceGroup::WorkspaceGroup() : Workspace(), m_deleteObserver(*this, &WorkspaceGroup::workspaceDeleteHandle), - m_replaceObserver(*this, &WorkspaceGroup::workspaceReplaceHandle), + m_beforeReplaceObserver(*this, + &WorkspaceGroup::workspaceBeforeReplaceHandle), m_workspaces(), m_observingADS(false) {} WorkspaceGroup::~WorkspaceGroup() { observeADSNotifications(false); } @@ -52,7 +53,7 @@ void WorkspaceGroup::observeADSNotifications(const bool observeADS) { AnalysisDataService::Instance().notificationCenter.addObserver( m_deleteObserver); AnalysisDataService::Instance().notificationCenter.addObserver( - m_replaceObserver); + m_beforeReplaceObserver); m_observingADS = true; } } else { @@ -60,7 +61,7 @@ void WorkspaceGroup::observeADSNotifications(const bool observeADS) { AnalysisDataService::Instance().notificationCenter.removeObserver( m_deleteObserver); AnalysisDataService::Instance().notificationCenter.removeObserver( - m_replaceObserver); + m_beforeReplaceObserver); m_observingADS = false; } } @@ -180,7 +181,7 @@ Workspace_sptr WorkspaceGroup::getItem(const size_t index) const { /** * Return the workspace by name * @param wsName The name of the workspace - * @throws an out_of_range error if the workspace'sname not contained in the + * @throws an out_of_range error if the workspace's name not contained in the * group's list of workspace names */ Workspace_sptr WorkspaceGroup::getItem(const std::string wsName) const { @@ -249,7 +250,7 @@ void WorkspaceGroup::removeItem(const size_t index) { * * Removes any deleted entries from the group. * This also deletes the workspace group when the last member of it gets - *deteleted. + * deleted. * * @param notice :: A pointer to a workspace delete notificiation object */ @@ -276,21 +277,42 @@ void WorkspaceGroup::workspaceDeleteHandle( } /** - * Callback when a after-replace notification is received - * Replaces a member if it was replaced in the ADS. - * @param notice :: A pointer to a workspace after-replace notificiation object + * Callback when a before-replace notification is received + * Replaces a member if it was replaced in the ADS and checks + * for duplicate members within the group + * @param notice :: A pointer to a workspace before-replace notification object */ -void WorkspaceGroup::workspaceReplaceHandle( +void WorkspaceGroup::workspaceBeforeReplaceHandle( Mantid::API::WorkspaceBeforeReplaceNotification_ptr notice) { std::lock_guard<std::recursive_mutex> _lock(m_mutex); - const std::string replacedName = notice->objectName(); - for (auto &workspace : m_workspaces) { - if ((*workspace).name() == replacedName) { - workspace = notice->newObject(); + const auto oldObject = notice->oldObject(); + const auto newObject = notice->newObject(); + + bool foundOld(false); + bool foundDuplicate(false); + + auto duplicateIter = m_workspaces.end(); + + for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { + auto &workspace = *it; + if (workspace == oldObject) { + workspace = newObject; + foundOld = true; + + } else if (workspace == newObject) { + duplicateIter = it; + foundDuplicate = true; + } + + if (foundOld && foundDuplicate) { break; } } + + if (foundOld && duplicateIter != m_workspaces.end()) { + m_workspaces.erase(duplicateIter); + } } /** diff --git a/Framework/Algorithms/inc/MantidAlgorithms/BinaryOperation.h b/Framework/Algorithms/inc/MantidAlgorithms/BinaryOperation.h index 347d6b8841bb88a90008fe401460dfefb2ae94a3..e05d58cc4bf837a887d56a034ae4fe1e4bedcb84 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/BinaryOperation.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/BinaryOperation.h @@ -1,9 +1,6 @@ #ifndef MANTID_ALGORITHMS_BINARYOPERATION_H_ #define MANTID_ALGORITHMS_BINARYOPERATION_H_ -//---------------------------------------------------------------------- -// Includes -//---------------------------------------------------------------------- #include "MantidAPI/Algorithm.h" #include "MantidAPI/Run.h" #include "MantidAPI/Workspace_fwd.h" @@ -285,12 +282,6 @@ private: void propagateBinMasks(const API::MatrixWorkspace_const_sptr rhs, API::MatrixWorkspace_sptr out); - /// Apply masking requested by propagateSpectraMasks. - void applyMaskingToOutput(API::MatrixWorkspace_sptr out); - - /// A store for accumulated spectra that should be masked in the output - /// workspace - std::vector<int64_t> m_indicesToMask; /// Progress reporting API::Progress *m_progress; }; diff --git a/Framework/Algorithms/inc/MantidAlgorithms/CalculateFlatBackground.h b/Framework/Algorithms/inc/MantidAlgorithms/CalculateFlatBackground.h index de26795826f5ba8a983aa82d99c5791f42dde788..05b92cb4f01005d2e5edb2313049468e7f746d32 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/CalculateFlatBackground.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/CalculateFlatBackground.h @@ -8,28 +8,29 @@ namespace Mantid { namespace Algorithms { -/** Finds a constant value fit to an appropriate range of each desired spectrum - and subtracts that value from the entire spectrum. +/** Finds a constant background value of each desired spectrum + and optionally subtracts that value from the entire spectrum. Required Properties: <UL> - <LI> InputWorkspace - The name of the input workspace. </LI> - <LI> OutputWorkspace - The name to give the output workspace. </LI> - <LI> SpectrumIndexList - The workspace indices of the spectra to fit + <LI> InputWorkspace - The name of the input workspace. </LI> + <LI> OutputWorkspace - The name to give the output workspace. </LI> + <LI> SpectrumIndexList - The workspace indices of the spectra to fit background to. </LI> - <LI> StartX - The start of the flat region to fit to. </LI> - <LI> EndX - The end of the flat region to fit to. </LI> - <LI> Mode - How to estimate the background number of counts: a - linear fit or the mean. </LI> - <LI> OutputMode - What to return in the Outputworkspace: the + <LI> StartX - The start of the flat region to fit to. </LI> + <LI> EndX - The end of the flat region to fit to. </LI> + <LI> AveragingWindowWidth - The width (in bins) of the moving window. </LI> + <LI> Mode - How to estimate the background number of + counts: a linear fit, the mean, or moving window average. </LI> + <LI> OutputMode - What to return in the Outputworkspace: the corrected signal or just the background. </LI> </UL> @author Russell Taylor, Tessella plc @date 5/02/2009 - Copyright © 2009 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge - National Laboratory & European Spallation Source + Copyright © 2009-2016 ISIS Rutherford Appleton Laboratory, NScD Oak + Ridge National Laboratory & European Spallation Source This file is part of Mantid. @@ -65,8 +66,8 @@ public: const std::string name() const override { return "CalculateFlatBackground"; } /// Summary of algorithms purpose const std::string summary() const override { - return "Finds a constant value fit to an appropriate range of each desired " - "spectrum and subtracts that value from the entire spectrum."; + return "Finds a constant background value of each desired spectrum and " + "optionally subtracts that value from the entire spectrum."; } /// Algorithm's version @@ -86,10 +87,12 @@ private: void restoreDistributionState(API::MatrixWorkspace_sptr workspace); void checkRange(double &startX, double &endX); void getWsInds(std::vector<int> &output, const int workspaceTotal); - double Mean(const API::MatrixWorkspace_const_sptr WS, const int wsInd, - const double startX, const double endX, double &variance) const; + double Mean(const API::MatrixWorkspace_sptr WS, const int wsInd, + const double startX, const double endX) const; double LinearFit(API::MatrixWorkspace_sptr WS, int spectrum, double startX, double endX); + double movingAverage(API::MatrixWorkspace_const_sptr WS, int wsIndex, + size_t windowWidth) const; /// variable bin width raw count data must be converted to distributions first /// and then converted back, keep track of this diff --git a/Framework/Algorithms/inc/MantidAlgorithms/NormaliseByDetector.h b/Framework/Algorithms/inc/MantidAlgorithms/NormaliseByDetector.h index fe2e3ce1050ac9acaf8a25eb52f2cc4d3268ada0..dd2fc222a2863173f37d4b1092fdab515c428f2a 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/NormaliseByDetector.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/NormaliseByDetector.h @@ -1,10 +1,10 @@ #ifndef MANTID_ALGORITHMS_NORMALISEBYDETECTOR_H_ #define MANTID_ALGORITHMS_NORMALISEBYDETECTOR_H_ -#include "MantidKernel/System.h" #include "MantidAPI/Algorithm.h" -#include "MantidGeometry/Instrument/FitParameter.h" #include "MantidGeometry/Instrument/Detector.h" +#include "MantidGeometry/Instrument/FitParameter.h" +#include "MantidKernel/System.h" #include <boost/shared_ptr.hpp> namespace Mantid { @@ -71,8 +71,8 @@ private: /// Process indivdual histogram. void processHistogram( size_t wsIndex, - boost::shared_ptr<Mantid::API::MatrixWorkspace> denominatorWS, boost::shared_ptr<const Mantid::API::MatrixWorkspace> inWS, + boost::shared_ptr<Mantid::API::MatrixWorkspace> denominatorWS, Mantid::API::Progress &prog); void init() override; @@ -82,4 +82,4 @@ private: } // namespace Algorithms } // namespace Mantid -#endif /* MANTID_ALGORITHMS_NORMALISEBYDETECTOR_H_ */ \ No newline at end of file +#endif /* MANTID_ALGORITHMS_NORMALISEBYDETECTOR_H_ */ diff --git a/Framework/Algorithms/inc/MantidAlgorithms/NormaliseToMonitor.h b/Framework/Algorithms/inc/MantidAlgorithms/NormaliseToMonitor.h index 59d786c2f1241c79d9e7f0fff8e7246ef2102d0a..f2db237673529f3326a6e2ba98e1fb1818343be5 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/NormaliseToMonitor.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/NormaliseToMonitor.h @@ -8,6 +8,14 @@ #include "MantidKernel/cow_ptr.h" #include "MantidKernel/IPropertyManager.h" +namespace Mantid { +namespace HistogramData { +class BinEdges; +class CountStandardDeviations; +class Counts; +} +} + namespace Mantid { namespace Algorithms { /** Normalizes a 2D workspace by a specified monitor spectrum. By default ,the @@ -111,8 +119,9 @@ protected: // for testing void normaliseBinByBin(const API::MatrixWorkspace_sptr &inputWorkspace, API::MatrixWorkspace_sptr &outputWorkspace); - void normalisationFactor(const MantidVec &X, MantidVec *Y, MantidVec *E); - // + void normalisationFactor(const HistogramData::BinEdges &X, + HistogramData::Counts &Y, + HistogramData::CountStandardDeviations &E); private: /// A single spectrum workspace containing the monitor diff --git a/Framework/Algorithms/inc/MantidAlgorithms/PDFFourierTransform.h b/Framework/Algorithms/inc/MantidAlgorithms/PDFFourierTransform.h index fc2a9027d09151bf0e87e66cf58d185f6df272f6..fb7dd244241e88c5266cc3baadc5e7b73e918463 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/PDFFourierTransform.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/PDFFourierTransform.h @@ -3,6 +3,7 @@ #include "MantidKernel/System.h" #include "MantidAPI/Algorithm.h" +#include "MantidAPI/WorkspaceUnitValidator.h" namespace Mantid { namespace Algorithms { diff --git a/Framework/Algorithms/inc/MantidAlgorithms/Q1D2.h b/Framework/Algorithms/inc/MantidAlgorithms/Q1D2.h index d145399d3b2d64ab687520d2f5139a5698b85ac4..06e40f7c178e16d8bc324137eb5b1e5b589c24fc 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/Q1D2.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/Q1D2.h @@ -2,6 +2,7 @@ #define MANTID_ALGORITHMS_Q1D2_H_ #include "MantidAPI/Algorithm.h" +#include "MantidHistogramData/Histogram.h" #include "MantidKernel/cow_ptr.h" namespace Mantid { @@ -67,30 +68,39 @@ private: API::MatrixWorkspace_sptr setUpOutputWorkspace(const std::vector<double> &binParams) const; // these are the steps that are run on each individual spectrum - void calculateNormalization(const size_t wavStart, const size_t wsIndex, - API::MatrixWorkspace_const_sptr pixelAdj, - API::MatrixWorkspace_const_sptr wavePixelAdj, - double const *const binNorms, - double const *const binNormEs, - const MantidVec::iterator norm, - const MantidVec::iterator normETo2) const; + void + calculateNormalization(const size_t wavStart, const size_t wsIndex, + API::MatrixWorkspace_const_sptr pixelAdj, + API::MatrixWorkspace_const_sptr wavePixelAdj, + double const *const binNorms, + double const *const binNormEs, + HistogramData::HistogramY::iterator norm, + HistogramData::HistogramY::iterator normETo2) const; void pixelWeight(API::MatrixWorkspace_const_sptr pixelAdj, const size_t wsIndex, double &weight, double &error) const; - void addWaveAdj(const double *c, const double *Dc, MantidVec::iterator bInOut, - MantidVec::iterator e2InOut) const; - void addWaveAdj(const double *c, const double *Dc, MantidVec::iterator bInOut, - MantidVec::iterator e2InOut, MantidVec::const_iterator, - MantidVec::const_iterator) const; + void addWaveAdj(const double *c, const double *Dc, + HistogramData::HistogramY::iterator bInOut, + HistogramData::HistogramY::iterator e2InOut) const; + void + addWaveAdj(const double *c, const double *Dc, + HistogramData::HistogramY::iterator bInOut, + HistogramData::HistogramY::iterator e2InOut, + HistogramData::HistogramY::const_iterator wavePixelAdjData, + HistogramData::HistogramE::const_iterator wavePixelAdjError) const; void normToMask(const size_t offSet, const size_t wsIndex, - const MantidVec::iterator theNorms, - const MantidVec::iterator errorSquared) const; + const HistogramData::HistogramY::iterator theNorms, + const HistogramData::HistogramY::iterator errorSquared) const; void convertWavetoQ(const API::SpectrumInfo &spectrumInfo, const size_t wsInd, const bool doGravity, const size_t offset, - MantidVec::iterator Qs, const double extraLength) const; - void getQBinPlus1(const MantidVec &OutQs, const double QToFind, - MantidVec::const_iterator &loc) const; - void normalize(const MantidVec &normSum, const MantidVec &normError2, - MantidVec &counts, MantidVec &errors) const; + HistogramData::HistogramY::iterator Qs, + const double extraLength) const; + void getQBinPlus1(const HistogramData::HistogramX &OutQs, + const double QToFind, + HistogramData::HistogramY::const_iterator &loc) const; + void normalize(const HistogramData::HistogramY &normSum, + const HistogramData::HistogramE &normError2, + HistogramData::HistogramY &counts, + HistogramData::HistogramE &errors) const; }; } // namespace Algorithms diff --git a/Framework/Algorithms/inc/MantidAlgorithms/Rebin2D.h b/Framework/Algorithms/inc/MantidAlgorithms/Rebin2D.h index 44bb0353b74f5c689c4454cd6208734fc02b2bfd..a9996e1f4c5621c04413a16ab1f90293ca6a9352 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/Rebin2D.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/Rebin2D.h @@ -9,7 +9,6 @@ #include "MantidDataObjects/RebinnedOutput.h" namespace Mantid { - namespace Algorithms { /** @@ -62,10 +61,9 @@ private: /// Run the algorithm void exec() override; /// Setup the output workspace - API::MatrixWorkspace_sptr - createOutputWorkspace(API::MatrixWorkspace_const_sptr parent, - MantidVec &newXBins, MantidVec &newYBins, - const bool useFractionalArea) const; + API::MatrixWorkspace_sptr createOutputWorkspace( + API::MatrixWorkspace_const_sptr parent, HistogramData::BinEdges &newXBins, + HistogramData::BinEdges &newYBins, const bool useFractionalArea) const; }; } // namespace Algorithms diff --git a/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h b/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h index 7e1e2f68f3ea946b3c25c9a0cd36ad4232dea25e..0a0c6854d40826e5b7cd823d1b79b7a9510333ee 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/ReflectometryReductionOne.h @@ -76,11 +76,6 @@ private: correctPosition(API::MatrixWorkspace_sptr &toCorrect, const double &thetaInDeg, const bool isPointDetector); - /// Sum spectra. - Mantid::API::MatrixWorkspace_sptr - sumSpectraOverRange(API::MatrixWorkspace_sptr inWS, const int startIndex, - const int endIndex); - /// Perform a transmission correction on the input IvsLam workspace API::MatrixWorkspace_sptr transmissonCorrection( API::MatrixWorkspace_sptr IvsLam, const MinMax &wavelengthInterval, diff --git a/Framework/Algorithms/inc/MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h b/Framework/Algorithms/inc/MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h index 5e11f3bc18582837925f17c3a4bcc080892b6b65..39c0e121a256f1f1ff2f1a4520754f293e1fe6de 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h @@ -23,6 +23,7 @@ Code Documentation is available at: <http://doxygen.mantidproject.org> */ #include "MantidKernel/System.h" +#include "MantidHistogramData/Histogram.h" #include <memory> #include <utility> #include <vector> @@ -61,15 +62,15 @@ public: /// Constructor MayersSampleCorrectionStrategy( MayersSampleCorrectionStrategy::Parameters params, - const std::vector<double> &tof, const std::vector<double> &sigIn, - const std::vector<double> &errIn); + const Mantid::HistogramData::Histogram &inputHist); /// Destructor - defined in cpp file to use forward declaration with /// unique_ptr ~MayersSampleCorrectionStrategy(); /// Return the correction factors - void apply(std::vector<double> &sigOut, std::vector<double> &errOut); - /// Calculate the self-attentation factor for a single mu*r value + Mantid::HistogramData::Histogram getCorrectedHisto(); + + /// Calculate the self-attenuation factor for a single mu*r value double calculateSelfAttenuation(const double muR); /// Calculate the multiple scattering factor for a single mu*r value & /// absorption value @@ -84,19 +85,15 @@ private: double muR(const double flightPath, const double tof) const; double muR(const double sigt) const; double sigmaTotal(const double flightPath, const double tof) const; - double tof(const size_t i) const; void seedRNG(const size_t seed); /// A copy of the correction parameters const Parameters m_pars; - /// A reference to the tof vluaes - const std::vector<double> &m_tof; - /// A reference to the input signal values - const std::vector<double> &m_sigin; - /// A reference to the input error values - const std::vector<double> &m_errin; - // True if we have binned TOF values - const bool m_histogram; + // Holds histogram to process + const HistogramData::Histogram &m_histogram; + const HistogramData::Points m_tofVals; + /// Holds the number of Y vals to process + const size_t m_histoYSize; /// Limits for the range of mu*r values to cover const std::pair<double, double> m_muRrange; /// Random number generator diff --git a/Framework/Algorithms/inc/MantidAlgorithms/SpectrumAlgorithm.h b/Framework/Algorithms/inc/MantidAlgorithms/SpectrumAlgorithm.h index 1827259f0d7232f40c5dab8a01346916fdb7a133..4b8ebfaa3b7c018a25a1d618fc941c1a602884db 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/SpectrumAlgorithm.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/SpectrumAlgorithm.h @@ -88,7 +88,7 @@ private: auto size = static_cast<int64_t>(indexSet.size()); API::Progress progress(this, 0.0, 1.0, size); - PARALLEL_FOR1((&workspace)) + PARALLEL_FOR_IF(Kernel::threadSafe(workspace)) for (int64_t i = 0; i < size; ++i) { PARALLEL_START_INTERUPT_REGION // Note the small but for now negligible overhead from the IndexSet access diff --git a/Framework/Algorithms/inc/MantidAlgorithms/UnwrapMonitor.h b/Framework/Algorithms/inc/MantidAlgorithms/UnwrapMonitor.h index ed2f79bd338875d5ed89ea34c4cd1acb37ee2fd5..c28cdd07658cb4de0142cdfa7317d958b45a5821 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/UnwrapMonitor.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/UnwrapMonitor.h @@ -3,6 +3,7 @@ #include "MantidAPI/Algorithm.h" #include "MantidKernel/cow_ptr.h" +#include "MantidHistogramData/HistogramX.h" namespace Mantid { namespace Algorithms { @@ -69,13 +70,14 @@ private: void init() override; void exec() override; - const std::vector<int> unwrapX(const API::MatrixWorkspace_sptr &tempWS, - const int &spectrum, const double &Ld); - std::pair<int, int> handleFrameOverlapped(const MantidVec &xdata, - const double &Ld, - std::vector<double> &tempX); + const std::vector<int> unwrapX(MantidVec &newX, const int &spectrum, + const double &Ld); + std::pair<int, int> + handleFrameOverlapped(const Mantid::HistogramData::HistogramX &xdata, + const double &Ld, std::vector<double> &tempX); void unwrapYandE(const API::MatrixWorkspace_sptr &tempWS, const int &spectrum, - const std::vector<int> &rangeBounds); + const std::vector<int> &rangeBounds, MantidVec &newY, + MantidVec &newE); API::MatrixWorkspace_sptr rebin(const API::MatrixWorkspace_sptr &workspace, const double &min, const double &max, const int &numBins); diff --git a/Framework/Algorithms/inc/MantidAlgorithms/UnwrapSNS.h b/Framework/Algorithms/inc/MantidAlgorithms/UnwrapSNS.h index 87bc30f3435ec94519415b05d2cdc6b77f9b124f..cbfc39c88c6770efed6d594be5ccec43d0366e40 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/UnwrapSNS.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/UnwrapSNS.h @@ -68,7 +68,8 @@ private: void execEvent(); void runMaskDetectors(); - int unwrapX(const MantidVec &, MantidVec &, const double &Ld); + int unwrapX(const Mantid::HistogramData::HistogramX &, MantidVec &, + const double &Ld); void getTofRangeData(const bool); double m_conversionConstant; ///< The constant used in the conversion from TOF /// to wavelength diff --git a/Framework/Algorithms/inc/MantidAlgorithms/WienerSmooth.h b/Framework/Algorithms/inc/MantidAlgorithms/WienerSmooth.h index 1b2f0d64abe532152c12d786da5af99f9384beba..6390c452d1e153f46c1e664dbfd1eca76b597914 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/WienerSmooth.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/WienerSmooth.h @@ -3,6 +3,7 @@ #include "MantidAPI/Algorithm.h" #include "MantidKernel/cow_ptr.h" +#include "MantidHistogramData/HistogramX.h" namespace Mantid { namespace Algorithms { @@ -43,8 +44,9 @@ private: void init() override; void exec() override; - std::pair<double, double> getStartEnd(const MantidVec &X, - bool isHistogram) const; + std::pair<double, double> + getStartEnd(const Mantid::HistogramData::HistogramX &X, + bool isHistogram) const; API::MatrixWorkspace_sptr copyInput(API::MatrixWorkspace_sptr inputWS, size_t wsIndex); API::MatrixWorkspace_sptr @@ -54,4 +56,4 @@ private: } // namespace Algorithms } // namespace Mantid -#endif /* MANTID_ALGORITHMS_WIENERSMOOTH_H_ */ \ No newline at end of file +#endif /* MANTID_ALGORITHMS_WIENERSMOOTH_H_ */ diff --git a/Framework/Algorithms/src/AlignDetectors.cpp b/Framework/Algorithms/src/AlignDetectors.cpp index 8d553002cf40c209660d5fae826ec1bad5f1df4b..799abab078eb4b6d4b3a9255ebfbb503059294b3 100644 --- a/Framework/Algorithms/src/AlignDetectors.cpp +++ b/Framework/Algorithms/src/AlignDetectors.cpp @@ -326,7 +326,7 @@ void AlignDetectors::exec() { void AlignDetectors::align(const ConversionFactors &converter, Progress &progress, MatrixWorkspace &outputWS) { - PARALLEL_FOR1((&outputWS)) + PARALLEL_FOR_IF(Kernel::threadSafe(outputWS)) for (int64_t i = 0; i < m_numberOfSpectra; ++i) { PARALLEL_START_INTERUPT_REGION try { diff --git a/Framework/Algorithms/src/BinaryOperation.cpp b/Framework/Algorithms/src/BinaryOperation.cpp index f4d7e154399e4dad36eee09d8a627728440420a6..03bab20ddfdbfd7002d491ddeb45a1cd1c11ed3c 100644 --- a/Framework/Algorithms/src/BinaryOperation.cpp +++ b/Framework/Algorithms/src/BinaryOperation.cpp @@ -26,8 +26,7 @@ BinaryOperation::BinaryOperation() m_AllowDifferentNumberSpectra(false), m_ClearRHSWorkspace(false), m_matchXSize(false), m_flipSides(false), m_keepEventWorkspace(false), m_useHistogramForRhsEventWorkspace(false), - m_do2D_even_for_SingleColumn_on_rhs(false), m_indicesToMask(), - m_progress(nullptr) {} + m_do2D_even_for_SingleColumn_on_rhs(false), m_progress(nullptr) {} BinaryOperation::~BinaryOperation() { if (m_progress) @@ -72,7 +71,6 @@ void BinaryOperation::init() { "will be empty."); } -//-------------------------------------------------------------------------------------------- /** Special handling for 1-WS and 1/WS. * * @return true if the operation was handled; exec() should then return @@ -145,7 +143,6 @@ bool BinaryOperation::handleSpecialDivideMinus() { return false; } -//-------------------------------------------------------------------------------------------- /** Executes the algorithm. Will call execEvent() if appropriate. * * @throw runtime_error Thrown if algorithm cannot execute @@ -277,27 +274,22 @@ void BinaryOperation::exec() { // Single column on rhs; if the RHS is an event workspace with one bin, it is // treated as a scalar. else if ((m_rhs->blocksize() == 1) && !m_do2D_even_for_SingleColumn_on_rhs) { - m_indicesToMask.reserve(m_out->getNumberHistograms()); doSingleColumn(); } else // The two are both 2D and should be the same size (except if LHS is an // event workspace) { - m_indicesToMask.reserve(m_out->getNumberHistograms()); - bool mismatchedSpectra = (m_AllowDifferentNumberSpectra && (m_rhs->getNumberHistograms() != m_lhs->getNumberHistograms())); do2D(mismatchedSpectra); } - applyMaskingToOutput(m_out); setOutputUnits(m_lhs, m_rhs, m_out); // Assign the result to the output workspace property setProperty(outputPropName(), m_out); } -//-------------------------------------------------------------------------------------------- /** * Execute a binary operation on events. Should be overridden. * @param lhs :: left-hand event workspace @@ -312,7 +304,6 @@ void BinaryOperation::execEvent(DataObjects::EventWorkspace_const_sptr lhs, "BinaryOperation::execEvent() is not implemented for this operation."); } -//-------------------------------------------------------------------------------------------- /** * Return true if the two workspaces are compatible for this operation * Virtual: will be overridden as needed. @@ -352,7 +343,6 @@ bool BinaryOperation::checkCompatibility( return true; } -//-------------------------------------------------------------------------------------------- /** Return true if the two workspaces can be treated as event workspaces * for the binary operation. If so, execEvent() will be called. * (e.g. Plus algorithm will concatenate event lists) @@ -368,7 +358,6 @@ bool BinaryOperation::checkEventCompatibility( return false; } -//-------------------------------------------------------------------------------------------- /** Performs a simple check to see if the sizes of two workspaces are compatible * for a binary operation * In order to be size compatible then the larger workspace @@ -439,7 +428,6 @@ std::string BinaryOperation::checkSizeCompatibility( } } -//-------------------------------------------------------------------------------------------- /** * Checks if the spectra at the given index of either input workspace is masked. * If so then the output spectra has zeroed data @@ -492,7 +480,7 @@ void BinaryOperation::doSingleValue() { if (m_eout) { // ---- The output is an EventWorkspace ------ - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_out->setX(i, m_lhs->refX(i)); @@ -503,7 +491,7 @@ void BinaryOperation::doSingleValue() { PARALLEL_CHECK_INTERUPT_REGION } else { // ---- Histogram Output ----- - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_out->setX(i, m_lhs->refX(i)); @@ -522,7 +510,6 @@ void BinaryOperation::doSingleValue() { } } -//-------------------------------------------------------------------------------------------- /** Called when the m_rhs operand is a 2D workspace of single values. * Loops over the workspaces calling the abstract binary operation function * with a single number as the m_rhs operand. @@ -537,7 +524,7 @@ void BinaryOperation::doSingleColumn() { const int64_t numHists = m_lhs->getNumberHistograms(); if (m_eout) { // ---- The output is an EventWorkspace ------ - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION const double rhsY = m_rhs->readY(i)[0]; @@ -553,7 +540,7 @@ void BinaryOperation::doSingleColumn() { PARALLEL_CHECK_INTERUPT_REGION } else { // ---- Histogram Output ----- - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION const double rhsY = m_rhs->readY(i)[0]; @@ -577,7 +564,6 @@ void BinaryOperation::doSingleColumn() { } } -//-------------------------------------------------------------------------------------------- /** Called when the m_rhs operand is a single spectrum. * Loops over the lhs workspace calling the abstract binary operation function. */ @@ -599,7 +585,7 @@ void BinaryOperation::doSingleSpectrum() { // Now loop over the spectra of the left hand side calling the virtual // function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION // m_out->setX(i,m_lhs->refX(i)); //unnecessary - that was copied @@ -622,7 +608,7 @@ void BinaryOperation::doSingleSpectrum() { // function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION // m_out->setX(i,m_lhs->refX(i)); //unnecessary - that was copied @@ -648,7 +634,7 @@ void BinaryOperation::doSingleSpectrum() { // function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_out->setX(i, m_lhs->refX(i)); @@ -667,7 +653,6 @@ void BinaryOperation::doSingleSpectrum() { } } -//-------------------------------------------------------------------------------------------- /** Called when the two workspaces are the same size. * Loops over the workspaces extracting the appropriate spectra and calling the *abstract binary operation function. @@ -693,7 +678,7 @@ void BinaryOperation::do2D(bool mismatchedSpectra) { // ------------ The rhs is ALSO an EventWorkspace --------------- // Now loop over the spectra of each one calling the virtual function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_progress->report(this->name()); @@ -726,7 +711,7 @@ void BinaryOperation::do2D(bool mismatchedSpectra) { // Now loop over the spectra of each one calling the virtual function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_progress->report(this->name()); @@ -763,7 +748,7 @@ void BinaryOperation::do2D(bool mismatchedSpectra) { // Now loop over the spectra of each one calling the virtual function const int64_t numHists = m_lhs->getNumberHistograms(); - PARALLEL_FOR3(m_lhs, m_rhs, m_out) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_lhs, *m_rhs, *m_out)) for (int64_t i = 0; i < numHists; ++i) { PARALLEL_START_INTERUPT_REGION m_progress->report(this->name()); @@ -827,39 +812,6 @@ void BinaryOperation::propagateBinMasks( } } -//--------------------------------------------------------------------------------------------- -/** - * Apply the requested masking to the output workspace - * @param out :: The workspace to mask - */ -void BinaryOperation::applyMaskingToOutput(API::MatrixWorkspace_sptr out) { - int64_t nindices = static_cast<int64_t>(m_indicesToMask.size()); - ParameterMap &pmap = out->instrumentParameters(); - PARALLEL_FOR1(out) - for (int64_t i = 0; i < nindices; ++i) { - if (!m_parallelException && !m_cancel) { - try { - IDetector_const_sptr det_out = out->getDetector(m_indicesToMask[i]); - PARALLEL_CRITICAL(BinaryOperation_masking) { - pmap.addBool(det_out.get(), "masked", true); - } - } /* End of try block in PARALLEL_START_INTERUPT_REGION */ - catch (Kernel::Exception::NotFoundError) { // detector not found, do - // nothing, go further - } catch (std::runtime_error &ex) { - if (!m_parallelException) { - m_parallelException = true; - g_log.error() << this->name() << ": " << ex.what() << "\n"; - } - } catch (...) { - m_parallelException = true; - } - - } // End of if block in PARALLEL_START_INTERUPT_REGION - } - PARALLEL_CHECK_INTERUPT_REGION -} - // ------- Default implementations of Event binary operations -------- /** @@ -917,7 +869,6 @@ void BinaryOperation::performEventBinaryOperation(DataObjects::EventList &lhs, "BinaryOperation::performEventBinaryOperation() not implemented."); } -//--------------------------------------------------------------------------------------------- /** * Get the type of operand from a workspace * @param ws :: workspace to check @@ -942,7 +893,6 @@ BinaryOperation::getOperandType(const API::MatrixWorkspace_const_sptr ws) { return eHistogram; } -//--------------------------------------------------------------------------------------------- /** Check what operation will be needed in order to apply the operation * to these two types of workspaces. This function must be overridden * and checked against all 9 possible combinations. @@ -965,7 +915,6 @@ void BinaryOperation::checkRequirements() { m_useHistogramForRhsEventWorkspace = false; } -//--------------------------------------------------------------------------------------------- /** Build up an BinaryOperationTable for performing a binary operation * e.g. lhs = (lhs + rhs) * where the spectra in rhs are to go into lhs. diff --git a/Framework/Algorithms/src/CalculateFlatBackground.cpp b/Framework/Algorithms/src/CalculateFlatBackground.cpp index c1a8da2d66452254eec85ca3c077894bab9a7997..8e7d06c8edb29f49d50ebbeac2820663fbdfd371 100644 --- a/Framework/Algorithms/src/CalculateFlatBackground.cpp +++ b/Framework/Algorithms/src/CalculateFlatBackground.cpp @@ -8,6 +8,7 @@ #include "MantidDataObjects/TableWorkspace.h" #include "MantidGeometry/IDetector.h" #include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/EnabledWhenProperty.h" #include "MantidKernel/ListValidator.h" #include "MantidKernel/MandatoryValidator.h" #include "MantidKernel/VectorHelper.h" @@ -26,6 +27,8 @@ DECLARE_ALGORITHM(CalculateFlatBackground) using namespace Kernel; using namespace API; +enum class Modes { LINEAR_FIT, MEAN, MOVING_AVERAGE }; + void CalculateFlatBackground::init() { declareProperty( make_unique<WorkspaceProperty<>>( @@ -38,22 +41,28 @@ void CalculateFlatBackground::init() { declareProperty(make_unique<WorkspaceProperty<>>("OutputWorkspace", "", Direction::Output), "Name to use for the output workspace."); - auto mustHaveValue = boost::make_shared<MandatoryValidator<double>>(); - - declareProperty("StartX", Mantid::EMPTY_DBL(), mustHaveValue, - "The X value at which to start the background fit"); - declareProperty("EndX", Mantid::EMPTY_DBL(), mustHaveValue, - "The X value at which to end the background fit"); + declareProperty("StartX", Mantid::EMPTY_DBL(), + "The X value at which to start the background fit. Mandatory " + "for the Linear Fit and Mean modes, ignored by Moving " + "Average."); + setPropertySettings("StartX", make_unique<EnabledWhenProperty>( + "Mode", IS_NOT_EQUAL_TO, "Moving Average")); + declareProperty("EndX", Mantid::EMPTY_DBL(), + "The X value at which to end the background fit. Mandatory " + "for the Linear Fit and Mean modes, ignored by Moving " + "Average."); + setPropertySettings("EndX", make_unique<EnabledWhenProperty>( + "Mode", IS_NOT_EQUAL_TO, "Moving Average")); declareProperty( make_unique<ArrayProperty<int>>("WorkspaceIndexList"), "Indices of the spectra that will have their background removed\n" "default: modify all spectra"); - std::vector<std::string> modeOptions{"Linear Fit", "Mean"}; + std::vector<std::string> modeOptions{"Linear Fit", "Mean", "Moving Average"}; declareProperty("Mode", "Linear Fit", boost::make_shared<StringListValidator>(modeOptions), "The background count rate is estimated either by taking a " - "mean or doing a\n" - "linear fit (default: Linear Fit)"); + "mean, doing a linear fit, or taking the\n" + "minimum of a moving average (default: Linear Fit)"); // Property to determine whether we subtract the background or just return the // background. std::vector<std::string> outputOptions{"Subtract Background", @@ -78,6 +87,12 @@ void CalculateFlatBackground::init() { "is added to the error. If false, the signal and errors are " "left unchanged", Direction::Input); + declareProperty("AveragingWindowWidth", Mantid::EMPTY_INT(), + "The width of the moving average window in bins. Mandatory " + "for the Moving Average mode."); + setPropertySettings( + "AveragingWindowWidth", + make_unique<EnabledWhenProperty>("Mode", IS_EQUAL_TO, "Moving Average")); } void CalculateFlatBackground::exec() { @@ -93,13 +108,46 @@ void CalculateFlatBackground::exec() { m_skipMonitors = getProperty("SkipMonitors"); m_nullifyNegative = getProperty("NullifyNegativeValues"); - // Get the required X range + std::string modeString = getProperty("Mode"); + Modes mode = Modes::LINEAR_FIT; + if (modeString == "Mean") { + mode = Modes::MEAN; + } else if (modeString == "Moving Average") { + mode = Modes::MOVING_AVERAGE; + } double startX, endX; - this->checkRange(startX, endX); + int windowWidth = 0; + switch (mode) { + case Modes::LINEAR_FIT: + case Modes::MEAN: + if (getPointerToProperty("StartX")->isDefault()) { + throw std::runtime_error("StartX property not set to any value"); + } + if (getPointerToProperty("EndX")->isDefault()) { + throw std::runtime_error("EndX property not set to any value"); + } + // Get the required X range + checkRange(startX, endX); + break; + case Modes::MOVING_AVERAGE: + if (getPointerToProperty("AveragingWindowWidth")->isDefault()) { + throw std::runtime_error( + "AveragingWindowWidth property not set to any value"); + } + windowWidth = getProperty("AveragingWindowWidth"); + if (windowWidth <= 0) { + throw std::runtime_error("AveragingWindowWidth zero or negative"); + } + if (blocksize < windowWidth) { + throw std::runtime_error("AveragingWindowWidth is larger than the number " + "of bins in InputWorkspace"); + } + break; + } std::vector<int> wsInds = getProperty("WorkspaceIndexList"); // check if the user passed an empty list, if so all of spec will be processed - this->getWsInds(wsInds, numHists); + getWsInds(wsInds, numHists); // Are we removing the background? const bool removeBackground = @@ -153,15 +201,19 @@ void CalculateFlatBackground::exec() { } } - // Only if Mean() is called will variance be changed - double variance = -1; - // Now call the function the user selected to calculate the background - const double background = - std::string(getProperty("mode")) == "Mean" - ? this->Mean(outputWS, currentSpec, startX, endX, variance) - : this->LinearFit(outputWS, currentSpec, startX, endX); - + double background = -1; + switch (mode) { + case Modes::LINEAR_FIT: + background = LinearFit(outputWS, currentSpec, startX, endX); + break; + case Modes::MEAN: + background = Mean(outputWS, currentSpec, startX, endX); + break; + case Modes::MOVING_AVERAGE: + background = movingAverage(outputWS, currentSpec, windowWidth); + break; + } if (background < 0) { g_log.warning() << "Problem with calculating the background number of " "counts spectrum with index " << currentSpec @@ -173,17 +225,9 @@ void CalculateFlatBackground::exec() { backgroundTotal += background; } - auto &E = outputWS->mutableE(currentSpec); - // only the Mean() function calculates the variance - // cppcheck-suppress knownConditionTrueFalse - if (variance > 0) { - // adjust the errors using the variance (variance = error^2) - std::transform( - E.begin(), E.end(), E.begin(), - std::bind2nd(VectorHelper::AddVariance<double>(), variance)); - } // Get references to the current spectrum auto &Y = outputWS->mutableY(currentSpec); + auto &E = outputWS->mutableE(currentSpec); // Now subtract the background from the data for (int j = 0; j < blocksize; ++j) { if (removeBackground) { @@ -316,29 +360,25 @@ void CalculateFlatBackground::getWsInds(std::vector<int> &output, } } /** Gets the mean number of counts in each bin the background region and the -* variance (error^2) of that -* number +* variance (error^2) of that number. Adjusts the y errors accordingly. * @param WS :: points to the input workspace * @param wsInd :: index of the spectrum to process * @param startX :: a X-value in the first bin that will be considered, must not * be greater endX * @param endX :: a X-value in the last bin that will be considered, must not * less than startX -* @param variance :: will be set to the number of counts divided by the number -* of bins squared (= error^2) * @return the mean number of counts in each bin the background region * @throw out_of_range if either startX or endX are out of the range of X-values * in the specified spectrum * @throw invalid_argument if endX has the value of first X-value one of the * spectra */ -double CalculateFlatBackground::Mean(const API::MatrixWorkspace_const_sptr WS, +double CalculateFlatBackground::Mean(const API::MatrixWorkspace_sptr WS, const int wsInd, const double startX, - const double endX, - double &variance) const { + const double endX) const { auto &XS = WS->x(wsInd); auto &YS = WS->y(wsInd); - auto &ES = WS->e(wsInd); + auto &ES = WS->mutableE(wsInd); // the function checkRange should already have checked that startX <= endX, // but we still need to check values weren't out side the ranges if (endX > XS.back() || startX < XS.front()) { @@ -379,9 +419,13 @@ double CalculateFlatBackground::Mean(const API::MatrixWorkspace_const_sptr WS, // is taken as the sqrt the total number counts. To get the the error on the // counts in each bin just divide this by the number of bins. The variance = // error^2 that is the total variance divide by the number of bins _squared_. - variance = std::accumulate(ES.begin() + startInd, ES.begin() + endInd + 1, - 0.0, VectorHelper::SumSquares<double>()) / - (numBins * numBins); + const double variance = + std::accumulate(ES.begin() + startInd, ES.begin() + endInd + 1, 0.0, + VectorHelper::SumSquares<double>()) / + (numBins * numBins); + // adjust the errors using the variance (variance = error^2) + std::transform(ES.begin(), ES.end(), ES.begin(), + std::bind2nd(VectorHelper::AddVariance<double>(), variance)); // return mean number of counts in each bin, the sum of the number of counts // in all the bins divided by the number of bins used in that sum return background; @@ -443,5 +487,39 @@ double CalculateFlatBackground::LinearFit(API::MatrixWorkspace_sptr WS, return slope * centre + intercept; } +/** +* Utilizes cyclic boundary conditions when calculating the +* average in the window. +* @param WS The workspace to operate on +* @param wsIndex The workspace index to operate on +* @param windowWidth Width of the averaging window in bins +* @return Minimum +*/ +double +CalculateFlatBackground::movingAverage(API::MatrixWorkspace_const_sptr WS, + int wsIndex, size_t windowWidth) const { + const auto &ys = WS->y(wsIndex); + double currentMin = std::numeric_limits<double>::max(); + + // Initialize sum. + double sum = 0; + for (size_t i = 0; i < windowWidth; ++i) { + sum += ys[i]; + } + // When moving the window, we need to subtract the single point "falling off" + // while adding a new point. Saves us summing all the points in the window. + for (size_t i = 0; i < ys.size() - 1; ++i) { + currentMin = std::min(currentMin, sum / static_cast<double>(windowWidth)); + size_t j = i + windowWidth; + // Cyclic boundary conditions. + if (j >= ys.size()) { + j -= ys.size(); + } + sum += ys[j] - ys[i]; + } + currentMin = std::min(currentMin, sum / static_cast<double>(windowWidth)); + return currentMin; +} + } // namespace Algorithms } // namespace Mantid diff --git a/Framework/Algorithms/src/ConvertUnits.cpp b/Framework/Algorithms/src/ConvertUnits.cpp index 83d1698a0677d1b2f98945274b296b5fc5235ff8..4b5c0d8a7495473358c79fbd1794e48f9957aaa5 100644 --- a/Framework/Algorithms/src/ConvertUnits.cpp +++ b/Framework/Algorithms/src/ConvertUnits.cpp @@ -813,18 +813,18 @@ API::MatrixWorkspace_sptr ConvertUnits::removeUnphysicalBins( auto edges = workspace->binEdges(j); auto k = lastBins[j]; - result->mutableX(j).assign(edges.cbegin(), edges.cbegin() + k); + auto &X = result->mutableX(j); + std::copy(edges.cbegin(), edges.cbegin() + k, X.begin()); // If the entire X range is not covered, generate fake values. if (k < maxBins) { - std::iota(result->mutableX(j).begin() + k, result->mutableX(j).end(), - workspace->x(j)[k] + 1); + std::iota(X.begin() + k, X.end(), workspace->x(j)[k] + 1); } - result->mutableY(j) - .assign(workspace->y(j).cbegin(), workspace->y(j).cbegin() + (k - 1)); - result->mutableE(j) - .assign(workspace->e(j).cbegin(), workspace->e(j).cbegin() + (k - 1)); + std::copy(workspace->y(j).cbegin(), workspace->y(j).cbegin() + (k - 1), + result->mutableY(j).begin()); + std::copy(workspace->e(j).cbegin(), workspace->e(j).cbegin() + (k - 1), + result->mutableE(j).begin()); } } diff --git a/Framework/Algorithms/src/DetectorDiagnostic.cpp b/Framework/Algorithms/src/DetectorDiagnostic.cpp index 4c57f308791efde2811296ec9b4cd7d7de9a0791..dbb315c6bfb33b7ac14cbbbe97676f9e383caabb 100644 --- a/Framework/Algorithms/src/DetectorDiagnostic.cpp +++ b/Framework/Algorithms/src/DetectorDiagnostic.cpp @@ -621,7 +621,7 @@ std::vector<double> DetectorDiagnostic::calculateMedian( (instrument->getSample() != nullptr)); } - PARALLEL_FOR1((&input)) + PARALLEL_FOR_IF(Kernel::threadSafe(input)) for (int i = 0; i < nhists; ++i) { // NOLINT PARALLEL_START_INTERUPT_REGION diff --git a/Framework/Algorithms/src/DetectorEfficiencyCorUser.cpp b/Framework/Algorithms/src/DetectorEfficiencyCorUser.cpp index 6e63ff725907a90dee7db76ab03d66233c37abfb..233b55d116e72f7d79eb214c67f0657234b6a168 100644 --- a/Framework/Algorithms/src/DetectorEfficiencyCorUser.cpp +++ b/Framework/Algorithms/src/DetectorEfficiencyCorUser.cpp @@ -161,8 +161,6 @@ MantidVec DetectorEfficiencyCorUser::calculateEfficiency( p.SetExpr(formula); for (size_t i = 0; i < effOut.size(); ++i) { - // Cppcheck cannot see that e is accessed in p.Eval(). - // cppcheck-suppress unreadVariable e = m_Ei - xIn[i]; double eff = p.Eval(); effOut[i] = eff / eff0; diff --git a/Framework/Algorithms/src/DetectorEfficiencyVariation.cpp b/Framework/Algorithms/src/DetectorEfficiencyVariation.cpp index 101c657e0bb916de257aa2096c09fa5d80ca9192..dc2214496a3546402fbab56d3d8aedfe8500b80b 100644 --- a/Framework/Algorithms/src/DetectorEfficiencyVariation.cpp +++ b/Framework/Algorithms/src/DetectorEfficiencyVariation.cpp @@ -210,7 +210,7 @@ int DetectorEfficiencyVariation::doDetectorTests( const double deadValue(1.0); int numFailed(0); const auto &spectrumInfo = counts1->spectrumInfo(); - PARALLEL_FOR3(counts1, counts2, maskWS) + PARALLEL_FOR_IF(Kernel::threadSafe(*counts1, *counts2, *maskWS)) for (int i = 0; i < numSpec; ++i) { PARALLEL_START_INTERUPT_REGION // move progress bar diff --git a/Framework/Algorithms/src/GetEiMonDet2.cpp b/Framework/Algorithms/src/GetEiMonDet2.cpp index c6a1fddea7d63bfb9a7dee6dc3964861db0a4348..0a1fee68e811104101b6ea03d6e1b965230336de 100644 --- a/Framework/Algorithms/src/GetEiMonDet2.cpp +++ b/Framework/Algorithms/src/GetEiMonDet2.cpp @@ -198,6 +198,7 @@ void GetEiMonDet2::averageDetectorDistanceAndTOF( double distanceSum = 0; double eppSum = 0; size_t n = 0; + // cppcheck-suppress syntaxError PRAGMA_OMP(parallel for if ( m_detectorEPPTable->threadSafe()) reduction(+: n, distanceSum, eppSum)) for (int i = 0; i < static_cast<int>(detectorIndices.size()); ++i) { diff --git a/Framework/Algorithms/src/NormaliseByCurrent.cpp b/Framework/Algorithms/src/NormaliseByCurrent.cpp index 1394877e9833afa779d04ef450e6d25a3fc07f9c..0265cc8de657d3a3cc5268b773717aa5e19ac9ec 100644 --- a/Framework/Algorithms/src/NormaliseByCurrent.cpp +++ b/Framework/Algorithms/src/NormaliseByCurrent.cpp @@ -1,8 +1,8 @@ #include "MantidAPI/Run.h" -#include "MantidKernel/LogFilter.h" -#include "MantidKernel/ArrayProperty.h" #include "MantidAlgorithms/NormaliseByCurrent.h" #include "MantidDataObjects/EventWorkspace.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/LogFilter.h" namespace Mantid { namespace Algorithms { diff --git a/Framework/Algorithms/src/NormaliseByDetector.cpp b/Framework/Algorithms/src/NormaliseByDetector.cpp index 3b2ff40bd6a2096540dfec48d0f051e1fec91916..72fdd3553c08abc3763af3e045452d67b94062bd 100644 --- a/Framework/Algorithms/src/NormaliseByDetector.cpp +++ b/Framework/Algorithms/src/NormaliseByDetector.cpp @@ -6,10 +6,10 @@ #include "MantidAPI/IFunction.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/WorkspaceUnitValidator.h" -#include "MantidGeometry/Instrument/ParameterMap.h" #include "MantidGeometry/Instrument/Component.h" #include "MantidGeometry/Instrument/DetectorGroup.h" #include "MantidGeometry/Instrument/FitParameter.h" +#include "MantidGeometry/Instrument/ParameterMap.h" #include "MantidGeometry/muParser_Silent.h" #include "MantidKernel/CompositeValidator.h" #include "MantidKernel/UnitFactory.h" @@ -92,8 +92,8 @@ use. @param prog: progress reporting object. */ void NormaliseByDetector::processHistogram(size_t wsIndex, - MatrixWorkspace_sptr denominatorWS, MatrixWorkspace_const_sptr inWS, + MatrixWorkspace_sptr denominatorWS, Progress &prog) { const Geometry::ParameterMap ¶mMap = inWS->instrumentParameters(); Geometry::IDetector_const_sptr det = inWS->getDetector(wsIndex); @@ -134,22 +134,18 @@ void NormaliseByDetector::processHistogram(size_t wsIndex, function->setParameter(fitParam.getName(), paramValue); } - auto wavelengths = inWS->readX(wsIndex); - const size_t nInputBins = wavelengths.size() - 1; - std::vector<double> centerPointWavelength(nInputBins); - std::vector<double> outIntensity(nInputBins); - for (size_t binIndex = 0; binIndex < nInputBins; ++binIndex) { - centerPointWavelength[binIndex] = - 0.5 * (wavelengths[binIndex] + wavelengths[binIndex + 1]); - } - FunctionDomain1DVector domain(centerPointWavelength); + auto wavelengths = inWS->points(wsIndex); + FunctionDomain1DVector domain(wavelengths.rawData()); FunctionValues values(domain); function->function(domain, values); + + auto &Y = denominatorWS->mutableY(wsIndex); for (size_t i = 0; i < domain.size(); ++i) { - outIntensity[i] = values[i]; + Y[i] = values[i]; } - denominatorWS->dataY(wsIndex) = outIntensity; - denominatorWS->dataE(wsIndex) = MantidVec(nInputBins, 0); + + denominatorWS->mutableE(wsIndex) = 0.0; + prog.report(); } @@ -181,13 +177,13 @@ NormaliseByDetector::processHistograms(MatrixWorkspace_sptr inWS) { PARALLEL_FOR2(inWS, denominatorWS) for (int wsIndex = 0; wsIndex < static_cast<int>(nHistograms); ++wsIndex) { PARALLEL_START_INTERUPT_REGION - this->processHistogram(wsIndex, denominatorWS, inWS, prog); + this->processHistogram(wsIndex, inWS, denominatorWS, prog); PARALLEL_END_INTERUPT_REGION } PARALLEL_CHECK_INTERUPT_REGION } else { for (size_t wsIndex = 0; wsIndex < nHistograms; ++wsIndex) { - this->processHistogram(wsIndex, denominatorWS, inWS, prog); + this->processHistogram(wsIndex, inWS, denominatorWS, prog); } } diff --git a/Framework/Algorithms/src/NormaliseToMonitor.cpp b/Framework/Algorithms/src/NormaliseToMonitor.cpp index 1ab370ee0d21fcd82ab2fd8bb0227da69731f29c..ae2de78e20288514ed56459af74630a9c5c192e2 100644 --- a/Framework/Algorithms/src/NormaliseToMonitor.cpp +++ b/Framework/Algorithms/src/NormaliseToMonitor.cpp @@ -17,6 +17,7 @@ #include <numeric> using namespace Mantid::DataObjects; +using namespace Mantid::HistogramData; using Mantid::Kernel::IPropertyManager; namespace Mantid { @@ -490,17 +491,15 @@ bool NormaliseToMonitor::setIntegrationProps() { } // Now check the end X values are within the X value range of the workspace - if (isEmpty(m_integrationMin) || - m_integrationMin < m_monitor->readX(0).front()) { + if (isEmpty(m_integrationMin) || m_integrationMin < m_monitor->x(0).front()) { g_log.warning() << "Integration range minimum set to workspace min: " << m_integrationMin << '\n'; - m_integrationMin = m_monitor->readX(0).front(); + m_integrationMin = m_monitor->x(0).front(); } - if (isEmpty(m_integrationMax) || - m_integrationMax > m_monitor->readX(0).back()) { + if (isEmpty(m_integrationMax) || m_integrationMax > m_monitor->x(0).back()) { g_log.warning() << "Integration range maximum set to workspace max: " << m_integrationMax << '\n'; - m_integrationMax = m_monitor->readX(0).back(); + m_integrationMax = m_monitor->x(0).back(); } // Return indicating that these properties should be used @@ -561,29 +560,31 @@ void NormaliseToMonitor::normaliseBinByBin( boost::dynamic_pointer_cast<EventWorkspace>(outputWorkspace); // Get hold of the monitor spectrum - const MantidVec &monX = m_monitor->readX(0); - MantidVec &monY = m_monitor->dataY(0); - MantidVec &monE = m_monitor->dataE(0); + const auto &monX = m_monitor->binEdges(0); + auto monY = m_monitor->counts(0); + auto monE = m_monitor->countStandardDeviations(0); // Calculate the overall normalization just the once if bins are all matching if (m_commonBins) - this->normalisationFactor(m_monitor->readX(0), &monY, &monE); + this->normalisationFactor(monX, monY, monE); const size_t numHists = inputWorkspace->getNumberHistograms(); - MantidVec::size_type specLength = inputWorkspace->blocksize(); + auto specLength = inputWorkspace->blocksize(); // Flag set when a division by 0 is found bool hasZeroDivision = false; Progress prog(this, 0.0, 1.0, numHists); // Loop over spectra - PARALLEL_FOR3(inputWorkspace, outputWorkspace, m_monitor) + PARALLEL_FOR_IF( + Kernel::threadSafe(*inputWorkspace, *outputWorkspace, *m_monitor)) for (int64_t i = 0; i < int64_t(numHists); ++i) { PARALLEL_START_INTERUPT_REGION prog.report(); - const MantidVec &X = inputWorkspace->readX(i); + const auto &X = inputWorkspace->binEdges(i); // If not rebinning, just point to our monitor spectra, otherwise create new // vectors - MantidVec *Y = (m_commonBins ? &monY : new MantidVec(specLength)); - MantidVec *E = (m_commonBins ? &monE : new MantidVec(specLength)); + + auto Y = (m_commonBins ? monY : Counts(specLength)); + auto E = (m_commonBins ? monE : CountStandardDeviations(specLength)); if (!m_commonBins) { // ConvertUnits can give X vectors of all zeros - skip these, they cause @@ -592,7 +593,9 @@ void NormaliseToMonitor::normaliseBinByBin( continue; // Rebin the monitor spectrum to match the binning of the current data // spectrum - VectorHelper::rebinHistogram(monX, monY, monE, X, *Y, *E, false); + VectorHelper::rebinHistogram( + monX.rawData(), monY.mutableRawData(), monE.mutableRawData(), + X.rawData(), Y.mutableRawData(), E.mutableRawData(), false); // Recalculate the overall normalization factor this->normalisationFactor(X, Y, E); } @@ -601,20 +604,21 @@ void NormaliseToMonitor::normaliseBinByBin( // ----------------------------------- EventWorkspace // --------------------------------------- EventList &outEL = outputEvent->getSpectrum(i); - outEL.divide(X, *Y, *E); + outEL.divide(X.rawData(), Y.mutableRawData(), E.mutableRawData()); } else { // ----------------------------------- Workspace2D // --------------------------------------- - MantidVec &YOut = outputWorkspace->dataY(i); - MantidVec &EOut = outputWorkspace->dataE(i); - const MantidVec &inY = inputWorkspace->readY(i); - const MantidVec &inE = inputWorkspace->readE(i); - outputWorkspace->dataX(i) = inputWorkspace->readX(i); + auto &YOut = outputWorkspace->mutableY(i); + auto &EOut = outputWorkspace->mutableE(i); + const auto &inY = inputWorkspace->y(i); + const auto &inE = inputWorkspace->e(i); + outputWorkspace->mutableX(i) = inputWorkspace->x(i); + // The code below comes more or less straight out of Divide.cpp - for (MantidVec::size_type k = 0; k < specLength; ++k) { - // Get references to the input Y's - const double &leftY = inY[k]; - const double &rightY = (*Y)[k]; + for (size_t k = 0; k < specLength; ++k) { + // Get the input Y's + const double leftY = inY[k]; + const double rightY = Y[k]; if (rightY == 0.0) { hasZeroDivision = true; @@ -630,7 +634,7 @@ void NormaliseToMonitor::normaliseBinByBin( ? 0.0 : pow((inE[k] / leftY), 2); const double rhsFactor = - (*E)[k] < 1.0e-12 ? 0.0 : pow(((*E)[k] / rightY), 2); + E[k] < 1.0e-12 ? 0.0 : pow((E[k] / rightY), 2); EOut[k] = std::abs(newY) * sqrt(lhsFactor + rhsFactor); } @@ -639,10 +643,6 @@ void NormaliseToMonitor::normaliseBinByBin( } // end Workspace2D case } // end loop over current spectrum - if (!m_commonBins) { - delete Y; - delete E; - } PARALLEL_END_INTERUPT_REGION } // end loop over spectra PARALLEL_CHECK_INTERUPT_REGION @@ -654,19 +654,23 @@ void NormaliseToMonitor::normaliseBinByBin( /** Calculates the overall normalization factor. * This multiplies result by (bin width * sum of monitor counts) / total frame * width. - * @param X The X vector - * @param Y The data vector - * @param E The error vector + * @param X The BinEdges of the workspace + * @param Y The Counts of the workspace + * @param E The CountStandardDeviations of the workspace */ -void NormaliseToMonitor::normalisationFactor(const MantidVec &X, MantidVec *Y, - MantidVec *E) { - const double monitorSum = std::accumulate(Y->begin(), Y->end(), 0.0); +void NormaliseToMonitor::normalisationFactor(const BinEdges &X, Counts &Y, + CountStandardDeviations &E) { + const double monitorSum = std::accumulate(Y.begin(), Y.end(), 0.0); const double range = X.back() - X.front(); - MantidVec::size_type specLength = Y->size(); - for (MantidVec::size_type j = 0; j < specLength; ++j) { + auto specLength = Y.size(); + + auto &yNew = Y.mutableRawData(); + auto &eNew = E.mutableRawData(); + + for (size_t j = 0; j < specLength; ++j) { const double factor = range / ((X[j + 1] - X[j]) * monitorSum); - (*Y)[j] *= factor; - (*E)[j] *= factor; + yNew[j] *= factor; + eNew[j] *= factor; } } diff --git a/Framework/Algorithms/src/PDCalibration.cpp b/Framework/Algorithms/src/PDCalibration.cpp index 7ffad489174f247b00ffbb7186f56263ee01af14..add9a37abc27229595f6933dcc463847bdd50b6a 100644 --- a/Framework/Algorithms/src/PDCalibration.cpp +++ b/Framework/Algorithms/src/PDCalibration.cpp @@ -60,8 +60,8 @@ public: } this->detid = *(detIds.begin()); - const MantidVec &X = spectrum.readX(); - const MantidVec &Y = spectrum.readY(); + const auto &X = spectrum.x(); + const auto &Y = spectrum.y(); tofMin = X.front(); tofMax = X.back(); @@ -806,7 +806,7 @@ void PDCalibration::createNewCalTable() { const size_t wi = it->second; API::TableRow newRow = m_calibrationTable->appendRow(); newRow << detID; - newRow << difcWS->readY(wi)[0]; + newRow << difcWS->y(wi)[0]; newRow << 0.; // difa newRow << 0.; // tzero newRow << 0.; // tofmin diff --git a/Framework/Algorithms/src/PDFFourierTransform.cpp b/Framework/Algorithms/src/PDFFourierTransform.cpp index a3cd8bd55a3d6fe8ee1d25cfb7929c292817a3fd..efd92caa5d60349175f4d818fa922c8ba6abaed3 100644 --- a/Framework/Algorithms/src/PDFFourierTransform.cpp +++ b/Framework/Algorithms/src/PDFFourierTransform.cpp @@ -10,6 +10,7 @@ #include "MantidKernel/PhysicalConstants.h" #include "MantidKernel/Unit.h" #include "MantidKernel/UnitFactory.h" +#include "MantidHistogramData/LinearGenerator.h" #include <cmath> #include <sstream> @@ -18,6 +19,7 @@ namespace Mantid { namespace Algorithms { using std::string; +using namespace HistogramData; // Register the algorithm into the AlgorithmFactory DECLARE_ALGORITHM(PDFFourierTransform) @@ -229,12 +231,12 @@ double PDFFourierTransform::determineRho0() { void PDFFourierTransform::exec() { // get input data API::MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace"); - MantidVec inputQ = inputWS->dataX(0); // x for input + auto inputQ = inputWS->x(0).rawData(); // x for input HistogramData::HistogramDx inputDQ(inputQ.size(), 0.0); // dx for input if (inputWS->sharedDx(0)) inputDQ = inputWS->dx(0); - MantidVec inputFOfQ = inputWS->dataY(0); // y for input - MantidVec inputDfOfQ = inputWS->dataE(0); // dy for input + auto inputFOfQ = inputWS->y(0).rawData(); // y for input + auto inputDfOfQ = inputWS->e(0).rawData(); // dy for input // transform input data into Q/MomentumTransfer const std::string inputXunit = inputWS->getAxis(0)->unit()->unitID(); @@ -335,16 +337,16 @@ void PDFFourierTransform::exec() { outputWS->mutableRun().addProperty("Qmax", inputQ[qmax_index], "Angstroms^-1", true); - MantidVec &outputR = outputWS->dataX(0); - for (size_t i = 0; i < sizer; i++) { - outputR[i] = rdelta * static_cast<double>(1 + i); - } + BinEdges edges(sizer + 1, LinearGenerator(rdelta, rdelta)); + outputWS->setBinEdges(0, edges); + + auto &outputR = outputWS->mutableX(0); g_log.information() << "Using rmin = " << outputR.front() << "Angstroms and rmax = " << outputR.back() << "Angstroms\n"; // always calculate G(r) then convert - MantidVec &outputY = outputWS->dataY(0); - MantidVec &outputE = outputWS->dataE(0); + auto &outputY = outputWS->mutableY(0); + auto &outputE = outputWS->mutableE(0); // do the math for (size_t r_index = 0; r_index < sizer; r_index++) { @@ -410,4 +412,4 @@ void PDFFourierTransform::exec() { } } // namespace Mantid -} // namespace Algorithms +} // namespace Algorithms \ No newline at end of file diff --git a/Framework/Algorithms/src/PhaseQuadMuon.cpp b/Framework/Algorithms/src/PhaseQuadMuon.cpp index cd2caba68cbf7f08c8c9107387625bca41fc67d2..6538d34ea39200b7a1d8723ad712f2f0be393f98 100644 --- a/Framework/Algorithms/src/PhaseQuadMuon.cpp +++ b/Framework/Algorithms/src/PhaseQuadMuon.cpp @@ -121,9 +121,9 @@ PhaseQuadMuon::getExponentialDecay(const API::MatrixWorkspace_sptr &ws) { for (size_t h = 0; h < ws->getNumberHistograms(); h++) { - const auto &X = ws->getSpectrum(h).readX(); - const auto &Y = ws->getSpectrum(h).readY(); - const auto &E = ws->getSpectrum(h).readE(); + const auto &X = ws->getSpectrum(h).x(); + const auto &Y = ws->getSpectrum(h).y(); + const auto &E = ws->getSpectrum(h).e(); double s, sx, sy; s = sx = sy = 0; @@ -214,20 +214,31 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, } // First X value - double X0 = ws->readX(0).front(); + double X0 = ws->x(0).front(); + + // Create and populate output workspace + API::MatrixWorkspace_sptr ows = API::WorkspaceFactory::Instance().create( + "Workspace2D", 2, npoints + 1, npoints); + + // X + ows->setSharedX(0, ws->sharedX(0)); + ows->setSharedX(1, ws->sharedX(0)); // Phase quadrature - std::vector<double> realY(npoints, 0), imagY(npoints, 0); - std::vector<double> realE(npoints, 0), imagE(npoints, 0); + auto &realY = ows->mutableY(0); + auto &imagY = ows->mutableY(1); + auto &realE = ows->mutableE(0); + auto &imagE = ows->mutableE(1); + for (size_t i = 0; i < npoints; i++) { for (size_t h = 0; h < nspec; h++) { // (X,Y,E) with exponential decay removed - double X = ws->readX(h)[i]; - double Y = ws->readY(h)[i] - n0[h] * exp(-(X - X0) / muLife); - double E = (ws->readY(h)[i] > poissonLimit) - ? ws->readE(h)[i] - : sqrt(n0[h] * exp(-(X - X0) / muLife)); + const double X = ws->x(h)[i]; + const double Y = ws->y(h)[i] - n0[h] * exp(-(X - X0) / muLife); + const double E = (ws->y(h)[i] > poissonLimit) + ? ws->e(h)[i] + : sqrt(n0[h] * exp(-(X - X0) / muLife)); realY[i] += aj[h] * Y; imagY[i] += bj[h] * Y; @@ -238,25 +249,14 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, imagE[i] = sqrt(imagE[i]); // Regain exponential decay - double X = ws->getSpectrum(0).readX()[i]; - double e = exp(-(X - X0) / muLife); + const double X = ws->getSpectrum(0).x()[i]; + const double e = exp(-(X - X0) / muLife); realY[i] /= e; imagY[i] /= e; realE[i] /= e; imagE[i] /= e; } - // Populate output workspace - API::MatrixWorkspace_sptr ows = API::WorkspaceFactory::Instance().create( - "Workspace2D", 2, npoints + 1, npoints); - ows->dataY(0).assign(realY.begin(), realY.end()); - ows->dataE(0).assign(realE.begin(), realE.end()); - ows->dataY(1).assign(imagY.begin(), imagY.end()); - ows->dataE(1).assign(imagE.begin(), imagE.end()); - // X - MantidVec x = ws->readX(0); - ows->dataX(0).assign(x.begin(), x.end()); - ows->dataX(1).assign(x.begin(), x.end()); return ows; } } diff --git a/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index d62325af3582f3481eb5f985c42ad79259f41b38..ae77d31cf88053bb4d0c2a9ef4849f7e0948c7f0 100644 --- a/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -266,11 +266,11 @@ void PlotAsymmetryByLogValue::checkProperties(size_t &is, size_t &ie) { for (size_t i = 0; i < nPoints; i++) { // The first spectrum contains: X -> run number, Y -> log value // The second spectrum contains: Y -> redY, E -> redE - size_t run = static_cast<size_t>(prevResults->readX(0)[i]); + size_t run = static_cast<size_t>(prevResults->x(0)[i]); if ((run >= is) && (run <= ie)) { - m_logValue[run] = prevResults->readY(0)[i]; - m_redY[run] = prevResults->readY(1)[i]; - m_redE[run] = prevResults->readE(1)[i]; + m_logValue[run] = prevResults->y(0)[i]; + m_redY[run] = prevResults->y(1)[i]; + m_redE[run] = prevResults->e(1)[i]; } } } else { @@ -281,17 +281,17 @@ void PlotAsymmetryByLogValue::checkProperties(size_t &is, size_t &ie) { // The third spectrum contains: Y -> redY, E -> redE // The fourth spectrum contains: Y -> greenY, E -> greeE // The fifth spectrum contains: Y -> sumY, E -> sumE - size_t run = static_cast<size_t>(prevResults->readX(0)[i]); + size_t run = static_cast<size_t>(prevResults->x(0)[i]); if ((run >= is) && (run <= ie)) { - m_logValue[run] = prevResults->readY(0)[i]; - m_diffY[run] = prevResults->readY(1)[i]; - m_diffE[run] = prevResults->readE(1)[i]; - m_redY[run] = prevResults->readY(2)[i]; - m_redE[run] = prevResults->readE(2)[i]; - m_greenY[run] = prevResults->readY(3)[i]; - m_greenE[run] = prevResults->readE(3)[i]; - m_sumY[run] = prevResults->readY(4)[i]; - m_sumE[run] = prevResults->readE(4)[i]; + m_logValue[run] = prevResults->y(0)[i]; + m_diffY[run] = prevResults->y(1)[i]; + m_diffE[run] = prevResults->e(1)[i]; + m_redY[run] = prevResults->y(2)[i]; + m_redE[run] = prevResults->e(2)[i]; + m_greenY[run] = prevResults->y(3)[i]; + m_greenE[run] = prevResults->e(3)[i]; + m_sumY[run] = prevResults->y(4)[i]; + m_sumE[run] = prevResults->e(4)[i]; } } } @@ -386,9 +386,9 @@ void PlotAsymmetryByLogValue::populateOutputWorkspace( if (nplots == 1) { size_t i = 0; for (auto &value : m_logValue) { - outWS->dataX(0)[i] = value.second; - outWS->dataY(0)[i] = m_redY[value.first]; - outWS->dataE(0)[i] = m_redE[value.first]; + outWS->mutableX(0)[i] = value.second; + outWS->mutableY(0)[i] = m_redY[value.first]; + outWS->mutableE(0)[i] = m_redE[value.first]; i++; } tAxis->setLabel(0, "Asymmetry"); @@ -396,18 +396,18 @@ void PlotAsymmetryByLogValue::populateOutputWorkspace( } else { size_t i = 0; for (auto &value : m_logValue) { - outWS->dataX(0)[i] = value.second; - outWS->dataY(0)[i] = m_diffY[value.first]; - outWS->dataE(0)[i] = m_diffE[value.first]; - outWS->dataX(1)[i] = value.second; - outWS->dataY(1)[i] = m_redY[value.first]; - outWS->dataE(1)[i] = m_redE[value.first]; - outWS->dataX(2)[i] = value.second; - outWS->dataY(2)[i] = m_greenY[value.first]; - outWS->dataE(2)[i] = m_greenE[value.first]; - outWS->dataX(3)[i] = value.second; - outWS->dataY(3)[i] = m_sumY[value.first]; - outWS->dataE(3)[i] = m_sumE[value.first]; + outWS->mutableX(0)[i] = value.second; + outWS->mutableY(0)[i] = m_diffY[value.first]; + outWS->mutableE(0)[i] = m_diffE[value.first]; + outWS->mutableX(1)[i] = value.second; + outWS->mutableY(1)[i] = m_redY[value.first]; + outWS->mutableE(1)[i] = m_redE[value.first]; + outWS->mutableX(2)[i] = value.second; + outWS->mutableY(2)[i] = m_greenY[value.first]; + outWS->mutableE(2)[i] = m_greenE[value.first]; + outWS->mutableX(3)[i] = value.second; + outWS->mutableY(3)[i] = m_sumY[value.first]; + outWS->mutableE(3)[i] = m_sumE[value.first]; i++; } tAxis->setLabel(0, "Red-Green"); @@ -431,26 +431,26 @@ void PlotAsymmetryByLogValue::saveResultsToADS(MatrixWorkspace_sptr &outWS, size_t i = 0; for (auto &value : m_logValue) { size_t run = value.first; - outWS->dataX(0)[i] = static_cast<double>(run); // run number - outWS->dataY(0)[i] = value.second; // log value - outWS->dataY(1)[i] = m_redY[run]; // redY - outWS->dataE(1)[i] = m_redE[run]; // redE + outWS->mutableX(0)[i] = static_cast<double>(run); // run number + outWS->mutableY(0)[i] = value.second; // log value + outWS->mutableY(1)[i] = m_redY[run]; // redY + outWS->mutableE(1)[i] = m_redE[run]; // redE i++; } } else { size_t i = 0; for (auto &value : m_logValue) { size_t run = value.first; - outWS->dataX(0)[i] = static_cast<double>(run); // run number - outWS->dataY(0)[i] = value.second; // log value - outWS->dataY(1)[i] = m_diffY[run]; // diffY - outWS->dataE(1)[i] = m_diffE[run]; // diffE - outWS->dataY(2)[i] = m_redY[run]; // redY - outWS->dataE(2)[i] = m_redE[run]; // redE - outWS->dataY(3)[i] = m_greenY[run]; // greenY - outWS->dataE(3)[i] = m_greenE[run]; // greenE - outWS->dataY(4)[i] = m_sumY[run]; // sumY - outWS->dataE(4)[i] = m_sumE[run]; // sumE + outWS->mutableX(0)[i] = static_cast<double>(run); // run number + outWS->mutableY(0)[i] = value.second; // log value + outWS->mutableY(1)[i] = m_diffY[run]; // diffY + outWS->mutableE(1)[i] = m_diffE[run]; // diffE + outWS->mutableY(2)[i] = m_redY[run]; // redY + outWS->mutableE(2)[i] = m_redE[run]; // redE + outWS->mutableY(3)[i] = m_greenY[run]; // greenY + outWS->mutableE(3)[i] = m_greenE[run]; // greenE + outWS->mutableY(4)[i] = m_sumY[run]; // sumY + outWS->mutableE(4)[i] = m_sumE[run]; // sumE i++; } } @@ -689,6 +689,9 @@ void PlotAsymmetryByLogValue::doAnalysis(Workspace_sptr loadedWs, void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws, double &Y, double &E) { + // Output workspace + MatrixWorkspace_sptr out; + if (!m_int) { // "Differential asymmetry" IAlgorithm_sptr asym = createChildAlgorithm("AsymmetryCalc"); asym->setLogging(false); @@ -702,10 +705,8 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws, integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); - MatrixWorkspace_sptr out = integr->getProperty("OutputWorkspace"); + out = integr->getProperty("OutputWorkspace"); - Y = out->readY(0)[0]; - E = out->readE(0)[0]; } else { // "Integral asymmetry" IAlgorithm_sptr integr = createChildAlgorithm("Integration"); @@ -720,11 +721,11 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws, asym->setLogging(false); asym->setProperty("InputWorkspace", intWS); asym->execute(); - MatrixWorkspace_sptr out = asym->getProperty("OutputWorkspace"); - - Y = out->readY(0)[0]; - E = out->readE(0)[0]; + out = asym->getProperty("OutputWorkspace"); } + + Y = out->y(0)[0]; + E = out->e(0)[0]; } /** Calculate the integral asymmetry for a pair of workspaces (red & green). @@ -739,17 +740,17 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws_red, if (!m_int) { // "Differential asymmetry" MatrixWorkspace_sptr tmpWS = WorkspaceFactory::Instance().create( - ws_red, 1, ws_red->readX(0).size(), ws_red->readY(0).size()); + ws_red, 1, ws_red->x(0).size(), ws_red->y(0).size()); - for (size_t i = 0; i < tmpWS->dataY(0).size(); i++) { - double FNORM = ws_green->readY(0)[i] + ws_red->readY(0)[i]; + for (size_t i = 0; i < tmpWS->y(0).size(); i++) { + double FNORM = ws_green->y(0)[i] + ws_red->y(0)[i]; FNORM = FNORM != 0.0 ? 1.0 / FNORM : 1.0; - double BNORM = ws_green->readY(1)[i] + ws_red->readY(1)[i]; + double BNORM = ws_green->y(1)[i] + ws_red->y(1)[i]; BNORM = BNORM != 0.0 ? 1.0 / BNORM : 1.0; - double ZF = (ws_green->readY(0)[i] - ws_red->readY(0)[i]) * FNORM; - double ZB = (ws_green->readY(1)[i] - ws_red->readY(1)[i]) * BNORM; - tmpWS->dataY(0)[i] = ZB - ZF; - tmpWS->dataE(0)[i] = (1.0 + ZF * ZF) * FNORM + (1.0 + ZB * ZB) * BNORM; + double ZF = (ws_green->y(0)[i] - ws_red->y(0)[i]) * FNORM; + double ZB = (ws_green->y(1)[i] - ws_red->y(1)[i]) * BNORM; + tmpWS->mutableY(0)[i] = ZB - ZF; + tmpWS->mutableE(0)[i] = (1.0 + ZF * ZF) * FNORM + (1.0 + ZB * ZB) * BNORM; } IAlgorithm_sptr integr = createChildAlgorithm("Integration"); @@ -759,8 +760,8 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws_red, integr->execute(); MatrixWorkspace_sptr out = integr->getProperty("OutputWorkspace"); - Y = out->readY(0)[0] / static_cast<double>(tmpWS->dataY(0).size()); - E = out->readE(0)[0] / static_cast<double>(tmpWS->dataY(0).size()); + Y = out->y(0)[0] / static_cast<double>(tmpWS->y(0).size()); + E = out->e(0)[0] / static_cast<double>(tmpWS->y(0).size()); } else { // "Integral asymmetry" IAlgorithm_sptr integr = createChildAlgorithm("Integration"); @@ -777,17 +778,17 @@ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws_red, integr->execute(); MatrixWorkspace_sptr intWS_green = integr->getProperty("OutputWorkspace"); - double YIF = (intWS_green->readY(0)[0] - intWS_red->readY(0)[0]) / - (intWS_green->readY(0)[0] + intWS_red->readY(0)[0]); - double YIB = (intWS_green->readY(1)[0] - intWS_red->readY(1)[0]) / - (intWS_green->readY(1)[0] + intWS_red->readY(1)[0]); + double YIF = (intWS_green->y(0)[0] - intWS_red->y(0)[0]) / + (intWS_green->y(0)[0] + intWS_red->y(0)[0]); + double YIB = (intWS_green->y(1)[0] - intWS_red->y(1)[0]) / + (intWS_green->y(1)[0] + intWS_red->y(1)[0]); Y = YIB - YIF; double VARIF = - (1.0 + YIF * YIF) / (intWS_green->readY(0)[0] + intWS_red->readY(0)[0]); + (1.0 + YIF * YIF) / (intWS_green->y(0)[0] + intWS_red->y(0)[0]); double VARIB = - (1.0 + YIB * YIB) / (intWS_green->readY(1)[0] + intWS_red->readY(1)[0]); + (1.0 + YIB * YIB) / (intWS_green->y(1)[0] + intWS_red->y(1)[0]); E = sqrt(VARIF + VARIB); } diff --git a/Framework/Algorithms/src/PointByPointVCorrection.cpp b/Framework/Algorithms/src/PointByPointVCorrection.cpp index 2b2de14b3b68b74c5c506643b2a8cae89b21d240..1d6a66d359755229cf7591997dbefecb35ccd3c1 100644 --- a/Framework/Algorithms/src/PointByPointVCorrection.cpp +++ b/Framework/Algorithms/src/PointByPointVCorrection.cpp @@ -49,24 +49,24 @@ void PointByPointVCorrection::exec() { check_validity(inputWS1, inputWS2, outputWS); // Now do the normalisation - const int size = static_cast<int>(inputWS1->readX(0).size()); + const int size = static_cast<int>(inputWS1->x(0).size()); const int nHist = static_cast<int>(inputWS1->getNumberHistograms()); Progress prog(this, 0.0, 1.0, nHist); - PARALLEL_FOR3(inputWS1, inputWS2, outputWS) + PARALLEL_FOR_IF(Kernel::threadSafe(*inputWS1, *inputWS2, *outputWS)) for (int i = 0; i < nHist; i++) // Looping on all histograms { PARALLEL_START_INTERUPT_REGION - const MantidVec &X = inputWS1->readX(i); - outputWS->setX(i, inputWS1->refX(i)); + outputWS->setSharedX(i, inputWS1->sharedX(i)); - const MantidVec &Y1 = inputWS1->readY(i); - const MantidVec &Y2 = inputWS2->readY(i); - const MantidVec &E1 = inputWS1->readE(i); - const MantidVec &E2 = inputWS2->readE(i); - MantidVec &resultY = outputWS->dataY(i); - MantidVec &resultE = outputWS->dataE(i); + const auto &X = inputWS1->x(i); + const auto &Y1 = inputWS1->y(i); + const auto &Y2 = inputWS2->y(i); + const auto &E1 = inputWS1->e(i); + const auto &E2 = inputWS2->e(i); + auto &resultY = outputWS->mutableY(i); + auto &resultE = outputWS->mutableE(i); // Work on the Y data MantidVec binwidths(size); // MantidVec for bin widths diff --git a/Framework/Algorithms/src/PolarizationCorrection.cpp b/Framework/Algorithms/src/PolarizationCorrection.cpp index acde7002488ec5ea493a5a82ed223f3be2378a7c..c7a88b8320e57aea23a6ea3f4bb28d032f9ad478 100644 --- a/Framework/Algorithms/src/PolarizationCorrection.cpp +++ b/Framework/Algorithms/src/PolarizationCorrection.cpp @@ -78,9 +78,11 @@ void validateInputWorkspace(WorkspaceGroup_sptr &ws) { "WorkspaceGroup"); } - auto currentX = ws2d->readX(0); - auto lastX = lastWS->readX(0); - if (currentX != lastX) { + auto ¤tX = ws2d->x(0); + auto &lastX = lastWS->x(0); + auto xMatches = + std::equal(lastX.cbegin(), lastX.cend(), currentX.cbegin()); + if (!xMatches) { throw std::invalid_argument("X-arrays do not match between all " "workspaces in the InputWorkspace " "WorkspaceGroup."); @@ -234,7 +236,7 @@ PolarizationCorrection::copyShapeAndFill(MatrixWorkspace_sptr &base, MatrixWorkspace_sptr wsTemplate = WorkspaceFactory::Instance().create(base); // Copy the x-array across to the new workspace. for (size_t i = 0; i < wsTemplate->getNumberHistograms(); ++i) { - wsTemplate->setX(i, base->refX(i)); + wsTemplate->setSharedX(i, base->sharedX(i)); } auto zeroed = this->multiply(wsTemplate, 0); auto filled = this->add(zeroed, value); diff --git a/Framework/Algorithms/src/Q1D2.cpp b/Framework/Algorithms/src/Q1D2.cpp index 5c97a099e5364eb60e32dcfd19ce684fcb2399b7..7433e9993bfcd2e53a5b526f2810ab42a639d5c7 100644 --- a/Framework/Algorithms/src/Q1D2.cpp +++ b/Framework/Algorithms/src/Q1D2.cpp @@ -117,9 +117,9 @@ void Q1D2::exec() { // FIXME: how to examine the wavePixelAdj? g_log.debug() << "All input workspaces were found to be valid\n"; // normalization as a function of wavelength (i.e. centers of x-value bins) - double const *const binNorms = waveAdj ? &(waveAdj->readY(0)[0]) : nullptr; + double const *const binNorms = waveAdj ? &(waveAdj->y(0)[0]) : nullptr; // error on the wavelength normalization - double const *const binNormEs = waveAdj ? &(waveAdj->readE(0)[0]) : nullptr; + double const *const binNormEs = waveAdj ? &(waveAdj->e(0)[0]) : nullptr; // define the (large number of) data objects that are going to be used in all // iterations of the loop below @@ -131,22 +131,21 @@ void Q1D2::exec() { MatrixWorkspace_sptr outputWS = setUpOutputWorkspace(getProperty("OutputBinning")); - const MantidVec &QOut = outputWS->readX(0); - MantidVec &YOut = outputWS->dataY(0); - MantidVec &EOutTo2 = outputWS->dataE(0); + auto &QOut = outputWS->x(0); + auto &YOut = outputWS->mutableY(0); + auto &EOutTo2 = outputWS->mutableE(0); // normalisation that is applied to counts in each Q bin - MantidVec normSum(YOut.size(), 0.0); + HistogramData::HistogramY normSum(YOut.size(), 0.0); // the error on the normalisation - MantidVec normError2(YOut.size(), 0.0); - + HistogramData::HistogramE normError2(EOutTo2.size(), 0.0); // the averaged Q resolution. - HistogramData::HistogramDx qResolutionOut(QOut.size() - 1, 0.0); + HistogramData::HistogramDx qResolutionOut(YOut.size(), 0.0); const int numSpec = static_cast<int>(m_dataWS->getNumberHistograms()); Progress progress(this, 0.05, 1.0, numSpec + 1); const auto &spectrumInfo = m_dataWS->spectrumInfo(); - PARALLEL_FOR3(m_dataWS, outputWS, pixelAdj) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_dataWS, *outputWS, pixelAdj.get())) for (int i = 0; i < numSpec; ++i) { PARALLEL_START_INTERUPT_REGION if (!spectrumInfo.hasDetectors(i)) { @@ -164,16 +163,16 @@ void Q1D2::exec() { // const size_t wavStart = waveLengthCutOff(i); const size_t wavStart = helper.waveLengthCutOff( m_dataWS, getProperty("RadiusCut"), getProperty("WaveCut"), i); - if (wavStart >= m_dataWS->readY(i).size()) { + if (wavStart >= m_dataWS->y(i).size()) { // all the spectra in this detector are out of range continue; } - const size_t numWavbins = m_dataWS->readY(i).size() - wavStart; + const size_t numWavbins = m_dataWS->y(i).size() - wavStart; // make just one call to new to reduce CPU overhead on each thread, access // to these // three "arrays" is via iterators - MantidVec _noDirectUseStorage_(3 * numWavbins); + HistogramData::HistogramY _noDirectUseStorage_(3 * numWavbins); // normalization term auto norms = _noDirectUseStorage_.begin(); // the error on these weights, it contributes to the error calculation on @@ -191,8 +190,8 @@ void Q1D2::exec() { getProperty("ExtraLength")); // Pointers to the counts data and it's error - auto YIn = m_dataWS->readY(i).cbegin() + wavStart; - auto EIn = m_dataWS->readE(i).cbegin() + wavStart; + auto YIn = m_dataWS->y(i).cbegin() + wavStart; + auto EIn = m_dataWS->e(i).cbegin() + wavStart; // Pointers to the QResolution data. Note that the xdata was initially the // same, hence @@ -201,14 +200,14 @@ void Q1D2::exec() { // that does not matter, as // we won't use it auto QResIn = - useQResolution ? (qResolution->readY(i).cbegin() + wavStart) : YIn; + useQResolution ? (qResolution->y(i).cbegin() + wavStart) : YIn; // when finding the output Q bin remember that the input Q bins (from the // convert to wavelength) start high and reduce auto loc = QOut.cend(); // sum the Q contributions from each individual spectrum into the output // array - const auto end = m_dataWS->readY(i).cend(); + const auto end = m_dataWS->y(i).cend(); for (; YIn != end; ++YIn, ++EIn, ++QIn, ++norms, ++normETo2s) { // find the output bin that each input y-value will fall into, remembering // there is one more bin boundary than bins @@ -274,21 +273,18 @@ void Q1D2::exec() { if (doOutputParts) { MatrixWorkspace_sptr ws_sumOfCounts = WorkspaceFactory::Instance().create(outputWS); - ws_sumOfCounts->dataX(0) = outputWS->dataX(0); - ws_sumOfCounts->dataY(0) = outputWS->dataY(0); + ws_sumOfCounts->setSharedX(0, outputWS->sharedX(0)); + // Copy now as YOut is modified in normalize + ws_sumOfCounts->mutableY(0) = YOut; ws_sumOfCounts->setSharedDx(0, outputWS->sharedDx(0)); - for (size_t i = 0; i < outputWS->dataE(0).size(); i++) { - ws_sumOfCounts->dataE(0)[i] = sqrt(outputWS->dataE(0)[i]); - } + ws_sumOfCounts->setFrequencyVariances(0, outputWS->e(0)); MatrixWorkspace_sptr ws_sumOfNormFactors = WorkspaceFactory::Instance().create(outputWS); - ws_sumOfNormFactors->dataX(0) = outputWS->dataX(0); + ws_sumOfNormFactors->setSharedX(0, outputWS->sharedX(0)); + ws_sumOfNormFactors->mutableY(0) = normSum; ws_sumOfNormFactors->setSharedDx(0, outputWS->sharedDx(0)); - for (size_t i = 0; i < ws_sumOfNormFactors->dataY(0).size(); i++) { - ws_sumOfNormFactors->dataY(0)[i] = normSum[i]; - ws_sumOfNormFactors->dataE(0)[i] = sqrt(normError2[i]); - } + ws_sumOfNormFactors->setFrequencyVariances(0, normError2); helper.outputParts(this, ws_sumOfCounts, ws_sumOfNormFactors); } @@ -346,17 +342,16 @@ Q1D2::setUpOutputWorkspace(const std::vector<double> &binParams) const { * @param normETo2 [out] this pointer must point to the end of the norm array, * it will be filled with the total of the error on the normalization */ -void Q1D2::calculateNormalization(const size_t wavStart, const size_t wsIndex, - API::MatrixWorkspace_const_sptr pixelAdj, - API::MatrixWorkspace_const_sptr wavePixelAdj, - double const *const binNorms, - double const *const binNormEs, - const MantidVec::iterator norm, - const MantidVec::iterator normETo2) const { +void Q1D2::calculateNormalization( + const size_t wavStart, const size_t wsIndex, + API::MatrixWorkspace_const_sptr pixelAdj, + API::MatrixWorkspace_const_sptr wavePixelAdj, double const *const binNorms, + double const *const binNormEs, HistogramData::HistogramY::iterator norm, + HistogramData::HistogramY::iterator normETo2) const { double detectorAdj, detAdjErr; pixelWeight(pixelAdj, wsIndex, detectorAdj, detAdjErr); // use that the normalization array ends at the start of the error array - for (MantidVec::iterator n = norm, e = normETo2; n != normETo2; ++n, ++e) { + for (auto n = norm, e = normETo2; n != normETo2; ++n, ++e) { *n = detectorAdj; *e = detAdjErr *detAdjErr; } @@ -365,8 +360,8 @@ void Q1D2::calculateNormalization(const size_t wavStart, const size_t wsIndex, if (wavePixelAdj) // pass the iterator for the wave pixel Adj dependent addWaveAdj(binNorms + wavStart, binNormEs + wavStart, norm, normETo2, - wavePixelAdj->readY(wsIndex).begin() + wavStart, - wavePixelAdj->readE(wsIndex).begin() + wavStart); + wavePixelAdj->y(wsIndex).begin() + wavStart, + wavePixelAdj->e(wsIndex).begin() + wavStart); else addWaveAdj(binNorms + wavStart, binNormEs + wavStart, norm, normETo2); } @@ -420,8 +415,8 @@ void Q1D2::pixelWeight(API::MatrixWorkspace_const_sptr pixelAdj, * before the WavelengthAdj term */ void Q1D2::addWaveAdj(const double *c, const double *Dc, - MantidVec::iterator bInOut, - MantidVec::iterator e2InOut) const { + HistogramData::HistogramY::iterator bInOut, + HistogramData::HistogramY::iterator e2InOut) const { // normalize by the wavelength dependent correction, keeping the percentage // errors the same // the error when a = b*c, the formula for Da, the error on a, in terms of Db, @@ -433,7 +428,7 @@ void Q1D2::addWaveAdj(const double *c, const double *Dc, // use the fact that error array follows straight after the normalization // array - const MantidVec::const_iterator end = e2InOut; + const auto end = e2InOut; for (; bInOut != end; ++e2InOut, ++c, ++Dc, ++bInOut) { // first the error *e2InOut = @@ -458,10 +453,12 @@ void Q1D2::addWaveAdj(const double *c, const double *Dc, * @param[in] wavePixelAdjError normalization correction incertainty for each bin * for each detector pixel. */ -void Q1D2::addWaveAdj(const double *c, const double *Dc, - MantidVec::iterator bInOut, MantidVec::iterator e2InOut, - MantidVec::const_iterator wavePixelAdjData, - MantidVec::const_iterator wavePixelAdjError) const { +void Q1D2::addWaveAdj( + const double *c, const double *Dc, + HistogramData::HistogramY::iterator bInOut, + HistogramData::HistogramY::iterator e2InOut, + HistogramData::HistogramY::const_iterator wavePixelAdjData, + HistogramData::HistogramE::const_iterator wavePixelAdjError) const { // normalize by the wavelength dependent correction, keeping the percentage // errors the same // the error when a = b*c*e, the formula for Da, the error on a, in terms of @@ -483,7 +480,7 @@ void Q1D2::addWaveAdj(const double *c, const double *Dc, // use the fact that error array follows straight after the normalization // array - const MantidVec::const_iterator end = e2InOut; + const auto end = e2InOut; for (; bInOut != end; ++e2InOut, ++c, ++Dc, ++bInOut, ++wavePixelAdjData, ++wavePixelAdjError) { // first the error @@ -507,9 +504,10 @@ void Q1D2::addWaveAdj(const double *c, const double *Dc, * @param[in,out] errorSquared the running total of the square of the * uncertainty in the normalization */ -void Q1D2::normToMask(const size_t offSet, const size_t wsIndex, - const MantidVec::iterator theNorms, - const MantidVec::iterator errorSquared) const { +void Q1D2::normToMask( + const size_t offSet, const size_t wsIndex, + const HistogramData::HistogramY::iterator theNorms, + const HistogramData::HistogramY::iterator errorSquared) const { // if any bins are masked it is normally a small proportion if (m_dataWS->hasMaskedBins(wsIndex)) { // Get a reference to the list of masked bins @@ -547,14 +545,14 @@ void Q1D2::normToMask(const size_t offSet, const size_t wsIndex, */ void Q1D2::convertWavetoQ(const SpectrumInfo &spectrumInfo, const size_t wsInd, const bool doGravity, const size_t offset, - MantidVec::iterator Qs, + HistogramData::HistogramY::iterator Qs, const double extraLength) const { static const double FOUR_PI = 4.0 * M_PI; // wavelengths (lamda) to be converted to Q - auto waves = m_dataWS->readX(wsInd).cbegin() + offset; + auto waves = m_dataWS->x(wsInd).cbegin() + offset; // going from bin boundaries to bin centered x-values the size goes down one - const MantidVec::const_iterator end = m_dataWS->readX(wsInd).end() - 1; + const auto end = m_dataWS->x(wsInd).end() - 1; if (doGravity) { GravitySANSHelper grav(spectrumInfo, wsInd, extraLength); for (; waves != end; ++Qs, ++waves) { @@ -592,8 +590,9 @@ void Q1D2::convertWavetoQ(const SpectrumInfo &spectrumInfo, const size_t wsInd, * checking the value of loc passed and then all the bins _downwards_ through the * array */ -void Q1D2::getQBinPlus1(const MantidVec &OutQs, const double QToFind, - MantidVec::const_iterator &loc) const { +void Q1D2::getQBinPlus1(const HistogramData::HistogramX &OutQs, + const double QToFind, + HistogramData::HistogramX::const_iterator &loc) const { if (loc != OutQs.end()) { while (loc != OutQs.begin()) { if ((QToFind >= *(loc - 1)) && (QToFind < *loc)) { @@ -628,8 +627,10 @@ void Q1D2::getQBinPlus1(const MantidVec &OutQs, const double QToFind, * @param[in, out] errors input the _square_ of the error on each bin, output * the total error (unsquared) */ -void Q1D2::normalize(const MantidVec &normSum, const MantidVec &normError2, - MantidVec &counts, MantidVec &errors) const { +void Q1D2::normalize(const HistogramData::HistogramY &normSum, + const HistogramData::HistogramE &normError2, + HistogramData::HistogramY &counts, + HistogramData::HistogramE &errors) const { for (size_t k = 0; k < counts.size(); ++k) { // the normalisation is a = b/c where b = counts c =normalistion term const double c = normSum[k]; diff --git a/Framework/Algorithms/src/Q1DWeighted.cpp b/Framework/Algorithms/src/Q1DWeighted.cpp index 5f717b8dd3ff8a9210435008eee2eb1543763fd6..383f400fbe506ca99a4e09aefc0385a3e7285243 100644 --- a/Framework/Algorithms/src/Q1DWeighted.cpp +++ b/Framework/Algorithms/src/Q1DWeighted.cpp @@ -108,8 +108,8 @@ void Q1DWeighted::exec() { // Set the X vector for the output workspace outputWS->setBinEdges(0, XOut); - MantidVec &YOut = outputWS->dataY(0); - MantidVec &EOut = outputWS->dataE(0); + auto &YOut = outputWS->mutableY(0); + auto &EOut = outputWS->mutableE(0); const int numSpec = static_cast<int>(inputWS->getNumberHistograms()); @@ -190,9 +190,9 @@ void Q1DWeighted::exec() { continue; // Get the current spectrum for both input workspaces - const MantidVec &XIn = inputWS->readX(i); - const MantidVec &YIn = inputWS->readY(i); - const MantidVec &EIn = inputWS->readE(i); + auto &XIn = inputWS->x(i); + auto &YIn = inputWS->y(i); + auto &EIn = inputWS->e(i); // Each pixel is sub-divided in the number of pixels given as input // parameter (NPixelDivision) @@ -296,8 +296,8 @@ void Q1DWeighted::exec() { // Normalize wedges for (int iWedge = 0; iWedge < nWedges; iWedge++) { if (wedge_XNorm[iWedge][k] > 0) { - MantidVec &wedgeYOut = wedgeWorkspaces[iWedge]->dataY(0); - MantidVec &wedgeEOut = wedgeWorkspaces[iWedge]->dataE(0); + auto &wedgeYOut = wedgeWorkspaces[iWedge]->mutableY(0); + auto &wedgeEOut = wedgeWorkspaces[iWedge]->mutableE(0); wedgeYOut[k] += wedge_lambda_iq[iWedge][k] / wedge_XNorm[iWedge][k]; wedgeEOut[k] += wedge_lambda_iq_err[iWedge][k] / wedge_XNorm[iWedge][k] / wedge_XNorm[iWedge][k]; @@ -317,8 +317,8 @@ void Q1DWeighted::exec() { } for (int iWedge = 0; iWedge < nWedges; iWedge++) { for (int i = 0; i < sizeOut - 1; i++) { - MantidVec &wedgeYOut = wedgeWorkspaces[iWedge]->dataY(0); - MantidVec &wedgeEOut = wedgeWorkspaces[iWedge]->dataE(0); + auto &wedgeYOut = wedgeWorkspaces[iWedge]->mutableY(0); + auto &wedgeEOut = wedgeWorkspaces[iWedge]->mutableE(0); wedgeYOut[i] /= wedge_XNormLambda[iWedge][i]; wedgeEOut[i] = sqrt(wedgeEOut[i]) / wedge_XNormLambda[iWedge][i]; } diff --git a/Framework/Algorithms/src/Qhelper.cpp b/Framework/Algorithms/src/Qhelper.cpp index 9e8baea0854678cda8ca1dcfe8711ab2876f2720..ad35cb9231470d2727518528fa354ae6aa767152 100644 --- a/Framework/Algorithms/src/Qhelper.cpp +++ b/Framework/Algorithms/src/Qhelper.cpp @@ -37,9 +37,9 @@ void Qhelper::examineInput(API::MatrixWorkspace_const_sptr dataWS, // We require the same binning for the input workspace and the q resolution // workspace - auto reqX = dataWS->readX(0).cbegin(); - auto qResX = qResolution->readX(0).cbegin(); - for (; reqX != dataWS->readX(0).end(); ++reqX, ++qResX) { + auto reqX = dataWS->x(0).cbegin(); + auto qResX = qResolution->x(0).cbegin(); + for (; reqX != dataWS->x(0).end(); ++reqX, ++qResX) { if (*reqX != *qResX) { throw std::invalid_argument( "The QResolution needs to have the same binning as" @@ -72,13 +72,13 @@ void Qhelper::examineInput(API::MatrixWorkspace_const_sptr dataWS, throw std::invalid_argument( "The WavelengthAdj workspace must have one spectrum"); } - if (binAdj->readY(0).size() != dataWS->readY(0).size()) { + if (binAdj->y(0).size() != dataWS->y(0).size()) { throw std::invalid_argument("The WavelengthAdj workspace's bins must " "match those of the detector bank workspace"); } - auto reqX = dataWS->readX(0).cbegin(); - auto testX = binAdj->readX(0).cbegin(); - for (; reqX != dataWS->readX(0).cend(); ++reqX, ++testX) { + auto reqX = dataWS->x(0).cbegin(); + auto testX = binAdj->x(0).cbegin(); + for (; reqX != dataWS->x(0).cend(); ++reqX, ++testX) { if (*reqX != *testX) { throw std::invalid_argument("The WavelengthAdj workspace must have " "matching bins with the detector bank " @@ -116,7 +116,7 @@ void Qhelper::examineInput(API::MatrixWorkspace_const_sptr dataWS, size_t num_histograms = dataWS->getNumberHistograms(); const auto &spectrumInfo = dataWS->spectrumInfo(); for (size_t i = 0; i < num_histograms; i++) { - double adj = static_cast<double>(detectAdj->readY(i)[0]); + double adj = static_cast<double>(detectAdj->y(i)[0]); if (adj <= 0.0) { bool det_is_masked; if (!spectrumInfo.hasDetectors(i)) { @@ -166,7 +166,7 @@ size_t Qhelper::waveLengthCutOff(API::MatrixWorkspace_const_sptr dataWS, R = std::sqrt(R); const double WMin = l_WCutOver * (l_RCut - R); - const MantidVec &Xs = dataWS->readX(wsInd); + auto Xs = dataWS->x(wsInd); return std::lower_bound(Xs.begin(), Xs.end(), WMin) - Xs.begin(); } diff --git a/Framework/Algorithms/src/Qxy.cpp b/Framework/Algorithms/src/Qxy.cpp index 8f5389434b3d5e13f2e3270f4762f3adaabebf7d..e2b85d0c1d4f8d589706669251cea164dce3e1e8 100644 --- a/Framework/Algorithms/src/Qxy.cpp +++ b/Framework/Algorithms/src/Qxy.cpp @@ -1,19 +1,22 @@ -#include "MantidHistogramData/LinearGenerator.h" -#include "MantidAlgorithms/GravitySANSHelper.h" #include "MantidAlgorithms/Qxy.h" -#include "MantidAlgorithms/Qhelper.h" #include "MantidAPI/BinEdgeAxis.h" #include "MantidAPI/HistogramValidator.h" #include "MantidAPI/InstrumentValidator.h" #include "MantidAPI/SpectrumInfo.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/WorkspaceUnitValidator.h" +#include "MantidAlgorithms/GravitySANSHelper.h" +#include "MantidAlgorithms/Qhelper.h" #include "MantidGeometry/Instrument.h" +#include "MantidHistogramData/LinearGenerator.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/CompositeValidator.h" #include "MantidKernel/UnitFactory.h" #include "MantidKernel/VectorHelper.h" +#include <algorithm> +#include <cmath> + namespace Mantid { namespace Algorithms { @@ -109,7 +112,7 @@ void Qxy::exec() { WorkspaceFactory::Instance().create(outputWorkspace); // Copy the X values from the output workspace to the solidAngles one for (size_t i = 0; i < weights->getNumberHistograms(); ++i) - weights->setX(i, outputWorkspace->refX(0)); + weights->setSharedX(i, outputWorkspace->sharedX(0)); const size_t numSpec = inputWorkspace->getNumberHistograms(); const size_t numBins = inputWorkspace->blocksize(); @@ -148,7 +151,7 @@ void Qxy::exec() { // to calculate for const size_t wavStart = helper.waveLengthCutOff( inputWorkspace, getProperty("RadiusCut"), getProperty("WaveCut"), i); - if (wavStart >= inputWorkspace->readY(i).size()) { + if (wavStart >= inputWorkspace->y(i).size()) { // all the spectra in this detector are out of range continue; } @@ -163,11 +166,11 @@ void Qxy::exec() { double sinTheta = sin(inputWorkspace->detectorTwoTheta(*det) * 0.5); // Get references to the data for this spectrum - const MantidVec &X = inputWorkspace->readX(i); - const MantidVec &Y = inputWorkspace->readY(i); - const MantidVec &E = inputWorkspace->readE(i); + const auto &X = inputWorkspace->x(i); + const auto &Y = inputWorkspace->y(i); + const auto &E = inputWorkspace->e(i); - const MantidVec &axis = outputWorkspace->readX(0); + const auto &axis = outputWorkspace->x(0); // the solid angle of the detector as seen by the sample is used for // normalisation later on @@ -175,7 +178,7 @@ void Qxy::exec() { // some bins are masked completely or partially, the following vector will // contain the fractions - MantidVec maskFractions; + std::vector<double> maskFractions; if (inputWorkspace->hasMaskedBins(i)) { // go through the set and convert it to a vector const MatrixWorkspace::MaskList &mask = inputWorkspace->maskedBins(i); @@ -224,7 +227,7 @@ void Qxy::exec() { break; // Find the indices pointing to the place in the 2D array where this bin's // contents should go - const MantidVec::difference_type xIndex = + const auto xIndex = std::upper_bound(axis.begin(), axis.end(), Qx) - axis.begin() - 1; const int yIndex = static_cast<int>( std::upper_bound(axis.begin(), axis.end(), Qy) - axis.begin() - 1); @@ -232,8 +235,8 @@ void Qxy::exec() { // */ { // the data will be copied to this bin in the output array - double &outputBinY = outputWorkspace->dataY(yIndex)[xIndex]; - double &outputBinE = outputWorkspace->dataE(yIndex)[xIndex]; + double &outputBinY = outputWorkspace->mutableY(yIndex)[xIndex]; + double &outputBinE = outputWorkspace->mutableE(yIndex)[xIndex]; if (std::isnan(outputBinY)) { outputBinY = outputBinE = 0; @@ -261,30 +264,43 @@ void Qxy::exec() { // then the product of contributions which have errors, i.e. optional // pixelAdj and waveAdj contributions + auto &outWeightsY = weights->mutableY(yIndex); + auto &outWeightsE = weights->mutableE(yIndex); if (pixelAdj && waveAdj) { - weights->dataY(yIndex)[xIndex] += - weight * pixelAdj->readY(i)[0] * waveAdj->readY(0)[j]; - const double pixelYSq = pixelAdj->readY(i)[0] * pixelAdj->readY(i)[0]; - const double pixelESq = pixelAdj->readE(i)[0] * pixelAdj->readE(i)[0]; - const double waveYSq = waveAdj->readY(0)[j] * waveAdj->readY(0)[j]; - const double waveESq = waveAdj->readE(0)[j] * waveAdj->readE(0)[j]; + auto pixelY = pixelAdj->y(i)[0]; + auto pixelE = pixelAdj->e(i)[0]; + + auto waveY = waveAdj->y(0)[j]; + auto waveE = waveAdj->e(0)[j]; + + outWeightsY[xIndex] += weight * pixelY * waveY; + const double pixelYSq = pixelY * pixelY; + const double pixelESq = pixelE * pixelE; + const double waveYSq = waveY * waveY; + const double waveESq = waveE * waveE; // add product of errors from pixelAdj and waveAdj (note no error on // weight is assumed) - weights->dataE(yIndex)[xIndex] += + outWeightsE[xIndex] += weight * weight * (waveESq * pixelYSq + pixelESq * waveYSq); } else if (pixelAdj) { - weights->dataY(yIndex)[xIndex] += weight * pixelAdj->readY(i)[0]; - const double pixelE = weight * pixelAdj->readE(i)[0]; + auto pixelY = pixelAdj->y(i)[0]; + auto pixelE = pixelAdj->e(i)[0]; + + outWeightsY[xIndex] += weight * pixelY; + const double pixelESq = weight * pixelE; // add error from pixelAdj - weights->dataE(yIndex)[xIndex] += pixelE * pixelE; + outWeightsE[xIndex] += pixelESq * pixelESq; } else if (waveAdj) { - weights->dataY(yIndex)[xIndex] += weight * waveAdj->readY(0)[j]; - const double waveE = weight * waveAdj->readE(0)[j]; + auto waveY = waveAdj->y(0)[j]; + auto waveE = waveAdj->e(0)[j]; + + outWeightsY[xIndex] += weight * waveY; + const double waveESq = weight * waveE; // add error from waveAdj - weights->dataE(yIndex)[xIndex] += waveE * waveE; + outWeightsE[xIndex] += waveESq * waveESq; } else - weights->dataY(yIndex)[xIndex] += weight; + outWeightsY[xIndex] += weight; } } // loop over single spectrum @@ -298,9 +314,9 @@ void Qxy::exec() { // left to be executed here for computational efficiency size_t numHist = weights->getNumberHistograms(); for (size_t i = 0; i < numHist; i++) { - for (double &j : weights->dataE(i)) { - j = sqrt(j); - } + auto &weightsE = weights->mutableE(i); + std::transform(weightsE.cbegin(), weightsE.cend(), weightsE.begin(), + [&](double val) { return sqrt(val); }); } bool doOutputParts = getProperty("OutputParts"); @@ -309,9 +325,7 @@ void Qxy::exec() { MatrixWorkspace_sptr ws_sumOfCounts = WorkspaceFactory::Instance().create(outputWorkspace); for (size_t i = 0; i < ws_sumOfCounts->getNumberHistograms(); i++) { - ws_sumOfCounts->dataX(i) = outputWorkspace->dataX(i); - ws_sumOfCounts->dataY(i) = outputWorkspace->dataY(i); - ws_sumOfCounts->dataE(i) = outputWorkspace->dataE(i); + ws_sumOfCounts->setHistogram(i, outputWorkspace->histogram(i)); } helper.outputParts(this, ws_sumOfCounts, weights); @@ -326,7 +340,7 @@ void Qxy::exec() { const size_t nbins = outputWorkspace->blocksize(); int emptyBins = 0; for (size_t i = 0; i < nhist; ++i) { - const auto &yOut = outputWorkspace->readY(i); + auto &yOut = outputWorkspace->y(i); for (size_t j = 0; j < nbins; ++j) { if (yOut[j] < 1.0e-12) ++emptyBins; @@ -381,9 +395,12 @@ Qxy::setUpOutputWorkspace(API::MatrixWorkspace_const_sptr inputWorkspace) { // Fill the X vectors in the output workspace for (int i = 0; i < bins - 1; ++i) { outputWorkspace->setBinEdges(i, axis); + auto &y = outputWorkspace->mutableY(i); + auto &e = outputWorkspace->mutableE(i); + for (int j = 0; j < bins - j; ++j) { - outputWorkspace->dataY(i)[j] = std::numeric_limits<double>::quiet_NaN(); - outputWorkspace->dataE(i)[j] = std::numeric_limits<double>::quiet_NaN(); + y[j] = std::numeric_limits<double>::quiet_NaN(); + e[j] = std::numeric_limits<double>::quiet_NaN(); } } diff --git a/Framework/Algorithms/src/RRFMuon.cpp b/Framework/Algorithms/src/RRFMuon.cpp index fa46019a585595db8b4714b918b1060d4f5d491a..b206495e068f516c40777813331376370eb2614c 100644 --- a/Framework/Algorithms/src/RRFMuon.cpp +++ b/Framework/Algorithms/src/RRFMuon.cpp @@ -58,19 +58,19 @@ void RRFMuon::exec() { // Get phase double phase = getProperty("Phase"); // Get number of histograms - size_t nHisto = inputWs->getNumberHistograms(); + const size_t nHisto = inputWs->getNumberHistograms(); if (nHisto != 2) { throw std::runtime_error("Invalid number of spectra in input workspace"); } // Set number of data points - size_t nData = inputWs->blocksize(); + const size_t nData = inputWs->blocksize(); // Compute the RRF polarization const double twoPiFreq = 2. * M_PI * freq * factor; - MantidVec time = inputWs->readX(0); // X axis: time - MantidVec labRe = inputWs->readY(0); // Lab-frame polarization (real part) - MantidVec labIm = - inputWs->readY(1); // Lab-frame polarization (imaginary part) + const auto &time = inputWs->x(0); // X axis: time + const auto &labRe = inputWs->y(0); // Lab-frame polarization (real part) + const auto &labIm = inputWs->y(1); // Lab-frame polarization (imaginary part) + MantidVec rrfRe(nData), rrfIm(nData); // Rotating Reference frame (RRF) polarizations for (size_t t = 0; t < nData; t++) { @@ -90,12 +90,12 @@ void RRFMuon::exec() { // Put results into output workspace // Real RRF polarization outputWs->getSpectrum(0).setSpectrumNo(1); - outputWs->dataX(0) = inputWs->readX(0); - outputWs->dataY(0) = rrfRe; + outputWs->setSharedX(0, inputWs->sharedX(0)); + outputWs->mutableY(0) = rrfRe; // Imaginary RRF polarization outputWs->getSpectrum(1).setSpectrumNo(2); - outputWs->dataX(1) = inputWs->readX(1); - outputWs->dataY(1) = rrfIm; + outputWs->setSharedX(1, inputWs->sharedX(1)); + outputWs->mutableY(1) = rrfIm; // Set output workspace setProperty("OutputWorkspace", outputWs); diff --git a/Framework/Algorithms/src/RadiusSum.cpp b/Framework/Algorithms/src/RadiusSum.cpp index 35a9e85127cd834d702862e948c58567a17257d9..8bdd59379ecce72d43b1e929cbbcd61d968c046f 100644 --- a/Framework/Algorithms/src/RadiusSum.cpp +++ b/Framework/Algorithms/src/RadiusSum.cpp @@ -1,16 +1,18 @@ #include "MantidAlgorithms/RadiusSum.h" -#include "MantidAPI/NumericAxis.h" #include "MantidAPI/MatrixWorkspace.h" +#include "MantidAPI/NumericAxis.h" #include "MantidAPI/SpectrumInfo.h" #include "MantidAPI/WorkspaceFactory.h" -#include "MantidKernel/VisibleWhenProperty.h" +#include "MantidGeometry/IDetector.h" +#include "MantidGeometry/IObjComponent.h" #include "MantidKernel/ArrayLengthValidator.h" #include "MantidKernel/ArrayProperty.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/Unit.h" #include "MantidKernel/UnitFactory.h" -#include "MantidGeometry/IDetector.h" -#include "MantidGeometry/IObjComponent.h" +#include "MantidKernel/VisibleWhenProperty.h" + +#include "MantidHistogramData/LinearGenerator.h" #include <boost/foreach.hpp> @@ -109,6 +111,7 @@ std::vector<double> RadiusSum::processInstrumentRadiusSum() { g_log.debug() << "For every detector in the image get its position " << " and sum up all the counts inside the related spectrum\n"; + const auto &spectrumInfo = inputWS->spectrumInfo(); for (size_t i = 0; i < inputWS->getNumberHistograms(); i++) { if (!spectrumInfo.hasDetectors(i)) { @@ -125,8 +128,8 @@ std::vector<double> RadiusSum::processInstrumentRadiusSum() { if (bin_n < 0) continue; // not in the limits of min_radius and max_radius - auto &refY = inputWS->getSpectrum(i).readY(); - accumulator[bin_n] += std::accumulate(refY.begin(), refY.end(), 0.0); + auto &refY = inputWS->getSpectrum(i).y(); + accumulator[bin_n] += std::accumulate(refY.cbegin(), refY.cend(), 0.0); } return accumulator; } @@ -149,23 +152,14 @@ std::vector<double> RadiusSum::processNumericImageRadiusSum() { // or the center of the bin, if it is a histogram. g_log.debug() << "Define the X positions of the pixels\n"; - auto &refX = inputWS->getSpectrum(0).readX(); - auto &refY = inputWS->getSpectrum(0).readY(); - std::vector<double> x_pos(refY.size()); - - if (refY.size() == refX.size()) { // non-histogram workspace X has n values - std::copy(refX.begin(), refX.end(), x_pos.begin()); - } else { // histogram based workspace X has n+1 values - for (size_t ind = 0; ind < x_pos.size(); ind++) - x_pos[ind] = (refX[ind] + refX[ind + 1]) / 2.0; - } + auto x_pos = inputWS->points(0); g_log.debug() << "For every pixel define its bin position and sum them up\n"; // for each row in the image for (size_t i = 0; i < inputWS->getNumberHistograms(); i++) { // pixel values - auto &refY = inputWS->getSpectrum(i).readY(); + auto &refY = inputWS->getSpectrum(i).y(); // for every pixel for (size_t j = 0; j < refY.size(); j++) { @@ -302,7 +296,7 @@ RadiusSum::getBoundariesOfNumericImage(API::MatrixWorkspace_sptr inWS) { // horizontal axis // get the pixel position in the horizontal axis from the middle of the image. - const MantidVec &refX = inWS->readX(inWS->getNumberHistograms() / 2); + const auto &refX = inWS->x(inWS->getNumberHistograms() / 2); double min_x, max_x; @@ -554,7 +548,7 @@ double RadiusSum::getMinBinSizeForNumericImage(API::MatrixWorkspace_sptr inWS) { // The minimum bin size is the smallest value between this two values. std::vector<double> boundaries = getBoundariesOfNumericImage(inWS); - const MantidVec &refX = inWS->readX(inputWS->getNumberHistograms() / 2); + const auto &refX = inWS->x(inputWS->getNumberHistograms() / 2); int nX = static_cast<int>(refX.size()); int nY = static_cast<int>(inWS->getAxis(1)->length()); @@ -620,16 +614,14 @@ void RadiusSum::setUpOutputWorkspace(std::vector<double> &values) { inputWS, 1, values.size() + 1, values.size()); g_log.debug() << "Set the data\n"; - MantidVec &refY = outputWS->dataY(0); - std::copy(values.begin(), values.end(), refY.begin()); + outputWS->mutableY(0) = values; g_log.debug() << "Set the bins limits\n"; - MantidVec &refX = outputWS->dataX(0); - double bin_size = (max_radius - min_radius) / num_bins; - for (int i = 0; i < (static_cast<int>(refX.size())) - 1; i++) - refX[i] = min_radius + i * bin_size; - refX.back() = max_radius; + auto xSize = outputWS->mutableX(0).size(); + double bin_size = (max_radius - min_radius) / num_bins; + outputWS->setBinEdges(0, xSize, + HistogramData::LinearGenerator(min_radius, bin_size)); // configure the axis: // for numeric images, the axis are the same as the input workspace, and are @@ -638,7 +630,7 @@ void RadiusSum::setUpOutputWorkspace(std::vector<double> &values) { // for instrument related, the axis Y (1) continues to be the same. // it is necessary to change only the axis X. We have to change it to radius. if (inputWorkspaceHasInstrumentAssociated(inputWS)) { - API::Axis *const horizontal = new API::NumericAxis(refX.size()); + API::Axis *const horizontal = new API::NumericAxis(xSize); auto labelX = UnitFactory::Instance().create("Label"); boost::dynamic_pointer_cast<Units::Label>(labelX)->setLabel("Radius"); horizontal->unit() = labelX; diff --git a/Framework/Algorithms/src/RayTracerTester.cpp b/Framework/Algorithms/src/RayTracerTester.cpp index 997223e46273a462e44af466579f08d7e4ac6cf2..1b910bcfdf302c7286c682f0ec0014aa20f2b8b0 100644 --- a/Framework/Algorithms/src/RayTracerTester.cpp +++ b/Framework/Algorithms/src/RayTracerTester.cpp @@ -50,7 +50,7 @@ void RayTracerTester::exec() { detid2index_map detTowi = ws->getDetectorIDToWorkspaceIndexMap(); for (size_t i = 0; i < ws->getNumberHistograms(); i++) - ws->dataY(i)[0] = 0.0; + ws->mutableY(i)[0] = 0.0; int NumAzimuth = getProperty("NumAzimuth"); int NumZenith = getProperty("NumZenith"); @@ -72,7 +72,7 @@ void RayTracerTester::exec() { if (det) { size_t wi = detTowi[det->getID()]; g_log.information() << "Found detector " << det->getID() << '\n'; - ws->dataY(wi)[0] = double(int(az * 57.3) * 1000 + int(iz)); + ws->mutableY(wi)[0] = double(int(az * 57.3) * 1000 + int(iz)); } } } diff --git a/Framework/Algorithms/src/ReadGroupsFromFile.cpp b/Framework/Algorithms/src/ReadGroupsFromFile.cpp index 5d3069371d4667e090820bddb7caadc38b95fe6c..07880d99ef21d9275996322dbd90c1313005a054 100644 --- a/Framework/Algorithms/src/ReadGroupsFromFile.cpp +++ b/Framework/Algorithms/src/ReadGroupsFromFile.cpp @@ -12,8 +12,8 @@ #include "MantidKernel/ListValidator.h" // Poco XML Headers for Grouping File -#include <Poco/DOM/Document.h> #include <Poco/DOM/DOMParser.h> +#include <Poco/DOM/Document.h> #include <Poco/DOM/Element.h> #include <Poco/DOM/NodeList.h> @@ -116,23 +116,23 @@ void ReadGroupsFromFile::exec() { const auto &dets = spec.getDetectorIDs(); if (dets.empty()) // Nothing { - spec.dataY()[0] = 0.0; + spec.mutableY()[0] = 0.0; continue; } // Find the first detector ID in the list calmap::const_iterator it = calibration.find(*dets.begin()); if (it == calibration.end()) // Could not find the detector { - spec.dataY()[0] = 0.0; + spec.mutableY()[0] = 0.0; continue; } if (showunselected) { if (((*it).second).second == 0) - spec.dataY()[0] = 0.0; + spec.mutableY()[0] = 0.0; else - spec.dataY()[0] = static_cast<double>(((*it).second).first); + spec.mutableY()[0] = static_cast<double>(((*it).second).first); } else - spec.dataY()[0] = static_cast<double>(((*it).second).first); + spec.mutableY()[0] = static_cast<double>(((*it).second).first); if (!success) success = true; // At least one detector is found in the cal file } diff --git a/Framework/Algorithms/src/RealFFT.cpp b/Framework/Algorithms/src/RealFFT.cpp index f3e7c97fb7cd33455dd8b3549bacfaeb9cef939b..134202698ac21b4292c1029b5222d0797063879a 100644 --- a/Framework/Algorithms/src/RealFFT.cpp +++ b/Framework/Algorithms/src/RealFFT.cpp @@ -9,21 +9,23 @@ #include <boost/shared_array.hpp> #include <gsl/gsl_errno.h> -#include <gsl/gsl_fft_real.h> #include <gsl/gsl_fft_halfcomplex.h> +#include <gsl/gsl_fft_real.h> #define REAL(z, i) ((z)[2 * (i)]) #define IMAG(z, i) ((z)[2 * (i) + 1]) -#include <sstream> -#include <numeric> #include <algorithm> -#include <functional> #include <cmath> +#include <functional> +#include <numeric> +#include <sstream> #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" +#include "MantidHistogramData/LinearGenerator.h" + namespace Mantid { namespace Algorithms { @@ -71,7 +73,7 @@ void RealFFT::exec() { int spec = (transform == "Forward") ? getProperty("WorkspaceIndex") : 0; - const MantidVec &X = inWS->readX(spec); + const auto &X = inWS->x(spec); int ySize = static_cast<int>(inWS->blocksize()); if (spec >= ySize) @@ -106,8 +108,9 @@ void RealFFT::exec() { gsl_fft_real_workspace *workspace = gsl_fft_real_workspace_alloc(ySize); boost::shared_array<double> data(new double[2 * ySize]); + auto &yData = inWS->mutableY(spec); for (int i = 0; i < ySize; i++) { - data[i] = inWS->dataY(spec)[i]; + data[i] = yData[i]; } gsl_fft_real_wavetable *wavetable = gsl_fft_real_wavetable_alloc(ySize); @@ -115,22 +118,24 @@ void RealFFT::exec() { gsl_fft_real_wavetable_free(wavetable); gsl_fft_real_workspace_free(workspace); + auto &x = outWS->mutableX(0); + auto &y1 = outWS->mutableY(0); + auto &y2 = outWS->mutableY(1); + auto &y3 = outWS->mutableY(2); for (int i = 0; i < yOutSize; i++) { int j = i * 2; - outWS->dataX(0)[i] = df * i; + x[i] = df * i; double re = i != 0 ? data[j - 1] : data[0]; double im = (i != 0 && (odd || i != yOutSize - 1)) ? data[j] : 0; - outWS->dataY(0)[i] = re * dx; // real part - outWS->dataY(1)[i] = im * dx; // imaginary part - outWS->dataY(2)[i] = dx * sqrt(re * re + im * im); // modulus + y1[i] = re * dx; // real part + y2[i] = im * dx; // imaginary part + y3[i] = dx * sqrt(re * re + im * im); // modulus } if (inWS->isHistogramData()) { - outWS->dataX(0)[yOutSize] = outWS->dataX(0)[yOutSize - 1] + df; + outWS->mutableX(0)[yOutSize] = outWS->mutableX(0)[yOutSize - 1] + df; } - outWS->dataX(1) = outWS->dataX(0); - outWS->dataX(2) = outWS->dataX(0); - // outWS->getAxis(1)->spectraNo(0)=inWS->getAxis(1)->spectraNo(spec); - // outWS->getAxis(1)->spectraNo(1)=inWS->getAxis(1)->spectraNo(spec); + outWS->setSharedX(1, outWS->sharedX(0)); + outWS->setSharedX(2, outWS->sharedX(0)); } else // Backward { @@ -139,7 +144,7 @@ void RealFFT::exec() { "The input workspace must have at least 2 spectra."); int yOutSize = (ySize - 1) * 2; - if (inWS->readY(1).back() != 0.0) + if (inWS->y(1).back() != 0.0) yOutSize++; int xOutSize = inWS->isHistogramData() ? yOutSize + 1 : yOutSize; bool odd = yOutSize % 2 != 0; @@ -152,35 +157,38 @@ void RealFFT::exec() { outWS->replaceAxis(1, tAxis); gsl_fft_real_workspace *workspace = gsl_fft_real_workspace_alloc(yOutSize); - boost::shared_array<double> data(new double[yOutSize]); + auto &xData = outWS->mutableX(0); + auto &yData = outWS->mutableY(0); + auto &y0 = inWS->mutableY(0); + auto &y1 = inWS->mutableY(1); for (int i = 0; i < ySize; i++) { int j = i * 2; - outWS->dataX(0)[i] = df * i; + xData[i] = df * i; if (i != 0) { - data[j - 1] = inWS->dataY(0)[i]; + yData[j - 1] = y0[i]; if (odd || i != ySize - 1) { - data[j] = inWS->dataY(1)[i]; + yData[j] = y1[i]; } } else { - data[0] = inWS->dataY(0)[0]; + yData[0] = y0[0]; } } gsl_fft_halfcomplex_wavetable *wavetable = gsl_fft_halfcomplex_wavetable_alloc(yOutSize); - gsl_fft_halfcomplex_inverse(data.get(), 1, yOutSize, wavetable, workspace); + + // &(yData[0]) because gsl func wants non const double data[] + gsl_fft_halfcomplex_inverse(&(yData[0]), 1, yOutSize, wavetable, workspace); gsl_fft_halfcomplex_wavetable_free(wavetable); gsl_fft_real_workspace_free(workspace); - for (int i = 0; i < yOutSize; i++) { - double x = df * i; - outWS->dataX(0)[i] = x; - outWS->dataY(0)[i] = data[i] / df; - } + std::generate(xData.begin(), xData.end(), + HistogramData::LinearGenerator(0, df)); + yData /= df; + if (outWS->isHistogramData()) - outWS->dataX(0)[yOutSize] = outWS->dataX(0)[yOutSize - 1] + df; - // outWS->getAxis(1)->spectraNo(0)=inWS->getAxis(1)->spectraNo(spec); + outWS->mutableX(0)[yOutSize] = outWS->mutableX(0)[yOutSize - 1] + df; } setProperty("OutputWorkspace", outWS); diff --git a/Framework/Algorithms/src/Rebin.cpp b/Framework/Algorithms/src/Rebin.cpp index 474a29507493d61ff950fcc179a1950fc7b859f6..64388219cf672609ce49b1fa75e91050dc9d1845 100644 --- a/Framework/Algorithms/src/Rebin.cpp +++ b/Framework/Algorithms/src/Rebin.cpp @@ -179,7 +179,7 @@ void Rebin::exec() { Progress prog(this, 0.0, 1.0, histnumber); // Go through all the histograms and set the data - PARALLEL_FOR3(inputWS, eventInputWS, outputWS) + PARALLEL_FOR_IF(Kernel::threadSafe(*inputWS, *outputWS)) for (int i = 0; i < histnumber; ++i) { PARALLEL_START_INTERUPT_REGION diff --git a/Framework/Algorithms/src/Rebin2D.cpp b/Framework/Algorithms/src/Rebin2D.cpp index f1a38bd712b34dd0db9fb87f34706c422c88e7db..96b916eecd3ee6157cba4ba8de48adbdd64b2bdb 100644 --- a/Framework/Algorithms/src/Rebin2D.cpp +++ b/Framework/Algorithms/src/Rebin2D.cpp @@ -5,14 +5,14 @@ #include "MantidAPI/BinEdgeAxis.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/WorkspaceProperty.h" -#include "MantidDataObjects/RebinnedOutput.h" #include "MantidDataObjects/FractionalRebinning.h" +#include "MantidDataObjects/RebinnedOutput.h" #include "MantidGeometry/Math/ConvexPolygon.h" #include "MantidGeometry/Math/PolygonIntersection.h" #include "MantidGeometry/Math/Quadrilateral.h" #include "MantidKernel/ArrayProperty.h" -#include "MantidKernel/RebinParamsValidator.h" #include "MantidKernel/PropertyWithValue.h" +#include "MantidKernel/RebinParamsValidator.h" #include "MantidKernel/VectorHelper.h" namespace Mantid { @@ -25,6 +25,7 @@ using namespace API; using namespace DataObjects; using namespace Geometry; using Kernel::V2D; +using namespace Mantid::HistogramData; //-------------------------------------------------------------------------- // Private methods @@ -81,7 +82,7 @@ void Rebin2D::exec() { "If it is a spectra axis try running ConvertSpectrumAxis first."); } - const MantidVec &oldXEdges = inputWS->readX(0); + const auto &oldXEdges = inputWS->x(0); const size_t numXBins = inputWS->blocksize(); const size_t numYBins = inputWS->getNumberHistograms(); std::vector<double> oldYEdges; @@ -96,13 +97,14 @@ void Rebin2D::exec() { } // Output grid and workspace. Fills in the new X and Y bin vectors - MantidVecPtr newXBins; - MantidVec newYBins; + // MantidVecPtr newXBins; + BinEdges newXBins(oldXEdges.size()); + BinEdges newYBins(oldXEdges.size()); // Flag for using a RebinnedOutput workspace bool useFractionalArea = getProperty("UseFractionalArea"); - MatrixWorkspace_sptr outputWS = createOutputWorkspace( - inputWS, newXBins.access(), newYBins, useFractionalArea); + MatrixWorkspace_sptr outputWS = + createOutputWorkspace(inputWS, newXBins, newYBins, useFractionalArea); if (useFractionalArea && !boost::dynamic_pointer_cast<RebinnedOutput>(outputWS)) { g_log.warning("Fractional area tracking requires the input workspace to " @@ -113,8 +115,7 @@ void Rebin2D::exec() { } // Progress reports & cancellation - const size_t nreports(static_cast<size_t>(inputWS->getNumberHistograms() * - inputWS->blocksize())); + const size_t nreports(static_cast<size_t>(numYBins)); m_progress = boost::shared_ptr<API::Progress>( new API::Progress(this, 0.0, 1.0, nreports)); @@ -124,10 +125,10 @@ void Rebin2D::exec() { { PARALLEL_START_INTERUPT_REGION + m_progress->report("Computing polygon intersections"); const double vlo = oldYEdges[i]; const double vhi = oldYEdges[i + 1]; for (size_t j = 0; j < numXBins; ++j) { - m_progress->report("Computing polygon intersections"); // For each input polygon test where it intersects with // the output grid and assign the appropriate weights of Y/E const double x_j = oldXEdges[j]; @@ -135,11 +136,12 @@ void Rebin2D::exec() { Quadrilateral inputQ = Quadrilateral(x_j, x_jp1, vlo, vhi); if (!useFractionalArea) { FractionalRebinning::rebinToOutput(inputQ, inputWS, i, j, outputWS, - newYBins); + newYBins.rawData()); } else { FractionalRebinning::rebinToFractionalOutput( inputQ, inputWS, i, j, - boost::dynamic_pointer_cast<RebinnedOutput>(outputWS), newYBins); + boost::dynamic_pointer_cast<RebinnedOutput>(outputWS), + newYBins.rawData()); } } @@ -176,14 +178,16 @@ void Rebin2D::exec() { */ MatrixWorkspace_sptr Rebin2D::createOutputWorkspace(MatrixWorkspace_const_sptr parent, - MantidVec &newXBins, MantidVec &newYBins, + BinEdges &newXBins, BinEdges &newYBins, const bool useFractionalArea) const { using Kernel::VectorHelper::createAxisFromRebinParams; + + auto &newY = newYBins.mutableRawData(); // First create the two sets of bin boundaries - const int newXSize = - createAxisFromRebinParams(getProperty("Axis1Binning"), newXBins); + const int newXSize = createAxisFromRebinParams(getProperty("Axis1Binning"), + newXBins.mutableRawData()); const int newYSize = - createAxisFromRebinParams(getProperty("Axis2Binning"), newYBins); + createAxisFromRebinParams(getProperty("Axis2Binning"), newY); // and now the workspace MatrixWorkspace_sptr outputWS; if (!useFractionalArea) { @@ -194,16 +198,15 @@ Rebin2D::createOutputWorkspace(MatrixWorkspace_const_sptr parent, "RebinnedOutput", newYSize - 1, newXSize, newXSize - 1); WorkspaceFactory::Instance().initializeFromParent(parent, outputWS, true); } - Axis *const verticalAxis = new BinEdgeAxis(newYBins); + Axis *const verticalAxis = new BinEdgeAxis(newY); // Meta data verticalAxis->unit() = parent->getAxis(1)->unit(); verticalAxis->title() = parent->getAxis(1)->title(); outputWS->replaceAxis(1, verticalAxis); - HistogramData::BinEdges binEdges(newXBins); // Now set the axis values for (size_t i = 0; i < static_cast<size_t>(newYSize - 1); ++i) { - outputWS->setBinEdges(i, binEdges); + outputWS->setBinEdges(i, newXBins); } return outputWS; diff --git a/Framework/Algorithms/src/ReflectometryReductionOne.cpp b/Framework/Algorithms/src/ReflectometryReductionOne.cpp index 2bf8ae662eb9a01a93c65d57e035a362530ca725..b63524e8dedc9d12b073e0cdff37594c64e5b54a 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOne.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOne.cpp @@ -131,10 +131,6 @@ void ReflectometryReductionOne::init() { boost::make_shared<StringListValidator>(propOptions), "The type of analysis to perform. Point detector or multi detector."); - declareProperty(make_unique<ArrayProperty<int>>("RegionOfInterest"), - "Indices of the spectra a pair (lower, upper) that mark the " - "ranges that correspond to the region of interest (reflected " - "beam) in multi-detector mode."); declareProperty(make_unique<ArrayProperty<int>>("RegionOfDirectBeam"), "Indices of the spectra a pair (lower, upper) that mark the " "ranges that correspond to the direct beam in multi-detector " @@ -485,25 +481,6 @@ ReflectometryReductionOne::getDetectorComponent( return searchResult; } -/** -* Sum spectra over a specified range. -* @param inWS -* @param startIndex -* @param endIndex -* @return Workspace with spectra summed over the specified range. -*/ -MatrixWorkspace_sptr ReflectometryReductionOne::sumSpectraOverRange( - MatrixWorkspace_sptr inWS, const int startIndex, const int endIndex) { - auto sumSpectra = this->createChildAlgorithm("SumSpectra"); - sumSpectra->initialize(); - sumSpectra->setProperty("InputWorkspace", inWS); - sumSpectra->setProperty("StartWorkspaceIndex", startIndex); - sumSpectra->setProperty("EndWorkspaceIndex", endIndex); - sumSpectra->execute(); - MatrixWorkspace_sptr outWS = sumSpectra->getProperty("OutputWorkspace"); - return outWS; -} - //---------------------------------------------------------------------------------------------- /** Execute the algorithm. */ diff --git a/Framework/Algorithms/src/SANSDirectBeamScaling.cpp b/Framework/Algorithms/src/SANSDirectBeamScaling.cpp index ac6abce7de15d62ef04150440e0020d4d1eaeab1..f485e744347519bcd696783ae8fce1e7edfc93d6 100644 --- a/Framework/Algorithms/src/SANSDirectBeamScaling.cpp +++ b/Framework/Algorithms/src/SANSDirectBeamScaling.cpp @@ -83,11 +83,11 @@ void SANSDirectBeamScaling::exec() { Progress progress(this, 0.0, 1.0, numHists); // Number of X bins - const int64_t xLength = inputWS->readY(0).size(); + const int64_t xLength = inputWS->y(0).size(); // Monitor counts double monitor = 0.0; - const MantidVec &MonIn = inputWS->readY(index[0]); + const auto &MonIn = inputWS->y(index[0]); for (int64_t j = 0; j < xLength; j++) monitor += MonIn[j]; @@ -111,8 +111,8 @@ void SANSDirectBeamScaling::exec() { if (spectrumInfo.isMonitor(i) || spectrumInfo.isMasked(i)) continue; - const MantidVec &YIn = inputWS->readY(i); - const MantidVec &EIn = inputWS->readE(i); + const auto &YIn = inputWS->y(i); + const auto &EIn = inputWS->e(i); // Sum up all the counts V3D pos = spectrumInfo.position(i) - V3D(sourcePos.X(), sourcePos.Y(), 0.0); diff --git a/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrection.cpp b/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrection.cpp index 3792bcd460a606fc91a7bb2ce03bc7629ee64e87..6fc6b35dd61ccec6edcdcc29a73fcebd2f03a9bb 100644 --- a/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrection.cpp +++ b/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrection.cpp @@ -105,9 +105,6 @@ void MayersSampleCorrection::exec() { for (int64_t i = 0; i < static_cast<int64_t>(nhist); ++i) { PARALLEL_START_INTERUPT_REGION - // Copy the X values over - const auto &inX = inputWS->readX(i); - outputWS->dataX(i) = inX; IDetector_const_sptr det; try { det = inputWS->getDetector(i); @@ -128,9 +125,9 @@ void MayersSampleCorrection::exec() { params.sigmaSc = sampleMaterial.totalScatterXSection(); params.cylRadius = radius; params.cylHeight = height; - MayersSampleCorrectionStrategy correction(params, inX, inputWS->readY(i), - inputWS->readE(i)); - correction.apply(outputWS->dataY(i), outputWS->dataE(i)); + + MayersSampleCorrectionStrategy correction(params, inputWS->histogram(i)); + outputWS->setHistogram(i, correction.getCorrectedHisto()); prog.report(); PARALLEL_END_INTERUPT_REGION diff --git a/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrectionStrategy.cpp b/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrectionStrategy.cpp index ca0a48439c72be9df8339b800fb6db889b6eba18..b04e7147902a9bf3f9639951c8787643fbd63bbc 100644 --- a/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrectionStrategy.cpp +++ b/Framework/Algorithms/src/SampleCorrections/MayersSampleCorrectionStrategy.cpp @@ -2,10 +2,10 @@ // Includes //----------------------------------------------------------------------------- #include "MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h" -#include "MantidKernel/MersenneTwister.h" -#include "MantidKernel/Statistics.h" #include "MantidKernel/Math/ChebyshevPolyFit.h" #include "MantidKernel/Math/Distributions/ChebyshevSeries.h" +#include "MantidKernel/MersenneTwister.h" +#include "MantidKernel/Statistics.h" #include <cassert> #include <cmath> @@ -73,23 +73,18 @@ namespace Algorithms { /** * Constructor * @param params Defines the required parameters for the correction - * @param tof The TOF values corresponding to the signals to correct. - * Number of tof values must match number of signal/error or be 1 greater - * @param sigIn Values of the signal that will be corrected - * @param errIn Values of the errors that will be corrected + * @param inputHist A histogram containing the TOF values corresponding + * to the values to be corrected. */ MayersSampleCorrectionStrategy::MayersSampleCorrectionStrategy( MayersSampleCorrectionStrategy::Parameters params, - const std::vector<double> &tof, const std::vector<double> &sigIn, - const std::vector<double> &errIn) - : m_pars(params), m_tof(tof), m_sigin(sigIn), m_errin(errIn), - m_histogram(tof.size() == sigIn.size() + 1), - m_muRrange(calculateMuRange()), m_rng(new MersenneTwister(1)) { - // Sanity check - assert(sigIn.size() == tof.size() || sigIn.size() == tof.size() - 1); - assert(errIn.size() == tof.size() || sigIn.size() == tof.size() - 1); + const Mantid::HistogramData::Histogram &inputHist) + : m_pars(params), m_histogram(inputHist), m_tofVals(inputHist.points()), + m_histoYSize(inputHist.y().size()), m_muRrange(calculateMuRange()), + m_rng(new MersenneTwister(1)) { - if (!(m_tof.front() < m_tof.back())) { + const auto &xVals = m_histogram.x(); + if (!(xVals.front() < xVals.back())) { throw std::invalid_argument( "TOF values are expected to be monotonically increasing"); } @@ -104,15 +99,11 @@ MayersSampleCorrectionStrategy::~MayersSampleCorrectionStrategy() = default; * Correct the data for absorption and multiple scattering effects. Allows * both histogram or point data. For histogram the TOF is taken to be * the mid point of a bin - * @param sigOut Signal values to correct [In/Out] - * @param errOut Error values to correct [In/Out] + * + * @return A histogram containing corrected values */ -void MayersSampleCorrectionStrategy::apply(std::vector<double> &sigOut, - std::vector<double> &errOut) { - const size_t nsig(m_sigin.size()); - // Sanity check - assert(sigOut.size() == m_sigin.size()); - assert(errOut.size() == m_errin.size()); +Mantid::HistogramData::Histogram +MayersSampleCorrectionStrategy::getCorrectedHisto() { // Temporary storage std::vector<double> xmur(N_MUR_PTS + 1, 0.0), @@ -162,8 +153,13 @@ void MayersSampleCorrectionStrategy::apply(std::vector<double> &sigOut, const double rns = (vol * 1e6) * (m_pars.rho * 1e24) * 1e-22; ChebyshevSeries chebyPoly(N_POLY_ORDER); - for (size_t i = 0; i < nsig; ++i) { - const double sigt = sigmaTotal(flightPath, tof(i)); + auto outputHistogram = m_histogram; + + auto &sigOut = outputHistogram.mutableY(); + auto &errOut = outputHistogram.mutableE(); + + for (size_t i = 0; i < m_histoYSize; ++i) { + const double sigt = sigmaTotal(flightPath, m_tofVals[i]); const double rmu = muR(sigt); // Varies between [-1,+1] const double xcap = ((rmu - muMin) - (muMax - rmu)) / (muMax - muMin); @@ -174,10 +170,11 @@ void MayersSampleCorrectionStrategy::apply(std::vector<double> &sigOut, corrfact *= (1.0 - beta) / rns; } // apply correction - const double yin(m_sigin[i]), ein(m_errin[i]); + const double yin(m_histogram.y()[i]), ein(m_histogram.e()[i]); sigOut[i] = yin * corrfact; errOut[i] = sigOut[i] * ein / yin; } + return outputHistogram; } /** @@ -290,7 +287,7 @@ MayersSampleCorrectionStrategy::calculateMS(const size_t irp, const double muR, std::pair<double, double> MayersSampleCorrectionStrategy::calculateMuRange() const { const double flightPath(m_pars.l1 + m_pars.l2); - const double tmin(tof(0)), tmax(tof(m_sigin.size() - 1)); + const double tmin(m_tofVals[0]), tmax(m_tofVals[m_histoYSize - 1]); return std::make_pair(muR(flightPath, tmin), muR(flightPath, tmax)); } @@ -330,17 +327,6 @@ double MayersSampleCorrectionStrategy::sigmaTotal(const double flightPath, return sigabs + m_pars.sigmaSc; } -/** - * Return the TOF for the given index of the signal value, taking into account - * if we have a histogram. Histograms will use the mid point of the bin - * as the TOF value. Note that there is no range check for the index. - * @param i Index of the signal value - * @return The associated TOF value - */ -double MayersSampleCorrectionStrategy::tof(const size_t i) const { - return m_histogram ? 0.5 * (m_tof[i] + m_tof[i + 1]) : m_tof[i]; -} - /** * (Re-)seed the random number generator * @param seed Seed value for the random number generator diff --git a/Framework/Algorithms/src/SetUncertainties.cpp b/Framework/Algorithms/src/SetUncertainties.cpp index c50c15891b02cee9508a39646767ded87f85f969..8604e10cb61341403f1d935655c6f08005491500 100644 --- a/Framework/Algorithms/src/SetUncertainties.cpp +++ b/Framework/Algorithms/src/SetUncertainties.cpp @@ -116,25 +116,24 @@ void SetUncertainties::exec() { PARALLEL_START_INTERUPT_REGION // copy the X/Y - outputWorkspace->setX(i, inputWorkspace->refX(i)); - outputWorkspace->dataY(i) = inputWorkspace->readY(i); + outputWorkspace->setSharedX(i, inputWorkspace->sharedX(i)); + outputWorkspace->setSharedY(i, inputWorkspace->sharedY(i)); // copy the E or set to zero depending on the mode if (errorType.compare(ONE_IF_ZERO) == 0) { - outputWorkspace->dataE(i) = inputWorkspace->readE(i); + outputWorkspace->setSharedE(i, inputWorkspace->sharedE(i)); } else { - outputWorkspace->dataE(i) = - std::vector<double>(inputWorkspace->readE(i).size(), 0.); + outputWorkspace->mutableE(i) = 0.0; } // ZERO mode doesn't calculate anything further if ((!zeroError) && (!isMasked(inputWorkspace, i))) { - MantidVec &E = outputWorkspace->dataE(i); + auto &E = outputWorkspace->mutableE(i); if (takeSqrt) { - const MantidVec &Y = outputWorkspace->readY(i); + const auto &Y = outputWorkspace->y(i); std::transform(Y.begin(), Y.end(), E.begin(), sqrterror(resetOne ? 1. : 0.)); } else { - std::for_each(E.begin(), E.end(), resetzeroerror(1.)); + std::transform(E.begin(), E.end(), E.begin(), resetzeroerror(1.)); } } diff --git a/Framework/Algorithms/src/SmoothData.cpp b/Framework/Algorithms/src/SmoothData.cpp index 9d29d867e13152106b54091926e0a56565677705..83c4d93f2fd211d5a70f8c5ee8a853314bb945ee 100644 --- a/Framework/Algorithms/src/SmoothData.cpp +++ b/Framework/Algorithms/src/SmoothData.cpp @@ -92,19 +92,19 @@ void SmoothData::exec() { // Copy the X data over. Preserves data sharing if present in input // workspace. - outputWorkspace->setX(i, inputWorkspace->refX(i)); + outputWorkspace->setSharedX(i, inputWorkspace->sharedX(i)); // Now get references to the Y & E vectors in the input and output // workspaces - const MantidVec &Y = inputWorkspace->readY(i); - const MantidVec &E = inputWorkspace->readE(i); - MantidVec &newY = outputWorkspace->dataY(i); - MantidVec &newE = outputWorkspace->dataE(i); if (npts == 0) { - newY = Y; - newE = E; + outputWorkspace->setSharedY(i, inputWorkspace->sharedY(i)); + outputWorkspace->setSharedE(i, inputWorkspace->sharedE(i)); continue; } + const auto &Y = inputWorkspace->y(i); + const auto &E = inputWorkspace->e(i); + auto &newY = outputWorkspace->mutableY(i); + auto &newE = outputWorkspace->mutableE(i); // Use total to help hold our moving average double total = 0.0, totalE = 0.0; // First push the values ahead of the current point onto total diff --git a/Framework/Algorithms/src/StripVanadiumPeaks.cpp b/Framework/Algorithms/src/StripVanadiumPeaks.cpp index 271402dba14095c47dd474500acc2db35f32d37e..f1a6c737dc7852b46e240494c3e09676859cacaa 100644 --- a/Framework/Algorithms/src/StripVanadiumPeaks.cpp +++ b/Framework/Algorithms/src/StripVanadiumPeaks.cpp @@ -87,10 +87,9 @@ void StripVanadiumPeaks::exec() { // Copy the data over from the input to the output workspace const int nhists = static_cast<int>(inputWS->getNumberHistograms()); Progress progress(this, 0.0, 1.0, nhists * 2); + for (int k = 0; k < nhists; ++k) { - outputWS->dataX(k) = inputWS->readX(k); - outputWS->dataY(k) = inputWS->readY(k); - outputWS->dataE(k) = inputWS->readE(k); + outputWS->setHistogram(k, inputWS->histogram(k)); progress.report(); } @@ -117,15 +116,13 @@ void StripVanadiumPeaks::exec() { for (int k = 0; k < nhists; ++k) { if ((!singleSpectrum) || (singleIndex == k)) { // Get the X and Y vectors - MantidVec X = outputWS->dataX(k); - MantidVec Y = outputWS->dataY(k); + const auto &X = outputWS->x(k); // Middle of each X bin - MantidVec midX; - convertToBinCentre(X, midX); + auto midX = outputWS->points(k); // This'll be the output - MantidVec outY = Y; + auto &outY = outputWS->mutableY(k); // Strip each peak listed std::vector<double>::iterator it; @@ -137,20 +134,26 @@ void StripVanadiumPeaks::exec() { // Find the bin indices on both sides. // We use averaging regions of 1/2 width, centered at +- width/2 from // the center - int L1 = getBinIndex(X, center - width * 0.75); - int L2 = getBinIndex(X, center - width * 0.25); + int L1 = getBinIndex(X.rawData(), center - width * 0.75); + int L2 = getBinIndex(X.rawData(), center - width * 0.25); double leftX = (midX[L1] + midX[L2]) / 2; double totY = 0; - for (int i = L1; i <= L2; i++) - totY += Y[i]; + + for (int i = L1; i <= L2; i++) { + totY += outY[i]; + } + double leftY = totY / (L2 - L1 + 1); - int R1 = getBinIndex(X, center + width * 0.25); - int R2 = getBinIndex(X, center + width * 0.75); + int R1 = getBinIndex(X.rawData(), center + width * 0.25); + int R2 = getBinIndex(X.rawData(), center + width * 0.75); double rightX = (midX[R1] + midX[R2]) / 2; totY = 0; - for (int i = R1; i <= R2; i++) - totY += Y[i]; + + for (int i = R1; i <= R2; i++) { + totY += outY[i]; + } + double rightY = totY / (R2 - R1 + 1); // Make a simple fit with these two points @@ -166,7 +169,7 @@ void StripVanadiumPeaks::exec() { } // Save the output - outputWS->dataY(k) = outY; + outputWS->mutableY(k) = outY; } // if the spectrum is to be changed. progress.report(); } // each spectrum diff --git a/Framework/Algorithms/src/SumEventsByLogValue.cpp b/Framework/Algorithms/src/SumEventsByLogValue.cpp index c28194955e67852cf43ff27b09940d0a94822ceb..e0656fb6155670aaf3f56d42f19b4b67401e795f 100644 --- a/Framework/Algorithms/src/SumEventsByLogValue.cpp +++ b/Framework/Algorithms/src/SumEventsByLogValue.cpp @@ -401,7 +401,9 @@ void SumEventsByLogValue::createBinnedOutput( log->maxValue() * 1.000001); // Make it a tiny bit larger to cover full range } - MantidVec XValues; + + // XValues will be resized in createAxisFromRebinParams() + std::vector<double> XValues; const int XLength = VectorHelper::createAxisFromRebinParams(m_binningParams, XValues); assert((int)XValues.size() == XLength); @@ -410,11 +412,11 @@ void SumEventsByLogValue::createBinnedOutput( MatrixWorkspace_sptr outputWorkspace = WorkspaceFactory::Instance().create( "Workspace2D", 1, XLength, XLength - 1); // Copy the bin boundaries into the output workspace - outputWorkspace->dataX(0) = XValues; + outputWorkspace->mutableX(0) = XValues; outputWorkspace->getAxis(0)->title() = m_logName; outputWorkspace->setYUnit("Counts"); - MantidVec &Y = outputWorkspace->dataY(0); + auto &Y = outputWorkspace->mutableY(0); const int numSpec = static_cast<int>(m_inputWorkspace->getNumberHistograms()); Progress prog(this, 0.0, 1.0, numSpec); PARALLEL_FOR1(m_inputWorkspace) @@ -438,7 +440,7 @@ void SumEventsByLogValue::createBinnedOutput( // The errors are the sqrt of the counts so long as we don't deal with // weighted events. - std::transform(Y.begin(), Y.end(), outputWorkspace->dataE(0).begin(), + std::transform(Y.cbegin(), Y.cend(), outputWorkspace->mutableE(0).begin(), (double (*)(double))std::sqrt); setProperty("OutputWorkspace", outputWorkspace); diff --git a/Framework/Algorithms/src/SumRowColumn.cpp b/Framework/Algorithms/src/SumRowColumn.cpp index e636f1edb92e8fab5c2a365142e6c7eb1bf675c2..c173f7c6a88aca20b9534e2e4957ff31f012c77f 100644 --- a/Framework/Algorithms/src/SumRowColumn.cpp +++ b/Framework/Algorithms/src/SumRowColumn.cpp @@ -86,8 +86,8 @@ void SumRowColumn::exec() { outputWS->getAxis(0)->unit().reset(new Mantid::Kernel::Units::Empty); // Get references to the vectors for the results - MantidVec &X = outputWS->dataX(0); - MantidVec &Y = outputWS->dataY(0); + auto &X = outputWS->mutableX(0); + auto &Y = outputWS->mutableY(0); // Get the orientation const std::string orientation = getProperty("Orientation"); @@ -101,7 +101,7 @@ void SumRowColumn::exec() { // Now loop over calculating Y's for (int j = start; j <= end; ++j) { const int index = (horizontal ? (i + j * dim) : (i * dim + j)); - Y[i] += integratedWS->readY(index)[0]; + Y[i] += integratedWS->y(index)[0]; } } diff --git a/Framework/Algorithms/src/SumSpectra.cpp b/Framework/Algorithms/src/SumSpectra.cpp index 9c7a81d1db288ac772ab31088067a814735a7ed6..ee879e7e78032d3f261ddc4f2880b296a5e8a5fd 100644 --- a/Framework/Algorithms/src/SumSpectra.cpp +++ b/Framework/Algorithms/src/SumSpectra.cpp @@ -134,7 +134,7 @@ void SumSpectra::exec() { // Create the 2D workspace for the output MatrixWorkspace_sptr outputWorkspace = API::WorkspaceFactory::Instance().create( - localworkspace, 1, localworkspace->readX(m_minWsInd).size(), + localworkspace, 1, localworkspace->x(m_minWsInd).size(), this->m_yLength); size_t numSpectra(0); // total number of processed spectra size_t numMasked(0); // total number of the masked and skipped spectra @@ -148,7 +148,7 @@ void SumSpectra::exec() { auto &outSpec = outputWorkspace->getSpectrum(0); // Copy over the bin boundaries - outSpec.dataX() = localworkspace->readX(0); + outSpec.setSharedX(localworkspace->sharedX(0)); // Build a new spectra map outSpec.setSpectrumNo(m_outSpecNum); @@ -163,9 +163,10 @@ void SumSpectra::exec() { } // Pointer to sqrt function - MantidVec &YError = outSpec.dataE(); typedef double (*uf)(double); uf rs = std::sqrt; + + auto &YError = outSpec.mutableE(); // take the square root of all the accumulated squared errors - Assumes // Gaussian errors std::transform(YError.begin(), YError.end(), YError.begin(), rs); @@ -185,7 +186,7 @@ void SumSpectra::exec() { /** * Determine the minimum spectrum No for summing. This requires that - * SumSpectra::indices has already been set. + * SumSpectra::indices has aly been set. * @param localworkspace The workspace to use. * @return The minimum spectrum No for all the spectra being summed. */ @@ -226,10 +227,10 @@ void SumSpectra::doWorkspace2D(MatrixWorkspace_const_sptr localworkspace, size_t &numSpectra, size_t &numMasked, size_t &numZeros) { // Get references to the output workspaces's data vectors - MantidVec &YSum = outSpec.dataY(); - MantidVec &YError = outSpec.dataE(); + auto &YSum = outSpec.mutableY(); + auto &YError = outSpec.mutableE(); - MantidVec Weight; + std::vector<double> Weight; std::vector<size_t> nZeros; if (m_calculateWeightedSum) { Weight.assign(YSum.size(), 0); @@ -263,8 +264,8 @@ void SumSpectra::doWorkspace2D(MatrixWorkspace_const_sptr localworkspace, numSpectra++; // Retrieve the spectrum into a vector - const MantidVec &YValues = localworkspace->readY(i); - const MantidVec &YErrors = localworkspace->readE(i); + const auto &YValues = localworkspace->y(i); + const auto &YErrors = localworkspace->e(i); if (m_calculateWeightedSum) { for (int k = 0; k < this->m_yLength; ++k) { if (YErrors[k] != 0) { @@ -336,10 +337,10 @@ void SumSpectra::doRebinnedOutput(MatrixWorkspace_sptr outputWorkspace, // Get references to the output workspaces's data vectors auto &outSpec = outputWorkspace->getSpectrum(0); - MantidVec &YSum = outSpec.dataY(); - MantidVec &YError = outSpec.dataE(); - MantidVec &FracSum = outWS->dataF(0); - MantidVec Weight; + auto &YSum = outSpec.mutableY(); + auto &YError = outSpec.mutableE(); + auto &FracSum = outWS->dataF(0); + std::vector<double> Weight; std::vector<size_t> nZeros; if (m_calculateWeightedSum) { Weight.assign(YSum.size(), 0); @@ -377,9 +378,9 @@ void SumSpectra::doRebinnedOutput(MatrixWorkspace_sptr outputWorkspace, numSpectra++; // Retrieve the spectrum into a vector - const MantidVec &YValues = localworkspace->readY(i); - const MantidVec &YErrors = localworkspace->readE(i); - const MantidVec &FracArea = inWS->readF(i); + const auto &YValues = localworkspace->y(i); + const auto &YErrors = localworkspace->e(i); + const auto &FracArea = inWS->readF(i); if (m_calculateWeightedSum) { for (int k = 0; k < this->m_yLength; ++k) { @@ -480,7 +481,7 @@ void SumSpectra::execEvent(EventWorkspace_const_sptr localworkspace, } // Set all X bins on the output - outputWorkspace->setAllX(HistogramData::BinEdges(localworkspace->refX(0))); + outputWorkspace->setAllX(localworkspace->binEdges(0)); outputWorkspace->mutableRun().addProperty("NumAllSpectra", int(numSpectra), "", true); diff --git a/Framework/Algorithms/src/TOFSANSResolution.cpp b/Framework/Algorithms/src/TOFSANSResolution.cpp index 6ec683c5a0cb5bd4eab2b54f9c968c17b3faaa7d..b06a7933b76fa8bee33743e1dd1fd373e5b542d0 100644 --- a/Framework/Algorithms/src/TOFSANSResolution.cpp +++ b/Framework/Algorithms/src/TOFSANSResolution.cpp @@ -100,7 +100,7 @@ void TOFSANSResolution::exec() { const std::vector<double> binParams = getProperty("OutputBinning"); // Count histogram for normalization - const int xLength = static_cast<int>(iqWS->readX(0).size()); + const int xLength = static_cast<int>(iqWS->x(0).size()); std::vector<double> XNorm(xLength - 1, 0.0); // Create workspaces with each component of the resolution for debugging @@ -110,16 +110,16 @@ void TOFSANSResolution::exec() { make_unique<WorkspaceProperty<>>("ThetaError", "", Direction::Output)); setPropertyValue("ThetaError", "__" + iqWS->getName() + "_theta_error"); setProperty("ThetaError", thetaWS); - thetaWS->setX(0, iqWS->refX(0)); - MantidVec &ThetaY = thetaWS->dataY(0); + thetaWS->setSharedX(0, iqWS->sharedX(0)); + auto &ThetaY = thetaWS->mutableY(0); MatrixWorkspace_sptr tofWS = WorkspaceFactory::Instance().create(iqWS); declareProperty( make_unique<WorkspaceProperty<>>("TOFError", "", Direction::Output)); setPropertyValue("TOFError", "__" + iqWS->getName() + "_tof_error"); setProperty("TOFError", tofWS); - tofWS->setX(0, iqWS->refX(0)); - MantidVec &TOFY = tofWS->dataY(0); + tofWS->setSharedX(0, iqWS->sharedX(0)); + auto &TOFY = tofWS->mutableY(0); // Initialize Dq HistogramData::HistogramDx DxOut(xLength - 1, 0.0); @@ -150,8 +150,8 @@ void TOFSANSResolution::exec() { const double theta = spectrumInfo.twoTheta(i); const double factor = 4.0 * M_PI * sin(0.5 * theta); - const MantidVec &XIn = reducedWS->readX(i); - const MantidVec &YIn = reducedWS->readY(i); + const auto &XIn = reducedWS->x(i); + const auto &YIn = reducedWS->y(i); const int wlLength = static_cast<int>(XIn.size()); std::vector<double> _dx(xLength - 1, 0.0); diff --git a/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp b/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp index 97dd63711186958f0afdf75a81973a9c9b67b69d..5757931ea14707deaeecbb132027d21d757193f9 100644 --- a/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp +++ b/Framework/Algorithms/src/TOFSANSResolutionByPixel.cpp @@ -94,8 +94,8 @@ void TOFSANSResolutionByPixel::exec() { // create interpolation table from sigmaModeratorVSwavelength Kernel::Interpolation lookUpTable; - const auto xInterpolate = sigmaModeratorVSwavelength->points(0); - const MantidVec yInterpolate = sigmaModeratorVSwavelength->readY(0); + const auto &xInterpolate = sigmaModeratorVSwavelength->points(0); + const auto &yInterpolate = sigmaModeratorVSwavelength->y(0); // prefer the input to be a pointworkspace and create interpolation function if (sigmaModeratorVSwavelength->isHistogramData()) { @@ -153,7 +153,7 @@ void TOFSANSResolutionByPixel::exec() { double sinTheta = sin(0.5 * theta); double factor = 4.0 * M_PI * sinTheta; - const MantidVec &xIn = inWS->readX(i); + const auto &xIn = inWS->x(i); const size_t xLength = xIn.size(); // Gravity correction @@ -164,7 +164,7 @@ void TOFSANSResolutionByPixel::exec() { } // Get handles on the outputWorkspace - MantidVec &yOut = outWS->dataY(i); + auto &yOut = outWS->mutableY(i); // for each wavelenght bin of each pixel calculate a q-resolution for (size_t j = 0; j < xLength - 1; j++) { // use the midpoint of each bin diff --git a/Framework/Algorithms/src/Transpose.cpp b/Framework/Algorithms/src/Transpose.cpp index 79e77ea269c5e76534fc2aecadfe33ecc59e6c50..bff41ff5a360e77a008b4a3a9c86a58d1d81c2d5 100644 --- a/Framework/Algorithms/src/Transpose.cpp +++ b/Framework/Algorithms/src/Transpose.cpp @@ -39,12 +39,12 @@ void Transpose::exec() { boost::dynamic_pointer_cast<DataObjects::RebinnedOutput>(outputWorkspace); size_t newNhist = outputWorkspace->getNumberHistograms(); - size_t newXsize = outputWorkspace->readX(0).size(); + size_t newXsize = outputWorkspace->x(0).size(); size_t newYsize = outputWorkspace->blocksize(); // Create a shareable X vector for the output workspace Axis *inputYAxis = getVerticalAxis(inputWorkspace); - MantidVec newXValues(newXsize); + std::vector<double> newXValues(newXsize); for (size_t i = 0; i < newXsize; ++i) { newXValues[i] = (*inputYAxis)(i); } @@ -52,25 +52,29 @@ void Transpose::exec() { Kernel::make_cow<HistogramData::HistogramX>(std::move(newXValues)); Progress progress(this, 0.0, 1.0, newNhist * newYsize); + progress.report("Swapping data values"); + PARALLEL_FOR2(inputWorkspace, outputWorkspace) for (int64_t i = 0; i < static_cast<int64_t>(newNhist); ++i) { PARALLEL_START_INTERUPT_REGION - outputWorkspace->setX(i, newXVector); + outputWorkspace->setSharedX(i, newXVector); + + auto &outY = outputWorkspace->mutableY(i); + auto &outE = outputWorkspace->mutableE(i); - MantidVec &outY = outputWorkspace->dataY(i); - MantidVec &outE = outputWorkspace->dataE(i); + // because setF wants a COW pointer + Kernel::cow_ptr<std::vector<double>> F; + std::vector<double> &outF = F.access(); - MantidVecPtr F; - MantidVec &outF = F.access(); if (outRebinWorkspace) { outF.resize(newYsize); } for (int64_t j = 0; j < int64_t(newYsize); ++j) { - progress.report("Swapping data values"); - outY[j] = inputWorkspace->readY(j)[i]; - outE[j] = inputWorkspace->readE(j)[i]; + progress.report(); + outY[j] = inputWorkspace->y(j)[i]; + outE[j] = inputWorkspace->e(j)[i]; if (outRebinWorkspace) { outF[j] = inRebinWorkspace->dataF(j)[i]; } @@ -93,7 +97,7 @@ API::MatrixWorkspace_sptr Transpose::createOutputWorkspace( API::MatrixWorkspace_const_sptr inputWorkspace) { Mantid::API::Axis *yAxis = getVerticalAxis(inputWorkspace); const size_t oldNhist = inputWorkspace->getNumberHistograms(); - const MantidVec &inX = inputWorkspace->readX(0); + const auto &inX = inputWorkspace->x(0); const size_t oldYlength = inputWorkspace->blocksize(); const size_t oldVerticalAxislength = yAxis->length(); @@ -107,9 +111,9 @@ API::MatrixWorkspace_sptr Transpose::createOutputWorkspace( // Values come from input X API::NumericAxis *newYAxis(nullptr); if (inputWorkspace->isHistogramData()) { - newYAxis = new API::BinEdgeAxis(inX); + newYAxis = new API::BinEdgeAxis(inX.rawData()); } else { - newYAxis = new API::NumericAxis(inX); + newYAxis = new API::NumericAxis(inX.rawData()); } newYAxis->unit() = inputWorkspace->getAxis(0)->unit(); diff --git a/Framework/Algorithms/src/UnaryOperation.cpp b/Framework/Algorithms/src/UnaryOperation.cpp index ebeb073f94f2a960b36af9c4a95177b9fca049dd..966dd3ec4f31055f5cde0e07c0a56e97152ed6df 100644 --- a/Framework/Algorithms/src/UnaryOperation.cpp +++ b/Framework/Algorithms/src/UnaryOperation.cpp @@ -57,7 +57,8 @@ void UnaryOperation::exec() { RebinnedOutput_sptr outtemp = boost::dynamic_pointer_cast<RebinnedOutput>(out_work); for (size_t i = 0; i < outtemp->getNumberHistograms(); ++i) { - MantidVecPtr F; + // because setF wants a COW pointer + Kernel::cow_ptr<std::vector<double>> F; F.access() = intemp->dataF(i); outtemp->setF(i, F); } @@ -80,15 +81,15 @@ void UnaryOperation::exec() { for (int64_t i = 0; i < int64_t(numSpec); ++i) { PARALLEL_START_INTERUPT_REGION // Copy the X values over - out_work->setX(i, in_work->refX(i)); + out_work->setSharedX(i, in_work->sharedX(i)); // Get references to the data // Output (non-const) ones first because they may copy the vector // if it's shared, which isn't thread-safe. - MantidVec &YOut = out_work->dataY(i); - MantidVec &EOut = out_work->dataE(i); + auto &YOut = out_work->mutableY(i); + auto &EOut = out_work->mutableE(i); const auto X = in_work->points(i); - const MantidVec &Y = in_work->readY(i); - const MantidVec &E = in_work->readE(i); + const auto &Y = in_work->y(i); + const auto &E = in_work->e(i); for (size_t j = 0; j < specSize; ++j) { // Call the abstract function, passing in the current values diff --git a/Framework/Algorithms/src/UnwrapMonitor.cpp b/Framework/Algorithms/src/UnwrapMonitor.cpp index 0b0b24609f4ee656a637153589dfebcf712b8e06..7d42b638d6878d561e92425ea46197fbc916e8ad 100644 --- a/Framework/Algorithms/src/UnwrapMonitor.cpp +++ b/Framework/Algorithms/src/UnwrapMonitor.cpp @@ -82,11 +82,11 @@ void UnwrapMonitor::exec() { // Get the "reference" flightpath (currently passed in as a property) m_LRef = getProperty("LRef"); // Get the min & max frame values - m_Tmin = m_inputWS->readX(0).front(); - m_Tmax = m_inputWS->readX(0).back(); + m_Tmin = m_inputWS->x(0).front(); + m_Tmax = m_inputWS->x(0).back(); g_log.debug() << "Frame range in microseconds is: " << m_Tmin << " - " << m_Tmax << '\n'; - m_XSize = m_inputWS->readX(0).size(); + m_XSize = m_inputWS->x(0).size(); // Need a new workspace. Will just be used temporarily until the data is // rebinned. @@ -109,23 +109,40 @@ void UnwrapMonitor::exec() { // If the detector flightpath is missing, zero the data g_log.debug() << "Detector information for workspace index " << i << " is not available.\n"; - tempWS->dataX(i).assign(tempWS->dataX(i).size(), 0.0); - tempWS->dataY(i).assign(tempWS->dataY(i).size(), 0.0); - tempWS->dataE(i).assign(tempWS->dataE(i).size(), 0.0); + tempWS->mutableX(i) = 0.0; + tempWS->mutableY(i) = 0.0; + tempWS->mutableE(i) = 0.0; continue; } + // Getting the unwrapped data is a three step process. + // 1. We ge the unwrapped version of the x data. + // 2. Then we get the unwrapped version of the y and e data for + // which we require the x data from the previous step + // 3. Finally we need to set the newly unwrapped data on the + // histogram + // Unwrap the x data. Returns the bin ranges that end up being used const double Ld = L1 + spectrumInfo.l2(i); - const std::vector<int> rangeBounds = this->unwrapX(tempWS, i, Ld); + MantidVec newX; + const std::vector<int> rangeBounds = this->unwrapX(newX, i, Ld); + // Unwrap the y & e data according to the ranges found above - this->unwrapYandE(tempWS, i, rangeBounds); - assert(tempWS->dataX(i).size() == tempWS->dataY(i).size() + 1); + MantidVec newY; + MantidVec newE; + this->unwrapYandE(tempWS, i, rangeBounds, newY, newE); + + // Now set the new X, Y and E values on the Histogram + auto histogram = tempWS->histogram(i); + tempWS->setHistogram( + i, Mantid::HistogramData::BinEdges(std::move(newX)), + Mantid::HistogramData::Counts(std::move(newY)), + Mantid::HistogramData::CountStandardDeviations(std::move(newE))); // Get the maximum number of bins (excluding monitors) for the rebinning // below if (!spectrumInfo.isMonitor(i)) { - const int XLen = static_cast<int>(tempWS->dataX(i).size()); + const int XLen = static_cast<int>(tempWS->x(i).size()); if (XLen > max_bins) max_bins = XLen; } @@ -152,16 +169,15 @@ void UnwrapMonitor::exec() { } /** Unwraps an X array, converting the units to wavelength along the way. - * @param tempWS :: A pointer to the temporary workspace in which the results - * are being stored + * @param newX :: A reference to a container which stores our unwrapped x + * data. * @param spectrum :: The workspace index * @param Ld :: The flightpath for the detector related to this spectrum * @return A 3-element vector containing the bins at which the upper and lower * ranges start & end */ const std::vector<int> -UnwrapMonitor::unwrapX(const API::MatrixWorkspace_sptr &tempWS, - const int &spectrum, const double &Ld) { +UnwrapMonitor::unwrapX(MantidVec &newX, const int &spectrum, const double &Ld) { // Create and initalise the vector that will store the bin ranges, and will be // returned // Elements are: 0 - Lower range start, 1 - Lower range end, 2 - Upper range @@ -179,12 +195,11 @@ UnwrapMonitor::unwrapX(const API::MatrixWorkspace_sptr &tempWS, m_XSize); // Doing this possible gives a small efficiency increase // Create a vector for the upper range. Make it a reference to the output // histogram to save an assignment later - MantidVec &tempX_U = tempWS->dataX(spectrum); - tempX_U.clear(); - tempX_U.reserve(m_XSize); + newX.clear(); + newX.reserve(m_XSize); // Get a reference to the input x data - const MantidVec &xdata = m_inputWS->readX(spectrum); + const auto &xdata = m_inputWS->x(spectrum); // Loop over histogram, selecting bins in appropriate ranges. // At the moment, the data in the bin in which a cut-off sits is excluded. for (unsigned int bin = 0; bin < m_XSize; ++bin) { @@ -205,10 +220,10 @@ UnwrapMonitor::unwrapX(const API::MatrixWorkspace_sptr &tempWS, else if (tof > T1) { const double velocity = Ld / (tof - m_Tmax + m_Tmin); const double wavelength = m_conversionConstant / velocity; - tempX_U.push_back(wavelength); + newX.push_back(wavelength); // Remove the duplicate boundary bin if (tof == m_Tmax && std::abs(wavelength - tempX_L.front()) < 1.0e-5) - tempX_U.pop_back(); + newX.pop_back(); // Record the bins that fall in this range for copying over the data & // errors if (binRange[2] == -1) @@ -235,7 +250,7 @@ UnwrapMonitor::unwrapX(const API::MatrixWorkspace_sptr &tempWS, } // Append first vector to back of second - tempX_U.insert(tempX_U.end(), tempX_L.begin(), tempX_L.end()); + newX.insert(newX.end(), tempX_L.begin(), tempX_L.end()); return binRange; } @@ -243,9 +258,9 @@ UnwrapMonitor::unwrapX(const API::MatrixWorkspace_sptr &tempWS, /** Deals with the (rare) case where the flightpath is longer than the reference * Note that in this case both T1 & T2 will be greater than Tmax */ -std::pair<int, int> -UnwrapMonitor::handleFrameOverlapped(const MantidVec &xdata, const double &Ld, - std::vector<double> &tempX) { +std::pair<int, int> UnwrapMonitor::handleFrameOverlapped( + const Mantid::HistogramData::HistogramX &xdata, const double &Ld, + std::vector<double> &tempX) { // Calculate the interval to exclude const double Dt = (m_Tmax - m_Tmin) * (1 - (m_LRef / Ld)); // This gives us new minimum & maximum tof values @@ -281,16 +296,19 @@ UnwrapMonitor::handleFrameOverlapped(const MantidVec &xdata, const double &Ld, * results are being stored * @param spectrum :: The workspace index * @param rangeBounds :: The upper and lower ranges for the unwrapping + * @param newY :: A reference to a container which stores our unwrapped y data. + * @param newE :: A reference to a container which stores our unwrapped e data. */ void UnwrapMonitor::unwrapYandE(const API::MatrixWorkspace_sptr &tempWS, const int &spectrum, - const std::vector<int> &rangeBounds) { + const std::vector<int> &rangeBounds, + MantidVec &newY, MantidVec &newE) { // Copy over the relevant ranges of Y & E data - MantidVec &Y = tempWS->dataY(spectrum); - MantidVec &E = tempWS->dataE(spectrum); + MantidVec &Y = newY; + MantidVec &E = newE; // Get references to the input data - const MantidVec &YIn = m_inputWS->dataY(spectrum); - const MantidVec &EIn = m_inputWS->dataE(spectrum); + const auto &YIn = m_inputWS->y(spectrum); + const auto &EIn = m_inputWS->e(spectrum); if (rangeBounds[2] != -1) { // Copy in the upper range Y.assign(YIn.begin() + rangeBounds[2], YIn.end()); diff --git a/Framework/Algorithms/src/UnwrapSNS.cpp b/Framework/Algorithms/src/UnwrapSNS.cpp index b58faed5ae2051c113b39192cc69c57306370c00..765a29ba2e1939a423a3daaae4f12561dba1d31b 100644 --- a/Framework/Algorithms/src/UnwrapSNS.cpp +++ b/Framework/Algorithms/src/UnwrapSNS.cpp @@ -106,7 +106,7 @@ void UnwrapSNS::exec() { // Get the "reference" flightpath (currently passed in as a property) m_LRef = getProperty("LRef"); - m_XSize = static_cast<int>(m_inputWS->dataX(0).size()); + m_XSize = static_cast<int>(m_inputWS->x(0).size()); m_numberOfSpectra = static_cast<int>(m_inputWS->getNumberHistograms()); g_log.debug() << "Number of spectra in input workspace: " << m_numberOfSpectra << "\n"; @@ -144,29 +144,35 @@ void UnwrapSNS::exec() { // If the detector flightpath is missing, zero the data g_log.debug() << "Detector information for workspace index " << workspaceIndex << " is not available.\n"; - outputWS->dataX(workspaceIndex) = m_inputWS->dataX(workspaceIndex); - outputWS->dataY(workspaceIndex).assign(m_XSize - 1, 0.0); - outputWS->dataE(workspaceIndex).assign(m_XSize - 1, 0.0); + outputWS->setSharedX(workspaceIndex, m_inputWS->sharedX(workspaceIndex)); + outputWS->mutableY(workspaceIndex) = 0.0; + outputWS->mutableE(workspaceIndex) = 0.0; } else { const double Ld = L1 + spectrumInfo.l2(workspaceIndex); // fix the x-axis - size_t pivot = this->unwrapX(m_inputWS->readX(workspaceIndex), - outputWS->dataX(workspaceIndex), Ld); + MantidVec timeBins; + size_t pivot = this->unwrapX(m_inputWS->x(workspaceIndex), timeBins, Ld); + outputWS->setBinEdges(workspaceIndex, std::move(timeBins)); + pivot++; // one-off difference between x and y // fix the counts using the pivot point - MantidVec yIn = m_inputWS->readY(workspaceIndex); - MantidVec &yOut = outputWS->dataY(workspaceIndex); - yOut.clear(); - yOut.insert(yOut.begin(), yIn.begin() + pivot, yIn.end()); - yOut.insert(yOut.end(), yIn.begin(), yIn.begin() + pivot); + auto &yIn = m_inputWS->y(workspaceIndex); + auto &yOut = outputWS->mutableY(workspaceIndex); + + auto lengthFirstPartY = std::distance(yIn.begin() + pivot, yIn.end()); + std::copy(yIn.begin() + pivot, yIn.end(), yOut.begin()); + std::copy(yIn.begin(), yIn.begin() + pivot, + yOut.begin() + lengthFirstPartY); // fix the uncertainties using the pivot point - MantidVec eIn = m_inputWS->readE(workspaceIndex); - MantidVec &eOut = outputWS->dataE(workspaceIndex); - eOut.clear(); - eOut.insert(eOut.begin(), eIn.begin() + pivot, eIn.end()); - eOut.insert(eOut.end(), eIn.begin(), eIn.begin() + pivot); + auto &eIn = m_inputWS->e(workspaceIndex); + auto &eOut = outputWS->mutableE(workspaceIndex); + + auto lengthFirstPartE = std::distance(eIn.begin() + pivot, eIn.end()); + std::copy(eIn.begin() + pivot, eIn.end(), eOut.begin()); + std::copy(eIn.begin(), eIn.begin() + pivot, + eOut.begin() + lengthFirstPartE); } m_progress->report(); PARALLEL_END_INTERUPT_REGION @@ -209,11 +215,11 @@ void UnwrapSNS::execEvent() { Ld = L1 + spectrumInfo.l2(workspaceIndex); MantidVec time_bins; - if (outW->dataX(0).size() > 2) { - this->unwrapX(m_inputWS->dataX(workspaceIndex), time_bins, Ld); - outW->setBinEdges(workspaceIndex, time_bins); + if (outW->x(0).size() > 2) { + this->unwrapX(m_inputWS->x(workspaceIndex), time_bins, Ld); + outW->setBinEdges(workspaceIndex, std::move(time_bins)); } else { - outW->setX(workspaceIndex, m_inputWS->refX(workspaceIndex)); + outW->setSharedX(workspaceIndex, m_inputWS->sharedX(workspaceIndex)); } if (numEvents > 0) { MantidVec times(numEvents); @@ -236,8 +242,8 @@ void UnwrapSNS::execEvent() { this->runMaskDetectors(); } -int UnwrapSNS::unwrapX(const MantidVec &datain, MantidVec &dataout, - const double &Ld) { +int UnwrapSNS::unwrapX(const Mantid::HistogramData::HistogramX &datain, + MantidVec &dataout, const double &Ld) { MantidVec tempX_L; // lower half - to be frame wrapped tempX_L.reserve(m_XSize); tempX_L.clear(); diff --git a/Framework/Algorithms/src/VesuvioL1ThetaResolution.cpp b/Framework/Algorithms/src/VesuvioL1ThetaResolution.cpp index c01446a7d53c20d60441bdc3a92d34002070c950..dfcb105e054d8bb8b140f1f83623055df87fe92b 100644 --- a/Framework/Algorithms/src/VesuvioL1ThetaResolution.cpp +++ b/Framework/Algorithms/src/VesuvioL1ThetaResolution.cpp @@ -201,24 +201,24 @@ void VesuvioL1ThetaResolution::exec() { // Set values in output workspace const int specNo = m_instWorkspace->getSpectrum(i).getSpectrumNo(); - m_outputWorkspace->dataX(0)[i] = specNo; - m_outputWorkspace->dataX(1)[i] = specNo; - m_outputWorkspace->dataX(2)[i] = specNo; - m_outputWorkspace->dataX(3)[i] = specNo; - m_outputWorkspace->dataY(0)[i] = l1Stats.mean; - m_outputWorkspace->dataY(1)[i] = l1Stats.standard_deviation; - m_outputWorkspace->dataY(2)[i] = thetaStats.mean; - m_outputWorkspace->dataY(3)[i] = thetaStats.standard_deviation; + m_outputWorkspace->mutableX(0)[i] = specNo; + m_outputWorkspace->mutableX(1)[i] = specNo; + m_outputWorkspace->mutableX(2)[i] = specNo; + m_outputWorkspace->mutableX(3)[i] = specNo; + m_outputWorkspace->mutableY(0)[i] = l1Stats.mean; + m_outputWorkspace->mutableY(1)[i] = l1Stats.standard_deviation; + m_outputWorkspace->mutableY(2)[i] = thetaStats.mean; + m_outputWorkspace->mutableY(3)[i] = thetaStats.standard_deviation; // Process data for L1 distribution if (m_l1DistributionWs) { - std::vector<double> &x = m_l1DistributionWs->dataX(i); + auto &x = m_l1DistributionWs->mutableX(i); std::vector<double> y(numEvents, 1.0); std::sort(l1.begin(), l1.end()); std::copy(l1.begin(), l1.end(), x.begin()); - m_l1DistributionWs->dataY(i) = y; + m_l1DistributionWs->mutableY(i) = y; auto &spec = m_l1DistributionWs->getSpectrum(i); spec.setSpectrumNo(specNo); @@ -227,13 +227,13 @@ void VesuvioL1ThetaResolution::exec() { // Process data for theta distribution if (m_thetaDistributionWs) { - std::vector<double> &x = m_thetaDistributionWs->dataX(i); + auto &x = m_thetaDistributionWs->mutableX(i); std::vector<double> y(numEvents, 1.0); std::sort(theta.begin(), theta.end()); std::copy(theta.begin(), theta.end(), x.begin()); - m_thetaDistributionWs->dataY(i) = y; + m_thetaDistributionWs->mutableY(i) = y; auto &spec = m_thetaDistributionWs->getSpectrum(i); spec.setSpectrumNo(specNo); @@ -429,7 +429,7 @@ VesuvioL1ThetaResolution::processDistribution(MatrixWorkspace_sptr ws, double xMin(DBL_MAX); double xMax(DBL_MIN); for (size_t i = 0; i < numHist; i++) { - const std::vector<double> &x = ws->readX(i); + auto &x = ws->x(i); xMin = std::min(xMin, x.front()); xMax = std::max(xMax, x.back()); } @@ -448,8 +448,8 @@ VesuvioL1ThetaResolution::processDistribution(MatrixWorkspace_sptr ws, ws = rebin->getProperty("OutputWorkspace"); for (size_t i = 0; i < numHist; i++) { - const std::vector<double> &y = ws->readY(i); - std::vector<double> &e = ws->dataE(i); + auto &y = ws->y(i); + auto &e = ws->mutableE(i); std::transform(y.begin(), y.end(), e.begin(), SquareRoot()); } diff --git a/Framework/Algorithms/src/WeightedMeanOfWorkspace.cpp b/Framework/Algorithms/src/WeightedMeanOfWorkspace.cpp index 11fbcab1b4a8074a80d63e970dd771f109bb6a40..ccf81b8e602332659ecceb3b5d115748660fa5f7 100644 --- a/Framework/Algorithms/src/WeightedMeanOfWorkspace.cpp +++ b/Framework/Algorithms/src/WeightedMeanOfWorkspace.cpp @@ -61,8 +61,8 @@ void WeightedMeanOfWorkspace::exec() { if (spectrumInfo.hasDetectors(i)) if (spectrumInfo.isMonitor(i) || spectrumInfo.isMasked(i)) continue; - MantidVec y = inputWS->dataY(i); - MantidVec e = inputWS->dataE(i); + auto &y = inputWS->y(i); + auto &e = inputWS->e(i); double weight = 0.0; for (std::size_t j = 0; j < y.size(); ++j) { if (std::isfinite(y[j]) && std::isfinite(e[j])) { @@ -72,9 +72,9 @@ void WeightedMeanOfWorkspace::exec() { } } } - singleValued->dataX(0)[0] = 0.0; - singleValued->dataY(0)[0] = averageValue / weightSum; - singleValued->dataE(0)[0] = std::sqrt(weightSum); + singleValued->mutableX(0)[0] = 0.0; + singleValued->mutableY(0)[0] = averageValue / weightSum; + singleValued->mutableE(0)[0] = std::sqrt(weightSum); this->setProperty("OutputWorkspace", singleValued); } diff --git a/Framework/Algorithms/src/WienerSmooth.cpp b/Framework/Algorithms/src/WienerSmooth.cpp index aa09001d3b1544ad850c3f582bf1edea513af8a5..a8f8d361dddf9bf06d40028e2290b4b18c811ebc 100644 --- a/Framework/Algorithms/src/WienerSmooth.cpp +++ b/Framework/Algorithms/src/WienerSmooth.cpp @@ -97,7 +97,7 @@ void WienerSmooth::exec() { // create full output workspace by copying all settings from tinputWS // blocksize is taken form first API::MatrixWorkspace_sptr outputWS = API::WorkspaceFactory::Instance().create( - inputWS, nOutputSpectra, first->readX(0).size(), first->readY(0).size()); + inputWS, nOutputSpectra, first->x(0).size(), first->y(0).size()); // TODO: ideally axis cloning should be done via API::Axis interface but it's // not possible @@ -120,9 +120,7 @@ void WienerSmooth::exec() { auto next = outIndex == 0 ? first : smoothSingleSpectrum(inputWS, inIndex); // copy the values - outputWS->dataX(outIndex) = next->readX(0); - outputWS->dataY(outIndex) = next->readY(0); - outputWS->dataE(outIndex) = next->readE(0); + outputWS->setHistogram(outIndex, next->histogram(0)); // set the axis value if (isSpectra) { @@ -166,19 +164,22 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, // add a fake value to the end to make size even inputWS = copyInput(inputWS, wsIndex); wsIndex = 0; - auto &X = inputWS->dataX(wsIndex); - auto &Y = inputWS->dataY(wsIndex); - auto &E = inputWS->dataE(wsIndex); + + auto &X = inputWS->x(wsIndex); + auto &Y = inputWS->y(wsIndex); + auto &E = inputWS->e(wsIndex); double dx = X[dataSize - 1] - X[dataSize - 2]; - X.push_back(X.back() + dx); - Y.push_back(Y.back()); - E.push_back(E.back()); + auto histogram = inputWS->histogram(wsIndex); + histogram.resize(histogram.size() + 1); + histogram.mutableX().back() = X.back() + dx; + histogram.mutableY().back() = Y.back(); + histogram.mutableE().back() = E.back(); + inputWS->setHistogram(wsIndex, histogram); } // the input vectors - auto &X = inputWS->readX(wsIndex); - auto &Y = inputWS->readY(wsIndex); - auto &E = inputWS->readE(wsIndex); + auto &X = inputWS->x(wsIndex); + auto &Y = inputWS->y(wsIndex); // Digital fourier transform works best for data oscillating around 0. // Fit a spline with a small number of break points to the data. @@ -244,7 +245,7 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, // spectrum 2 of the transformed workspace has the transform modulus which is // a square // root of the power spectrum - auto &powerSpec = fourierOut->dataY(2); + auto &powerSpec = fourierOut->mutableY(2); // convert the modulus to power spectrum wich is the base of the Wiener filter std::transform(powerSpec.begin(), powerSpec.end(), powerSpec.begin(), PowerSpectrum()); @@ -335,8 +336,8 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, } // multiply the fourier transform by the filter - auto &re = fourierOut->dataY(0); - auto &im = fourierOut->dataY(1); + auto &re = fourierOut->mutableY(0); + auto &im = fourierOut->mutableY(1); std::transform(re.begin(), re.end(), wf.begin(), re.begin(), std::multiplies<double>()); @@ -352,8 +353,8 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, fourier->execute(); API::MatrixWorkspace_sptr out = fourier->getProperty("OutputWorkspace"); - auto &background = fitOut->readY(1); - auto &y = out->dataY(0); + auto &background = fitOut->y(1); + auto &y = out->mutableY(0); if (y.size() != background.size()) { throw std::logic_error("Logic error: inconsistent arrays"); @@ -365,13 +366,18 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, // copy the x-values and errors from the original spectrum // remove the last values for odd-sized inputs + if (isOddSize) { - out->dataX(0).assign(X.begin(), X.end() - 1); - out->dataE(0).assign(E.begin(), E.end() - 1); - out->dataY(0).resize(Y.size() - 1); + auto histogram = out->histogram(0); + histogram.setSharedX(inputWS->sharedX(wsIndex)); + histogram.setSharedE(inputWS->sharedE(wsIndex)); + auto newSize = histogram.y().size() - 1; + + histogram.resize(newSize); + out->setHistogram(0, histogram); } else { - out->mutableX(0) = X; - out->dataE(0).assign(E.begin(), E.end()); + out->setSharedX(0, inputWS->sharedX(wsIndex)); + out->setSharedE(0, inputWS->sharedE(wsIndex)); } return out; @@ -385,8 +391,9 @@ WienerSmooth::smoothSingleSpectrum(API::MatrixWorkspace_sptr inputWS, * centres are used. * @return :: A pair of start x and end x. */ -std::pair<double, double> WienerSmooth::getStartEnd(const MantidVec &X, - bool isHistogram) const { +std::pair<double, double> +WienerSmooth::getStartEnd(const Mantid::HistogramData::HistogramX &X, + bool isHistogram) const { const size_t n = X.size(); if (n < 3) { // 3 is the smallest number for this method to work without breaking diff --git a/Framework/Algorithms/src/WorkspaceJoiners.cpp b/Framework/Algorithms/src/WorkspaceJoiners.cpp index c767982fc2b0cd401c90e2f3cd242514c1841b8b..77730df8a6526bcf32a0138b5de97b4e2535a6e9 100644 --- a/Framework/Algorithms/src/WorkspaceJoiners.cpp +++ b/Framework/Algorithms/src/WorkspaceJoiners.cpp @@ -36,7 +36,7 @@ WorkspaceJoiners::execWS2D(API::MatrixWorkspace_const_sptr ws1, const size_t totalHists = ws1->getNumberHistograms() + ws2->getNumberHistograms(); MatrixWorkspace_sptr output = WorkspaceFactory::Instance().create( - "Workspace2D", totalHists, ws1->readX(0).size(), ws1->readY(0).size()); + "Workspace2D", totalHists, ws1->x(0).size(), ws1->y(0).size()); // Copy over stuff from first input workspace. This will include the spectrum // masking WorkspaceFactory::Instance().initializeFromParent(ws1, output, true); @@ -56,19 +56,14 @@ WorkspaceJoiners::execWS2D(API::MatrixWorkspace_const_sptr ws1, auto &outSpec = output->getSpectrum(i); const auto &inSpec = ws1->getSpectrum(i); - // Copy X,Y,E - outSpec.setX(XValues); - outSpec.dataY() = inSpec.dataY(); - outSpec.dataE() = inSpec.dataE(); + outSpec.setHistogram(inSpec.histogram()); // Copy the spectrum number/detector IDs outSpec.copyInfoFrom(inSpec); // Propagate binmasking, if needed if (ws1->hasMaskedBins(i)) { - const MatrixWorkspace::MaskList &inputMasks = ws1->maskedBins(i); - MatrixWorkspace::MaskList::const_iterator it; - for (it = inputMasks.begin(); it != inputMasks.end(); ++it) { - output->flagMasked(i, (*it).first, (*it).second); + for (const auto &inputMask : ws1->maskedBins(i)) { + output->flagMasked(i, inputMask.first, inputMask.second); } } @@ -88,19 +83,14 @@ WorkspaceJoiners::execWS2D(API::MatrixWorkspace_const_sptr ws1, // Spectrum in the second workspace const auto &inSpec = ws2->getSpectrum(j); - // Copy X,Y,E - outSpec.setX(XValues); - outSpec.dataY() = inSpec.dataY(); - outSpec.dataE() = inSpec.dataE(); + outSpec.setHistogram(inSpec.histogram()); // Copy the spectrum number/detector IDs outSpec.copyInfoFrom(inSpec); // Propagate masking, if needed if (ws2->hasMaskedBins(j)) { - const MatrixWorkspace::MaskList &inputMasks = ws2->maskedBins(j); - MatrixWorkspace::MaskList::const_iterator it; - for (it = inputMasks.begin(); it != inputMasks.end(); ++it) { - output->flagMasked(nhist1 + j, (*it).first, (*it).second); + for (const auto &inputMask : ws2->maskedBins(j)) { + output->flagMasked(nhist1 + j, inputMask.first, inputMask.second); } } // Propagate spectrum masking @@ -129,8 +119,8 @@ MatrixWorkspace_sptr WorkspaceJoiners::execEvent() { // Have the minimum # of histograms in the output. EventWorkspace_sptr output = boost::dynamic_pointer_cast<EventWorkspace>( WorkspaceFactory::Instance().create("EventWorkspace", totalHists, - event_ws1->readX(0).size(), - event_ws1->readY(0).size())); + event_ws1->x(0).size(), + event_ws1->y(0).size())); // Copy over geometry (but not data) from first input workspace WorkspaceFactory::Instance().initializeFromParent(event_ws1, output, true); @@ -160,7 +150,7 @@ MatrixWorkspace_sptr WorkspaceJoiners::execEvent() { } // Set the same bins for all output pixels - output->setAllX(HistogramData::BinEdges(event_ws1->refX(0))); + output->setAllX(event_ws1->binEdges(0)); fixSpectrumNumbers(event_ws1, event_ws2, output); diff --git a/Framework/Algorithms/test/CalculateFlatBackgroundTest.h b/Framework/Algorithms/test/CalculateFlatBackgroundTest.h index d0bf902875172923c811b048884f5251eba06485..1e9aea8d6f3fa2d24eaa97e54d1a691a52007e8f 100644 --- a/Framework/Algorithms/test/CalculateFlatBackgroundTest.h +++ b/Framework/Algorithms/test/CalculateFlatBackgroundTest.h @@ -439,6 +439,33 @@ public: AnalysisDataService::Instance().remove("Removed1"); } + void test_movingAverageThrowsOnlyWithInvalidWindowWidth() { + size_t binCount = 5; + movingAverageWindowWidthTest(0, binCount, true); + movingAverageWindowWidthTest(1, binCount, false); + movingAverageWindowWidthTest(binCount - 1, binCount, false); + movingAverageWindowWidthTest(binCount, binCount, false); + movingAverageWindowWidthTest(binCount + 1, binCount, true); + } + + void test_movingAverageModeWhenWindowWidthIsOne() { + const size_t spectraCount = 3; + const size_t binCount = 4; + movingAverageTest(1, spectraCount, binCount); + } + + void test_movingAverageModeWhenWindowWidthIsTwo() { + const size_t spectraCount = 2; + const size_t binCount = 7; + movingAverageTest(2, spectraCount, binCount); + } + + void test_movingAverageModeWithMaximalWindowWidth() { + const size_t spectraCount = 4; + const size_t binCount = 9; + movingAverageTest(binCount, spectraCount, binCount); + } + private: double bg; @@ -477,6 +504,96 @@ private: WS->getSpectrum(i).addDetectorID(physicalPixel->getID()); } } + + /// Creates a workspace with a single special value in each spectrum. + Mantid::DataObjects::Workspace2D_sptr + movingAverageCreateWorkspace(const size_t spectraCount, const size_t binCount, + const size_t specialIndex) { + Mantid::DataObjects::Workspace2D_sptr WS( + new Mantid::DataObjects::Workspace2D); + WS->initialize(spectraCount, binCount + 1, binCount); + for (size_t i = 0; i < spectraCount; ++i) { + for (size_t j = 0; j < binCount; ++j) { + // Make non-trivial but still linear x axis. + WS->mutableX(i)[j] = 0.78 * (static_cast<double>(j) - + static_cast<double>(binCount) / 3.0) - + 0.31 * static_cast<double>(i); + // Compute some non-trivial y values. + WS->mutableY(i)[j] = movingAverageStandardY(i); + WS->mutableE(i)[j] = std::sqrt(WS->y(i)[j]); + } + // Add extra x value because histogram. + WS->mutableX(i)[binCount] = + 0.78 * 2.0 / 3.0 * static_cast<double>(binCount) - + 0.31 * static_cast<double>(i); + // The special background value is set here. + WS->mutableY(i)[specialIndex] = movingAverageSpecialY(i); + } + return WS; + } + + double movingAverageSpecialY(const size_t wsIndex) { + // This value has to be smaller than what is returned by + // movingAverageStandardY(). + return 0.23 * movingAverageStandardY(wsIndex); + } + + double movingAverageStandardY(const size_t wsIndex) { + return 9.34 + 3.2 * static_cast<double>(wsIndex); + } + + void movingAverageTest(const size_t windowWidth, const size_t spectraCount, + const size_t binCount) { + Mantid::DataObjects::Workspace2D_sptr WS; + for (size_t i = 0; i < binCount; ++i) { + WS = movingAverageCreateWorkspace(spectraCount, binCount, i); + Mantid::Algorithms::CalculateFlatBackground flatBG; + flatBG.setRethrows(true); + TS_ASSERT_THROWS_NOTHING(flatBG.initialize()) + TS_ASSERT(flatBG.isInitialized()) + flatBG.setProperty("InputWorkspace", WS); + flatBG.setPropertyValue("OutputWorkspace", "Removed1"); + flatBG.setPropertyValue("Mode", "Moving Average"); + flatBG.setProperty("AveragingWindowWidth", static_cast<int>(windowWidth)); + flatBG.setPropertyValue("OutputMode", "Return Background"); + TS_ASSERT_THROWS_NOTHING(flatBG.execute()) + TS_ASSERT(flatBG.isExecuted()) + MatrixWorkspace_sptr outputWS = + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + "Removed1"); + for (size_t j = 0; j < spectraCount; ++j) { + const double expected = (movingAverageSpecialY(j) + + (static_cast<double>(windowWidth) - 1) * + movingAverageStandardY(j)) / + static_cast<double>(windowWidth); + TS_ASSERT_DELTA(outputWS->y(j)[0], expected, 1e-12) + } + AnalysisDataService::Instance().remove("Removed1"); + } + } + + void movingAverageWindowWidthTest(size_t windowWidth, size_t binCount, + bool shouldThrow) { + Mantid::DataObjects::Workspace2D_sptr WS; + WS = movingAverageCreateWorkspace(1, binCount, 0); + Mantid::Algorithms::CalculateFlatBackground flatBG; + flatBG.setRethrows(true); + TS_ASSERT_THROWS_NOTHING(flatBG.initialize()) + TS_ASSERT(flatBG.isInitialized()) + flatBG.setProperty("InputWorkspace", WS); + flatBG.setPropertyValue("OutputWorkspace", "Removed1"); + flatBG.setPropertyValue("Mode", "Moving Average"); + flatBG.setProperty("AveragingWindowWidth", static_cast<int>(windowWidth)); + flatBG.setPropertyValue("OutputMode", "Return Background"); + if (shouldThrow) { + TS_ASSERT_THROWS_ANYTHING(flatBG.execute()) + TS_ASSERT(!flatBG.isExecuted()) + } else { + TS_ASSERT_THROWS_NOTHING(flatBG.execute()) + TS_ASSERT(flatBG.isExecuted()) + } + AnalysisDataService::Instance().remove("Removed1"); + } }; #endif /*FlatBackgroundTest_H_*/ diff --git a/Framework/Algorithms/test/MayersSampleCorrectionStrategyTest.h b/Framework/Algorithms/test/MayersSampleCorrectionStrategyTest.h index d315671f08f101f9e96a7abcff09c0fb6c073813..60ddd593b217a45fc7d873e8e5536e5e345202fc 100644 --- a/Framework/Algorithms/test/MayersSampleCorrectionStrategyTest.h +++ b/Framework/Algorithms/test/MayersSampleCorrectionStrategyTest.h @@ -4,10 +4,12 @@ #include <cxxtest/TestSuite.h> #include "MantidAlgorithms/SampleCorrections/MayersSampleCorrectionStrategy.h" +#include "MantidHistogramData/LinearGenerator.h" #include <algorithm> #include <cmath> using Mantid::Algorithms::MayersSampleCorrectionStrategy; +using namespace Mantid::HistogramData; class MayersSampleCorrectionStrategyTest : public CxxTest::TestSuite { public: @@ -21,10 +23,8 @@ public: } void test_Attentuaton_Correction_For_Fixed_Mur() { - std::vector<double> dummy(2, 0.0); - dummy[1] = 1.0; - MayersSampleCorrectionStrategy mscat(createTestParameters(), dummy, dummy, - dummy); + Histogram histo(Points{0, 1}, Counts{0, 1}); + MayersSampleCorrectionStrategy mscat(createTestParameters(), histo); auto absFactor = mscat.calculateSelfAttenuation(0.01); const double delta = 1e-8; @@ -33,10 +33,8 @@ public: void test_Multiple_Scattering_With_Fixed_Mur_And_Absorption_Correction_Factor() { - std::vector<double> dummy(2, 0.0); - dummy[1] = 1.0; - MayersSampleCorrectionStrategy mscat(createTestParameters(), dummy, dummy, - dummy); + Histogram histo(Points{0, 1}, Counts{0, 1}); + MayersSampleCorrectionStrategy mscat(createTestParameters(), histo); const size_t irp(1); const double muR(0.01), abs(0.0003); auto absFactor = mscat.calculateMS(irp, muR, abs); @@ -47,17 +45,16 @@ public: } void test_Corrects_Both_Absorption_And_Multiple_Scattering_For_Point_Data() { - using std::sqrt; const size_t nypts(100); - std::vector<double> signal(nypts, 2.0), tof(nypts), error(nypts); - std::transform(signal.begin(), signal.end(), error.begin(), - (double (*)(double))sqrt); - std::generate(tof.begin(), tof.end(), Incrementer(100.0)); - MayersSampleCorrectionStrategy mscat(createTestParameters(), tof, signal, - error); + Histogram histo(Points(nypts, LinearGenerator(100.0, 1.0)), + Counts(nypts, 2.0)); + MayersSampleCorrectionStrategy mscat(createTestParameters(), histo); - // Correct it - mscat.apply(signal, error); + auto outHisto = mscat.getCorrectedHisto(); + + const auto &tof = outHisto.x(); + const auto &signal = outHisto.y(); + const auto &error = outHisto.e(); // Check some values const double delta(1e-06); @@ -73,18 +70,16 @@ public: void test_Corrects_Both_Absorption_And_Multiple_Scattering_For_Histogram_Data() { - using std::sqrt; const size_t nypts(100); - std::vector<double> signal(nypts, 2.0), tof(nypts + 1), error(nypts); - std::transform(signal.begin(), signal.end(), error.begin(), - (double (*)(double))sqrt); - // Generate a histogram with the same mid points as the point data example - std::generate(tof.begin(), tof.end(), Incrementer(99.5)); - MayersSampleCorrectionStrategy mscat(createTestParameters(), tof, signal, - error); + Histogram histo(BinEdges(nypts + 1, LinearGenerator(99.5, 1.0)), + Counts(nypts, 2.0)); + MayersSampleCorrectionStrategy mscat(createTestParameters(), histo); + + auto outHisto = mscat.getCorrectedHisto(); - // Correct it - mscat.apply(signal, error); + const auto &tof = outHisto.x(); + const auto &signal = outHisto.y(); + const auto &error = outHisto.e(); // Check some values const double delta(1e-06); @@ -99,19 +94,17 @@ public: } void test_Corrects_For_Absorption_For_Histogram_Data() { - using std::sqrt; const size_t nypts(100); - std::vector<double> signal(nypts, 2.0), tof(nypts + 1), error(nypts); - std::transform(signal.begin(), signal.end(), error.begin(), - (double (*)(double))sqrt); - // Generate a histogram with the same mid points as the point data example - std::generate(tof.begin(), tof.end(), Incrementer(99.5)); bool mscatOn(false); - MayersSampleCorrectionStrategy mscat(createTestParameters(mscatOn), tof, - signal, error); + Histogram histo(BinEdges(nypts + 1, LinearGenerator(99.5, 1.0)), + Counts(nypts, 2.0)); + MayersSampleCorrectionStrategy mscat(createTestParameters(mscatOn), histo); + + auto outHisto = mscat.getCorrectedHisto(); - // Correct it - mscat.apply(signal, error); + auto tof = outHisto.x(); + auto signal = outHisto.y(); + auto error = outHisto.e(); // Check some values const double delta(1e-06); @@ -127,29 +120,16 @@ public: // ---------------------- Failure tests ----------------------------- void test_Tof_Not_Monotonically_Increasing_Throws_Invalid_Argument() { - using std::sqrt; const size_t nypts(10); - std::vector<double> signal(nypts, 2.0), tof(nypts + 1), error(nypts); - std::transform(signal.begin(), signal.end(), error.begin(), - (double (*)(double))sqrt); - std::generate(tof.begin(), tof.end(), Decrementer(199.5)); - TS_ASSERT_THROWS(MayersSampleCorrectionStrategy(createTestParameters(), tof, - signal, error), - std::invalid_argument); + Histogram histo(BinEdges(nypts + 1, LinearGenerator(199.5, -1.0)), + Counts(nypts, 2.0)); + + TS_ASSERT_THROWS( + MayersSampleCorrectionStrategy(createTestParameters(), histo), + std::invalid_argument); } private: - struct Incrementer { - Incrementer(double start) : current(start) {} - double operator()() { return current++; } - double current; - }; - struct Decrementer { - Decrementer(double start) : current(start) {} - double operator()() { return current--; } - double current; - }; - MayersSampleCorrectionStrategy::Parameters createTestParameters(bool mscatOn = true) { // A bit like a POLARIS spectrum diff --git a/Framework/Algorithms/test/MayersSampleCorrectionTest.h b/Framework/Algorithms/test/MayersSampleCorrectionTest.h index d2080b7d1a5e0971164218c3e1a8e1a8cf272521..0e5c2e679ed0df8abb2a9b57ad38616c5e8f995b 100644 --- a/Framework/Algorithms/test/MayersSampleCorrectionTest.h +++ b/Framework/Algorithms/test/MayersSampleCorrectionTest.h @@ -34,9 +34,9 @@ public: TS_ASSERT(alg->isExecuted()); MatrixWorkspace_sptr corrected = alg->getProperty("OutputWorkspace"); - const auto &tof = corrected->readX(0); - const auto &signal = corrected->readY(0); - const auto &error = corrected->readE(0); + const auto &tof = corrected->x(0); + const auto &signal = corrected->y(0); + const auto &error = corrected->e(0); const double delta(1e-06); TS_ASSERT_DELTA(99.5, tof.front(), delta); TS_ASSERT_DELTA(199.5, tof.back(), delta); @@ -57,9 +57,9 @@ public: TS_ASSERT(alg->isExecuted()); MatrixWorkspace_sptr corrected = alg->getProperty("OutputWorkspace"); - const auto &tof = corrected->readX(0); - const auto &signal = corrected->readY(0); - const auto &error = corrected->readE(0); + const auto &tof = corrected->x(0); + const auto &signal = corrected->y(0); + const auto &error = corrected->e(0); const double delta(1e-06); TS_ASSERT_DELTA(99.5, tof.front(), delta); TS_ASSERT_DELTA(199.5, tof.back(), delta); diff --git a/Framework/Algorithms/test/NormaliseByCurrentTest.h b/Framework/Algorithms/test/NormaliseByCurrentTest.h index 4206e23427a3df8b2e086bf2fb7c04a1639a1f82..33d772f65e5ecb0d08079f1b25d44eafdda4d7e5 100644 --- a/Framework/Algorithms/test/NormaliseByCurrentTest.h +++ b/Framework/Algorithms/test/NormaliseByCurrentTest.h @@ -1,16 +1,16 @@ #ifndef NORMALISEBYCURRENTTEST_H_ #define NORMALISEBYCURRENTTEST_H_ -#include <cxxtest/TestSuite.h> #include "MantidTestHelpers/WorkspaceCreationHelper.h" +#include <cxxtest/TestSuite.h> -#include "MantidAlgorithms/NormaliseByCurrent.h" #include "MantidAPI/AnalysisDataService.h" #include "MantidAPI/Axis.h" #include "MantidAPI/WorkspaceGroup.h" -#include "MantidKernel/UnitFactory.h" -#include "MantidKernel/ArrayProperty.h" +#include "MantidAlgorithms/NormaliseByCurrent.h" #include "MantidDataObjects/EventWorkspace.h" +#include "MantidKernel/ArrayProperty.h" +#include "MantidKernel/UnitFactory.h" using namespace Mantid; using namespace Mantid::Kernel; @@ -18,77 +18,42 @@ using namespace Mantid::API; using namespace Mantid::Algorithms; using namespace Mantid::DataObjects; -class NormaliseByCurrentTest : public CxxTest::TestSuite { -private: - /// Helper method to add necessary log values to simulate multi-period data. - /// The algorithm uses these logs to determien how to normalise by the - /// current. - void addMultiPeriodLogsTo(MatrixWorkspace_sptr ws, int period, - const std::string &protonCharges) { - ArrayProperty<double> *chargeProp = - new ArrayProperty<double>("proton_charge_by_period", protonCharges); - PropertyWithValue<int> *nperiodsProp = - new PropertyWithValue<int>("nperiods", 3); - PropertyWithValue<int> *currentPeriodProp = - new PropertyWithValue<int>("current_period", period); - - ws->mutableRun().addLogData(chargeProp); - ws->mutableRun().addLogData(nperiodsProp); - ws->mutableRun().addLogData(currentPeriodProp); - } - -public: - void testName() { TS_ASSERT_EQUALS(norm.name(), "NormaliseByCurrent"); } - - void testVersion() { TS_ASSERT_EQUALS(norm.version(), 1); } - - void testInit() { - TS_ASSERT_THROWS_NOTHING(norm.initialize()); - TS_ASSERT(norm.isInitialized()); - } - - void testNotInitialized() { - if (!norm.isInitialized()) - norm.initialize(); +namespace { +MatrixWorkspace_const_sptr doTest(MatrixWorkspace_sptr inWS, + std::string wsNameOut, double expectedY, + double expectedE, bool performance = false) { + NormaliseByCurrent norm1; + if (!norm1.isInitialized()) + norm1.initialize(); - // Check it fails if properties haven't been set - TS_ASSERT_THROWS(norm.execute(), std::runtime_error); - TS_ASSERT(!norm.isExecuted()); + const auto &Y = inWS->y(0); + double initValue = Y[0]; + bool checkNormFactor = true; + if (initValue <= 0) { + checkNormFactor = false; } + double normFactor = initValue / expectedY; - MatrixWorkspace_const_sptr doTest(MatrixWorkspace_sptr inWS, - std::string wsNameOut, double expectedY, - double expectedE) { - NormaliseByCurrent norm1; - if (!norm1.isInitialized()) - norm1.initialize(); - - const MantidVec &Y = inWS->readY(0); - double initValue = Y[0]; - bool checkNormFactor = true; - if (initValue <= 0) { - checkNormFactor = false; - } - double normFactor = initValue / expectedY; + TS_ASSERT_THROWS_NOTHING(norm1.setProperty("InputWorkspace", inWS)); + TS_ASSERT_THROWS_NOTHING( + norm1.setPropertyValue("OutputWorkspace", wsNameOut)); - TS_ASSERT_THROWS_NOTHING(norm1.setProperty("InputWorkspace", inWS)); - TS_ASSERT_THROWS_NOTHING( - norm1.setPropertyValue("OutputWorkspace", wsNameOut)); + TS_ASSERT_THROWS_NOTHING(norm1.execute()); + TS_ASSERT(norm1.isExecuted()); - TS_ASSERT_THROWS_NOTHING(norm1.execute()); - TS_ASSERT(norm1.isExecuted()); + MatrixWorkspace_const_sptr output; + TS_ASSERT_THROWS_NOTHING( + output = + AnalysisDataService::Instance().retrieveWS<const MatrixWorkspace>( + wsNameOut)); - MatrixWorkspace_const_sptr output; - TS_ASSERT_THROWS_NOTHING( - output = - AnalysisDataService::Instance().retrieveWS<const MatrixWorkspace>( - wsNameOut)); + if (!performance) { for (size_t i = 0; i < output->getNumberHistograms(); i++) { - const MantidVec &inX = inWS->readX(i); - const MantidVec &X = output->readX(i); - const MantidVec &Y = output->dataY(i); - const MantidVec &E = output->dataE(i); + const auto &inX = inWS->x(i); + const auto &X = output->x(i); + const auto &Y = output->y(i); + const auto &E = output->e(i); for (size_t j = 0; j < Y.size(); j++) { TS_ASSERT_EQUALS(X[j], inX[j]); TS_ASSERT_EQUALS(Y[j], expectedY); @@ -109,25 +74,70 @@ public: double realFactor = (*pFactor)(); TS_ASSERT_DELTA(realFactor, normFactor, 1.e-5); } - - return output; } + return output; +} + +MatrixWorkspace_const_sptr doTest(std::string wsNameIn, std::string wsNameOut, + double expectedY, double expectedE, + bool performance = false) { + MatrixWorkspace_sptr inWS = + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsNameIn); + + // Now set the charge + inWS->mutableRun().setProtonCharge(2.0); + inWS->getAxis(0)->unit() = + Mantid::Kernel::UnitFactory::Instance().create("TOF"); + inWS->setYUnit("Counts"); + + return doTest(inWS, wsNameOut, expectedY, expectedE, performance); +} + +/// Helper method to add necessary log values to simulate multi-period data. +/// The algorithm uses these logs to determien how to normalise by the +/// current. +void addMultiPeriodLogsTo(MatrixWorkspace_sptr ws, int period, + const std::string &protonCharges) { + ArrayProperty<double> *chargeProp = + new ArrayProperty<double>("proton_charge_by_period", protonCharges); + PropertyWithValue<int> *nperiodsProp = + new PropertyWithValue<int>("nperiods", 3); + PropertyWithValue<int> *currentPeriodProp = + new PropertyWithValue<int>("current_period", period); + + ws->mutableRun().addLogData(chargeProp); + ws->mutableRun().addLogData(nperiodsProp); + ws->mutableRun().addLogData(currentPeriodProp); +} +} +class NormaliseByCurrentTest : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static NormaliseByCurrentTest *createSuite() { + return new NormaliseByCurrentTest(); + } + static void destroySuite(NormaliseByCurrentTest *suite) { delete suite; } - MatrixWorkspace_const_sptr doTest(std::string wsNameIn, std::string wsNameOut, - double expectedY, double expectedE) { - MatrixWorkspace_sptr inWS = - AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsNameIn); + void test_name() { TS_ASSERT_EQUALS(norm.name(), "NormaliseByCurrent"); } - // Now set the charge - inWS->mutableRun().setProtonCharge(2.0); - inWS->getAxis(0)->unit() = - Mantid::Kernel::UnitFactory::Instance().create("TOF"); - inWS->setYUnit("Counts"); + void test_version() { TS_ASSERT_EQUALS(norm.version(), 1); } + + void test_init() { + TS_ASSERT_THROWS_NOTHING(norm.initialize()); + TS_ASSERT(norm.isInitialized()); + } + + void test_notInitialized() { + if (!norm.isInitialized()) + norm.initialize(); - return doTest(inWS, wsNameOut, expectedY, expectedE); + // Check it fails if properties haven't been set + TS_ASSERT_THROWS(norm.execute(), std::runtime_error); + TS_ASSERT(!norm.isExecuted()); } - void testExec() { + void test_exec() { AnalysisDataService::Instance().add( "normIn", WorkspaceCreationHelper::Create2DWorkspaceBinned(10, 3, 1)); doTest("normIn", "normOut", 1.0, 0.5 * M_SQRT2); @@ -135,7 +145,7 @@ public: AnalysisDataService::Instance().remove("normOut"); } - void testMultiPeriodData() { + void test_multiPeriodData() { const std::string protonChargeByPeriod = "2.0, 4.0, 8.0"; // Note that CreateWorkspace123 creates uniform signal value of 2.0, and @@ -265,14 +275,14 @@ public: !alg.isExecuted()); } - void testExec_InPlace() { + void test_execInPlace() { AnalysisDataService::Instance().add( "normIn", WorkspaceCreationHelper::Create2DWorkspaceBinned(10, 3, 1)); doTest("normIn", "normIn", 1.0, 0.5 * M_SQRT2); AnalysisDataService::Instance().remove("normIn"); } - void testExecEvent() { + void test_execEvent() { AnalysisDataService::Instance().add( "normInEvent", WorkspaceCreationHelper::CreateEventWorkspace(10, 3, 100, 0.0, 1.0, 2)); @@ -287,7 +297,7 @@ public: AnalysisDataService::Instance().remove("normOutEvent"); } - void testExecEvent_InPlace() { + void test_execEventInPlace() { AnalysisDataService::Instance().add( "normInEvent", WorkspaceCreationHelper::CreateEventWorkspace(10, 3, 100, 0.0, 1.0, 2)); @@ -301,7 +311,7 @@ public: AnalysisDataService::Instance().remove("normInEvent"); } - void testExecZero() { + void test_execZero() { AnalysisDataService::Instance().add( "normIn", WorkspaceCreationHelper::Create2DWorkspace123(3, 10, 1)); @@ -332,4 +342,116 @@ private: NormaliseByCurrent norm; }; +class NormaliseByCurrentTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static NormaliseByCurrentTestPerformance *createSuite() { + return new NormaliseByCurrentTestPerformance(); + } + static void destroySuite(NormaliseByCurrentTestPerformance *suite) { + delete suite; + } + + /// Set up all the test workspaces + NormaliseByCurrentTestPerformance(int nHist = 1000, int nBins = 3000, + int nPixels = 200) { + // test_execPerformance + AnalysisDataService::Instance().add( + execWSIn, + WorkspaceCreationHelper::Create2DWorkspaceBinned(nHist, nBins, 1)); + + // test_execInPlacePerformance + AnalysisDataService::Instance().add( + execInPlaceWSIn, + WorkspaceCreationHelper::Create2DWorkspaceBinned(nHist, nBins, 1)); + + // test_execEventPerformance + AnalysisDataService::Instance().add( + execEventWSIn, WorkspaceCreationHelper::CreateEventWorkspace( + nHist, nBins, nPixels, 0.0, 1.0, 2)); + + // test_execEventInPlacePerformance + AnalysisDataService::Instance().add( + execEventInPlaceWSIn, WorkspaceCreationHelper::CreateEventWorkspace( + nHist, nBins, nPixels, 0.0, 1.0, 2)); + + // test_multiPeriodDataPerformance + const std::string protonChargeByPeriod = "2.0, 4.0, 8.0"; + + // Note that CreateWorkspace123 creates uniform signal value of 2.0, and + // uniform error value of 3.0. + multiPeriodWS1 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins, 1); + multiPeriodWS1->setYUnit("Counts"); + addMultiPeriodLogsTo(multiPeriodWS1, 1, protonChargeByPeriod); + + multiPeriodWS2 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins, 1); + multiPeriodWS2->setYUnit("Counts"); + addMultiPeriodLogsTo(multiPeriodWS2, 2, protonChargeByPeriod); + + multiPeriodWS3 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins, 1); + multiPeriodWS3->setYUnit("Counts"); + addMultiPeriodLogsTo(multiPeriodWS3, 3, protonChargeByPeriod); + } + + ~NormaliseByCurrentTestPerformance() { + // test_execPerformance + AnalysisDataService::Instance().remove(execWSIn); + AnalysisDataService::Instance().remove(execWSOut); + + // test_execInPlacePerformance + AnalysisDataService::Instance().remove(execInPlaceWSIn); + + // test_execEventPerformance + AnalysisDataService::Instance().remove(execEventWSIn); + AnalysisDataService::Instance().remove(execEventWSOut); + + // test_execEventInPlacePerformance + AnalysisDataService::Instance().remove(execEventInPlaceWSIn); + } + + void test_execPerformance() { + doTest(execWSIn, execWSOut, 1.0, 0.5 * M_SQRT2, performance); + } + void test_execInPlacePerformance() { + doTest(execInPlaceWSIn, execInPlaceWSIn, 1.0, 0.5 * M_SQRT2, performance); + } + + void test_execEventPerformance() { + EventWorkspace_const_sptr outputEvent; + outputEvent = boost::dynamic_pointer_cast<const EventWorkspace>( + doTest(execEventWSIn, execEventWSOut, 1.0, 0.5 * M_SQRT2, performance)); + } + void test_execEventInPlacePerformance() { + EventWorkspace_const_sptr outputEvent; + outputEvent = boost::dynamic_pointer_cast<const EventWorkspace>( + doTest(execEventInPlaceWSIn, execEventInPlaceWSIn, 1.0, 0.5 * M_SQRT2, + performance)); + } + void test_multiPeriodDataPerformance() { + + // Check that normalisation has used the protonChargeByPeriod data. i.e Yout + // = Yin/2.0, Yout = Yin/4.0, ... for each period workspace. + doTest(multiPeriodWS1, "period1", 1.00, 1.500, performance); // 2/2, 3/2 + doTest(multiPeriodWS2, "period2", 0.50, 0.750, performance); // 2/4, 3/4 + doTest(multiPeriodWS3, "period3", 0.25, 0.375, performance); // 2/8, 3/8 + } + +private: + const std::string execWSIn = "execWSIn"; + const std::string execWSOut = "execWSOut"; + const std::string execInPlaceWSIn = "execInPlaceWSIn"; + const std::string execEventWSIn = "execEventWSIn"; + const std::string execEventWSOut = "execEventWSOut"; + const std::string execEventInPlaceWSIn = "execEventInPlaceWSIn"; + + MatrixWorkspace_sptr multiPeriodWS1; + MatrixWorkspace_sptr multiPeriodWS2; + MatrixWorkspace_sptr multiPeriodWS3; + + const bool performance = true; +}; #endif /*NORMALISEBYCURRENTTEST_H_*/ diff --git a/Framework/Algorithms/test/NormaliseByDetectorTest.h b/Framework/Algorithms/test/NormaliseByDetectorTest.h index cb52664534e9dc736028cd61fc9914b1cf9197c1..852f8723b1acd9e95f7cfbacd178bf00d1586d73 100644 --- a/Framework/Algorithms/test/NormaliseByDetectorTest.h +++ b/Framework/Algorithms/test/NormaliseByDetectorTest.h @@ -1,21 +1,17 @@ #ifndef MANTID_ALGORITHMS_NORMALISEBYDETECTORTEST_H_ #define MANTID_ALGORITHMS_NORMALISEBYDETECTORTEST_H_ -#include <cxxtest/TestSuite.h> -#include "MantidKernel/Timer.h" -#include "MantidKernel/System.h" -#include "MantidAPI/WorkspaceGroup.h" #include "MantidAPI/FrameworkManager.h" +#include "MantidAPI/WorkspaceGroup.h" +#include "MantidKernel/Timer.h" #include <boost/format.hpp> -#include <boost/algorithm/string.hpp> +#include <cxxtest/TestSuite.h> -#include "MantidDataHandling/LoadParameterFile.h" -#include "MantidDataHandling/LoadEmptyInstrument.h" #include "MantidAlgorithms/NormaliseByDetector.h" +#include "MantidDataHandling/LoadParameterFile.h" #include "MantidTestHelpers/ComponentCreationHelper.h" -#include "MantidTestHelpers/WorkspaceCreationHelper.h" #include "MantidTestHelpers/ScopedFileHelper.h" -#include "MantidKernel/ConfigService.h" +#include "MantidTestHelpers/WorkspaceCreationHelper.h" using namespace Mantid; using namespace Mantid::Algorithms; @@ -347,7 +343,6 @@ public: } void test_workspace_with_instrument_only_fitting_functions() { - const std::string outWSName = "normalised_ws"; // Linear function 2*x + 1 applied to each x-value. INSTRUMENT LEVEL FIT // FUNCTION ONLY. MatrixWorkspace_sptr inputWS = create_workspace_with_fitting_functions(); @@ -360,25 +355,25 @@ public: // Test the application of the linear function for (size_t wsIndex = 0; wsIndex < outWS->getNumberHistograms(); ++wsIndex) { - const MantidVec &yValues = outWS->readY(wsIndex); - const MantidVec &xValues = outWS->readX(wsIndex); - const MantidVec &eValues = outWS->readE(wsIndex); + const auto &yValues = outWS->y(wsIndex); + const auto &xValues = outWS->x(wsIndex); + const auto &eValues = outWS->e(wsIndex); TS_ASSERT_EQUALS(3, yValues.size()); TS_ASSERT_EQUALS(3, eValues.size()); TS_ASSERT_EQUALS(4, xValues.size()); - const MantidVec &yInputValues = inputWS->readY(wsIndex); - const MantidVec &eInputValues = inputWS->readE(wsIndex); + const auto &yInputValues = inputWS->y(wsIndex); + const auto &eInputValues = inputWS->e(wsIndex); + const auto &wavelength = outWS->points(wsIndex); for (size_t binIndex = 0; binIndex < (xValues.size() - 1); ++binIndex) { - const double wavelength = - (xValues[binIndex] + xValues[binIndex + 1]) / 2; const double expectedValue = yInputValues[binIndex] / - ((2 * wavelength) + 1); // According to the equation written into - // the instrument parameter file for the - // instrument component link. + ((2 * wavelength[binIndex]) + + 1); // According to the equation written into + // the instrument parameter file for the + // instrument component link. TS_ASSERT_EQUALS(expectedValue, yValues[binIndex]); const double expectedError = (eInputValues[binIndex] * expectedValue) / @@ -390,7 +385,6 @@ public: } void test_compare_sequential_and_parallel_results() { - const std::string outWSName = "normalised_ws"; // Linear function 2*x + 1 applied to each x-value. INSTRUMENT LEVEL FIT // FUNCTION ONLY. MatrixWorkspace_sptr inputWS = create_workspace_with_fitting_functions(); @@ -409,13 +403,13 @@ public: // Test the application of the linear function for (size_t wsIndex = 0; wsIndex < inputWS->getNumberHistograms(); ++wsIndex) { - const MantidVec &yValuesParallel = outWS_parallel->readY(wsIndex); - const MantidVec &xValuesParallel = outWS_parallel->readX(wsIndex); - const MantidVec &eValuesParallel = outWS_parallel->readE(wsIndex); + const auto &yValuesParallel = outWS_parallel->y(wsIndex); + const auto &xValuesParallel = outWS_parallel->x(wsIndex); + const auto &eValuesParallel = outWS_parallel->e(wsIndex); - const MantidVec &yValuesSequential = outWS_sequential->readY(wsIndex); - const MantidVec &xValuesSequential = outWS_sequential->readX(wsIndex); - const MantidVec &eValuesSequential = outWS_sequential->readE(wsIndex); + const auto &yValuesSequential = outWS_sequential->y(wsIndex); + const auto &xValuesSequential = outWS_sequential->x(wsIndex); + const auto &eValuesSequential = outWS_sequential->e(wsIndex); // Compare against known sizes. TS_ASSERT_EQUALS(3, yValuesParallel.size()); @@ -426,19 +420,19 @@ public: TS_ASSERT_EQUALS(xValuesSequential.size(), xValuesParallel.size()); TS_ASSERT_EQUALS(eValuesSequential.size(), eValuesParallel.size()); - const MantidVec &yInputValues = inputWS->readY(wsIndex); - const MantidVec &xInputValues = inputWS->readX(wsIndex); - const MantidVec &eInputValues = inputWS->readE(wsIndex); + const auto &yInputValues = inputWS->y(wsIndex); + const auto &xInputValues = inputWS->x(wsIndex); + const auto &eInputValues = inputWS->e(wsIndex); + const auto &wavelength = inputWS->points(wsIndex); for (size_t binIndex = 0; binIndex < (xInputValues.size() - 1); ++binIndex) { - const double wavelength = - (xInputValues[binIndex] + xInputValues[binIndex + 1]) / 2; const double expectedValue = yInputValues[binIndex] / - ((2 * wavelength) + 1); // According to the equation written into - // the instrument parameter file for the - // instrument component link. + ((2 * wavelength[binIndex]) + + 1); // According to the equation written into + // the instrument parameter file for the + // instrument component link. // Compare against the known/calculated value. TS_ASSERT_EQUALS(expectedValue, yValuesParallel[binIndex]); // Compare results from different execution types. @@ -456,7 +450,6 @@ public: } void test_workspace_with_detector_level_only_fit_functions() { - const std::string outWSName = "normalised_ws"; // Linear function 1*x + N applied to each x-value, where N is the workspace // index. DETECTOR LEVEL FIT FUNCTIONS ONLY. MatrixWorkspace_sptr inputWS = @@ -470,23 +463,22 @@ public: // Test the application of the linear function for (size_t wsIndex = 0; wsIndex < outWS->getNumberHistograms(); ++wsIndex) { - const MantidVec &yValues = outWS->readY(wsIndex); - const MantidVec &xValues = outWS->readX(wsIndex); - const MantidVec &eValues = outWS->readE(wsIndex); + const auto &yValues = outWS->y(wsIndex); + const auto &xValues = outWS->x(wsIndex); + const auto &eValues = outWS->e(wsIndex); TS_ASSERT_EQUALS(3, yValues.size()); TS_ASSERT_EQUALS(3, eValues.size()); TS_ASSERT_EQUALS(4, xValues.size()); - const MantidVec &yInputValues = inputWS->readY(wsIndex); - const MantidVec &eInputValues = inputWS->readE(wsIndex); + const auto &yInputValues = inputWS->y(wsIndex); + const auto &eInputValues = inputWS->e(wsIndex); + const auto &wavelength = outWS->points(wsIndex); for (size_t binIndex = 0; binIndex < (xValues.size() - 1); ++binIndex) { - const double wavelength = - (xValues[binIndex] + xValues[binIndex + 1]) / 2; const double expectedValue = yInputValues[binIndex] / - ((1 * wavelength) + + ((1 * wavelength[binIndex]) + static_cast<double>(wsIndex)); // According to the equation written // into the instrument parameter // file for the detector component @@ -526,23 +518,22 @@ public: // Test the application of the linear function for (size_t wsIndex = 0; wsIndex < completeWS->getNumberHistograms(); ++wsIndex) { - const MantidVec &yValues = outWS->readY(wsIndex); - const MantidVec &xValues = outWS->readX(wsIndex); - const MantidVec &eValues = outWS->readE(wsIndex); + const auto &yValues = outWS->y(wsIndex); + const auto &xValues = outWS->x(wsIndex); + const auto &eValues = outWS->e(wsIndex); TS_ASSERT_EQUALS(3, yValues.size()); TS_ASSERT_EQUALS(3, eValues.size()); TS_ASSERT_EQUALS(4, xValues.size()); - const MantidVec &yInputValues = completeWS->readY(wsIndex); - const MantidVec &eInputValues = completeWS->readE(wsIndex); + const auto &yInputValues = completeWS->y(wsIndex); + const auto &eInputValues = completeWS->e(wsIndex); + const auto &wavelength = outWS->points(wsIndex); for (size_t binIndex = 0; binIndex < (xValues.size() - 1); ++binIndex) { - const double wavelength = - (xValues[binIndex] + xValues[binIndex + 1]) / 2; const double expectedValue = yInputValues[binIndex] / - ((1 * static_cast<double>(wsIndex) * wavelength) + + ((1 * static_cast<double>(wsIndex) * wavelength[binIndex]) + 3.0); // According to the equation written into the instrument // parameter file for the detector component link. const double expectedError = @@ -562,18 +553,6 @@ Performance Tests */ class NormaliseByDetectorTestPerformance : public CxxTest::TestSuite { -private: - MatrixWorkspace_sptr ws; - - /// Helper method to run common sanity checks. - void do_basic_checks(MatrixWorkspace_sptr normalisedWS) { - TS_ASSERT(normalisedWS != NULL); - TS_ASSERT(ws->getNumberHistograms() == normalisedWS->getNumberHistograms()); - TS_ASSERT(ws->readX(0).size() == normalisedWS->readX(0).size()); - TS_ASSERT(ws->readY(0).size() == normalisedWS->readY(0).size()); - TS_ASSERT(ws->readE(0).size() == normalisedWS->readE(0).size()); - } - public: static NormaliseByDetectorTestPerformance *createSuite() { return new NormaliseByDetectorTestPerformance(); @@ -660,6 +639,18 @@ public: // Run some basic sanity checks do_basic_checks(normalisedWS); } + +private: + /// Helper method to run common sanity checks. + void do_basic_checks(MatrixWorkspace_sptr normalisedWS) { + TS_ASSERT(normalisedWS != NULL); + TS_ASSERT(ws->getNumberHistograms() == normalisedWS->getNumberHistograms()); + TS_ASSERT(ws->x(0).size() == normalisedWS->x(0).size()); + TS_ASSERT(ws->y(0).size() == normalisedWS->y(0).size()); + TS_ASSERT(ws->e(0).size() == normalisedWS->e(0).size()); + } + + MatrixWorkspace_sptr ws; }; #endif /* MANTID_ALGORITHMS_NORMALISEBYDETECTORTEST_H_ */ diff --git a/Framework/Algorithms/test/NormaliseToMonitorTest.h b/Framework/Algorithms/test/NormaliseToMonitorTest.h index ddf1b0c52fd167466bc821cd9c3ffa45bdb89ae4..d25254cc9933d206e58da00a49ae110ec564161c 100644 --- a/Framework/Algorithms/test/NormaliseToMonitorTest.h +++ b/Framework/Algorithms/test/NormaliseToMonitorTest.h @@ -1,12 +1,12 @@ #ifndef NORMALISETOMONITORTEST_H_ #define NORMALISETOMONITORTEST_H_ -#include <cxxtest/TestSuite.h> #include "MantidTestHelpers/WorkspaceCreationHelper.h" +#include <cxxtest/TestSuite.h> -#include "MantidAlgorithms/NormaliseToMonitor.h" #include "MantidAPI/Axis.h" #include "MantidAPI/FrameworkManager.h" +#include "MantidAlgorithms/NormaliseToMonitor.h" #include "MantidGeometry/Instrument.h" #include "MantidKernel/UnitFactory.h" @@ -16,98 +16,80 @@ using namespace Mantid::Algorithms; using namespace Mantid::DataObjects; using Mantid::Geometry::Instrument; -class NormaliseToMonitorTest : public CxxTest::TestSuite { -public: - static NormaliseToMonitorTest *createSuite() { - return new NormaliseToMonitorTest(); - } - static void destroySuite(NormaliseToMonitorTest *suite) { delete suite; } - - void setUpWorkspace() { - MatrixWorkspace_sptr input = - WorkspaceCreationHelper::Create2DWorkspace123(3, 10, 1); - // Change the data in the monitor spectrum - input->dataY(0).assign(10, 10.0); - // Need to change bins - for (int i = 0; i < 11; ++i) { - input->dataX(0)[i] = i; - input->dataX(1)[i] = i; - input->dataX(2)[i] = i; - } - - input->getAxis(0)->unit() = - Mantid::Kernel::UnitFactory::Instance().create("Wavelength"); - // Now need to set up a minimal instrument - input->getSpectrum(0).setSpectrumNo(0); - input->getSpectrum(1).setSpectrumNo(1); - input->getSpectrum(2).setSpectrumNo(2); - boost::shared_ptr<Instrument> instr = boost::make_shared<Instrument>(); - input->setInstrument(instr); - Mantid::Geometry::Detector *mon = - new Mantid::Geometry::Detector("monitor", 0, NULL); - instr->add(mon); - instr->markAsMonitor(mon); - Mantid::Geometry::Detector *det = - new Mantid::Geometry::Detector("NOTmonitor", 1, NULL); - instr->add(det); - instr->markAsDetector(det); - - AnalysisDataService::Instance().addOrReplace("normMon", input); - - // Create a single spectrum workspace to be the monitor one - MatrixWorkspace_sptr monWS = - WorkspaceCreationHelper::Create2DWorkspaceBinned(1, 20, 0.1, 0.5); - monWS->getAxis(0)->unit() = - Mantid::Kernel::UnitFactory::Instance().create("Wavelength"); - // Now need to set up a minimal instrument and spectra-detector map - input->getSpectrum(0).setSpectrumNo(0); - monWS->setInstrument(input->getInstrument()); - - AnalysisDataService::Instance().addOrReplace("monWS", monWS); +// Anonymous namespace for shared methods between unit and performance test +namespace { +void setUpWorkspace(int histograms = 3, int bins = 10) { + MatrixWorkspace_sptr input = + WorkspaceCreationHelper::Create2DWorkspace123(histograms, bins, 1); + // Change the data in the monitor spectrum + input->mutableY(0).assign(bins, 10.0); + // Need to change bins + + auto &x0 = input->mutableX(0); + auto &x1 = input->mutableX(1); + auto &x2 = input->mutableX(2); + + for (int i = 0; i < bins + 1; ++i) { + x0[i] = i; + x1[i] = i; + x2[i] = i; } - void testName() { - NormaliseToMonitor norm; - TS_ASSERT_EQUALS(norm.name(), "NormaliseToMonitor") - } - - void testVersion() { - NormaliseToMonitor norm; - TS_ASSERT_EQUALS(norm.version(), 1) - } - - void testInit() { - NormaliseToMonitor norm; - TS_ASSERT_THROWS_NOTHING(norm.initialize()) - TS_ASSERT(norm.isInitialized()) - } - - void dotestExec(bool events, bool sameOutputWS) { - setUpWorkspace(); - - NormaliseToMonitor norm; - if (events) - FrameworkManager::Instance().exec( - "ConvertToEventWorkspace", 8, "InputWorkspace", "normMon", - "GenerateZeros", "1", "GenerateMultipleEvents", "0", - "OutputWorkspace", "normMon"); - - if (!norm.isInitialized()) - norm.initialize(); - // Check it fails if properties haven't been set - TS_ASSERT_THROWS(norm.execute(), std::runtime_error) - TS_ASSERT(!norm.isExecuted()) - TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("InputWorkspace", "normMon")) - std::string outputWS("normMon"); - if (!sameOutputWS) - outputWS.append("2"); - TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("OutputWorkspace", outputWS)) - TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("MonitorSpectrum", "0")) - TS_ASSERT_THROWS_NOTHING( - norm.setPropertyValue("NormFactorWS", "NormFactor")) - TS_ASSERT_THROWS_NOTHING(norm.execute()) - TS_ASSERT(norm.isExecuted()) - + input->getAxis(0)->unit() = + Mantid::Kernel::UnitFactory::Instance().create("Wavelength"); + // Now need to set up a minimal instrument + input->getSpectrum(0).setSpectrumNo(0); + input->getSpectrum(1).setSpectrumNo(1); + input->getSpectrum(2).setSpectrumNo(2); + boost::shared_ptr<Instrument> instr = boost::make_shared<Instrument>(); + input->setInstrument(instr); + Mantid::Geometry::Detector *mon = + new Mantid::Geometry::Detector("monitor", 0, NULL); + instr->add(mon); + instr->markAsMonitor(mon); + Mantid::Geometry::Detector *det = + new Mantid::Geometry::Detector("NOTmonitor", 1, NULL); + instr->add(det); + instr->markAsDetector(det); + + AnalysisDataService::Instance().addOrReplace("normMon", input); + + // Create a single spectrum workspace to be the monitor one + MatrixWorkspace_sptr monWS = + WorkspaceCreationHelper::Create2DWorkspaceBinned(1, 20, 0.1, 0.5); + monWS->getAxis(0)->unit() = + Mantid::Kernel::UnitFactory::Instance().create("Wavelength"); + // Now need to set up a minimal instrument and spectra-detector map + input->getSpectrum(0).setSpectrumNo(0); + monWS->setInstrument(input->getInstrument()); + + AnalysisDataService::Instance().addOrReplace("monWS", monWS); +} +void dotestExec(bool events, bool sameOutputWS, bool performance = false) { + NormaliseToMonitor norm; + if (events) + FrameworkManager::Instance().exec( + "ConvertToEventWorkspace", 8, "InputWorkspace", "normMon", + "GenerateZeros", "1", "GenerateMultipleEvents", "0", "OutputWorkspace", + "normMon"); + + if (!norm.isInitialized()) + norm.initialize(); + // Check it fails if properties haven't been set + TS_ASSERT_THROWS(norm.execute(), std::runtime_error) + TS_ASSERT(!norm.isExecuted()) + TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("InputWorkspace", "normMon")) + std::string outputWS("normMon"); + if (!sameOutputWS) + outputWS.append("2"); + TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("OutputWorkspace", outputWS)) + TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("MonitorSpectrum", "0")) + TS_ASSERT_THROWS_NOTHING(norm.setPropertyValue("NormFactorWS", "NormFactor")) + TS_ASSERT_THROWS_NOTHING(norm.execute()) + TS_ASSERT(norm.isExecuted()) + + // if not a performance test do all the checks + if (!performance) { MatrixWorkspace_const_sptr output; TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( @@ -115,18 +97,24 @@ public: // Check the non-monitor spectra for (size_t i = 1; i < output->getNumberHistograms(); ++i) { + const auto &x = output->x(i); + const auto &y = output->y(i); + const auto &e = output->e(i); for (size_t j = 0; j < output->blocksize(); ++j) { - TS_ASSERT_EQUALS(output->readX(i)[j], j) - TS_ASSERT_DELTA(output->readY(i)[j], 2, 0.00001) - TS_ASSERT_DELTA(output->readE(i)[j], 3.05941, 0.00001) + TS_ASSERT_EQUALS(x[j], j) + TS_ASSERT_DELTA(y[j], 2, 0.00001) + TS_ASSERT_DELTA(e[j], 3.05941, 0.00001) } } // Now check the monitor one + const auto &monX = output->x(0); + const auto &monY = output->y(0); + const auto &monE = output->e(0); for (size_t k = 0; k < output->blocksize(); ++k) { - TS_ASSERT_EQUALS(output->readX(0)[k], k) - TS_ASSERT_DELTA(output->readY(0)[k], 10, 0.00001) - TS_ASSERT_DELTA(output->readE(0)[k], 4.24264, 0.00001) + TS_ASSERT_EQUALS(monX[k], k) + TS_ASSERT_DELTA(monY[k], 10, 0.00001) + TS_ASSERT_DELTA(monE[k], 4.24264, 0.00001) } if (events) { @@ -140,14 +128,51 @@ public: TS_ASSERT_EQUALS(output->getNumberHistograms(), 1); AnalysisDataService::Instance().remove("NormFactor"); } +} +} - void testExec() { dotestExec(false, false); } +class NormaliseToMonitorTest : public CxxTest::TestSuite { +public: + static NormaliseToMonitorTest *createSuite() { + return new NormaliseToMonitorTest(); + } + static void destroySuite(NormaliseToMonitorTest *suite) { delete suite; } + + void testName() { + NormaliseToMonitor norm; + TS_ASSERT_EQUALS(norm.name(), "NormaliseToMonitor") + } + + void testVersion() { + NormaliseToMonitor norm; + TS_ASSERT_EQUALS(norm.version(), 1) + } + + void testInit() { + NormaliseToMonitor norm; + TS_ASSERT_THROWS_NOTHING(norm.initialize()) + TS_ASSERT(norm.isInitialized()) + } - void testExec_Events() { dotestExec(true, false); } + void testExec() { + setUpWorkspace(); + dotestExec(false, false); + } - void testExec_inplace() { dotestExec(false, true); } + void testExec_Events() { + setUpWorkspace(); + dotestExec(true, false); + } - void testExec_Events_inplace() { dotestExec(true, true); } + void testExec_inplace() { + setUpWorkspace(); + dotestExec(false, true); + } + + void testExec_Events_inplace() { + setUpWorkspace(); + dotestExec(true, true); + } void testNormaliseByIntegratedCount() { setUpWorkspace(); @@ -175,18 +200,24 @@ public: // Check the non-monitor spectra for (size_t i = 1; i < output->getNumberHistograms(); ++i) { + auto &x = output->x(i); + auto &y = output->y(i); + auto &e = output->e(i); for (size_t j = 0; j < output->blocksize(); ++j) { - TS_ASSERT_EQUALS(output->readX(i)[j], j) - TS_ASSERT_EQUALS(output->readY(i)[j], 0.04) - TS_ASSERT_DELTA(output->readE(i)[j], 0.0602, 0.0001) + TS_ASSERT_EQUALS(x[j], j) + TS_ASSERT_EQUALS(y[j], 0.04) + TS_ASSERT_DELTA(e[j], 0.0602, 0.0001) } } // Now check the monitor one + auto &monitorX = output->x(0); + auto &monitorY = output->y(0); + auto &monitorE = output->e(0); for (size_t k = 0; k < output->blocksize(); ++k) { - TS_ASSERT_EQUALS(output->readX(0)[k], k) - TS_ASSERT_EQUALS(output->readY(0)[k], 0.2) - TS_ASSERT_DELTA(output->readE(0)[k], 0.0657, 0.0001) + TS_ASSERT_EQUALS(monitorX[k], k) + TS_ASSERT_EQUALS(monitorY[k], 0.2) + TS_ASSERT_DELTA(monitorE[k], 0.0657, 0.0001) } TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( @@ -220,18 +251,24 @@ public: // Check the non-monitor spectra for (size_t i = 1; i < output->getNumberHistograms(); ++i) { + auto &x = output->x(i); + auto &y = output->y(i); + auto &e = output->e(i); for (size_t j = 0; j < output->blocksize(); ++j) { - TS_ASSERT_EQUALS(output->readX(i)[j], j) - TS_ASSERT_DELTA(output->readY(i)[j], 0.0323, 0.0001) - TS_ASSERT_DELTA(output->readE(i)[j], 0.0485, 0.0001) + TS_ASSERT_EQUALS(x[j], j) + TS_ASSERT_DELTA(y[j], 0.0323, 0.0001) + TS_ASSERT_DELTA(e[j], 0.0485, 0.0001) } } // Now check the monitor one + auto &monitorX = output->x(0); + auto &monitorY = output->y(0); + auto &monitorE = output->e(0); for (size_t k = 0; k < output->blocksize(); ++k) { - TS_ASSERT_EQUALS(output->readX(0)[k], k) - TS_ASSERT_DELTA(output->readY(0)[k], 0.1613, 0.0001) - TS_ASSERT_DELTA(output->readE(0)[k], 0.0518, 0.0001) + TS_ASSERT_EQUALS(monitorX[k], k) + TS_ASSERT_DELTA(monitorY[k], 0.1613, 0.0001) + TS_ASSERT_DELTA(monitorE[k], 0.0518, 0.0001) } AnalysisDataService::Instance().remove("normMon4"); TS_ASSERT(!AnalysisDataService::Instance().doesExist("NormWS")); @@ -351,6 +388,8 @@ public: // it should return the list of allowed monitor ID-s std::vector<std::string> monitors = monSpec->allowedValues(); TS_ASSERT_EQUALS(1, monitors.size()); + + // dereferencing the iterator to get monitors[0] TS_ASSERT_EQUALS("0", *(monitors.begin())); // now deal with ws without monitors @@ -376,4 +415,21 @@ public: } }; +class NormaliseToMonitorTestPerformance : public CxxTest::TestSuite { +public: + static NormaliseToMonitorTestPerformance *createSuite() { + return new NormaliseToMonitorTestPerformance(); + } + static void destroySuite(NormaliseToMonitorTestPerformance *suite) { + delete suite; + } + + NormaliseToMonitorTestPerformance() { setUpWorkspace(100, 1000); } + void testExec() { dotestExec(false, false, performance); } + + void testExec_Events() { dotestExec(true, false, performance); } + +private: + const bool performance = true; +}; #endif /*NORMALISETOMONITORTEST_H_*/ diff --git a/Framework/Algorithms/test/PDCalibrationTest.h b/Framework/Algorithms/test/PDCalibrationTest.h index 6381e57a792e214e6c27e0a7537b9828adf3cfc4..650cfadc4b9bd85a643df3c5f5b31d768470c417 100644 --- a/Framework/Algorithms/test/PDCalibrationTest.h +++ b/Framework/Algorithms/test/PDCalibrationTest.h @@ -20,6 +20,29 @@ using Mantid::API::FrameworkManager; using Mantid::API::AnalysisDataService; using Mantid::Algorithms::CreateSampleWorkspace; +namespace { +/** +* Creates a workspace with peaks at 400, 800, 1300, 1600 us +*/ +void createSampleWS() { + CreateSampleWorkspace sampleWS; + sampleWS.initialize(); + sampleWS.setPropertyValue("WorkspaceType", "Event"); + sampleWS.setPropertyValue("Function", "User Defined"); + sampleWS.setPropertyValue( + "UserDefinedFunction", + "name=Gaussian,Height=100,PeakCentre=400,Sigma=10;" + "name=Gaussian,Height=80,PeakCentre=800,Sigma=12;" + "name=Gaussian,Height=350,PeakCentre=1300,Sigma=12;" + "name=Gaussian,Height=210,PeakCentre=1600,Sigma=15"); + sampleWS.setProperty("XMin", 100.0); + sampleWS.setProperty("XMax", 2000.0); + sampleWS.setProperty("BinWidth", 1.0); + sampleWS.setPropertyValue("OutputWorkspace", "PDCalibrationTest_WS"); + sampleWS.execute(); +} +} + class PDCalibrationTest : public CxxTest::TestSuite { public: // This pair of boilerplate methods prevent the suite being created statically @@ -29,26 +52,7 @@ public: PDCalibrationTest() { FrameworkManager::Instance(); } - void setUp() override { - /** - * Creates a workspace with peaks at 400, 800, 1300, 1600 us - */ - CreateSampleWorkspace create; - create.initialize(); - create.setPropertyValue("WorkspaceType", "Event"); - create.setPropertyValue("Function", "User Defined"); - create.setPropertyValue( - "UserDefinedFunction", - "name=Gaussian,Height=100,PeakCentre=400,Sigma=10;" - "name=Gaussian,Height=80,PeakCentre=800,Sigma=12;" - "name=Gaussian,Height=350,PeakCentre=1300,Sigma=12;" - "name=Gaussian,Height=210,PeakCentre=1600,Sigma=15"); - create.setProperty("XMin", 100.0); - create.setProperty("XMax", 2000.0); - create.setProperty("BinWidth", 1.0); - create.setPropertyValue("OutputWorkspace", "PDCalibrationTest_WS"); - create.execute(); - } + void setUp() override { createSampleWS(); } void test_Init() { PDCalibration alg; @@ -101,6 +105,7 @@ public: TS_ASSERT_EQUALS(mask->y(182)[0], 0); TS_ASSERT_EQUALS(mask->y(183)[0], 1); } + void test_exec_difc_tzero() { PDCalibration alg; TS_ASSERT_THROWS_NOTHING(alg.initialize()) @@ -203,4 +208,40 @@ public: } }; +class PDCalibrationTestPerformance : public CxxTest::TestSuite { + +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PDCalibrationTestPerformance *createSuite() { + return new PDCalibrationTestPerformance(); + } + + static void destroySuite(PDCalibrationTestPerformance *suite) { + delete suite; + } + + PDCalibrationTestPerformance() { FrameworkManager::Instance(); } + + void setUp() override { + createSampleWS(); + pdc.initialize(); + pdc.setProperty("SignalWorkspace", "PDCalibrationTest_WS"); + pdc.setPropertyValue("TofBinning", "200,1.0,2000"); + pdc.setPropertyValue("PeakWindow", "1"); + pdc.setPropertyValue("OutputCalibrationTable", "outputWS"); + pdc.setPropertyValue("PeakPositions", "9.523809, 22.222222, " + "38.095238, 47.619047"); + } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove("outputWS"); + } + + void testPerformanceWS() { pdc.execute(); } + +private: + PDCalibration pdc; +}; + #endif /* MANTID_ALGORITHMS_PDCALIBRATIONTEST_H_ */ diff --git a/Framework/Algorithms/test/PDFFourierTransformTest.h b/Framework/Algorithms/test/PDFFourierTransformTest.h index f50088bedd486fd8fe1ca9b1ff9f82383828201b..7b731a526aa03f530e953ae3749dedaf2140ac76 100644 --- a/Framework/Algorithms/test/PDFFourierTransformTest.h +++ b/Framework/Algorithms/test/PDFFourierTransformTest.h @@ -21,6 +21,45 @@ using namespace Mantid::Algorithms; using namespace Mantid::Kernel; using namespace Mantid; +namespace { +/** +* Create Workspace from 0 to N*dx +*/ +Mantid::API::MatrixWorkspace_sptr createWS(size_t n, double dx, + const std::string &name, + const std::string unitlabel, + const bool withBadValues = false) { + + Mantid::API::FrameworkManager::Instance(); + Mantid::DataObjects::Workspace2D_sptr ws = + boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( + Mantid::API::WorkspaceFactory::Instance().create("Workspace2D", 1, n, + n)); + + auto &X = ws->mutableX(0); + auto &Y = ws->mutableY(0); + auto &E = ws->mutableE(0); + + for (size_t i = 0; i < n; i++) { + X[i] = double(i) * dx; + Y[i] = X[i] + 1.0; + E[i] = sqrt(fabs(X[i])); + } + + if (withBadValues) { + Y[0] = std::numeric_limits<double>::quiet_NaN(); + Y[Y.size() - 1] = std::numeric_limits<double>::quiet_NaN(); + } + + ws->getAxis(0)->unit() = + Mantid::Kernel::UnitFactory::Instance().create(unitlabel); + + Mantid::API::AnalysisDataService::Instance().add(name, ws); + + return ws; +} +} + class PDFFourierTransformTest : public CxxTest::TestSuite { public: void test_Init() { @@ -75,8 +114,8 @@ public: DataObjects::Workspace2D_sptr pdfws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( API::AnalysisDataService::Instance().retrieve("PDFGofR")); - MantidVec &R = pdfws->dataX(0); - MantidVec &GofR = pdfws->dataY(0); + const auto R = pdfws->x(0); + const auto GofR = pdfws->y(0); TS_ASSERT_DELTA(R[0], 0.01, 0.0001); TS_ASSERT_DELTA(R[249], 2.5, 0.0001); @@ -109,8 +148,8 @@ public: DataObjects::Workspace2D_sptr pdfws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( API::AnalysisDataService::Instance().retrieve("PDFGofR")); - MantidVec &R = pdfws->dataX(0); - MantidVec &GofR = pdfws->dataY(0); + const auto R = pdfws->x(0); + const auto GofR = pdfws->y(0); TS_ASSERT_DELTA(R[0], 0.01, 0.0001); TS_ASSERT_DELTA(R[249], 2.5, 0.0001); @@ -123,7 +162,7 @@ public: void test_filter() { API::MatrixWorkspace_sptr ws = createWS(200, 0.1, "filter", "MomentumTransfer"); - MantidVec &SofQ = ws->dataY(0); + auto &SofQ = ws->mutableY(0); for (size_t i = 0; i < SofQ.size(); i++) { SofQ[i] = 1.0; } @@ -146,7 +185,7 @@ public: DataObjects::Workspace2D_sptr pdfws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( API::AnalysisDataService::Instance().retrieve("PDFGofR")); - MantidVec &GofR = pdfws->dataY(0); + const auto GofR = pdfws->y(0); TS_ASSERT(GofR[0] > 40.0); for (size_t i = 1; i < GofR.size(); i++) { @@ -155,44 +194,46 @@ public: Mantid::API::AnalysisDataService::Instance().clear(); } +}; -private: - /** - * Create Workspace from 0 to N*dx - */ - Mantid::API::MatrixWorkspace_sptr createWS(size_t n, double dx, - const std::string &name, - const std::string unitlabel, - const bool withBadValues = false) { - - Mantid::API::FrameworkManager::Instance(); - Mantid::DataObjects::Workspace2D_sptr ws = - boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( - Mantid::API::WorkspaceFactory::Instance().create("Workspace2D", 1, - n, n)); - - Mantid::MantidVec &X = ws->dataX(0); - Mantid::MantidVec &Y = ws->dataY(0); - Mantid::MantidVec &E = ws->dataE(0); - - for (size_t i = 0; i < n; i++) { - X[i] = double(i) * dx; - Y[i] = X[i] + 1.0; - E[i] = sqrt(fabs(X[i])); - } +class PDFFourierTransformTestPerformance : public CxxTest::TestSuite { - if (withBadValues) { - Y[0] = std::numeric_limits<double>::quiet_NaN(); - Y[Y.size() - 1] = std::numeric_limits<double>::quiet_NaN(); - } +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PDFFourierTransformTestPerformance *createSuite() { + return new PDFFourierTransformTestPerformance(); + } - ws->getAxis(0)->unit() = - Mantid::Kernel::UnitFactory::Instance().create(unitlabel); + static void destroySuite(PDFFourierTransformTestPerformance *suite) { + delete suite; + } - Mantid::API::AnalysisDataService::Instance().add(name, ws); + void setUp() override { + ws = createWS(2000000, 0.1, "inputWS", "MomentumTransfer"); + pdfft = Mantid::API::FrameworkManager::Instance().createAlgorithm( + "PDFFourierTransform"); - return ws; + pdfft->initialize(); + pdfft->setProperty("InputWorkspace", ws); + pdfft->setProperty("OutputWorkspace", "outputWS"); + pdfft->setProperty("InputSofQType", "S(Q)"); + pdfft->setProperty("Rmax", 20.0); + pdfft->setProperty("DeltaR", 0.01); + pdfft->setProperty("Qmin", 0.0); + pdfft->setProperty("Qmax", 30.0); + pdfft->setProperty("PDFType", "G(r)"); + } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove("outputWS"); } + + void testPerformanceWS() { pdfft->execute(); } + +private: + Mantid::API::MatrixWorkspace_sptr ws; + API::IAlgorithm *pdfft; }; #endif /* MANTID_ALGORITHMS_PDFFOURIERTRANSFORMTEST_H_ */ diff --git a/Framework/Algorithms/test/PhaseQuadMuonTest.h b/Framework/Algorithms/test/PhaseQuadMuonTest.h index b3f39bc0d1f1fd480d9b1a3933f447227305736d..ec8dfc94a65b43a12950ba7b39ebef118e30d0ff 100644 --- a/Framework/Algorithms/test/PhaseQuadMuonTest.h +++ b/Framework/Algorithms/test/PhaseQuadMuonTest.h @@ -11,6 +11,49 @@ using namespace Mantid::DataObjects; using namespace Mantid::API; +namespace { +void populatePhaseTable(ITableWorkspace_sptr phaseTable) { + phaseTable->addColumn("int", "DetectorID"); + phaseTable->addColumn("double", "DetectorAsymmetry"); + phaseTable->addColumn("double", "DetectorPhase"); + for (int i = 0; i < 16; i++) { + TableRow phaseRow1 = phaseTable->appendRow(); + phaseRow1 << i << 1. << 0.; + TableRow phaseRow2 = phaseTable->appendRow(); + phaseRow2 << i << 1. << 1.57; + } +} + +IAlgorithm_sptr setupAlg(MatrixWorkspace_sptr inputWs, bool isChildAlg) { + // Create and populate a detector table + boost::shared_ptr<ITableWorkspace> phaseTable( + new Mantid::DataObjects::TableWorkspace); + populatePhaseTable(phaseTable); + + // Set up PhaseQuad + IAlgorithm_sptr phaseQuad = AlgorithmManager::Instance().create("PhaseQuad"); + phaseQuad->setChild(isChildAlg); + phaseQuad->initialize(); + phaseQuad->setProperty("InputWorkspace", inputWs); + phaseQuad->setProperty("PhaseTable", phaseTable); + phaseQuad->setPropertyValue("OutputWorkspace", "outputWs"); + return phaseQuad; +} + +MatrixWorkspace_sptr loadMuonDataset() { + IAlgorithm_sptr loader = AlgorithmManager::Instance().create("Load"); + loader->setChild(true); + loader->initialize(); + loader->setProperty("Filename", "emu00006473.nxs"); + loader->setPropertyValue("OutputWorkspace", "outputWs"); + loader->execute(); + Workspace_sptr temp = loader->getProperty("OutputWorkspace"); + MatrixWorkspace_sptr inputWs = + boost::dynamic_pointer_cast<MatrixWorkspace>(temp); + return inputWs; +} +} + class PhaseQuadMuonTest : public CxxTest::TestSuite { public: void testTheBasics() { @@ -23,30 +66,8 @@ public: } void testExecPhaseTable() { - // Load a muon dataset - IAlgorithm_sptr loader = AlgorithmManager::Instance().create("Load"); - loader->setChild(true); - loader->initialize(); - loader->setProperty("Filename", "emu00006473.nxs"); - loader->setPropertyValue("OutputWorkspace", "out_ws"); - loader->execute(); - Workspace_sptr temp = loader->getProperty("OutputWorkspace"); - MatrixWorkspace_sptr inputWs = - boost::dynamic_pointer_cast<MatrixWorkspace>(temp); - - // Create and populate a detector table - boost::shared_ptr<ITableWorkspace> phaseTable( - new Mantid::DataObjects::TableWorkspace); - populatePhaseTable(phaseTable); - - // Run PhaseQuad - IAlgorithm_sptr phaseQuad = - AlgorithmManager::Instance().create("PhaseQuad"); - phaseQuad->setChild(true); - phaseQuad->initialize(); - phaseQuad->setProperty("InputWorkspace", inputWs); - phaseQuad->setProperty("PhaseTable", phaseTable); - phaseQuad->setPropertyValue("OutputWorkspace", "out_ws"); + MatrixWorkspace_sptr inputWs = loadMuonDataset(); + IAlgorithm_sptr phaseQuad = setupAlg(inputWs, true); TS_ASSERT_THROWS_NOTHING(phaseQuad->execute()); TS_ASSERT(phaseQuad->isExecuted()); @@ -60,10 +81,10 @@ public: TS_ASSERT_EQUALS(outputWs->getSpectrum(1).readX(), inputWs->getSpectrum(1).readX()); - auto specReY = outputWs->getSpectrum(0).readY(); - auto specReE = outputWs->getSpectrum(0).readE(); - auto specImY = outputWs->getSpectrum(1).readY(); - auto specImE = outputWs->getSpectrum(1).readE(); + const auto specReY = outputWs->getSpectrum(0).y(); + const auto specReE = outputWs->getSpectrum(0).e(); + const auto specImY = outputWs->getSpectrum(1).y(); + const auto specImE = outputWs->getSpectrum(1).e(); // Check real Y values TS_ASSERT_DELTA(specReY[0], -0.9982, 0.0001); TS_ASSERT_DELTA(specReY[20], -0.0252, 0.0001); @@ -81,18 +102,35 @@ public: TS_ASSERT_DELTA(specImE[20], 0.0031, 0.0001); TS_ASSERT_DELTA(specImE[50], 0.0035, 0.0001); } +}; + +class PhaseQuadMuonTestPerformance : public CxxTest::TestSuite { + +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PhaseQuadMuonTestPerformance *createSuite() { + return new PhaseQuadMuonTestPerformance(); + } + + static void destroySuite(PhaseQuadMuonTestPerformance *suite) { + delete suite; + } - void populatePhaseTable(ITableWorkspace_sptr phaseTable) { - phaseTable->addColumn("int", "DetectorID"); - phaseTable->addColumn("double", "DetectorAsymmetry"); - phaseTable->addColumn("double", "DetectorPhase"); - for (int i = 0; i < 16; i++) { - TableRow phaseRow1 = phaseTable->appendRow(); - phaseRow1 << i << 1. << 0.; - TableRow phaseRow2 = phaseTable->appendRow(); - phaseRow2 << i << 1. << 1.57; - } + void setUp() override { + inputWs = loadMuonDataset(); + phaseQuad = setupAlg(inputWs, false); } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove("outputWs"); + } + + void testPerformanceWs() { phaseQuad->execute(); } + +private: + MatrixWorkspace_sptr inputWs; + IAlgorithm_sptr phaseQuad; }; #endif /* MANTID_ALGORITHMS_PHASEQUADMUONTEST_H_ */ \ No newline at end of file diff --git a/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h b/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h index 64b6d539043899d3825911495e92593d111b2e9d..3d046d0773ff25f594d96d56a23be808aa9ee9e5 100644 --- a/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h +++ b/Framework/Algorithms/test/PlotAsymmetryByLogValueTest.h @@ -109,7 +109,6 @@ public: return new PlotAsymmetryByLogValueTest(); } static void destroySuite(PlotAsymmetryByLogValueTest *suite) { delete suite; } - PlotAsymmetryByLogValueTest() : firstRun("MUSR00015189.nxs"), lastRun("MUSR00015190.nxs") {} @@ -136,7 +135,7 @@ public: TS_ASSERT(outWS); TS_ASSERT_EQUALS(outWS->blocksize(), 2); TS_ASSERT_EQUALS(outWS->getNumberHistograms(), 4); - const Mantid::MantidVec &Y = outWS->readY(0); + const auto Y = outWS->y(0); TS_ASSERT_DELTA(Y[0], 0.0128845, 0.001); TS_ASSERT_DELTA(Y[1], 0.0224898, 0.00001); @@ -172,7 +171,7 @@ public: TS_ASSERT(outWS); TS_ASSERT_EQUALS(outWS->blocksize(), 2); TS_ASSERT_EQUALS(outWS->getNumberHistograms(), 4); - const Mantid::MantidVec &Y = outWS->readY(0); + const auto Y = outWS->y(0); TS_ASSERT_DELTA(Y[0], -0.01236, 0.001); TS_ASSERT_DELTA(Y[1], 0.019186, 0.00001); } @@ -280,7 +279,7 @@ public: TS_ASSERT_EQUALS(outWs->blocksize(), 2); TS_ASSERT_EQUALS(outWs->getNumberHistograms(), 1); - const Mantid::MantidVec &Y = outWs->readY(0); + const auto Y = outWs->y(0); TS_ASSERT_DELTA(Y[0], 0.15214, 0.00001); TS_ASSERT_DELTA(Y[1], 0.14492, 0.00001); @@ -313,7 +312,7 @@ public: TS_ASSERT_EQUALS(outWs->blocksize(), 2); TS_ASSERT_EQUALS(outWs->getNumberHistograms(), 1); - const Mantid::MantidVec &Y = outWs->readY(0); + const auto Y = outWs->y(0); TS_ASSERT_DELTA(Y[0], 0.151202, 0.00001); TS_ASSERT_DELTA(Y[1], 0.144008, 0.00001); @@ -348,10 +347,10 @@ public: TS_ASSERT_EQUALS(outWs->blocksize(), 2); TS_ASSERT_EQUALS(outWs->getNumberHistograms(), 4); - const Mantid::MantidVec &YDiff = outWs->readY(0); - const Mantid::MantidVec &EDiff = outWs->readE(0); - const Mantid::MantidVec &YSum = outWs->readY(3); - const Mantid::MantidVec &ESum = outWs->readE(3); + const auto YDiff = outWs->y(0); + const auto EDiff = outWs->e(0); + const auto YSum = outWs->y(3); + const auto ESum = outWs->e(3); TS_ASSERT_DELTA(YDiff[0], 0.001135, 0.000001); TS_ASSERT_DELTA(EDiff[0], 0.001805, 0.000001); @@ -388,7 +387,7 @@ public: TS_ASSERT_EQUALS(outWs->blocksize(), 2); TS_ASSERT_EQUALS(outWs->getNumberHistograms(), 1); - const Mantid::MantidVec &Y = outWs->readY(0); + const auto Y = outWs->y(0); TS_ASSERT_DELTA(Y[0], 0.14700, 0.00001); TS_ASSERT_DELTA(Y[1], 0.13042, 0.00001); } @@ -422,7 +421,7 @@ public: // Now we want to test X values (log values) in the output workspace // rather than asymmetry (Y values) - const Mantid::MantidVec &X = outWs->readX(0); + const auto X = outWs->x(0); TS_ASSERT_DELTA(X[0], 178.740476, 0.00001); TS_ASSERT_DELTA(X[1], 178.849998, 0.00001); @@ -448,7 +447,6 @@ public: // number. The algorithm should ignore the supplied green and/or red periods // as the input nexus file is single-period const std::string ws = "Test_singlePeriodGreen"; - PlotAsymmetryByLogValue alg; alg.initialize(); alg.setPropertyValue("FirstRun", "emu00006473.nxs"); @@ -468,9 +466,9 @@ public: TS_ASSERT_EQUALS(outWS->blocksize(), 1); TS_ASSERT_EQUALS(outWS->getNumberHistograms(), 1); - TS_ASSERT_EQUALS(outWS->readX(0)[0], 6473); - TS_ASSERT_DELTA(outWS->readY(0)[0], 0.283444, 0.000001); - TS_ASSERT_DELTA(outWS->readE(0)[0], 0.000145, 0.000001); + TS_ASSERT_EQUALS(outWS->x(0)[0], 6473); + TS_ASSERT_DELTA(outWS->y(0)[0], 0.283444, 0.000001); + TS_ASSERT_DELTA(outWS->e(0)[0], 0.000145, 0.000001); } void test_run_start_log() { @@ -590,4 +588,41 @@ private: std::string firstRun, lastRun; }; +class PlotAsymmetryByLogValueTestPerformance : public CxxTest::TestSuite { + +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PlotAsymmetryByLogValueTestPerformance *createSuite() { + return new PlotAsymmetryByLogValueTestPerformance(); + } + + static void destroySuite(PlotAsymmetryByLogValueTestPerformance *suite) { + delete suite; + } + + PlotAsymmetryByLogValueTestPerformance() + : firstRun("MUSR00015189.nxs"), lastRun("MUSR00015190.nxs") {} + + void setUp() override { + alg.initialize(); + alg.setPropertyValue("FirstRun", firstRun); + alg.setPropertyValue("LastRun", lastRun); + alg.setPropertyValue("OutputWorkspace", "outputWS"); + alg.setPropertyValue("LogValue", "Field_Danfysik"); + alg.setPropertyValue("Red", "2"); + alg.setPropertyValue("Green", "1"); + } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove("outputWS"); + } + + void testPerformanceWS() { alg.execute(); } + +private: + PlotAsymmetryByLogValue alg; + std::string firstRun, lastRun; +}; + #endif /*PLOTASYMMETRYBYLOGVALUTEST_H_*/ diff --git a/Framework/Algorithms/test/PointByPointVCorrectionTest.h b/Framework/Algorithms/test/PointByPointVCorrectionTest.h index ff3547f05466f29f896909118c74e91b7e92c280..2fd6d9756f078177c191c560f07c520cc1e30263 100644 --- a/Framework/Algorithms/test/PointByPointVCorrectionTest.h +++ b/Framework/Algorithms/test/PointByPointVCorrectionTest.h @@ -7,6 +7,9 @@ #include "MantidGeometry/Instrument.h" #include "MantidTestHelpers/WorkspaceCreationHelper.h" +using namespace Mantid::API; +using Mantid::Algorithms::PointByPointVCorrection; + class PointByPointVCorrectionTest : public CxxTest::TestSuite { public: void testName() { TS_ASSERT_EQUALS(pbpv.name(), "PointByPointVCorrection"); } @@ -19,8 +22,6 @@ public: } void testExec() { - using namespace Mantid::API; - if (!pbpv.isInitialized()) pbpv.initialize(); @@ -33,8 +34,8 @@ public: testSample->setInstrument(inst); testVanadium->setInstrument(inst); // Change the Y values - testSample->dataY(1) = Mantid::MantidVec(5, 3.0); - testVanadium->dataY(1) = Mantid::MantidVec(5, 5.5); + testSample->mutableY(1) = Mantid::HistogramData::HistogramY(5, 3.0); + testVanadium->mutableY(1) = Mantid::HistogramData::HistogramY(5, 5.5); pbpv.setProperty<MatrixWorkspace_sptr>("InputW1", testSample); pbpv.setProperty<MatrixWorkspace_sptr>("InputW2", testVanadium); @@ -48,21 +49,63 @@ public: AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("out")); // Check a few values - TS_ASSERT_DELTA(output->readX(1)[4], 6.5, 0.0001); - TS_ASSERT_DELTA(output->readX(1)[1], 2.0, 0.0001); - TS_ASSERT_DELTA(output->readX(0)[0], 0.5, 0.000001); - TS_ASSERT_DELTA(output->readY(1)[4], 2.9999, 0.0001); - TS_ASSERT_DELTA(output->readY(1)[1], 2.9999, 0.0001); - TS_ASSERT_DELTA(output->readY(0)[0], 2.0, 0.000001); - TS_ASSERT_DELTA(output->readE(1)[3], 1.8745, 0.0001); - TS_ASSERT_DELTA(output->readE(1)[2], 1.8745, 0.0001); - TS_ASSERT_DELTA(output->readE(0)[0], 2.2803, 0.0001); + TS_ASSERT_DELTA(output->x(1)[4], 6.5, 0.0001); + TS_ASSERT_DELTA(output->x(1)[1], 2.0, 0.0001); + TS_ASSERT_DELTA(output->x(0)[0], 0.5, 0.000001); + TS_ASSERT_DELTA(output->y(1)[4], 2.9999, 0.0001); + TS_ASSERT_DELTA(output->y(1)[1], 2.9999, 0.0001); + TS_ASSERT_DELTA(output->y(0)[0], 2.0, 0.000001); + TS_ASSERT_DELTA(output->e(1)[3], 1.8745, 0.0001); + TS_ASSERT_DELTA(output->e(1)[2], 1.8745, 0.0001); + TS_ASSERT_DELTA(output->e(0)[0], 2.2803, 0.0001); AnalysisDataService::Instance().remove("out"); } private: - Mantid::Algorithms::PointByPointVCorrection pbpv; + PointByPointVCorrection pbpv; +}; + +class PointByPointVCorrectionTestPerformance : public CxxTest::TestSuite { + +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static PointByPointVCorrectionTestPerformance *createSuite() { + return new PointByPointVCorrectionTestPerformance(); + } + + static void destroySuite(PointByPointVCorrectionTestPerformance *suite) { + delete suite; + } + + void setUp() override { + MatrixWorkspace_sptr testSample = + WorkspaceCreationHelper::Create2DWorkspaceBinned(20000, 5, 0.5, 1.5); + MatrixWorkspace_sptr testVanadium = + WorkspaceCreationHelper::Create2DWorkspaceBinned(20000, 5, 0.5, 1.5); + // Make the instruments match + Mantid::Geometry::Instrument_sptr inst(new Mantid::Geometry::Instrument); + testSample->setInstrument(inst); + testVanadium->setInstrument(inst); + // Change the Y values + testSample->mutableY(1) = Mantid::HistogramData::HistogramY(5, 3.0); + testVanadium->mutableY(1) = Mantid::HistogramData::HistogramY(5, 5.5); + + pbpv.initialize(); + pbpv.setProperty<MatrixWorkspace_sptr>("InputW1", testSample); + pbpv.setProperty<MatrixWorkspace_sptr>("InputW2", testVanadium); + pbpv.setPropertyValue("OutputWorkspace", "outputWS"); + } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove("outputWS"); + } + + void testPerformanceWS() { pbpv.execute(); } + +private: + PointByPointVCorrection pbpv; }; #endif /*POINTBYPOINTVCORRECTIONTEST_H_*/ diff --git a/Framework/Algorithms/test/Q1D2Test.h b/Framework/Algorithms/test/Q1D2Test.h index 98b3808b6d6d929643bc0d3720e5a060dd6fe032..95192a24e8970b792ad3a05201f1adc6bd782902 100644 --- a/Framework/Algorithms/test/Q1D2Test.h +++ b/Framework/Algorithms/test/Q1D2Test.h @@ -82,22 +82,22 @@ public: TS_ASSERT_EQUALS(result->getAxis(0)->unit()->unitID(), "MomentumTransfer") TS_ASSERT_EQUALS(result->getNumberHistograms(), 1) - TS_ASSERT_EQUALS(result->readX(0).size(), 26) - TS_ASSERT_DELTA(result->readX(0).front(), 0, 1e-5) - TS_ASSERT_DELTA(result->readX(0)[6], 0.12, 1e-5) - TS_ASSERT_DELTA(result->readX(0).back(), 0.5, 1e-5) + TS_ASSERT_EQUALS(result->x(0).size(), 26) + TS_ASSERT_DELTA(result->x(0).front(), 0, 1e-5) + TS_ASSERT_DELTA(result->x(0)[6], 0.12, 1e-5) + TS_ASSERT_DELTA(result->x(0).back(), 0.5, 1e-5) // values below taken from running the algorithm in the state it was // excepted by the ISIS SANS in // empty bins are 0/0 - TS_ASSERT_DELTA(result->readY(0).front(), 2226533, 1) - TS_ASSERT_DELTA(result->readY(0)[4], 946570.8, 0.1) - TS_ASSERT(std::isnan(result->readY(0)[18])) - TS_ASSERT(std::isnan(result->readY(0).back())) + TS_ASSERT_DELTA(result->y(0).front(), 2226533, 1) + TS_ASSERT_DELTA(result->y(0)[4], 946570.8, 0.1) + TS_ASSERT(std::isnan(result->y(0)[18])) + TS_ASSERT(std::isnan(result->y(0).back())) - TS_ASSERT_DELTA(result->readE(0)[1], 57964.04, 0.01) - TS_ASSERT_DELTA(result->readE(0)[5], 166712.6, 0.1) - TS_ASSERT(std::isnan(result->readE(0).back())) + TS_ASSERT_DELTA(result->e(0)[1], 57964.04, 0.01) + TS_ASSERT_DELTA(result->e(0)[5], 166712.6, 0.1) + TS_ASSERT(std::isnan(result->e(0).back())) Mantid::API::AnalysisDataService::Instance().remove(outputWS); } @@ -138,25 +138,24 @@ public: Mantid::API::AnalysisDataService::Instance().retrieve( outputWS + "_sumOfNormFactors"))) - TS_ASSERT_DELTA(result->readX(0)[10], 0.1999, 0.0001) - TS_ASSERT_DELTA(sumOfCounts->readX(0)[10], 0.1999, 0.0001) - TS_ASSERT_DELTA(sumOfNormFactors->readX(0)[10], 0.1999, 0.0001) + TS_ASSERT_DELTA(result->x(0)[10], 0.1999, 0.0001) + TS_ASSERT_DELTA(sumOfCounts->x(0)[10], 0.1999, 0.0001) + TS_ASSERT_DELTA(sumOfNormFactors->x(0)[10], 0.1999, 0.0001) - TS_ASSERT_DELTA(result->readY(0)[1], 1131778.3299, 0.01) - TS_ASSERT_DELTA(sumOfCounts->readY(0)[1], 1016.8990, 0.01) - TS_ASSERT_DELTA(sumOfNormFactors->readY(0)[1], 0.00089849, 0.01) + TS_ASSERT_DELTA(result->y(0)[1], 1131778.3299, 0.01) + TS_ASSERT_DELTA(sumOfCounts->y(0)[1], 1016.8990, 0.01) + TS_ASSERT_DELTA(sumOfNormFactors->y(0)[1], 0.00089849, 0.01) - TS_ASSERT_DELTA(result->readE(0)[1], 57964.04, 0.01) - TS_ASSERT_DELTA(sumOfCounts->readE(0)[1], 31.888, 0.01) - TS_ASSERT_DELTA(sumOfNormFactors->readE(0)[1], 3.6381851288154988e-005, - 0.01) + TS_ASSERT_DELTA(result->e(0)[1], 57964.04, 0.01) + TS_ASSERT_DELTA(sumOfCounts->e(0)[1], 31.888, 0.01) + TS_ASSERT_DELTA(sumOfNormFactors->e(0)[1], 3.6381851288154988e-005, 0.01) TS_ASSERT_EQUALS(result->getNumberHistograms(), 1) TS_ASSERT_EQUALS(sumOfCounts->getNumberHistograms(), 1) TS_ASSERT_EQUALS(sumOfNormFactors->getNumberHistograms(), 1) - TS_ASSERT_EQUALS(result->dataY(0).size(), 25) - TS_ASSERT_EQUALS(sumOfCounts->dataY(0).size(), 25) + TS_ASSERT_EQUALS(result->y(0).size(), 25) + TS_ASSERT_EQUALS(sumOfCounts->y(0).size(), 25) Mantid::API::AnalysisDataService::Instance().remove(outputWS); Mantid::API::AnalysisDataService::Instance().remove(outputWS + @@ -186,21 +185,21 @@ public: TS_ASSERT(result) TS_ASSERT_EQUALS(result->getNumberHistograms(), 1) - TS_ASSERT_EQUALS(result->readX(0).size(), 83) - TS_ASSERT_EQUALS(result->readX(0).front(), 0.1) - TS_ASSERT_DELTA(result->readX(0)[3], 0.1061208, 1e-6) - TS_ASSERT_DELTA(result->readX(0)[56], 0.3031165, 1e-5) - TS_ASSERT_EQUALS(result->readX(0).back(), 0.5) + TS_ASSERT_EQUALS(result->x(0).size(), 83) + TS_ASSERT_EQUALS(result->x(0).front(), 0.1) + TS_ASSERT_DELTA(result->x(0)[3], 0.1061208, 1e-6) + TS_ASSERT_DELTA(result->x(0)[56], 0.3031165, 1e-5) + TS_ASSERT_EQUALS(result->x(0).back(), 0.5) - TS_ASSERT_DELTA(result->readY(0).front(), 944237.8, 0.1) - TS_ASSERT_DELTA(result->readY(0)[3], 1009296, 1) - TS_ASSERT_DELTA(result->readY(0)[12], 620952.6, 0.1) - TS_ASSERT(std::isnan(result->readY(0).back())) + TS_ASSERT_DELTA(result->y(0).front(), 944237.8, 0.1) + TS_ASSERT_DELTA(result->y(0)[3], 1009296, 1) + TS_ASSERT_DELTA(result->y(0)[12], 620952.6, 0.1) + TS_ASSERT(std::isnan(result->y(0).back())) // empty bins are 0/0 - TS_ASSERT_DELTA(result->readE(0)[2], 404981, 10) - TS_ASSERT_DELTA(result->readE(0)[10], 489710.39, 100) - TS_ASSERT(std::isnan(result->readE(0)[7])) + TS_ASSERT_DELTA(result->e(0)[2], 404981, 10) + TS_ASSERT_DELTA(result->e(0)[10], 489710.39, 100) + TS_ASSERT(std::isnan(result->e(0)[7])) TSM_ASSERT("Should not have a DX value", !result->hasDx(0)) } @@ -270,16 +269,16 @@ public: // TS_ASSERT_EQUALS( (*(gravity->getAxis(1)))(0), // (*(refNoGrav->getAxis(1)))(0) ) - TS_ASSERT_EQUALS(gravity->readX(0).size(), refNoGrav->readX(0).size()) - TS_ASSERT_EQUALS(gravity->readX(0)[55], refNoGrav->readX(0)[55]) + TS_ASSERT_EQUALS(gravity->x(0).size(), refNoGrav->x(0).size()) + TS_ASSERT_EQUALS(gravity->x(0)[55], refNoGrav->x(0)[55]) - TS_ASSERT_DELTA(gravity->readY(0)[3], 1009296.4, 0.8) - TS_ASSERT_DELTA(gravity->readY(0)[10], 891346.9, 0.1) - TS_ASSERT(std::isnan(gravity->readY(0)[78])) + TS_ASSERT_DELTA(gravity->y(0)[3], 1009296.4, 0.8) + TS_ASSERT_DELTA(gravity->y(0)[10], 891346.9, 0.1) + TS_ASSERT(std::isnan(gravity->y(0)[78])) - TS_ASSERT_DELTA(gravity->readE(0).front(), 329383, 1) - TS_ASSERT_DELTA(gravity->readE(0)[10], 489708, 1) // 489710 - TS_ASSERT(std::isnan(gravity->readE(0)[77])) + TS_ASSERT_DELTA(gravity->e(0).front(), 329383, 1) + TS_ASSERT_DELTA(gravity->e(0)[10], 489708, 1) // 489710 + TS_ASSERT(std::isnan(gravity->e(0)[77])) Mantid::API::AnalysisDataService::Instance().remove(outputWS); } @@ -307,20 +306,20 @@ public: TS_ASSERT(result) TS_ASSERT_EQUALS(result->getNumberHistograms(), 1) - TS_ASSERT_EQUALS(result->readX(0).size(), 83) - TS_ASSERT_EQUALS(result->readX(0).front(), 0.1) - TS_ASSERT_DELTA(result->readX(0)[3], 0.1061208, 1e-6) - TS_ASSERT_DELTA(result->readX(0)[56], 0.3031165, 1e-5) - TS_ASSERT_EQUALS(result->readX(0).back(), 0.5) + TS_ASSERT_EQUALS(result->x(0).size(), 83) + TS_ASSERT_EQUALS(result->x(0).front(), 0.1) + TS_ASSERT_DELTA(result->x(0)[3], 0.1061208, 1e-6) + TS_ASSERT_DELTA(result->x(0)[56], 0.3031165, 1e-5) + TS_ASSERT_EQUALS(result->x(0).back(), 0.5) - TS_ASSERT_DELTA(result->readY(0).front(), 1192471.95, 0.1) - TS_ASSERT(std::isnan(result->readY(0)[3])) - TS_ASSERT_DELTA(result->readY(0)[12], 503242.79, 0.1) - TS_ASSERT(std::isnan(result->readY(0).back())) + TS_ASSERT_DELTA(result->y(0).front(), 1192471.95, 0.1) + TS_ASSERT(std::isnan(result->y(0)[3])) + TS_ASSERT_DELTA(result->y(0)[12], 503242.79, 0.1) + TS_ASSERT(std::isnan(result->y(0).back())) - TS_ASSERT_DELTA(result->readE(0)[2], 404980, 1) - TS_ASSERT_DELTA(result->readE(0)[10], 489708, 100) - TS_ASSERT(std::isnan(result->readE(0)[7])) + TS_ASSERT_DELTA(result->e(0)[2], 404980, 1) + TS_ASSERT_DELTA(result->e(0)[10], 489708, 100) + TS_ASSERT(std::isnan(result->e(0)[7])) } // here the cut parameters are set but should only affect detectors with lower @@ -353,13 +352,12 @@ public: TS_ASSERT(nocuts) TS_ASSERT_EQUALS(nocuts->getNumberHistograms(), 1) - for (size_t i = 0; i < nocuts->readY(0).size(); ++i) { - TS_ASSERT_EQUALS(nocuts->readX(0)[i], noGrav->readX(0)[i]) - if (!std::isnan(nocuts->readY(0)[i]) && - !std::isnan(nocuts->readE(0)[i])) { - TS_ASSERT_EQUALS(nocuts->readY(0)[i], noGrav->readY(0)[i]) + for (size_t i = 0; i < nocuts->y(0).size(); ++i) { + TS_ASSERT_EQUALS(nocuts->x(0)[i], noGrav->x(0)[i]) + if (!std::isnan(nocuts->y(0)[i]) && !std::isnan(nocuts->e(0)[i])) { + TS_ASSERT_EQUALS(nocuts->y(0)[i], noGrav->y(0)[i]) - TS_ASSERT_EQUALS(nocuts->readE(0)[i], noGrav->readE(0)[i]) + TS_ASSERT_EQUALS(nocuts->e(0)[i], noGrav->e(0)[i]) } } @@ -372,7 +370,7 @@ public: // this is a small change to the normalization workspace that should be // enough to stop progress - Mantid::MantidVec &xData = m_wavNorm->dataX(0); + auto &xData = m_wavNorm->mutableX(0); xData[15] += 0.001; const std::string outputWS("Q1D2Test_invalid_result"); @@ -594,12 +592,12 @@ void createInputWorkspaces(int start, int end, Mantid::API::AnalysisDataService::Instance().retrieve(wavNorm)); pixels = WorkspaceCreationHelper::Create2DWorkspaceBinned(29, 1); for (int i = 0; i < 29; ++i) { - pixels->dataY(i)[0] = flat_cell061Ys[i]; - pixels->dataE(i)[0] = flat_cell061Es[i]; + pixels->mutableY(i)[0] = flat_cell061Ys[i]; + pixels->mutableE(i)[0] = flat_cell061Es[i]; } if (forMasking) { - pixels->dataY(5)[0] = 0.0; // This pixels should be masked - pixels->dataY(6)[0] = -1.0; // This pixel should be masked + pixels->mutableY(5)[0] = 0.0; // This pixels should be masked + pixels->mutableY(6)[0] = -1.0; // This pixel should be masked AnalysisDataService::Instance().add("Q1DTest_flat_file", pixels); } else AnalysisDataService::Instance().add("Q1DTest_flat_file_for_masking", @@ -623,14 +621,12 @@ void createQResolutionWorkspace(Mantid::API::MatrixWorkspace_sptr &qResolution, // Populate Y with Value1 for (size_t i = 0; i < qResolution->getNumberHistograms(); ++i) { - auto &data = qResolution->dataY(i); - std::fill(data.begin(), data.end(), value1); + qResolution->mutableY(i) = value1; } // Populate Y with Value2 for (size_t i = 0; i < alteredInput->getNumberHistograms(); ++i) { - auto &data = alteredInput->dataY(i); - std::fill(data.begin(), data.end(), value2); + alteredInput->mutableY(i) = value2; } } diff --git a/Framework/Algorithms/test/Q1DWeightedTest.h b/Framework/Algorithms/test/Q1DWeightedTest.h index 6abd0718970d3084d54eb7a1695b75f939d050f6..e7f5fe2de36134ed0e540b2e43a733db6f2e4f97 100644 --- a/Framework/Algorithms/test/Q1DWeightedTest.h +++ b/Framework/Algorithms/test/Q1DWeightedTest.h @@ -76,12 +76,12 @@ public: // For NPixelDivision = 1 // Y[1] = 0.0398848*3600; Y[2] = 0.0371762*3600; Y[30] = 0.030971*3600; // Y[80] = 0.0275545*3600; Y[90] = 0.0270528*3600 - TS_ASSERT_EQUALS(result->dataX(0)[0], 0.01); - TS_ASSERT_DELTA(result->dataY(0)[30], 110.9651, tolerance); - TS_ASSERT_DELTA(result->dataY(0)[1], 143.2190, tolerance); - TS_ASSERT_DELTA(result->dataY(0)[2], 134.2864, tolerance); - TS_ASSERT_DELTA(result->dataY(0)[80], 98.3834, tolerance); - TS_ASSERT_DELTA(result->dataY(0)[90], 95.9322, tolerance); + TS_ASSERT_EQUALS(result->x(0)[0], 0.01); + TS_ASSERT_DELTA(result->y(0)[30], 110.9651, tolerance); + TS_ASSERT_DELTA(result->y(0)[1], 143.2190, tolerance); + TS_ASSERT_DELTA(result->y(0)[2], 134.2864, tolerance); + TS_ASSERT_DELTA(result->y(0)[80], 98.3834, tolerance); + TS_ASSERT_DELTA(result->y(0)[90], 95.9322, tolerance); Mantid::API::AnalysisDataService::Instance().remove(inputWS); Mantid::API::AnalysisDataService::Instance().remove(outputWS); @@ -184,8 +184,8 @@ public: double tolerance = 1e-12; // The two wedges shold be identical. - for (size_t i = 0; i < wedge1->dataY(0).size(); ++i) - TS_ASSERT_DELTA(wedge1->dataY(0)[i], wedge2->dataY(0)[i], tolerance); + for (size_t i = 0; i < wedge1->y(0).size(); ++i) + TS_ASSERT_DELTA(wedge1->y(0)[i], wedge2->y(0)[i], tolerance); Mantid::API::AnalysisDataService::Instance().remove(inputWS); Mantid::API::AnalysisDataService::Instance().remove(outputWS); diff --git a/Framework/Algorithms/test/QxyTest.h b/Framework/Algorithms/test/QxyTest.h index a9eb5480882768131f51ee3788750d0b9107b48e..5bade76b90cb94bd51b1ebf5829a5a53ad475c50 100644 --- a/Framework/Algorithms/test/QxyTest.h +++ b/Framework/Algorithms/test/QxyTest.h @@ -71,19 +71,19 @@ public: TS_ASSERT_DELTA((*(result->getAxis(1)))(31), -0.038, 0.001) TS_ASSERT_EQUALS((*(result->getAxis(1)))(100), 0.1) - TS_ASSERT_EQUALS(result->readX(0).size(), 101) - TS_ASSERT_EQUALS(result->readX(0).front(), -0.1) - TS_ASSERT_DELTA(result->readX(0)[64], 0.028, 0.01) - TS_ASSERT_DELTA(result->readX(0).back(), 0.1, 1e-14) + TS_ASSERT_EQUALS(result->x(0).size(), 101) + TS_ASSERT_EQUALS(result->x(0).front(), -0.1) + TS_ASSERT_DELTA(result->x(0)[64], 0.028, 0.01) + TS_ASSERT_DELTA(result->x(0).back(), 0.1, 1e-14) - TS_ASSERT_DIFFERS(result->readY(0).front(), result->readY(0).front()) // NaN - TS_ASSERT_DELTA(result->readY(28)[71], 229914.7, 1) - TS_ASSERT_DELTA(result->readY(26)[73], 0.0, 1) - TS_ASSERT_DELTA(result->readY(18)[80], 344640.4, 1) + TS_ASSERT_DIFFERS(result->y(0).front(), result->y(0).front()) // NaN + TS_ASSERT_DELTA(result->y(28)[71], 229914.7, 1) + TS_ASSERT_DELTA(result->y(26)[73], 0.0, 1) + TS_ASSERT_DELTA(result->y(18)[80], 344640.4, 1) - TS_ASSERT_DELTA(result->readE(20)[67], 0.0, 1e-3) - TS_ASSERT_DELTA(result->readE(27)[70], 114778.1004, 1) - TS_ASSERT_DELTA(result->readE(18)[80], 344640, 1) + TS_ASSERT_DELTA(result->e(20)[67], 0.0, 1e-3) + TS_ASSERT_DELTA(result->e(27)[70], 114778.1004, 1) + TS_ASSERT_DELTA(result->e(18)[80], 344640, 1) Mantid::API::MatrixWorkspace_sptr sumOfCounts; TS_ASSERT_THROWS_NOTHING( @@ -98,12 +98,12 @@ public: Mantid::API::AnalysisDataService::Instance().retrieve( outputWS + "_sumOfNormFactors"))) - TS_ASSERT_DELTA(sumOfCounts->readY(28)[71], 2.0000, 0.01) - TS_ASSERT_DELTA(sumOfNormFactors->readY(28)[71], 8.6988767154375003e-006, + TS_ASSERT_DELTA(sumOfCounts->y(28)[71], 2.0000, 0.01) + TS_ASSERT_DELTA(sumOfNormFactors->y(28)[71], 8.6988767154375003e-006, 0.00000001) - TS_ASSERT_DELTA(sumOfCounts->readE(28)[71], 1.4142135623730951, 0.01) - TS_ASSERT_DELTA(sumOfNormFactors->readE(28)[71], 0.0, 0.00000001) + TS_ASSERT_DELTA(sumOfCounts->e(28)[71], 1.4142135623730951, 0.01) + TS_ASSERT_DELTA(sumOfNormFactors->e(28)[71], 0.0, 0.00000001) TS_ASSERT_EQUALS(sumOfCounts->getNumberHistograms(), 100) TS_ASSERT_EQUALS(sumOfCounts->blocksize(), 100) @@ -133,28 +133,20 @@ public: TS_ASSERT_THROWS_NOTHING( result = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>( Mantid::API::AnalysisDataService::Instance().retrieve(outputWS))) - /* for (int i = 0 ; i < 30; i ++) - { - std::cout << i << '\n'; - for (int j = 0 ; j < 30; j ++) - { - std::cout << result->readY(i)[j] << " "; - } - }*/ TS_ASSERT_EQUALS(result->getNumberHistograms(), 100) TS_ASSERT_EQUALS(result->blocksize(), 100) TS_ASSERT_EQUALS((*(result->getAxis(1)))(0), -0.1) TS_ASSERT_DELTA((*(result->getAxis(1)))(31), -0.038, 0.001) TS_ASSERT_EQUALS((*(result->getAxis(1)))(100), 0.1) - TS_ASSERT_DIFFERS(result->readY(0).front(), result->readY(0).front()) // NaN - TS_ASSERT_DELTA(result->readY(3)[26], 0.0000, 1) - TS_ASSERT_DELTA(result->readY(6)[51], 341936, 1) - TS_ASSERT_DELTA(result->readY(7)[27], 685501, 1) + TS_ASSERT_DIFFERS(result->y(0).front(), result->y(0).front()) // NaN + TS_ASSERT_DELTA(result->y(3)[26], 0.0000, 1) + TS_ASSERT_DELTA(result->y(6)[51], 341936, 1) + TS_ASSERT_DELTA(result->y(7)[27], 685501, 1) - TS_ASSERT_DELTA(result->readE(20)[67], 0.0, 1e-3) - TS_ASSERT_DELTA(result->readE(7)[27], 685500.615, 1e-3) - TS_ASSERT_DELTA(result->readE(23)[34], 0.0, 1e-3) + TS_ASSERT_DELTA(result->e(20)[67], 0.0, 1e-3) + TS_ASSERT_DELTA(result->e(7)[27], 685500.615, 1e-3) + TS_ASSERT_DELTA(result->e(23)[34], 0.0, 1e-3) Mantid::API::AnalysisDataService::Instance().remove(m_inputWS); Mantid::API::AnalysisDataService::Instance().remove(outputWS); @@ -165,4 +157,43 @@ private: const std::string m_inputWS; }; +class QxyTestPerformance : public CxxTest::TestSuite { +public: + std::string m_inputWS; + std::string m_outputWS; + + QxyTestPerformance() + : m_inputWS("QxyTest_input_in_wav"), m_outputWS("result") {} + + void setUp() override { + Mantid::DataHandling::LoadRaw3 loader; + loader.initialize(); + loader.setPropertyValue("Filename", "LOQ48098.raw"); + loader.setPropertyValue("OutputWorkspace", m_inputWS); + loader.execute(); + + Mantid::Algorithms::ConvertUnits convert; + convert.initialize(); + convert.setPropertyValue("InputWorkspace", m_inputWS); + convert.setPropertyValue("OutputWorkspace", m_inputWS); + convert.setPropertyValue("Target", "Wavelength"); + convert.execute(); + } + + void tearDown() override { + Mantid::API::AnalysisDataService::Instance().remove(m_outputWS); + } + + void test_slow_performance() { + Mantid::Algorithms::Qxy qxy; + qxy.initialize(); + qxy.setPropertyValue("InputWorkspace", m_inputWS); + qxy.setPropertyValue("OutputWorkspace", m_outputWS); + qxy.setPropertyValue("MaxQxy", "0.1"); + qxy.setPropertyValue("DeltaQ", "0.002"); + qxy.setProperty("OutputParts", true); + qxy.execute(); + } +}; + #endif /*QXYTEST_H_*/ diff --git a/Framework/Algorithms/test/RRFMuonTest.h b/Framework/Algorithms/test/RRFMuonTest.h index 17e0e899fc380b64157496c4398c0586f4bc61dd..0010979b6022b5cddfa8ed43d91a000c3fa29533 100644 --- a/Framework/Algorithms/test/RRFMuonTest.h +++ b/Framework/Algorithms/test/RRFMuonTest.h @@ -7,6 +7,7 @@ #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidKernel/UnitFactory.h" +#include "MantidTestHelpers/HistogramDataTestHelper.h" using namespace Mantid::Algorithms; using namespace Mantid::API; @@ -46,11 +47,11 @@ public: // Checks // X values - TS_ASSERT_EQUALS(ws->readX(0), ows->readX(0)); - TS_ASSERT_EQUALS(ws->readX(1), ows->readX(1)); + TS_ASSERT_EQUALS(ws->x(0), ows->x(0)); + TS_ASSERT_EQUALS(ws->x(1), ows->x(1)); // Y values - TS_ASSERT_EQUALS(ws->readY(0), ows->readY(0)); - TS_ASSERT_EQUALS(ws->readY(1), ows->readY(1)); + TS_ASSERT_EQUALS(ws->y(0), ows->y(0)); + TS_ASSERT_EQUALS(ws->y(1), ows->y(1)); } void testRRFMuonNonZeroFrequency() { @@ -80,19 +81,19 @@ public: // Checks // X values - TS_ASSERT_EQUALS(ws->readX(0), ows->readX(0)); - TS_ASSERT_EQUALS(ws->readX(1), ows->readX(1)); + TS_ASSERT_EQUALS(ws->x(0), ows->x(0)); + TS_ASSERT_EQUALS(ws->x(1), ows->x(1)); // Y values // The input frequency is close to the precession frequency, so: // The real part of the RRF polarization should be close to 1 for all X // values // The imaginary part should be close to 0 for all X values - TS_ASSERT_DELTA(ows->readY(0)[0], 1, 0.001); - TS_ASSERT_DELTA(ows->readY(0)[100], 1, 0.001); - TS_ASSERT_DELTA(ows->readY(0)[200], 1, 0.001); - TS_ASSERT_DELTA(ows->readY(1)[0], 0, 0.001); - TS_ASSERT_DELTA(ows->readY(1)[100], 0, 0.001); - TS_ASSERT_DELTA(ows->readY(1)[200], 0, 0.001); + TS_ASSERT_DELTA(ows->y(0)[0], 1, 0.001); + TS_ASSERT_DELTA(ows->y(0)[100], 1, 0.001); + TS_ASSERT_DELTA(ows->y(0)[200], 1, 0.001); + TS_ASSERT_DELTA(ows->y(1)[0], 0, 0.001); + TS_ASSERT_DELTA(ows->y(1)[100], 0, 0.001); + TS_ASSERT_DELTA(ows->y(1)[200], 0, 0.001); } void testRRFMuonUnits() { @@ -154,27 +155,27 @@ public: // Check Y values // ows1 vs ows2 // Results with different frequency units should be very similar - TS_ASSERT_DELTA(ows1->readY(0)[5], ows2->readY(0)[5], 0.000001); - TS_ASSERT_DELTA(ows1->readY(0)[98], ows2->readY(0)[98], 0.000001); - TS_ASSERT_DELTA(ows1->readY(0)[276], ows2->readY(0)[276], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[5], ows2->y(0)[5], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[98], ows2->y(0)[98], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[276], ows2->y(0)[276], 0.000001); // But not exactly the same // (They should only be the same if the input frequency in rrfMuon2 were // exactly 1/2/M_PI) - TS_ASSERT_DIFFERS(ows1->readY(0)[5], ows2->readY(0)[5]); - TS_ASSERT_DIFFERS(ows1->readY(0)[98], ows2->readY(0)[98]); - TS_ASSERT_DIFFERS(ows1->readY(0)[276], ows2->readY(0)[276]); + TS_ASSERT_DIFFERS(ows1->y(0)[5], ows2->y(0)[5]); + TS_ASSERT_DIFFERS(ows1->y(0)[98], ows2->y(0)[98]); + TS_ASSERT_DIFFERS(ows1->y(0)[276], ows2->y(0)[276]); // ows1 vs ows3 // Results with different frequency units should be very similar - TS_ASSERT_DELTA(ows1->readY(0)[8], ows3->readY(0)[8], 0.000001); - TS_ASSERT_DELTA(ows1->readY(0)[109], ows3->readY(0)[109], 0.000001); - TS_ASSERT_DELTA(ows1->readY(0)[281], ows3->readY(0)[281], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[8], ows3->y(0)[8], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[109], ows3->y(0)[109], 0.000001); + TS_ASSERT_DELTA(ows1->y(0)[281], ows3->y(0)[281], 0.000001); // But not exactly the same // (They should only be the same if the input frequency in rrfMuon3 were // exactly 1/2/M_PI/MU // being MU the muon gyromagnetic ratio) - TS_ASSERT_DIFFERS(ows1->readY(0)[8], ows3->readY(0)[8]); - TS_ASSERT_DIFFERS(ows1->readY(0)[109], ows3->readY(0)[109]); - TS_ASSERT_DIFFERS(ows1->readY(0)[281], ows3->readY(0)[281]); + TS_ASSERT_DIFFERS(ows1->y(0)[8], ows3->y(0)[8]); + TS_ASSERT_DIFFERS(ows1->y(0)[109], ows3->y(0)[109]); + TS_ASSERT_DIFFERS(ows1->y(0)[281], ows3->y(0)[281]); } private: @@ -188,14 +189,14 @@ private: for (int i = 0; i < nBins; i++) { double x = i / static_cast<double>(nBins); - ws->dataX(0)[i] = x; - ws->dataY(0)[i] = cos(2 * M_PI * x); - ws->dataX(1)[i] = x; - ws->dataY(1)[i] = sin(2 * M_PI * x); + ws->mutableX(0)[i] = x; + ws->mutableY(0)[i] = cos(2 * M_PI * x); + ws->mutableX(1)[i] = x; + ws->mutableY(1)[i] = sin(2 * M_PI * x); } - ws->dataX(0)[nBins] = nBins; - ws->dataX(1)[nBins] = nBins; + ws->mutableX(0)[nBins] = nBins; + ws->mutableX(1)[nBins] = nBins; // Units ws->getAxis(0)->unit() = diff --git a/Framework/Algorithms/test/RadiusSumTest.h b/Framework/Algorithms/test/RadiusSumTest.h index a3031783eff8b486da537451f40c5bb60b9c3054..a1b16948c93fba515470b2b465be7d234a9a935f 100644 --- a/Framework/Algorithms/test/RadiusSumTest.h +++ b/Framework/Algorithms/test/RadiusSumTest.h @@ -1,12 +1,12 @@ #ifndef MANTID_ALGORITHMS_RADIUSSUMTEST_H_ #define MANTID_ALGORITHMS_RADIUSSUMTEST_H_ -#include <cxxtest/TestSuite.h> -#include <boost/shared_ptr.hpp> +#include "MantidAPI/NumericAxis.h" #include "MantidAlgorithms/RadiusSum.h" #include "MantidTestHelpers/WorkspaceCreationHelper.h" -#include "MantidAPI/NumericAxis.h" #include "RingProfileTest.h" +#include <boost/shared_ptr.hpp> +#include <cxxtest/TestSuite.h> using Mantid::Algorithms::RadiusSum; using namespace Mantid::API; @@ -67,7 +67,7 @@ public: // centre must be inside the limits of the workspace std::vector<double> twoInputs(2, 0); // set the centre outside the matrix workspace - twoInputs[0] = goodWS->readX(0)[0] - 3.5; + twoInputs[0] = goodWS->x(0)[0] - 3.5; twoInputs[1] = goodWS->getAxis(1)->getMin() - 4.5; // it is a valid input because it has just two inputs TS_ASSERT_THROWS_NOTHING(alg->setProperty("Centre", twoInputs)); @@ -91,9 +91,9 @@ public: MatrixWorkspace_sptr outws = RingProfileTest::basic_checkup_on_output_workspace((*alg), numbins); - TS_ASSERT_DELTA(outws->readY(0)[0], 0, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[1], 1 + 2 + 3 + 4, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[2], 4 + 1 + 1 + 2 + 2 + 3 + 3 + 4, 0.1); + TS_ASSERT_DELTA(outws->y(0)[0], 0, 0.1); + TS_ASSERT_DELTA(outws->y(0)[1], 1 + 2 + 3 + 4, 0.1); + TS_ASSERT_DELTA(outws->y(0)[2], 4 + 1 + 1 + 2 + 2 + 3 + 3 + 4, 0.1); } void test_radiussum_center_of_numeric_image_normalized() { @@ -112,9 +112,9 @@ public: MatrixWorkspace_sptr outws = RingProfileTest::basic_checkup_on_output_workspace((*alg), numbins); - TS_ASSERT_DELTA(outws->readY(0)[0], 0, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[1], (1 + 2 + 3 + 4) / 0.15, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[2], (4 + 1 + 1 + 2 + 2 + 3 + 3 + 4) / 0.25, + TS_ASSERT_DELTA(outws->y(0)[0], 0, 0.1); + TS_ASSERT_DELTA(outws->y(0)[1], (1 + 2 + 3 + 4) / 0.15, 0.1); + TS_ASSERT_DELTA(outws->y(0)[2], (4 + 1 + 1 + 2 + 2 + 3 + 3 + 4) / 0.25, 0.1); } @@ -139,8 +139,9 @@ public: double output[] = {0, 8, 11, 6, 5}; + const auto &y = outws->y(0); for (size_t i = 0; i < 5; i++) { - TS_ASSERT_DELTA(outws->readY(0)[i], output[i], 0.1); + TS_ASSERT_DELTA(y[i], output[i], 0.1); } } @@ -165,9 +166,9 @@ public: MatrixWorkspace_sptr outws = RingProfileTest::basic_checkup_on_output_workspace((*alg), numbins); - TS_ASSERT_DELTA(outws->readY(0)[0], 0, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[1], 1 + 2 + 3 + 4, 0.1); - TS_ASSERT_DELTA(outws->readY(0)[2], 4 + 1 + 1 + 2 + 2 + 3 + 3 + 4, 0.1); + TS_ASSERT_DELTA(outws->y(0)[0], 0, 0.1); + TS_ASSERT_DELTA(outws->y(0)[1], 1 + 2 + 3 + 4, 0.1); + TS_ASSERT_DELTA(outws->y(0)[2], 4 + 1 + 1 + 2 + 2 + 3 + 3 + 4, 0.1); } void test_radiussum_horizontal_left_vertical_center_instrument() { @@ -195,11 +196,13 @@ public: double output[] = {1 + 2 + 2, 0, 11, 7, 7}; + const auto &x = outws->x(0); for (int i = 0; i < numbins + 1; i++) - TS_ASSERT_DELTA(outws->readX(0)[i], maxradius / numbins * i, 0.001); + TS_ASSERT_DELTA(x[i], maxradius / numbins * i, 0.001); + const auto &y = outws->y(0); for (int i = 0; i < numbins; i++) - TS_ASSERT_DELTA(outws->readY(0)[i], output[i], 0.1); + TS_ASSERT_DELTA(y[i], output[i], 0.1); // check the units of the instrument TS_ASSERT_EQUALS(outws->getAxis(0)->unit()->caption(), "Radius"); diff --git a/Framework/Algorithms/test/RayTracerTesterTest.h b/Framework/Algorithms/test/RayTracerTesterTest.h index 9f9e6972af7bfd70bb5d5e1e30f5f10381a34025..c7e76c1260ad8f80c58a49e31e4b7ef92d011d15 100644 --- a/Framework/Algorithms/test/RayTracerTesterTest.h +++ b/Framework/Algorithms/test/RayTracerTesterTest.h @@ -37,4 +37,34 @@ public: } }; +class RayTracerTesterTestPerformance : public CxxTest::TestSuite { +public: + static RayTracerTesterTestPerformance *createSuite() { + return new RayTracerTesterTestPerformance(); + } + static void destroySuite(RayTracerTesterTestPerformance *suite) { + delete suite; + } + + void setUp() override { + TS_ASSERT_THROWS_NOTHING(alg.initialize()) + TS_ASSERT(alg.isInitialized()) + alg.setPropertyValue("Filename", "CNCS_Definition.xml"); + alg.setPropertyValue("OutputWorkspace", "cncs"); + } + + void test_performance() { + int iterations = 3; + doTestExec(iterations); + } + + void doTestExec(int iterations) { + for (int i = 0; i < iterations; i++) { + alg.exec(); + } + } + +private: + RayTracerTester alg; +}; #endif /* MANTID_ALGORITHMS_RAYTRACERTESTERTEST_H_ */ diff --git a/Framework/Algorithms/test/ReadGroupsFromFileTest.h b/Framework/Algorithms/test/ReadGroupsFromFileTest.h index 90ded796d502c241b22bf6a55a66ae651f6ac68d..5d017bac061aad93342bb50b509e043a995293ff 100644 --- a/Framework/Algorithms/test/ReadGroupsFromFileTest.h +++ b/Framework/Algorithms/test/ReadGroupsFromFileTest.h @@ -1,20 +1,20 @@ #ifndef READGROUPSFROMFILETEST_H_ #define READGROUPSFROMFILETEST_H_ -#include "MantidAlgorithms/ReadGroupsFromFile.h" -#include "MantidAlgorithms/CreateGroupingWorkspace.h" -#include "MantidDataHandling/SaveCalFile.h" #include "MantidAPI/Algorithm.h" #include "MantidAPI/AnalysisDataService.h" #include "MantidAPI/FrameworkManager.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/Workspace.h" #include "MantidAPI/WorkspaceFactory.h" +#include "MantidAlgorithms/CreateGroupingWorkspace.h" +#include "MantidAlgorithms/ReadGroupsFromFile.h" #include "MantidDataHandling/LoadEmptyInstrument.h" +#include "MantidDataHandling/SaveCalFile.h" #include "MantidDataObjects/Workspace2D.h" +#include "MantidGeometry/Instrument.h" #include "MantidGeometry/Instrument/Component.h" #include "MantidGeometry/Instrument/FitParameter.h" -#include "MantidGeometry/Instrument.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/Exception.h" #include <Poco/File.h> @@ -99,9 +99,9 @@ public: TS_ASSERT_EQUALS(ws->blocksize(), 1); - TS_ASSERT_DELTA(ws->readY(2)[0], 1.0, 1e-6); - TS_ASSERT_DELTA(ws->readY(25)[0], 2.0, 1e-6); - TS_ASSERT_DELTA(ws->readY(45)[0], 3.0, 1e-6); + TS_ASSERT_DELTA(ws->y(2)[0], 1.0, 1e-6); + TS_ASSERT_DELTA(ws->y(25)[0], 2.0, 1e-6); + TS_ASSERT_DELTA(ws->y(45)[0], 3.0, 1e-6); // remove file created by this algorithm Poco::File(outputFile).remove(); diff --git a/Framework/Algorithms/test/RealFFTTest.h b/Framework/Algorithms/test/RealFFTTest.h index 03783ee8f5a190dba2f34e290dd701f846549fbd..1b1b428fc99d5d2387f5a49af008cdd6d846cbeb 100644 --- a/Framework/Algorithms/test/RealFFTTest.h +++ b/Framework/Algorithms/test/RealFFTTest.h @@ -1,89 +1,86 @@ #ifndef REALFFT_TEST_H_ #define REALFFT_TEST_H_ -#include <cxxtest/TestSuite.h> #include <cmath> +#include <cxxtest/TestSuite.h> -#include "MantidAlgorithms/FFT.h" #include "MantidAPI/AnalysisDataService.h" #include "MantidAPI/FrameworkManager.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/WorkspaceFactory.h" +#include "MantidAlgorithms/FFT.h" #include "MantidDataObjects/Workspace2D.h" #include "MantidKernel/System.h" using namespace Mantid; using namespace Mantid::API; -class RealFFTTest : public CxxTest::TestSuite { -public: - static RealFFTTest *createSuite() { return new RealFFTTest(); } - static void destroySuite(RealFFTTest *suite) { delete suite; } - - RealFFTTest() : N(116), dX(0.3), XX(N * dX) { - - FrameworkManager::Instance(); - Mantid::DataObjects::Workspace2D_sptr ws = - boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( - WorkspaceFactory::Instance().create("Workspace2D", 1, N, N)); - - Mantid::DataObjects::Workspace2D_sptr ws1 = - boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( - WorkspaceFactory::Instance().create("Workspace2D", 1, N + 1, N)); - - Mantid::MantidVec &X = ws->dataX(0); - Mantid::MantidVec &Y = ws->dataY(0); - Mantid::MantidVec &E = ws->dataE(0); - - int n2 = N / 2; - for (int k = 0; k <= n2; k++) { - int i = n2 - k; - if (i >= 0) { - X[i] = -dX * (k); - Y[i] = exp(-X[i] * X[i] * 3.); - E[i] = 1.; - } - i = n2 + k; - if (i < N) { - X[i] = dX * (k); - Y[i] = exp(-X[i] * X[i] * 3.); - E[i] = 1.; - } +// Anonymous namespace to share methods with Performance test +namespace { +void setupWorkspaces(int N, double dX) { + FrameworkManager::Instance(); + Mantid::DataObjects::Workspace2D_sptr ws = + boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( + WorkspaceFactory::Instance().create("Workspace2D", 1, N, N)); + + Mantid::DataObjects::Workspace2D_sptr ws1 = + boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( + WorkspaceFactory::Instance().create("Workspace2D", 1, N + 1, N)); + + auto &X = ws->mutableX(0); + auto &Y = ws->mutableY(0); + auto &E = ws->mutableE(0); + + int n2 = N / 2; + for (int k = 0; k <= n2; k++) { + int i = n2 - k; + if (i >= 0) { + X[i] = -dX * (k); + Y[i] = exp(-X[i] * X[i] * 3.); + E[i] = 1.; + } + i = n2 + k; + if (i < N) { + X[i] = dX * (k); + Y[i] = exp(-X[i] * X[i] * 3.); + E[i] = 1.; } - - Mantid::MantidVec &X1 = ws1->dataX(0); - - std::copy(X.begin(), X.end(), X1.begin()); - X1.back() = X.back() + dX; - ws1->dataY(0) = Y; - ws1->dataE(0) = E; - - AnalysisDataService::Instance().add("RealFFT_WS", ws); - AnalysisDataService::Instance().add("RealFFT_WS_hist", ws1); - } - ~RealFFTTest() override { - FrameworkManager::Instance().deleteWorkspace("RealFFT_WS"); - FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_hist"); - FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_forward"); - FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_backward"); } - void dotestForward(std::string IgnoreXBins) { - UNUSED_ARG(IgnoreXBins); - IAlgorithm *fft = - Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); - fft->initialize(); - fft->setPropertyValue("InputWorkspace", "RealFFT_WS"); - fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_forward"); - fft->setPropertyValue("WorkspaceIndex", "0"); - fft->execute(); - + auto &X1 = ws1->mutableX(0); + + std::copy(X.cbegin(), X.cend(), X1.begin()); + X1.back() = X.back() + dX; + ws1->mutableY(0) = Y; + ws1->mutableE(0) = E; + + AnalysisDataService::Instance().add("RealFFT_WS", ws); + AnalysisDataService::Instance().add("RealFFT_WS_hist", ws1); +} + +void deleteWorkspacesFromADS() { + FrameworkManager::Instance().deleteWorkspace("RealFFT_WS"); + FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_hist"); + FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_forward"); + FrameworkManager::Instance().deleteWorkspace("RealFFT_WS_backward"); +} + +void doTestForward(const int N, const double XX, bool performance = false) { + IAlgorithm *fft = + Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); + fft->initialize(); + fft->setPropertyValue("InputWorkspace", "RealFFT_WS"); + fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_forward"); + fft->setPropertyValue("WorkspaceIndex", "0"); + fft->execute(); + + if (!performance) { MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve("RealFFT_WS_forward")); - const MantidVec &X = fWS->readX(0); - const MantidVec &Yr = fWS->readY(0); - const MantidVec &Yi = fWS->readY(1); + const auto &X = fWS->x(0); + const auto &Yr = fWS->y(0); + const auto &Yi = fWS->y(1); double h = sqrt(M_PI / 3); double a = M_PI * M_PI / 3; @@ -98,52 +95,53 @@ public: TS_ASSERT_DELTA(Yi[i], 0.0, 0.00001); } } - - void testForward() { dotestForward("0"); } - - void testForward_IgnoringX() { dotestForward("1"); } - - void testBackward() { - IAlgorithm *fft = - Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); - fft->initialize(); - fft->setPropertyValue("InputWorkspace", "RealFFT_WS_forward"); - fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_backward"); - fft->setPropertyValue("Transform", "Backward"); - fft->execute(); - +} + +void doTestBackward(const int N, const double dX, bool performance = false) { + IAlgorithm *fft = + Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); + fft->initialize(); + fft->setPropertyValue("InputWorkspace", "RealFFT_WS_forward"); + fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_backward"); + fft->setPropertyValue("Transform", "Backward"); + fft->execute(); + + if (!performance) { MatrixWorkspace_sptr WS = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve("RealFFT_WS")); MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve("RealFFT_WS_backward")); - const MantidVec &Y0 = WS->readY(0); + const auto &Y0 = WS->y(0); - const MantidVec &X = fWS->readX(0); - const MantidVec &Y = fWS->readY(0); + const auto &X = fWS->x(0); + const auto &Y = fWS->y(0); for (int i = 0; i < N; i++) { TS_ASSERT_DELTA(X[i], dX * i, 0.00001); TS_ASSERT_DELTA(Y[i], Y0[i], 0.00001); } } - - void testForwardHistogram() { - IAlgorithm *fft = - Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); - fft->initialize(); - fft->setPropertyValue("InputWorkspace", "RealFFT_WS_hist"); - fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_forward_hist"); - fft->setPropertyValue("WorkspaceIndex", "0"); - fft->execute(); - - MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( - AnalysisDataService::Instance().retrieve("RealFFT_WS_forward_hist")); - - const MantidVec &X = fWS->readX(0); - const MantidVec &Yr = fWS->readY(0); - const MantidVec &Yi = fWS->readY(1); +} + +void doTestForwardHistogram(const int N, const double XX, + bool performance = false) { + IAlgorithm *fft = + Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); + fft->initialize(); + fft->setPropertyValue("InputWorkspace", "RealFFT_WS_hist"); + fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_forward_hist"); + fft->setPropertyValue("WorkspaceIndex", "0"); + fft->execute(); + + MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( + AnalysisDataService::Instance().retrieve("RealFFT_WS_forward_hist")); + + if (!performance) { + const auto &X = fWS->x(0); + const auto &Yr = fWS->y(0); + const auto &Yi = fWS->y(1); double h = sqrt(M_PI / 3); double a = M_PI * M_PI / 3; @@ -158,34 +156,74 @@ public: TS_ASSERT_DELTA(Yi[i], 0.0, 0.00001); } } +} - void testBackwardHistogram() { - IAlgorithm *fft = - Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); - fft->initialize(); - fft->setPropertyValue("InputWorkspace", "RealFFT_WS_forward_hist"); - fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_backward_hist"); - fft->setPropertyValue("Transform", "Backward"); - fft->execute(); +void doTestBackwardHistogram(const int N, const double dX, + bool performance = false) { + IAlgorithm *fft = + Mantid::API::FrameworkManager::Instance().createAlgorithm("RealFFT"); + fft->initialize(); + fft->setPropertyValue("InputWorkspace", "RealFFT_WS_forward_hist"); + fft->setPropertyValue("OutputWorkspace", "RealFFT_WS_backward_hist"); + fft->setPropertyValue("Transform", "Backward"); + fft->execute(); - MatrixWorkspace_sptr WS = boost::dynamic_pointer_cast<MatrixWorkspace>( - AnalysisDataService::Instance().retrieve("RealFFT_WS")); - - MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( - AnalysisDataService::Instance().retrieve("RealFFT_WS_backward_hist")); + MatrixWorkspace_sptr WS = boost::dynamic_pointer_cast<MatrixWorkspace>( + AnalysisDataService::Instance().retrieve("RealFFT_WS")); - const MantidVec &Y0 = WS->readY(0); + MatrixWorkspace_sptr fWS = boost::dynamic_pointer_cast<MatrixWorkspace>( + AnalysisDataService::Instance().retrieve("RealFFT_WS_backward_hist")); - const MantidVec &X = fWS->readX(0); - const MantidVec &Y = fWS->readY(0); + if (!performance) { + const auto &Y0 = WS->y(0); + const auto &X = fWS->x(0); + const auto &Y = fWS->y(0); for (int i = 0; i < N; i++) { TS_ASSERT_DELTA(X[i], dX * i, 0.00001); TS_ASSERT_DELTA(Y[i], Y0[i], 0.00001); } } +} +} + +class RealFFTTest : public CxxTest::TestSuite { +public: + static RealFFTTest *createSuite() { return new RealFFTTest(); } + static void destroySuite(RealFFTTest *suite) { delete suite; } + + RealFFTTest() : N(116), dX(0.3), XX(N * dX) { setupWorkspaces(N, dX); } + ~RealFFTTest() override { deleteWorkspacesFromADS(); } + + void testForward() { doTestForward(N, XX); } + void testBackward() { doTestBackward(N, dX); } + void testForwardHistogram() { doTestForwardHistogram(N, XX); } + void testBackwardHistogram() { doTestBackwardHistogram(N, dX); } + +private: + const int N; + const double dX, XX; +}; + +class RealFFTTestPerformance : public CxxTest::TestSuite { +public: + static RealFFTTestPerformance *createSuite() { + return new RealFFTTestPerformance(); + } + static void destroySuite(RealFFTTestPerformance *suite) { delete suite; } + + RealFFTTestPerformance() : N(116), dX(0.3), XX(N * dX) { + setupWorkspaces(N, dX); + } + ~RealFFTTestPerformance() override { deleteWorkspacesFromADS(); } + + void testForward() { doTestForward(N, XX, performance); } + void testBackward() { doTestBackward(N, dX, performance); } + void testForwardHistogram() { doTestForwardHistogram(N, XX, performance); } + void testBackwardHistogram() { doTestBackwardHistogram(N, dX, performance); } private: + const bool performance = true; const int N; const double dX, XX; }; diff --git a/Framework/Algorithms/test/Rebin2DTest.h b/Framework/Algorithms/test/Rebin2DTest.h index c94281e68d9ea56532435d47608cc23feac69b59..d24a362220616e876ad1bcdfc86d71a74f2bdd24 100644 --- a/Framework/Algorithms/test/Rebin2DTest.h +++ b/Framework/Algorithms/test/Rebin2DTest.h @@ -131,14 +131,16 @@ public: const double epsilon(1e-08); for (size_t i = 0; i < outputWS->getNumberHistograms(); ++i) { + const auto &y = outputWS->y(i); + const auto &e = outputWS->e(i); for (size_t j = 0; j < outputWS->blocksize(); ++j) { if (j < 5) { - TS_ASSERT_DELTA(outputWS->readY(i)[j], 9, epsilon); + TS_ASSERT_DELTA(y[j], 9, epsilon); } else { // Last bin - TS_ASSERT_DELTA(outputWS->readY(i)[j], 5, epsilon); + TS_ASSERT_DELTA(y[j], 5, epsilon); } - TS_ASSERT_DELTA(outputWS->readE(i)[j], errors[j], epsilon); + TS_ASSERT_DELTA(e[j], errors[j], epsilon); } } } @@ -152,48 +154,49 @@ private: // Axis sizes TS_ASSERT_EQUALS(outputWS->getAxis(0)->length(), nxvalues); TS_ASSERT_EQUALS(outputWS->getAxis(1)->length(), nhist + 1); - TS_ASSERT_EQUALS(outputWS->readX(0).size(), nxvalues); - TS_ASSERT_EQUALS(outputWS->readY(0).size(), nxvalues - 1); + TS_ASSERT_EQUALS(outputWS->x(0).size(), nxvalues); + TS_ASSERT_EQUALS(outputWS->y(0).size(), nxvalues - 1); const double epsilon(1e-08); for (size_t i = 0; i < nhist; ++i) { + const auto &x = outputWS->x(i); + const auto &y = outputWS->y(i); + const auto &e = outputWS->e(i); for (size_t j = 0; j < nxvalues - 1; ++j) { std::ostringstream os; os << "Bin " << i << "," << j; if (onAxis1) { if (small_bins) { - TS_ASSERT_DELTA(outputWS->readX(i)[j], - 5.0 + 0.2 * static_cast<double>(j), epsilon); + TS_ASSERT_DELTA(x[j], 5.0 + 0.2 * static_cast<double>(j), epsilon); } else { if (dist) { - TS_ASSERT_DELTA(outputWS->readX(i)[j], - 5.0 + 4.0 * static_cast<double>(j), epsilon); + TS_ASSERT_DELTA(x[j], 5.0 + 4.0 * static_cast<double>(j), + epsilon); } else { - TS_ASSERT_DELTA(outputWS->readX(i)[j], - 5.0 + 2.0 * static_cast<double>(j), epsilon); + TS_ASSERT_DELTA(x[j], 5.0 + 2.0 * static_cast<double>(j), + epsilon); } } } else { - TS_ASSERT_DELTA(outputWS->readX(i)[j], 5.0 + static_cast<double>(j), - epsilon); + TS_ASSERT_DELTA(x[j], 5.0 + static_cast<double>(j), epsilon); } if (dist) { - TS_ASSERT_DELTA(outputWS->readY(i)[j], 1.0, epsilon); - TS_ASSERT_DELTA(outputWS->readE(i)[j], 0.5, epsilon); + TS_ASSERT_DELTA(y[j], 1.0, epsilon); + TS_ASSERT_DELTA(e[j], 0.5, epsilon); } else { - TSM_ASSERT_DELTA(os.str(), outputWS->readY(i)[j], 4.0, epsilon); - TS_ASSERT_DELTA(outputWS->readE(i)[j], 2.0, epsilon); + TSM_ASSERT_DELTA(os.str(), y[j], 4.0, epsilon); + TS_ASSERT_DELTA(e[j], 2.0, epsilon); } } // Final X boundary if (small_bins) { - TS_ASSERT_DELTA(outputWS->readX(i)[nxvalues - 1], 6.0, epsilon); + TS_ASSERT_DELTA(x[nxvalues - 1], 6.0, epsilon); } else { if (dist) { - TS_ASSERT_DELTA(outputWS->readX(i)[nxvalues - 1], 25.0, epsilon); + TS_ASSERT_DELTA(x[nxvalues - 1], 25.0, epsilon); } else { - TS_ASSERT_DELTA(outputWS->readX(i)[nxvalues - 1], 15.0, epsilon); + TS_ASSERT_DELTA(x[nxvalues - 1], 15.0, epsilon); } } } @@ -209,7 +212,9 @@ private: class Rebin2DTestPerformance : public CxxTest::TestSuite { public: - Rebin2DTestPerformance() { m_inputWS = makeInputWS(false, true); } + Rebin2DTestPerformance() { + m_inputWS = makeInputWS(distribution, perf_test, small_bins); + } void test_On_Large_Workspace() { runAlgorithm(m_inputWS, "100,200,41000", "-0.5,2,499.5"); @@ -217,6 +222,10 @@ public: private: MatrixWorkspace_sptr m_inputWS; + + const bool distribution = false; + const bool perf_test = true; + const bool small_bins = false; }; #endif /* MANTID_ALGORITHMS_REBIN2DTEST_H_ */ diff --git a/Framework/Algorithms/test/SetUncertaintiesTest.h b/Framework/Algorithms/test/SetUncertaintiesTest.h index 162bf0aacc880afcc11a2b5486728e83ce208705..4f5ed91d34c442659cf5eb706d858f1cfa543911 100644 --- a/Framework/Algorithms/test/SetUncertaintiesTest.h +++ b/Framework/Algorithms/test/SetUncertaintiesTest.h @@ -26,9 +26,11 @@ public: API::MatrixWorkspace_sptr runAlg(const std::string &mode) { // random data mostly works auto inWksp = WorkspaceCreationHelper::Create1DWorkspaceRand(30); - auto E = inWksp->dataE(0); - E[0] = 0.; // stress oneIfZero - auto Y = inWksp->dataY(0); + // Ensure first elements of random workspace are zero so test don't + // pass randomly + auto &E = inWksp->mutableE(0); + E[0] = 0.; + auto &Y = inWksp->mutableY(0); Y[1] = 0.; // stress sqrtOrOne std::string outWSname = "SetUncertainties_" + mode; @@ -41,7 +43,7 @@ public: TS_ASSERT_THROWS_NOTHING(alg.execute()); TS_ASSERT(alg.isExecuted()); - auto outWS = + const auto outWS = API::AnalysisDataService::Instance().retrieveWS<API::MatrixWorkspace>( outWSname); TS_ASSERT(bool(outWS)); // non-null pointer @@ -49,10 +51,10 @@ public: } void test_zero() { - auto outWS = runAlg("zero"); + const auto outWS = runAlg("zero"); - const auto E = outWS->readE(0); - for (auto item : E) { + const auto E = outWS->e(0); + for (const auto item : E) { TS_ASSERT_EQUALS(item, 0.); } @@ -60,10 +62,10 @@ public: } void test_sqrt() { - auto outWS = runAlg("sqrt"); + const auto outWS = runAlg("sqrt"); - const auto E = outWS->readE(0); - const auto Y = outWS->readY(0); + const auto E = outWS->e(0); + const auto Y = outWS->y(0); for (size_t i = 0; i < E.size(); ++i) { TS_ASSERT_DELTA(Y[i], E[i] * E[i], .001); } @@ -72,20 +74,20 @@ public: } void test_oneIfZero() { - auto outWS = runAlg("oneIfZero"); + const auto outWS = runAlg("oneIfZero"); - const auto E = outWS->readE(0); - for (auto item : E) { + const auto E = outWS->e(0); + for (const auto item : E) { TS_ASSERT(item > 0.); } API::AnalysisDataService::Instance().remove(outWS->name()); } void test_sqrtOrOne() { - auto outWS = runAlg("sqrtOrOne"); + const auto outWS = runAlg("sqrtOrOne"); - const auto E = outWS->readE(0); - const auto Y = outWS->readY(0); + const auto &E = outWS->e(0); + const auto &Y = outWS->y(0); for (size_t i = 0; i < E.size(); ++i) { if (Y[i] == 0.) { TS_ASSERT_EQUALS(E[i], 1.); @@ -98,4 +100,41 @@ public: } }; +class SetUncertaintiesTestPerformance : public CxxTest::TestSuite { +public: + void setUp() { + algZero.initialize(); + algCalc.initialize(); + + // This size controls the test time - and aims for + // 0.1-0.2 seconds for the algorithm execution time + constexpr size_t wsSize(1000000); + + // random data mostly works + inputWs = WorkspaceCreationHelper::Create1DWorkspaceRand(wsSize); + algZero.setProperty("InputWorkspace", inputWs); + algZero.setProperty("SetError", "zero"); + algZero.setProperty("OutputWorkspace", wsName); + + algCalc.setProperty("InputWorkspace", inputWs); + algCalc.setProperty("SetError", "zero"); + algCalc.setProperty("OutputWorkspace", wsName); + + algZero.setRethrows(true); + algCalc.setRethrows(true); + } + + void testSetUncertaintiesPerformance() { + // First run zeroing all errors + TS_ASSERT_THROWS_NOTHING(algZero.execute()); + TS_ASSERT_THROWS_NOTHING(algCalc.execute()); + } + +private: + SetUncertainties algZero; + SetUncertainties algCalc; + boost::shared_ptr<Mantid::DataObjects::Workspace2D> inputWs; + const std::string wsName = "outputWs"; +}; + #endif /* MANTID_ALGORITHMS_SETUNCERTAINTIESTEST_H_ */ diff --git a/Framework/Algorithms/test/SmoothDataTest.h b/Framework/Algorithms/test/SmoothDataTest.h index d06d26af480fe799e4e8f39336e4cb005f278a82..248d5ae0c8a714219711d84f4cb9dbedab63aa0f 100644 --- a/Framework/Algorithms/test/SmoothDataTest.h +++ b/Framework/Algorithms/test/SmoothDataTest.h @@ -1,13 +1,14 @@ #ifndef SMOOTHDATATEST_H_ #define SMOOTHDATATEST_H_ -#include <cxxtest/TestSuite.h> -#include "MantidAlgorithms/CreateSampleWorkspace.h" -#include "MantidAlgorithms/CreateGroupingWorkspace.h" -#include "MantidAlgorithms/SmoothData.h" #include "MantidAPI/FrameworkManager.h" #include "MantidAPI/WorkspaceFactory.h" +#include "MantidAlgorithms/CreateGroupingWorkspace.h" +#include "MantidAlgorithms/CreateSampleWorkspace.h" +#include "MantidAlgorithms/SmoothData.h" #include "MantidDataObjects/GroupingWorkspace.h" +#include "MantidTestHelpers/WorkspaceCreationHelper.h" +#include <cxxtest/TestSuite.h> using namespace Mantid::API; using namespace Mantid::Algorithms; @@ -23,9 +24,13 @@ public: // Set up a small workspace for testing MatrixWorkspace_sptr space = WorkspaceFactory::Instance().create("Workspace2D", 2, 10, 10); + + auto &yVals = space->mutableY(0); + auto &eVals = space->mutableE(0); + for (int i = 0; i < 10; ++i) { - space->dataY(0)[i] = i + 1.0; - space->dataE(0)[i] = sqrt(i + 1.0); + yVals[i] = i + 1.0; + eVals[i] = sqrt(i + 1.0); } // Register the workspace in the data service @@ -109,9 +114,9 @@ public: MatrixWorkspace_const_sptr output = smooth.getProperty("OutputWorkspace"); // as alg child is set true, wouldnt need to use AnalysisDataService - const Mantid::MantidVec &Y = output->dataY(0); - const Mantid::MantidVec &X = output->dataX(0); - const Mantid::MantidVec &E = output->dataE(0); + const auto &Y = output->y(0); + const auto &X = output->x(0); + const auto &E = output->e(0); TS_ASSERT_EQUALS(Y[0], 0.3); TS_ASSERT_EQUALS(X[6], 1200); TS_ASSERT_DIFFERS(E[2], Y[2]); @@ -131,7 +136,7 @@ public: TS_ASSERT_DIFFERS(X[0], Y[0]); TS_ASSERT_DIFFERS(E[5], Y[5]); // Check X vectors are shared - TS_ASSERT_EQUALS(&(output->dataX(0)), &(output->dataX(1))); + TS_ASSERT_EQUALS(&(output->x(0)), &(output->x(1))); } void testExec() { @@ -153,8 +158,8 @@ public: TS_ASSERT_THROWS_NOTHING( output = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( outputWS)); - const Mantid::MantidVec &Y = output->dataY(0); - const Mantid::MantidVec &E = output->dataE(0); + const auto &Y = output->y(0); + const auto &E = output->e(0); TS_ASSERT_EQUALS(Y[0], 2); TS_ASSERT_DELTA(E[0], sqrt(Y[0] / 3.0), 0.0001); TS_ASSERT_EQUALS(Y[1], 2.5); @@ -169,10 +174,48 @@ public: TS_ASSERT_DELTA(E[9], sqrt(Y[9] / 3.0), 0.0001); // Check X vectors are shared - TS_ASSERT_EQUALS(&(output->dataX(0)), &(output->dataX(1))); + TS_ASSERT_EQUALS(&(output->x(0)), &(output->x(1))); AnalysisDataService::Instance().remove(outputWS); } }; +class SmoothDataTestPerformance : public CxxTest::TestSuite { +public: + void setUp() { + + // Set up a small workspace for testing + constexpr size_t numHistograms(1); + constexpr size_t numBins(1000000); + + inputWs = + WorkspaceCreationHelper::Create2DWorkspace(numHistograms, numBins); + + auto &yVals = inputWs->mutableY(0); + auto &eVals = inputWs->mutableE(0); + + double currentVal(0.0); + for (size_t i = 0; i < numBins; ++i) { + yVals[i] = currentVal + 1.0; + eVals[i] = sqrt(currentVal + 1.0); + currentVal++; + } + + smoothAlg.initialize(); + smoothAlg.setProperty("InputWorkspace", inputWs); + smoothAlg.setPropertyValue("OutputWorkspace", "outputWS"); + smoothAlg.setRethrows(true); + } + + void testSmoothDataPerformance() { + TS_ASSERT_THROWS_NOTHING(smoothAlg.execute()); + } + + void tearDown() { AnalysisDataService::Instance().remove("outputWS"); } + +private: + Workspace2D_sptr inputWs; + SmoothData smoothAlg; +}; + #endif /*SMOOTHDATATEST_H_*/ diff --git a/Framework/Algorithms/test/StripVanadiumPeaksTest.h b/Framework/Algorithms/test/StripVanadiumPeaksTest.h index 71b43cbc158f65d5b4064c4f846e0d3ea2c2f0ae..d2b1a22efe2456bdf1c52c0ec13246dcacd98133 100644 --- a/Framework/Algorithms/test/StripVanadiumPeaksTest.h +++ b/Framework/Algorithms/test/StripVanadiumPeaksTest.h @@ -12,7 +12,6 @@ using namespace Mantid::API; using namespace Mantid::Kernel::VectorHelper; using Mantid::Algorithms::StripVanadiumPeaks; -using Mantid::MantidVec; class StripVanadiumPeaksTest : public CxxTest::TestSuite { public: @@ -56,14 +55,14 @@ public: outputWSName); // Get a spectrum - MantidVec X = output->dataX(2); - MantidVec Y = output->dataX(2); + const auto &X = output->x(2); + const auto &Y = output->y(2); // Check the height at a couple of peak position int bin; - bin = getBinIndex(X, 0.8113); + bin = getBinIndex(X.rawData(), 0.8113); TS_ASSERT_LESS_THAN(Y[bin], 11407); - bin = getBinIndex(X, 0.8758); + bin = getBinIndex(X.rawData(), 0.8758); TS_ASSERT_LESS_THAN(Y[bin], 10850); AnalysisDataService::Instance().remove(outputWSName); diff --git a/Framework/Algorithms/test/SumEventsByLogValueTest.h b/Framework/Algorithms/test/SumEventsByLogValueTest.h index 1ba3e2bfacdc542e0967c1c53f9f7e3e1aedf1b6..749d0587c73fde428883ff0fd78f03fbbd244c8b 100644 --- a/Framework/Algorithms/test/SumEventsByLogValueTest.h +++ b/Framework/Algorithms/test/SumEventsByLogValueTest.h @@ -98,7 +98,7 @@ public: MatrixWorkspace_const_sptr outWS = boost::dynamic_pointer_cast<const MatrixWorkspace>(out); TS_ASSERT_EQUALS(outWS->getNumberHistograms(), 1); - TS_ASSERT_EQUALS(outWS->readY(0)[0], 300); + TS_ASSERT_EQUALS(outWS->y(0)[0], 300); } void test_double_property_with_number_of_bins_only() { @@ -186,7 +186,7 @@ public: } SumEventsByLogValueTestPerformance() { - ws = WorkspaceCreationHelper::CreateEventWorkspace(1000, 1, 10000); + ws = WorkspaceCreationHelper::CreateEventWorkspace(100, 100, 1000); // Add a bunch of logs std::vector<DateAndTime> times; std::vector<int> index; diff --git a/Framework/Algorithms/test/SumRowColumnTest.h b/Framework/Algorithms/test/SumRowColumnTest.h index b1ddadf7838496fd310cad2a0970e99862188d2a..293087a08276ddeb091c20630b93a5602cb60ec2 100644 --- a/Framework/Algorithms/test/SumRowColumnTest.h +++ b/Framework/Algorithms/test/SumRowColumnTest.h @@ -54,15 +54,15 @@ public: output = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve("H"))); // Check a couple of values - TS_ASSERT_EQUALS(output->readX(0).size(), 10) - TS_ASSERT_EQUALS(output->readY(0).size(), 10) - TS_ASSERT_EQUALS(output->readX(0)[1], 1) - TS_ASSERT_EQUALS(output->readX(0)[9], 9) - TS_ASSERT_EQUALS(output->readY(0)[1], 200) - TS_ASSERT_EQUALS(output->readY(0)[9], 200) + TS_ASSERT_EQUALS(output->x(0).size(), 10) + TS_ASSERT_EQUALS(output->y(0).size(), 10) + TS_ASSERT_EQUALS(output->x(0)[1], 1) + TS_ASSERT_EQUALS(output->x(0)[9], 9) + TS_ASSERT_EQUALS(output->y(0)[1], 200) + TS_ASSERT_EQUALS(output->y(0)[9], 200) // This algorithm doesn't compute errors - TS_ASSERT_EQUALS(output->readE(0)[1], 0) - TS_ASSERT_EQUALS(output->readE(0)[9], 0) + TS_ASSERT_EQUALS(output->e(0)[1], 0) + TS_ASSERT_EQUALS(output->e(0)[9], 0) TSM_ASSERT("Should have an empty unit", boost::dynamic_pointer_cast<Mantid::Kernel::Units::Empty>( @@ -89,15 +89,15 @@ public: output = boost::dynamic_pointer_cast<MatrixWorkspace>( AnalysisDataService::Instance().retrieve("V"))); // Check a couple of values - TS_ASSERT_EQUALS(output->readX(0).size(), 10) - TS_ASSERT_EQUALS(output->readY(0).size(), 10) - TS_ASSERT_EQUALS(output->readX(0)[1], 1) - TS_ASSERT_EQUALS(output->readX(0)[9], 9) - TS_ASSERT_EQUALS(output->readY(0)[1], 60) - TS_ASSERT_EQUALS(output->readY(0)[9], 60) + TS_ASSERT_EQUALS(output->x(0).size(), 10) + TS_ASSERT_EQUALS(output->y(0).size(), 10) + TS_ASSERT_EQUALS(output->x(0)[1], 1) + TS_ASSERT_EQUALS(output->x(0)[9], 9) + TS_ASSERT_EQUALS(output->y(0)[1], 60) + TS_ASSERT_EQUALS(output->y(0)[9], 60) // This algorithm doesn't compute errors - TS_ASSERT_EQUALS(output->readE(0)[1], 0) - TS_ASSERT_EQUALS(output->readE(0)[9], 0) + TS_ASSERT_EQUALS(output->e(0)[1], 0) + TS_ASSERT_EQUALS(output->e(0)[9], 0) } private: diff --git a/Framework/Algorithms/test/SumSpectraTest.h b/Framework/Algorithms/test/SumSpectraTest.h index 8f0dab72fbfc089836f8e620437cd6002e30d9b1..17b4481d03557ccc7c4242ff41be4dfc33b06b93 100644 --- a/Framework/Algorithms/test/SumSpectraTest.h +++ b/Framework/Algorithms/test/SumSpectraTest.h @@ -27,7 +27,7 @@ public: this->inputSpace->instrumentParameters().addBool( inputSpace->getDetector(1).get(), "masked", true); - inputSpace->dataE(5)[38] = 0.0; + inputSpace->mutableE(5)[38] = 0.0; } ~SumSpectraTest() override { AnalysisDataService::Instance().clear(); } @@ -64,19 +64,18 @@ public: TS_ASSERT_EQUALS(max = inputSpace->blocksize(), output2D->blocksize()); TS_ASSERT_EQUALS(output2D->getNumberHistograms(), 1); - const Mantid::MantidVec &x = output2D->readX(0); - const Mantid::MantidVec &y = output2D->readY(0); - const Mantid::MantidVec &e = output2D->readE(0); + const auto &x = output2D->x(0); + const auto &y = output2D->y(0); + const auto &e = output2D->e(0); TS_ASSERT_EQUALS(x.size(), 103); TS_ASSERT_EQUALS(y.size(), 102); TS_ASSERT_EQUALS(e.size(), 102); for (size_t i = 0; i < max; ++i) { - TS_ASSERT_EQUALS(x[i], inputSpace->readX(0)[i]); - TS_ASSERT_EQUALS(y[i], inputSpace->readY(2)[i] + inputSpace->readY(3)[i]); + TS_ASSERT_EQUALS(x[i], inputSpace->x(0)[i]); + TS_ASSERT_EQUALS(y[i], inputSpace->y(2)[i] + inputSpace->y(3)[i]); TS_ASSERT_DELTA( - e[i], std::sqrt(inputSpace->readY(2)[i] + inputSpace->readY(3)[i]), - 1.0e-10); + e[i], std::sqrt(inputSpace->y(2)[i] + inputSpace->y(3)[i]), 1.0e-10); } // Check the detectors mapped to the single spectra @@ -125,17 +124,17 @@ public: TS_ASSERT_EQUALS(output2D->getNumberHistograms(), 1); - const Mantid::MantidVec &x = output2D->readX(0); - const Mantid::MantidVec &y = output2D->readY(0); - const Mantid::MantidVec &e = output2D->readE(0); + const auto &x = output2D->x(0); + const auto &y = output2D->y(0); + const auto &e = output2D->e(0); TS_ASSERT_EQUALS(x.size(), 103); TS_ASSERT_EQUALS(y.size(), 102); TS_ASSERT_EQUALS(e.size(), 102); // Check a few bins - TS_ASSERT_EQUALS(x[0], inputSpace->readX(0)[0]); - TS_ASSERT_EQUALS(x[50], inputSpace->readX(0)[50]); - TS_ASSERT_EQUALS(x[100], inputSpace->readX(0)[100]); + TS_ASSERT_EQUALS(x[0], inputSpace->x(0)[0]); + TS_ASSERT_EQUALS(x[50], inputSpace->x(0)[50]); + TS_ASSERT_EQUALS(x[100], inputSpace->x(0)[100]); TS_ASSERT_EQUALS(y[7], 14); TS_ASSERT_EQUALS(y[38], 14); TS_ASSERT_EQUALS(y[72], 14); @@ -210,7 +209,7 @@ public: TS_ASSERT(output); TS_ASSERT_EQUALS(output->getNumberHistograms(), 1); TS_ASSERT_EQUALS(output->getNumberEvents(), 9 * numEvents); - TS_ASSERT_EQUALS(input->readX(0).size(), output->readX(0).size()); + TS_ASSERT_EQUALS(input->x(0).size(), output->x(0).size()); TS_ASSERT(output->run().hasProperty("NumAllSpectra")) TS_ASSERT(output->run().hasProperty("NumMaskSpectra")) @@ -247,12 +246,12 @@ public: TS_ASSERT_EQUALS(output->getNumberHistograms(), 1); TS_ASSERT_EQUALS(output->blocksize(), 6); // Row with full acceptance - TS_ASSERT_EQUALS(output->dataY(0)[1], 1.); - TS_ASSERT_DELTA(output->dataE(0)[1], 0.40824829046386296, 1.e-5); + TS_ASSERT_EQUALS(output->mutableY(0)[1], 1.); + TS_ASSERT_DELTA(output->mutableE(0)[1], 0.40824829046386296, 1.e-5); TS_ASSERT_EQUALS(output->dataF(0)[1], 6.); // Row with limited, but non-zero acceptance, shouldn't have nans! - TS_ASSERT_DELTA(output->dataY(0)[5], 0.66666, 1.e-5); - TS_ASSERT_DELTA(output->dataE(0)[5], 0.47140452079103173, 1.e-5); + TS_ASSERT_DELTA(output->mutableY(0)[5], 0.66666, 1.e-5); + TS_ASSERT_DELTA(output->mutableE(0)[5], 0.47140452079103173, 1.e-5); TS_ASSERT_EQUALS(output->dataF(0)[5], 3.); TS_ASSERT(output->run().hasProperty("NumAllSpectra")) @@ -271,8 +270,8 @@ public: TS_ASSERT_THROWS_NOTHING(alg2.initialize()); TS_ASSERT(alg2.isInitialized()); - const Mantid::MantidVec &y0 = inputSpace->readY(0); - const Mantid::MantidVec &e0 = inputSpace->readE(0); + const auto &y0 = inputSpace->y(0); + const auto &e0 = inputSpace->e(0); // Set the properties alg2.setProperty("InputWorkspace", inputSpace); const std::string outputSpace2 = "SumSpectraOut2"; @@ -292,9 +291,9 @@ public: TS_ASSERT_EQUALS(output2D->getNumberHistograms(), 1); - const Mantid::MantidVec &x = output2D->readX(0); - const Mantid::MantidVec &y = output2D->readY(0); - const Mantid::MantidVec &e = output2D->readE(0); + const auto &x = output2D->x(0); + const auto &y = output2D->y(0); + const auto &e = output2D->e(0); TS_ASSERT_EQUALS(x.size(), 103); TS_ASSERT_EQUALS(y.size(), 102); TS_ASSERT_EQUALS(e.size(), 102); @@ -313,9 +312,9 @@ public: size_t nSignals = nTestHist - 3; // Check a few bins - TS_ASSERT_EQUALS(x[0], inputSpace->readX(0)[0]); - TS_ASSERT_EQUALS(x[50], inputSpace->readX(0)[50]); - TS_ASSERT_EQUALS(x[100], inputSpace->readX(0)[100]); + TS_ASSERT_EQUALS(x[0], inputSpace->x(0)[0]); + TS_ASSERT_EQUALS(x[50], inputSpace->x(0)[50]); + TS_ASSERT_EQUALS(x[100], inputSpace->x(0)[100]); TS_ASSERT_DELTA(y[7], double(nSignals) * y0[7], 1.e-6); TS_ASSERT_DELTA(y[38], double(nSignals - 1) * y0[38], 1.e-6); TS_ASSERT_DELTA(y[72], double(nSignals) * y0[72], 1.e-6); @@ -359,8 +358,8 @@ public: testVal[2] = 1; testVal[3] = 10; for (int i = 0; i < nHist; i++) { - Mantid::MantidVec &y0 = tws->dataY(i); - Mantid::MantidVec &e0 = tws->dataE(i); + auto &y0 = tws->mutableY(i); + auto &e0 = tws->mutableE(i); for (int j = 0; j < nBins; j++) { y0[j] = testVal[i]; e0[j] = std::sqrt(testVal[i]); @@ -390,9 +389,9 @@ public: TS_ASSERT_EQUALS(output2D->getNumberHistograms(), 1); - const Mantid::MantidVec &x = output2D->readX(0); - const Mantid::MantidVec &y = output2D->readY(0); - const Mantid::MantidVec &e = output2D->readE(0); + const auto &x = output2D->x(0); + const auto &y = output2D->y(0); + const auto &e = output2D->e(0); TS_ASSERT_EQUALS(x.size(), nBins + 1); TS_ASSERT_EQUALS(y.size(), nBins); TS_ASSERT_EQUALS(e.size(), nBins); @@ -409,9 +408,9 @@ public: output2D->run().getLogData("NumZeroSpectra")->value()) // Check a few bins - TS_ASSERT_EQUALS(x[0], tws->readX(0)[0]); - TS_ASSERT_EQUALS(x[5], tws->readX(0)[5]); - TS_ASSERT_EQUALS(x[10], tws->readX(0)[10]); + TS_ASSERT_EQUALS(x[0], tws->x(0)[0]); + TS_ASSERT_EQUALS(x[5], tws->x(0)[5]); + TS_ASSERT_EQUALS(x[10], tws->x(0)[10]); TS_ASSERT_DELTA(y[0], testRez, 1.e-6); TS_ASSERT_DELTA(y[5], testRez, 1.e-6); TS_ASSERT_DELTA(y[9], testRez, 1.e-6); diff --git a/Framework/Algorithms/test/TOFSANSResolutionByPixelTest.h b/Framework/Algorithms/test/TOFSANSResolutionByPixelTest.h index 81d2c9df506170e312cffa6f382b050bc9fa30c5..272ad4e9c8cfe25cb067d28290c02ad4c3d6a9db 100644 --- a/Framework/Algorithms/test/TOFSANSResolutionByPixelTest.h +++ b/Framework/Algorithms/test/TOFSANSResolutionByPixelTest.h @@ -236,8 +236,8 @@ public: result = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>( Mantid::API::AnalysisDataService::Instance().retrieve(outputWS))); - const Mantid::MantidVec &xOUT = result->dataX(0); - const Mantid::MantidVec &xIN = testWorkspace->dataX(0); + const auto &xOUT = result->x(0); + const auto &xIN = testWorkspace->x(0); TSM_ASSERT_EQUALS("Output should have the same binning as the input.", xOUT.size(), xIN.size()); diff --git a/Framework/Algorithms/test/TransposeTest.h b/Framework/Algorithms/test/TransposeTest.h index 664f820e6e85cbfa71ad28fa7070b5779d1b1c86..a6a35a2fd7023d11bee54a4fc9ced90c71104a50 100644 --- a/Framework/Algorithms/test/TransposeTest.h +++ b/Framework/Algorithms/test/TransposeTest.h @@ -17,6 +17,14 @@ using namespace Mantid::DataObjects; class TransposeTest : public CxxTest::TestSuite { public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static TransposeTest *createSuite() { return new TransposeTest(); } + static void destroySuite(TransposeTest *suite) { + AnalysisDataService::Instance().clear(); + delete suite; + } + void testMetaInfo() { transpose = new Transpose(); TS_ASSERT_EQUALS(transpose->name(), "Transpose"); @@ -84,9 +92,9 @@ public: TS_ASSERT_EQUALS(outputWS->getAxis(0)->unit(), inputWS->getAxis(1)->unit()); // Values - TS_ASSERT_EQUALS(inputWS->readY(0)[0], outputWS->readY(0)[0]); - TS_ASSERT_EQUALS(inputWS->readY(nHist - 1)[nBins - 1], - outputWS->readY(nBins - 1)[nHist - 1]); + TS_ASSERT_EQUALS(inputWS->y(0)[0], outputWS->y(0)[0]); + TS_ASSERT_EQUALS(inputWS->y(nHist - 1)[nBins - 1], + outputWS->y(nBins - 1)[nHist - 1]); delete transpose; } @@ -115,13 +123,13 @@ public: TS_ASSERT_EQUALS(outputWS->getNumberHistograms(), inputWS->blocksize()); // Value - TS_ASSERT_EQUALS(outputWS->dataY(3)[1], inputWS->dataY(1)[3]); - TS_ASSERT_DELTA(outputWS->dataE(3)[1], inputWS->dataE(1)[3], 1.e-5); + TS_ASSERT_EQUALS(outputWS->mutableY(3)[1], inputWS->mutableY(1)[3]); + TS_ASSERT_DELTA(outputWS->mutableE(3)[1], inputWS->mutableE(1)[3], 1.e-5); TS_ASSERT_EQUALS(outputWS->dataF(0).size(), 4); TS_ASSERT_EQUALS(outputWS->dataF(3)[1], inputWS->dataF(1)[3]); // Check a nan - bool inNan = std::isnan(inputWS->dataY(0)[5]); - bool outNan = std::isnan(outputWS->dataY(5)[0]); + bool inNan = boost::math::isnan(inputWS->mutableY(0)[5]); + bool outNan = boost::math::isnan(outputWS->mutableY(5)[0]); TS_ASSERT_EQUALS(outNan, inNan); delete transpose; @@ -130,4 +138,66 @@ public: private: Transpose *transpose; }; + +class TransposeTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static TransposeTestPerformance *createSuite() { + return new TransposeTestPerformance(); + } + static void destroySuite(TransposeTestPerformance *suite) { + AnalysisDataService::Instance().clear(); + delete suite; + } + + TransposeTestPerformance() { + + // set up testExecPerformance + IAlgorithm *loader; + loader = new Mantid::DataHandling::LoadRaw3; + loader->initialize(); + loader->setPropertyValue("Filename", "IRS21360.raw"); + loader->setPropertyValue("OutputWorkspace", "transpose_irs_r"); + loader->setPropertyValue("SpectrumMin", "3"); + loader->setPropertyValue("SpectrumMax", "13"); + + TS_ASSERT_THROWS_NOTHING(loader->execute()); + TS_ASSERT(loader->isExecuted()); + + delete loader; + + // set up testRebinnedOutputPerformance + RebinnedOutput_sptr inputWS = + WorkspaceCreationHelper::CreateRebinnedOutputWorkspace(); + std::string inName = rebinned_inputWS; + AnalysisDataService::Instance().addOrReplace(inName, inputWS); + } + + void testExecPerformance() { + // Input workspace + Transpose transpose; + MatrixWorkspace_const_sptr inputWS = + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + "transpose_irs_r"); + transpose.initialize(); + + transpose.setPropertyValue("InputWorkspace", "transpose_irs_r"); + transpose.setPropertyValue("OutputWorkspace", "transpose_irs_t"); + TS_ASSERT_THROWS_NOTHING(transpose.execute()); + TS_ASSERT(transpose.isExecuted()); + } + + void testRebinnedOutputPerformance() { + Transpose transpose; + transpose.initialize(); + transpose.setPropertyValue("InputWorkspace", rebinned_inputWS); + transpose.setPropertyValue("OutputWorkspace", rebinned_outputWS); + TS_ASSERT_THROWS_NOTHING(transpose.execute()); + TS_ASSERT(transpose.isExecuted()); + } + + const std::string rebinned_inputWS = "rebinned_inputWS"; + const std::string rebinned_outputWS = "rebinned_outputWS"; +}; #endif diff --git a/Framework/Algorithms/test/UnwrapSNSTest.h b/Framework/Algorithms/test/UnwrapSNSTest.h index 874ca566bd36e8da695fdedc5a111623b28a7f0d..78f1661f1a8c5f74eab87d7f580431ad1f50debb 100644 --- a/Framework/Algorithms/test/UnwrapSNSTest.h +++ b/Framework/Algorithms/test/UnwrapSNSTest.h @@ -87,9 +87,9 @@ public: TS_ASSERT(min_eventN < ws->getSpectrum(NUMPIXELS - 1).getTofMin()); TS_ASSERT(max_eventN < ws->getSpectrum(NUMPIXELS - 1).getTofMax()); - TS_ASSERT_EQUALS(ws->getSpectrum(0).dataX()[0], 0.0); - TS_ASSERT_EQUALS(ws->getSpectrum(0).dataX()[1], 2.0); - TS_ASSERT_EQUALS(ws->getSpectrum(0).dataX()[2], 4.0); + TS_ASSERT_EQUALS(ws->getSpectrum(0).x()[0], 0.0); + TS_ASSERT_EQUALS(ws->getSpectrum(0).x()[1], 2.0); + TS_ASSERT_EQUALS(ws->getSpectrum(0).x()[2], 4.0); } }; diff --git a/Framework/Algorithms/test/WeightedMeanOfWorkspaceTest.h b/Framework/Algorithms/test/WeightedMeanOfWorkspaceTest.h index ddf8b0ce2aaaafa5ac96240c3c0e2375db033a32..f00686b59302d7fd0def80bb4388da07f4bbd8da 100644 --- a/Framework/Algorithms/test/WeightedMeanOfWorkspaceTest.h +++ b/Framework/Algorithms/test/WeightedMeanOfWorkspaceTest.h @@ -54,8 +54,8 @@ public: return; TS_ASSERT_EQUALS(ws->getNumberHistograms(), 1); - TS_ASSERT_EQUALS(ws->readY(0)[0], 2.0); - TS_ASSERT_EQUALS(ws->readE(0)[0], 1.0); + TS_ASSERT_EQUALS(ws->y(0)[0], 2.0); + TS_ASSERT_EQUALS(ws->e(0)[0], 1.0); // Remove workspace from the data service. AnalysisDataService::Instance().remove(outWSName); @@ -66,9 +66,9 @@ public: MatrixWorkspace_sptr inputWS = createWorkspace(false); // Put bad values into workspace - inputWS->dataY(1)[0] = std::numeric_limits<double>::quiet_NaN(); - inputWS->dataE(1)[1] = std::numeric_limits<double>::quiet_NaN(); - inputWS->dataY(1)[2] = std::numeric_limits<double>::infinity(); + inputWS->mutableY(1)[0] = std::numeric_limits<double>::quiet_NaN(); + inputWS->mutableE(1)[1] = std::numeric_limits<double>::quiet_NaN(); + inputWS->mutableY(1)[2] = std::numeric_limits<double>::infinity(); // Name of the output workspace. std::string outWSName("WeightedMeanOfWorkspaceTest_OutputWS"); @@ -88,8 +88,8 @@ public: return; TS_ASSERT_EQUALS(ws->getNumberHistograms(), 1); - TS_ASSERT_EQUALS(ws->readY(0)[0], 2.0); - TS_ASSERT_EQUALS(ws->readE(0)[0], 1.0); + TS_ASSERT_EQUALS(ws->y(0)[0], 2.0); + TS_ASSERT_EQUALS(ws->e(0)[0], 1.0); // Remove workspace from the data service. AnalysisDataService::Instance().remove(outWSName); diff --git a/Framework/Algorithms/test/WienerSmoothTest.h b/Framework/Algorithms/test/WienerSmoothTest.h index e6b8b094b0481acd0c891cec4071013af48a9a23..a0816cee670e2cdc161d50c6b90913ac9bd797a0 100644 --- a/Framework/Algorithms/test/WienerSmoothTest.h +++ b/Framework/Algorithms/test/WienerSmoothTest.h @@ -522,9 +522,9 @@ private: double *ysmooth) { auto dataWS = WorkspaceFactory::Instance().create("Workspace2D", 1, nx, ny); - auto &X = dataWS->dataX(0); - auto &Y = dataWS->dataY(0); - auto &E = dataWS->dataE(0); + auto &X = dataWS->mutableX(0); + auto &Y = dataWS->mutableY(0); + auto &E = dataWS->mutableE(0); X.assign(x, x + nx); Y.assign(y, y + ny); E.assign(e, e + ny); @@ -532,11 +532,10 @@ private: std::vector<int> wsIndexList(1, 0); auto outputWs = runWienerSmooth(dataWS, wsIndexList); - auto &outY = outputWs->readY(0); + auto &outY = outputWs->y(0); for (size_t i = 0; i < outY.size(); ++i) { TS_ASSERT_DELTA(outY[i], ysmooth[i], 1e-5); - // std::cerr << outY[i] << '\n'; } AnalysisDataService::Instance().clear(); @@ -557,8 +556,8 @@ private: for (size_t outSpec = 0; outSpec < nSpec; ++outSpec) { size_t inSpec = wsIndexList.empty() ? outSpec : wsIndexList[outSpec]; - auto &inY = inputWS->readY(inSpec); - auto &outY = outputWS->readY(outSpec); + auto &inY = inputWS->y(inSpec); + auto &outY = outputWS->y(outSpec); TS_ASSERT(!std::equal(outY.begin(), outY.end(), inY.begin())); std::vector<double> diff(inY.size()); @@ -599,13 +598,13 @@ private: outWSName)); TS_ASSERT(ws); - auto &inX = inputWS->readX(0); - auto &inE = inputWS->readE(0); + auto &inX = inputWS->x(0); + auto &inE = inputWS->e(0); for (size_t i = 0; i < ws->getNumberHistograms(); ++i) { - auto outX = ws->readX(i); - auto outE = ws->readE(i); + auto outX = ws->x(i); + auto outE = ws->e(i); TS_ASSERT(std::equal(outX.begin(), outX.end(), inX.begin())); TS_ASSERT(std::equal(outE.begin(), outE.end(), inE.begin())); @@ -634,9 +633,9 @@ private: WorkspaceFactory::Instance().create("Workspace2D", nSpec, nx, ny); for (size_t i = 0; i < nSpec; ++i) { - auto &X = dataWS->dataX(i); - auto &Y = dataWS->dataY(i); - auto &E = dataWS->dataE(i); + auto &X = dataWS->mutableX(i); + auto &Y = dataWS->mutableY(i); + auto &E = dataWS->mutableE(i); X.assign(x, x + nx); Y.assign(y, y + ny); E.assign(e, e + ny); diff --git a/Framework/Algorithms/test/WorkspaceGroupTest.h b/Framework/Algorithms/test/WorkspaceGroupTest.h index 7b7febb1cecbf114503ad206131938913abfbb30..978c70964f0d1dd4a55fc696b71dd732345533d3 100644 --- a/Framework/Algorithms/test/WorkspaceGroupTest.h +++ b/Framework/Algorithms/test/WorkspaceGroupTest.h @@ -296,6 +296,142 @@ public: AnalysisDataService::Instance().remove("InputWS"); } + void testRenameWorkspaceConsecutiveDuplicates() { + // Tests that setting a workspace to the name of an existing + // workspace in a group is correctly handled by the workspace group + // when they are consecutive + + constexpr int nHist = 20, nBins = 10; + // Register the workspace in the data service + MatrixWorkspace_sptr work_in1 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins); + MatrixWorkspace_sptr work_in2 = + WorkspaceCreationHelper::Create2DWorkspace154(nHist, nBins); + + const std::string ws1Name = "test_ws1"; + const std::string ws2Name = "test_ws2"; + const std::string wsGroupName = "test_group"; + + WorkspaceGroup_sptr wsSptr = WorkspaceGroup_sptr(new WorkspaceGroup); + if (wsSptr) { + AnalysisDataService::Instance().add(wsGroupName, wsSptr); + AnalysisDataService::Instance().add(ws1Name, work_in1); + wsSptr->add(ws1Name); + AnalysisDataService::Instance().add(ws2Name, work_in2); + wsSptr->add(ws2Name); + } + + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 2); + + // Rename ws2Name to ws1Name + AnalysisDataService::Instance().rename(ws2Name, ws1Name); + + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 1); + TS_ASSERT_EQUALS(wsSptr->contains(work_in2), true); + TS_ASSERT_EQUALS(wsSptr->contains(work_in1), false); + + AnalysisDataService::Instance().remove(ws1Name); + AnalysisDataService::Instance().remove(wsGroupName); + } + + void testRenameWorkspaceNonConsecutiveDuplicates() { + // Performs the same test as testRenameWorkspaceConsecutiveDuplicates + // but for workspaces where the duplicates are not adjacent + + // If this test fails but the aforementioned test passes it means + // the algorithm is only considering consecutive workspaces + + constexpr int nHist = 20, nBins = 10; + // Register the workspace in the data service + MatrixWorkspace_sptr work_in1 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins); + MatrixWorkspace_sptr work_in2 = + WorkspaceCreationHelper::Create2DWorkspace154(nHist, nBins); + MatrixWorkspace_sptr work_in3 = + WorkspaceCreationHelper::Create2DWorkspace154(nHist, nBins); + + const std::string ws1Name = "test_ws1"; + const std::string ws2Name = "test_ws2"; + const std::string ws3Name = "test_ws3"; + const std::string wsGroupName = "test_group"; + + WorkspaceGroup_sptr wsSptr = WorkspaceGroup_sptr(new WorkspaceGroup); + if (wsSptr) { + AnalysisDataService::Instance().add(wsGroupName, wsSptr); + AnalysisDataService::Instance().add(ws1Name, work_in1); + wsSptr->add(ws1Name); + AnalysisDataService::Instance().add(ws2Name, work_in2); + wsSptr->add(ws2Name); + AnalysisDataService::Instance().add(ws3Name, work_in3); + wsSptr->add(ws3Name); + } + + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 3); + + // Rename wsName3 to wsName1 + AnalysisDataService::Instance().rename(ws3Name, ws1Name); + + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 2); + TS_ASSERT_EQUALS(wsSptr->contains(work_in3), true); + TS_ASSERT_EQUALS(wsSptr->contains(work_in2), true); + TS_ASSERT_EQUALS(wsSptr->contains(work_in1), false); + + AnalysisDataService::Instance().remove(ws1Name); + AnalysisDataService::Instance().remove(ws2Name); + AnalysisDataService::Instance().remove(wsGroupName); + } + + void testRenameWorkspaceDuplicateNotInGroup() { + // Tests renaming a workspace that is part of a group + // to a name that exists but not in a group + + constexpr int nHist = 20, nBins = 10; + // Register the workspace in the data service + MatrixWorkspace_sptr inGroupWs1 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins); + MatrixWorkspace_sptr inGroupWs2 = + WorkspaceCreationHelper::Create2DWorkspace123(nHist, nBins); + MatrixWorkspace_sptr notInGroupWs = + WorkspaceCreationHelper::Create2DWorkspace154(nHist, nBins); + + const std::string inGroupWsName1 = "test_ws1"; + const std::string inGroupWsName2 = "test_ws2"; + const std::string notInGroupWsName = "test_outOfGroup"; + const std::string wsGroupName = "test_group"; + + WorkspaceGroup_sptr wsSptr = WorkspaceGroup_sptr(new WorkspaceGroup); + if (wsSptr) { + AnalysisDataService::Instance().add(wsGroupName, wsSptr); + AnalysisDataService::Instance().add(inGroupWsName1, inGroupWs1); + wsSptr->add(inGroupWsName1); + AnalysisDataService::Instance().add(inGroupWsName2, inGroupWs2); + wsSptr->add(inGroupWsName2); + AnalysisDataService::Instance().add(notInGroupWsName, notInGroupWs); + } + + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 2); + TS_ASSERT_EQUALS( + AnalysisDataService::Instance().doesExist(notInGroupWsName), true); + + // Rename groupWs to use a name outside of group + AnalysisDataService::Instance().rename(inGroupWsName1, notInGroupWsName); + + // Test the group didn't change size or pointers only names + TS_ASSERT_EQUALS(wsSptr->getNumberOfEntries(), 2); + TS_ASSERT_EQUALS(wsSptr->contains(inGroupWs1), true); + TS_ASSERT_EQUALS(wsSptr->contains(notInGroupWs), false); + const auto &groupNames = wsSptr->getNames(); + TS_ASSERT_EQUALS(doesExistInVector(groupNames, inGroupWsName1), false); + TS_ASSERT_EQUALS(doesExistInVector(groupNames, notInGroupWsName), true); + + // Test the workspace outside the group was deleted + const auto &allSptrs = AnalysisDataService::Instance().getObjects(); + TS_ASSERT_EQUALS(doesExistInVector(allSptrs, notInGroupWs), false); + + AnalysisDataService::Instance().remove(inGroupWsName1); + AnalysisDataService::Instance().remove(wsGroupName); + } + void testTwoGroupWorkspaces() { int nHist = 10, nBins = 20; // Register the workspace in the data service @@ -605,6 +741,13 @@ public: AnalysisDataService::Instance().remove("test_out_3"); AnalysisDataService::Instance().remove("test_out_4"); } + +private: + template <typename VT, typename VA, typename T> + bool doesExistInVector(const std::vector<VT, VA> &vec, const T &val) const { + // Where VA is for custom VectorAllocators + return (std::find(vec.cbegin(), vec.cend(), val)) != vec.cend(); + } }; #endif /*PLUSTEST_H_*/ diff --git a/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h b/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h index 81b591db67930a37d51534bb3dd533d18d290e63..837aeff6fe7a15b0ad06380ed28bddc03c429f59 100644 --- a/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h +++ b/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h @@ -21,6 +21,12 @@ #include <array> +// Forward Declarations +namespace Mantid { +namespace HistogramData { +class HistogramX; +} +} namespace Mantid { namespace Crystal { /** @@ -287,8 +293,8 @@ private: Kernel::V3D &Center, double &Radius, int *&ArryofID); int CalculateTimeChannelSpan(Geometry::IPeak const &peak, const double dQ, - Mantid::MantidVec const &X, const int specNum, - int &Centerchan); + const Mantid::HistogramData::HistogramX &X, + const int specNum, int &Centerchan); double CalculatePositionSpan(Geometry::IPeak const &peak, const double dQ); @@ -341,8 +347,8 @@ private: const double row, const double col, std::vector<double> &StatBase); - int find(std::string const &oneName, - std::vector<std::string> const &nameList); + int findNameInVector(std::string const &oneName, + std::vector<std::string> const &nameList); double CalculateIsawIntegrateError(const double background, const double backError, @@ -355,7 +361,8 @@ private: double &pixWidthx, double &pixHeighty, Geometry::IPeak const &peak) const; - int find(Mantid::MantidVec const &X, const double time); + int findTimeChannel(const Mantid::HistogramData::HistogramX &X, + const double time); // returns true if Neighborhood list is changed bool updateNeighbors(boost::shared_ptr<Geometry::IComponent> &comp, diff --git a/Framework/Crystal/src/AnvredCorrection.cpp b/Framework/Crystal/src/AnvredCorrection.cpp index 93b633615f0b5a692de97685291080c0b6c210c6..5d1051413c2fa2168a1817e869065b42a91d30f5 100644 --- a/Framework/Crystal/src/AnvredCorrection.cpp +++ b/Framework/Crystal/src/AnvredCorrection.cpp @@ -133,7 +133,7 @@ void AnvredCorrection::exec() { } } - std::string unitStr = m_inputWS->getAxis(0)->unit()->unitID(); + const std::string &unitStr = m_inputWS->getAxis(0)->unit()->unitID(); // Get the input parameters retrieveBaseProperties(); @@ -154,14 +154,13 @@ void AnvredCorrection::exec() { MatrixWorkspace_sptr correctionFactors = WorkspaceFactory::Instance().create(m_inputWS); + // needs to be a signed because OpenMP gives an error otherwise const int64_t numHists = static_cast<int64_t>(m_inputWS->getNumberHistograms()); const int64_t specSize = static_cast<int64_t>(m_inputWS->blocksize()); if (specSize < 3) throw std::runtime_error("Problem in AnvredCorrection::events not binned"); - const bool isHist = m_inputWS->isHistogramData(); - // If sample not at origin, shift cached positions. const V3D samplePos = m_inputWS->getInstrument()->getSample()->getPos(); const V3D pos = m_inputWS->getInstrument()->getSource()->getPos() - samplePos; @@ -173,18 +172,6 @@ void AnvredCorrection::exec() { for (int64_t i = 0; i < int64_t(numHists); ++i) { PARALLEL_START_INTERUPT_REGION - // Get a reference to the Y's in the output WS for storing the factors - MantidVec &Y = correctionFactors->dataY(i); - MantidVec &E = correctionFactors->dataE(i); - - // Copy over bin boundaries - const auto &inSpec = m_inputWS->getSpectrum(i); - - const MantidVec &Xin = inSpec.readX(); - correctionFactors->dataX(i) = Xin; - const MantidVec &Yin = inSpec.readY(); - const MantidVec &Ein = inSpec.readE(); - // Get detector position IDetector_const_sptr det; try { @@ -208,28 +195,46 @@ void AnvredCorrection::exec() { // scattered beam double scattering = dir.angle(V3D(0.0, 0.0, 1.0)); - Mantid::Kernel::Units::Wavelength wl; - std::vector<double> timeflight; double depth = 0.2; + double pathlength = 0.0; + std::string bankName; - if (m_useScaleFactors) + + if (m_useScaleFactors) { scale_init(det, inst, L2, depth, pathlength, bankName); + } + + Mantid::Kernel::Units::Wavelength wl; + auto points = m_inputWS->points(i); + // share bin boundaries + const auto &inSpec = m_inputWS->getSpectrum(i); + correctionFactors->setSharedX(i, inSpec.sharedX()); + + // get references to input data for calculations + const auto &Yin = inSpec.y(); + const auto &Ein = inSpec.x(); + + // Get a reference to the Y's in the output WS for storing the factors + auto &Y = correctionFactors->mutableY(i); + auto &E = correctionFactors->mutableE(i); // Loop through the bins in the current spectrum for (int64_t j = 0; j < specSize; j++) { - timeflight.push_back((isHist ? (0.5 * (Xin[j] + Xin[j + 1])) : Xin[j])); - if (unitStr.compare("TOF") == 0) - wl.fromTOF(timeflight, timeflight, L1, L2, scattering, 0, 0, 0); - double lambda = timeflight[0]; - timeflight.clear(); + + double lambda = + (unitStr == "TOF") + ? wl.convertSingleFromTOF(points[j], L1, L2, scattering, 0, 0, 0) + : points[j]; if (m_returnTransmissionOnly) { Y[j] = 1.0 / this->getEventWeight(lambda, scattering); } else { double value = this->getEventWeight(lambda, scattering); - if (m_useScaleFactors) + + if (m_useScaleFactors) { scale_exec(bankName, lambda, depth, inst, pathlength, value); + } Y[j] = Yin[j] * value; E[j] = Ein[j] * value; } @@ -258,12 +263,13 @@ void AnvredCorrection::execEvent() { const int64_t numHists = static_cast<int64_t>(m_inputWS->getNumberHistograms()); - std::string unitStr = m_inputWS->getAxis(0)->unit()->unitID(); + + const std::string unitStr = m_inputWS->getAxis(0)->unit()->unitID(); // Create a new outputworkspace with not much in it - DataObjects::EventWorkspace_sptr correctionFactors; - correctionFactors = boost::dynamic_pointer_cast<EventWorkspace>( + auto correctionFactors = boost::dynamic_pointer_cast<EventWorkspace>( API::WorkspaceFactory::Instance().create("EventWorkspace", numHists, 2, 1)); + correctionFactors->sortAll(TOF_SORT, nullptr); // Copy required stuff from it API::WorkspaceFactory::Instance().initializeFromParent( @@ -286,9 +292,8 @@ void AnvredCorrection::execEvent() { for (int64_t i = 0; i < int64_t(numHists); ++i) { PARALLEL_START_INTERUPT_REGION - // Copy over bin boundaries - const MantidVec &X = eventW->readX(i); - correctionFactors->dataX(i) = X; + // share bin boundaries, and leave Y and E nullptr + correctionFactors->setHistogram(i, eventW->binEdges(i)); // Get detector position IDetector_const_sptr det; @@ -316,11 +321,8 @@ void AnvredCorrection::execEvent() { el.switchTo(WEIGHTED_NOTIME); std::vector<WeightedEventNoTime> events = el.getWeightedEventsNoTime(); - std::vector<WeightedEventNoTime>::iterator itev; - auto itev_end = events.end(); - Mantid::Kernel::Units::Wavelength wl; - std::vector<double> timeflight; + double depth = 0.2; double pathlength = 0.0; std::string bankName; @@ -328,18 +330,25 @@ void AnvredCorrection::execEvent() { scale_init(det, inst, L2, depth, pathlength, bankName); // multiplying an event list by a scalar value - for (itev = events.begin(); itev != itev_end; ++itev) { - timeflight.push_back(itev->tof()); - if (unitStr.compare("TOF") == 0) - wl.fromTOF(timeflight, timeflight, L1, L2, scattering, 0, 0, 0); - double value = this->getEventWeight(timeflight[0], scattering); - if (m_useScaleFactors) - scale_exec(bankName, timeflight[0], depth, inst, pathlength, value); - timeflight.clear(); - itev->m_errorSquared = - static_cast<float>(itev->m_errorSquared * value * value); - itev->m_weight *= static_cast<float>(value); + + for (auto &ev : events) { + // get the event's TOF + double lambda = ev.tof(); + + if ("TOF" == unitStr) { + lambda = wl.convertSingleFromTOF(lambda, L1, L2, scattering, 0, 0, 0); + } + + double value = this->getEventWeight(lambda, scattering); + + if (m_useScaleFactors) { + scale_exec(bankName, lambda, depth, inst, pathlength, value); + } + + ev.m_errorSquared = static_cast<float>(ev.m_errorSquared * value * value); + ev.m_weight *= static_cast<float>(value); } + correctionFactors->getSpectrum(i) += events; auto &dets = eventW->getSpectrum(i).getDetectorIDs(); @@ -374,13 +383,14 @@ void AnvredCorrection::retrieveBaseProperties() { m_radius = getProperty("Radius"); // in cm m_power_th = getProperty("PowerLambda"); // in cm const Material &sampleMaterial = m_inputWS->sample().getMaterial(); - if (sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) != - 0.0) { + + const double scatterXSection = + sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda); + + if (scatterXSection != 0.0) { double rho = sampleMaterial.numberDensity(); if (m_smu == EMPTY_DBL()) - m_smu = - sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) * - rho; + m_smu = scatterXSection * rho; if (m_amu == EMPTY_DBL()) m_amu = sampleMaterial.absorbXSection(NeutronAtom::ReferenceLambda) * rho; } else // Save input in Sample with wrong atomic number and name @@ -419,7 +429,7 @@ double AnvredCorrection::getEventWeight(double lamda, double two_theta) { return transinv; // Resolution of the lambda table - size_t lamda_index = static_cast<size_t>(STEPS_PER_ANGSTROM * lamda); + auto lamda_index = static_cast<size_t>(STEPS_PER_ANGSTROM * lamda); if (lamda_index >= m_lamda_weight.size()) lamda_index = m_lamda_weight.size() - 1; @@ -543,11 +553,12 @@ void AnvredCorrection::BuildLamdaWeights() { m_lamda_weight.push_back(1.); } - for (size_t i = 0; i < m_lamda_weight.size(); i++) { + for (size_t i = 0; i < m_lamda_weight.size(); ++i) { double lamda = static_cast<double>(i) / STEPS_PER_ANGSTROM; m_lamda_weight[i] *= (1 / std::pow(lamda, power)); } } + void AnvredCorrection::scale_init(IDetector_const_sptr det, Instrument_const_sptr inst, double &L2, double &depth, double &pathlength, @@ -555,13 +566,11 @@ void AnvredCorrection::scale_init(IDetector_const_sptr det, bankName = det->getParent()->getParent()->getName(); // Distance to center of detector boost::shared_ptr<const IComponent> det0 = inst->getComponentByName(bankName); - if (inst->getName().compare("CORELLI") == - 0) // for Corelli with sixteenpack under bank + if ("CORELLI" == inst->getName()) // for Corelli with sixteenpack under bank { std::vector<Geometry::IComponent_const_sptr> children; - boost::shared_ptr<const Geometry::ICompAssembly> asmb = - boost::dynamic_pointer_cast<const Geometry::ICompAssembly>( - inst->getComponentByName(bankName)); + auto asmb = boost::dynamic_pointer_cast<const Geometry::ICompAssembly>( + inst->getComponentByName(bankName)); asmb->getChildren(children, false); det0 = children[0]; } @@ -569,6 +578,7 @@ void AnvredCorrection::scale_init(IDetector_const_sptr det, double cosA = det0->getDistance(*sample) / L2; pathlength = depth / cosA; } + void AnvredCorrection::scale_exec(std::string &bankName, double &lambda, double &depth, Instrument_const_sptr inst, double &pathlength, double &value) { diff --git a/Framework/Crystal/src/CentroidPeaks.cpp b/Framework/Crystal/src/CentroidPeaks.cpp index 73ea7b933056ccad9a03baad383bee7d3861d6b5..4f1b59c355f5a739fde98cf74e4a441ea034609d 100644 --- a/Framework/Crystal/src/CentroidPeaks.cpp +++ b/Framework/Crystal/src/CentroidPeaks.cpp @@ -70,7 +70,7 @@ void CentroidPeaks::integrate() { int MaxPeaks = -1; size_t Numberwi = inWS->getNumberHistograms(); int NumberPeaks = peakWS->getNumberPeaks(); - for (int i = 0; i < NumberPeaks; i++) { + for (int i = 0; i < NumberPeaks; ++i) { Peak &peak = peakWS->getPeaks()[i]; int pixelID = peak.getDetectorID(); @@ -88,21 +88,21 @@ void CentroidPeaks::integrate() { int Edge = getProperty("EdgePixels"); Progress prog(this, MinPeaks, 1.0, MaxPeaks); PARALLEL_FOR2(inWS, peakWS) - for (int i = MinPeaks; i <= MaxPeaks; i++) { + for (int i = MinPeaks; i <= MaxPeaks; ++i) { PARALLEL_START_INTERUPT_REGION // Get a direct ref to that peak. - IPeak &peak = peakWS->getPeak(i); + auto &peak = peakWS->getPeak(i); int col = peak.getCol(); int row = peak.getRow(); int pixelID = peak.getDetectorID(); - detid2index_map::const_iterator it = wi_to_detid_map.find(pixelID); + auto it = wi_to_detid_map.find(pixelID); if (it == wi_to_detid_map.end()) { continue; } size_t workspaceIndex = it->second; double TOFPeakd = peak.getTOF(); - const MantidVec &X = inWS->readX(workspaceIndex); - int chan = Kernel::VectorHelper::getBinIndex(X, TOFPeakd); + const auto &X = inWS->x(workspaceIndex); + int chan = Kernel::VectorHelper::getBinIndex(X.rawData(), TOFPeakd); std::string bankName = peak.getBankName(); double intensity = 0.0; @@ -121,13 +121,13 @@ void CentroidPeaks::integrate() { for (int icol = colstart; icol <= colend; ++icol) { if (edgePixel(bankName, icol, irow, Edge)) continue; - detid2index_map::const_iterator it = + const auto it = wi_to_detid_map.find(findPixelID(bankName, icol, irow)); if (it == wi_to_detid_map.end()) continue; size_t workspaceIndex = (it->second); - const MantidVec &histogram = inWS->readY(workspaceIndex); + const auto &histogram = inWS->y(workspaceIndex); intensity += histogram[ichan]; rowcentroid += irow * histogram[ichan]; @@ -152,7 +152,7 @@ void CentroidPeaks::integrate() { workspaceIndex = (it->second); Mantid::Kernel::Units::Wavelength wl; std::vector<double> timeflight; - timeflight.push_back(inWS->readX(workspaceIndex)[chan]); + timeflight.push_back(inWS->x(workspaceIndex)[chan]); double scattering = peak.getScattering(); double L1 = peak.getL1(); double L2 = peak.getL2(); @@ -161,7 +161,7 @@ void CentroidPeaks::integrate() { timeflight.clear(); peak.setWavelength(lambda); - peak.setBinCount(inWS->readY(workspaceIndex)[chan]); + peak.setBinCount(inWS->y(workspaceIndex)[chan]); } PARALLEL_END_INTERUPT_REGION } @@ -169,7 +169,7 @@ void CentroidPeaks::integrate() { for (int i = int(peakWS->getNumberPeaks()) - 1; i >= 0; --i) { // Get a direct ref to that peak. - IPeak &peak = peakWS->getPeak(i); + auto &peak = peakWS->getPeak(i); int col = peak.getCol(); int row = peak.getRow(); std::string bankName = peak.getBankName(); @@ -206,8 +206,9 @@ void CentroidPeaks::integrateEvent() { int MaxPeaks = -1; size_t Numberwi = inWS->getNumberHistograms(); int NumberPeaks = peakWS->getNumberPeaks(); - for (int i = 0; i < NumberPeaks; i++) { - Peak &peak = peakWS->getPeaks()[i]; + + for (int i = 0; i < NumberPeaks; ++i) { + auto &peak = peakWS->getPeak(i); int pixelID = peak.getDetectorID(); // Find the workspace index for this detector ID @@ -224,10 +225,10 @@ void CentroidPeaks::integrateEvent() { int Edge = getProperty("EdgePixels"); Progress prog(this, MinPeaks, 1.0, MaxPeaks); PARALLEL_FOR2(inWS, peakWS) - for (int i = MinPeaks; i <= MaxPeaks; i++) { + for (int i = MinPeaks; i <= MaxPeaks; ++i) { PARALLEL_START_INTERUPT_REGION // Get a direct ref to that peak. - IPeak &peak = peakWS->getPeak(i); + auto &peak = peakWS->getPeak(i); int col = peak.getCol(); int row = peak.getRow(); double TOFPeakd = peak.getTOF(); @@ -237,8 +238,6 @@ void CentroidPeaks::integrateEvent() { double tofcentroid = 0.0; if (edgePixel(bankName, col, row, Edge)) continue; - Mantid::detid2index_map::iterator it; - it = wi_to_detid_map.find(findPixelID(bankName, col, row)); double tofstart = TOFPeakd * std::pow(1.004, -PeakRadius); double tofend = TOFPeakd * std::pow(1.004, PeakRadius); @@ -250,23 +249,19 @@ void CentroidPeaks::integrateEvent() { int colend = col + PeakRadius; for (int irow = rowstart; irow <= rowend; ++irow) { for (int icol = colstart; icol <= colend; ++icol) { - Mantid::detid2index_map::iterator it; if (edgePixel(bankName, icol, irow, Edge)) continue; - it = wi_to_detid_map.find(findPixelID(bankName, icol, irow)); - size_t workspaceIndex = (it->second); + auto it1 = wi_to_detid_map.find(findPixelID(bankName, icol, irow)); + size_t workspaceIndex = (it1->second); EventList el = eventW->getSpectrum(workspaceIndex); el.switchTo(WEIGHTED_NOTIME); std::vector<WeightedEventNoTime> events = el.getWeightedEventsNoTime(); - std::vector<WeightedEventNoTime>::iterator itev; - auto itev_end = events.end(); - // Check for events in tof range - for (itev = events.begin(); itev != itev_end; ++itev) { - double tof = itev->tof(); + for (const auto &event : events) { + double tof = event.tof(); if (tof > tofstart && tof < tofend) { - double weight = itev->weight(); + double weight = event.weight(); intensity += weight; rowcentroid += irow * weight; colcentroid += icol * weight; @@ -304,7 +299,7 @@ void CentroidPeaks::integrateEvent() { for (int i = int(peakWS->getNumberPeaks()) - 1; i >= 0; --i) { // Get a direct ref to that peak. - IPeak &peak = peakWS->getPeak(i); + auto &peak = peakWS->getPeak(i); int col = peak.getCol(); int row = peak.getRow(); std::string bankName = peak.getBankName(); @@ -334,6 +329,7 @@ void CentroidPeaks::exec() { this->integrate(); } } + int CentroidPeaks::findPixelID(std::string bankName, int col, int row) { Geometry::Instrument_const_sptr Iptr = inWS->getInstrument(); boost::shared_ptr<const IComponent> parent = diff --git a/Framework/Crystal/src/FindSXPeaks.cpp b/Framework/Crystal/src/FindSXPeaks.cpp index 92eea9600fc9843f5a1418393cb52aff3bcd0d63..e5c0d6ecec38f8d7dfe27ad506b413656d306e10 100644 --- a/Framework/Crystal/src/FindSXPeaks.cpp +++ b/Framework/Crystal/src/FindSXPeaks.cpp @@ -61,10 +61,9 @@ void FindSXPeaks::exec() { m_MinRange = getProperty("RangeLower"); m_MaxRange = getProperty("RangeUpper"); - int minSpec = getProperty("StartWorkspaceIndex"); - int maxSpec = getProperty("EndWorkspaceIndex"); - m_MinSpec = minSpec; - m_MaxSpec = maxSpec; + // the assignment below is intended and if removed will break the unit tests + m_MinSpec = static_cast<int>(getProperty("StartWorkspaceIndex")); + m_MaxSpec = static_cast<int>(getProperty("EndWorkspaceIndex")); double SB = getProperty("SignalBackground"); // Get the input workspace @@ -115,22 +114,19 @@ void FindSXPeaks::exec() { ++i) { PARALLEL_START_INTERUPT_REGION // Retrieve the spectrum into a vector - const MantidVec &X = localworkspace->readX(i); - const MantidVec &Y = localworkspace->readY(i); + const auto &X = localworkspace->x(i); + const auto &Y = localworkspace->y(i); // Find the range [min,max] - MantidVec::const_iterator lowit, highit; + auto lowit = (m_MinRange == EMPTY_DBL()) + ? X.begin() + : std::lower_bound(X.begin(), X.end(), m_MinRange); - if (m_MinRange == EMPTY_DBL()) - lowit = X.begin(); - else - lowit = std::lower_bound(X.begin(), X.end(), m_MinRange); - - if (m_MaxRange == EMPTY_DBL()) - highit = X.end(); - else - highit = std::find_if(lowit, X.end(), - std::bind2nd(std::greater<double>(), m_MaxRange)); + auto highit = + (m_MaxRange == EMPTY_DBL()) + ? X.end() + : std::find_if(lowit, X.end(), + std::bind2nd(std::greater<double>(), m_MaxRange)); // If range specified doesn't overlap with this spectrum then bail out if (lowit == X.end() || highit == X.begin()) @@ -139,23 +135,21 @@ void FindSXPeaks::exec() { --highit; // Upper limit is the bin before, i.e. the last value smaller than // MaxRange - MantidVec::difference_type distmin = std::distance(X.begin(), lowit); - MantidVec::difference_type distmax = std::distance(X.begin(), highit); + auto distmin = std::distance(X.begin(), lowit); + auto distmax = std::distance(X.begin(), highit); // Find the max element - MantidVec::const_iterator maxY; - if (Y.size() > 1) { - maxY = std::max_element(Y.begin() + distmin, Y.begin() + distmax); - } else { - maxY = Y.begin(); - } + auto maxY = (Y.size() > 1) + ? std::max_element(Y.begin() + distmin, Y.begin() + distmax) + : Y.begin(); + double intensity = (*maxY); double background = 0.5 * (1.0 + Y.front() + Y.back()); if (intensity < SB * background) // This is not a peak. continue; // t.o.f. of the peak - MantidVec::difference_type d = std::distance(Y.begin(), maxY); + auto d = std::distance(Y.begin(), maxY); auto leftBinPosition = X.begin() + d; double leftBinEdge = *leftBinPosition; double rightBinEdge = *std::next(leftBinPosition); diff --git a/Framework/Crystal/src/IntegratePeakTimeSlices.cpp b/Framework/Crystal/src/IntegratePeakTimeSlices.cpp index b9f67285fa603209d1ba29f1471b56ab6dd46f4a..1d7cce4ce184541e7a065da84438e09ee966f61d 100644 --- a/Framework/Crystal/src/IntegratePeakTimeSlices.cpp +++ b/Framework/Crystal/src/IntegratePeakTimeSlices.cpp @@ -17,12 +17,15 @@ #include "MantidAPI/WorkspaceFactory.h" #include "MantidDataObjects/Workspace2D.h" +#include "MantidHistogramData/BinEdges.h" + #include <boost/math/special_functions/round.hpp> using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::DataObjects; using namespace Mantid::Geometry; +using namespace Mantid::HistogramData; using namespace std; namespace Mantid { namespace Crystal { @@ -277,7 +280,7 @@ void IntegratePeakTimeSlices::exec() { R = 2 * R; // Gets a few more background cells. int Chan; - const MantidVec &X = inpWkSpace->dataX(wsIndx); + const auto &X = inpWkSpace->x(wsIndx); int dChan = CalculateTimeChannelSpan(peak, dQ, X, int(wsIndx), Chan); dChan = max<int>(dChan, MinTimeSpan); @@ -588,7 +591,7 @@ void IntegratePeakTimeSlices::exec() { if (!done) { // Now set up the center for this peak - int i = find("Mrow", names); + int i = findNameInVector("Mrow", names); if (i < 0) { throw std::runtime_error("Inconsistency found in algorithm " "execution. The index for the parameter " @@ -596,7 +599,7 @@ void IntegratePeakTimeSlices::exec() { } lastRow = static_cast<int>(params[i] + .5); - i = find("Mcol", names); + i = findNameInVector("Mcol", names); if (i >= 0) lastCol = static_cast<int>(params[i] + .5); prog.report(); @@ -811,18 +814,18 @@ IntegratePeakTimeSlices::CalculatePositionSpan(Geometry::IPeak const &peak, * @return The number of time channels around Centerchan to use */ int IntegratePeakTimeSlices::CalculateTimeChannelSpan( - Geometry::IPeak const &peak, const double dQ, Mantid::MantidVec const &X, + Geometry::IPeak const &peak, const double dQ, const HistogramX &X, const int specNum, int &Centerchan) { UNUSED_ARG(specNum); double Q = peak.getQLabFrame().norm(); // getQ( peak)/2/M_PI; double time = peak.getTOF(); double dtime = dQ / Q * time; - int chanCenter = find(X, time); + int chanCenter = findTimeChannel(X, time); Centerchan = chanCenter; - int chanLeft = find(X, time - dtime); - int chanRight = find(X, time + dtime); + int chanLeft = findTimeChannel(X, time - dtime); + int chanRight = findTimeChannel(X, time + dtime); int dchan = abs(chanCenter - chanLeft); if (abs(chanRight - chanCenter) > dchan) @@ -1229,9 +1232,9 @@ double DataModeHandler::getNewRCRadius() { * @param yvals The y(row) values of the data to be considered * @param counts The intensity at the given row and column (and timeslice) */ -void DataModeHandler::setHeightHalfWidthInfo(const MantidVec &xvals, - const MantidVec &yvals, - const MantidVec &counts) { +void DataModeHandler::setHeightHalfWidthInfo( + const std::vector<double> &xvals, const std::vector<double> &yvals, + const std::vector<double> &counts) { double minCount, maxCount; const auto &X = xvals; const auto &Y = yvals; @@ -1566,10 +1569,10 @@ void IntegratePeakTimeSlices::SetUpData1( for (int i = 0; i < NAttributes + 2; i++) StatBase.push_back(0); - Mantid::MantidVec yvalB; - Mantid::MantidVec errB; - Mantid::MantidVec xvalB; - Mantid::MantidVec YvalB; + std::vector<double> yvalB; + std::vector<double> errB; + std::vector<double> xvalB; + std::vector<double> YvalB; double TotBoundaryIntensities = 0; int nBoundaryCells = 0; @@ -1582,7 +1585,7 @@ void IntegratePeakTimeSlices::SetUpData1( int jj = 0; - Mantid::MantidVec xRef; + std::vector<double> xRef; for (int i = 2; i < m_NeighborIDs[1]; i++) { int DetID = m_NeighborIDs[i]; @@ -1620,9 +1623,9 @@ void IntegratePeakTimeSlices::SetUpData1( if (row > NBadEdges && col > NBadEdges && (m_NROWS < 0 || row < m_NROWS - NBadEdges) && (m_NCOLS < 0 || col < m_NCOLS - NBadEdges)) { - Mantid::MantidVec histogram = inpWkSpace->readY(workspaceIndex); + auto &histogram = inpWkSpace->y(workspaceIndex); - Mantid::MantidVec histoerrs = inpWkSpace->readE(workspaceIndex); + auto &histoerrs = inpWkSpace->e(workspaceIndex); double intensity = 0; double variance = 0; for (int chan = chanMin; chan <= chanMax; chan++) { @@ -1711,8 +1714,8 @@ void IntegratePeakTimeSlices::SetUpData1( * @param time The desired time * @return the time channel */ -int IntegratePeakTimeSlices::find(Mantid::MantidVec const &X, - const double time) { +int IntegratePeakTimeSlices::findTimeChannel(const HistogramX &X, + const double time) { int sgn = 1; if (X[0] > X[1]) @@ -1797,8 +1800,8 @@ std::string IntegratePeakTimeSlices::CalculateFunctionProperty_Fit() { * * @return the position in the vector of oneName or -1. */ -int IntegratePeakTimeSlices::find(std::string const &oneName, - std::vector<std::string> const &nameList) +int IntegratePeakTimeSlices::findNameInVector( + std::string const &oneName, std::vector<std::string> const &nameList) { for (size_t i = 0; i < nameList.size(); i++) @@ -2196,7 +2199,7 @@ void IntegratePeakTimeSlices::PreFit(MatrixWorkspace_sptr &Data, } vector<std::string> ParNames(m_ParameterNames, m_ParameterNames + NParams); for (int i = 0; i < NParams; i++) { - int k = find(Bestnames[i], ParNames); + int k = findNameInVector(Bestnames[i], ParNames); if (k >= 0 && k < NParams) m_ParameterValues[k] = Bestparams[k]; } @@ -2219,13 +2222,13 @@ bool IntegratePeakTimeSlices::isGoodFit(std::vector<double> const ¶ms, std::vector<double> const &errs, std::vector<std::string> const &names, double chisqOverDOF) { - int Ibk = find("Background", names); + int Ibk = findNameInVector("Background", names); if (Ibk < 0) throw std::runtime_error( "Irrecoverable inconsistency found. The index for the " "parameter 'Background' is lower than zero."); - int IIntensity = find("Intensity", names); + int IIntensity = findNameInVector("Intensity", names); if (IIntensity < 0) throw std::runtime_error( "Irrecoverable inconsistency found. The index for the " @@ -2497,13 +2500,13 @@ int IntegratePeakTimeSlices::UpdateOutputWS( std::vector<double> const ¶ms, std::vector<double> const &errs, std::vector<std::string> const &names, const double Chisq, const double time, string spec_idList) { - int Ibk = find("Background", names); - int IIntensity = find("Intensity", names); - int IVx = find("SScol", names); - int IVy = find("SSrow", names); - int IVxy = find("SSrc", names); - int Irow = find("Mrow", names); - int Icol = find("Mcol", names); + int Ibk = findNameInVector("Background", names); + int IIntensity = findNameInVector("Intensity", names); + int IVx = findNameInVector("SScol", names); + int IVy = findNameInVector("SSrow", names); + int IVxy = findNameInVector("SSrc", names); + int Irow = findNameInVector("Mrow", names); + int Icol = findNameInVector("Mcol", names); if (Ibk < 0 || IIntensity < 0 || IVx < 0 || IVy < 0 || IVxy < 0 || Irow < 0 || Icol < 0) { diff --git a/Framework/Crystal/src/MaskPeaksWorkspace.cpp b/Framework/Crystal/src/MaskPeaksWorkspace.cpp index 3ba6cbe3eae5e0aec19f4e4bc5a6892989812b80..378be6b7113f2edc1b53afc1d796baaf688afb2d 100644 --- a/Framework/Crystal/src/MaskPeaksWorkspace.cpp +++ b/Framework/Crystal/src/MaskPeaksWorkspace.cpp @@ -89,7 +89,7 @@ void MaskPeaksWorkspace::exec() { // Loop over peaks const std::vector<Peak> &peaks = peaksW->getPeaks(); - PARALLEL_FOR3(m_inputW, peaksW, tablews) + PARALLEL_FOR_IF(Kernel::threadSafe(*m_inputW, *peaksW, *tablews)) for (int i = 0; i < static_cast<int>(peaks.size()); i++) { // NOLINT PARALLEL_START_INTERUPT_REGION const Peak &peak = peaks[i]; diff --git a/Framework/Crystal/src/PeakIntegration.cpp b/Framework/Crystal/src/PeakIntegration.cpp index 218265137bb6def382e09a7249481ec1e2253857..c1524ad285c6567e5695450e65bda98c8f757349 100644 --- a/Framework/Crystal/src/PeakIntegration.cpp +++ b/Framework/Crystal/src/PeakIntegration.cpp @@ -124,7 +124,7 @@ void PeakIntegration::exec() { } Progress prog(this, MinPeaks, 1.0, NumberPeaks); - PARALLEL_FOR3(inputW, peaksW, outputW) + PARALLEL_FOR_IF(Kernel::threadSafe(*inputW, *peaksW, *outputW)) for (int i = MinPeaks; i < NumberPeaks; i++) { PARALLEL_START_INTERUPT_REGION diff --git a/Framework/Crystal/src/SCDCalibratePanels.cpp b/Framework/Crystal/src/SCDCalibratePanels.cpp index dbfefc0d28ed1e3c0865c15330c93d5a699d7841..dd4f20a3a277ee2c58a1d9a2178d013ca2bd80ad 100644 --- a/Framework/Crystal/src/SCDCalibratePanels.cpp +++ b/Framework/Crystal/src/SCDCalibratePanels.cpp @@ -371,7 +371,7 @@ void SCDCalibratePanels::exec() { DblMatrix UB = lattice.getUB(); // sort again since edge peaks can trace to other banks peaksWs->sort(criteria); - PARALLEL_FOR3(ColWksp, RowWksp, TofWksp) + PARALLEL_FOR_IF(Kernel::threadSafe(*ColWksp, *RowWksp, *TofWksp)) for (int i = 0; i < static_cast<int>(MyBankNames.size()); ++i) { PARALLEL_START_INTERUPT_REGION const std::string &bankName = *std::next(MyBankNames.begin(), i); diff --git a/Framework/Crystal/test/AnvredCorrectionTest.h b/Framework/Crystal/test/AnvredCorrectionTest.h index 6af67a762fda57cb7080668c821028cd870043b8..9cfe9fe7607267ea0a27924ebafa56ad3a7ecabd 100644 --- a/Framework/Crystal/test/AnvredCorrectionTest.h +++ b/Framework/Crystal/test/AnvredCorrectionTest.h @@ -28,72 +28,67 @@ using namespace Mantid::DataObjects; using namespace Mantid::DataHandling; using namespace Mantid::Geometry; -class AnvredCorrectionTest : public CxxTest::TestSuite { -public: - /** Create an EventWorkspace containing fake data - * of single-crystal diffraction. - * - * @return EventWorkspace_sptr - */ - EventWorkspace_sptr createDiffractionEventWorkspace() { - // setup the test workspace - EventWorkspace_sptr retVal = - WorkspaceCreationHelper::createEventWorkspaceWithFullInstrument(1, 1, - false); - - MoveInstrumentComponent mover; - mover.initialize(); - mover.setProperty("Workspace", retVal); - mover.setPropertyValue("ComponentName", "bank1(x=0)"); - mover.setPropertyValue("X", "0.5"); - mover.setPropertyValue("Y", "0."); - mover.setPropertyValue("Z", "-5"); - mover.setPropertyValue("RelativePosition", "1"); - mover.execute(); - double angle = -90.0; - Mantid::Kernel::V3D axis(0., 1., 0.); - RotateInstrumentComponent alg; - alg.initialize(); - alg.setChild(true); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("Workspace", retVal)); - TS_ASSERT_THROWS_NOTHING( - alg.setPropertyValue("ComponentName", "bank1(x=0)")); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("X", axis.X())); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("Y", axis.Y())); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("Z", axis.Z())); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("Angle", angle)); - TS_ASSERT_THROWS_NOTHING(alg.setProperty("RelativeRotation", false)); - TS_ASSERT_THROWS_NOTHING(alg.execute();); - TS_ASSERT(alg.isExecuted()); - - return retVal; - } +// Anonymous namespace to share methods between Unit and performance test +namespace { +/** Create an EventWorkspace containing fake data + * of single-crystal diffraction. + * + * @return EventWorkspace_sptr + */ +EventWorkspace_sptr createDiffractionEventWorkspace(int numBanks = 1, + int numPixels = 1) { + // setup the test workspace + EventWorkspace_sptr retVal = + WorkspaceCreationHelper::createEventWorkspaceWithFullInstrument( + numBanks, numPixels, false); - void test_Init() { - AnvredCorrection alg; - TS_ASSERT_THROWS_NOTHING(alg.initialize()) - TS_ASSERT(alg.isInitialized()) - } + MoveInstrumentComponent mover; + mover.initialize(); + mover.setProperty("Workspace", retVal); + mover.setPropertyValue("ComponentName", "bank1(x=0)"); + mover.setPropertyValue("X", "0.5"); + mover.setPropertyValue("Y", "0."); + mover.setPropertyValue("Z", "-5"); + mover.setPropertyValue("RelativePosition", "1"); + mover.execute(); + double angle = -90.0; + Mantid::Kernel::V3D axis(0., 1., 0.); + RotateInstrumentComponent alg; + alg.initialize(); + alg.setChild(true); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("Workspace", retVal)); + TS_ASSERT_THROWS_NOTHING(alg.setPropertyValue("ComponentName", "bank1(x=0)")); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("X", axis.X())); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("Y", axis.Y())); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("Z", axis.Z())); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("Angle", angle)); + TS_ASSERT_THROWS_NOTHING(alg.setProperty("RelativeRotation", false)); + TS_ASSERT_THROWS_NOTHING(alg.execute();); + TS_ASSERT(alg.isExecuted()); - void do_test_events(bool ev) { + return retVal; +} - MatrixWorkspace_sptr inputW = createDiffractionEventWorkspace(); - inputW->getAxis(0)->setUnit("Wavelength"); +void do_test_events(MatrixWorkspace_sptr workspace, bool ev, + bool performance = false) { - AnvredCorrection alg; - TS_ASSERT_THROWS_NOTHING(alg.initialize()) - TS_ASSERT(alg.isInitialized()) - alg.setProperty("InputWorkspace", inputW); - alg.setProperty("OutputWorkspace", "TOPAZ"); - alg.setProperty("PreserveEvents", ev); - alg.setProperty("OnlySphericalAbsorption", false); - alg.setProperty("LinearScatteringCoef", 0.369); - alg.setProperty("LinearAbsorptionCoef", 0.011); - alg.setProperty("Radius", 0.05); - alg.setProperty("PowerLambda", 3.0); - TS_ASSERT_THROWS_NOTHING(alg.execute();) - TS_ASSERT(alg.isExecuted()) + workspace->getAxis(0)->setUnit("Wavelength"); + AnvredCorrection alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()) + TS_ASSERT(alg.isInitialized()) + alg.setProperty("InputWorkspace", workspace); + alg.setProperty("OutputWorkspace", "TOPAZ"); + alg.setProperty("PreserveEvents", ev); + alg.setProperty("OnlySphericalAbsorption", false); + alg.setProperty("LinearScatteringCoef", 0.369); + alg.setProperty("LinearAbsorptionCoef", 0.011); + alg.setProperty("Radius", 0.05); + alg.setProperty("PowerLambda", 3.0); + TS_ASSERT_THROWS_NOTHING(alg.execute();) + TS_ASSERT(alg.isExecuted()) + + if (!performance) { MatrixWorkspace_sptr ws; TS_ASSERT_THROWS_NOTHING( ws = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( @@ -102,18 +97,63 @@ public: if (!ws) return; // do the final comparison - const MantidVec &y_actual = ws->readY(0); + const auto &y_actual = ws->y(0); TS_ASSERT_DELTA(y_actual[0], 8.2052, 0.0001); TS_ASSERT_DELTA(y_actual[1], 0.3040, 0.0001); TS_ASSERT_DELTA(y_actual[2], 0.0656, 0.0001); + } +} +} + +class AnvredCorrectionTest : public CxxTest::TestSuite { +public: + static AnvredCorrectionTest *createSuite() { + return new AnvredCorrectionTest(); + } + static void destroySuite(AnvredCorrectionTest *suite) { delete suite; } - AnalysisDataService::Instance().remove("TOPAZ"); + void test_Init() { + AnvredCorrection alg; + TS_ASSERT_THROWS_NOTHING(alg.initialize()) + TS_ASSERT(alg.isInitialized()) + } + + void setUp() override { workspace = createDiffractionEventWorkspace(); } + + void tearDown() override { AnalysisDataService::Instance().remove("TOPAZ"); } + + void test_Events() { do_test_events(workspace, true); } + + void test_NoEvents() { do_test_events(workspace, false); } + +private: + EventWorkspace_sptr workspace; +}; + +class AnvredCorrectionTestPerformance : public CxxTest::TestSuite { +public: + static AnvredCorrectionTestPerformance *createSuite() { + return new AnvredCorrectionTestPerformance(); + } + static void destroySuite(AnvredCorrectionTestPerformance *suite) { + delete suite; } - void test_events() { - do_test_events(true); - do_test_events(false); + // executed before each test + void setUp() override { workspace = createDiffractionEventWorkspace(100, 5); } + + // executed after each test + void tearDown() override { AnalysisDataService::Instance().remove("TOPAZ"); } + + void testEventsPerformance() { do_test_events(workspace, true, performance); } + + void testNoEventsPerformace() { + do_test_events(workspace, false, performance); } + +private: + const bool performance = true; + EventWorkspace_sptr workspace; }; #endif /* MANTID_CRYSTAL_AnvredCorrectionTEST_H_ */ diff --git a/Framework/Crystal/test/CentroidPeaksTest.h b/Framework/Crystal/test/CentroidPeaksTest.h index d61fb52fbde0c7cc5e8b1a861979c38650f89de3..466b01f5ae35ddf1524440b74f38a35fc8bc03df 100644 --- a/Framework/Crystal/test/CentroidPeaksTest.h +++ b/Framework/Crystal/test/CentroidPeaksTest.h @@ -86,7 +86,7 @@ public: DateAndTime run_start("2010-01-01T00:00:00"); - for (int pix = 0; pix < numPixels; pix++) { + for (int pix = 0; pix < numPixels; ++pix) { auto &el = retVal->getSpectrum(pix); el.setSpectrumNo(pix); el.setDetectorID(pix); diff --git a/Framework/Crystal/test/FindSXPeaksTest.h b/Framework/Crystal/test/FindSXPeaksTest.h index af0020930b947e47562933420d549b65705c2928..85695499becb648bd1c61a592a71333e567b8b22 100644 --- a/Framework/Crystal/test/FindSXPeaksTest.h +++ b/Framework/Crystal/test/FindSXPeaksTest.h @@ -12,24 +12,22 @@ using namespace Mantid::DataObjects; // Helper method to overwrite spectra. void overWriteSpectraY(size_t histo, Workspace2D_sptr workspace, - const Mantid::MantidVec &Yvalues) { - Mantid::MantidVec &Y = workspace->dataY(histo); - for (size_t i = 0; i < Y.size(); i++) { - Y[i] = Yvalues[i]; - } + const std::vector<double> &Yvalues) { + + workspace->dataY(histo) = Yvalues; } // Helper method to make what will be recognised as a single peak. void makeOnePeak(size_t histo, double peak_intensity, size_t at_bin, Workspace2D_sptr workspace) { - size_t nBins = workspace->readY(0).size(); - Mantid::MantidVec peaksInY(nBins); + size_t nBins = workspace->y(0).size(); + std::vector<double> peaksInY(nBins); for (size_t i = 0; i < nBins; i++) { if (i == at_bin) { peaksInY[i] = peak_intensity; // overwrite with special value } else { - peaksInY[i] = workspace->readY(histo)[i]; + peaksInY[i] = workspace->y(histo)[i]; } } overWriteSpectraY(histo, workspace, peaksInY); diff --git a/Framework/Crystal/test/IntegratePeakTimeSlicesTest.h b/Framework/Crystal/test/IntegratePeakTimeSlicesTest.h index 558918f190aa71cc1dce3d115c8fe10260acbfe5..7dd89cc118d56d34ed003290285d1a97d29068cf 100644 --- a/Framework/Crystal/test/IntegratePeakTimeSlicesTest.h +++ b/Framework/Crystal/test/IntegratePeakTimeSlicesTest.h @@ -140,8 +140,8 @@ public: 0.0, MaxPeakIntensity * (1 - abs(row - PeakRow) / MaxPeakRCSpan)); double MaxRC = max<double>(0.0, MaxR * (1 - abs(col - PeakCol) / MaxPeakRCSpan)); - MantidVec dataY; - MantidVec dataE; + std::vector<double> dataY; + std::vector<double> dataE; for (int chan = 0; chan < NTimes; chan++) { double val = max<double>( @@ -158,8 +158,8 @@ public: } } - wsPtr->dataY(wsIndex) = dataY; - wsPtr->dataE(wsIndex) = dataE; + wsPtr->mutableY(wsIndex) = dataY; + wsPtr->mutableE(wsIndex) = dataE; } PeaksWorkspace_sptr pks(new PeaksWorkspace()); diff --git a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonProfile.h b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonProfile.h index 194e5e35c96db034cabd6c426e7e9223a51305f9..98afb9abda7ec8edee2f5f5307d5357f88d014ea 100644 --- a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonProfile.h +++ b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonProfile.h @@ -6,6 +6,7 @@ #include "MantidAPI/IPeakFunction.h" #include "MantidAPI/MatrixWorkspace_fwd.h" #include "MantidAPI/ParamFunction.h" +#include "MantidHistogramData/Histogram.h" namespace Mantid { namespace CurveFitting { @@ -65,14 +66,12 @@ public: void buildCaches(); /// Pre-calculate the Y-space values with specified resolution parameters - void cacheYSpaceValues(const std::vector<double> &tseconds, - const bool isHistogram, + void cacheYSpaceValues(const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar, const ResolutionParams &respar); /// Pre-calculate the Y-space values - virtual void cacheYSpaceValues(const std::vector<double> &tseconds, - const bool isHistogram, + virtual void cacheYSpaceValues(const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar); /// Turn off logger void disableLogging() { m_log.setEnabled(false); } @@ -87,7 +86,7 @@ public: /// of the mass profile virtual size_t fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const = 0; + const HistogramData::HistogramE &errors) const = 0; void setParameter(size_t i, const double &value, bool explicitlySet = true) override; diff --git a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonScatteringCountRate.h b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonScatteringCountRate.h index b89f9134a7daedac62902343abcc59acb9c546a0..a489312147c76533af0d2b4dca0fa30b7ec9203c 100644 --- a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonScatteringCountRate.h +++ b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/ComptonScatteringCountRate.h @@ -68,9 +68,9 @@ private: void cacheBackground(const API::IFunction1D_sptr &function1D, const size_t paramsOffset); /// Set up the constraint matrices - void createConstraintMatrices(const std::vector<double> &xValues); + void createConstraintMatrices(); /// Set up positivity constraint matrix - void createPositivityCM(const std::vector<double> &xValues); + void createPositivityCM(); /// Set up equality constraint matrix void createEqualityCM(const size_t nmasses); @@ -86,8 +86,10 @@ private: std::string m_bkgdOrderAttr; /// The order of the background int m_bkgdPolyN; - /// Errors on the data - std::vector<double> m_errors; + /// The histogram of the matrix workspace being cached for use + boost::shared_ptr<HistogramData::Histogram> m_hist; + /// The workspace index being worked on + size_t wsIndex; /// Ratio of data & errors std::vector<double> m_dataErrorRatio; }; diff --git a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GaussianComptonProfile.h b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GaussianComptonProfile.h index 575e568f4ca1ce4adb30648fc8d097fe03e5acae..b8b3f6e3b956cf5988c7fa0e6900159fdf32b03d 100644 --- a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GaussianComptonProfile.h +++ b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GaussianComptonProfile.h @@ -54,8 +54,9 @@ private: /// Returns the indices of the intensity parameters std::vector<size_t> intensityParameterIndices() const override; /// Fill in the columns of the matrix for this mass - size_t fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const override; + size_t + fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, + const HistogramData::HistogramE &errors) const override; /// Compute the function void massProfile(double *result, const size_t nData) const override; diff --git a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GramCharlierComptonProfile.h b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GramCharlierComptonProfile.h index 895f0051a8479d63442bfd3b765ff890da8e46f1..70914b62a0a1241dd81d17f37d1992a41af966fe 100644 --- a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GramCharlierComptonProfile.h +++ b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/GramCharlierComptonProfile.h @@ -57,8 +57,9 @@ private: /// Returns the indices of the intensity parameters std::vector<size_t> intensityParameterIndices() const override; /// Fill in the columns of the matrix for this mass - size_t fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const override; + size_t + fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, + const HistogramData::HistogramE &errors) const override; /// Compute the sum for all Hermite polynomial coefficents void massProfile(double *result, const size_t nData) const override; /// Compute the contribution to mass profile nth Hermite polynomial @@ -75,8 +76,7 @@ private: setMatrixWorkspace(boost::shared_ptr<const API::MatrixWorkspace> workspace, size_t wi, double startX, double endX) override; /// Pre-calculate the Y-space values - void cacheYSpaceValues(const std::vector<double> &tseconds, - const bool isHistogram, + void cacheYSpaceValues(const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar) override; /// The active hermite coefficents diff --git a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/MultivariateGaussianComptonProfile.h b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/MultivariateGaussianComptonProfile.h index 4972440e1eeb32d57d0300494e05922a4962cf3a..c118fbe475a53282bf0625b4b1e87039eeb1811e 100644 --- a/Framework/CurveFitting/inc/MantidCurveFitting/Functions/MultivariateGaussianComptonProfile.h +++ b/Framework/CurveFitting/inc/MantidCurveFitting/Functions/MultivariateGaussianComptonProfile.h @@ -59,8 +59,9 @@ private: /// Returns the indices of the intensity parameters std::vector<size_t> intensityParameterIndices() const override; /// Fill in the columns of the matrix for this mass - size_t fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const override; + size_t + fillConstraintMatrix(Kernel::DblMatrix &cmatrix, const size_t start, + const HistogramData::HistogramE &errors) const override; /// Compute the function void massProfile(double *result, const size_t nData) const override; diff --git a/Framework/CurveFitting/src/Algorithms/ConvolveWorkspaces.cpp b/Framework/CurveFitting/src/Algorithms/ConvolveWorkspaces.cpp index bceffdf53e839c586f11f7086b84124da8fc63e7..cdf6947d8a7cdf8e71abb73bfe6b06ee45527ad5 100644 --- a/Framework/CurveFitting/src/Algorithms/ConvolveWorkspaces.cpp +++ b/Framework/CurveFitting/src/Algorithms/ConvolveWorkspaces.cpp @@ -62,7 +62,7 @@ void ConvolveWorkspaces::exec() { prog = new Progress(this, 0.0, 1.0, numHists); // Now convolve the histograms - PARALLEL_FOR3(ws1, ws2, outputWS) + PARALLEL_FOR_IF(Kernel::threadSafe(*ws1, *ws2, *outputWS)) for (int l = 0; l < static_cast<int>(numHists); ++l) { PARALLEL_START_INTERUPT_REGION prog->report(); diff --git a/Framework/CurveFitting/src/Algorithms/VesuvioCalculateGammaBackground.cpp b/Framework/CurveFitting/src/Algorithms/VesuvioCalculateGammaBackground.cpp index cb3db378fc77bdb1c629190cf6c15ff2ffbed78e..3749bf274f9c92e7958dcb9b987328197305a5dc 100644 --- a/Framework/CurveFitting/src/Algorithms/VesuvioCalculateGammaBackground.cpp +++ b/Framework/CurveFitting/src/Algorithms/VesuvioCalculateGammaBackground.cpp @@ -115,7 +115,8 @@ void VesuvioCalculateGammaBackground::exec() { 10 + nhist * (m_npeaks + 2 * m_foils0.size() * NTHETA * NUP * m_npeaks); m_progress = new Progress(this, 0.0, 1.0, nreports); - PARALLEL_FOR3(m_inputWS, m_correctedWS, m_backgroundWS) + PARALLEL_FOR_IF( + Kernel::threadSafe(*m_inputWS, *m_correctedWS, *m_backgroundWS)) for (int64_t i = 0; i < nhist; ++i) { PARALLEL_START_INTERUPT_REGION const size_t outputIndex = i; @@ -409,7 +410,7 @@ std::vector<double> VesuvioCalculateGammaBackground::calculateTofSpectrum( // Fix the Mass parameter profile->fix(0); - profile->cacheYSpaceValues(tseconds.rawData(), false, detpar, respar); + profile->cacheYSpaceValues(m_backgroundWS->points(wsIndex), detpar, respar); profile->massProfile(tmpWork.data(), tmpWork.size()); // Add to final result diff --git a/Framework/CurveFitting/src/Functions/ComptonProfile.cpp b/Framework/CurveFitting/src/Functions/ComptonProfile.cpp index 1f3408ab70a7473b43af182fcc025708ea6cf326..2a8084830404fa39522775078d53e1ae4d0315ff 100644 --- a/Framework/CurveFitting/src/Functions/ComptonProfile.cpp +++ b/Framework/CurveFitting/src/Functions/ComptonProfile.cpp @@ -107,27 +107,25 @@ void ComptonProfile::buildCaches() { Algorithms::DetectorParams detpar = ConvertToYSpace::getDetectorParameters(m_workspace, m_wsIndex); - this->cacheYSpaceValues(m_workspace->readX(m_wsIndex), - m_workspace->isHistogramData(), detpar); + this->cacheYSpaceValues(m_workspace->points(m_wsIndex), detpar); } -void ComptonProfile::cacheYSpaceValues(const std::vector<double> &tseconds, - const bool isHistogram, +void ComptonProfile::cacheYSpaceValues(const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar, const ResolutionParams &respar) { m_resolutionFunction->setAttributeValue("Mass", m_mass); m_resolutionFunction->cacheResolutionComponents(detpar, respar); - this->cacheYSpaceValues(tseconds, isHistogram, detpar); + this->cacheYSpaceValues(tseconds, detpar); } /** * @param tseconds A vector containing the time-of-flight values in seconds - * @param isHistogram True if histogram tof values have been passed in * @param detpar Structure containing detector parameters */ void ComptonProfile::cacheYSpaceValues( - const std::vector<double> &tseconds, const bool isHistogram, + const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar) { + // ------ Fixed coefficients related to resolution & Y-space transforms // ------------------ const double mevToK = PhysicalConstants::E_mev_toNeutronWavenumberSq; @@ -138,14 +136,13 @@ void ComptonProfile::cacheYSpaceValues( const double k1 = std::sqrt(detpar.efixed / mevToK); // Calculate energy dependent factors and transform q to Y-space - const size_t nData = (isHistogram) ? tseconds.size() - 1 : tseconds.size(); + const size_t nData = tseconds.size(); m_e0.resize(nData); m_modQ.resize(nData); m_yspace.resize(nData); for (size_t i = 0; i < nData; ++i) { - const double tsec = - (isHistogram) ? 0.5 * (tseconds[i] + tseconds[i + 1]) : tseconds[i]; + const double tsec = tseconds[i]; ConvertToYSpace::calculateY(m_yspace[i], m_modQ[i], m_e0[i], m_mass, tsec, k1, v1, detpar); } diff --git a/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp b/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp index e42ae776c6b9b51d4ab82628a586013b6075dedc..665f81cffca2e0b9dc4ff1522bd8756815856911 100644 --- a/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp +++ b/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp @@ -31,8 +31,7 @@ DECLARE_FUNCTION(ComptonScatteringCountRate) */ ComptonScatteringCountRate::ComptonScatteringCountRate() : CompositeFunction(), m_profiles(), m_fixedParamIndices(), m_cmatrix(), - m_eqMatrix(), m_bkgdOrderAttr("n"), m_bkgdPolyN(0), m_errors(), - m_dataErrorRatio() { + m_eqMatrix(), m_bkgdOrderAttr("n"), m_bkgdPolyN(0), m_dataErrorRatio() { // Must be a string to be able to be passed through Fit declareAttribute(CONSTRAINT_MATRIX_NAME, IFunction::Attribute("", true)); declareAttribute(BKGD_ORDER_ATTR_NAME, IFunction::Attribute(m_bkgdOrderAttr)); @@ -208,7 +207,7 @@ void ComptonScatteringCountRate::updateCMatrixValues() const { for (size_t i = 0, start = 0; i < nprofiles; ++i) { auto *profile = m_profiles[i]; const size_t numFilled = - profile->fillConstraintMatrix(m_cmatrix, start, m_errors); + profile->fillConstraintMatrix(m_cmatrix, start, m_hist->e()); start += numFilled; } // Using different minimizer for background constraints as the original is not @@ -233,31 +232,33 @@ void ComptonScatteringCountRate::updateCMatrixValues() const { * Cache workspace reference. Expects a MatrixWorkspace * @param matrix A shared_ptr to a Workspace * @param wsIndex A workspace index - * @param startX Starting x-vaue (unused). - * @param endX Ending x-vaue (unused). + * @param startX Starting x-value (unused). + * @param endX Ending x-value (unused). */ void ComptonScatteringCountRate::setMatrixWorkspace( boost::shared_ptr<const API::MatrixWorkspace> matrix, size_t wsIndex, double startX, double endX) { CompositeFunction::setMatrixWorkspace(matrix, wsIndex, startX, endX); - const auto &values = matrix->readY(wsIndex); - + this->m_hist = + boost::make_shared<HistogramData::Histogram>(matrix->histogram(wsIndex)); + this->wsIndex = wsIndex; + const auto &values = m_hist->y(); + const auto &errors = m_hist->e(); // Keep the errors for the constraint calculation - m_errors = matrix->readE(wsIndex); - m_dataErrorRatio.resize(m_errors.size()); - std::transform(values.begin(), values.end(), m_errors.begin(), + m_dataErrorRatio.resize(errors.size()); + std::transform(values.begin(), values.end(), errors.begin(), m_dataErrorRatio.begin(), std::divides<double>()); if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "-- data/error --\n"; - for (size_t i = 0; i < m_errors.size(); ++i) { + for (size_t i = 0; i < errors.size(); ++i) { g_log.debug() << m_dataErrorRatio[i] << "\n"; } } cacheFunctions(); - createConstraintMatrices(matrix->readX(wsIndex)); + createConstraintMatrices(); } /* @@ -353,8 +354,7 @@ void ComptonScatteringCountRate::cacheBackground( * Also creates the inequality matrix * @param xValues The xdata from the workspace */ -void ComptonScatteringCountRate::createConstraintMatrices( - const MantidVec &xValues) { +void ComptonScatteringCountRate::createConstraintMatrices() { const size_t nmasses = m_profiles.size(); // Sanity check that equality constraints matrix has the same number of @@ -368,7 +368,7 @@ void ComptonScatteringCountRate::createConstraintMatrices( throw std::invalid_argument(os.str()); } - createPositivityCM(xValues); + createPositivityCM(); createEqualityCM(nmasses); if (g_log.is(Logger::Priority::PRIO_DEBUG)) { @@ -382,15 +382,15 @@ void ComptonScatteringCountRate::createConstraintMatrices( } } -/** - * @param xValues The X data for the fitted spectrum - */ -void ComptonScatteringCountRate::createPositivityCM(const MantidVec &xValues) { +void ComptonScatteringCountRate::createPositivityCM() { // -- Constraint matrix for J(y) > 0 -- // The first N columns are filled with J(y) for each mass + N_h for the first // mass hermite // terms included + (n+1) for each termn the background of order n // The background columns are filled with x^j/error where j=(1,n+1) + const auto &xValues = m_hist->x(); + const auto &errors = m_hist->e(); + const size_t nrows(xValues.size()); size_t nColsCMatrix(m_fixedParamIndices.size()); m_cmatrix = Kernel::DblMatrix(nrows, nColsCMatrix); @@ -402,7 +402,7 @@ void ComptonScatteringCountRate::createPositivityCM(const MantidVec &xValues) { { double *row = m_cmatrix[i]; const double &xi = xValues[i]; - const double &erri = m_errors[i]; + const double &erri = errors[i]; size_t polyN = m_bkgdPolyN; for (size_t j = polyStartCol; j < nColsCMatrix; ++j) // cols { diff --git a/Framework/CurveFitting/src/Functions/GaussianComptonProfile.cpp b/Framework/CurveFitting/src/Functions/GaussianComptonProfile.cpp index 3c4bb0d10c15574b9eb4b1e4b14b63556fefecbd..bc4e7fa95e0b53a4d31f0f889b022e5350bc732f 100644 --- a/Framework/CurveFitting/src/Functions/GaussianComptonProfile.cpp +++ b/Framework/CurveFitting/src/Functions/GaussianComptonProfile.cpp @@ -54,7 +54,7 @@ std::vector<size_t> GaussianComptonProfile::intensityParameterIndices() const { */ size_t GaussianComptonProfile::fillConstraintMatrix( Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const { + const HistogramData::HistogramE &errors) const { std::vector<double> result(ySpace().size()); const double amplitude = 1.0; this->massProfile(result.data(), ySpace().size(), amplitude); diff --git a/Framework/CurveFitting/src/Functions/GramCharlierComptonProfile.cpp b/Framework/CurveFitting/src/Functions/GramCharlierComptonProfile.cpp index 2d872afe5e8fb4923f230013aebef7f71ac1be30..8054cfe6b052041f1d57b1897c349476638ea65b 100644 --- a/Framework/CurveFitting/src/Functions/GramCharlierComptonProfile.cpp +++ b/Framework/CurveFitting/src/Functions/GramCharlierComptonProfile.cpp @@ -194,7 +194,7 @@ GramCharlierComptonProfile::intensityParameterIndices() const { */ size_t GramCharlierComptonProfile::fillConstraintMatrix( Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const { + const HistogramData::HistogramE &errors) const { std::vector<double> profile(NFINE_Y, 0.0); const size_t nData(ySpace().size()); std::vector<double> result(nData, 0.0); @@ -364,13 +364,12 @@ void GramCharlierComptonProfile::setMatrixWorkspace( /** * @param tseconds A vector containing the time-of-flight values in seconds - * @param isHistogram True if histogram tof values have been passed in * @param detpar Structure containing detector parameters */ void GramCharlierComptonProfile::cacheYSpaceValues( - const std::vector<double> &tseconds, const bool isHistogram, + const HistogramData::Points &tseconds, const Algorithms::DetectorParams &detpar) { - ComptonProfile::cacheYSpaceValues(tseconds, isHistogram, + ComptonProfile::cacheYSpaceValues(tseconds, detpar); // base-class calculations // Is FSE fixed at the moment? diff --git a/Framework/CurveFitting/src/Functions/MultivariateGaussianComptonProfile.cpp b/Framework/CurveFitting/src/Functions/MultivariateGaussianComptonProfile.cpp index 86a3aa224f2f35d94073155025c232e91c99d6ee..5cb7659e4782309755cf94038bd5ef46c664b33e 100644 --- a/Framework/CurveFitting/src/Functions/MultivariateGaussianComptonProfile.cpp +++ b/Framework/CurveFitting/src/Functions/MultivariateGaussianComptonProfile.cpp @@ -91,7 +91,7 @@ MultivariateGaussianComptonProfile::intensityParameterIndices() const { */ size_t MultivariateGaussianComptonProfile::fillConstraintMatrix( Kernel::DblMatrix &cmatrix, const size_t start, - const std::vector<double> &errors) const { + const HistogramData::HistogramE &errors) const { std::vector<double> result(ySpace().size()); this->massProfile(result.data(), ySpace().size()); std::transform(result.begin(), result.end(), errors.begin(), result.begin(), diff --git a/Framework/CurveFitting/src/Functions/ProcessBackground.cpp b/Framework/CurveFitting/src/Functions/ProcessBackground.cpp index 6596651b122dbc7d25f19c4b9896d1f064ce7f5a..26f472a8e3a05dd35019170c62ef278d2b4bcb13 100644 --- a/Framework/CurveFitting/src/Functions/ProcessBackground.cpp +++ b/Framework/CurveFitting/src/Functions/ProcessBackground.cpp @@ -27,6 +27,8 @@ using namespace Mantid::DataObjects; using namespace Mantid::CurveFitting; +using namespace HistogramData; + using namespace std; namespace Mantid { @@ -249,9 +251,9 @@ void ProcessBackground::exec() { m_lowerBound = getProperty("LowerBound"); m_upperBound = getProperty("UpperBound"); if (isEmpty(m_lowerBound)) - m_lowerBound = m_dataWS->readX(m_wsIndex).front(); + m_lowerBound = m_dataWS->x(m_wsIndex).front(); if (isEmpty(m_upperBound)) - m_upperBound = m_dataWS->readX(m_wsIndex).back(); + m_upperBound = m_dataWS->x(m_wsIndex).back(); // 2. Do different work std::string option = getProperty("Options"); @@ -303,41 +305,38 @@ void ProcessBackground::deleteRegion() { "Lower boundary cannot be equal or larger than upper boundary."); } - // Copy original data and exclude region defined by m_lowerBound and - // m_upperBound - const MantidVec &dataX = m_dataWS->readX(0); - const MantidVec &dataY = m_dataWS->readY(0); - const MantidVec &dataE = m_dataWS->readE(0); - - std::vector<double> vx, vy, ve; + const auto &dataX = m_dataWS->x(0); + const auto &dataY = m_dataWS->y(0); + const auto &dataE = m_dataWS->e(0); - for (size_t i = 0; i < dataY.size(); ++i) { - double xtmp = dataX[i]; - if (xtmp < m_lowerBound || xtmp > m_upperBound) { - vx.push_back(dataX[i]); - vy.push_back(dataY[i]); - ve.push_back(dataE[i]); + // Find the dimensions of the region excluded by m_lowerBound and m_upperBound + std::vector<size_t> incIndexes; + for (size_t i = 0; i < dataY.size(); i++) { + if (dataX[i] < m_lowerBound || dataX[i] > m_upperBound) { + incIndexes.push_back(i); } } + size_t sizex = incIndexes.size(); + size_t sizey = incIndexes.size(); if (dataX.size() > dataY.size()) { - vx.push_back(dataX.back()); + sizex++; } - // Create new workspace - size_t sizex = vx.size(); - size_t sizey = vy.size(); + // Create a new workspace with these dimensions and copy data from the defined + // region API::MatrixWorkspace_sptr mws = API::WorkspaceFactory::Instance().create("Workspace2D", 1, sizex, sizey); m_outputWS = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(mws); m_outputWS->getAxis(0)->setUnit(m_dataWS->getAxis(0)->unit()->unitID()); - for (size_t i = 0; i < sizey; ++i) { - m_outputWS->dataX(0)[i] = vx[i]; - m_outputWS->dataY(0)[i] = vy[i]; - m_outputWS->dataE(0)[i] = ve[i]; + for (size_t i = 0; i < sizey; i++) { + size_t index = incIndexes[i]; + m_outputWS->mutableX(0)[i] = dataX[index]; + m_outputWS->mutableY(0)[i] = dataY[index]; + m_outputWS->mutableE(0)[i] = dataE[index]; } if (sizex > sizey) { - m_outputWS->dataX(0)[sizex - 1] = vx.back(); + m_outputWS->mutableX(0)[sizex - 1] = dataX.back(); } // Set up dummies @@ -360,9 +359,9 @@ void ProcessBackground::addRegion() { } // Copy data to a set of vectors - const MantidVec &vecX = m_dataWS->readX(0); - const MantidVec &vecY = m_dataWS->readY(0); - const MantidVec &vecE = m_dataWS->readE(0); + const auto &vecX = m_dataWS->x(0); + const auto &vecY = m_dataWS->y(0); + const auto &vecE = m_dataWS->e(0); std::vector<double> vx, vy, ve; for (size_t i = 0; i < vecY.size(); ++i) { @@ -383,9 +382,9 @@ void ProcessBackground::addRegion() { if (!refWS) throw std::invalid_argument("ReferenceWorkspace is not given. "); - const MantidVec &refX = refWS->dataX(0); - const MantidVec &refY = refWS->dataY(0); - const MantidVec &refE = refWS->dataE(0); + const auto &refX = refWS->x(0); + const auto &refY = refWS->y(0); + const auto &refE = refWS->e(0); // 4. Insert the value of the reference workspace from lowerBoundary to // upperBoundary @@ -396,9 +395,9 @@ void ProcessBackground::addRegion() { size_t eindex = size_t(refiter - refX.begin()); for (size_t i = sindex; i < eindex; ++i) { - double tmpx = refX[i]; - double tmpy = refY[i]; - double tmpe = refE[i]; + const double tmpx = refX[i]; + const double tmpy = refY[i]; + const double tmpe = refE[i]; // Locate the position of tmpx in the array to be inserted auto newit = std::lower_bound(vx.begin(), vx.end(), tmpx); @@ -415,8 +414,8 @@ void ProcessBackground::addRegion() { } // Check - for (size_t i = 1; i < vx.size(); ++i) { - if (vx[i] <= vx[i - 1]) { + for (auto it = vx.begin() + 1; it != vx.end(); ++it) { + if (*it <= *it - 1) { g_log.error() << "The vector X with value inserted is not ordered incrementally\n"; throw std::runtime_error("Build new vector error!"); @@ -428,13 +427,8 @@ void ProcessBackground::addRegion() { API::WorkspaceFactory::Instance().create("Workspace2D", 1, vx.size(), vy.size())); m_outputWS->getAxis(0)->setUnit(m_dataWS->getAxis(0)->unit()->unitID()); - for (size_t i = 0; i < vy.size(); ++i) { - m_outputWS->dataX(0)[i] = vx[i]; - m_outputWS->dataY(0)[i] = vy[i]; - m_outputWS->dataE(0)[i] = ve[i]; - } - if (vx.size() > vy.size()) - m_outputWS->dataX(0).back() = vx.back(); + m_outputWS->setHistogram( + 0, Histogram(Points(vx), Counts(vy), CountStandardDeviations(ve))); // Write out dummy output workspaces setupDummyOutputWSes(); @@ -483,10 +477,10 @@ void ProcessBackground::selectFromGivenXValues() { string mode = getProperty("BackgroundPointSelectMode"); // Construct background workspace for fit - std::vector<double> realx, realy, reale; - const MantidVec &vecX = m_dataWS->readX(m_wsIndex); - const MantidVec &vecY = m_dataWS->readY(m_wsIndex); - const MantidVec &vecE = m_dataWS->readE(m_wsIndex); + std::vector<size_t> realIndexes; + const auto &vecX = m_dataWS->x(m_wsIndex); + const auto &vecY = m_dataWS->y(m_wsIndex); + const auto &vecE = m_dataWS->e(m_wsIndex); for (size_t i = 0; i < bkgdpoints.size(); ++i) { // Data range validation double bkgdpoint = bkgdpoints[i]; @@ -514,21 +508,21 @@ void ProcessBackground::selectFromGivenXValues() { << ", " << vecX.back() << "] " << "\n"; - // Add to list - realx.push_back(vecX[index]); - realy.push_back(vecY[index]); - reale.push_back(vecE[index]); + // Add index to list + realIndexes.push_back(index); } // ENDFOR (i) + size_t wsSize = realIndexes.size(); DataObjects::Workspace2D_sptr bkgdWS = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, - realx.size(), realy.size())); - for (size_t i = 0; i < realx.size(); ++i) { - bkgdWS->dataX(0)[i] = realx[i]; - bkgdWS->dataY(0)[i] = realy[i]; - bkgdWS->dataE(0)[i] = reale[i]; + API::WorkspaceFactory::Instance().create("Workspace2D", 1, wsSize, + wsSize)); + for (size_t i = 0; i < wsSize; ++i) { + size_t index = realIndexes[i]; + bkgdWS->mutableX(0)[i] = vecX[index]; + bkgdWS->mutableY(0)[i] = vecY[index]; + bkgdWS->mutableE(0)[i] = vecE[index]; } // Select background points according to mode @@ -596,11 +590,10 @@ ProcessBackground::autoBackgroundSelection(Workspace2D_sptr bkgdWS) { bkgdfunction->setAttributeValue("n", bkgdorder); bkgdfunction->initialize(); - g_log.information() << "Input background points has " - << bkgdWS->readX(0).size() << " data points for fit " - << bkgdorder << "-th order " << bkgdfunction->name() - << " (background) function" << bkgdfunction->asString() - << "\n"; + g_log.information() << "Input background points has " << bkgdWS->x(0).size() + << " data points for fit " << bkgdorder << "-th order " + << bkgdfunction->name() << " (background) function" + << bkgdfunction->asString() << "\n"; // Fit input (a few) background pionts to get initial guess API::IAlgorithm_sptr fit; @@ -689,8 +682,8 @@ ProcessBackground::filterForBackground(BackgroundFunction_sptr bkgdfunction) { negnoisetolerance = posnoisetolerance; // Calcualte theoretical values - const std::vector<double> x = m_dataWS->readX(m_wsIndex); - API::FunctionDomain1DVector domain(x); + const auto &x = m_dataWS->x(m_wsIndex); + API::FunctionDomain1DVector domain(x.rawData()); API::FunctionValues values(domain); bkgdfunction->function(domain, values); @@ -709,49 +702,42 @@ ProcessBackground::filterForBackground(BackgroundFunction_sptr bkgdfunction) { WorkspaceFactory::Instance().create("Workspace2D", 4, sizex, sizey)); for (size_t i = 0; i < sizex; ++i) { for (size_t j = 0; j < 4; ++j) { - visualws->dataX(j)[i] = domain[i]; + visualws->mutableX(j)[i] = domain[i]; } } for (size_t i = 0; i < sizey; ++i) { - visualws->dataY(0)[i] = values[i]; - visualws->dataY(1)[i] = m_dataWS->readY(m_wsIndex)[i] - values[i]; - visualws->dataY(2)[i] = posnoisetolerance; - visualws->dataY(3)[i] = -negnoisetolerance; + visualws->mutableY(0)[i] = values[i]; + visualws->mutableY(1)[i] = m_dataWS->y(m_wsIndex)[i] - values[i]; + visualws->mutableY(2)[i] = posnoisetolerance; + visualws->mutableY(3)[i] = -negnoisetolerance; } setProperty("UserBackgroundWorkspace", visualws); // Filter for background - std::vector<double> vecx, vecy, vece; + std::vector<size_t> selectedIndexes; for (size_t i = 0; i < domain.size(); ++i) { - // double y = m_dataWS->readY(m_wsIndex)[i]; - // double theoryy = values[i]; y-theoryy - double purey = visualws->readY(1)[i]; + double purey = visualws->y(1)[i]; if (purey < posnoisetolerance && purey > -negnoisetolerance) { - // Selected - double x = domain[i]; - double y = m_dataWS->readY(m_wsIndex)[i]; - double e = m_dataWS->readE(m_wsIndex)[i]; - vecx.push_back(x); - vecy.push_back(y); - vece.push_back(e); + selectedIndexes.push_back(i); } } - g_log.information() << "Found " << vecx.size() << " background points out of " - << m_dataWS->readX(m_wsIndex).size() - << " total data points. " + size_t wsSize = selectedIndexes.size(); + g_log.information() << "Found " << wsSize << " background points out of " + << m_dataWS->x(m_wsIndex).size() << " total data points. " << "\n"; // Build new workspace for OutputWorkspace size_t nspec = 3; Workspace2D_sptr outws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", nspec, - vecx.size(), vecy.size())); - for (size_t i = 0; i < vecx.size(); ++i) { + API::WorkspaceFactory::Instance().create("Workspace2D", nspec, wsSize, + wsSize)); + for (size_t i = 0; i < wsSize; ++i) { + size_t index = selectedIndexes[i]; for (size_t j = 0; j < nspec; ++j) - outws->dataX(j)[i] = vecx[i]; - outws->dataY(0)[i] = vecy[i]; - outws->dataE(0)[i] = vece[i]; + outws->mutableX(j)[i] = domain[index]; + outws->mutableY(0)[i] = m_dataWS->y(m_wsIndex)[index]; + outws->mutableE(0)[i] = m_dataWS->e(m_wsIndex)[index]; } return outws; @@ -769,8 +755,8 @@ void ProcessBackground::fitBackgroundFunction(std::string bkgdfunctiontype) { bkgdfunction->setAttributeValue("n", bkgdorder); if (bkgdfunctiontype == "Chebyshev") { - double xmin = m_outputWS->readX(0).front(); - double xmax = m_outputWS->readX(0).back(); + double xmin = m_outputWS->x(0).front(); + double xmax = m_outputWS->x(0).back(); g_log.information() << "Chebyshev Fit range: " << xmin << ", " << xmax << "\n"; bkgdfunction->setAttributeValue("StartX", xmin); @@ -848,15 +834,15 @@ void ProcessBackground::fitBackgroundFunction(std::string bkgdfunctiontype) { setProperty("OutputBackgroundParameterWorkspace", outbkgdparws); // Set output workspace - const MantidVec &vecX = m_outputWS->readX(0); - const MantidVec &vecY = m_outputWS->readY(0); - FunctionDomain1DVector domain(vecX); + const auto &vecX = m_outputWS->x(0); + const auto &vecY = m_outputWS->y(0); + FunctionDomain1DVector domain(vecX.rawData()); FunctionValues values(domain); funcout->function(domain, values); - MantidVec &dataModel = m_outputWS->dataY(1); - MantidVec &dataDiff = m_outputWS->dataY(2); + auto &dataModel = m_outputWS->mutableY(1); + auto &dataDiff = m_outputWS->mutableY(2); for (size_t i = 0; i < dataModel.size(); ++i) { dataModel[i] = values[i]; dataDiff[i] = vecY[i] - dataModel[i]; @@ -916,16 +902,16 @@ RemovePeaks::removePeaks(API::MatrixWorkspace_const_sptr dataws, int wsindex, throw runtime_error("RemovePeaks has not been setup yet. "); // Initialize vectors - const MantidVec &vecX = dataws->readX(wsindex); - const MantidVec &vecY = dataws->readY(wsindex); - const MantidVec &vecE = dataws->readE(wsindex); + const auto &vecX = dataws->x(wsindex); + const auto &vecY = dataws->y(wsindex); + const auto &vecE = dataws->e(wsindex); size_t sizex = vecX.size(); vector<bool> vec_useX(sizex, true); // Exclude regions - size_t numbkgdpoints = - excludePeaks(vecX, vec_useX, m_vecPeakCentre, m_vecPeakFWHM, numfwhm); + size_t numbkgdpoints = excludePeaks(vecX.rawData(), vec_useX, m_vecPeakCentre, + m_vecPeakFWHM, numfwhm); size_t numbkgdpointsy = numbkgdpoints; size_t sizey = vecY.size(); if (sizex > sizey) @@ -936,9 +922,9 @@ RemovePeaks::removePeaks(API::MatrixWorkspace_const_sptr dataws, int wsindex, WorkspaceFactory::Instance().create("Workspace2D", 1, numbkgdpoints, numbkgdpointsy)); outws->getAxis(0)->setUnit(dataws->getAxis(0)->unit()->unitID()); - MantidVec &outX = outws->dataX(0); - MantidVec &outY = outws->dataY(0); - MantidVec &outE = outws->dataE(0); + auto &outX = outws->mutableX(0); + auto &outY = outws->mutableY(0); + auto &outE = outws->mutableE(0); size_t index = 0; for (size_t i = 0; i < sizex; ++i) { if (vec_useX[i]) { diff --git a/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp b/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp index b0f40fcf6a50814f2b4fda6942616a017a323189..97f44caeebb6be70ba1b9a501552044fe15e279b 100644 --- a/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp +++ b/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp @@ -261,21 +261,10 @@ void TabulatedFunction::setupData() const { g_log.debug() << "Setting up " << m_workspace->name() << " index " << index << '\n'; - const bool hist = m_workspace->isHistogramData(); - const size_t nbins = m_workspace->blocksize(); - m_xData.resize(nbins); - m_yData.resize(nbins); - - for (size_t i = 0; i < nbins; i++) { - double x = 0.0; - m_yData[i] = m_workspace->readY(index)[i]; - auto &xvec = m_workspace->readX(index); - if (hist) - x = (xvec[i] + xvec[i + 1]) / 2; - else - x = xvec[i]; - m_xData[i] = x; - } + const auto &xData = m_workspace->points(index); + const auto &yData = m_workspace->y(index); + m_xData.assign(xData.begin(), xData.end()); + m_yData.assign(yData.begin(), yData.end()); m_workspace.reset(); m_setupFinished = true; diff --git a/Framework/CurveFitting/src/HistogramDomainCreator.cpp b/Framework/CurveFitting/src/HistogramDomainCreator.cpp index 0b146233787b39863f773204a041a65770c72c79..5e6fd9b204457514a38867cabbb9802030cba314 100644 --- a/Framework/CurveFitting/src/HistogramDomainCreator.cpp +++ b/Framework/CurveFitting/src/HistogramDomainCreator.cpp @@ -45,7 +45,7 @@ void HistogramDomainCreator::createDomain( "Cannot create non-simple domain for histogram fitting."); } - const Mantid::MantidVec &X = m_matrixWorkspace->readX(m_workspaceIndex); + const auto &X = m_matrixWorkspace->x(m_workspaceIndex); // find the fitting interval: from -> to size_t endIndex = 0; @@ -63,27 +63,18 @@ void HistogramDomainCreator::createDomain( } // set the data to fit to - const Mantid::MantidVec &Y = m_matrixWorkspace->readY(m_workspaceIndex); - const Mantid::MantidVec &E = m_matrixWorkspace->readE(m_workspaceIndex); + const auto &Y = m_matrixWorkspace->counts(m_workspaceIndex); + const auto &E = m_matrixWorkspace->countStandardDeviations(m_workspaceIndex); if (endIndex > Y.size()) { throw std::runtime_error("FitMW: Inconsistent MatrixWorkspace"); } - bool isDistribution = m_matrixWorkspace->isDistribution(); - for (size_t i = m_startIndex; i < endIndex; ++i) { size_t j = i - m_startIndex + i0; double y = Y[i]; double error = E[i]; double weight = 0.0; - if (isDistribution) { - // If workspace is a distribution, convert data to histogram - auto dx = X[i + 1] - X[i]; - y *= dx; - error *= dx; - } - if (!std::isfinite(y)) // nan or inf data { if (!m_ignoreInvalidData) @@ -132,8 +123,8 @@ boost::shared_ptr<API::Workspace> HistogramDomainCreator::createOutputWorkspace( // skip the diff spectrum continue; } - auto &y = mws.dataY(iSpec); - auto &e = mws.dataE(iSpec); + auto &y = mws.mutableY(iSpec); + auto &e = mws.mutableE(iSpec); double left = bins.leftBoundary(); for (size_t i = 0; i < bins.size(); ++i) { double right = bins[i]; diff --git a/Framework/CurveFitting/test/Functions/ComptonProfileTest.h b/Framework/CurveFitting/test/Functions/ComptonProfileTest.h index 74dd80c044b565e5c8bcfcaed0e992dabd6496c8..64417b0eb551e4cab30742dff996791028372fd8 100644 --- a/Framework/CurveFitting/test/Functions/ComptonProfileTest.h +++ b/Framework/CurveFitting/test/Functions/ComptonProfileTest.h @@ -51,8 +51,9 @@ private: std::vector<size_t> intensityParameterIndices() const override { return std::vector<size_t>(); } - size_t fillConstraintMatrix(Mantid::Kernel::DblMatrix &, const size_t, - const std::vector<double> &) const override { + size_t fillConstraintMatrix( + Mantid::Kernel::DblMatrix &, const size_t, + const Mantid::HistogramData::HistogramE &) const override { return 0; } diff --git a/Framework/CurveFitting/test/Functions/ComptonScatteringCountRateTest.h b/Framework/CurveFitting/test/Functions/ComptonScatteringCountRateTest.h index 6d5fbb2482b1f9e1ca72ac882f299a159453d1ef..77730ea337226725cc8e1b7a496e9b45d1b6496f 100644 --- a/Framework/CurveFitting/test/Functions/ComptonScatteringCountRateTest.h +++ b/Framework/CurveFitting/test/Functions/ComptonScatteringCountRateTest.h @@ -74,12 +74,12 @@ public: IFunction_sptr func = createFunctionNoBackground(); double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); + auto &dataX = testWS->mutableX(0); std::transform( dataX.begin(), dataX.end(), dataX.begin(), std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); - FunctionDomain1DView domain(dataX.data(), dataX.size()); + FunctionDomain1DView domain(&dataX.front(), dataX.size()); FunctionValues values(domain); TS_ASSERT_THROWS_NOTHING(func->function(domain, values)); @@ -96,13 +96,10 @@ public: IFunction_sptr func = createFunctionWithBackground(); double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); - std::transform( - dataX.begin(), dataX.end(), dataX.begin(), - std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds + auto &dataX = testWS->mutableX(0) *= 1e-06; // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); - FunctionDomain1DView domain(dataX.data(), dataX.size()); + FunctionDomain1DView domain(&dataX.front(), dataX.size()); FunctionValues values(domain); TS_ASSERT_THROWS_NOTHING(func->function(domain, values)); @@ -120,10 +117,7 @@ public: IFunction_sptr func = createFunctionNoBackground(); double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); - std::transform( - dataX.begin(), dataX.end(), dataX.begin(), - std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds + auto &dataX = testWS->mutableX(0) *= 1e-06; // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); func->iterationStarting(); @@ -144,10 +138,7 @@ public: double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); - std::transform( - dataX.begin(), dataX.end(), dataX.begin(), - std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds + auto &dataX = testWS->mutableX(0) *= 1e-06; // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); func->iterationStarting(); @@ -168,11 +159,7 @@ public: double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); - std::transform( - dataX.begin(), dataX.end(), dataX.begin(), - std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds - + auto &dataX = testWS->mutableX(0) *= 1e-06; // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); func->iterationStarting(); @@ -197,11 +184,7 @@ public: double x0(165.0), x1(166.0), dx(0.5); auto testWS = ComptonProfileTestHelpers::createTestWorkspace(1, x0, x1, dx); - auto &dataX = testWS->dataX(0); - std::transform( - dataX.begin(), dataX.end(), dataX.begin(), - std::bind2nd(std::multiplies<double>(), 1e-06)); // to seconds - + auto &dataX = testWS->mutableX(0) *= 1e-06; // to seconds func->setMatrixWorkspace(testWS, 0, dataX.front(), dataX.back()); func->iterationStarting(); @@ -229,9 +212,9 @@ private: return std::vector<size_t>(1, 1); } - size_t fillConstraintMatrix(Mantid::Kernel::DblMatrix &cmatrix, - const size_t start, - const std::vector<double> &) const override { + size_t fillConstraintMatrix( + Mantid::Kernel::DblMatrix &cmatrix, const size_t start, + const Mantid::HistogramData::HistogramE &) const override { for (size_t i = 0; i < cmatrix.numRows(); ++i) { cmatrix[i][start] = 1.0; } @@ -260,9 +243,9 @@ private: indices[1] = 2; // index 2 return indices; } - size_t fillConstraintMatrix(Mantid::Kernel::DblMatrix &cmatrix, - const size_t start, - const std::vector<double> &) const override { + size_t fillConstraintMatrix( + Mantid::Kernel::DblMatrix &cmatrix, const size_t start, + const Mantid::HistogramData::HistogramE &) const override { for (size_t i = 0; i < cmatrix.numRows(); ++i) { for (size_t j = start; j < start + 2; ++j) { cmatrix[i][j] = 1.0; diff --git a/Framework/CurveFitting/test/Functions/ProcessBackgroundTest.h b/Framework/CurveFitting/test/Functions/ProcessBackgroundTest.h index 0518e798be4fb9305e8cfc608fc15041d71fe72c..a89fdc30a80bc54c8a5cdf2a2f8afe622c83af6c 100644 --- a/Framework/CurveFitting/test/Functions/ProcessBackgroundTest.h +++ b/Framework/CurveFitting/test/Functions/ProcessBackgroundTest.h @@ -8,6 +8,7 @@ #include "MantidDataObjects/TableWorkspace.h" #include "MantidAPI/WorkspaceFactory.h" #include "MantidAPI/TableRow.h" +#include "MantidKernel/MersenneTwister.h" #include <fstream> @@ -16,6 +17,17 @@ using namespace Mantid; using namespace Mantid::API; using namespace Kernel; using namespace Mantid::DataObjects; +using namespace HistogramData; + +namespace { +Workspace2D_sptr createInputWS(std::string name, size_t sizex, size_t sizey) { + Workspace2D_sptr inputWS = boost::dynamic_pointer_cast<Workspace2D>( + WorkspaceFactory::Instance().create("Workspace2D", 1, sizex, sizey)); + AnalysisDataService::Instance().addOrReplace(name, inputWS); + + return inputWS; +} +} class ProcessBackgroundTest : public CxxTest::TestSuite { public: @@ -29,15 +41,12 @@ public: /** Test option delete region */ void test_DeleteRegion() { - // 1. Create Workspace2D - DataObjects::Workspace2D_sptr inpws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, 10, 10)); - for (size_t i = 0; i < 10; ++i) { - inpws->dataX(0)[i] = double(i); - inpws->dataY(0)[i] = double(i) * double(i); + size_t wsSize = 10; + auto inpws = createInputWS("Background1", wsSize, wsSize); + for (size_t i = 0; i < wsSize; ++i) { + inpws->mutableX(0)[i] = double(i); + inpws->mutableY(0)[i] = double(i) * double(i); } - API::AnalysisDataService::Instance().addOrReplace("Background1", inpws); // 2. Do the job ProcessBackground alg; @@ -55,16 +64,15 @@ public: TS_ASSERT(alg.isExecuted()); // 3. Check - DataObjects::Workspace2D_sptr outws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::AnalysisDataService::Instance().retrieve("NewBackground")); - size_t newsize = outws->dataX(0).size(); + Workspace2D_sptr outws = boost::dynamic_pointer_cast<Workspace2D>( + AnalysisDataService::Instance().retrieve("NewBackground")); + size_t newsize = outws->x(0).size(); TS_ASSERT_EQUALS(newsize, 8); // 4. Clean - API::AnalysisDataService::Instance().remove("Background1"); - API::AnalysisDataService::Instance().remove("NewBackground"); + AnalysisDataService::Instance().remove("Background1"); + AnalysisDataService::Instance().remove("NewBackground"); return; } @@ -72,24 +80,18 @@ public: /** Test option "Add Region" */ void test_AddRegion() { - // 1. Create Workspace2D - DataObjects::Workspace2D_sptr inpws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, 10, 10)); - for (size_t i = 0; i < 10; ++i) { - inpws->dataX(0)[i] = double(i); - inpws->dataY(0)[i] = double(i) * double(i); + size_t wsSize = 10; + auto inpws = createInputWS("Background2", wsSize, wsSize); + for (size_t i = 0; i < wsSize; ++i) { + inpws->mutableX(0)[i] = double(i); + inpws->mutableY(0)[i] = double(i) * double(i); } - API::AnalysisDataService::Instance().addOrReplace("Background2", inpws); - DataObjects::Workspace2D_sptr refws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, 10, 10)); - for (size_t i = 0; i < 10; ++i) { - refws->dataX(0)[i] = double(i) * 0.3 + 1.01; - refws->dataY(0)[i] = double(i) * double(i); + auto refws = createInputWS("RefBackground", wsSize, wsSize); + for (size_t i = 0; i < wsSize; ++i) { + refws->mutableX(0)[i] = double(i) * 0.3 + 1.01; + refws->mutableY(0)[i] = double(i) * double(i); } - API::AnalysisDataService::Instance().addOrReplace("RefBackground", refws); // 2. Do the job ProcessBackground alg; @@ -108,16 +110,16 @@ public: TS_ASSERT(alg.isExecuted()); // 3. Check - DataObjects::Workspace2D_sptr outws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::AnalysisDataService::Instance().retrieve("NewBackground")); - size_t newsize = outws->dataX(0).size(); + Workspace2D_sptr outws = boost::dynamic_pointer_cast<Workspace2D>( + AnalysisDataService::Instance().retrieve("NewBackground")); + size_t newsize = outws->x(0).size(); TS_ASSERT_EQUALS(newsize, 14); // 4. Clean - API::AnalysisDataService::Instance().remove("Background2"); - API::AnalysisDataService::Instance().remove("NewBackground"); + AnalysisDataService::Instance().remove("Background2"); + AnalysisDataService::Instance().remove("RefBackground"); + AnalysisDataService::Instance().remove("NewBackground"); return; } @@ -130,9 +132,8 @@ public: // 1. Prepare for data std::string datafile("/home/wzz/Mantid/Code/debug/MyTestData/4862b7.inp"); - DataObjects::Workspace2D_sptr dataws = createWorkspace2D(datafile); - API::AnalysisDataService::Instance().addOrReplace("DiffractionData", - dataws); + Workspace2D_sptr dataws = createWorkspace2D(datafile); + AnalysisDataService::Instance().addOrReplace("DiffractionData", dataws); /// Background points for bank 7 std::vector<double> bkgdpts = {57741.0, 63534.0, 69545.0, 89379.0, 89379.0, 115669.0, @@ -157,10 +158,8 @@ public: TS_ASSERT(alg.isExecuted()); // 3. Check the result - DataObjects::Workspace2D_sptr bkgdws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::AnalysisDataService::Instance().retrieve( - "SelectedBackgroundPoints")); + Workspace2D_sptr bkgdws = boost::dynamic_pointer_cast<Workspace2D>( + AnalysisDataService::Instance().retrieve("SelectedBackgroundPoints")); TS_ASSERT(bkgdws); return; @@ -170,19 +169,14 @@ public: /** Test automatic background selection */ void test_SimpleBackgroundGeneration() { - // Create Workspace2D - DataObjects::Workspace2D_sptr dataws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, 1000, - 1000)); - for (size_t i = 0; i < 1000; ++i) { - dataws->dataX(0)[i] = double(i); - dataws->dataY(0)[i] = double(i) * double(i); + // Create input data + size_t wsSize = 1000; + auto dataws = createInputWS("DiffractionData1", wsSize, wsSize); + for (size_t i = 0; i < wsSize; ++i) { + dataws->mutableX(0)[i] = double(i); + dataws->mutableY(0)[i] = double(i) * double(i); } - API::AnalysisDataService::Instance().addOrReplace("DiffractionData", - dataws); - std::vector<double> bkgdpts = {577.400, 635.340, 695.450, 893.790}; // Prepare algorithm @@ -207,16 +201,14 @@ public: TS_ASSERT(alg.isExecuted()); // 3. Check the result - DataObjects::Workspace2D_sptr bkgdws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::AnalysisDataService::Instance().retrieve( - "SelectedBackgroundPoints")); + Workspace2D_sptr bkgdws = boost::dynamic_pointer_cast<Workspace2D>( + AnalysisDataService::Instance().retrieve("SelectedBackgroundPoints")); TS_ASSERT(bkgdws); if (bkgdws) { - TS_ASSERT_EQUALS(bkgdws->readX(0).size(), bkgdpts.size()); + TS_ASSERT_EQUALS(bkgdws->x(0).size(), bkgdpts.size()); } - AnalysisDataService::Instance().remove("DiffractionData"); + AnalysisDataService::Instance().remove("DiffractionData1"); AnalysisDataService::Instance().remove("SelectedBackgroundPoints"); return; @@ -227,17 +219,13 @@ public: */ void test_SelectBackgroundFromInputFunction() { // Create input data - DataObjects::Workspace2D_sptr dataws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::WorkspaceFactory::Instance().create("Workspace2D", 1, 1000, - 1000)); - for (size_t i = 0; i < 1000; ++i) { - dataws->dataX(0)[i] = double(i); - dataws->dataY(0)[i] = + size_t wsSize = 1000; + auto dataws = createInputWS("DiffractionData2", wsSize, wsSize); + for (size_t i = 0; i < wsSize; ++i) { + dataws->mutableX(0)[i] = double(i); + dataws->mutableY(0)[i] = double(i) * double(i) + sin(double(i) / 180. * 3.14); } - API::AnalysisDataService::Instance().addOrReplace("DiffractionData2", - dataws); // Create background function TableWorkspace_sptr functablews = boost::make_shared<TableWorkspace>(); @@ -278,19 +266,16 @@ public: TS_ASSERT(alg.isExecuted()); // 3. Check the result - DataObjects::Workspace2D_sptr bkgdws = - boost::dynamic_pointer_cast<DataObjects::Workspace2D>( - API::AnalysisDataService::Instance().retrieve( - "SelectedBackgroundPoints2")); + Workspace2D_sptr bkgdws = boost::dynamic_pointer_cast<Workspace2D>( + AnalysisDataService::Instance().retrieve("SelectedBackgroundPoints2")); TS_ASSERT(bkgdws); if (bkgdws) { - TS_ASSERT(bkgdws->readX(0).size() > 10); + TS_ASSERT(bkgdws->x(0).size() > 10); TS_ASSERT_EQUALS(bkgdws->getNumberHistograms(), 3); } TableWorkspace_sptr bkgdparws = boost::dynamic_pointer_cast<TableWorkspace>( - API::AnalysisDataService::Instance().retrieve( - "OutBackgroundParameters")); + AnalysisDataService::Instance().retrieve("OutBackgroundParameters")); TS_ASSERT(bkgdparws); AnalysisDataService::Instance().remove("DiffractionData2"); @@ -303,35 +288,27 @@ public: //---------------------------------------------------------------------------------------------- /** Read column file to create a workspace2D */ - DataObjects::Workspace2D_sptr createWorkspace2D(std::string filename) { + Workspace2D_sptr createWorkspace2D(std::string filename) { // 1. Read data - std::vector<double> vecx, vecy, vece; - importDataFromColumnFile(filename, vecx, vecy, vece); + auto data = importDataFromColumnFile(filename); // 2. Create workspace - size_t datasize = vecx.size(); + size_t datasize = data.x().size(); DataObjects::Workspace2D_sptr dataws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>( API::WorkspaceFactory::Instance().create("Workspace2D", 1, datasize, datasize)); + dataws->setHistogram(0, data); - for (size_t i = 0; i < vecx.size(); ++i) { - dataws->dataX(0)[i] = vecx[i]; - dataws->dataY(0)[i] = vecy[i]; - dataws->dataE(0)[i] = vece[i]; - } - - std::cout << "DBT505 dataX range: " << vecx[0] << ", " << vecx.back() - << " sized " << vecx.size() << '\n'; + std::cout << "DBT505 dataX range: " << data.x()[0] << ", " + << data.x().back() << " sized " << data.x().size() << '\n'; return dataws; } /** Import data from a column data file */ - void importDataFromColumnFile(std::string filename, std::vector<double> &vecX, - std::vector<double> &vecY, - std::vector<double> &vecE) { + Histogram importDataFromColumnFile(std::string filename) { // 1. Open file std::ifstream ins; ins.open(filename.c_str()); @@ -342,23 +319,219 @@ public: // 2. Read file char line[256]; + std::vector<double> vx, vy, ve; while (ins.getline(line, 256)) { if (line[0] != '#') { double x, y; std::stringstream ss; ss.str(line); ss >> x >> y; - vecX.push_back(x); - vecY.push_back(y); double e = 1.0; if (y > 1.0E-5) e = std::sqrt(y); - vecE.push_back(e); + vx.push_back(x); + vy.push_back(y); + ve.push_back(e); } } - return; + return Histogram(Points(vx), Counts(vy), CountStandardDeviations(ve)); + } +}; + +// Performance test for "Delete Region" option +class ProcessBackgroundDRTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static ProcessBackgroundDRTestPerformance *createSuite() { + return new ProcessBackgroundDRTestPerformance(); + } + + static void destroySuite(ProcessBackgroundDRTestPerformance *suite) { + delete suite; } + + void setUp() override { + auto inpws = createInputWS("Background1", 1000000, 1000000); + for (size_t i = 0; i < 1000000; ++i) { + inpws->mutableX(0)[i] = double(i); + inpws->mutableY(0)[i] = double(i) * double(i); + } + + dr.initialize(); + dr.setProperty("InputWorkspace", inpws); + dr.setProperty("OutputWorkspace", "NewBackground"); + dr.setProperty("Options", "DeleteRegion"); + dr.setProperty("LowerBound", 450000.0); + dr.setProperty("UpperBound", 630000.0); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("Background1"); + } + + void testPerformanceWS() { dr.execute(); } + +private: + ProcessBackground dr; +}; + +// Performance test for "Add Region" option +class ProcessBackgroundARTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static ProcessBackgroundARTestPerformance *createSuite() { + return new ProcessBackgroundARTestPerformance(); + } + + static void destroySuite(ProcessBackgroundARTestPerformance *suite) { + delete suite; + } + + void setUp() override { + auto inpws = createInputWS("Background2", 80000, 80000); + for (size_t i = 0; i < 80000; ++i) { + inpws->mutableX(0)[i] = double(i); + inpws->mutableY(0)[i] = double(i) * double(i); + } + + auto refws = createInputWS("RefBackground", 80000, 80000); + for (size_t i = 0; i < 80000; ++i) { + refws->mutableX(0)[i] = double(i) * 0.3 + 8080.0; + refws->mutableY(0)[i] = double(i) * double(i); + } + + ar.initialize(); + ar.setProperty("InputWorkspace", inpws); + ar.setProperty("OutputWorkspace", "NewBackground"); + ar.setProperty("ReferenceWorkspace", refws); + ar.setProperty("Options", "AddRegion"); + ar.setProperty("LowerBound", 8000.0); + ar.setProperty("UpperBound", 16000.0); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("Background2"); + AnalysisDataService::Instance().remove("RefBackground"); + } + + void testPerformanceWS() { ar.execute(); } + +private: + ProcessBackground ar; +}; + +// Performance test for Simple Background Generation +class ProcessBackgroundSBGTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static ProcessBackgroundSBGTestPerformance *createSuite() { + return new ProcessBackgroundSBGTestPerformance(); + } + + static void destroySuite(ProcessBackgroundSBGTestPerformance *suite) { + delete suite; + } + + void setUp() override { + auto inpws = createInputWS("DiffractionData1", 1000000, 1000000); + for (size_t i = 0; i < 1000000; ++i) { + inpws->mutableX(0)[i] = double(i); + inpws->mutableY(0)[i] = double(i) * double(i); + } + + MersenneTwister mt(1234, 0.0, 1000000.0); + std::vector<double> bkgdpts(10000); + for (auto it = bkgdpts.begin(); it != bkgdpts.end(); it++) { + *it = mt.nextValue(); + } + + sbg.initialize(); + sbg.setProperty("InputWorkspace", inpws); + sbg.setProperty("OutputWorkspace", "SelectedBackgroundPoints"); + sbg.setProperty("Options", "SelectBackgroundPoints"); + sbg.setProperty("BackgroundPointSelectMode", + "Input Background Points Only"); + sbg.setProperty("SelectionMode", "FitGivenDataPoints"); + sbg.setProperty("BackgroundType", "Polynomial"); + sbg.setProperty("BackgroundPoints", bkgdpts); + sbg.setProperty("WorkspaceIndex", 0); + sbg.setProperty("NoiseTolerance", 100.0); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("DiffractionData1"); + } + + void testPerformanceWS() { sbg.execute(); } + +private: + ProcessBackground sbg; +}; + +// Performance test for Select Background From Input Function +class ProcessBackgroundSBFIFTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static ProcessBackgroundSBFIFTestPerformance *createSuite() { + return new ProcessBackgroundSBFIFTestPerformance(); + } + + static void destroySuite(ProcessBackgroundSBFIFTestPerformance *suite) { + delete suite; + } + + void setUp() override { + auto dataws = createInputWS("DiffractionData2", 50000, 50000); + for (size_t i = 0; i < 50000; ++i) { + dataws->mutableX(0)[i] = double(i); + dataws->mutableY(0)[i] = + double(i) * double(i) + sin(double(i) / 180. * 3.14); + } + + // Create background function + TableWorkspace_sptr functablews = boost::make_shared<TableWorkspace>(); + functablews->addColumn("str", "Name"); + functablews->addColumn("double", "Value"); + TableRow row0 = functablews->appendRow(); + row0 << "A0" << 0.; + TableRow row1 = functablews->appendRow(); + row1 << "A1" << 0.; + TableRow row2 = functablews->appendRow(); + row2 << "A2" << 1.; + AnalysisDataService::Instance().addOrReplace("BackgroundParameters", + functablews); + + // Create and set up algorithm + sbfif.initialize(); + sbfif.setProperty("InputWorkspace", dataws); + sbfif.setProperty("WorkspaceIndex", 0); + sbfif.setProperty("OutputWorkspace", "SelectedBackgroundPoints2"); + sbfif.setProperty("Options", "SelectBackgroundPoints"); + sbfif.setProperty("BackgroundType", "Polynomial"); + sbfif.setProperty("SelectionMode", "UserFunction"); + sbfif.setProperty("BackgroundTableWorkspace", functablews); + sbfif.setProperty("OutputBackgroundParameterWorkspace", + "OutBackgroundParameters"); + sbfif.setProperty("UserBackgroundWorkspace", "VisualWS"); + sbfif.setProperty("OutputBackgroundType", "Chebyshev"); + sbfif.setProperty("OutputBackgroundOrder", 6); + sbfif.setProperty("NoiseTolerance", 0.25); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("DiffractionData2"); + AnalysisDataService::Instance().remove("BackgroundParameters"); + } + + void testPerformanceWS() { sbfif.execute(); } + +private: + ProcessBackground sbfif; }; #endif /* MANTID_ALGORITHMS_PROCESSBACKGROUNDTEST_H_ */ diff --git a/Framework/CurveFitting/test/HistogramDomainCreatorTest.h b/Framework/CurveFitting/test/HistogramDomainCreatorTest.h index dbac9d0db211a05a6e7fa6cd871e7252356b4c14..6cde3b1409032953a83fe3aa02165d3aabc7c499 100644 --- a/Framework/CurveFitting/test/HistogramDomainCreatorTest.h +++ b/Framework/CurveFitting/test/HistogramDomainCreatorTest.h @@ -83,7 +83,7 @@ public: TS_ASSERT_EQUALS(values->size(), 10); TS_ASSERT_EQUALS(ws->blocksize(), 10); auto &h = dynamic_cast<FunctionDomain1DHistogram &>(*domain); - auto &x = ws->readX(0); + auto &x = ws->x(0); for (size_t j = 0; j < 10; ++j) { TS_ASSERT_EQUALS(h[j], x[j + 1]); } @@ -187,9 +187,9 @@ public: "fit_Workspace"); TS_ASSERT(outWS); - auto &y = outWS->readY(0); - auto &f = outWS->readY(1); - auto &d = outWS->readY(2); + auto &y = outWS->y(0); + auto &f = outWS->y(1); + auto &d = outWS->y(2); for (size_t i = 0; i < y.size(); ++i) { TS_ASSERT_DELTA(y[i], f[i], 1e-5); TS_ASSERT_DELTA(d[i], 0.0, 1e-5); @@ -309,9 +309,9 @@ public: "fit_Workspace"); TS_ASSERT(outWS); - auto &y = outWS->readY(0); - auto &f = outWS->readY(1); - auto &d = outWS->readY(2); + auto &y = outWS->y(0); + auto &f = outWS->y(1); + auto &d = outWS->y(2); for (size_t i = 0; i < y.size(); ++i) { TS_ASSERT_DELTA(y[i], f[i], 1e-5); TS_ASSERT_DELTA(d[i], 0.0, 1e-5); @@ -337,9 +337,9 @@ public: "fit_Workspace"); TS_ASSERT(outWS); - auto &y = outWS->readY(0); - auto &f = outWS->readY(1); - auto &d = outWS->readY(2); + auto &y = outWS->y(0); + auto &f = outWS->y(1); + auto &d = outWS->y(2); for (size_t i = 0; i < y.size(); ++i) { TS_ASSERT_DELTA(y[i], f[i], 1e-5); TS_ASSERT_DELTA(d[i], 0.0, 1e-5); @@ -366,9 +366,9 @@ public: "fit_Workspace"); TS_ASSERT(outWS); - auto &y = outWS->readY(0); - auto &f = outWS->readY(1); - auto &d = outWS->readY(2); + auto &y = outWS->y(0); + auto &f = outWS->y(1); + auto &d = outWS->y(2); for (size_t i = 0; i < y.size(); ++i) { TS_ASSERT_DELTA(y[i], f[i], 1e-5); TS_ASSERT_DELTA(d[i], 0.0, 1e-5); @@ -400,9 +400,9 @@ public: "fit_Workspace"); TS_ASSERT(outWS); - auto &y = outWS->readY(0); - auto &f = outWS->readY(1); - auto &d = outWS->readY(2); + auto &y = outWS->y(0); + auto &f = outWS->y(1); + auto &d = outWS->y(2); for (size_t i = 0; i < y.size(); ++i) { TS_ASSERT_DELTA(y[i], f[i], 1e-5); @@ -444,8 +444,8 @@ private: ws2->initialize(2, nx, ny); for (size_t is = 0; is < ws2->getNumberHistograms(); ++is) { - Mantid::MantidVec &x = ws2->dataX(is); - Mantid::MantidVec &y = ws2->dataY(is); + auto &x = ws2->mutableX(is); + auto &y = ws2->mutableY(is); for (size_t i = 0; i < ws2->blocksize(); ++i) { x[i] = 0.1 * double(i) + 0.01 * double(is); y[i] = (10.0 + double(is)) * exp(-(x[i]) / (0.5 * (1 + double(is)))); @@ -464,9 +464,9 @@ private: double x1 = 1.0; double dx = (x1 - x0) / static_cast<double>(ny); ws->initialize(1, nx, ny); - Mantid::MantidVec &x = ws->dataX(0); - Mantid::MantidVec &y = ws->dataY(0); - Mantid::MantidVec &e = ws->dataE(0); + auto &x = ws->mutableX(0); + auto &y = ws->mutableY(0); + auto &e = ws->mutableE(0); x.front() = x0; for (size_t i = 0; i < ny; ++i) { double xl = x0 + dx * double(i); diff --git a/Framework/DataHandling/inc/MantidDataHandling/LoadILLTOF.h b/Framework/DataHandling/inc/MantidDataHandling/LoadILLTOF.h index f9b1124cd7da133e5470a4f5865b870295d9127e..c20363e1bc7961d61b8a97bb028447bd99b8509e 100644 --- a/Framework/DataHandling/inc/MantidDataHandling/LoadILLTOF.h +++ b/Framework/DataHandling/inc/MantidDataHandling/LoadILLTOF.h @@ -7,6 +7,8 @@ #include "MantidAPI/IFileLoader.h" #include "MantidNexus/NexusClasses.h" #include "MantidDataHandling/LoadHelper.h" +#include "MantidGeometry/IDTypes.h" +#include "MantidAPI/Progress.h" namespace Mantid { namespace DataHandling { @@ -76,6 +78,9 @@ private: loadDataIntoTheWorkSpace(NeXus::NXEntry &entry, const std::vector<std::vector<int>> &, int vanaCalculatedDetectorElasticPeakPosition = -1); + void loadSpectra(size_t &spec, size_t numberOfMonitors, size_t numberOfTubes, + std::vector<Mantid::detid_t> &detectorIDs, NeXus::NXInt data, + Mantid::API::Progress progress); void runLoadInstrument(); diff --git a/Framework/DataHandling/inc/MantidDataHandling/LoadLLB.h b/Framework/DataHandling/inc/MantidDataHandling/LoadLLB.h index 23bc18daa81c2befa92d3409761d8dd7b71b9674..2f815b5469af16e950fc179b5d14f61ad8dd2f6a 100644 --- a/Framework/DataHandling/inc/MantidDataHandling/LoadLLB.h +++ b/Framework/DataHandling/inc/MantidDataHandling/LoadLLB.h @@ -5,6 +5,7 @@ #include "MantidAPI/IFileLoader.h" #include "MantidNexus/NexusClasses.h" #include "MantidDataHandling/LoadHelper.h" +#include "MantidHistogramData/Histogram.h" namespace Mantid { namespace DataHandling { @@ -55,7 +56,7 @@ private: void loadTimeDetails(NeXus::NXEntry &entry); void loadDataIntoTheWorkSpace(NeXus::NXEntry &); int getDetectorElasticPeakPosition(const NeXus::NXFloat &); - std::vector<double> getTimeBinning(int, double); + void setTimeBinning(HistogramData::HistogramX &histX, int, double); /// Calculate error for y static double calculateError(double in) { return sqrt(in); } void loadExperimentDetails(NeXus::NXEntry &); diff --git a/Framework/DataHandling/src/GroupDetectors.cpp b/Framework/DataHandling/src/GroupDetectors.cpp index 1c060c3e3dfb913848b612459e94e9749f2fa4b6..53cb496725bea49ae8931ed0ab79277190730134 100644 --- a/Framework/DataHandling/src/GroupDetectors.cpp +++ b/Framework/DataHandling/src/GroupDetectors.cpp @@ -1,9 +1,10 @@ //---------------------------------------------------------------------- // Includes //---------------------------------------------------------------------- -#include "MantidDataHandling/GroupDetectors.h" #include "MantidAPI/CommonBinsValidator.h" #include "MantidAPI/WorkspaceOpOverloads.h" +#include "MantidDataHandling/GroupDetectors.h" +#include "MantidHistogramData/HistogramMath.h" #include "MantidKernel/ArrayProperty.h" #include <set> #include <numeric> @@ -82,16 +83,15 @@ void GroupDetectors::exec() { return; } - const size_t vectorSize = WS->blocksize(); - const specnum_t firstIndex = static_cast<specnum_t>(indexList[0]); auto &firstSpectrum = WS->getSpectrum(firstIndex); - MantidVec &firstY = WS->dataY(firstIndex); - setProperty("ResultIndex", firstIndex); // loop over the spectra to group Progress progress(this, 0.0, 1.0, static_cast<int>(indexList.size() - 1)); + + auto outputHisto = firstSpectrum.histogram(); + for (size_t i = 0; i < indexList.size() - 1; ++i) { // The current spectrum const size_t currentIndex = indexList[i + 1]; @@ -101,24 +101,17 @@ void GroupDetectors::exec() { firstSpectrum.addDetectorIDs(spec.getDetectorIDs()); // Add up all the Y spectra and store the result in the first one - auto fEit = firstSpectrum.dataE().begin(); - auto Yit = spec.dataY().begin(); - auto Eit = spec.dataE().begin(); - for (auto fYit = firstY.begin(); fYit != firstY.end(); - ++fYit, ++fEit, ++Yit, ++Eit) { - *fYit += *Yit; - // Assume 'normal' (i.e. Gaussian) combination of errors - *fEit = sqrt((*fEit) * (*fEit) + (*Eit) * (*Eit)); - } + outputHisto += spec.histogram(); // Now zero the now redundant spectrum and set its spectraNo to indicate // this (using -1) - spec.dataY().assign(vectorSize, 0.0); - spec.dataE().assign(vectorSize, 0.0); + spec.clearData(); spec.setSpectrumNo(-1); spec.clearDetectorIDs(); progress.report(); } + + firstSpectrum.setHistogram(outputHisto); } } // namespace DataHandling diff --git a/Framework/DataHandling/src/ImggAggregateWavelengths.cpp b/Framework/DataHandling/src/ImggAggregateWavelengths.cpp index 886dc9558e90a9789ecddb5658445d1619014b05..3b8d5948b6ab3a4abed85ba54449baa7b25199ec 100644 --- a/Framework/DataHandling/src/ImggAggregateWavelengths.cpp +++ b/Framework/DataHandling/src/ImggAggregateWavelengths.cpp @@ -778,10 +778,7 @@ void ImggAggregateWavelengths::aggImage(API::MatrixWorkspace_sptr accum, } for (size_t row = 0; row < sizeY; row++) { - auto &dataY = accum->dataY(row); - const auto &dataYIn = toAdd->readY(row); - std::transform(dataY.begin(), dataY.end(), dataYIn.cbegin(), dataY.begin(), - std::plus<double>()); + accum->mutableY(row) += toAdd->y(row); } } diff --git a/Framework/DataHandling/src/LoadAscii.cpp b/Framework/DataHandling/src/LoadAscii.cpp index a9fd1c471f847cd8248d4aefbfac7d9363feb99e..24e0a47913934a66585e433c9cbe5ab8329cc368 100644 --- a/Framework/DataHandling/src/LoadAscii.cpp +++ b/Framework/DataHandling/src/LoadAscii.cpp @@ -199,11 +199,14 @@ API::Workspace_sptr LoadAscii::readData(std::ifstream &file) const { } for (size_t i = 0; i < numSpectra; ++i) { - spectra[i].dataX().push_back(values[0]); - spectra[i].dataY().push_back(values[i * 2 + 1]); + auto hist = spectra[i].histogram(); + hist.resize(hist.size() + 1); + hist.mutableX().back() = values[0]; + hist.mutableY().back() = values[i * 2 + 1]; if (haveErrors) { - spectra[i].dataE().push_back(values[i * 2 + 2]); + hist.mutableE().back() = values[i * 2 + 2]; } + spectra[i].setHistogram(hist); } if (haveXErrors) { // Note: we only have X errors with 4-column files. @@ -231,16 +234,8 @@ API::Workspace_sptr LoadAscii::readData(std::ifstream &file) const { } for (size_t i = 0; i < numSpectra; ++i) { - localWorkspace->dataX(i) = spectra[i].dataX(); - localWorkspace->dataY(i) = spectra[i].dataY(); - /* If Y or E errors are not there, DON'T copy across as the 'spectra' - vectors - have not been filled above. The workspace will by default have vectors of - the right length filled with zeroes. */ - if (haveErrors) - localWorkspace->dataE(i) = spectra[i].dataE(); - if (haveXErrors) - localWorkspace->setSharedDx(i, spectra[i].sharedDx()); + localWorkspace->setHistogram(i, spectra[i].histogram()); + // Just have spectrum number start at 1 and count up localWorkspace->getSpectrum(i).setSpectrumNo(static_cast<specnum_t>(i) + 1); } diff --git a/Framework/DataHandling/src/LoadAscii2.cpp b/Framework/DataHandling/src/LoadAscii2.cpp index b26f34512db616d1cf57abd4d50fd268fc3cd07b..e5ccb44c41b46c8b3b262c1f4f4c205941c92a1e 100644 --- a/Framework/DataHandling/src/LoadAscii2.cpp +++ b/Framework/DataHandling/src/LoadAscii2.cpp @@ -5,6 +5,7 @@ #include "MantidAPI/RegisterFileLoader.h" #include "MantidAPI/Run.h" #include "MantidAPI/WorkspaceFactory.h" +#include "MantidHistogramData/HistogramMath.h" #include "MantidKernel/BoundedValidator.h" #include "MantidKernel/ListValidator.h" #include <MantidKernel/StringTokenizer.h> @@ -199,12 +200,12 @@ void LoadAscii2::writeToWorkspace(API::MatrixWorkspace_sptr &localWorkspace, } for (size_t i = 0; i < numSpectra; ++i) { - localWorkspace->dataX(i) = m_spectra[i].readX(); - localWorkspace->dataY(i) = m_spectra[i].readY(); + localWorkspace->setSharedX(i, m_spectra[i].sharedX()); + localWorkspace->setSharedY(i, m_spectra[i].sharedY()); // if E or DX are ommitted they're implicitly initalised as 0 if (m_baseCols == 4 || m_baseCols == 3) { // E in file - localWorkspace->dataE(i) = m_spectra[i].readE(); + localWorkspace->setSharedE(i, m_spectra[i].sharedE()); } // DX could be NULL localWorkspace->setSharedDx(i, m_spectra[i].sharedDx()); @@ -420,7 +421,7 @@ void LoadAscii2::processHeader(std::ifstream &file) { } /** -* Check if the file has been found to inconsistantly include spectra IDs +* Check if the file has been found to inconsistently include spectra IDs * @param[in] columns : the columns of values in the current line of data */ void LoadAscii2::addToCurrentSpectra(std::list<std::string> &columns) { @@ -428,29 +429,34 @@ void LoadAscii2::addToCurrentSpectra(std::list<std::string> &columns) { m_spectraStart = false; fillInputValues(values, columns); // add X and Y - m_curSpectra->dataX().push_back(values[0]); - m_curSpectra->dataY().push_back(values[1]); + auto histo = m_curSpectra->histogram(); + histo.resize(histo.size() + 1); + + histo.mutableX().back() = values[0]; + histo.mutableY().back() = values[1]; + // check for E and DX switch (m_baseCols) { // if only 2 columns X and Y in file, E = 0 is implicit when constructing // workspace, omit DX case 3: { // E in file, include it, omit DX - m_curSpectra->dataE().push_back(values[2]); + histo.mutableE().back() = values[2]; break; } case 4: { // E and DX in file, include both - m_curSpectra->dataE().push_back(values[2]); + histo.mutableE().back() = values[2]; m_curDx.push_back(values[3]); break; } } + m_curSpectra->setHistogram(histo); m_curBins++; } /** -* Check if the file has been found to incosistantly include spectra IDs +* Check if the file has been found to inconsistently include spectra IDs * @param[in] cols : the number of columns in the current line of data */ void LoadAscii2::checkLineColumns(const size_t &cols) const { @@ -499,11 +505,12 @@ void LoadAscii2::newSpectra() { if (m_curSpectra) { size_t specSize = m_curSpectra->size(); if (specSize > 0 && specSize == m_lastBins) { - if (m_curSpectra->readX().size() == m_curDx.size()) + if (m_curSpectra->x().size() == m_curDx.size()) m_curSpectra->setPointStandardDeviations(std::move(m_curDx)); m_spectra.push_back(*m_curSpectra); } delete m_curSpectra; + m_curSpectra = nullptr; } m_curSpectra = @@ -521,15 +528,15 @@ void LoadAscii2::newSpectra() { * @return True if the line should be skipped */ bool LoadAscii2::skipLine(const std::string &line, bool header) const { - // Comments are skipped, Empty actually means somehting and shouldn't be + // Comments are skipped, Empty actually means something and shouldn't be // skipped // just checking the comment's first character should be ok as comment - // cahracters can't be numeric at all, so they can't really be confused + // characters can't be numeric at all, so they can't really be confused return ((line.empty() && header) || line.at(0) == m_comment.at(0)); } /** -* Return true if the line doesn't start wiht a valid character. +* Return true if the line doesn't start with a valid character. * @param[in] line :: The line to be checked * @return :: True if the line doesn't start with a valid character. */ diff --git a/Framework/DataHandling/src/LoadCalFile.cpp b/Framework/DataHandling/src/LoadCalFile.cpp index 90d05c69649d20cbe62d251c214bdbe183e74e16..d41a66d19ec8f33529041582b59cb2345856cb97 100644 --- a/Framework/DataHandling/src/LoadCalFile.cpp +++ b/Framework/DataHandling/src/LoadCalFile.cpp @@ -310,10 +310,10 @@ void LoadCalFile::readCalFile(const std::string &calFileName, if (select <= 0) { // Not selected, then mask this detector maskWS->maskWorkspaceIndex(wi); - maskWS->dataY(wi)[0] = 1.0; + maskWS->mutableY(wi)[0] = 1.0; } else { // Selected, set the value to be 0 - maskWS->dataY(wi)[0] = 0.0; + maskWS->mutableY(wi)[0] = 0.0; if (!hasUnmasked) hasUnmasked = true; } diff --git a/Framework/DataHandling/src/LoadEventNexus.cpp b/Framework/DataHandling/src/LoadEventNexus.cpp index 153b07e355ec093850659a9ee827e1e936c894e0..9244311039d023f280653b4baed1f61d002b1fff 100644 --- a/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Framework/DataHandling/src/LoadEventNexus.cpp @@ -488,13 +488,13 @@ public: // Abort if anything failed if (m_loadError) { - prog->reportIncrement(4, entry_name + ": skipping"); delete[] m_event_id; delete[] m_event_time_of_flight; if (m_have_weight) { delete[] m_event_weight; } delete event_index_ptr; + return; } @@ -1911,9 +1911,10 @@ void LoadEventNexus::runLoadMonitorsAsEvents(API::Progress *const prog) { // Note the reuse of the m_ws member variable below. Means I need to grab a // copy of its current value. auto dataWS = m_ws; - m_ws = boost::make_shared< - EventWorkspaceCollection>(); // Algorithm currently relies on an - // object-level workspace ptr + m_ws = boost::make_shared<EventWorkspaceCollection>(); // Algorithm + // currently relies + // on an + // object-level workspace ptr // add filename m_ws->mutableRun().addProperty("Filename", m_filename); diff --git a/Framework/DataHandling/src/LoadILLTOF.cpp b/Framework/DataHandling/src/LoadILLTOF.cpp index 5649733dae78e57fa7d49263140eea3f81a1e701..2b566758da196c905ab23ba42e5108a7b5b80227 100644 --- a/Framework/DataHandling/src/LoadILLTOF.cpp +++ b/Framework/DataHandling/src/LoadILLTOF.cpp @@ -17,6 +17,7 @@ namespace DataHandling { using namespace Kernel; using namespace API; using namespace NeXus; +using namespace HistogramData; DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadILLTOF) @@ -525,71 +526,38 @@ void LoadILLTOF::loadDataIntoTheWorkSpace( 1e6; // microsecs // Calculate the real tof (t1+t2) put it in tof array - std::vector<double> detectorTofBins(m_numberOfChannels + 1); + auto &X0 = m_localWorkspace->mutableX(0); for (size_t i = 0; i < m_numberOfChannels + 1; ++i) { - detectorTofBins[i] = - theoreticalElasticTOF + - m_channelWidth * - static_cast<double>(static_cast<int>(i) - - calculatedDetectorElasticPeakPosition) - - m_channelWidth / - 2; // to make sure the bin is in the middle of the elastic peak + X0[i] = theoreticalElasticTOF + + m_channelWidth * + static_cast<double>(static_cast<int>(i) - + calculatedDetectorElasticPeakPosition) - + m_channelWidth / + 2; // to make sure the bin is in the middle of the elastic peak } g_log.information() << "T1+T2 : Theoretical = " << theoreticalElasticTOF; - g_log.information() - << " :: Calculated bin = [" - << detectorTofBins[calculatedDetectorElasticPeakPosition] << "," - << detectorTofBins[calculatedDetectorElasticPeakPosition + 1] << "]\n"; + g_log.information() << " :: Calculated bin = [" + << X0[calculatedDetectorElasticPeakPosition] << "," + << X0[calculatedDetectorElasticPeakPosition + 1] << "]\n"; // The binning for monitors is considered the same as for detectors size_t spec = 0; auto const &instrument = m_localWorkspace->getInstrument(); - std::vector<detid_t> monitorIDs = instrument->getMonitors(); for (const auto &monitor : monitors) { - m_localWorkspace->dataX(spec) - .assign(detectorTofBins.begin(), detectorTofBins.end()); - // Assign Y - m_localWorkspace->dataY(spec).assign(monitor.begin(), monitor.end()); - // Assign Error - MantidVec &E = m_localWorkspace->dataE(spec); - std::transform(monitor.begin(), monitor.end(), E.begin(), - LoadILLTOF::calculateError); - m_localWorkspace->getSpectrum(spec).setDetectorID(monitorIDs[spec]); - ++spec; + m_localWorkspace->setHistogram(spec++, m_localWorkspace->binEdges(0), + Counts(monitor.begin(), monitor.end())); } std::vector<detid_t> detectorIDs = instrument->getDetectorIDs(true); - - // Assign calculated bins to first X axis - size_t firstSpec = spec; size_t numberOfMonitors = monitors.size(); - m_localWorkspace->dataX(firstSpec) - .assign(detectorTofBins.begin(), detectorTofBins.end()); Progress progress(this, 0, 1, m_numberOfTubes * m_numberOfPixelsPerTube); - for (size_t i = 0; i < m_numberOfTubes; ++i) { - for (size_t j = 0; j < m_numberOfPixelsPerTube; ++j) { - if (spec > firstSpec) { - // just copy the time binning axis to every spectra - m_localWorkspace->dataX(spec) = m_localWorkspace->readX(firstSpec); - } - // Assign Y - int *data_p = &data(static_cast<int>(i), static_cast<int>(j), 0); - m_localWorkspace->dataY(spec).assign(data_p, data_p + m_numberOfChannels); - // Assign Error - MantidVec &E = m_localWorkspace->dataE(spec); - std::transform(data_p, data_p + m_numberOfChannels, E.begin(), - LoadILLTOF::calculateError); - m_localWorkspace->getSpectrum(spec) - .setDetectorID(detectorIDs[spec - numberOfMonitors]); - ++spec; - progress.report(); - } - } + loadSpectra(spec, numberOfMonitors, m_numberOfTubes, detectorIDs, data, + progress); g_log.debug() << "Loading data into the workspace: DONE!\n"; @@ -608,24 +576,37 @@ void LoadILLTOF::loadDataIntoTheWorkSpace( Progress progressRosace(this, 0, 1, numberOfTubes * m_numberOfPixelsPerTube); - for (size_t i = 0; i < numberOfTubes; ++i) { - for (size_t j = 0; j < m_numberOfPixelsPerTube; ++j) { - // just copy the time binning axis to every spectra - m_localWorkspace->dataX(spec) = m_localWorkspace->readX(firstSpec); - - // Assign Y - int *data_p = &dataRosace(static_cast<int>(i), static_cast<int>(j), 0); - m_localWorkspace->dataY(spec) - .assign(data_p, data_p + m_numberOfChannels); - - // Assign Error - MantidVec &E = m_localWorkspace->dataE(spec); - std::transform(data_p, data_p + m_numberOfChannels, E.begin(), - LoadILLTOF::calculateError); - - ++spec; - progressRosace.report(); - } + + loadSpectra(spec, numberOfMonitors, numberOfTubes, detectorIDs, dataRosace, + progressRosace); + } +} + +/** + * Loops over all the pixels and loads the correct spectra. Called for each set + * of detector types in the workspace. + * + * @param spec The current spectrum id + * @param numberOfMonitors The number of monitors in the workspace + * @param numberOfTubes The number of detector tubes in the workspace + * @param detectorIDs A list of all of the detector IDs + * @param data The NeXus data to load into the workspace + * @param progress The progress monitor (different + */ +void LoadILLTOF::loadSpectra(size_t &spec, size_t numberOfMonitors, + size_t numberOfTubes, + std::vector<detid_t> &detectorIDs, NXInt data, + Progress progress) { + for (size_t i = 0; i < numberOfTubes; ++i) { + for (size_t j = 0; j < m_numberOfPixelsPerTube; ++j) { + int *data_p = &data(static_cast<int>(i), static_cast<int>(j), 0); + m_localWorkspace->setHistogram( + spec, m_localWorkspace->binEdges(0), + Counts(data_p, data_p + m_numberOfChannels)); + m_localWorkspace->getSpectrum(spec) + .setDetectorID(detectorIDs[spec - numberOfMonitors]); + spec++; + progress.report(); } } } diff --git a/Framework/DataHandling/src/LoadISISNexus2.cpp b/Framework/DataHandling/src/LoadISISNexus2.cpp index f72d533e9e9146af0a1ae32d48860c1e12b01ed5..aa2b35fa6c34afcbdcee943cb59fb872c6515050 100644 --- a/Framework/DataHandling/src/LoadISISNexus2.cpp +++ b/Framework/DataHandling/src/LoadISISNexus2.cpp @@ -70,6 +70,7 @@ DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadISISNexus2) using namespace Kernel; using namespace API; using namespace NeXus; +using namespace HistogramData; using std::size_t; /// Empty default constructor @@ -290,8 +291,8 @@ void LoadISISNexus2::exec() { // Get the X data NXFloat timeBins = entry.openNXFloat("detector_1/time_of_flight"); timeBins.load(); - m_tof_data = boost::make_shared<HistogramData::HistogramX>( - timeBins(), timeBins() + x_length); + m_tof_data = + boost::make_shared<HistogramX>(timeBins(), timeBins() + x_length); } int64_t firstentry = (m_entrynumber > 0) ? m_entrynumber : 1; loadPeriodData(firstentry, entry, local_workspace, m_load_selected_spectra); @@ -786,10 +787,11 @@ void LoadISISNexus2::loadPeriodData( NXInt mondata = monitor.openIntData(); m_progress->report("Loading monitor"); mondata.load(1, static_cast<int>(period - 1)); // TODO this is just wrong - MantidVec &Y = local_workspace->dataY(hist_index); - Y.assign(mondata(), mondata() + m_monBlockInfo.getNumberOfChannels()); - MantidVec &E = local_workspace->dataE(hist_index); - std::transform(Y.begin(), Y.end(), E.begin(), dblSqrt); + NXFloat timeBins = monitor.openNXFloat("time_of_flight"); + timeBins.load(); + local_workspace->setHistogram( + hist_index, BinEdges(timeBins(), timeBins() + timeBins.dim0()), + Counts(mondata(), mondata() + m_monBlockInfo.getNumberOfChannels())); if (update_spectra2det_mapping) { // local_workspace->getAxis(1)->setValue(hist_index, @@ -800,11 +802,6 @@ void LoadISISNexus2::loadPeriodData( m_spec2det_map.getDetectorIDsForSpectrumNo(specNum)); spec.setSpectrumNo(specNum); } - - NXFloat timeBins = monitor.openNXFloat("time_of_flight"); - timeBins.load(); - local_workspace->dataX(hist_index) - .assign(timeBins(), timeBins() + timeBins.dim0()); hist_index++; } else if (m_have_detector) { NXData nxdata = entry.openNXData("detector_1"); @@ -883,14 +880,10 @@ void LoadISISNexus2::loadBlock(NXDataSetTyped<int> &data, int64_t blocksize, int64_t final(hist + blocksize); while (hist < final) { m_progress->report("Loading data"); - MantidVec &Y = local_workspace->dataY(hist); - Y.assign(data_start, data_end); + local_workspace->setHistogram(hist, BinEdges(m_tof_data), + Counts(data_start, data_end)); data_start += m_detBlockInfo.getNumberOfChannels(); data_end += m_detBlockInfo.getNumberOfChannels(); - MantidVec &E = local_workspace->dataE(hist); - std::transform(Y.begin(), Y.end(), E.begin(), dblSqrt); - // Populate the workspace. Loop starts from 1, hence i-1 - local_workspace->setX(hist, m_tof_data); if (m_load_selected_spectra) { // local_workspace->getAxis(1)->setValue(hist, // static_cast<specnum_t>(spec_num)); diff --git a/Framework/DataHandling/src/LoadLLB.cpp b/Framework/DataHandling/src/LoadLLB.cpp index 9e4f536e9accc46e3d833aabd9fc8fcfa5ba5460..85a91acad526e9f95d5aaa190111c42de2f8e635 100644 --- a/Framework/DataHandling/src/LoadLLB.cpp +++ b/Framework/DataHandling/src/LoadLLB.cpp @@ -19,6 +19,7 @@ namespace DataHandling { using namespace Kernel; using namespace API; using namespace NeXus; +using namespace HistogramData; DECLARE_NEXUS_FILELOADER_ALGORITHM(LoadLLB) @@ -166,30 +167,18 @@ void LoadLLB::loadDataIntoTheWorkSpace(NeXus::NXEntry &entry) { int calculatedDetectorElasticPeakPosition = getDetectorElasticPeakPosition(data); - std::vector<double> timeBinning = - getTimeBinning(calculatedDetectorElasticPeakPosition, m_channelWidth); - // Assign time bin to first X entry - m_localWorkspace->dataX(0).assign(timeBinning.begin(), timeBinning.end()); + setTimeBinning(m_localWorkspace->mutableX(0), + calculatedDetectorElasticPeakPosition, m_channelWidth); Progress progress(this, 0, 1, m_numberOfTubes * m_numberOfPixelsPerTube); size_t spec = 0; for (size_t i = 0; i < m_numberOfTubes; ++i) { for (size_t j = 0; j < m_numberOfPixelsPerTube; ++j) { - if (spec > 0) { - // just copy the time binning axis to every spectra - m_localWorkspace->dataX(spec) = m_localWorkspace->readX(0); - } - // Assign Y float *data_p = &data(static_cast<int>(i), static_cast<int>(j)); - m_localWorkspace->dataY(spec).assign(data_p, data_p + m_numberOfChannels); - - // Assign Error - MantidVec &E = m_localWorkspace->dataE(spec); - std::transform(data_p, data_p + m_numberOfChannels, E.begin(), - LoadLLB::calculateError); - - ++spec; + m_localWorkspace->setHistogram( + spec++, m_localWorkspace->binEdges(0), + Counts(data_p, data_p + m_numberOfChannels)); progress.report(); } } @@ -237,8 +226,8 @@ int LoadLLB::getDetectorElasticPeakPosition(const NeXus::NXFloat &data) { return calculatedDetectorElasticPeakPosition; } -std::vector<double> LoadLLB::getTimeBinning(int elasticPeakPosition, - double channelWidth) { +void LoadLLB::setTimeBinning(HistogramX &histX, int elasticPeakPosition, + double channelWidth) { double l1 = m_loader.getL1(m_localWorkspace); double l2 = m_loader.getL2(m_localWorkspace); @@ -253,17 +242,14 @@ std::vector<double> LoadLLB::getTimeBinning(int elasticPeakPosition, g_log.debug() << "l2 : " << l2 << '\n'; g_log.debug() << "theoreticalElasticTOF : " << theoreticalElasticTOF << '\n'; - std::vector<double> detectorTofBins(m_numberOfChannels + 1); - for (size_t i = 0; i < m_numberOfChannels + 1; ++i) { - detectorTofBins[i] = + histX[i] = theoreticalElasticTOF + channelWidth * static_cast<double>(static_cast<int>(i) - elasticPeakPosition) - channelWidth / 2; // to make sure the bin is in the middle of the elastic peak } - return detectorTofBins; } void LoadLLB::loadRunDetails(NXEntry &entry) { diff --git a/Framework/DataHandling/src/LoadMask.cpp b/Framework/DataHandling/src/LoadMask.cpp index 6544f336eb354bac7f9e8469a64d742aed68252d..36f8d26745769b678c90e77f34c21fd8803becdc 100644 --- a/Framework/DataHandling/src/LoadMask.cpp +++ b/Framework/DataHandling/src/LoadMask.cpp @@ -416,10 +416,7 @@ void LoadMask::processMaskOnDetectors( it = indexmap.find(detid); if (it != indexmap.end()) { size_t index = it->second; - if (tomask) - m_maskWS->dataY(index)[0] = 1; - else - m_maskWS->dataY(index)[0] = 0; + m_maskWS->mutableY(index)[0] = (tomask) ? 1 : 0; } else { g_log.warning() << "Pixel w/ ID = " << detid << " Cannot Be Located\n"; } @@ -580,10 +577,7 @@ void LoadMask::processMaskOnWorkspaceIndex(bool mask, << m_maskWS->getNumberHistograms() << '\n'; } else { // Finally set the masking; - if (mask) - m_maskWS->dataY(wsindex)[0] = 1.0; - else - m_maskWS->dataY(wsindex)[0] = 0.0; + m_maskWS->mutableY(wsindex)[0] = (mask) ? 1.0 : 0.0; } // IF-ELSE: ws index out of range } // IF-ELSE: spectrum No has an entry diff --git a/Framework/DataHandling/src/LoadMcStas.cpp b/Framework/DataHandling/src/LoadMcStas.cpp index cc379e0cf6416c4c74f07fa863f809007b9cec06..9c9d0ea293834c9c6b8f7c6665e8c1d7cc68d173 100644 --- a/Framework/DataHandling/src/LoadMcStas.cpp +++ b/Framework/DataHandling/src/LoadMcStas.cpp @@ -433,7 +433,8 @@ void LoadMcStas::readHistogramData( nxFile.closeData(); } - std::vector<double> axis1Values, axis2Values; + std::vector<double> axis1Values; + std::vector<double> axis2Values; nxFile.readData<double>(axis1Name, axis1Values); if (axis2Name.length() == 0) { axis2Name = nameAttrValueYLABEL; @@ -483,17 +484,17 @@ void LoadMcStas::readHistogramData( ws->replaceAxis(1, axis2); for (size_t wsIndex = 0; wsIndex < axis2Length; ++wsIndex) { - auto &dataY = ws->dataY(wsIndex); - auto &dataE = ws->dataE(wsIndex); - auto &dataX = ws->dataX(wsIndex); + auto &dataX = ws->mutableX(wsIndex); + auto &dataY = ws->mutableY(wsIndex); + auto &dataE = ws->mutableE(wsIndex); for (size_t j = 0; j < axis1Length; ++j) { // Data is stored in column-major order so we are translating to // row major for Mantid const size_t fileDataIndex = j * axis2Length + wsIndex; - dataY[j] = data[fileDataIndex]; dataX[j] = axis1Values[j]; + dataY[j] = data[fileDataIndex]; if (!errors.empty()) dataE[j] = errors[fileDataIndex]; } diff --git a/Framework/DataHandling/test/GroupDetectorsTest.h b/Framework/DataHandling/test/GroupDetectorsTest.h index eb63d4f8547d5e1d9f7ca4d5e0ff3fb85953fdab..4cc67d38032948633205828d9c4e8a65c7ed24c3 100644 --- a/Framework/DataHandling/test/GroupDetectorsTest.h +++ b/Framework/DataHandling/test/GroupDetectorsTest.h @@ -10,6 +10,7 @@ #include "MantidAPI/WorkspaceProperty.h" #include "MantidKernel/ArrayProperty.h" #include "MantidDataObjects/Workspace2D.h" +#include "MantidTestHelpers/HistogramDataTestHelper.h" #include "MantidKernel/UnitFactory.h" #include "MantidGeometry/Instrument.h" #include "MantidGeometry/Instrument/Detector.h" @@ -21,12 +22,9 @@ using namespace Mantid::Kernel; using namespace Mantid::API; using namespace Mantid::Geometry; using namespace Mantid::DataObjects; +using namespace Mantid::HistogramData; using Mantid::detid_t; using Mantid::specnum_t; -using Mantid::HistogramData::BinEdges; -using Mantid::HistogramData::Counts; -using Mantid::HistogramData::CountStandardDeviations; -using Mantid::HistogramData::LinearGenerator; class GroupDetectorsTest : public CxxTest::TestSuite { public: @@ -113,31 +111,33 @@ public: MatrixWorkspace_sptr outputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( "GroupTestWS"); - std::vector<double> tens{10, 11, 12, 13, 14, 15}; - std::vector<double> ones(5, 1.0); - std::vector<double> threes(5, 3.0); - std::vector<double> zeroes(5, 0.0); - TS_ASSERT_EQUALS(outputWS->dataX(0), tens); - TS_ASSERT_EQUALS(outputWS->dataY(0), threes); + const HistogramX tens{10, 11, 12, 13, 14, 15}; + const HistogramY yOnes(5, 1.0); + const HistogramE eOnes(5, 1.0); + const HistogramY threes(5, 3.0); + const HistogramY yZeroes(5, 0.0); + const HistogramE eZeroes(5, 0.0); + TS_ASSERT_EQUALS(outputWS->x(0), tens); + TS_ASSERT_EQUALS(outputWS->y(0), threes); for (int i = 0; i < 5; ++i) { - TS_ASSERT_DELTA(outputWS->dataE(0)[i], 1.7321, 0.0001); + TS_ASSERT_DELTA(outputWS->e(0)[i], 1.7321, 0.0001); } TS_ASSERT_EQUALS(outputWS->getSpectrum(0).getSpectrumNo(), 0); - TS_ASSERT_EQUALS(outputWS->dataX(1), tens); - TS_ASSERT_EQUALS(outputWS->dataY(1), ones); - TS_ASSERT_EQUALS(outputWS->dataE(1), ones); + TS_ASSERT_EQUALS(outputWS->x(1), tens); + TS_ASSERT_EQUALS(outputWS->y(1), yOnes); + TS_ASSERT_EQUALS(outputWS->e(1), eOnes); TS_ASSERT_EQUALS(outputWS->getSpectrum(1).getSpectrumNo(), 1); - TS_ASSERT_EQUALS(outputWS->dataX(2), tens); - TS_ASSERT_EQUALS(outputWS->dataY(2), zeroes); - TS_ASSERT_EQUALS(outputWS->dataE(2), zeroes); + TS_ASSERT_EQUALS(outputWS->x(2), tens); + TS_ASSERT_EQUALS(outputWS->y(2), yZeroes); + TS_ASSERT_EQUALS(outputWS->e(2), eZeroes); TS_ASSERT_EQUALS(outputWS->getSpectrum(2).getSpectrumNo(), -1); - TS_ASSERT_EQUALS(outputWS->dataX(3), tens); - TS_ASSERT_EQUALS(outputWS->dataY(3), zeroes); - TS_ASSERT_EQUALS(outputWS->dataE(3), zeroes); + TS_ASSERT_EQUALS(outputWS->x(3), tens); + TS_ASSERT_EQUALS(outputWS->y(3), yZeroes); + TS_ASSERT_EQUALS(outputWS->e(3), eZeroes); TS_ASSERT_EQUALS(outputWS->getSpectrum(3).getSpectrumNo(), -1); - TS_ASSERT_EQUALS(outputWS->dataX(4), tens); - TS_ASSERT_EQUALS(outputWS->dataY(4), ones); - TS_ASSERT_EQUALS(outputWS->dataE(4), ones); + TS_ASSERT_EQUALS(outputWS->x(4), tens); + TS_ASSERT_EQUALS(outputWS->y(4), yOnes); + TS_ASSERT_EQUALS(outputWS->e(4), eOnes); TS_ASSERT_EQUALS(outputWS->getSpectrum(4).getSpectrumNo(), 4); boost::shared_ptr<const IDetector> det; diff --git a/Framework/DataHandling/test/LoadAscii2Test.h b/Framework/DataHandling/test/LoadAscii2Test.h index 251f0c46b887cc394795f60b607c9b71a9ef1e35..547ba2e8bf34b5ebecdd383e2d6bb9f9dac32440 100644 --- a/Framework/DataHandling/test/LoadAscii2Test.h +++ b/Framework/DataHandling/test/LoadAscii2Test.h @@ -398,9 +398,9 @@ private: boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( WorkspaceFactory::Instance().create("Workspace2D", 5, 4, 4)); for (int i = 0; i < 5; i++) { - std::vector<double> &X = wsToSave->dataX(i); - std::vector<double> &Y = wsToSave->dataY(i); - std::vector<double> &E = wsToSave->dataE(i); + auto &X = wsToSave->mutableX(i); + auto &Y = wsToSave->mutableY(i); + auto &E = wsToSave->mutableE(i); for (int j = 0; j < 4; j++) { X[j] = 1.5 * j / 0.9; Y[j] = (i + 1) * (2. + 4. * X[j]); @@ -498,33 +498,33 @@ private: TS_ASSERT_EQUALS(outputWS->getNumberHistograms(), 5); TS_ASSERT_EQUALS(outputWS->blocksize(), 4); - TS_ASSERT_DELTA(outputWS->readX(0)[0], 0, 1e-6); - TS_ASSERT_DELTA(outputWS->readY(0)[0], 2, 1e-6); + TS_ASSERT_DELTA(outputWS->x(0)[0], 0, 1e-6); + TS_ASSERT_DELTA(outputWS->y(0)[0], 2, 1e-6); - TS_ASSERT_DELTA(outputWS->readX(0)[1], 1.666667, 1e-6); - TS_ASSERT_DELTA(outputWS->readY(0)[1], 8.666667, 1e-6); + TS_ASSERT_DELTA(outputWS->x(0)[1], 1.666667, 1e-6); + TS_ASSERT_DELTA(outputWS->y(0)[1], 8.666667, 1e-6); - TS_ASSERT_DELTA(outputWS->readX(1)[2], 3.333333, 1e-6); - TS_ASSERT_DELTA(outputWS->readY(1)[2], 30.66667, 1e-6); + TS_ASSERT_DELTA(outputWS->x(1)[2], 3.333333, 1e-6); + TS_ASSERT_DELTA(outputWS->y(1)[2], 30.66667, 1e-6); - TS_ASSERT_DELTA(outputWS->readX(3)[3], 5, 1e-6); - TS_ASSERT_DELTA(outputWS->readY(3)[3], 88, 1e-6); + TS_ASSERT_DELTA(outputWS->x(3)[3], 5, 1e-6); + TS_ASSERT_DELTA(outputWS->y(3)[3], 88, 1e-6); if (cols == 3 || cols == 4) { - TS_ASSERT_DELTA(outputWS->readE(0)[0], 1, 1e-6); + TS_ASSERT_DELTA(outputWS->e(0)[0], 1, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(0)[1], 1, 1e-6); + TS_ASSERT_DELTA(outputWS->e(0)[1], 1, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(1)[2], 1, 1e-6); + TS_ASSERT_DELTA(outputWS->e(1)[2], 1, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(3)[3], 1, 1e-6); + TS_ASSERT_DELTA(outputWS->e(3)[3], 1, 1e-6); } else { - TS_ASSERT_DELTA(outputWS->readE(0)[0], 0, 1e-6); + TS_ASSERT_DELTA(outputWS->e(0)[0], 0, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(0)[1], 0, 1e-6); + TS_ASSERT_DELTA(outputWS->e(0)[1], 0, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(1)[2], 0, 1e-6); + TS_ASSERT_DELTA(outputWS->e(1)[2], 0, 1e-6); - TS_ASSERT_DELTA(outputWS->readE(3)[3], 0, 1e-6); + TS_ASSERT_DELTA(outputWS->e(3)[3], 0, 1e-6); } if (cols == 4) { TS_ASSERT_DELTA(outputWS->dx(0)[0], 1, 1e-6); @@ -542,4 +542,79 @@ private: size_t m_testno; }; +class LoadAscii2TestPerformance : public CxxTest::TestSuite { +public: + void setUp() override { + setupFile(); + loadAlg.initialize(); + + TS_ASSERT_THROWS_NOTHING(loadAlg.setPropertyValue("Filename", filename)); + loadAlg.setPropertyValue("OutputWorkspace", outputName); + loadAlg.setPropertyValue("Separator", sep); + loadAlg.setPropertyValue("CustomSeparator", custsep); + loadAlg.setPropertyValue("CommentIndicator", comment); + + loadAlg.setRethrows(true); + } + + void testLoadAscii2Performance() { + TS_ASSERT_THROWS_NOTHING(loadAlg.execute()); + } + + void tearDown() override { + TS_ASSERT_THROWS_NOTHING(Poco::File(filename).remove()); + AnalysisDataService::Instance().remove(outputName); + } + +private: + LoadAscii2 loadAlg; + + const std::string outputName = "outWs"; + std::string filename; + + // Common saving/loading parameters + const std::string sep = "CSV"; + const std::string custsep = ""; + const std::string comment = "#"; + + void setupFile() { + constexpr int numVecs = 100; + constexpr int xyLen = 100; + + Mantid::DataObjects::Workspace2D_sptr wsToSave = + boost::dynamic_pointer_cast<Mantid::DataObjects::Workspace2D>( + WorkspaceFactory::Instance().create("Workspace2D", numVecs, xyLen, + xyLen)); + + const std::string name = "SaveAsciiWS"; + AnalysisDataService::Instance().add(name, wsToSave); + + SaveAscii2 save; + save.initialize(); + + save.initialize(); + TS_ASSERT_EQUALS(save.isInitialized(), true); + + const bool scientific = true; + + save.setPropertyValue("Filename", "testFile"); + save.setPropertyValue("InputWorkspace", name); + save.setPropertyValue("CommentIndicator", comment); + save.setPropertyValue("ScientificFormat", + boost::lexical_cast<std::string>(scientific)); + save.setPropertyValue("ColumnHeader", + boost::lexical_cast<std::string>(true)); + save.setPropertyValue("WriteXError", + boost::lexical_cast<std::string>(false)); + save.setPropertyValue("Separator", sep); + save.setPropertyValue("CustomSeparator", custsep); + save.setRethrows(true); + + TS_ASSERT_THROWS_NOTHING(save.execute()); + + AnalysisDataService::Instance().remove(name); + filename = save.getPropertyValue("Filename"); + } +}; + #endif // LOADASCIITEST_H_ diff --git a/Framework/DataHandling/test/LoadAsciiTest.h b/Framework/DataHandling/test/LoadAsciiTest.h index f696f777fdfe561ca370235161ca57237eee71fb..29bc2fa4e558fc2b3604873fcbf9537f825508d8 100644 --- a/Framework/DataHandling/test/LoadAsciiTest.h +++ b/Framework/DataHandling/test/LoadAsciiTest.h @@ -276,33 +276,33 @@ private: TS_ASSERT_EQUALS(outputWS->getNumberHistograms(), 1); TS_ASSERT_EQUALS(outputWS->blocksize(), 30); - TS_ASSERT_EQUALS(outputWS->readX(0)[0], 1.0); - TS_ASSERT_EQUALS(outputWS->readY(0)[0], 0.4577471236305); - TS_ASSERT_EQUALS(outputWS->readE(0)[0], 0.4583269753105); + TS_ASSERT_EQUALS(outputWS->x(0)[0], 1.0); + TS_ASSERT_EQUALS(outputWS->y(0)[0], 0.4577471236305); + TS_ASSERT_EQUALS(outputWS->e(0)[0], 0.4583269753105); - TS_ASSERT_EQUALS(outputWS->readX(0)[18], 19.0); - TS_ASSERT_EQUALS(outputWS->readY(0)[18], 0.4269539475692); - TS_ASSERT_EQUALS(outputWS->readE(0)[18], 0.7621692556536); + TS_ASSERT_EQUALS(outputWS->x(0)[18], 19.0); + TS_ASSERT_EQUALS(outputWS->y(0)[18], 0.4269539475692); + TS_ASSERT_EQUALS(outputWS->e(0)[18], 0.7621692556536); - TS_ASSERT_EQUALS(outputWS->readX(0)[29], 30.0); - TS_ASSERT_EQUALS(outputWS->readY(0)[29], 0.9277321695608); - TS_ASSERT_EQUALS(outputWS->readE(0)[29], 0.6603289895322); + TS_ASSERT_EQUALS(outputWS->x(0)[29], 30.0); + TS_ASSERT_EQUALS(outputWS->y(0)[29], 0.9277321695608); + TS_ASSERT_EQUALS(outputWS->e(0)[29], 0.6603289895322); } else { TS_ASSERT_EQUALS(outputWS->getNumberHistograms(), 1); TS_ASSERT_EQUALS(outputWS->blocksize(), 51); TS_ASSERT(!outputWS->sharedDx(0)); - TS_ASSERT_EQUALS(outputWS->readX(0)[0], 0.25); - TS_ASSERT_EQUALS(outputWS->readY(0)[0], 0.19104); - TS_ASSERT_EQUALS(outputWS->readE(0)[0], 0.0); + TS_ASSERT_EQUALS(outputWS->x(0)[0], 0.25); + TS_ASSERT_EQUALS(outputWS->y(0)[0], 0.19104); + TS_ASSERT_EQUALS(outputWS->e(0)[0], 0.0); - TS_ASSERT_EQUALS(outputWS->readX(0)[18], 0.34); - TS_ASSERT_EQUALS(outputWS->readY(0)[18], 0.1825); - TS_ASSERT_EQUALS(outputWS->readE(0)[18], 0.0); + TS_ASSERT_EQUALS(outputWS->x(0)[18], 0.34); + TS_ASSERT_EQUALS(outputWS->y(0)[18], 0.1825); + TS_ASSERT_EQUALS(outputWS->e(0)[18], 0.0); - TS_ASSERT_EQUALS(outputWS->readX(0)[50], 0.50); - TS_ASSERT_EQUALS(outputWS->readY(0)[50], 0.16611); - TS_ASSERT_EQUALS(outputWS->readE(0)[50], 0.0); + TS_ASSERT_EQUALS(outputWS->x(0)[50], 0.50); + TS_ASSERT_EQUALS(outputWS->y(0)[50], 0.16611); + TS_ASSERT_EQUALS(outputWS->e(0)[50], 0.0); } } }; diff --git a/Framework/DataHandling/test/LoadCalFileTest.h b/Framework/DataHandling/test/LoadCalFileTest.h index 18da332d651e251bb241b2e9353269d8e635384a..f5c96908b2384523e6132c95b100d1504ebb65cd 100644 --- a/Framework/DataHandling/test/LoadCalFileTest.h +++ b/Framework/DataHandling/test/LoadCalFileTest.h @@ -103,4 +103,55 @@ public: } }; +class LoadCalFileTestPerformance : public CxxTest::TestSuite { +public: + void setUp() override { + // Since we have no control over the cal file size + // instead we setup lots of load algorithms and run it + // multiple times to create a stable time for this test + loadAlgPtrArray.resize(numberOfIterations); + for (auto &vectorItem : loadAlgPtrArray) { + vectorItem = setupAlg(); + } + } + + void testLoadCalFilePerformance() { + for (int i = 0; i < numberOfIterations; i++) { + TS_ASSERT_THROWS_NOTHING(loadAlgPtrArray[i]->execute()); + } + } + + void tearDown() override { + for (size_t i = 0; i < loadAlgPtrArray.size(); i++) { + delete loadAlgPtrArray[i]; + } + loadAlgPtrArray.clear(); + + AnalysisDataService::Instance().remove(outWSName); + } + +private: + const int numberOfIterations = 5; // Controls performance test speed + std::vector<LoadCalFile *> loadAlgPtrArray; + + const std::string outWSName = "LoadCalFileTest"; + + LoadCalFile *setupAlg() { + + LoadCalFile *loadAlg = new LoadCalFile; + + loadAlg->initialize(); + loadAlg->setPropertyValue("InstrumentName", "GEM"); + loadAlg->setProperty("MakeGroupingWorkspace", true); + loadAlg->setProperty("MakeOffsetsWorkspace", true); + loadAlg->setProperty("MakeMaskWorkspace", true); + loadAlg->setPropertyValue("CalFilename", "offsets_2006_cycle064.cal"); + loadAlg->setPropertyValue("WorkspaceName", outWSName); + + loadAlg->setRethrows(true); + + return loadAlg; + } +}; + #endif /* MANTID_DATAHANDLING_LOADCALFILETEST_H_ */ diff --git a/Framework/DataHandling/test/LoadILLTOFTest.h b/Framework/DataHandling/test/LoadILLTOFTest.h index 6dafcd3c3da2f1c431f75097eb0ed35a42976228..fdb6e1e47ac6b022b20acfb9c4f451982bf63416 100644 --- a/Framework/DataHandling/test/LoadILLTOFTest.h +++ b/Framework/DataHandling/test/LoadILLTOFTest.h @@ -56,6 +56,16 @@ public: TS_ASSERT_EQUALS(output2D->getNumberHistograms(), numberOfHistograms); + // Check all detectors have a unique and defined detector ID >= 0 + + Mantid::detid2index_map detectorMap; + TS_ASSERT_THROWS_NOTHING( + detectorMap = output->getDetectorIDToWorkspaceIndexMap(true)); + + for (auto value : detectorMap) { + TS_ASSERT(value.first >= 0); + } + return output2D; } diff --git a/Framework/DataHandling/test/LoadISISNexusTest.h b/Framework/DataHandling/test/LoadISISNexusTest.h index 49dfd09b575e1a8183d053b76be486bb9ff744d4..c27c7b1b0c16637f78b8bcafa87867693104e032 100644 --- a/Framework/DataHandling/test/LoadISISNexusTest.h +++ b/Framework/DataHandling/test/LoadISISNexusTest.h @@ -100,25 +100,25 @@ public: // Two monitors which form two first spectra are excluded by load separately // spectrum with ID 5 is now spectrum N 3 as 2 monitors - TS_ASSERT_EQUALS(ws->readY(5 - 2)[1], 1.); + TS_ASSERT_EQUALS(ws->y(5 - 2)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(5 - 2).getSpectrumNo(), 6); TS_ASSERT_EQUALS(*(ws->getSpectrum(5 - 2).getDetectorIDs().begin()), 6); // spectrum with ID 7 is now spectrum N 4 - TS_ASSERT_EQUALS(ws->readY(6 - 2)[0], 1.); + TS_ASSERT_EQUALS(ws->y(6 - 2)[0], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(6 - 2).getSpectrumNo(), 7); TS_ASSERT_EQUALS(*(ws->getSpectrum(6 - 2).getDetectorIDs().begin()), 7); // - TS_ASSERT_EQUALS(ws->readY(8 - 2)[3], 1.); + TS_ASSERT_EQUALS(ws->y(8 - 2)[3], 1.); - TS_ASSERT_EQUALS(mon_ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(mon_ws->readX(0)[1], 4005.); - TS_ASSERT_EQUALS(mon_ws->readX(0)[2], 8005.); + TS_ASSERT_EQUALS(mon_ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(mon_ws->x(0)[1], 4005.); + TS_ASSERT_EQUALS(mon_ws->x(0)[2], 8005.); // these spectra are not loaded as above so their values are different // (occasionally 0) - TS_ASSERT_EQUALS(mon_ws->readY(0)[1], 0); - TS_ASSERT_EQUALS(mon_ws->readY(1)[0], 0.); - TS_ASSERT_EQUALS(mon_ws->readY(0)[3], 0.); + TS_ASSERT_EQUALS(mon_ws->y(0)[1], 0); + TS_ASSERT_EQUALS(mon_ws->y(1)[0], 0.); + TS_ASSERT_EQUALS(mon_ws->y(0)[3], 0.); const std::vector<Property *> &logs = mon_ws->run().getLogData(); for (size_t i = 0; i < logs.size(); ++i) @@ -163,41 +163,41 @@ public: AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>("outWS"); TS_ASSERT_EQUALS(ws->blocksize(), 5); TS_ASSERT_EQUALS(ws->getNumberHistograms(), 17792); - TS_ASSERT_EQUALS(ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(ws->readX(0)[1], 4005.); - TS_ASSERT_EQUALS(ws->readX(0)[2], 8005.); + TS_ASSERT_EQUALS(ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(ws->x(0)[1], 4005.); + TS_ASSERT_EQUALS(ws->x(0)[2], 8005.); TS_ASSERT_EQUALS(ws->getSpectrum(0).getSpectrumNo(), 1); TS_ASSERT_EQUALS(*(ws->getSpectrum(0).getDetectorIDs().begin()), 1); - TS_ASSERT_EQUALS(ws->readY(5)[1], 1.); + TS_ASSERT_EQUALS(ws->y(5)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(5).getSpectrumNo(), 6); TS_ASSERT_EQUALS(*(ws->getSpectrum(5).getDetectorIDs().begin()), 6); - TS_ASSERT_EQUALS(ws->readY(6)[0], 1.); + TS_ASSERT_EQUALS(ws->y(6)[0], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(6).getSpectrumNo(), 7); TS_ASSERT_EQUALS(*(ws->getSpectrum(6).getDetectorIDs().begin()), 7); - TS_ASSERT_EQUALS(ws->readY(8)[3], 1.); + TS_ASSERT_EQUALS(ws->y(8)[3], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(8).getSpectrumNo(), 9); TS_ASSERT_EQUALS(*(ws->getSpectrum(8).getDetectorIDs().begin()), 9); - TS_ASSERT_EQUALS(ws->readY(13)[1], 1.); + TS_ASSERT_EQUALS(ws->y(13)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(13).getSpectrumNo(), 14); TS_ASSERT_EQUALS(*(ws->getSpectrum(13).getDetectorIDs().begin()), 14); - TS_ASSERT_EQUALS(ws->readY(17)[1], 2.); + TS_ASSERT_EQUALS(ws->y(17)[1], 2.); TS_ASSERT_EQUALS(ws->getSpectrum(17).getSpectrumNo(), 18); TS_ASSERT_EQUALS(*(ws->getSpectrum(17).getDetectorIDs().begin()), 18); - TS_ASSERT_EQUALS(ws->readY(18)[1], 1.); + TS_ASSERT_EQUALS(ws->y(18)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(18).getSpectrumNo(), 19); TS_ASSERT_EQUALS(*(ws->getSpectrum(18).getDetectorIDs().begin()), 19); - TS_ASSERT_EQUALS(ws->readY(33)[2], 1.); + TS_ASSERT_EQUALS(ws->y(33)[2], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(33).getSpectrumNo(), 34); TS_ASSERT_EQUALS(*(ws->getSpectrum(33).getDetectorIDs().begin()), 34); - TS_ASSERT_EQUALS(ws->readY(34)[1], 1.); + TS_ASSERT_EQUALS(ws->y(34)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(34).getSpectrumNo(), 35); TS_ASSERT_EQUALS(*(ws->getSpectrum(34).getDetectorIDs().begin()), 35); - TS_ASSERT_EQUALS(ws->readY(37)[3], 1.); - TS_ASSERT_EQUALS(ws->readY(37)[4], 1.); + TS_ASSERT_EQUALS(ws->y(37)[3], 1.); + TS_ASSERT_EQUALS(ws->y(37)[4], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(37).getSpectrumNo(), 38); TS_ASSERT_EQUALS(*(ws->getSpectrum(37).getDetectorIDs().begin()), 38); @@ -281,46 +281,46 @@ public: TS_ASSERT_EQUALS(ws->blocksize(), 5); TS_ASSERT_EQUALS(ws->getNumberHistograms(), 15); - TS_ASSERT_EQUALS(ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(ws->readX(0)[1], 4005.); - TS_ASSERT_EQUALS(ws->readX(0)[2], 8005.); + TS_ASSERT_EQUALS(ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(ws->x(0)[1], 4005.); + TS_ASSERT_EQUALS(ws->x(0)[2], 8005.); TS_ASSERT_EQUALS(ws->getSpectrum(0).getSpectrumNo(), 5); TS_ASSERT_EQUALS(*(ws->getSpectrum(0).getDetectorIDs().begin()), 5); // these spectra are not loaded as above so their values are different // (occasionally 0) TSM_ASSERT_EQUALS("Total workspace spectra N13, index 1 is occasionally 1 ", - ws->readY(5)[1], 1.); + ws->y(5)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(5).getSpectrumNo(), 14); TS_ASSERT_EQUALS(*(ws->getSpectrum(5).getDetectorIDs().begin()), 14); - TS_ASSERT_EQUALS(ws->readY(6)[0], 0.); + TS_ASSERT_EQUALS(ws->y(6)[0], 0.); TS_ASSERT_EQUALS(ws->getSpectrum(6).getSpectrumNo(), 15); TS_ASSERT_EQUALS(*(ws->getSpectrum(6).getDetectorIDs().begin()), 15); - TS_ASSERT_EQUALS(ws->readY(8)[3], 0.); + TS_ASSERT_EQUALS(ws->y(8)[3], 0.); TS_ASSERT_EQUALS(ws->getSpectrum(8).getSpectrumNo(), 17); TS_ASSERT_EQUALS(*(ws->getSpectrum(8).getDetectorIDs().begin()), 17); // look at the same values as the full loader above - TS_ASSERT_EQUALS(ws->readY(13 - 8)[1], 1.); + TS_ASSERT_EQUALS(ws->y(13 - 8)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(13 - 8).getSpectrumNo(), 14); TS_ASSERT_EQUALS(*(ws->getSpectrum(13 - 8).getDetectorIDs().begin()), 14); - TS_ASSERT_EQUALS(ws->readY(17 - 8)[1], 2.); + TS_ASSERT_EQUALS(ws->y(17 - 8)[1], 2.); TS_ASSERT_EQUALS(ws->getSpectrum(17 - 8).getSpectrumNo(), 18); TS_ASSERT_EQUALS(*(ws->getSpectrum(17 - 8).getDetectorIDs().begin()), 18); - TS_ASSERT_EQUALS(ws->readY(18 - 8)[1], 1.); + TS_ASSERT_EQUALS(ws->y(18 - 8)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(18 - 8).getSpectrumNo(), 19); TS_ASSERT_EQUALS(*(ws->getSpectrum(18 - 8).getDetectorIDs().begin()), 19); // look at the same values as the full loader above - TS_ASSERT_EQUALS(ws->readY(33 - 21)[2], 1.); + TS_ASSERT_EQUALS(ws->y(33 - 21)[2], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(33 - 21).getSpectrumNo(), 34); TS_ASSERT_EQUALS(*(ws->getSpectrum(33 - 21).getDetectorIDs().begin()), 34); - TS_ASSERT_EQUALS(ws->readY(34 - 21)[1], 1.); + TS_ASSERT_EQUALS(ws->y(34 - 21)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(34 - 21).getSpectrumNo(), 35); TS_ASSERT_EQUALS(*(ws->getSpectrum(34 - 21).getDetectorIDs().begin()), 35); - TS_ASSERT_EQUALS(ws->readY(37 - 23)[3], 1.); - TS_ASSERT_EQUALS(ws->readY(37 - 23)[4], 1.); + TS_ASSERT_EQUALS(ws->y(37 - 23)[3], 1.); + TS_ASSERT_EQUALS(ws->y(37 - 23)[4], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(37 - 23).getSpectrumNo(), 38); TS_ASSERT_EQUALS(*(ws->getSpectrum(37 - 23).getDetectorIDs().begin()), 38); @@ -366,22 +366,22 @@ public: TS_ASSERT_EQUALS(ws->blocksize(), 5); TS_ASSERT_EQUALS(ws->getNumberHistograms(), 11); - TS_ASSERT_EQUALS(ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(ws->readX(0)[1], 4005.); - TS_ASSERT_EQUALS(ws->readX(0)[2], 8005.); + TS_ASSERT_EQUALS(ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(ws->x(0)[1], 4005.); + TS_ASSERT_EQUALS(ws->x(0)[2], 8005.); // these spectra are not loaded as above so their values are different // (occasionally 0) - TS_ASSERT_EQUALS(ws->readY(5)[1], 0); - TS_ASSERT_EQUALS(ws->readY(6)[0], 0.); - TS_ASSERT_EQUALS(ws->readY(8)[3], 0.); + TS_ASSERT_EQUALS(ws->y(5)[1], 0); + TS_ASSERT_EQUALS(ws->y(6)[0], 0.); + TS_ASSERT_EQUALS(ws->y(8)[3], 0.); // look at the same values as the full/partial loader above - TS_ASSERT_EQUALS(ws->readY(13 - 9)[1], 1.); + TS_ASSERT_EQUALS(ws->y(13 - 9)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(13 - 9).getSpectrumNo(), 14); - TS_ASSERT_EQUALS(ws->readY(17 - 9)[1], 2.); + TS_ASSERT_EQUALS(ws->y(17 - 9)[1], 2.); TS_ASSERT_EQUALS(ws->getSpectrum(17 - 9).getSpectrumNo(), 18); - TS_ASSERT_EQUALS(ws->readY(18 - 9)[1], 1.); + TS_ASSERT_EQUALS(ws->y(18 - 9)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(18 - 9).getSpectrumNo(), 19); Mantid::specnum_t offset; @@ -420,17 +420,17 @@ public: TS_ASSERT_EQUALS(ws->getNumberHistograms(), 10); TS_ASSERT_DELTA(ws->run().getProtonCharge(), 0.069991, 1e-6); - TS_ASSERT_EQUALS(ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(ws->readX(0)[1], 6.); - TS_ASSERT_EQUALS(ws->readX(0)[2], 7.); + TS_ASSERT_EQUALS(ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(ws->x(0)[1], 6.); + TS_ASSERT_EQUALS(ws->x(0)[2], 7.); - TS_ASSERT_EQUALS(ws->readY(5)[1], 0); - TS_ASSERT_EQUALS(ws->readY(6)[0], 0.); - TS_ASSERT_EQUALS(ws->readY(8)[3], 0.); + TS_ASSERT_EQUALS(ws->y(5)[1], 0); + TS_ASSERT_EQUALS(ws->y(6)[0], 0.); + TS_ASSERT_EQUALS(ws->y(8)[3], 0.); - TS_ASSERT_EQUALS(ws->readY(7)[1], 0.); - TS_ASSERT_EQUALS(ws->readY(9)[3], 0.); - TS_ASSERT_EQUALS(ws->readY(9)[1], 0.); + TS_ASSERT_EQUALS(ws->y(7)[1], 0.); + TS_ASSERT_EQUALS(ws->y(9)[3], 0.); + TS_ASSERT_EQUALS(ws->y(9)[1], 0.); AnalysisDataService::Instance().remove("outWS"); } @@ -453,17 +453,17 @@ public: // TS_ASSERT_EQUALS(ws->getNumberHistograms(),14); TS_ASSERT_EQUALS(ws->getTitle(), "hello\\0"); TS_ASSERT_DELTA(ws->run().getProtonCharge(), 0.069991, 1e-6); - TS_ASSERT_EQUALS(ws->readX(0)[0], 5.); - TS_ASSERT_EQUALS(ws->readX(0)[1], 6.); - TS_ASSERT_EQUALS(ws->readX(0)[2], 7.); + TS_ASSERT_EQUALS(ws->x(0)[0], 5.); + TS_ASSERT_EQUALS(ws->x(0)[1], 6.); + TS_ASSERT_EQUALS(ws->x(0)[2], 7.); - TS_ASSERT_EQUALS(ws->readY(5)[1], 0.); - TS_ASSERT_EQUALS(ws->readY(6)[0], 0.); - TS_ASSERT_EQUALS(ws->readY(8)[3], 0.); + TS_ASSERT_EQUALS(ws->y(5)[1], 0.); + TS_ASSERT_EQUALS(ws->y(6)[0], 0.); + TS_ASSERT_EQUALS(ws->y(8)[3], 0.); - TS_ASSERT_EQUALS(ws->readY(7)[1], 0.); - TS_ASSERT_EQUALS(ws->readY(9)[3], 0.); - TS_ASSERT_EQUALS(ws->readY(9)[1], 0.); + TS_ASSERT_EQUALS(ws->y(7)[1], 0.); + TS_ASSERT_EQUALS(ws->y(9)[3], 0.); + TS_ASSERT_EQUALS(ws->y(9)[1], 0.); AnalysisDataService::Instance().remove("outWS"); } @@ -565,42 +565,42 @@ public: // Two monitors which form two first spectra are excluded by load separately // spectrum with ID 5 is now spectrum N 3 as 2 monitors - TS_ASSERT_EQUALS(ws->readY(5 - 2)[1], 1.); + TS_ASSERT_EQUALS(ws->y(5 - 2)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(5 - 2).getSpectrumNo(), 6); TS_ASSERT_EQUALS(*(ws->getSpectrum(5 - 2).getDetectorIDs().begin()), 6); // spectrum with ID 7 is now spectrum N 4 - TS_ASSERT_EQUALS(ws->readY(6 - 2)[0], 1.); + TS_ASSERT_EQUALS(ws->y(6 - 2)[0], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(6 - 2).getSpectrumNo(), 7); TS_ASSERT_EQUALS(*(ws->getSpectrum(6 - 2).getDetectorIDs().begin()), 7); // - TS_ASSERT_EQUALS(ws->readY(8 - 2)[3], 1.); + TS_ASSERT_EQUALS(ws->y(8 - 2)[3], 1.); // spectrum with ID 9 is now spectrum N 6 TS_ASSERT_EQUALS(ws->getSpectrum(8 - 2).getSpectrumNo(), 9); TS_ASSERT_EQUALS(*(ws->getSpectrum(8 - 2).getDetectorIDs().begin()), 9); // spectrum with ID 14 is now spectrum N 11 - TS_ASSERT_EQUALS(ws->readY(13 - 2)[1], 1.); + TS_ASSERT_EQUALS(ws->y(13 - 2)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(13 - 2).getSpectrumNo(), 14); TS_ASSERT_EQUALS(*(ws->getSpectrum(13 - 2).getDetectorIDs().begin()), 14); // spectrum with ID 18 is now spectrum N 15 - TS_ASSERT_EQUALS(ws->readY(17 - 2)[1], 2.); + TS_ASSERT_EQUALS(ws->y(17 - 2)[1], 2.); TS_ASSERT_EQUALS(ws->getSpectrum(17 - 2).getSpectrumNo(), 18); TS_ASSERT_EQUALS(*(ws->getSpectrum(17 - 2).getDetectorIDs().begin()), 18); // spectrum with ID 19 is now spectrum N 16 - TS_ASSERT_EQUALS(ws->readY(18 - 2)[1], 1.); + TS_ASSERT_EQUALS(ws->y(18 - 2)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(18 - 2).getSpectrumNo(), 19); TS_ASSERT_EQUALS(*(ws->getSpectrum(18 - 2).getDetectorIDs().begin()), 19); - TS_ASSERT_EQUALS(ws->readY(33 - 2)[2], 1.); + TS_ASSERT_EQUALS(ws->y(33 - 2)[2], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(33 - 2).getSpectrumNo(), 34); TS_ASSERT_EQUALS(*(ws->getSpectrum(33 - 2).getDetectorIDs().begin()), 34); // - TS_ASSERT_EQUALS(ws->readY(34 - 2)[1], 1.); + TS_ASSERT_EQUALS(ws->y(34 - 2)[1], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(34 - 2).getSpectrumNo(), 35); TS_ASSERT_EQUALS(*(ws->getSpectrum(34 - 2).getDetectorIDs().begin()), 35); - TS_ASSERT_EQUALS(ws->readY(37 - 2)[3], 1.); - TS_ASSERT_EQUALS(ws->readY(37 - 2)[4], 1.); + TS_ASSERT_EQUALS(ws->y(37 - 2)[3], 1.); + TS_ASSERT_EQUALS(ws->y(37 - 2)[4], 1.); TS_ASSERT_EQUALS(ws->getSpectrum(37 - 2).getSpectrumNo(), 38); TS_ASSERT_EQUALS(*(ws->getSpectrum(37 - 2).getDetectorIDs().begin()), 38); @@ -695,18 +695,18 @@ public: boost::dynamic_pointer_cast<MatrixWorkspace>(detGroup->getItem(0)); TS_ASSERT_EQUALS(1000, detWS0->blocksize()); TS_ASSERT_EQUALS(243, detWS0->getNumberHistograms()); - TS_ASSERT_DELTA(105, detWS0->readX(1)[1], 1e-08); - TS_ASSERT_DELTA(2, detWS0->readY(1)[1], 1e-08); - TS_ASSERT_DELTA(M_SQRT2, detWS0->readE(1)[1], 1e-08); + TS_ASSERT_DELTA(105, detWS0->x(1)[1], 1e-08); + TS_ASSERT_DELTA(2, detWS0->y(1)[1], 1e-08); + TS_ASSERT_DELTA(M_SQRT2, detWS0->e(1)[1], 1e-08); TS_ASSERT_EQUALS(detWS0->getSpectrum(0).getSpectrumNo(), 4); auto monWS0 = boost::dynamic_pointer_cast<MatrixWorkspace>(monGroup->getItem(0)); TS_ASSERT_EQUALS(1000, monWS0->blocksize()); TS_ASSERT_EQUALS(3, monWS0->getNumberHistograms()); - TS_ASSERT_DELTA(105, monWS0->readX(1)[1], 1e-08); - TS_ASSERT_DELTA(12563.0, monWS0->readY(0)[1], 1e-08); - TS_ASSERT_DELTA(std::sqrt(12563.0), monWS0->readE(0)[1], 1e-08); + TS_ASSERT_DELTA(105, monWS0->x(1)[1], 1e-08); + TS_ASSERT_DELTA(12563.0, monWS0->y(0)[1], 1e-08); + TS_ASSERT_DELTA(std::sqrt(12563.0), monWS0->e(0)[1], 1e-08); TS_ASSERT_EQUALS(monWS0->getSpectrum(0).getSpectrumNo(), 1); TS_ASSERT_EQUALS(monWS0->getSpectrum(2).getSpectrumNo(), 3); @@ -714,9 +714,9 @@ public: boost::dynamic_pointer_cast<MatrixWorkspace>(monGroup->getItem(1)); TS_ASSERT_EQUALS(1000, monWS1->blocksize()); TS_ASSERT_EQUALS(3, monWS1->getNumberHistograms()); - TS_ASSERT_DELTA(105, monWS1->readX(1)[1], 1e-08); - TS_ASSERT_DELTA(12595.0, monWS1->readY(0)[1], 1e-08); - TS_ASSERT_DELTA(std::sqrt(12595.0), monWS1->readE(0)[1], 1e-08); + TS_ASSERT_DELTA(105, monWS1->x(1)[1], 1e-08); + TS_ASSERT_DELTA(12595.0, monWS1->y(0)[1], 1e-08); + TS_ASSERT_DELTA(std::sqrt(12595.0), monWS1->e(0)[1], 1e-08); TS_ASSERT_EQUALS(monWS1->getSpectrum(0).getSpectrumNo(), 1); TS_ASSERT_EQUALS(monWS1->getSpectrum(2).getSpectrumNo(), 3); @@ -815,15 +815,15 @@ public: // Check some of the data double delta = 1e-6; - TS_ASSERT_DELTA(ws->readY(142)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[1], 82.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[2], 57.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17034], 5.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17035], 8.0, delta); + TS_ASSERT_DELTA(ws->y(142)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(142)[1], 82.0, delta); + TS_ASSERT_DELTA(ws->y(142)[2], 57.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17034], 5.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17035], 8.0, delta); - TS_ASSERT_DELTA(ws->readY(143)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(143)[1], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(143)[2], 0.0, delta); + TS_ASSERT_DELTA(ws->y(143)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(143)[1], 0.0, delta); + TS_ASSERT_DELTA(ws->y(143)[2], 0.0, delta); // Check that the data has the expected spectrum number and the expected // detecor ID @@ -963,17 +963,17 @@ public: // Check some of the data double delta = 1e-6; - TS_ASSERT_DELTA(ws->readY(142)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[1], 82.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[2], 57.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17034], 5.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17035], 8.0, delta); - - TS_ASSERT_DELTA(ws->readY(144)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(144)[1], 176660.0, delta); - TS_ASSERT_DELTA(ws->readY(144)[2], 57659.0, delta); - TS_ASSERT_DELTA(ws->readY(144)[17034], 4851.0, delta); - TS_ASSERT_DELTA(ws->readY(144)[17035], 4513.0, delta); + TS_ASSERT_DELTA(ws->y(142)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(142)[1], 82.0, delta); + TS_ASSERT_DELTA(ws->y(142)[2], 57.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17034], 5.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17035], 8.0, delta); + + TS_ASSERT_DELTA(ws->y(144)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(144)[1], 176660.0, delta); + TS_ASSERT_DELTA(ws->y(144)[2], 57659.0, delta); + TS_ASSERT_DELTA(ws->y(144)[17034], 4851.0, delta); + TS_ASSERT_DELTA(ws->y(144)[17035], 4513.0, delta); // Check that the data has the expected spectrum number and the expected // detecor ID @@ -1062,11 +1062,11 @@ public: double delta = 1e-6; // Make sure that the monitor data is correct (should be workspace index 26) - TS_ASSERT_DELTA(ws->readY(25)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(25)[1], 176660.0, delta); - TS_ASSERT_DELTA(ws->readY(25)[2], 57659.0, delta); - TS_ASSERT_DELTA(ws->readY(25)[17034], 4851.0, delta); - TS_ASSERT_DELTA(ws->readY(25)[17035], 4513.0, delta); + TS_ASSERT_DELTA(ws->y(25)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(25)[1], 176660.0, delta); + TS_ASSERT_DELTA(ws->y(25)[2], 57659.0, delta); + TS_ASSERT_DELTA(ws->y(25)[17034], 4851.0, delta); + TS_ASSERT_DELTA(ws->y(25)[17035], 4513.0, delta); // Check that the data has the expected spectrum number and the expected // detecor ID (for some sample spectra) @@ -1145,21 +1145,21 @@ public: // Check some of the data double delta = 1e-6; - TS_ASSERT_DELTA(ws->readY(142)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[1], 82.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[2], 57.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17034], 5.0, delta); - TS_ASSERT_DELTA(ws->readY(142)[17035], 8.0, delta); - - TS_ASSERT_DELTA(ws->readY(143)[0], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(143)[1], 0.0, delta); - TS_ASSERT_DELTA(ws->readY(143)[2], 0.0, delta); - - TS_ASSERT_DELTA(mon_ws->readY(0)[0], 0.0, delta); - TS_ASSERT_DELTA(mon_ws->readY(0)[1], 176660.0, delta); - TS_ASSERT_DELTA(mon_ws->readY(0)[2], 57659.0, delta); - TS_ASSERT_DELTA(mon_ws->readY(0)[17034], 4851.0, delta); - TS_ASSERT_DELTA(mon_ws->readY(0)[17035], 4513.0, delta); + TS_ASSERT_DELTA(ws->y(142)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(142)[1], 82.0, delta); + TS_ASSERT_DELTA(ws->y(142)[2], 57.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17034], 5.0, delta); + TS_ASSERT_DELTA(ws->y(142)[17035], 8.0, delta); + + TS_ASSERT_DELTA(ws->y(143)[0], 0.0, delta); + TS_ASSERT_DELTA(ws->y(143)[1], 0.0, delta); + TS_ASSERT_DELTA(ws->y(143)[2], 0.0, delta); + + TS_ASSERT_DELTA(mon_ws->y(0)[0], 0.0, delta); + TS_ASSERT_DELTA(mon_ws->y(0)[1], 176660.0, delta); + TS_ASSERT_DELTA(mon_ws->y(0)[2], 57659.0, delta); + TS_ASSERT_DELTA(mon_ws->y(0)[17034], 4851.0, delta); + TS_ASSERT_DELTA(mon_ws->y(0)[17035], 4513.0, delta); // Check that the data has the expected spectrum number and the expected // detecor ID diff --git a/Framework/DataHandling/test/LoadMaskTest.h b/Framework/DataHandling/test/LoadMaskTest.h index f2969b120b029be398c08f59de8f4ea2bedf76d6..945a2a14473e14d1d45f9ea8996c5d104bd5af19 100644 --- a/Framework/DataHandling/test/LoadMaskTest.h +++ b/Framework/DataHandling/test/LoadMaskTest.h @@ -91,7 +91,7 @@ public: // 3. Check for (size_t iws = 0; iws < maskws->getNumberHistograms(); iws++) { - double y = maskws->dataY(iws)[0]; + double y = maskws->y(iws)[0]; if (iws == 34 || iws == 1000 || iws == 2000) { // These 3 workspace index are masked TS_ASSERT_DELTA(y, 1.0, 1.0E-5); @@ -143,7 +143,7 @@ public: // 3. Check size_t errorcounts = 0; for (size_t iws = 0; iws < maskws->getNumberHistograms(); iws++) { - double y = maskws->dataY(iws)[0]; + double y = maskws->y(iws)[0]; if (iws == 34 || iws == 1000 || iws == 2000 || (iws >= 36 && iws <= 39) || (iws >= 1001 && iws <= 1004)) { // All these workspace index are masked @@ -266,7 +266,7 @@ public: if (source_masked) { maskSourceDet.push_back(source->getDetector(i)->getID()); } - bool targ_masked = (maskWs->getSpectrum(i).readY()[0] > 0.5); + bool targ_masked = (maskWs->getSpectrum(i).y()[0] > 0.5); if (targ_masked) { maskTargDet.push_back(maskWs->getDetector(i)->getID()); } @@ -279,6 +279,7 @@ public: TS_ASSERT_EQUALS(maskSourceDet[i], maskTargDet[i]); } } + void test_IDF_acceptedAsFileName() { auto ws_creator = AlgorithmManager::Instance().createUnmanaged( "CreateSimulationWorkspace"); @@ -508,4 +509,35 @@ public: } }; +//------------------------------------------------------------------------------ +// Performance test +//------------------------------------------------------------------------------ + +class LoadMaskTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static LoadMaskTestPerformance *createSuite() { + return new LoadMaskTestPerformance(); + } + + static void destroySuite(LoadMaskTestPerformance *suite) { delete suite; } + + void setUp() override { + loadFile.initialize(); + loadFile.setProperty("Instrument", "POWGEN"); + loadFile.setProperty("InputFile", "testmasking.xml"); + loadFile.setProperty("OutputWorkspace", "outputWS"); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("outputWS"); + } + + void testDefaultLoad() { loadFile.execute(); } + +private: + LoadMask loadFile; +}; + #endif /* MANTID_DATAHANDLING_LOADMASKINGFILETEST_H_ */ diff --git a/Framework/DataHandling/test/LoadMcStasTest.h b/Framework/DataHandling/test/LoadMcStasTest.h index 59d1eefcc6368303bd8199ca89ca4f331a429236..e9ebc98da5d18a6c32ab5dd0c2035e5e3345e319 100644 --- a/Framework/DataHandling/test/LoadMcStasTest.h +++ b/Framework/DataHandling/test/LoadMcStasTest.h @@ -73,7 +73,7 @@ public: TS_ASSERT_EQUALS(outputItem1->getNumberHistograms(), 8192); double sum = 0.0; for (size_t i = 0; i < outputItem1->getNumberHistograms(); i++) - sum += outputItem1->readY(i)[0]; + sum += outputItem1->y(i)[0]; sum *= 1.0e22; TS_ASSERT_DELTA(sum, 107163.7851, 0.0001); // @@ -111,4 +111,30 @@ private: std::string outputSpace; }; +class LoadMcStasTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static LoadMcStasTestPerformance *createSuite() { + return new LoadMcStasTestPerformance(); + } + + static void destroySuite(LoadMcStasTestPerformance *suite) { delete suite; } + + void setUp() override { + loadFile.initialize(); + loadFile.setProperty("Filename", "mcstas_event_hist.h5"); + loadFile.setProperty("OutputWorkspace", "outputWS"); + } + + void tearDown() override { + AnalysisDataService::Instance().remove("outputWS"); + } + + void testDefaultLoad() { loadFile.execute(); } + +private: + LoadMcStas loadFile; +}; + #endif /*LoadMcStasTEST_H_*/ diff --git a/Framework/HistogramData/CMakeLists.txt b/Framework/HistogramData/CMakeLists.txt index 9783a1706b0c462eb34f16603bb18c529355c984..6aba7d185aef8e230699fe6237253c6643294d5c 100644 --- a/Framework/HistogramData/CMakeLists.txt +++ b/Framework/HistogramData/CMakeLists.txt @@ -8,6 +8,7 @@ set ( SRC_FILES src/FrequencyVariances.cpp src/Histogram.cpp src/HistogramMath.cpp + src/Rebin.cpp src/Points.cpp ) @@ -26,6 +27,7 @@ set ( INC_FILES inc/MantidHistogramData/HistogramDx.h inc/MantidHistogramData/HistogramE.h inc/MantidHistogramData/HistogramMath.h + inc/MantidHistogramData/Rebin.h inc/MantidHistogramData/HistogramX.h inc/MantidHistogramData/HistogramY.h inc/MantidHistogramData/Iterable.h @@ -59,6 +61,7 @@ set ( TEST_FILES HistogramDxTest.h HistogramETest.h HistogramMathTest.h + RebinTest.h HistogramTest.h HistogramXTest.h HistogramYTest.h diff --git a/Framework/HistogramData/inc/MantidHistogramData/FixedLengthVector.h b/Framework/HistogramData/inc/MantidHistogramData/FixedLengthVector.h index 489347987a6a4a4f0da5205517fe0a3405880436..f5fec094938fc09f4cd89ec67eb15b22ce15850c 100644 --- a/Framework/HistogramData/inc/MantidHistogramData/FixedLengthVector.h +++ b/Framework/HistogramData/inc/MantidHistogramData/FixedLengthVector.h @@ -157,6 +157,10 @@ public: double &back() { return m_data.back(); } const double &front() const { return m_data.front(); } const double &back() const { return m_data.back(); } + + // expose typedefs for the iterator types in the underlying container + typedef std::vector<double>::iterator iterator; + typedef std::vector<double>::const_iterator const_iterator; }; } // namespace detail diff --git a/Framework/HistogramData/inc/MantidHistogramData/Histogram.h b/Framework/HistogramData/inc/MantidHistogramData/Histogram.h index e31c0b0c3db19a6c59ea5e828f14bbab376e92f6..dd772eb01de4316023ade7ae5d71040c5e5c87ff 100644 --- a/Framework/HistogramData/inc/MantidHistogramData/Histogram.h +++ b/Framework/HistogramData/inc/MantidHistogramData/Histogram.h @@ -137,6 +137,13 @@ public: void setSharedE(const Kernel::cow_ptr<HistogramE> &e) & ; void setSharedDx(const Kernel::cow_ptr<HistogramDx> &Dx) & ; + /// Returns the size of the histogram, i.e., the number of Y data points. + size_t size() const { + if (xMode() == XMode::BinEdges) + return m_x->size() - 1; + return m_x->size(); + } + void resize(size_t n); // Temporary legacy interface to X @@ -199,12 +206,6 @@ private: void switchDxToBinEdges(); void switchDxToPoints(); - size_t size() const { - if (xMode() == XMode::BinEdges) - return m_x->size() - 1; - return m_x->size(); - } - XMode m_xMode; YMode m_yMode{YMode::Uninitialized}; }; diff --git a/Framework/HistogramData/inc/MantidHistogramData/Iterable.h b/Framework/HistogramData/inc/MantidHistogramData/Iterable.h index c86967f1b07e069e9605a48d150b3301a8c32a25..cdfea120b0605221176976aa7e6833a7ddd2a6a8 100644 --- a/Framework/HistogramData/inc/MantidHistogramData/Iterable.h +++ b/Framework/HistogramData/inc/MantidHistogramData/Iterable.h @@ -85,6 +85,10 @@ public: return static_cast<const T *>(this)->data().back(); } + // expose typedefs for the iterator types in the underlying container + typedef std::vector<double>::iterator iterator; + typedef std::vector<double>::const_iterator const_iterator; + protected: ~Iterable() = default; }; diff --git a/Framework/HistogramData/inc/MantidHistogramData/Rebin.h b/Framework/HistogramData/inc/MantidHistogramData/Rebin.h new file mode 100644 index 0000000000000000000000000000000000000000..b0ff6d0d5fa14f42c112852875bbbd82527f52e6 --- /dev/null +++ b/Framework/HistogramData/inc/MantidHistogramData/Rebin.h @@ -0,0 +1,38 @@ +#ifndef MANTID_HISTOGRAMDATA_HISTOGRAMREBIN_H_ +#define MANTID_HISTOGRAMDATA_HISTOGRAMREBIN_H_ + +#include "MantidHistogramData/DllConfig.h" +namespace Mantid { +namespace HistogramData { +class Histogram; +class BinEdges; + +/** + Copyright © 2016 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge + National Laboratory & European Spallation Source + + 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 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/>. + + File change history is stored at: <https://github.com/mantidproject/mantid> + Code Documentation is available at: <http://doxygen.mantidproject.org> +*/ + +MANTID_HISTOGRAMDATA_DLL Histogram +rebin(const Histogram &input, const BinEdges &binEdges); +} // namespace HistogramData +} // namespace Mantid + +#endif /* MANTID_HISTOGRAMDATA_HISTOGRAMREBIN_H_ */ \ No newline at end of file diff --git a/Framework/HistogramData/src/Rebin.cpp b/Framework/HistogramData/src/Rebin.cpp new file mode 100644 index 0000000000000000000000000000000000000000..19d767e674c3590a73096cd4b61a94e00061fa11 --- /dev/null +++ b/Framework/HistogramData/src/Rebin.cpp @@ -0,0 +1,147 @@ +#include "MantidHistogramData/Rebin.h" +#include "MantidHistogramData/BinEdges.h" +#include "MantidHistogramData/Histogram.h" +#include <algorithm> +#include <numeric> + +using Mantid::HistogramData::Histogram; +using Mantid::HistogramData::BinEdges; +using Mantid::HistogramData::Counts; +using Mantid::HistogramData::CountStandardDeviations; +using Mantid::HistogramData::CountVariances; +using Mantid::HistogramData::Frequencies; +using Mantid::HistogramData::FrequencyStandardDeviations; +using Mantid::HistogramData::FrequencyVariances; + +namespace { +Histogram rebinCounts(const Histogram &input, const BinEdges &binEdges) { + auto &xold = input.x(); + auto &yold = input.y(); + auto &eold = input.e(); + + auto &xnew = binEdges.rawData(); + Counts newCounts(xnew.size() - 1); + CountVariances newCountVariances(xnew.size() - 1); + auto &ynew = newCounts.mutableData(); + auto &enew = newCountVariances.mutableData(); + + auto size_yold = yold.size(); + auto size_ynew = ynew.size(); + size_t iold = 0; + size_t inew = 0; + + while ((inew < size_ynew) && (iold < size_yold)) { + auto xo_low = xold[iold]; + auto xo_high = xold[iold + 1]; + auto xn_low = xnew[inew]; + auto xn_high = xnew[inew + 1]; + auto owidth = xo_high - xo_low; + auto nwidth = xn_high - xn_low; + + if (owidth <= 0.0 || nwidth <= 0.0) + throw std::runtime_error("Negative or zero bin widths not allowed."); + + if (xn_high <= xo_low) + inew++; /* old and new bins do not overlap */ + else if (xo_high <= xn_low) + iold++; /* old and new bins do not overlap */ + else { + // delta is the overlap of the bins on the x axis + auto delta = xo_high < xn_high ? xo_high : xn_high; + delta -= xo_low > xn_low ? xo_low : xn_low; + + auto factor = 1 / owidth; + ynew[inew] += yold[iold] * delta * factor; + enew[inew] += eold[iold] * eold[iold] * delta * factor; + + if (xn_high > xo_high) { + iold++; + } else { + inew++; + } + } + } + + return Histogram(binEdges, newCounts, + CountStandardDeviations(std::move(newCountVariances))); +} + +Histogram rebinFrequencies(const Histogram &input, const BinEdges &binEdges) { + auto &xold = input.x(); + auto &yold = input.y(); + auto &eold = input.e(); + + auto &xnew = binEdges.rawData(); + Frequencies newFrequencies(xnew.size() - 1); + FrequencyStandardDeviations newFrequencyStdDev(xnew.size() - 1); + auto &ynew = newFrequencies.mutableData(); + auto &enew = newFrequencyStdDev.mutableData(); + + auto size_yold = yold.size(); + auto size_ynew = ynew.size(); + size_t iold = 0; + size_t inew = 0; + + while ((inew < size_ynew) && (iold < size_yold)) { + auto xo_low = xold[iold]; + auto xo_high = xold[iold + 1]; + auto xn_low = xnew[inew]; + auto xn_high = xnew[inew + 1]; + + auto owidth = xo_high - xo_low; + auto nwidth = xn_high - xn_low; + + if (owidth <= 0.0 || nwidth <= 0.0) + throw std::runtime_error("Negative or zero bin widths not allowed."); + + if (xn_high <= xo_low) + inew++; /* old and new bins do not overlap */ + else if (xo_high <= xn_low) + iold++; /* old and new bins do not overlap */ + else { + // delta is the overlap of the bins on the x axis + auto delta = xo_high < xn_high ? xo_high : xn_high; + delta -= xo_low > xn_low ? xo_low : xn_low; + + ynew[inew] += yold[iold] * delta; + enew[inew] += eold[iold] * eold[iold] * delta * owidth; + + if (xn_high > xo_high) { + iold++; + } else { + auto factor = 1 / nwidth; + ynew[inew] *= factor; + enew[inew] = sqrt(enew[inew]) * factor; + inew++; + } + } + } + + return Histogram(binEdges, newFrequencies, newFrequencyStdDev); +} +} // anonymous namespace + +namespace Mantid { +namespace HistogramData { + +/** Rebins data according to a new set of bin edges. +* @param input :: input histogram data to be rebinned. +* @param binEdges :: input will be rebinned according to this set of bin edges. +* @returns The rebinned histogram. +* @throws std::runtime_error if the input histogram xmode is not BinEdges, +* the input yMode is undefined, or for non-positive input/output bin widths +*/ +Histogram rebin(const Histogram &input, const BinEdges &binEdges) { + if (input.xMode() != Histogram::XMode::BinEdges) + throw std::runtime_error( + "XMode must be Histogram::XMode::BinEdges for input histogram"); + if (input.yMode() == Histogram::YMode::Counts) + return rebinCounts(input, binEdges); + else if (input.yMode() == Histogram::YMode::Frequencies) + return rebinFrequencies(input, binEdges); + else + throw std::runtime_error("YMode must be defined for input histogram."); +} + +} // namespace HistogramData +} // namespace Mantid diff --git a/Framework/HistogramData/test/CMakeLists.txt b/Framework/HistogramData/test/CMakeLists.txt index 63fa7501775429fac7275bcb7840c8d341b2c649..36db35df4cd657b37814fd6f3646eb62a9f31eb9 100644 --- a/Framework/HistogramData/test/CMakeLists.txt +++ b/Framework/HistogramData/test/CMakeLists.txt @@ -1,5 +1,5 @@ if ( CXXTEST_FOUND ) - include_directories ( SYSTEM ${CXXTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR} ) + include_directories ( SYSTEM ${CXXTEST_INCLUDE_DIR} ${GMOCK_INCLUDE_DIR} ${GTEST_INCLUDE_DIR} ../../TestHelpers/inc) cxxtest_add_test ( HistogramDataTest ${TEST_FILES} ${GMOCK_TEST_FILES}) target_link_libraries( HistogramDataTest LINK_PRIVATE ${TCMALLOC_LIBRARIES_LINKTIME} diff --git a/Framework/HistogramData/test/RebinTest.h b/Framework/HistogramData/test/RebinTest.h new file mode 100644 index 0000000000000000000000000000000000000000..e3b4a7d78424ca94576a2e9dbf2c179e54be22ff --- /dev/null +++ b/Framework/HistogramData/test/RebinTest.h @@ -0,0 +1,449 @@ +#ifndef MANTID_HISTOGRAMDATA_REBINTEST_H_ +#define MANTID_HISTOGRAMDATA_REBINTEST_H_ + +#include <cxxtest/TestSuite.h> + +#include "MantidHistogramData/Histogram.h" +#include "MantidHistogramData/LinearGenerator.h" +#include "MantidHistogramData/Rebin.h" +#include "MantidTestHelpers/HistogramDataTestHelper.h" + +#include <algorithm> +#include <random> + +using namespace Mantid::HistogramData; + +class RebinTest : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static RebinTest *createSuite() { return new RebinTest(); } + static void destroySuite(RebinTest *suite) { delete suite; } + + void testExecrebin() { + TS_ASSERT_THROWS_NOTHING( + rebin(getCountsHistogram(), BinEdges(10, LinearGenerator(0, 0.5)))); + } + + void testExecRebinFrequency() { + TS_ASSERT_THROWS_NOTHING( + rebin(getFrequencyHistogram(), BinEdges(10, LinearGenerator(0, 0.5)))); + } + + void testRebinNoYModeDefined() { + BinEdges edges(5, LinearGenerator(0, 2)); + Points points(5, LinearGenerator(0, 1)); + Counts counts{10, 1, 3, 4, 7}; + // X Mode Points + TS_ASSERT_THROWS(rebin(Histogram(points, counts), edges), + std::runtime_error); + // No YMode set + TS_ASSERT_THROWS( + rebin(Histogram(BinEdges(10, LinearGenerator(0, 0.5))), edges), + std::runtime_error); + } + + void testRebinFailsCentralBinEdgesInvalid() { + std::vector<double> binEdges{1, 2, 3, 3, 5, 7}; + BinEdges edges(binEdges); + + TS_ASSERT_THROWS(rebin(getCountsHistogram(), edges), std::runtime_error); + } + + void testRebinFailsStartBinEdgesInvalid() { + std::vector<double> binEdges{1, 1, 3, 4, 5, 7}; + BinEdges edges(binEdges); + + TS_ASSERT_THROWS(rebin(getCountsHistogram(), edges), std::runtime_error); + } + + void testRebinEndCentralBinEdgesInvalid() { + std::vector<double> binEdges{1, 2, 3, 4, 5, 5}; + BinEdges edges(binEdges); + + TS_ASSERT_THROWS(rebin(getCountsHistogram(), edges), std::runtime_error); + } + + void testRebinFailsInputBinEdgesInvalid() { + std::vector<double> binEdges{1, 2, 3, 3, 5, 7}; + Histogram hist(BinEdges(std::move(binEdges)), Counts(5, 10)); + BinEdges edges{1, 2, 3, 4, 5, 6}; + + TS_ASSERT_THROWS(rebin(hist, edges), std::runtime_error); + } + + void testRebinFailsInputAndOutputBinEdgesInvalid() { + std::vector<double> binEdges{1, 2, 3, 3, 5, 7}; + Histogram hist(BinEdges(binEdges), Counts(5, 10)); + BinEdges edges(std::move(binEdges)); + + TS_ASSERT_THROWS(rebin(hist, edges), std::runtime_error); + } + + void testRebinIdenticalBins() { + auto histCounts = getCountsHistogram(); + auto histFreq = getFrequencyHistogram(); + + auto outCounts = rebin(histCounts, histCounts.binEdges()); + auto outFreq = rebin(histFreq, histFreq.binEdges()); + + TS_ASSERT_EQUALS(outCounts.x(), histCounts.x()); + TS_ASSERT_EQUALS(outCounts.y(), histCounts.y()); + TS_ASSERT_EQUALS(outCounts.e(), histCounts.e()); + + TS_ASSERT_EQUALS(outFreq.x(), histFreq.x()); + TS_ASSERT_EQUALS(outFreq.y(), histFreq.y()); + TS_ASSERT_EQUALS(outFreq.e(), histFreq.e()); + } + + void testBinEdgesOutsideInputBins() { + auto histCounts = getCountsHistogram(); + auto histFreq = getFrequencyHistogram(); + + auto outCounts = rebin(histCounts, BinEdges(10, LinearGenerator(30, 1))); + auto outFreq = rebin(histFreq, BinEdges(10, LinearGenerator(30, 2))); + + TS_ASSERT(std::all_of(outCounts.y().cbegin(), outCounts.y().cend(), + [](const double i) { return i == 0; })); + TS_ASSERT(std::all_of(outCounts.e().cbegin(), outCounts.e().cend(), + [](const double i) { return i == 0; })); + TS_ASSERT(std::all_of(outFreq.y().cbegin(), outFreq.y().cend(), + [](const double i) { return i == 0; })); + TS_ASSERT(std::all_of(outFreq.e().cbegin(), outFreq.e().cend(), + [](const double i) { return i == 0; })); + } + + void testSplitBinSymmetric() { + // Handles the case where + // | | | becomes: + // ||||| + Histogram hist(BinEdges{0, 1, 2}, Counts{10, 10}); + Histogram histFreq(BinEdges{0, 1, 2}, Frequencies{12, 12}); + BinEdges edges{0, 0.5, 1, 1.5, 2}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + for (size_t i = 0; i < outCounts.y().size(); i++) { + TS_ASSERT_EQUALS(outCounts.y()[i], 5.0); + TS_ASSERT_DELTA(outCounts.e()[i], std::sqrt(5), 1e-14); + TS_ASSERT_EQUALS(outFreq.y()[i], 12.0); + TS_ASSERT_DELTA(outFreq.e()[i], + std::sqrt(outFreq.y()[i] / (edges[i + 1] - edges[i])), + 1e-14); + } + } + + void testCombineMultipleBinsSymmetric() { + // Handles the case where + // ||||| becomes: + // | | | + Histogram hist(BinEdges(5, LinearGenerator(0, 1)), Counts{5, 7, 10, 6}); + Histogram histFreq(BinEdges(5, LinearGenerator(0, 1)), + Frequencies{3, 9, 8, 12}); + BinEdges edges(3, LinearGenerator(0, 2)); + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + for (size_t i = 0; i < outCounts.y().size(); i++) { + TS_ASSERT_EQUALS(outCounts.y()[i], + hist.y()[2 * i] + hist.y()[(2 * i) + 1]); + TS_ASSERT_DELTA(outCounts.e()[i], std::sqrt(outCounts.y()[i]), 1e-14); + TS_ASSERT_EQUALS(outFreq.y()[i], + (histFreq.y()[2 * i] + histFreq.y()[(2 * i) + 1]) / 2); + TS_ASSERT_DELTA(outFreq.e()[i], std::sqrt(outFreq.y()[i] / 2), 1e-14); + } + } + + void testSplitBinsAsymmetric() { + // Handles the case where + // | | | becomes: + // || || + Histogram hist(BinEdges(3, LinearGenerator(0, 1)), Counts{15, 7}); + Histogram histFreq(BinEdges(3, LinearGenerator(0, 1)), Frequencies{12, 20}); + BinEdges edges{0, 0.5, 1.5, 2}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[0] / 2); + TS_ASSERT_EQUALS(outCounts.y()[1], (hist.y()[0] + hist.y()[1]) / 2); + TS_ASSERT_EQUALS(outCounts.y()[2], hist.y()[1] / 2); + + TS_ASSERT_EQUALS(outFreq.y()[0], histFreq.y()[0]); + TS_ASSERT_EQUALS(outFreq.y()[1], (histFreq.y()[0] + histFreq.y()[1]) / 2); + TS_ASSERT_EQUALS(outFreq.y()[2], histFreq.y()[1]); + + for (size_t i = 0; i < outCounts.y().size(); i++) { + TS_ASSERT_DELTA(outCounts.e()[i], std::sqrt(outCounts.y()[i]), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[i], + std::sqrt(outFreq.y()[i] / (edges[i + 1] - edges[i])), + 1e-14); + } + } + + void testCombineBinsAsymmetric() { + // Handles the case where + // || || becomes: + // | | | + Histogram hist(BinEdges{0, 0.5, 1.5, 2}, Counts{10, 18, 7}); + Histogram histFreq(BinEdges{0, 0.5, 1.5, 2}, Frequencies{16, 32, 8}); + BinEdges edges{0, 1, 2}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[0] + (hist.y()[1] / 2)); + TS_ASSERT_EQUALS(outCounts.y()[1], (hist.y()[1] / 2) + hist.y()[2]); + + TS_ASSERT_EQUALS(outFreq.y()[0], (histFreq.y()[0] + histFreq.y()[1]) / 2); + TS_ASSERT_EQUALS(outFreq.y()[1], (histFreq.y()[1] + histFreq.y()[2]) / 2); + + TS_ASSERT_DELTA(outCounts.e()[0], std::sqrt(outCounts.y()[0]), 1e-14); + TS_ASSERT_DELTA(outCounts.e()[1], std::sqrt(outCounts.y()[1]), 1e-14); + + TS_ASSERT_DELTA(outFreq.e()[0], + std::sqrt(((histFreq.y()[0] / 2) + histFreq.y()[1]) / 2), + 1e-14); + TS_ASSERT_DELTA(outFreq.e()[1], + std::sqrt(((histFreq.y()[2] / 2) + histFreq.y()[1]) / 2), + 1e-14); + } + + void testSplitCombineBinsAsymmetric() { + // Handles the case where + // | | | | becomes: + // || || + Histogram hist(BinEdges{0, 1, 2, 3}, Counts{100, 50, 216}); + Histogram histFreq(BinEdges{0, 1, 2, 3}, Frequencies{210, 19, 80}); + BinEdges edges{0, 0.5, 2.5, 3}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[0] / 2); + TS_ASSERT_EQUALS(outCounts.y()[1], + ((hist.y()[0] + hist.y()[2]) / 2) + hist.y()[1]); + TS_ASSERT_EQUALS(outCounts.y()[2], hist.y()[2] / 2); + + TS_ASSERT_EQUALS(outFreq.y()[0], histFreq.y()[0]); + TS_ASSERT_EQUALS( + outFreq.y()[1], + ((histFreq.y()[0] / 2) + histFreq.y()[1] + (histFreq.y()[2] / 2)) / 2); + TS_ASSERT_EQUALS(outFreq.y()[2], histFreq.y()[2]); + + for (size_t i = 0; i < outCounts.y().size(); i++) { + TS_ASSERT_DELTA(outCounts.e()[i], std::sqrt(outCounts.y()[i]), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[i], + std::sqrt(outFreq.y()[i] / (edges[i + 1] - edges[i])), + 1e-14); + } + } + + void testSplitCombineBinsAsymmetric2() { + // Handles the case where + // || || becomes: + // | | | | + Histogram hist(BinEdges{0, 0.5, 2.5, 3}, Counts{10, 100, 30}); + Histogram histFreq(BinEdges{0, 0.5, 2.5, 3}, Frequencies{17, 8, 15}); + BinEdges edges{0, 1, 2, 3}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[0] + (hist.y()[1] / 4)); + TS_ASSERT_EQUALS(outCounts.y()[1], hist.y()[1] / 2); + TS_ASSERT_EQUALS(outCounts.y()[2], (hist.y()[1] / 4) + hist.y()[2]); + + TS_ASSERT_EQUALS(outFreq.y()[0], (histFreq.y()[0] + histFreq.y()[1]) / 2); + TS_ASSERT_EQUALS(outFreq.y()[1], histFreq.y()[1]); + TS_ASSERT_EQUALS(outFreq.y()[2], (histFreq.y()[1] + histFreq.y()[2]) / 2); + + TS_ASSERT_DELTA(outCounts.e()[0], std::sqrt(outCounts.y()[0]), 1e-14); + TS_ASSERT_DELTA(outCounts.e()[1], std::sqrt(outCounts.y()[1]), 1e-14); + TS_ASSERT_DELTA(outCounts.e()[2], std::sqrt(outCounts.y()[2]), 1e-14); + + TS_ASSERT_DELTA( + outFreq.e()[0], + std::sqrt(((histFreq.y()[0] / 2) + (histFreq.y()[1] * 2)) / 2), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[1], std::sqrt(histFreq.y()[1] * 2), 1e-14); + TS_ASSERT_DELTA( + outFreq.e()[2], + std::sqrt(((histFreq.y()[2] / 2) + (histFreq.y()[1] * 2)) / 2), 1e-14); + } + + void testSmallerBinsAsymmetric() { + // Handles the case where + // | | | | becomes: + // | | | + Histogram hist(BinEdges{0, 1, 2, 3}, Counts{15, 35, 9}); + Histogram histFreq(BinEdges{0, 1, 2, 3}, Frequencies{17, 8, 15}); + BinEdges edges{0.5, 1.5, 2.5}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], (hist.y()[0] + hist.y()[1]) / 2); + TS_ASSERT_EQUALS(outCounts.y()[1], (hist.y()[1] + hist.y()[2]) / 2); + + TS_ASSERT_EQUALS(outFreq.y()[0], (histFreq.y()[0] + histFreq.y()[1]) / 2); + TS_ASSERT_EQUALS(outFreq.y()[1], (histFreq.y()[1] + histFreq.y()[2]) / 2); + + for (size_t i = 0; i < outCounts.y().size(); i++) { + TS_ASSERT_DELTA(outCounts.e()[i], std::sqrt(outCounts.y()[i]), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[i], std::sqrt(outFreq.y()[i]), 1e-14); + } + } + + void testLargerRangeAsymmetric() { + // Handles the case where + // | | | becomes: + // | | | | + Histogram hist(BinEdges{0.5, 1.5, 2.5}, Counts{11, 23}); + Histogram histFreq(BinEdges{0.5, 1.5, 2.5}, Frequencies{100, 14}); + BinEdges edges{0, 1, 2, 3}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[0] / 2); + TS_ASSERT_EQUALS(outCounts.y()[1], (hist.y()[0] + hist.y()[1]) / 2); + TS_ASSERT_EQUALS(outCounts.y()[2], hist.y()[1] / 2); + + TS_ASSERT_EQUALS(outFreq.y()[0], histFreq.y()[0] / 2); + TS_ASSERT_EQUALS(outFreq.y()[1], (histFreq.y()[0] + histFreq.y()[1]) / 2); + TS_ASSERT_EQUALS(outFreq.y()[2], histFreq.y()[1] / 2); + + TS_ASSERT_DELTA(outCounts.e()[0], std::sqrt(outCounts.y()[0]), 1e-14); + TS_ASSERT_DELTA(outCounts.e()[1], std::sqrt(outCounts.y()[1]), 1e-14); + TS_ASSERT_DELTA(outCounts.e()[2], std::sqrt(outCounts.y()[2]), 1e-14); + + TS_ASSERT_DELTA(outFreq.e()[0], std::sqrt(outFreq.y()[0]), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[1], std::sqrt(outFreq.y()[1]), 1e-14); + TS_ASSERT_DELTA(outFreq.e()[2], outFreq.y()[2], 1e-14); + } + + void testSmallerBinsSymmetric() { + // Handles the case where + // | | | | becomes: + // | | + Histogram hist(BinEdges{0, 1, 2, 3}, Counts{15, 35, 9}); + Histogram histFreq(BinEdges{0, 1, 2, 3}, Frequencies{17, 8, 15}); + BinEdges edges{1, 2}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], hist.y()[1]); + TS_ASSERT_EQUALS(outCounts.e()[0], hist.e()[1]); + + TS_ASSERT_EQUALS(outFreq.y()[0], histFreq.y()[1]); + TS_ASSERT_EQUALS(outFreq.e()[0], histFreq.e()[1]); + } + + void testLargerBinsSymmetric() { + // Handles the case where + // | | becomes: + //| | | | + Histogram hist(BinEdges{1, 2}, Counts{20}); + Histogram histFreq(BinEdges{1, 2}, Frequencies{13}); + BinEdges edges{0, 1, 2, 3}; + + auto outCounts = rebin(hist, edges); + auto outFreq = rebin(histFreq, edges); + + TS_ASSERT_EQUALS(outCounts.y()[0], 0); + TS_ASSERT_EQUALS(outCounts.y()[1], hist.y()[0]); + TS_ASSERT_EQUALS(outCounts.y()[2], 0); + + TS_ASSERT_EQUALS(outCounts.e()[0], 0); + TS_ASSERT_DELTA(outCounts.e()[1], std::sqrt(outCounts.y()[1]), 1e-14); + TS_ASSERT_EQUALS(outCounts.e()[2], 0); + + TS_ASSERT_EQUALS(outFreq.y()[0], 0); + TS_ASSERT_EQUALS(outFreq.y()[1], histFreq.y()[0]); + TS_ASSERT_EQUALS(outFreq.y()[2], 0); + + TS_ASSERT_EQUALS(outFreq.e()[0], 0); + TS_ASSERT_DELTA(outFreq.e()[1], std::sqrt(outFreq.y()[1]), 1e-14); + TS_ASSERT_EQUALS(outFreq.e()[2], 0); + } + +private: + Histogram getCountsHistogram() { + return Histogram(BinEdges(10, LinearGenerator(0, 1)), + Counts{10.5, 11.2, 19.3, 25.4, 36.8, 40.3, 17.7, 9.3, 4.6}, + CountStandardDeviations{3.2404, 3.3466, 4.3932, 5.0398, + 6.0663, 6.3482, 4.2071, 3.0496, + 2.1448}); + } + + Histogram getFrequencyHistogram() { + return Histogram( + BinEdges(10, LinearGenerator(0, 1)), + Frequencies{10.5, 11.2, 19.3, 25.4, 36.8, 40.3, 17.7, 9.3, 4.6}, + FrequencyStandardDeviations{3.2404, 3.3466, 4.3932, 5.0398, 6.0663, + 6.3482, 4.2071, 3.0496, 2.1448}); + } +}; + +class RebinTestPerformance : public CxxTest::TestSuite { +public: + // This pair of boilerplate methods prevent the suite being created statically + // This means the constructor isn't called when running other tests + static RebinTestPerformance *createSuite() { + return new RebinTestPerformance(); + } + static void destroySuite(RebinTestPerformance *suite) { delete suite; } + + RebinTestPerformance() + : hist(BinEdges(binSize, LinearGenerator(0, 1))), + histFreq(BinEdges(binSize, LinearGenerator(0, 1))), + smBins(binSize * 2, LinearGenerator(0, 0.5)), + lgBins(binSize / 2, LinearGenerator(0, 2)) { + setupOutput(); + } + + void testRebinCountsSmallerBins() { + for (size_t i = 0; i < nIters; i++) + rebin(hist, smBins); + } + + void testRebinFrequenciesSmallerBins() { + for (size_t i = 0; i < nIters; i++) + rebin(histFreq, smBins); + } + + void testRebinCountsLargerBins() { + for (size_t i = 0; i < nIters; i++) + rebin(hist, lgBins); + } + + void testRebinFrequenciesLargerBins() { + for (size_t i = 0; i < nIters; i++) + rebin(histFreq, lgBins); + } + +private: + const size_t binSize = 10000; + const size_t nIters = 10000; + Histogram hist; + Histogram histFreq; + BinEdges smBins; + BinEdges lgBins; + + void setupOutput() { + Counts counts(binSize - 1, 0); + CountStandardDeviations countErrors(counts.size(), 0); + Frequencies freqs(binSize - 1, 0); + FrequencyStandardDeviations freqErrors(freqs.size(), 0); + + hist.setCounts(counts); + hist.setCountStandardDeviations(countErrors); + histFreq.setFrequencies(freqs); + histFreq.setFrequencyStandardDeviations(freqErrors); + } +}; + +#endif /* MANTID_HISTOGRAMDATA_REBINTEST_H_ */ \ No newline at end of file diff --git a/Framework/Kernel/inc/MantidKernel/DataService.h b/Framework/Kernel/inc/MantidKernel/DataService.h index 3214c7f51b177be2941cd0660650a546f48453c0..c29896cf0470b39b3362f53f97ae3d8fa6728add 100644 --- a/Framework/Kernel/inc/MantidKernel/DataService.h +++ b/Framework/Kernel/inc/MantidKernel/DataService.h @@ -136,12 +136,16 @@ public: BeforeReplaceNotification(const std::string &name, const boost::shared_ptr<T> obj, const boost::shared_ptr<T> newObj) - : DataServiceNotification(name, obj), m_newObject(newObj) {} + : DataServiceNotification(name, obj), m_newObject(newObj), + m_oldObject(obj) {} const boost::shared_ptr<T> newObject() const { return m_newObject; } ///< Returns the pointer to the new object. + const boost::shared_ptr<T> oldObject() const { return m_oldObject; } + private: boost::shared_ptr<T> m_newObject; ///< shared pointer to the object + boost::shared_ptr<T> m_oldObject; }; /// AfterReplaceNotification is sent after an object is replaced in the @@ -310,28 +314,40 @@ public: void rename(const std::string &oldName, const std::string &newName) { checkForEmptyName(newName); + if (oldName == newName) { + g_log.warning("Rename: The existing name matches the new name"); + return; + } + // Make DataService access thread-safe std::unique_lock<std::recursive_mutex> lock(m_mutex); - auto it = datamap.find(oldName); - if (it == datamap.end()) { + auto existingNameIter = datamap.find(oldName); + if (existingNameIter == datamap.end()) { lock.unlock(); g_log.warning(" rename '" + oldName + "' cannot be found"); return; } - // delete the object with the old name - auto object = std::move(it->second); - datamap.erase(it); + auto existingNameObject = std::move(existingNameIter->second); + auto targetNameIter = datamap.find(newName); + + // If we are overriding send a notification for observers + if (targetNameIter != datamap.end()) { + auto targetNameObject = targetNameIter->second; + // As we are renaming the existing name turns into the new name + notificationCenter.postNotification(new BeforeReplaceNotification( + newName, targetNameObject, existingNameObject)); + } + + datamap.erase(existingNameIter); - // if there is another object which has newName delete it - auto it2 = datamap.find(newName); - if (it2 != datamap.end()) { + if (targetNameIter != datamap.end()) { + targetNameIter->second = std::move(existingNameObject); notificationCenter.postNotification( - new AfterReplaceNotification(newName, object)); - it2->second = std::move(object); + new AfterReplaceNotification(newName, targetNameIter->second)); } else { - if (!(datamap.emplace(newName, std::move(object)).second)) { + if (!(datamap.emplace(newName, std::move(existingNameObject)).second)) { // should never happen lock.unlock(); std::string error = diff --git a/Framework/Kernel/inc/MantidKernel/MultiThreaded.h b/Framework/Kernel/inc/MantidKernel/MultiThreaded.h index c7b8bc90f5a152bc4b9fca56b3122e3ae7351f65..07014cbba03a54ca45dede942876485463bc8b8b 100644 --- a/Framework/Kernel/inc/MantidKernel/MultiThreaded.h +++ b/Framework/Kernel/inc/MantidKernel/MultiThreaded.h @@ -1,11 +1,75 @@ #ifndef MANTID_KERNEL_MULTITHREADED_H_ #define MANTID_KERNEL_MULTITHREADED_H_ +#include "MantidKernel/DataItem.h" + #include <mutex> namespace Mantid { -namespace Kernel {} // namespace -} // namespace +namespace Kernel { + +/** Thread-safety check + * Checks the workspace to ensure it is suitable for multithreaded access. + * NULL workspaces are assumed suitable + * @param workspace pointer to workspace to verify. + * @return Whether workspace is threadsafe. + */ +template <typename Arg> +inline typename std::enable_if<std::is_pointer<Arg>::value, bool>::type +threadSafe(Arg workspace) { + static_assert( + std::is_base_of<DataItem, typename std::remove_pointer<Arg>::type>::value, + "Parameter must be derived from Mantid::Kernel::DataItem!"); + return !workspace || workspace->threadSafe(); +} + +/** Thread-safety check + * Checks the workspace to ensure it is suitable for multithreaded access. + * NULL workspaces are assumed suitable + * @param workspace pointer to workspace to verify. + * @param others pointers to all other workspaces which need to be checked. + * @return whether workspace is threadsafe. + */ +template <typename Arg, typename... Args> +inline typename std::enable_if<std::is_pointer<Arg>::value, bool>::type +threadSafe(Arg workspace, Args &&... others) { + static_assert( + std::is_base_of<DataItem, typename std::remove_pointer<Arg>::type>::value, + "Parameter must be derived from Mantid::Kernel::DataItem!"); + return (!workspace || workspace->threadSafe()) && + threadSafe(std::forward<Args>(others)...); +} + +/** Thread-safety check + * Checks the workspace to ensure it is suitable for multithreaded access. + * @param workspace reference to workspace to verify. + * @return Whether workspace is threadsafe. + */ +template <typename Arg> +inline typename std::enable_if<!std::is_pointer<Arg>::value, bool>::type +threadSafe(const Arg &workspace) { + static_assert(std::is_base_of<DataItem, Arg>::value, + "Parameter must be derived from Mantid::Kernel::DataItem!"); + return workspace.threadSafe(); +} + +/** Thread-safety check + * Checks the workspace to ensure it is suitable for multithreaded access. + * @param workspace reference to workspace to verify. + * @param others references or pointers to all other workspaces which need to be + * checked. + * @return whether workspace is threadsafe. + */ +template <typename Arg, typename... Args> +inline typename std::enable_if<!std::is_pointer<Arg>::value, bool>::type +threadSafe(const Arg &workspace, Args &&... others) { + static_assert(std::is_base_of<DataItem, Arg>::value, + "Parameter must be derived from Mantid::Kernel::DataItem!"); + return workspace.threadSafe() && threadSafe(std::forward<Args>(others)...); +} + +} // namespace Kernel +} // namespace Mantid // The syntax used to define a pragma within a macro is different on windows and // GCC @@ -98,16 +162,6 @@ namespace Kernel {} // namespace PRAGMA(omp parallel for if ( ( !workspace1 || workspace1->threadSafe() ) && \ ( !workspace2 || workspace2->threadSafe() ) )) -/** Includes code to add OpenMP commands to run the next for loop in parallel. -* All three workspaces are checked to ensure they are suitable for -*multithreaded access -* but NULL workspaces are assumed to be safe -*/ -#define PARALLEL_FOR3(workspace1, workspace2, workspace3) \ - PRAGMA(omp parallel for if ( (!workspace1 || workspace1->threadSafe()) && \ - ( !workspace2 || workspace2->threadSafe() ) && \ - ( !workspace3 || workspace3->threadSafe() ) )) - /** Ensures that the next execution line or block is only executed if * there are multple threads execting in this region */ @@ -164,7 +218,6 @@ namespace Kernel {} // namespace #define PARALLEL_FOR_NO_WSP_CHECK_FIRSTPRIVATE2(variable1, variable2) #define PARALLEL_FOR1(workspace1) #define PARALLEL_FOR2(workspace1, workspace2) -#define PARALLEL_FOR3(workspace1, workspace2, workspace3) #define IF_PARALLEL if (false) #define IF_NOT_PARALLEL #define PARALLEL_CRITICAL(name) diff --git a/Framework/Kernel/src/DateAndTime.cpp b/Framework/Kernel/src/DateAndTime.cpp index 21315ee18dcd1a53d6db4fbba106aeb4f7ac1718..02f4c1b7f0927ae3d1c959d552f43eff3d807482 100644 --- a/Framework/Kernel/src/DateAndTime.cpp +++ b/Framework/Kernel/src/DateAndTime.cpp @@ -43,7 +43,6 @@ std::tm *gmtime_r_portable(const std::time_t *clock, struct std::tm *result) { #ifdef _WIN32 // Windows implementation if (!gmtime_s(result, clock)) { // Returns zero if successful - // cppcheck-suppress CastIntegerToAddressAtReturn return result; } else { // Returned some non-zero error code return NULL; diff --git a/Framework/Kernel/test/DataServiceTest.h b/Framework/Kernel/test/DataServiceTest.h index 41ba0ee0f7cb46d54aa60b2b74e4518735b0e749..14b39c910d0b581e8f3859a876634a5ea63a5839 100644 --- a/Framework/Kernel/test/DataServiceTest.h +++ b/Framework/Kernel/test/DataServiceTest.h @@ -129,8 +129,8 @@ public: std::runtime_error); } - void handleAfterReplaceNotification( - const Poco::AutoPtr<FakeDataService::AfterReplaceNotification> &) { + void handleBeforeReplaceNotification( + const Poco::AutoPtr<FakeDataService::BeforeReplaceNotification> &) { ++notificationFlag; } @@ -140,8 +140,8 @@ public: } void test_rename() { - Poco::NObserver<DataServiceTest, FakeDataService::AfterReplaceNotification> - observer(*this, &DataServiceTest::handleAfterReplaceNotification); + Poco::NObserver<DataServiceTest, FakeDataService::BeforeReplaceNotification> + observer(*this, &DataServiceTest::handleBeforeReplaceNotification); svc.notificationCenter.addObserver(observer); Poco::NObserver<DataServiceTest, FakeDataService::RenameNotification> observer2(*this, &DataServiceTest::handleRenameNotification); @@ -157,7 +157,9 @@ public: svc.rename("One", "One")); TSM_ASSERT_THROWS_NOTHING("Should be just a warning if object not there", svc.rename("NotThere", "NewName")); - + // We aren't doing anything so no notifications should post + TSM_ASSERT_EQUALS("No notifications should have been posted", + notificationFlag, 0); svc.rename( "one", "anotherOne"); // Note: Rename is case-insensitive on the old name @@ -167,17 +169,20 @@ public: TSM_ASSERT_EQUALS("One should have been renamed to anotherOne", svc.retrieve("anotherOne"), one); - TSM_ASSERT_EQUALS("The observers should have been called 2 times in total", - notificationFlag, 2); + TSM_ASSERT_EQUALS("The observers should have been called once", + notificationFlag, 1); + notificationFlag = 0; svc.rename("Two", "anotherOne"); TS_ASSERT_EQUALS(svc.size(), 1); TSM_ASSERT_THROWS("Two should have been renamed to anotherOne", svc.retrieve("two"), Exception::NotFoundError); TSM_ASSERT_EQUALS("Two should have been renamed to anotherOne", svc.retrieve("anotherOne"), two); - TSM_ASSERT_EQUALS("The observers should have been called 4 times in total", - notificationFlag, 4); + // As we are renaming to an existing workspace there should be 2 + // notifications + TSM_ASSERT_EQUALS("The observers should have been called 2 times in total", + notificationFlag, 2); svc.notificationCenter.removeObserver(observer); svc.notificationCenter.removeObserver(observer2); diff --git a/Framework/Kernel/test/RebinHistogramTest.h b/Framework/Kernel/test/RebinHistogramTest.h index 011f6863bd4bf180d5cc69334cf3a1eadd349229..d4016988f3519453fc37965152cfc7bbc6d2abb5 100644 --- a/Framework/Kernel/test/RebinHistogramTest.h +++ b/Framework/Kernel/test/RebinHistogramTest.h @@ -1,9 +1,11 @@ #ifndef REBINHISTOGRAM_TEST_H_ #define REBINHISTOGRAM_TEST_H_ +#include "MantidKernel/VectorHelper.h" +#include <algorithm> #include <cxxtest/TestSuite.h> +#include <numeric> #include <vector> -#include "MantidKernel/VectorHelper.h" /// @author Laurent C Chapon, ISIS Facility, Rutherford Appleton Laboratory /// 13/03/2009 @@ -52,4 +54,72 @@ public: } }; +class RebinHistogramTestPerformance : public CxxTest::TestSuite { +public: + RebinHistogramTestPerformance *createSuite() { + return new RebinHistogramTestPerformance(); + } + + void destroySuite(RebinHistogramTestPerformance *suite) { delete suite; } + + RebinHistogramTestPerformance() { + setupHistogram(); + setupOutput(); + } + + void testRebinSmaller() { + auto size = smallerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + Mantid::Kernel::VectorHelper::rebinHistogram( + binEdges, counts, errors, smallerBinEdges, yout, eout, false); + } + } + + void testRebinLarger() { + auto size = largerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + Mantid::Kernel::VectorHelper::rebinHistogram( + binEdges, counts, errors, largerBinEdges, yout, eout, false); + } + } + +private: + const size_t binSize = 10000; + const size_t nIters = 10000; + std::vector<double> binEdges; + std::vector<double> counts; + std::vector<double> errors; + std::vector<double> smallerBinEdges; + std::vector<double> largerBinEdges; + + void setupHistogram() { + binEdges.resize(binSize); + counts.resize(binSize - 1); + errors.resize(binSize - 1); + + std::iota(binEdges.begin(), binEdges.end(), 0); + } + + void setupOutput() { + smallerBinEdges.resize(binSize * 2); + largerBinEdges.resize(binSize / 2); + + auto binWidth = binEdges[1] - binEdges[0]; + + for (size_t i = 0; i < binSize - 1; i++) { + smallerBinEdges[2 * i] = binEdges[i]; + smallerBinEdges[(2 * i) + 1] = (binEdges[i] + binEdges[i + 1]) / 2; + } + smallerBinEdges[2 * (binSize - 1)] = binEdges.back(); + smallerBinEdges.back() = binEdges.back() + (binWidth / 2); + + for (size_t i = 0; i < largerBinEdges.size(); i++) + largerBinEdges[i] = binEdges[(2 * i)]; + } +}; + #endif // REBINHISTOGRAM_TEST_H_/ diff --git a/Framework/Kernel/test/VectorHelperTest.h b/Framework/Kernel/test/VectorHelperTest.h index 359f70db939eaa2e179f98e11bd2f53aedb21e2d..5deed794647f21622951a891ceeec19f3efa48ba 100644 --- a/Framework/Kernel/test/VectorHelperTest.h +++ b/Framework/Kernel/test/VectorHelperTest.h @@ -4,8 +4,10 @@ #include "MantidKernel/System.h" #include "MantidKernel/Timer.h" #include "MantidKernel/VectorHelper.h" -#include <cxxtest/TestSuite.h> +#include <algorithm> #include <cstdlib> +#include <cxxtest/TestSuite.h> +#include <numeric> using namespace Mantid::Kernel; @@ -429,4 +431,107 @@ private: std::vector<double> m_test_bins; }; +class VectorHelperTestPerformance : public CxxTest::TestSuite { +public: + VectorHelperTestPerformance *createSuite() { + return new VectorHelperTestPerformance(); + } + void destroySuite(VectorHelperTestPerformance *suite) { delete suite; } + + VectorHelperTestPerformance() { + setupHistogram(); + setupOutput(); + } + + void testRebinSmaller() { + auto size = smallerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + VectorHelper::rebin(binEdges, counts, errors, smallerBinEdges, yout, eout, + false, false); + } + } + + void testRebinSmallerFrequencies() { + auto size = smallerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + VectorHelper::rebin(binEdges, frequencies, frequencyErrors, + smallerBinEdges, yout, eout, true, false); + } + } + + void testRebinLarger() { + auto size = largerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + VectorHelper::rebin(binEdges, counts, errors, largerBinEdges, yout, eout, + false, false); + } + } + + void testRebinLargerFrequencies() { + auto size = largerBinEdges.size() - 1; + for (size_t i = 0; i < nIters; i++) { + std::vector<double> yout(size); + std::vector<double> eout(size); + VectorHelper::rebin(binEdges, frequencies, frequencyErrors, + largerBinEdges, yout, eout, true, false); + } + } + +private: + const size_t binSize = 10000; + const size_t nIters = 10000; + std::vector<double> binEdges; + std::vector<double> counts; + std::vector<double> frequencies; + std::vector<double> errors; + std::vector<double> frequencyErrors; + std::vector<double> smallerBinEdges; + std::vector<double> largerBinEdges; + + void setupHistogram() { + binEdges.resize(binSize); + frequencies.resize(binSize - 1); + frequencyErrors.resize(binSize - 1); + counts.resize(binSize - 1); + errors.resize(binSize - 1); + + std::iota(binEdges.begin(), binEdges.end(), 0); + std::generate(counts.begin(), counts.end(), + []() { return static_cast<double>(rand() % 1000); }); + + for (size_t i = 0; i < counts.size(); i++) + frequencies[i] = counts[i] / (binEdges[i + 1] - binEdges[i]); + + std::transform(counts.cbegin(), counts.cend(), errors.begin(), + [](const double count) { return sqrt(count); }); + + std::transform(frequencies.cbegin(), frequencies.cend(), + frequencyErrors.begin(), + [](const double freq) { return sqrt(freq); }); + } + + void setupOutput() { + smallerBinEdges.resize(binSize * 2); + largerBinEdges.resize(binSize / 2); + + auto binWidth = binEdges[1] - binEdges[0]; + + for (size_t i = 0; i < binSize - 1; i++) { + smallerBinEdges[2 * i] = binEdges[i]; + smallerBinEdges[(2 * i) + 1] = (binEdges[i] + binEdges[i + 1]) / 2; + } + smallerBinEdges[2 * (binSize - 1)] = binEdges.back(); + smallerBinEdges.back() = binEdges.back() + (binWidth / 2); + + for (size_t i = 0; i < largerBinEdges.size(); i++) + largerBinEdges[i] = binEdges[(2 * i)]; + } +}; + #endif /* MANTID_KERNEL_VECTORHELPERTEST_H_ */ diff --git a/Framework/MDAlgorithms/src/FindPeaksMD.cpp b/Framework/MDAlgorithms/src/FindPeaksMD.cpp index f5fa15140917b9c7cc3ea36ad2893aa256c04b63..5c14e785bc631e720b64c4696bbb0b77245aa37e 100644 --- a/Framework/MDAlgorithms/src/FindPeaksMD.cpp +++ b/Framework/MDAlgorithms/src/FindPeaksMD.cpp @@ -270,7 +270,7 @@ void FindPeaksMD::findPeaks(typename MDEventWorkspace<MDE, nd>::sptr ws) { // peak. signal_t thresholdDensity = ws->getBox()->getSignalNormalized() * DensityThresholdFactor * m_densityScaleFactor; - if (std::isfinite(thresholdDensity)) { + if (!std::isfinite(thresholdDensity)) { g_log.warning() << "Infinite or NaN overall density found. Your input data " "may be invalid. Using a 0 threshold instead.\n"; diff --git a/Framework/PythonInterface/mantid/simpleapi.py b/Framework/PythonInterface/mantid/simpleapi.py index 755d4d2c279bee08941fa05fe76a29c170681e83..1353c38f76272c662b3932b26d438da856735bbc 100644 --- a/Framework/PythonInterface/mantid/simpleapi.py +++ b/Framework/PythonInterface/mantid/simpleapi.py @@ -781,52 +781,38 @@ def _set_logging_option(algm_obj, kwargs): def set_properties(alg_object, *args, **kwargs): """ - Set all of the properties of the algorithm + Set all of the properties of the algorithm. There is no guarantee of + the order the properties will be set :param alg_object: An initialised algorithm object :param *args: Positional arguments :param **kwargs: Keyword arguments """ - args_dict = {} - if len(args) > 0: - mandatory_props = alg_object.mandatoryProperties() - # Remove any already in kwargs - for key in kwargs.keys(): - try: - mandatory_props.remove(key) - except ValueError: - pass - # If have any left - if len(mandatory_props) > 0: - # Now pair up the properties & arguments - for (key, arg) in zip(mandatory_props[:len(args)], args): - args_dict[key] = arg - else: - raise RuntimeError("Positional argument(s) provided but none are required. Check function call.") - - # As dictionaries are no longer ordered in Python 3 we need to - # pass the positional arguments before the keyword arguments as some - # algorithms require the positional args to be set first - _set_alg_properties(arguments=args_dict, algorithm=alg_object) - _set_alg_properties(arguments=kwargs, algorithm=alg_object) - -def _set_alg_properties(arguments, algorithm): - """ - Loops over all keys in a dictionary passing the values to the algorithm - :param arguments: Dictionary containing key-value arguments to set - :param algorithm: The algorithm to pass these to - """ - for key in arguments.keys(): - value = arguments[key] + def do_set_property(name, value): if value is None: - continue + return # The correct parent/child relationship is not quite set up yet: #5157 # ChildAlgorithms in Python are marked as children but their output is in the # ADS meaning we cannot just set DataItem properties by value. At the moment # they are just set with strings if isinstance(value, _kernel.DataItem): - algorithm.setPropertyValue(key, value.name()) + alg_object.setPropertyValue(key, value.name()) else: - algorithm.setProperty(key, value) + alg_object.setProperty(key, value) + # end + if len(args) > 0: + mandatory_props = alg_object.mandatoryProperties() + else: + mandatory_props = [] + if len(kwargs) > 0: + for (key, value) in iteritems(kwargs): + do_set_property(key, value) + try: + mandatory_props.remove(key) + except ValueError: + pass + if len(args) > 0: + for (key, value) in zip(mandatory_props[:len(args)], args): + do_set_property(key, value) def _create_algorithm_function(name, version, algm_object): diff --git a/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsSingleAxis.py b/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsSingleAxis.py index 13881bc6e779813582ba5def3c8e309206d3904b..5fb6f9009c1af9eba744fc686f9dc1d951b6d158 100644 --- a/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsSingleAxis.py +++ b/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsSingleAxis.py @@ -1,4 +1,5 @@ # pylint: disable=too-many-branches,too-many-locals, invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -51,7 +52,7 @@ class AngularAutoCorrelationsSingleAxis(PythonAlgorithm): # Convert description object to string via for loop. The original object has strange formatting particleID = '' for i in description: - particleID += i + particleID += i.decode('UTF-8') # Extract particle id's from string using regular expressions p_atoms=re.findall(r"A\('[a-z]+\d+',\d+", particleID) @@ -250,7 +251,7 @@ class AngularAutoCorrelationsSingleAxis(PythonAlgorithm): # Returns angular auto-correlation of a normalised time-dependent 3-vector num=np.shape(vector)[0] norm=np.arange(np.ceil(num/2.0),num+1) - norm=np.append(norm,(np.arange(num/2+1,num)[::-1])) + norm=np.append(norm,(np.arange(int(num/2)+1,num)[::-1])) # x dimension autoCorr=np.divide(np.correlate(vector[:,0],vector[:,0],"same"),norm) @@ -263,7 +264,7 @@ class AngularAutoCorrelationsSingleAxis(PythonAlgorithm): def fold_correlation(self,omega): # Folds an array with symmetrical values into half by averaging values around the centre - right_half=omega[len(omega)/2:] + right_half=omega[int(len(omega)/2):] left_half=omega[:int(np.ceil(len(omega)/2.0))][::-1] return (left_half+right_half)/2.0 diff --git a/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsTwoAxes.py b/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsTwoAxes.py index 0198b9d415273289181692016994d247e5f099d8..7177bd93d33e151c468fc20c1c92127c95110e90 100644 --- a/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsTwoAxes.py +++ b/Framework/PythonInterface/plugins/algorithms/AngularAutoCorrelationsTwoAxes.py @@ -1,4 +1,5 @@ # pylint: disable=too-many-branches,too-many-locals, invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -54,7 +55,7 @@ class AngularAutoCorrelationsTwoAxes(PythonAlgorithm): # Convert description object to string via for loop. The original object has strange formatting particleID = '' for i in description: - particleID += i + particleID += i.decode('UTF-8') # Extract particle id's from string using regular expressions p_atoms=re.findall(r"A\('[a-z]+\d+',\d+", particleID) @@ -299,7 +300,7 @@ class AngularAutoCorrelationsTwoAxes(PythonAlgorithm): # Returns angular auto-correlation of a normalised time-dependent 3-vector num=np.shape(vector)[0] norm=np.arange(np.ceil(num/2.0),num+1) - norm=np.append(norm,(np.arange(num/2+1,num)[::-1])) + norm=np.append(norm,(np.arange(int(num/2)+1,num)[::-1])) # x dimension autoCorr=np.divide(np.correlate(vector[:,0],vector[:,0],"same"),norm) @@ -312,7 +313,7 @@ class AngularAutoCorrelationsTwoAxes(PythonAlgorithm): def fold_correlation(self,omega): # Folds an array with symmetrical values into half by averaging values around the centre - right_half=omega[len(omega)/2:] + right_half=omega[int(len(omega))/2:] left_half=omega[:int(np.ceil(len(omega)/2.0))][::-1] return (left_half+right_half)/2.0 diff --git a/Framework/PythonInterface/plugins/algorithms/BASISReduction.py b/Framework/PythonInterface/plugins/algorithms/BASISReduction.py index 80705b5a8b24801a8d5e7993fa2ef40abb46f28f..c27087d2bc7ad0ed2d339432b4acf41c82b0fa89 100644 --- a/Framework/PythonInterface/plugins/algorithms/BASISReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/BASISReduction.py @@ -10,8 +10,6 @@ from os.path import join as pjoin DEFAULT_RANGE = [6.24, 6.30] DEFAULT_MASK_GROUP_DIR = "/SNS/BSS/shared/autoreduce/new_masks_08_12_2015" -DEFAULT_VANADIUM_ENERGY_RANGE = [-0.0034, 0.0034] # meV -DEFAULT_VANADIUM_BINS = [-0.0034, 0.068, 0.0034] # meV DEFAULT_CONFIG_DIR = config["instrumentDefinition.directory"] # BASIS allows two possible reflections, with associated default properties @@ -19,15 +17,20 @@ DEFAULT_CONFIG_DIR = config["instrumentDefinition.directory"] REFLECTIONS_DICT = {"silicon111": {"name": "silicon111", "energy_bins": [-150, 0.4, 500], # micro-eV "q_bins": [0.3, 0.2, 1.9], # inverse Angstroms - "mask_file": "BASIS_Mask_ThreeQuartersRemain_SouthTop_NorthTop_NorthBottom_MorePixelsEliminated_08122015.xml", + "mask_file": "BASIS_Mask_default_111.xml", "parameter_file": "BASIS_silicon_111_Parameters.xml", - "default_energy": 2.0826}, # mili-eV + "default_energy": 2.0826, # mili-eV + "vanadium_bins": [-0.0034, 0.068, 0.0034] # mili-eV + }, "silicon311": {"name": "silicon311", "energy_bins": [-740, 1.6, 740], "q_bins": [0.5, 0.2, 3.7], - "mask_file": "BASIS_Mask_OneQuarterRemains_SouthBottom.xml", + "mask_file": "BASIS_Mask_default_311.xml", "parameter_file": "BASIS_silicon_311_Parameters.xml", - "default_energy": 7.6368}} + "default_energy": 7.6368, # mili-eV + "vanadium_bins": [-0.015, 0.030, 0.015]# mili-eV + } + } #pylint: disable=too-many-instance-attributes @@ -38,20 +41,24 @@ class BASISReduction(PythonAlgorithm): _long_inst = None _extension = None _doIndiv = None - _noMonNorm = None + _groupDetOpt = None _overrideMask = None _dMask = None _run_list = None # a list of runs, or a list of sets of runs _samWs = None - _samMonWs = None + _samWsRun = None _samSqwWs = None + _debugMode = False # delete intermediate workspaces if False def __init__(self): PythonAlgorithm.__init__(self) self._normalizeToFirst = False + # properties related to monitor + self._noMonNorm = None + # properties related to the chosen reflection self._reflection = None # entry in the reflections dictionary self._etBins = None @@ -143,6 +150,7 @@ class BASISReduction(PythonAlgorithm): self.setPropertySettings("NormWavelengthRange", ifDivideByVanadium) self.setPropertyGroup("NormWavelengthRange", titleDivideByVanadium) + #pylint: disable=too-many-branches def PyExec(self): config['default.facility'] = "SNS" config['default.instrument'] = self._long_inst @@ -191,20 +199,22 @@ class BASISReduction(PythonAlgorithm): # norm_runs encompasses a single set, thus _getRuns returns # a list of only one item norm_set = self._getRuns(norm_runs, doIndiv=False)[0] - self._normWs = self._sum_and_calibrate(norm_set, extra_extension="_norm") + normWs = self._sum_and_calibrate(norm_set, extra_extension="_norm") # This rebin integrates counts onto a histogram of a single bin if self._normalizationType == "by detectorID": normRange = self.getProperty("NormWavelengthRange").value self._normRange = [normRange[0], normRange[1]-normRange[0], normRange[1]] - sapi.Rebin(InputWorkspace=self._normWs, OutputWorkspace=self._normWs, Params=self._normRange) + sapi.Rebin(InputWorkspace=normWs, OutputWorkspace=normWs, Params=self._normRange) # FindDetectorsOutsideLimits to be substituted by MedianDetectorTest - sapi.FindDetectorsOutsideLimits(InputWorkspace=self._normWs, OutputWorkspace="BASIS_NORM_MASK") + sapi.FindDetectorsOutsideLimits(InputWorkspace=normWs, OutputWorkspace="BASIS_NORM_MASK") # additional reduction steps when normalizing by Q slice if self._normalizationType == "by Q slice": - self._normWs = self._group_and_SofQW(self._normWs, DEFAULT_VANADIUM_BINS, isSample=False) + self._normWs = self._group_and_SofQW(normWs, self._etBins, isSample=False) + if not self._debugMode: + sapi.DeleteWorkspace(normWs) # Delete vanadium events file ########################## ## Process the sample ## @@ -213,15 +223,16 @@ class BASISReduction(PythonAlgorithm): for run_set in self._run_list: self._samWs = self._sum_and_calibrate(run_set) self._samWsRun = str(run_set[0]) - # Mask detectors with insufficient Vanadium signal - if self._doNorm: - sapi.MaskDetectors(Workspace=self._samWs, MaskedWorkspace='BASIS_NORM_MASK') - # Divide by Vanadium + # Divide by Vanadium detector ID, if pertinent if self._normalizationType == "by detector ID": + # Mask detectors with insufficient Vanadium signal before dividing + sapi.MaskDetectors(Workspace=self._samWs, MaskedWorkspace='BASIS_NORM_MASK') sapi.Divide(LHSWorkspace=self._samWs, RHSWorkspace=self._normWs, OutputWorkspace=self._samWs) # additional reduction steps self._samSqwWs = self._group_and_SofQW(self._samWs, self._etBins, isSample=True) - # Divide by Vanadium + if not self._debugMode: + sapi.DeleteWorkspace(self._samWs) # delete events file + # Divide by Vanadium Q slice, if pertinent if self._normalizationType == "by Q slice": sapi.Divide(LHSWorkspace=self._samSqwWs, RHSWorkspace=self._normWs, OutputWorkspace=self._samSqwWs) # Clear mask from reduced file. Needed for binary operations @@ -245,6 +256,12 @@ class BASISReduction(PythonAlgorithm): processed_filename = self._makeRunName(self._samWsRun, False) + extension sapi.SaveNexus(Filename=processed_filename, InputWorkspace=self._samSqwWs) + if not self._debugMode: + sapi.DeleteWorkspace("BASIS_MASK") # delete the mask + if self._doNorm and bool(norm_runs): + sapi.DeleteWorkspace("BASIS_NORM_MASK") # delete vanadium mask + sapi.DeleteWorkspace(self._normWs) # Delete vanadium S(Q) + def _getRuns(self, rlist, doIndiv=True): """ Create sets of run numbers for analysis. A semicolon indicates a @@ -276,9 +293,9 @@ class BASISReduction(PythonAlgorithm): def _makeRunFile(self, run): """ - Make name like BSS24234 + Make name like BSS_24234_event.nxs """ - return self._short_inst + str(run) + return "{0}_{1}_event.nxs".format(self._short_inst,str(run)) def _sumRuns(self, run_set, sam_ws, mon_ws, extra_ext=None): """ @@ -339,9 +356,11 @@ class BASISReduction(PythonAlgorithm): """ wsName = self._makeRunName(run_set[0]) wsName += extra_extension - wsMonName = wsName + "_monitors" - self._sumRuns(run_set, wsName, wsMonName, extra_extension) - self._calibData(wsName, wsMonName) + wsName_mon = wsName + "_monitors" + self._sumRuns(run_set, wsName, wsName_mon, extra_extension) + self._calibData(wsName, wsName_mon) + if not self._debugMode: + sapi.DeleteWorkspace(wsName_mon) # delete monitors return wsName def _group_and_SofQW(self, wsName, etRebins, isSample=True): @@ -367,6 +386,9 @@ class BASISReduction(PythonAlgorithm): wsSqwName = wsName+'_divided_sqw' if isSample and self._doNorm else wsName+'_sqw' sapi.SofQW3(InputWorkspace=wsName, QAxisBinning=self._qBins, EMode='Indirect', EFixed=self._reflection["default_energy"], OutputWorkspace=wsSqwName) + # Rebin the vanadium within the elastic line + if not isSample: + sapi.Rebin(InputWorkspace=wsSqwName, OutputWorkspace=wsSqwName, Params=self._reflection["vanadium_bins"]) return wsSqwName def _ScaleY(self, wsName): diff --git a/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py b/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py index b4cdb39855b71ee92b867563cb6a85e442e1d5a0..aaec28d2bc621c4c0270f683da087d6237c8f0a2 100644 --- a/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py +++ b/Framework/PythonInterface/plugins/algorithms/CalculateSampleTransmission.py @@ -12,6 +12,7 @@ class CalculateSampleTransmission(PythonAlgorithm): _bin_params = None _chemical_formula = None + _density_type = None _density = None _thickness = None _output_ws = None @@ -31,8 +32,12 @@ class CalculateSampleTransmission(PythonAlgorithm): validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='NumberDensity', defaultValue=0.1, - doc='Number denisty per atom (atoms/Angstrom^3). Default=0.1') + self.declareProperty(name='DensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + + self.declareProperty(name='Density', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3). Default=0.1') self.declareProperty(name='Thickness', defaultValue=0.1, doc='Sample thickness (cm). Default=0.1') @@ -43,9 +48,9 @@ class CalculateSampleTransmission(PythonAlgorithm): def validateInputs(self): issues = dict() - density = self.getProperty('NumberDensity').value + density = self.getProperty('Density').value if density < 0.0: - issues['NumberDensity'] = 'NumberDensity must be positive' + issues['Density'] = 'Density must be positive' thickness = self.getProperty('Thickness').value if thickness < 0.0: @@ -61,6 +66,11 @@ class CalculateSampleTransmission(PythonAlgorithm): VerticalAxisUnit='Text', VerticalAxisValues='Transmission,Scattering') Rebin(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws, Params=self._bin_params) + + if self._density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._chemical_formula).setMassDensity(self._density).build() + self._density = mat.numberDensity SetSampleMaterial(InputWorkspace=self._output_ws, ChemicalFormula=self._chemical_formula, SampleNumberDensity=self._density) ConvertToPointData(InputWorkspace=self._output_ws, OutputWorkspace=self._output_ws) @@ -87,7 +97,8 @@ class CalculateSampleTransmission(PythonAlgorithm): self._bin_params = self.getPropertyValue('WavelengthRange') self._chemical_formula = self.getPropertyValue('ChemicalFormula') - self._density = self.getProperty('NumberDensity').value + self._density_type = self.getPropertyValue('DensityType') + self._density = self.getProperty('Density').value self._thickness = self.getProperty('Thickness').value self._output_ws = self.getPropertyValue('OutputWorkspace') @@ -95,7 +106,7 @@ class CalculateSampleTransmission(PythonAlgorithm): """ Calculates transmission and scattering at a given wavelength. - @param wavelength Wavelength at which to calculate (in Angstrom) + @param wavelength Wavelength at which to calculate (in Angstroms) @return Tuple of transmission and scattering percentages """ diff --git a/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py b/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py index e17d2ecee3cad4452eb67f40295f3445730b9ea5..cdc4acc40aadfc5bcd5b0cea0a4ece3fc48cab17 100644 --- a/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py +++ b/Framework/PythonInterface/plugins/algorithms/CalibrateRectangularDetectors.py @@ -6,7 +6,6 @@ from mantid.kernel import * from mantid.simpleapi import * import os from time import strftime -from mantid import config from mantid.kernel import Direction COMPRESS_TOL_TOF = .01 diff --git a/Framework/PythonInterface/plugins/algorithms/ComputeCalibrationCoefVan.py b/Framework/PythonInterface/plugins/algorithms/ComputeCalibrationCoefVan.py index d4590765fc39fc669331aa4ad9f58f3801e0835b..905ef1818e5378073963ac722f9fcbfa197b2df6 100644 --- a/Framework/PythonInterface/plugins/algorithms/ComputeCalibrationCoefVan.py +++ b/Framework/PythonInterface/plugins/algorithms/ComputeCalibrationCoefVan.py @@ -63,9 +63,9 @@ class ComputeCalibrationCoefVan(PythonAlgorithm): if table.rowCount() != inws.getNumberHistograms(): issues['EPPTable'] = "Number of rows in the table must match to the input workspace dimension." # table must have 'PeakCentre' and 'Sigma' columns - if not 'PeakCentre' in table.getColumnNames(): + if 'PeakCentre' not in table.getColumnNames(): issues['EPPTable'] = "EPP Table must have the PeakCentre column." - if not 'Sigma' in table.getColumnNames(): + if 'Sigma' not in table.getColumnNames(): issues['EPPTable'] = "EPP Table must have the Sigma column." return issues diff --git a/Framework/PythonInterface/plugins/algorithms/ComputeIncoherentDOS.py b/Framework/PythonInterface/plugins/algorithms/ComputeIncoherentDOS.py index f527137c30324fbd32680c83cf6d0a7806ef8360..22a37db34ac813da369f3fb18ac5de30a6bc5153 100644 --- a/Framework/PythonInterface/plugins/algorithms/ComputeIncoherentDOS.py +++ b/Framework/PythonInterface/plugins/algorithms/ComputeIncoherentDOS.py @@ -50,7 +50,8 @@ class ComputeIncoherentDOS(PythonAlgorithm): validators = CompositeValidator() validators.add(HistogramValidator(True)) validators.add(CommonBinsValidator()) - self.declareProperty(MatrixWorkspaceProperty(name='InputWorkspace', defaultValue='', direction=Direction.Input, validator=validators), + self.declareProperty(MatrixWorkspaceProperty(name='InputWorkspace', defaultValue='', + direction=Direction.Input, validator=validators), doc='Input MatrixWorkspace containing the reduced inelastic neutron spectrum in (Q,E) space.') self.declareProperty(name='Temperature', defaultValue=300., validator=FloatBoundedValidator(lower=0), doc='Sample temperature in Kelvin.') @@ -164,7 +165,8 @@ class ComputeIncoherentDOS(PythonAlgorithm): ylabel = 'g^{neutron}(E) (arb. units)' if absunits: if len(atoms) != 1: - self.log().warning('Sample material information not set, or sample is not a pure element. Ignoring StatesPerEnergy property.') + self.log().warning('Sample material information not set, or sample is not a pure element. ' + 'Ignoring StatesPerEnergy property.') absunits = False else: if cm: diff --git a/Framework/PythonInterface/plugins/algorithms/CorrectTOF.py b/Framework/PythonInterface/plugins/algorithms/CorrectTOF.py index 87c71143677dee7816439a21fcf20e9c6d8334bb..8d1d0e831e269e098ceee84acd15b8cbcbbc9f8e 100644 --- a/Framework/PythonInterface/plugins/algorithms/CorrectTOF.py +++ b/Framework/PythonInterface/plugins/algorithms/CorrectTOF.py @@ -58,7 +58,7 @@ class CorrectTOF (PythonAlgorithm): if table.rowCount() != input_workspace.getNumberHistograms(): issues['EPPTable'] = "Number of rows in the table must match to the input workspace dimension." # table must have 'PeakCentre' column - if not 'PeakCentre' in table.getColumnNames(): + if 'PeakCentre' not in table.getColumnNames(): issues['EPPTable'] = "EPP Table must have the PeakCentre column." return issues diff --git a/Framework/PythonInterface/plugins/algorithms/CylinderPaalmanPingsCorrection2.py b/Framework/PythonInterface/plugins/algorithms/CylinderPaalmanPingsCorrection2.py index 6e1711c3be3440967dd9983d9d7cdf9fb8818a9c..d09d6c929ec9abd132fea25c229643eccf27e1c4 100644 --- a/Framework/PythonInterface/plugins/algorithms/CylinderPaalmanPingsCorrection2.py +++ b/Framework/PythonInterface/plugins/algorithms/CylinderPaalmanPingsCorrection2.py @@ -7,21 +7,26 @@ from mantid.simpleapi import * from mantid.api import (PythonAlgorithm, AlgorithmFactory, PropertyMode, MatrixWorkspaceProperty, WorkspaceGroupProperty, InstrumentValidator, WorkspaceUnitValidator, Progress) from mantid.kernel import (StringListValidator, StringMandatoryValidator, IntBoundedValidator, - FloatBoundedValidator, Direction, logger, CompositeValidator) + FloatBoundedValidator, Direction, logger, CompositeValidator, MaterialBuilder) class CylinderPaalmanPingsCorrection(PythonAlgorithm): + # Sample variables _sample_ws_name = None - _sample_chemical_formula = None - _sample_number_density = None + _use_sample_mass_density = None _sample_inner_radius = None _sample_outer_radius = None + _sample_density_type = None + _sample_density = None + + # Container variables _use_can = False _can_ws_name = None - _can_chemical_formula = None - _can_number_density = None + _can_density_type = None + _can_density = None _can_outer_radius = None + _number_can = 1 _ms = 1 _number_wavelengths = 10 @@ -63,12 +68,18 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='SampleChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='SampleNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Sample number density') + + self.declareProperty(name='SampleDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + + self.declareProperty(name='SampleDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') + self.declareProperty(name='SampleInnerRadius', defaultValue=0.05, validator=FloatBoundedValidator(0.0), doc='Sample inner radius') + self.declareProperty(name='SampleOuterRadius', defaultValue=0.1, validator=FloatBoundedValidator(0.0), doc='Sample outer radius') @@ -81,9 +92,14 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='CanChemicalFormula', defaultValue='', doc='Can chemical formula') - self.declareProperty(name='CanNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Can number density') + + self.declareProperty(name='CanDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + + self.declareProperty(name='CanDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') + self.declareProperty(name='CanOuterRadius', defaultValue=0.15, validator=FloatBoundedValidator(0.0), doc='Can outer radius') @@ -91,6 +107,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='BeamHeight', defaultValue=3.0, validator=FloatBoundedValidator(0.0), doc='Beam height') + self.declareProperty(name='BeamWidth', defaultValue=2.0, validator=FloatBoundedValidator(0.0), doc='Beam width') @@ -98,8 +115,10 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='StepSize', defaultValue=0.002, validator=FloatBoundedValidator(0.0), doc='Step size') + self.declareProperty(name='Interpolate', defaultValue=True, doc='Interpolate the correction workspaces to match the sample workspace') + self.declareProperty(name='NumberWavelengths', defaultValue=10, validator=IntBoundedValidator(1), doc='Number of wavelengths for calculation') @@ -107,6 +126,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='Emode', defaultValue='Elastic', validator=StringListValidator(['Elastic', 'Indirect', 'Direct']), doc='Energy transfer mode') + self.declareProperty(name='Efixed', defaultValue=1.0, doc='Analyser energy') @@ -123,7 +143,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): if self._use_can: can_chemical_formula = self.getPropertyValue('CanChemicalFormula') if can_chemical_formula == '': - issues['CanChemicalFormula'] = 'Must provide a chemical foruma when providing a can workspace' + issues['CanChemicalFormula'] = 'Must provide a chemical formula when providing a can workspace' # Ensure there are enough steps number_steps = int((self._sample_outer_radius - self._sample_inner_radius) / self._step_size) @@ -149,8 +169,8 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): data_prog = Progress(self, start=0.1, end=0.85, nreports=len(self._angles)) for angle in self._angles: (A1, A2, A3, A4) = self._cyl_abs(angle) - logger.information('Angle : %f * successful' % (angle)) - data_prog.report('Appending data for angle %f' % (angle)) + logger.information('Angle : %f * successful' % angle) + data_prog.report('Appending data for angle %f' % angle) dataA1 = np.append(dataA1, A1) dataA2 = np.append(dataA2, A2) dataA3 = np.append(dataA3, A3) @@ -170,7 +190,8 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): DataY=dataA1, NSpec=len(self._angles), UnitX='Wavelength', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) workspaces = [ass_ws] if self._use_can: @@ -182,7 +203,8 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): DataY=dataA2, NSpec=len(self._angles), UnitX='Wavelength', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) workflow_prog.report('Creating acsc Workspace') acsc_ws = self._output_ws_name + '_acsc' @@ -192,7 +214,8 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): DataY=dataA3, NSpec=len(self._angles), UnitX='Wavelength', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) workflow_prog.report('Creating acc Workspace') acc_ws = self._output_ws_name + '_acc' @@ -202,7 +225,8 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): DataY=dataA4, NSpec=len(self._angles), UnitX='Wavelength', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) if self._interpolate: self._interpolate_corrections(workspaces) @@ -223,10 +247,10 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): for ws_name in sample_log_workspaces: workflow_prog.report('Adding sample logs to %s' % ws_name) - AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values) + AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values, EnableLogging=False) - workflow_prog.report('Create GroupWorkpsace Output') - GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name) + workflow_prog.report('Create GroupWorkspace Output') + GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name, EnableLogging=False) self.setPropertyValue('OutputWorkspace', self._output_ws_name) workflow_prog.report('Algorithm complete') @@ -236,16 +260,16 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): setup_prog = Progress(self, start=0.00, end=0.01, nreports=2) setup_prog.report('Obtaining input properties') self._sample_ws_name = self.getPropertyValue('SampleWorkspace') - self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') - self._sample_number_density = self.getProperty('SampleNumberDensity').value + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value self._sample_inner_radius = self.getProperty('SampleInnerRadius').value self._sample_outer_radius = self.getProperty('SampleOuterRadius').value self._number_can = 1 self._can_ws_name = self.getPropertyValue('CanWorkspace') self._use_can = self._can_ws_name != '' - self._can_chemical_formula = self.getPropertyValue('CanChemicalFormula') - self._can_number_density = self.getProperty('CanNumberDensity').value + self._can_density_type = self.getPropertyValue('CanDensityType') + self._can_density = self.getProperty('CanDensity').value self._can_outer_radius = self.getProperty('CanOuterRadius').value if self._use_can: self._number_can = 2 @@ -260,11 +284,11 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): logger.information('Sample : inner radius = %f ; outer radius = %f' % (self._radii[0], self._radii[1])) self._ms = int((self._radii[1] - self._radii[0] + 0.0001)/self._step_size) if self._ms < 20: - raise ValueError('Number of steps ( %i ) should be >= 20' % (self._ms)) + raise ValueError('Number of steps ( %i ) should be >= 20' % self._ms) else: if self._ms < 1: - self._ms=1 - logger.information('Sample : ms = %i ' % (self._ms)) + self._ms = 1 + logger.information('Sample : ms = %i ' % self._ms) if self._use_can: self._radii[2] = self._can_outer_radius if (self._radii[2] - self._radii[1]) < 1e-4: @@ -297,29 +321,65 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): def _sample(self): sample_prog = Progress(self, start=0.01, end=0.03, nreports=2) sample_prog.report('Setting Sample Material for Sample') - SetSampleMaterial(self._sample_ws_name , ChemicalFormula=self._sample_chemical_formula, - SampleNumberDensity=self._sample_number_density) - sample = mtd[self._sample_ws_name].sample() - sam_material = sample.getMaterial() + + sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') + + sample_ws, self._sample_density = self._set_material(self._sample_ws_name, + sample_chemical_formula, + self._sample_density_type, + self._sample_density) + + sample_material = sample_ws.sample().getMaterial() # total scattering x-section self._sig_s = np.zeros(self._number_can) - self._sig_s[0] = sam_material.totalScatterXSection() + self._sig_s[0] = sample_material.totalScatterXSection() # absorption x-section self._sig_a = np.zeros(self._number_can) - self._sig_a[0] = sam_material.absorbXSection() + self._sig_a[0] = sample_material.absorbXSection() # density self._density = np.zeros(self._number_can) - self._density[0] = self._sample_number_density + self._density[0] = self._sample_density if self._use_can: sample_prog.report('Setting Sample Material for Container') - SetSampleMaterial(InputWorkspace=self._can_ws_name, ChemicalFormula=self._can_chemical_formula, - SampleNumberDensity=self._can_number_density) - can_sample = mtd[self._can_ws_name].sample() - can_material = can_sample.getMaterial() + + can_chemical_formula = self.getPropertyValue('CanChemicalFormula') + + can_ws, self._can_density = self._set_material(self._can_ws_name, + can_chemical_formula, + self._can_density_type, + self._can_density) + + can_material = can_ws.sample().getMaterial() self._sig_s[1] = can_material.totalScatterXSection() self._sig_a[1] = can_material.absorbXSection() - self._density[1] = self._can_number_density + self._density[1] = self._can_density + + def _set_material(self, ws_name, chemical_formula, density_type, density): + """ + Sets the sample material for a given workspace + @param ws_name :: name of the workspace to set sample material for + @param chemical_formula :: Chemical formula of sample + @param density_type :: 'Mass Density' or 'Number Density' + @param density :: Density of sample + @return pointer to the workspace with sample material set + AND + number density of the sample material + """ + set_material_alg = self.createChildAlgorithm('SetSampleMaterial') + if density_type == 'Mass Density': + set_material_alg.setProperty('SampleMassDensity', density) + builder = MaterialBuilder() + mat = builder.setFormula(chemical_formula).setMassDensity(density).build() + number_density = mat.numberDensity + else: + number_density = density + set_material_alg.setProperty('InputWorkspace', ws_name) + set_material_alg.setProperty('ChemicalFormula', chemical_formula) + set_material_alg.setProperty('SampleNumberDensity', number_density) + set_material_alg.execute() + ws = set_material_alg.getProperty('InputWorkspace').value + return ws, number_density #------------------------------------------------------------------------------ @@ -354,26 +414,26 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): for idx in range(0, number_waves): wave_prog.report('Appending wave data: %i' % idx) self._waves.append(wave_min + idx * wave_bin) - DeleteWorkspace(wave_range) + DeleteWorkspace(wave_range, EnableLogging = False) if self._emode == 'Elastic': self._elastic = self._waves[int(len(self._waves) / 2)] else: self._elastic = math.sqrt(81.787/self._efixed) # elastic wavelength - logger.information('Elastic lambda : %f' % (self._elastic)) + logger.information('Elastic lambda : %f' % self._elastic) logger.information('Lambda : %i values from %f to %f' % (len(self._waves), self._waves[0], self._waves[-1])) #------------------------------------------------------------------------------ def _transmission(self): distance = self._radii[1] - self._radii[0] - trans= math.exp(-distance*self._density[0]*(self._sig_s[0] + self._sig_a[0])) - logger.information('Sample transmission : %f' % (trans)) + trans = math.exp(-distance*self._density[0]*(self._sig_s[0] + self._sig_a[0])) + logger.information('Sample transmission : %f' % trans) if self._use_can: distance = self._radii[2] - self._radii[1] - trans= math.exp(-distance*self._density[1]*(self._sig_s[1] + self._sig_a[1])) - logger.information('Can transmission : %f' % (trans)) + trans = math.exp(-distance*self._density[1]*(self._sig_s[1] + self._sig_a[1])) + logger.information('Can transmission : %f' % trans) #------------------------------------------------------------------------------ @@ -458,7 +518,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): theta, amu_scat, amu_tot_i, amu_tot_s) Area_s += Area_A + Area_B Ass += AAAA + AAAB - Ass = Ass/Area_s + Ass /= Area_s else: for i in range(0, self._number_can -1): radius_1 = self._radii[i] @@ -542,7 +602,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): LSSN = self._distance(r, self._radii[j+1], O) LSS.append(LSSN - LSST) # -# CALCULATE ABSORBTION FOR PATH THROUGH ALL ANNULI,AND THROUGH INNER ANNULI +# CALCULATE ABSORPTION FOR PATH THROUGH ALL ANNULI,AND THROUGH INNER ANNULI path = np.zeros(3) # split into input (I) and scattered (S) paths path[0] += amu_tot_i[0]*LIS[0] + amu_tot_s[0]*LSS[0] @@ -576,7 +636,7 @@ class CylinderPaalmanPingsCorrection(PythonAlgorithm): if r <= radius: distance = t + d else: - distance = d*(1.0 + math.copysign(1.0,t)) + distance = d*(1.0 + math.copysign(1.0, t)) return distance #------------------------------------------------------------------------------ diff --git a/Framework/PythonInterface/plugins/algorithms/DSFinterp.py b/Framework/PythonInterface/plugins/algorithms/DSFinterp.py index 8f0f3ff3a96862cd30e8d3c0821372ef5d9028b1..247cd9e99fdef1fcde29838f58ec0f4c5f40025c 100644 --- a/Framework/PythonInterface/plugins/algorithms/DSFinterp.py +++ b/Framework/PythonInterface/plugins/algorithms/DSFinterp.py @@ -116,7 +116,7 @@ class DSFinterp(PythonAlgorithm): ############################################################################################# #pylint: disable=unused-import try: - import dsfinterp + import dsfinterp # noqa AlgorithmFactory.subscribe(DSFinterp) except ImportError: logger.debug('Failed to subscribe algorithm DSFinterp; Python package dsfinterp' diff --git a/Framework/PythonInterface/plugins/algorithms/EnggFitPeaks.py b/Framework/PythonInterface/plugins/algorithms/EnggFitPeaks.py index b7a285f4ddc938f700fa44338bf369c49e239abc..4630e5e4d6d4876668af6741b591c0c454f197ce 100644 --- a/Framework/PythonInterface/plugins/algorithms/EnggFitPeaks.py +++ b/Framework/PythonInterface/plugins/algorithms/EnggFitPeaks.py @@ -394,10 +394,8 @@ class EnggFitPeaks(PythonAlgorithm): detTwoTheta = ws.detectorTwoTheta(det) # hard coded equation to convert dSpacing -> TOF for the single detector - dSpacingToTof = lambda d: 252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * d - # Values (in principle, expected peak positions) in TOF for the detector - tof_values = [dSpacingToTof(ep) for ep in dsp_values] + tof_values = [252.816 * 2 * (50 + detL2) * math.sin(detTwoTheta / 2.0) * ep for ep in dsp_values] return tof_values def _create_fitted_peaks_table(self, tbl_name): @@ -501,7 +499,7 @@ class EnggFitPeaks(PythonAlgorithm): (0 != fitted_params['X0_Err'] and 0 != fitted_params['A_Err'] and 0 != fitted_params['B_Err'] and 0 != fitted_params['S_Err'] and 0 != fitted_params['I_Err']) - ) + ) def _add_parameters_to_map(self, param_map, param_table): """ diff --git a/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py b/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py index 39e1e577c1e39bc3fe53917f5a0220b51e91c82d..590a91ba31e30eff08e64912bca8e87d78e054d6 100644 --- a/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py +++ b/Framework/PythonInterface/plugins/algorithms/Examples/Squares.py @@ -28,7 +28,7 @@ class Squares(PythonAlgorithm): "A workspace containing the squares") def PyExec(self): - dummy_msg = self.getProperty("Preamble").value # Convert to string + dummy_msg = self.getProperty("Preamble").value # Convert to string # noqa endrange = self.getProperty("MaxRange").value # Convert to int do_sum = self.getProperty('Sum').value # Convert to boolean diff --git a/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py b/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py index dd26abac94072bc359df99e70955bf0a3c07bb2a..3833329fa72b409a5dc75fecbb576203574b3a49 100644 --- a/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py +++ b/Framework/PythonInterface/plugins/algorithms/ExportExperimentLog.py @@ -379,7 +379,9 @@ class ExportExperimentLog(PythonAlgorithm): # ENDFOR # Check needs to re-order - if list(linedict.keys()) != sorted(linedict.keys()): + # This test does not work with python 3, you can not assume the order of a dictionary + # if list(linedict.keys()) != sorted(linedict.keys()): + if True: # temporary hack to get it working with python 3, always write a new file! # Re-write file wbuf = "" @@ -420,7 +422,7 @@ class ExportExperimentLog(PythonAlgorithm): wbuf = wbuf[0:-1] # Remove unsupported character which may cause importing error of GNUMERIC - wbuf = wbuf.translate(None, chr(0)) + wbuf = wbuf.replace(chr(0),"") # Re-write file ofile = open(self._logfilename, "w") diff --git a/Framework/PythonInterface/plugins/algorithms/ExportSpectraMask.py b/Framework/PythonInterface/plugins/algorithms/ExportSpectraMask.py index 37335ba9742dc988c6dfffc750d0936c16d58171..33c24ca00b31e842829198e2d9ea31e33166de4e 100644 --- a/Framework/PythonInterface/plugins/algorithms/ExportSpectraMask.py +++ b/Framework/PythonInterface/plugins/algorithms/ExportSpectraMask.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name, no-init +from __future__ import (absolute_import, division, print_function) import os from mantid import config from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty, mtd, FileProperty, FileAction diff --git a/Framework/PythonInterface/plugins/algorithms/FindEPP.py b/Framework/PythonInterface/plugins/algorithms/FindEPP.py index 25a002af2adc3ed110dcaa50ea229abb32c59a2d..44be8317995b78d03cef85b23b7e5b8063612e06 100644 --- a/Framework/PythonInterface/plugins/algorithms/FindEPP.py +++ b/Framework/PythonInterface/plugins/algorithms/FindEPP.py @@ -51,27 +51,44 @@ class FindEPP(PythonAlgorithm): self.log().warning("Workspace %s, detector %d has maximum <= 0" % (self.workspace.getName(), index)) return result - # guess sigma (assume the signal is sufficiently smooth) - # the _only_ peak is at least three samples wide - # selecting samples above .5 ("full width at half maximum") - indices = np.argwhere(y_values > 0.5*height) - nentries = len(indices) - - if nentries < 3: + # Get the positions around the max, where the y value first drops down 0.5*height + # This is a better approach when there is a higher noise in the tails in real data + fwhm_right = x_values.size - 1 - imax # number of bins from max to the right end + fwhm_left = imax # number of bins from max to the left end + + if imax < y_values.size - 1: + y_right = y_values[imax+1:] + y_right_below = np.argwhere(y_right < 0.5 * height) + if y_right_below.size != 0: + fwhm_right = y_right_below[0][0] + + if imax > 0: + y_left = y_values[:imax] + y_left = y_left[::-1] + y_left_below = np.argwhere(y_left < 0.5 * height) + if y_left_below.size != 0: + fwhm_left = y_left_below[0][0] + + fwhm_pos = np.minimum(imax+fwhm_right,x_values.size-1) + fwhm_neg = np.maximum(imax-fwhm_left,0) + + self.log().debug("(spectrum %d) : FWHM lower edge is %d, upper edge is %d" % (index,fwhm_neg,fwhm_pos)) + + if fwhm_pos - fwhm_neg + 1 < 3: self.log().warning("Spectrum " + str(index) + " in workspace " + self.workspace.getName() + " has a too narrow peak. Cannot guess sigma. Check your data.") return result - minIndex = indices[0,0] - maxIndex = indices[-1,0] + fwhm = x_values[fwhm_pos] - x_values[fwhm_neg] + + self.log().debug("(spectrum %d) : FWHM is %f" % (index, fwhm)) - # full width at half maximum: fwhm = sigma * (2.*np.sqrt(2.*np.log(2.))) - fwhm = np.fabs(x_values[maxIndex] - x_values[minIndex]) sigma = fwhm / (2.*np.sqrt(2.*np.log(2.))) # execute Fit algorithm tryCentre = x_values[imax] fitFun = "name=Gaussian,PeakCentre=%s,Height=%s,Sigma=%s" % (tryCentre,height,sigma) + startX = tryCentre - 3.0*fwhm endX = tryCentre + 3.0*fwhm @@ -83,7 +100,7 @@ class FindEPP(PythonAlgorithm): return result def PyExec(self): - self.workspace = self.getProperty("InputWorkspace").value + self.workspace = self.getProperty("InputWorkspace").value outws_name = self.getPropertyValue("OutputWorkspace") # create table and columns diff --git a/Framework/PythonInterface/plugins/algorithms/FitGaussian.py b/Framework/PythonInterface/plugins/algorithms/FitGaussian.py index b1c9faefc208e514e662fc37efffbc94c5a9b824..6dc36405d72eff27086d4116b3d7a6f59d8ce432 100644 --- a/Framework/PythonInterface/plugins/algorithms/FitGaussian.py +++ b/Framework/PythonInterface/plugins/algorithms/FitGaussian.py @@ -90,7 +90,7 @@ class FitGaussian(PythonAlgorithm): if not 'success' == fitStatus: self._warning("For detector " + str(index) + " in workspace " + workspace.getName() + - "fit was not successful. Input guess parameters were " + str(fitFunc)) + "fit was not successful. Input guess parameters were " + str(fitFun)) return fitParams = paramTable.column(1) diff --git a/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py b/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py index 4e5d24d72417d40f06b3b05fad2065478e2653e0..5a26872144296b5629d20580ca63b46780c2ad01 100644 --- a/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py +++ b/Framework/PythonInterface/plugins/algorithms/IndirectTransmission.py @@ -49,8 +49,12 @@ class IndirectTransmission(PythonAlgorithm): self.declareProperty(name='ChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='NumberDensity', defaultValue=0.1, - doc='Number denisty (atoms/Angstrom^3). Default=0.1') + self.declareProperty(name='DensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + + self.declareProperty(name='Density', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3). Default=0.1') self.declareProperty(name='Thickness', defaultValue=0.1, doc='Sample thickness (cm). Default=0.1') @@ -64,7 +68,11 @@ class IndirectTransmission(PythonAlgorithm): analyser = self.getPropertyValue('Analyser') reflection = self.getPropertyValue('Reflection') formula = self.getPropertyValue('ChemicalFormula') - density = self.getPropertyValue('NumberDensity') + densityType = self.getPropertyValue('DensityType') + density = self.getProperty('Density').value + if densityType == 'Mass Density': + mat = MaterialBuilder().setFormula(formula).setMassDensity(density).build() + density = mat.numberDensity thickness = self.getPropertyValue('Thickness') # Create an empty instrument workspace diff --git a/Framework/PythonInterface/plugins/algorithms/LRDirectBeamSort.py b/Framework/PythonInterface/plugins/algorithms/LRDirectBeamSort.py index 79865a282ba015d304a15760b7816231e46f16af..b03c6cd8bd651cae571f914da71387e25b9cdf27 100644 --- a/Framework/PythonInterface/plugins/algorithms/LRDirectBeamSort.py +++ b/Framework/PythonInterface/plugins/algorithms/LRDirectBeamSort.py @@ -1,6 +1,5 @@ #pylint: disable=no-init,invalid-name from __future__ import (absolute_import, division, print_function) -import mantid from mantid.api import * from mantid.simpleapi import * from mantid.kernel import * diff --git a/Framework/PythonInterface/plugins/algorithms/LRReflectivityOutput.py b/Framework/PythonInterface/plugins/algorithms/LRReflectivityOutput.py index 8b52dec93b722ebbecab7195036c49be2d79ee3d..f1fcde5f87b03c5ca3da9c168a2099a71ad25d51 100644 --- a/Framework/PythonInterface/plugins/algorithms/LRReflectivityOutput.py +++ b/Framework/PythonInterface/plugins/algorithms/LRReflectivityOutput.py @@ -38,7 +38,7 @@ class LRReflectivityOutput(PythonAlgorithm): def PyExec(self): # Check that all the input workspaces are scaled workspace_list = self.getProperty("ReducedWorkspaces").value - if self.check_scaling(workspace_list) == False: + if not self.check_scaling(workspace_list): logger.error("Absolute normalization not available!") # Put the workspaces together diff --git a/Framework/PythonInterface/plugins/algorithms/LoadCIF.py b/Framework/PythonInterface/plugins/algorithms/LoadCIF.py index 37e7a9be75d98642e944ec4c83e5e55288a1de85..6854025decbe3fb80bd96caf2d3fa87e641c2002 100644 --- a/Framework/PythonInterface/plugins/algorithms/LoadCIF.py +++ b/Framework/PythonInterface/plugins/algorithms/LoadCIF.py @@ -50,11 +50,11 @@ class SpaceGroupBuilder(object): try: return self._getSpaceGroupFromString(cifData) # pylint: disable=unused-variable - except (RuntimeError, ValueError) as error: + except (RuntimeError, ValueError): try: return self._getSpaceGroupFromNumber(cifData) # pylint: disable=unused-variable,invalid-name - except RuntimeError as e: + except RuntimeError: raise RuntimeError( 'Can not create space group from supplied CIF-file. You could try to modify the HM-symbol ' 'to contain spaces between the components.\n' diff --git a/Framework/PythonInterface/plugins/algorithms/LoadPreNexusLive.py b/Framework/PythonInterface/plugins/algorithms/LoadPreNexusLive.py index 5a2b647ee90a732d663cef1c86b4b9f8b444ddd8..42694a4ccb968fe05ce73b559b0a44072a830675 100644 --- a/Framework/PythonInterface/plugins/algorithms/LoadPreNexusLive.py +++ b/Framework/PythonInterface/plugins/algorithms/LoadPreNexusLive.py @@ -1,3 +1,4 @@ +from __future__ import (absolute_import, division, print_function) from mantid import mtd from mantid.api import AlgorithmFactory, DataProcessorAlgorithm, FileAction, \ FileProperty, WorkspaceProperty diff --git a/Framework/PythonInterface/plugins/algorithms/RefLReduction.py b/Framework/PythonInterface/plugins/algorithms/RefLReduction.py index ac2cc0ac4fcd44ae6c24d8e6a978cd1c5fd2d9b4..5da86fd3a5bbc0b31f0a38f1d395e233bdabc6b3 100644 --- a/Framework/PythonInterface/plugins/algorithms/RefLReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/RefLReduction.py @@ -2,16 +2,15 @@ from __future__ import (absolute_import, division, print_function) from mantid.api import * from mantid.simpleapi import * +from mantid.kernel import * # import sfCalculator import sys import os sys.path.insert(0,os.path.dirname(__file__)) -import sfCalculator +import sfCalculator # noqa sys.path.pop(0) -from mantid.kernel import * - class RefLReduction(PythonAlgorithm): @@ -131,7 +130,7 @@ class RefLReduction(PythonAlgorithm): # NORM normalizationRunNumber = self.getProperty("NormalizationRunNumber").value - normFlag = self.getProperty("NormFlag") + # normFlag = self.getProperty("NormFlag") normBackRange = self.getProperty("NormBackgroundPixelRange").value normPeakRange = self.getProperty("NormPeakPixelRange").value normBackFlag = self.getProperty("SubtractNormBackground").value @@ -165,9 +164,6 @@ class RefLReduction(PythonAlgorithm): # angle offset angleOffsetDeg = self.getProperty("AngleOffset").value - h = 6.626e-34 #m^2 kg s^-1 - m = 1.675e-27 #kg - # sfCalculator settings slitsValuePrecision = sfCalculator.PRECISION sfFile = self.getProperty("ScalingFactorFile").value @@ -365,9 +361,6 @@ class RefLReduction(PythonAlgorithm): # y_axis, # y_error_axis) - sz = q_axis.shape - nbr_pixel = sz[0] - # create workspace q_workspace = wks_utility.createQworkspace(q_axis, y_axis, y_error_axis) @@ -378,8 +371,6 @@ class RefLReduction(PythonAlgorithm): # keep only the q values that have non zero counts nonzero_q_rebin_wks = wks_utility.cropAxisToOnlyNonzeroElements(q_rebin, dataPeakRange) - new_q_axis = nonzero_q_rebin_wks.readX(0)[:] - # integrate spectra (normal mean) and remove first and last Q value [final_x_axis, final_y_axis, final_error_axis] = wks_utility.integrateOverPeakRange(nonzero_q_rebin_wks, dataPeakRange) @@ -392,11 +383,11 @@ class RefLReduction(PythonAlgorithm): _time = int(time.time()) name_output_ws = self.getPropertyValue("OutputWorkspace") name_output_ws = name_output_ws + '_#' + str(_time) + 'ts' - final_workspace = wks_utility.createFinalWorkspace(final_x_axis, - final_y_axis, - final_y_error_axis, - name_output_ws, - ws_event_data) + wks_utility.createFinalWorkspace(final_x_axis, + final_y_axis, + final_y_error_axis, + name_output_ws, + ws_event_data) AddSampleLog(Workspace=name_output_ws, LogName='isSFfound', LOgText=str(isSFfound)) diff --git a/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py b/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py index 9002e6f95b734860afd812277b19037d3bf19382..b0442c806c7d38f98608335b3c0f645c2db3976e 100644 --- a/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py +++ b/Framework/PythonInterface/plugins/algorithms/RefinePowderDiffProfileSeq.py @@ -5,7 +5,6 @@ from six.moves import range #pylint: disable=redefined-builtin from mantid.api import * import mantid.simpleapi as api -from mantid.api import * from mantid.kernel import * diff --git a/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py b/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py index 8dede44ba8a10b645628722cd1365a18964a24cb..3797f4da1789223b0ba0ff26537c64a8ba141dc9 100644 --- a/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py +++ b/Framework/PythonInterface/plugins/algorithms/RetrieveRunInfo.py @@ -3,7 +3,7 @@ from __future__ import (absolute_import, division, print_function) from mantid.api import PythonAlgorithm, AlgorithmFactory, ITableWorkspaceProperty from mantid.simpleapi import * from mantid.kernel import StringMandatoryValidator, Direction -from mantid import logger, config +from mantid import config import os from six.moves import filterfalse diff --git a/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py b/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py index 8c5320e7da087b9d9f4666c4c125f33d418423df..50e0f297f729ae216ec0b830f672ebc46f10b33d 100644 --- a/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/SNSPowderReduction.py @@ -367,7 +367,7 @@ class SNSPowderReduction(DataProcessorAlgorithm): # ENDIF (Sum data or not) for (samRunIndex, sam_ws_name) in enumerate(samwksplist): - assert isinstance(sam_ws_name, str), 'Assuming that samRun is a string. But it is %s' % str(type(sam_ws_)) + assert isinstance(sam_ws_name, str), 'Assuming that samRun is a string. But it is %s' % str(type(sam_ws_name)) if is_event_workspace(sam_ws_name): self.log().information('Sample Run %s: starting number of events = %d.' % ( sam_ws_name, get_workspace(sam_ws_name).getNumberEvents())) @@ -641,14 +641,14 @@ class SNSPowderReduction(DataProcessorAlgorithm): 1. run number are integers Guarantees: - :param run_number_list: list of run numbers + :param filename_list: list of filenames :param outName: :param filterWall: :return: """ # Check requirements assert isinstance(filename_list, list), \ - 'Run number list is not a list but of type %s' % str(type(run_number_list)) + 'Run number list is not a list but of type %s' % str(type(filename_list)) # Form output workspaces' names out_ws_name_list = ['%s_loadsum' % getBasename(filename) for filename in filename_list] @@ -1262,7 +1262,7 @@ class SNSPowderReduction(DataProcessorAlgorithm): van_bkgd_ws_name = self._loadAndSum([van_bkgd_run_number], van_bkgd_ws_name, **vanFilterWall) van_bkgd_ws = get_workspace(van_bkgd_ws_name) - if van_bkgd_ws.id() == EVENT_WORKSPACE_ID and van_bkgd_ws.getNumberEvents() > 0: + if van_bkgd_ws.id() == EVENT_WORKSPACE_ID and van_bkgd_ws.getNumberEvents() <= 0: # skip if background run is empty pass else: diff --git a/Framework/PythonInterface/plugins/algorithms/SaveNexusPD.py b/Framework/PythonInterface/plugins/algorithms/SaveNexusPD.py index ecc451904d19b0b564e02442941170e5b4126037..35aa2fa6e4330d40646ccab42d6066d7b9c32640 100644 --- a/Framework/PythonInterface/plugins/algorithms/SaveNexusPD.py +++ b/Framework/PythonInterface/plugins/algorithms/SaveNexusPD.py @@ -152,7 +152,7 @@ class SaveNexusPD(mantid.api.PythonAlgorithm): temp.attrs['units'] = units def _writeProtonCharge(self, nxentry, wksp): - if not 'gd_prtn_chrg' in wksp.run(): + if 'gd_prtn_chrg' not in wksp.run(): return # nothing to do pcharge = wksp.run()['gd_prtn_chrg'] diff --git a/Framework/PythonInterface/plugins/algorithms/SavePlot1DAsJson.py b/Framework/PythonInterface/plugins/algorithms/SavePlot1DAsJson.py index 454914a4bb98934e5127245d421cde45c05c1f7f..ba4b9d21553df71c87f801906a65d8dc5c92c8f5 100644 --- a/Framework/PythonInterface/plugins/algorithms/SavePlot1DAsJson.py +++ b/Framework/PythonInterface/plugins/algorithms/SavePlot1DAsJson.py @@ -27,7 +27,7 @@ class SavePlot1DAsJson(PythonAlgorithm): def require(self): try: - import json + import json # noqa except: raise ImportError("Missing json package") @@ -103,8 +103,6 @@ class SavePlot1DAsJson(PythonAlgorithm): serialized['data'][spectrum_no] = arr continue # axes - # .. helper - label = lambda axis: axis.getUnit().caption() def unit(axis): s = axis.getUnit().symbol() @@ -113,8 +111,8 @@ class SavePlot1DAsJson(PythonAlgorithm): except: return '%s' % s axes = dict( - xlabel=label(workspace.getAxis(0)), - ylabel=label(workspace.getAxis(1)), + xlabel=workspace.getAxis(0).getUnit().caption(), + ylabel=workspace.getAxis(1).getUnit().caption(), xunit = unit(workspace.getAxis(0)), # yunit = unit(workspace.getAxis(1)), yunit = workspace.YUnitLabel(), diff --git a/Framework/PythonInterface/plugins/algorithms/SelectNexusFilesByMetadata.py b/Framework/PythonInterface/plugins/algorithms/SelectNexusFilesByMetadata.py index 1f955d55977f200bcac41afd5a96e6acf581ea93..11f709a0bdb3f7401f46bd38cd19328b580d1681 100644 --- a/Framework/PythonInterface/plugins/algorithms/SelectNexusFilesByMetadata.py +++ b/Framework/PythonInterface/plugins/algorithms/SelectNexusFilesByMetadata.py @@ -4,7 +4,7 @@ from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * -from mantid import logger +from six import PY3 class SelectNexusFilesByMetadata(PythonAlgorithm): @@ -20,7 +20,6 @@ class SelectNexusFilesByMetadata(PythonAlgorithm): def validateInputs(self): issues = dict() criteria = self.getPropertyValue('NexusCriteria') - # at least one nexus entry should be specified dollars = criteria.count('$') if dollars % 2 != 0 or dollars < 2: @@ -103,6 +102,8 @@ class SelectNexusFilesByMetadata(PythonAlgorithm): if str(value.dtype).startswith('|S'): # string value, need to quote for eval + if PY3: + value = value.decode() toeval += '\"' + value + '\"' else: toeval += str(value) diff --git a/Framework/PythonInterface/plugins/algorithms/SetDetScale.py b/Framework/PythonInterface/plugins/algorithms/SetDetScale.py index 7dad1707a39733c9089616304a64f6ee0d7d185f..2f5f11ef6c3d3994663ced466318bc07d48220d7 100644 --- a/Framework/PythonInterface/plugins/algorithms/SetDetScale.py +++ b/Framework/PythonInterface/plugins/algorithms/SetDetScale.py @@ -1,6 +1,6 @@ from __future__ import (absolute_import, division, print_function) -from mantid.api import PythonAlgorithm, AlgorithmFactory, PropertyMode, WorkspaceProperty, InstrumentValidator +from mantid.api import PythonAlgorithm, AlgorithmFactory, WorkspaceProperty, InstrumentValidator from mantid.kernel import Direction, StringArrayProperty import mantid.simpleapi as api diff --git a/Framework/PythonInterface/plugins/algorithms/StatisticsOfTableWorkspace.py b/Framework/PythonInterface/plugins/algorithms/StatisticsOfTableWorkspace.py index d4616d15fab1bdeec3eb351467c9dc2a7a4e7972..c43714a2aee07ce0f654cf869f6e1e3a9e7ed2e6 100644 --- a/Framework/PythonInterface/plugins/algorithms/StatisticsOfTableWorkspace.py +++ b/Framework/PythonInterface/plugins/algorithms/StatisticsOfTableWorkspace.py @@ -42,7 +42,7 @@ class StatisticsOfTableWorkspace(PythonAlgorithm): in_ws = mtd[self.getPropertyValue('InputWorkspace')] out_ws_name = self.getPropertyValue('OutputWorkspace') - out_ws = ms.CreateEmptyTableWorkspace(OutputWOrkspace=out_ws_name) + out_ws = ms.CreateEmptyTableWorkspace(OutputWorkspace=out_ws_name) out_ws.addColumn('str', 'statistic') @@ -68,7 +68,7 @@ class StatisticsOfTableWorkspace(PythonAlgorithm): stat1['statistic'] = name out_ws.addRow(stat1) - self.setProperty('OutputWorkspace', out_ws_name) + self.setProperty('OutputWorkspace', out_ws) # Register algorithm with Mantid diff --git a/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py b/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py index 5066b3662e9432ed3a42033341ea9c0bc5b2d8b7..13a1d28b8663676671a1cd0a61afe482d5ae64de 100644 --- a/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py +++ b/Framework/PythonInterface/plugins/algorithms/UpdatePeakParameterTableValue.py @@ -84,7 +84,7 @@ class UpdatePeakParameterTableValue(mantid.api.PythonAlgorithm): icolumn = colnamedict[colname] else: raise NotImplementedError("Column name %s does not exist in TableWorkspace %s" - % (colname, tablews.name())) + % (colname, tableWS.name())) # 3. Set value if colname in ["FitOrTie", "Name"]: diff --git a/Framework/PythonInterface/plugins/algorithms/VelocityAutoCorrelations.py b/Framework/PythonInterface/plugins/algorithms/VelocityAutoCorrelations.py index fe1c3ff57dda9931ea03eadb6ba4cb1a1f47c82a..79e573173362fc01fb32bce38d84413489396dcb 100644 --- a/Framework/PythonInterface/plugins/algorithms/VelocityAutoCorrelations.py +++ b/Framework/PythonInterface/plugins/algorithms/VelocityAutoCorrelations.py @@ -1,4 +1,5 @@ # pylint: disable=too-many-branches,too-many-locals, invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -42,7 +43,7 @@ class VelocityAutoCorrelations(PythonAlgorithm): # Convert description object to string via for loop. The original object has strange formatting particleID = '' for i in description: - particleID += i + particleID += i.decode('UTF-8') # Extract particle id's from string using regular expressions p_atoms=re.findall(r"A\('[a-z]+\d+',\d+", particleID) diff --git a/Framework/PythonInterface/plugins/algorithms/VelocityCrossCorrelations.py b/Framework/PythonInterface/plugins/algorithms/VelocityCrossCorrelations.py index b5979f95eaec1de669ed092f40257f9775225015..bd4cf3cf5650a2dc4fb035694327cc7b93cc2682 100644 --- a/Framework/PythonInterface/plugins/algorithms/VelocityCrossCorrelations.py +++ b/Framework/PythonInterface/plugins/algorithms/VelocityCrossCorrelations.py @@ -1,4 +1,5 @@ # pylint: disable=too-many-branches,too-many-locals, invalid-name +from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.kernel import * from mantid.api import * @@ -45,7 +46,7 @@ class VelocityCrossCorrelations(PythonAlgorithm): # Convert description object to string via for loop. The original object has strange formatting particleID = '' for i in description: - particleID += i + particleID += i.decode('UTF-8') # Extract particle id's from string using regular expressions p_atoms=re.findall(r"A\('[a-z]+\d+',\d+", particleID) @@ -283,7 +284,7 @@ class VelocityCrossCorrelations(PythonAlgorithm): row_names.append(elements[i].capitalize()+' and '+elements[j].capitalize()) # Initialise & populate the output_ws workspace - nrows=(n_species*n_species-n_species)/2+n_species + nrows=int((n_species*n_species-n_species)/2+n_species) #nbins=(np.shape(correlations)[2]) yvals=np.empty(0) for i in range(n_species): @@ -321,7 +322,7 @@ class VelocityCrossCorrelations(PythonAlgorithm): def fold_correlation(self,w): # Folds an array with symmetrical values into half by averaging values around the centre - right_half=w[len(w)/2:] + right_half=w[int(len(w)/2):] left_half=w[:int(np.ceil(len(w)/2.0))][::-1] return (left_half+right_half)/2.0 diff --git a/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py b/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py index 42a0678230864433be29b7cd95bafe85bf2a7b96..5cd96001590381f0aa69d42b103696b165d0bb8d 100644 --- a/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py +++ b/Framework/PythonInterface/plugins/algorithms/VesuvioResolution.py @@ -1,13 +1,12 @@ #pylint: disable=no-init from __future__ import (absolute_import, division, print_function) -from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * -import mantid +from vesuvio.base import VesuvioBase -class VesuvioResolution(PythonAlgorithm): +class VesuvioResolution(VesuvioBase): _workspace_index = None _mass = None @@ -79,29 +78,22 @@ class VesuvioResolution(PythonAlgorithm): output_ysp = (out_ws_ysp != '') if output_tof: - res_tof = self._calculate_resolution(sample_ws, out_ws_tof) + res_tof = self._calculate_resolution(sample_ws) self.setProperty('OutputWorkspaceTOF', res_tof) if output_ysp: - y_space_conv = mantid.api.AlgorithmManager.createUnmanaged('ConvertToYSpace') - y_space_conv.initialize() - y_space_conv.setChild(True) - y_space_conv.setAlwaysStoreInADS(True) - y_space_conv.setProperty('InputWorkspace', sample_ws) - y_space_conv.setProperty('OutputWorkspace', '__yspace_sample') - y_space_conv.setProperty('Mass', self._mass) - y_space_conv.execute() - - res_ysp = self._calculate_resolution(mtd['__yspace_sample'], out_ws_ysp) + y_space_conv = self._execute_child_alg('ConvertToYSpace', + return_values='OutputWorkspace', + InputWorkspace=sample_ws, + Mass=self._mass) + res_ysp = self._calculate_resolution(y_space_conv) self.setProperty('OutputWorkspaceYSpace', res_ysp) - DeleteWorkspace('__yspace_sample') - def _calculate_resolution(self, workspace, output_ws_name): + def _calculate_resolution(self, workspace): """ Calculates the resolution function using the VesuvioResolution fit function. @param workspace The sample workspace - @param output_ws_name Name of the output workspace """ function = 'name=VesuvioResolution, Mass=%f' % self._mass @@ -110,26 +102,17 @@ class VesuvioResolution(PythonAlgorithm): # Execute the resolution function using fit. # Functions can't currently be executed as stand alone objects, # so for now we will run fit with zero iterations to achieve the same result. - fit = mantid.api.AlgorithmManager.createUnmanaged('Fit') - fit.initialize() - fit.setChild(True) - mantid.simpleapi.set_properties(fit, function, InputWorkspace=workspace, MaxIterations=0, - CreateOutput=True, Output=fit_naming_stem, - WorkspaceIndex=self._workspace_index, - OutputCompositeMembers=True) - fit.execute() - fit_ws = fit.getProperty('OutputWorkspace').value + fit_ws = self._execute_child_alg('Fit', return_values='OutputWorkspace', + Function=function, InputWorkspace=workspace, + MaxIterations=0, + CreateOutput=True, Output=fit_naming_stem, + WorkspaceIndex=self._workspace_index, + OutputCompositeMembers=False) # Extract just the function values from the fit spectrum - extract = mantid.api.AlgorithmManager.createUnmanaged('ExtractSingleSpectrum') - extract.initialize() - extract.setChild(True) - extract.setProperty('InputWorkspace', fit_ws) - extract.setProperty('OutputWorkspace', output_ws_name) - extract.setProperty('WorkspaceIndex', 1) - extract.execute() - - res_ws = extract.getProperty('OutputWorkspace').value + res_ws = self._execute_child_alg('ExtractSingleSpectrum', + InputWorkspace=fit_ws, + WorkspaceIndex=1) return res_ws diff --git a/Framework/PythonInterface/plugins/algorithms/VesuvioThickness.py b/Framework/PythonInterface/plugins/algorithms/VesuvioThickness.py index f8326887ca7207551e4c699e705bce439362db47..f697b4e7ecf2af067fa19a54780db6ca79f29bfb 100644 --- a/Framework/PythonInterface/plugins/algorithms/VesuvioThickness.py +++ b/Framework/PythonInterface/plugins/algorithms/VesuvioThickness.py @@ -63,9 +63,9 @@ class VesuvioThickness(PythonAlgorithm): num_masses = len(self._masses) num_amplitudes = len(self._amplitudes) if num_masses == 0: - isuues['Masses'] = ('Must have 1 or more Masses defined') + issues['Masses'] = ('Must have 1 or more Masses defined') if num_amplitudes == 0: - isuues['Amplitudes'] = ('Must have 1 or more Amplitudes defined') + issues['Amplitudes'] = ('Must have 1 or more Amplitudes defined') if num_masses != num_amplitudes: issues['Masses'] = ('The number of masses: %d, ' % num_masses diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/BayesStretch.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/BayesStretch.py index 34918554d47c18c2113dce110b83f5804c57658a..f173b1db8998799ad83fc6d0fce6eae18be5a831 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/BayesStretch.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/BayesStretch.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name,too-many-instance-attributes,too-many-branches,no-init +from __future__ import (absolute_import, division, print_function) from IndirectImport import * from mantid.api import (PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py index 0dfb1e49517637f6a6ef584d6de44eb3ecb6015c..a4a6c00b98f8be0e293e58d02bdee4ded9674da7 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/EQSANSDirectBeamTransmission.py @@ -179,15 +179,13 @@ class EQSANSDirectBeamTransmission(PythonAlgorithm): {"InputWorkspace": sample_mon_ws, "OutputWorkspace": "__sample_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False - }) + "PreserveEvents": False}) sample_ws = alg.getProperty("OutputWorkspace").value alg = TransmissionUtils.simple_algorithm("Rebin", {"InputWorkspace": empty_mon_ws, "OutputWorkspace": "__empty_mon_"+suffix, "Params": rebin_params, - "PreserveEvents": False - }) + "PreserveEvents": False}) empty_ws = alg.getProperty("OutputWorkspace").value trans_ws, raw_ws = TransmissionUtils.calculate_transmission(self, sample_ws, @@ -198,15 +196,13 @@ class EQSANSDirectBeamTransmission(PythonAlgorithm): {"WorkspaceToRebin": trans_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_"+suffix, - "PreserveEvents": False - }) + "PreserveEvents": False}) trans_ws = alg.getProperty("OutputWorkspace").value alg = TransmissionUtils.simple_algorithm("RebinToWorkspace", {"WorkspaceToRebin": raw_ws, "WorkspaceToMatch": workspace, "OutputWorkspace": "__transmission_unfitted_"+suffix, - "PreserveEvents": False - }) + "PreserveEvents": False}) raw_ws = alg.getProperty("OutputWorkspace").value return trans_ws, raw_ws @@ -220,8 +216,7 @@ class EQSANSDirectBeamTransmission(PythonAlgorithm): alg = TransmissionUtils.simple_algorithm("Plus", {"LHSWorkspace": trans_frame_1, "RHSWorkspace": trans_frame_2, - "OutputWorkspace": "__transmission", - }) + "OutputWorkspace": "__transmission"}) trans_ws = alg.getProperty("OutputWorkspace").value self.setPropertyValue("TransmissionWorkspace", trans_ws_name) self.setProperty("TransmissionWorkspace", trans_ws) @@ -229,8 +224,7 @@ class EQSANSDirectBeamTransmission(PythonAlgorithm): alg = TransmissionUtils.simple_algorithm("Plus", {"LHSWorkspace": raw_frame_1, "RHSWorkspace": raw_frame_2, - "OutputWorkspace": "__transmission_unfitted", - }) + "OutputWorkspace": "__transmission_unfitted"}) raw_ws = alg.getProperty("OutputWorkspace").value raw_ws_name = "__transmission_raw_%s" % input_ws_name self.setPropertyValue("RawTransmissionWorkspace", raw_ws_name) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py index 3fdaf92ca08e82f31a6b6987ed071dd09d99cd10..f3ad42addd96ff22857b4cfe8a019293916174a0 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ElasticWindowMultiple.py @@ -94,7 +94,6 @@ class ElasticWindowMultiple(DataProcessorAlgorithm): return issues def PyExec(self): - from IndirectImport import import_mantidplot from IndirectCommon import getInstrRun # Do setup @@ -293,8 +292,7 @@ class ElasticWindowMultiple(DataProcessorAlgorithm): # Look for temperature in logs in workspace tmp = run[self._sample_log_name].value value_action = {'last_value': lambda x: x[len(x)-1], - 'average': lambda x: x.mean() - } + 'average': lambda x: x.mean()} temp = value_action[self._sample_log_value](tmp) logger.debug('Temperature %d K found for run: %s' % (temp, run_name)) return temp diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FlatPlatePaalmanPingsCorrection.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FlatPlatePaalmanPingsCorrection.py index 71be055c0748acfb243f7c193f42e06d5ae574ba..df9c73c4cb995b3861b0e545027a57bbdf7faa77 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FlatPlatePaalmanPingsCorrection.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/FlatPlatePaalmanPingsCorrection.py @@ -1,4 +1,5 @@ -#pylint: disable=no-init,invalid-name +# pylint: disable=no-init,invalid-name,too-many-instance-attributes + from __future__ import (absolute_import, division, print_function) from six import iteritems from six import integer_types @@ -6,27 +7,30 @@ from six import integer_types import math import numpy as np from mantid.simpleapi import * -from mantid.api import PythonAlgorithm, AlgorithmFactory, PropertyMode, MatrixWorkspaceProperty, \ - WorkspaceGroupProperty, InstrumentValidator, WorkspaceUnitValidator, Progress -from mantid.kernel import StringListValidator, StringMandatoryValidator, IntBoundedValidator, \ - FloatBoundedValidator, Direction, logger, CompositeValidator - -#pylint: disable=too-many-instance-attributes +from mantid.api import (PythonAlgorithm, AlgorithmFactory, PropertyMode, MatrixWorkspaceProperty, + WorkspaceGroupProperty, InstrumentValidator, WorkspaceUnitValidator, Progress) +from mantid.kernel import (StringListValidator, StringMandatoryValidator, IntBoundedValidator, + FloatBoundedValidator, Direction, logger, CompositeValidator, MaterialBuilder) class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): - + # Sample variables _sample_ws_name = None _sample_chemical_formula = None - _sample_number_density = None + _sample_density_type = None + _sample_density = None _sample_thickness = None _sample_angle = 0.0 + + # Container Variables _use_can = False _can_ws_name = None _can_chemical_formula = None - _can_number_density = None + _can_density_type = None + _can_density = None _can_front_thickness = None _can_back_thickness = None + _number_wavelengths = 10 _emode = None _efixed = 0.0 @@ -34,9 +38,9 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): _angles = list() _waves = list() _elastic = 0.0 - _interpolate=None + _interpolate = None -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def category(self): return "Workflow\\MIDAS;CorrectionFunctions\\AbsorptionCorrections" @@ -44,7 +48,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): def summary(self): return "Calculates absorption corrections for a flat plate sample using Paalman & Pings format." -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def PyInit(self): ws_validator = CompositeValidator([WorkspaceUnitValidator('Wavelength'), InstrumentValidator()]) @@ -57,12 +61,18 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='SampleChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='SampleNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Sample number density in atoms/Angstrom3') + + self.declareProperty(name='SampleDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Use of Mass density or Number density') + + self.declareProperty(name='SampleDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') + self.declareProperty(name='SampleThickness', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Sample thickness in cm') + self.declareProperty(name='SampleAngle', defaultValue=0.0, doc='Sample angle in degrees') @@ -74,13 +84,18 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='CanChemicalFormula', defaultValue='', doc='Container chemical formula') - self.declareProperty(name='CanNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Container number density in atoms/Angstrom3') + + self.declareProperty(name='CanDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Use of Mass density or Number density') + + self.declareProperty(name='CanDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='CanFrontThickness', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Container front thickness in cm') + self.declareProperty(name='CanBackThickness', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Container back thickness in cm') @@ -88,12 +103,14 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self.declareProperty(name='NumberWavelengths', defaultValue=10, validator=IntBoundedValidator(1), doc='Number of wavelengths for calculation') + self.declareProperty(name='Interpolate', defaultValue=True, doc='Interpolate the correction workspaces to match the sample workspace') self.declareProperty(name='Emode', defaultValue='Elastic', validator=StringListValidator(['Elastic', 'Indirect', 'Direct']), doc='Energy transfer mode') + self.declareProperty(name='Efixed', defaultValue=1.0, doc='Analyser energy') @@ -101,7 +118,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): direction=Direction.Output), doc='The output corrections workspace group') -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def validateInputs(self): issues = dict() @@ -113,11 +130,11 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): if use_can: can_chemical_formula = self.getPropertyValue('CanChemicalFormula') if can_chemical_formula == '': - issues['CanChemicalFormula'] = 'Must provide a chemical foruma when providing a can workspace' + issues['CanChemicalFormula'] = 'Must provide a chemical formula when providing a can workspace' return issues -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def PyExec(self): self._setup() @@ -126,16 +143,18 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): setup_prog = Progress(self, start=0.0, end=0.2, nreports=2) # Set sample material form chemical formula setup_prog.report('Set sample material') - SetSampleMaterial(InputWorkspace=self._sample_ws_name, - ChemicalFormula=self._sample_chemical_formula, - SampleNumberDensity=self._sample_number_density) + self._sample_density = self._set_material(self._sample_ws_name, + self._sample_chemical_formula, + self._sample_density_type, + self._sample_density) # If using a can, set sample material using chemical formula if self._use_can: - setup_prog.report('Set contianer sample material') - SetSampleMaterial(InputWorkspace=self._can_ws_name, - ChemicalFormula=self._can_chemical_formula, - SampleNumberDensity=self._can_number_density) + setup_prog.report('Set container sample material') + self._can_density = self._set_material(self._can_ws_name, + self._can_chemical_formula, + self._can_density_type, + self._can_density) # Holders for the corrected data data_ass = [] @@ -145,13 +164,13 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self._get_angles() num_angles = len(self._angles) - workflow_prog = Progress(self, start=0.2, end =0.8, nreports=num_angles*2) + workflow_prog = Progress(self, start=0.2, end=0.8, nreports=num_angles * 2) for angle_idx in range(num_angles): - workflow_prog.report('Running flat correction for angle %s' % (angle_idx)) + workflow_prog.report('Running flat correction for angle %s' % angle_idx) angle = self._angles[angle_idx] (ass, assc, acsc, acc) = self._flat_abs(angle) - logger.information('Angle %d: %f successful' % (angle_idx+1, self._angles[angle_idx])) + logger.information('Angle %d: %f successful' % (angle_idx + 1, self._angles[angle_idx])) workflow_prog.report('Appending data for angle %s' % angle_idx) data_ass = np.append(data_ass, ass) data_assc = np.append(data_assc, assc) @@ -173,15 +192,16 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): NSpec=num_angles, UnitX='Wavelength', VerticalAxisUnit='SpectraNumber', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) log_prog.report('Adding sample logs') self._add_sample_logs(ass_ws, sample_logs) workspaces = [ass_ws] if self._use_can: - log_prog.report('Adding can smaple logs') - AddSampleLog(Workspace=ass_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name)) + log_prog.report('Adding can sample logs') + AddSampleLog(Workspace=ass_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False) assc_ws = self._output_ws_name + '_assc' workspaces.append(assc_ws) @@ -192,10 +212,11 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): NSpec=num_angles, UnitX='Wavelength', VerticalAxisUnit='SpectraNumber', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) log_prog.report('Adding assc sample logs') self._add_sample_logs(assc_ws, sample_logs) - AddSampleLog(Workspace=assc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name)) + AddSampleLog(Workspace=assc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False) acsc_ws = self._output_ws_name + '_acsc' workspaces.append(acsc_ws) @@ -206,10 +227,11 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): NSpec=num_angles, UnitX='Wavelength', VerticalAxisUnit='SpectraNumber', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) log_prog.report('Adding acsc sample logs') self._add_sample_logs(acsc_ws, sample_logs) - AddSampleLog(Workspace=acsc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name)) + AddSampleLog(Workspace=acsc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False) acc_ws = self._output_ws_name + '_acc' workspaces.append(acc_ws) @@ -220,23 +242,25 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): NSpec=num_angles, UnitX='Wavelength', VerticalAxisUnit='SpectraNumber', - ParentWorkspace=self._sample_ws_name) + ParentWorkspace=self._sample_ws_name, + EnableLogging=False) log_prog.report('Adding acc sample logs') self._add_sample_logs(acc_ws, sample_logs) - AddSampleLog(Workspace=acc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name)) + AddSampleLog(Workspace=acc_ws, LogName='can_filename', LogType='String', LogText=str(self._can_ws_name), EnableLogging=False) if self._interpolate: self._interpolate_corrections(workspaces) log_prog.report('Grouping Output Workspaces') - GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name) + GroupWorkspaces(InputWorkspaces=','.join(workspaces), OutputWorkspace=self._output_ws_name, EnableLogging=False) self.setPropertyValue('OutputWorkspace', self._output_ws_name) -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _setup(self): self._sample_ws_name = self.getPropertyValue('SampleWorkspace') self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') - self._sample_number_density = self.getProperty('SampleNumberDensity').value + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value self._sample_thickness = self.getProperty('SampleThickness').value self._sample_angle = self.getProperty('SampleAngle').value @@ -244,7 +268,8 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self._use_can = self._can_ws_name != '' self._can_chemical_formula = self.getPropertyValue('CanChemicalFormula') - self._can_number_density = self.getProperty('CanNumberDensity').value + self._can_density_type = self.getPropertyValue('CanDensityType') + self._can_density = self.getProperty('CanDensity').value self._can_front_thickness = self.getProperty('CanFrontThickness').value self._can_back_thickness = self.getProperty('CanBackThickness').value @@ -256,7 +281,34 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self._output_ws_name = self.getPropertyValue('OutputWorkspace') -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ + + def _set_material(self, ws_name, chemical_formula, density_type, density): + """ + Sets the sample material for a given workspace + @param ws_name :: name of the workspace to set sample material for + @param chemical_formula :: Chemical formula of sample + @param density_type :: 'Mass Density' or 'Number Density' + @param density :: Density of sample + @return pointer to the workspace with sample material set + AND + number density of the sample material + """ + set_material_alg = self.createChildAlgorithm('SetSampleMaterial') + if density_type == 'Mass Density': + set_material_alg.setProperty('SampleMassDensity', density) + builder = MaterialBuilder() + mat = builder.setFormula(chemical_formula).setMassDensity(density).build() + number_density = mat.numberDensity + else: + number_density = density + set_material_alg.setProperty('InputWorkspace', ws_name) + set_material_alg.setProperty('ChemicalFormula', chemical_formula) + set_material_alg.setProperty('SampleNumberDensity', number_density) + set_material_alg.execute() + return number_density + + # ------------------------------------------------------------------------------ def _get_angles(self): num_hist = mtd[self._sample_ws_name].getNumberHistograms() @@ -269,7 +321,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): two_theta = detector.getTwoTheta(sample_pos, beam_pos) * 180.0 / math.pi # calc angle self._angles.append(two_theta) -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _wave_range(self): wave_range = '__WaveRange' @@ -278,7 +330,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): wave_min = mtd[wave_range].readX(0)[0] wave_max = mtd[wave_range].readX(0)[len(Xin) - 1] number_waves = self._number_wavelengths - wave_bin = (wave_max - wave_min) / (number_waves-1) + wave_bin = (wave_max - wave_min) / (number_waves - 1) self._waves = list() for idx in range(0, number_waves): @@ -290,9 +342,9 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): self._elastic = math.sqrt(81.787 / self._efixed) # elastic wavelength logger.information('Elastic lambda %f' % self._elastic) - DeleteWorkspace(wave_range) + DeleteWorkspace(wave_range, EnableLogging=False) -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _interpolate_corrections(self, workspaces): """ @@ -308,7 +360,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): OutputWorkspace=ws, OutputWorkspaceDeriv='') -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _add_sample_logs(self, ws, sample_logs): """ @@ -328,9 +380,9 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): else: log_type = 'String' - AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value)) + AddSampleLog(Workspace=ws, LogName=key, LogType=log_type, LogText=str(value), EnableLogging=False) -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _flat_abs(self, angle): """ @@ -364,7 +416,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): sample = mtd[self._sample_ws_name].sample() sam_material = sample.getMaterial() - tsec = tsec * PICONV + tsec *= PICONV sec1 = 1.0 / math.cos(canAngle) sec2 = 1.0 / math.cos(tsec) @@ -373,7 +425,7 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): waves = np.array(self._waves) # Sample cross section - sample_x_section = (sam_material.totalScatterXSection() + sam_material.absorbXSection() * waves / 1.8) * self._sample_number_density + sample_x_section = (sam_material.totalScatterXSection() + sam_material.absorbXSection() * waves / 1.8) * self._sample_density vecFact = np.vectorize(self._fact) fs = vecFact(sample_x_section, self._sample_thickness, sec1, sec2) @@ -383,19 +435,19 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): if sec2 < 0.0: ass = fs / self._sample_thickness else: - ass= np.exp(-sample_sect_2) * fs / self._sample_thickness + ass = np.exp(-sample_sect_2) * fs / self._sample_thickness if self._use_can: can_sample = mtd[self._can_ws_name].sample() can_material = can_sample.getMaterial() # Calculate can cross section - can_x_section = (can_material.totalScatterXSection() + can_material.absorbXSection() * waves / 1.8) * self._can_number_density + can_x_section = (can_material.totalScatterXSection() + can_material.absorbXSection() * waves / 1.8) * self._can_density assc, acsc, acc = self._calculate_can(ass, can_x_section, sample_sect_1, sample_sect_2, [sec1, sec2]) return ass, assc, acsc, acc -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _fact(self, x_section, thickness, sec1, sec2): S = x_section * thickness * (sec1 - sec2) @@ -404,10 +456,10 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): F = thickness else: S = (1 - math.exp(-S)) / S - F = thickness*S + F = thickness * S return F -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ def _calc_thickness_at_x_sect(self, x_section, thickness, sec): sec1, sec2 = sec @@ -417,9 +469,9 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): return thick_sec_1, thick_sec_2 -#------------------------------------------------------------------------------ + # ------------------------------------------------------------------------------ - #pylint: disable=too-many-arguments + # pylint: disable=too-many-arguments def _calculate_can(self, ass, can_x_section, sample_sect_1, sample_sect_2, sec): """ Calculates the A_s,sc, A_c,sc and A_c,c data. @@ -466,7 +518,8 @@ class FlatPlatePaalmanPingsCorrection(PythonAlgorithm): return assc, acsc, acc -#------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------ # Register algorithm with Mantid AlgorithmFactory.subscribe(FlatPlatePaalmanPingsCorrection) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py index dcd8f31a39fa8f058d1579f7d70e552314b4acfb..c45ccaa0ce0b43e6dd8894c9c78aff4b6a75dc24 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/ISISIndirectEnergyTransfer.py @@ -9,9 +9,16 @@ from mantid import config import os -_str_or_none = lambda s: s if s != '' else None -_ws_or_none = lambda s: mtd[s] if s != '' else None -_elems_or_none = lambda l: l if len(l) != 0 else None +def _str_or_none(s): + return s if s != '' else None + + +def _ws_or_none(s): + return mtd[s] if s != '' else None + + +def _elems_or_none(l): + return l if len(l) != 0 else None class ISISIndirectEnergyTransfer(DataProcessorAlgorithm): diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption.py index 6d4d13c30d75b1d1205f4c5d6005771b1995f298..f311fd41862d0d6433320268aa8a71cd9198028d 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectAnnulusAbsorption.py @@ -1,31 +1,37 @@ -#pylint: disable=no-init +# pylint: disable=no-init, too-many-instance-attributes + from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode, Progress, WorkspaceGroupProperty -from mantid.kernel import StringMandatoryValidator, Direction, logger, IntBoundedValidator, FloatBoundedValidator - -#pylint: disable=too-many-instance-attributes +from mantid.kernel import (StringMandatoryValidator, Direction, logger, IntBoundedValidator, + FloatBoundedValidator, StringListValidator, MaterialBuilder) class IndirectAnnulusAbsorption(DataProcessorAlgorithm): + # Sample variables + _sample_ws_name = '' + _sample_chemical_formula = '' + _sample_density_type = None + _sample_density = 0.0 + _sample_inner_radius = 0.0 + _sample_outer_radius = 0.0 + + # Container variables + _can_ws_name = '' + _can_chemical_formula = '' + _can_density_type = None + _can_density = 0.0 _can_inner_radius = 0.0 _can_outer_radius = 0.0 + _use_can_corrections = False + _can_scale = 0.0 + _output_ws = None _ass_ws = None - _can_ws_name = '' - _can_number_density = 0. - _can_chemical_formula = '' - _sample_outer_radius = 0. _abs_ws = None - _events = 0 - _use_can_corrections = False - _sample_ws_name = '' - _can_scale = 0. - _sample_chemical_formula = '' _acc_ws = None - _sample_number_density = 0. - _sample_inner_radius = 0. + _events = 0 def category(self): return "Workflow\\Inelastic;CorrectionFunctions\\AbsorptionCorrections;Workflow\\MIDAS" @@ -38,12 +44,13 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): self.declareProperty(MatrixWorkspaceProperty('SampleWorkspace', '', direction=Direction.Input), doc='Sample workspace.') - self.declareProperty(name='SampleChemicalFormula', defaultValue='', - validator=StringMandatoryValidator(), - doc='Chemical formula for the sample') - self.declareProperty(name='SampleNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Sample number density') + self.declareProperty(name='SampleChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), + doc='Sample chemical formula') + self.declareProperty(name='SampleDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Use of Mass density or Number density') + self.declareProperty(name='SampleDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='SampleInnerRadius', defaultValue=0.2, validator=FloatBoundedValidator(0.0), doc='Sample radius') @@ -59,9 +66,11 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): doc='Use can corrections in subtraction') self.declareProperty(name='CanChemicalFormula', defaultValue='', doc='Chemical formula for the can') - self.declareProperty(name='CanNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Can number density') + self.declareProperty(name='CanDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Use of Mass density or Number density') + self.declareProperty(name='CanDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='CanInnerRadius', defaultValue=0.19, validator=FloatBoundedValidator(0.0), doc='Sample radius') @@ -85,7 +94,7 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): optional=PropertyMode.Optional), doc='The corrections workspace for scattering and absorptions in sample.') - #pylint: disable=too-many-branches + # pylint: disable=too-many-branches def PyExec(self): from IndirectCommon import getEfixed @@ -101,12 +110,17 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): sample_wave_ws = '__sam_wave' ConvertUnits(InputWorkspace=self._sample_ws_name, OutputWorkspace=sample_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging=False) sample_thickness = self._sample_outer_radius - self._sample_inner_radius logger.information('Sample thickness: ' + str(sample_thickness)) prog.report('Calculating sample corrections') + if self._sample_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._sample_chemical_formula).setMassDensity(self._sample_density).build() + self._sample_density = mat.numberDensity + SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_density) AnnularRingAbsorption(InputWorkspace=sample_wave_ws, OutputWorkspace=self._ass_ws, SampleHeight=3.0, @@ -114,7 +128,7 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): CanInnerRadius=self._can_inner_radius, CanOuterRadius=self._can_outer_radius, SampleChemicalFormula=self._sample_chemical_formula, - SampleNumberDensity=self._sample_number_density, + SampleNumberDensity=self._sample_density, NumberOfWavelengthPoints=10, EventsPerPoint=self._events) @@ -124,11 +138,11 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): can1_wave_ws = '__can1_wave' can2_wave_ws = '__can2_wave' ConvertUnits(InputWorkspace=self._can_ws_name, OutputWorkspace=can1_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging=False) if self._can_scale != 1.0: logger.information('Scaling container by: ' + str(self._can_scale)) Scale(InputWorkspace=can1_wave_ws, OutputWorkspace=can1_wave_ws, Factor=self._can_scale, Operation='Multiply') - CloneWorkspace(InputWorkspace=can1_wave_ws, OutputWorkspace=can2_wave_ws) + CloneWorkspace(InputWorkspace=can1_wave_ws, OutputWorkspace=can2_wave_ws, EnableLogging=False) can_thickness_1 = self._sample_inner_radius - self._can_inner_radius can_thickness_2 = self._can_outer_radius - self._sample_outer_radius @@ -138,7 +152,13 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): prog.report('Calculating container corrections') Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - SetSampleMaterial(can1_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density) + if self._can_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._can_chemical_formula).setMassDensity(self._can_density).build() + self._can_density = mat.numberDensity + SetSampleMaterial(can1_wave_ws, ChemicalFormula=self._can_chemical_formula, + SampleNumberDensity=self._can_density) + AnnularRingAbsorption(InputWorkspace=can1_wave_ws, OutputWorkspace='__Acc1', SampleHeight=3.0, @@ -146,11 +166,11 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): CanInnerRadius=self._can_inner_radius, CanOuterRadius=self._sample_outer_radius, SampleChemicalFormula=self._can_chemical_formula, - SampleNumberDensity=self._can_number_density, + SampleNumberDensity=self._can_density, NumberOfWavelengthPoints=10, EventsPerPoint=self._events) - SetSampleMaterial(can2_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density) + SetSampleMaterial(can2_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_density) AnnularRingAbsorption(InputWorkspace=can2_wave_ws, OutputWorkspace='__Acc2', SampleHeight=3.0, @@ -158,13 +178,13 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): CanInnerRadius=self._sample_inner_radius, CanOuterRadius=self._can_outer_radius, SampleChemicalFormula=self._can_chemical_formula, - SampleNumberDensity=self._can_number_density, + SampleNumberDensity=self._can_density, NumberOfWavelengthPoints=10, EventsPerPoint=self._events) - Multiply(LHSWorkspace='__Acc1', RHSWorkspace='__Acc2', OutputWorkspace=self._acc_ws) - DeleteWorkspace('__Acc1') - DeleteWorkspace('__Acc2') + Multiply(LHSWorkspace='__Acc1', RHSWorkspace='__Acc2', OutputWorkspace=self._acc_ws, EnableLogging=False) + DeleteWorkspace('__Acc1', EnableLogging=False) + DeleteWorkspace('__Acc2', EnableLogging=False) Divide(LHSWorkspace=can1_wave_ws, RHSWorkspace=self._acc_ws, OutputWorkspace=can1_wave_ws) Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can1_wave_ws, OutputWorkspace=sample_wave_ws) @@ -175,8 +195,8 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can1_wave_ws, OutputWorkspace=sample_wave_ws) Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - DeleteWorkspace(can1_wave_ws) - DeleteWorkspace(can2_wave_ws) + DeleteWorkspace(can1_wave_ws, EnableLogging=False) + DeleteWorkspace(can2_wave_ws, EnableLogging=False) else: Divide(LHSWorkspace=sample_wave_ws, @@ -187,8 +207,9 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): OutputWorkspace=self._output_ws, Target='DeltaE', EMode='Indirect', - EFixed=efixed) - DeleteWorkspace(sample_wave_ws) + EFixed=efixed, + EnableLogging=False) + DeleteWorkspace(sample_wave_ws, EnableLogging=False) prog.report('Recording sample logs') sample_log_workspaces = [self._output_ws, self._ass_ws] @@ -211,17 +232,17 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): log_values = [item[1] for item in sample_logs] for ws_name in sample_log_workspaces: - AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values) + AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values, EnableLogging=False) self.setProperty('OutputWorkspace', self._output_ws) # Output the Ass workspace if it is wanted, delete if not if self._abs_ws == '': - DeleteWorkspace(self._ass_ws) + DeleteWorkspace(self._ass_ws, EnableLogging=False) if self._can_ws_name is not None and self._use_can_corrections: - DeleteWorkspace(self._acc_ws) + DeleteWorkspace(self._acc_ws, EnableLogging=False) else: - GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws) + GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws, EnableLogging=False) self.setProperty('CorrectionsWorkspace', self._abs_ws) def _setup(self): @@ -231,7 +252,8 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): self._sample_ws_name = self.getPropertyValue('SampleWorkspace') self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') - self._sample_number_density = self.getProperty('SampleNumberDensity').value + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value self._sample_inner_radius = self.getProperty('SampleInnerRadius').value self._sample_outer_radius = self.getProperty('SampleOuterRadius').value @@ -240,7 +262,8 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): self._can_ws_name = None self._use_can_corrections = self.getProperty('UseCanCorrections').value self._can_chemical_formula = self.getPropertyValue('CanChemicalFormula') - self._can_number_density = self.getProperty('CanNumberDensity').value + self._can_density_type = self.getPropertyValue('CanDensityType') + self._can_density = self.getProperty('CanDensity').value self._can_inner_radius = self.getProperty('CanInnerRadius').value self._can_outer_radius = self.getProperty('CanOuterRadius').value self._can_scale = self.getProperty('CanScaleFactor').value @@ -268,7 +291,7 @@ class IndirectAnnulusAbsorption(DataProcessorAlgorithm): issues['CanChemicalFormula'] = 'Must be set to use can corrections' if self._use_can_corrections and self._can_ws_name is None: - issues['UseCanCorrections'] = 'Must specify a can workspace to use can corections' + issues['UseCanCorrections'] = 'Must specify a can workspace to use can corrections' # Geometry validation: can inner < sample inner < sample outer < can outer if self._sample_inner_radius < self._can_inner_radius: diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCylinderAbsorption.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCylinderAbsorption.py index 3ca242228581bca57695088b2b0ec2f5d30df0dc..90e921fb633e0c5b24e6a3d7c0325e112d7e3f5a 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCylinderAbsorption.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectCylinderAbsorption.py @@ -1,25 +1,31 @@ -#pylint: disable=no-init +#pylint: disable=no-init, too-many-instance-attributes + from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, WorkspaceGroupProperty, PropertyMode, Progress -from mantid.kernel import StringMandatoryValidator, Direction, logger, FloatBoundedValidator, IntBoundedValidator - -#pylint: disable=too-many-instance-attributes +from mantid.kernel import (StringMandatoryValidator, Direction, logger, FloatBoundedValidator, + IntBoundedValidator, MaterialBuilder, StringListValidator) class IndirectCylinderAbsorption(DataProcessorAlgorithm): + # Sample variables _sample_ws_name = None _sample_chemical_formula = None - _sample_number_density = None + _sample_density_type = None + _sample_density = None _sample_radius = None + + # Container variables _can_ws_name = None _use_can_corrections = None _can_chemical_formula = None - _can_number_density = None + _can_density_type = None + _can_density = None _can_radius = None _can_scale = None + _events = None _output_ws = None _abs_ws = None @@ -38,9 +44,11 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): doc='Sample workspace.') self.declareProperty(name='SampleChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), doc='Sample chemical formula') - self.declareProperty(name='SampleNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Sample number density') + self.declareProperty(name='SampleDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + self.declareProperty(name='SampleDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='SampleRadius', defaultValue=0.1, validator=FloatBoundedValidator(0.0), doc='Sample radius') @@ -53,9 +61,11 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): doc='Use can corrections in subtraction') self.declareProperty(name='CanChemicalFormula', defaultValue='', doc='Can chemical formula') - self.declareProperty(name='CanNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Can number density') + self.declareProperty(name='CanDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + self.declareProperty(name='CanDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='CanRadius', defaultValue=0.2, validator=FloatBoundedValidator(0.0), doc='Can radius') @@ -92,14 +102,18 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): sample_wave_ws = '__sam_wave' ConvertUnits(InputWorkspace=self._sample_ws_name, OutputWorkspace=sample_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) - - SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_number_density) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging = False) + prog.report('Calculating sample corrections') + if self._sample_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._sample_chemical_formula).setMassDensity(self._sample_density).build() + self._sample_density = mat.numberDensity + SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_density) prog.report('Calculating sample corrections') CylinderAbsorption(InputWorkspace=sample_wave_ws, OutputWorkspace=self._ass_ws, - SampleNumberDensity=self._sample_number_density, + SampleNumberDensity=self._sample_density, NumberOfWavelengthPoints=10, CylinderSampleHeight=3.0, CylinderSampleRadius=self._sample_radius, @@ -111,7 +125,7 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): if self._can_ws_name is not None: can_wave_ws = '__can_wave' ConvertUnits(InputWorkspace=self._can_ws_name, OutputWorkspace=can_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging = False) if self._can_scale != 1.0: logger.information('Scaling can by: ' + str(self._can_scale)) Scale(InputWorkspace=can_wave_ws, OutputWorkspace=can_wave_ws, Factor=self._can_scale, Operation='Multiply') @@ -124,7 +138,12 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): prog.report('Calculating container corrections') Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density) + if self._sample_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._can_chemical_formula).setMassDensity(self._can_density).build() + self._can_density = mat.numberDensity + SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_density) + AnnularRingAbsorption(InputWorkspace=can_wave_ws, OutputWorkspace=self._acc_ws, SampleHeight=3.0, @@ -132,7 +151,7 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): CanInnerRadius=0.9*self._sample_radius, CanOuterRadius=1.1*self._can_radius, SampleChemicalFormula=self._can_chemical_formula, - SampleNumberDensity=self._can_number_density, + SampleNumberDensity=self._can_density, NumberOfWavelengthPoints=10, EventsPerPoint=self._events) @@ -146,14 +165,14 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws) Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - DeleteWorkspace(can_wave_ws) + DeleteWorkspace(can_wave_ws, EnableLogging = False) else: Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) ConvertUnits(InputWorkspace=sample_wave_ws, OutputWorkspace=self._output_ws, - Target='DeltaE', EMode='Indirect', EFixed=efixed) - DeleteWorkspace(sample_wave_ws) + Target='DeltaE', EMode='Indirect', EFixed=efixed, EnableLogging = False) + DeleteWorkspace(sample_wave_ws, EnableLogging = False) # Record sample logs prog.report('Recording sample logs') @@ -173,18 +192,18 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): log_values = [item[1] for item in sample_logs] for ws_name in sample_log_workspaces: - AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values) + AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values, EnableLogging = False) self.setProperty('OutputWorkspace', self._output_ws) # Output the Abs group workspace if it is wanted, delete if not if self._abs_ws == '': - DeleteWorkspace(self._ass_ws) + DeleteWorkspace(self._ass_ws, EnableLogging = False) if self._can_ws_name is not None and self._use_can_corrections: - DeleteWorkspace(self._acc_ws) + DeleteWorkspace(self._acc_ws, EnableLogging = False) else: - GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws) + GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws, EnableLogging = False) self.setProperty('CorrectionsWorkspace', self._abs_ws) def _setup(self): @@ -194,7 +213,8 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): self._sample_ws_name = self.getPropertyValue('SampleWorkspace') self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') - self._sample_number_density = self.getProperty('SampleNumberDensity').value + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value self._sample_radius = self.getProperty('SampleRadius').value self._can_ws_name = self.getPropertyValue('CanWorkspace') @@ -203,7 +223,8 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): self._use_can_corrections = self.getProperty('UseCanCorrections').value self._can_chemical_formula = self.getPropertyValue('CanChemicalFormula') - self._can_number_density = self.getProperty('CanNumberDensity').value + self._can_density_type = self.getPropertyValue('CanDensityType') + self._can_density = self.getProperty('CanDensity').value self._can_radius = self.getProperty('CanRadius').value self._can_scale = self.getProperty('CanScaleFactor').value @@ -234,7 +255,7 @@ class IndirectCylinderAbsorption(DataProcessorAlgorithm): issues['CanChemicalFormula'] = 'Must be set to use can corrections' if self._use_can_corrections and self._can_ws_name is None: - issues['UseCanCorrections'] = 'Must specify a can workspace to use can corections' + issues['UseCanCorrections'] = 'Must specify a can workspace to use can corrections' return issues diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py index b525ff6c5865fac9c2f12e66d93249635485ec08..f0e9aec5bacd1fa231abb3d6763a03238c7237e2 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectFlatPlateAbsorption.py @@ -3,24 +3,30 @@ from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, PropertyMode, Progress, WorkspaceGroupProperty -from mantid.kernel import StringMandatoryValidator, Direction, logger, FloatBoundedValidator +from mantid.kernel import StringMandatoryValidator, Direction, logger, FloatBoundedValidator, MaterialBuilder, StringListValidator class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): + # Sample variables _sample_ws = None _sample_chemical_formula = None - _sample_number_density = None + _sample_density_type = None + _sample_density = None _sample_height = None _sample_width = None _sample_thickness = None + + # Container variables _can_ws_name = None _use_can_corrections = None _can_chemical_formula = None - _can_number_density = None + _can_density_type = None + _can_density = None _can_front_thickness = None _can_back_thickness = None _can_scale = None + _element_size = None _output_ws = None _abs_ws = None @@ -40,9 +46,11 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): self.declareProperty(name='SampleChemicalFormula', defaultValue='', validator=StringMandatoryValidator(), doc='Chemical formula for the sample') - self.declareProperty(name='SampleNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Sample number density') + self.declareProperty(name='SampleDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + self.declareProperty(name='SampleDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='SampleHeight', defaultValue=1.0, validator=FloatBoundedValidator(0.0), doc='Sample height') @@ -61,9 +69,11 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): doc='Use can corrections in subtraction') self.declareProperty(name='CanChemicalFormula', defaultValue='', doc='Chemical formula for the Container') - self.declareProperty(name='CanNumberDensity', defaultValue=0.1, - validator=FloatBoundedValidator(0.0), - doc='Container number density') + self.declareProperty(name='CanDensityType', defaultValue = 'Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc = 'Use of Mass density or Number density') + self.declareProperty(name='CanDensity', defaultValue=0.1, + doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') self.declareProperty(name='CanFrontThickness', defaultValue=0.1, validator=FloatBoundedValidator(0.0), doc='Can front thickness') @@ -102,9 +112,13 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): sample_wave_ws = '__sam_wave' ConvertUnits(InputWorkspace=self._sample_ws, OutputWorkspace=sample_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging = False) - SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_number_density) + if self._sample_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._sample_chemical_formula).setMassDensity(self._sample_density).build() + self._sample_density = mat.numberDensity + SetSampleMaterial(sample_wave_ws, ChemicalFormula=self._sample_chemical_formula, SampleNumberDensity=self._sample_density) prog.report('Calculating sample corrections') FlatPlateAbsorption(InputWorkspace=sample_wave_ws, @@ -122,7 +136,7 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): if self._can_ws_name is not None: can_wave_ws = '__can_wave' ConvertUnits(InputWorkspace=self._can_ws_name, OutputWorkspace=can_wave_ws, - Target='Wavelength', EMode='Indirect', EFixed=efixed) + Target='Wavelength', EMode='Indirect', EFixed=efixed, EnableLogging = False) if self._can_scale != 1.0: logger.information('Scaling container by: ' + str(self._can_scale)) Scale(InputWorkspace=can_wave_ws, OutputWorkspace=can_wave_ws, Factor=self._can_scale, Operation='Multiply') @@ -131,7 +145,12 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): prog.report('Calculating container corrections') Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_number_density) + if self._sample_density_type == 'Mass Density': + builder = MaterialBuilder() + mat = builder.setFormula(self._can_chemical_formula).setMassDensity(self._can_density).build() + self._can_density = mat.numberDensity + SetSampleMaterial(can_wave_ws, ChemicalFormula=self._can_chemical_formula, SampleNumberDensity=self._can_density) + FlatPlateAbsorption(InputWorkspace=can_wave_ws, OutputWorkspace=self._acc_ws, SampleHeight=self._sample_height, @@ -151,16 +170,16 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): Minus(LHSWorkspace=sample_wave_ws, RHSWorkspace=can_wave_ws, OutputWorkspace=sample_wave_ws) Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) - DeleteWorkspace(can_wave_ws) + DeleteWorkspace(can_wave_ws, EnableLogging = False) else: Divide(LHSWorkspace=sample_wave_ws, RHSWorkspace=self._ass_ws, OutputWorkspace=sample_wave_ws) ConvertUnits(InputWorkspace=sample_wave_ws, OutputWorkspace=self._output_ws, - Target='DeltaE', EMode='Indirect', EFixed=efixed) - DeleteWorkspace(sample_wave_ws) + Target='DeltaE', EMode='Indirect', EFixed=efixed, EnableLogging = False) + DeleteWorkspace(sample_wave_ws, EnableLogging = False) - prog.report('Recording samle logs') + prog.report('Recording sample logs') sample_log_workspaces = [self._output_ws, self._ass_ws] sample_logs = [('sample_shape', 'flatplate'), ('sample_filename', self._sample_ws), @@ -181,17 +200,17 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): log_values = [item[1] for item in sample_logs] for ws_name in sample_log_workspaces: - AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values) + AddSampleLogMultiple(Workspace=ws_name, LogNames=log_names, LogValues=log_values, EnableLogging = False) self.setProperty('OutputWorkspace', self._output_ws) # Output the Ass workspace if it is wanted, delete if not if self._abs_ws == '': - DeleteWorkspace(self._ass_ws) + DeleteWorkspace(self._ass_ws, EnableLogging = False) if self._can_ws_name is not None and self._use_can_corrections: - DeleteWorkspace(self._acc_ws) + DeleteWorkspace(self._acc_ws, EnableLogging = False) else: - GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws) + GroupWorkspaces(InputWorkspaces=group, OutputWorkspace=self._abs_ws, EnableLogging = False) self.setProperty('CorrectionsWorkspace', self._abs_ws) def _setup(self): @@ -201,7 +220,8 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): self._sample_ws = self.getPropertyValue('SampleWorkspace') self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') - self._sample_number_density = self.getProperty('SampleNumberDensity').value + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value self._sample_height = self.getProperty('SampleHeight').value self._sample_width = self.getProperty('SampleWidth').value self._sample_thickness = self.getProperty('SampleThickness').value @@ -211,7 +231,8 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): self._can_ws_name = None self._use_can_corrections = self.getProperty('UseCanCorrections').value self._can_chemical_formula = self.getPropertyValue('CanChemicalFormula') - self._can_number_density = self.getProperty('CanNumberDensity').value + self._can_density_type = self.getPropertyValue('CanDensityType') + self._can_density = self.getProperty('CanDensity').value self._can_front_thickness = self.getProperty('CanFrontThickness').value self._can_back_thickness = self.getProperty('CanBackThickness').value self._can_scale = self.getProperty('CanScaleFactor').value @@ -239,7 +260,7 @@ class IndirectFlatPlateAbsorption(DataProcessorAlgorithm): issues['CanChemicalFormula'] = 'Must be set to use can corrections' if self._use_can_corrections and self._can_ws_name is None: - issues['UseCanCorrections'] = 'Must specify a can workspace to use can corections' + issues['UseCanCorrections'] = 'Must specify a can workspace to use can corrections' return issues diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py index 46cfdcecf2c2b41cedf9559fa5ff44da37ac4669..accc5160f35cb2f846e1edabe6a18a979aca580a 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/IndirectResolution.py @@ -4,7 +4,6 @@ from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * -from mantid import logger #pylint: disable=too-many-instance-attributes diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDarkRunBackgroundCorrection.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDarkRunBackgroundCorrection.py index 5118fc700b2ed8510c6ac25c17ef86a421d53e76..509ed637581b307cfcb6692d7723c4e19df610e0 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDarkRunBackgroundCorrection.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSDarkRunBackgroundCorrection.py @@ -48,7 +48,6 @@ class SANSDarkRunBackgroundCorrection(PythonAlgorithm): # Get the workspaces workspace = self.getProperty("InputWorkspace").value dark_run = self.getProperty("DarkRun").value - dummy_output_ws_name = self.getPropertyValue("OutputWorkspace") # Provide progress reporting progress = Progress(self, 0, 1, 4) @@ -378,7 +377,7 @@ class DarkRunMonitorAndDetectorRemover(object): ''' det_id_list = [] if len(monitor_list) != 0: - det_id_list = zip(*monitor_list)[1] + det_id_list = list(zip(*monitor_list))[1] selected_monitors = [] if len(monitor_selection) > 0: diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSFitShiftScale.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSFitShiftScale.py index a6220a87b8d965a304e7d9fe69490a46fc965d7f..1c572a48061ede943d79ca227cfadda9f131e1c4 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSFitShiftScale.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSFitShiftScale.py @@ -178,16 +178,14 @@ class SANSFitShiftScale(DataProcessorAlgorithm): # 2. Shift in x direction # 3. Scaling in x direction # 4. Shift in y direction - row0 = list(param.row(0).items()) - row3 = list(param.row(3).items()) - scale = row0[1][1] + scale = param.row(0)['Value'] if scale == 0.0: raise RuntimeError('Fit scaling as part of stitching evaluated to zero') # In order to determine the shift, we need to remove the scale factor - shift = row3[1][1] / scale + shift = param.row(3)['Value'] / scale return (shift, scale) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSPatchSensitivity.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSPatchSensitivity.py index 7f28904beebe59dcec507c82834cf11ea54c6a63..4ea35add8b688aa50e718da6c70d220d65d825e2 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSPatchSensitivity.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSPatchSensitivity.py @@ -1,4 +1,5 @@ # pylint: disable=no-init,invalid-name,bare-except +from __future__ import (absolute_import, division, print_function) import mantid.simpleapi as api from mantid.api import * from mantid.kernel import * diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSStitch.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSStitch.py index 3b0ce1aa9dd872a0dec5cfc7bce933f8e6870d8d..70dde02ac4fef3e66367c2e0df2c351d2ed68bfb 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSStitch.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSStitch.py @@ -3,7 +3,7 @@ from __future__ import (absolute_import, division, print_function) from mantid.simpleapi import * -from mantid.api import DataProcessorAlgorithm, MatrixWorkspaceProperty, PropertyMode, AnalysisDataService +from mantid.api import DataProcessorAlgorithm, MatrixWorkspaceProperty, PropertyMode from mantid.kernel import Direction, Property, StringListValidator, UnitFactory, \ EnabledWhenProperty, PropertyCriterion import numpy as np diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py index bfe6e2b684af3844aa61c40d2b281c881352b382..75939d3a5664fcb3393de86e6a0b9faab6f32318 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SofQWMoments.py @@ -8,7 +8,6 @@ from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspace from mantid.kernel import Direction from mantid import logger -import os.path import numpy as np @@ -34,7 +33,7 @@ class SofQWMoments(DataProcessorAlgorithm): #pylint: disable=too-many-locals def PyExec(self): - from IndirectCommon import CheckHistZero, CheckElimits, getDefaultWorkingDirectory + from IndirectCommon import CheckHistZero, CheckElimits workflow_prog = Progress(self, start=0.0, end=1.0, nreports=20) workflow_prog.report('Setting up algorithm') diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py index b162138f2ac517c0219bc0564ef922ed8d887f72..d4f6ab0658ba982f75f14ebd236e818a8ae3f727 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransformToIqt.py @@ -4,9 +4,7 @@ from mantid.simpleapi import * from mantid.api import (PythonAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, ITableWorkspaceProperty, PropertyMode, Progress) from mantid.kernel import Direction, logger -from mantid import config import math -import os class TransformToIqt(PythonAlgorithm): diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py index e94a73404eed9eb39f38717b0d16121fd29f3728..ae543a541616c1167211ac1502365103b7e308f5 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/TransmissionUtils.py @@ -67,7 +67,7 @@ def load_monitors(self, property_manager): alg_props = {"Filename": filename, "OutputWorkspace": output_ws, "ReductionProperties": property_manager_name, - } + } if beam_center_x is not None and beam_center_y is not None: alg_props["BeamCenterX"] = beam_center_x alg_props["BeamCenterY"] = beam_center_y @@ -118,8 +118,7 @@ def load_monitors(self, property_manager): # since the beam center may be at a different location alg = _execute("FindDetectorsInShape", {"Workspace": sample_ws, - "ShapeXML": cylXML - }) + "ShapeXML": cylXML}) det_list = alg.getProperty("DetectorList").value first_det = det_list[0] @@ -138,8 +137,7 @@ def load_monitors(self, property_manager): alg = _execute(p.valueAsStr, {"InputWorkspace": workspace, "OutputWorkspace": workspace, - "ReductionProperties": property_manager_name - }, + "ReductionProperties": property_manager_name}, is_name=False) msg = '' if alg.existsProperty("OutputMessage"): @@ -164,55 +162,47 @@ def load_monitors(self, property_manager): alg = _execute("ExtractSingleSpectrum", {"InputWorkspace": empty_ws, "OutputWorkspace": '__reference_binning', - "WorkspaceIndex": det_list[0] - }) + "WorkspaceIndex": det_list[0]}) reference_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": empty_ws_name - }) + "OutputWorkspace": empty_ws_name}) empty_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": sample_ws, "WorkspaceToMatch": reference_ws, - "OutputWorkspace": sample_ws_name - }) + "OutputWorkspace": sample_ws_name}) sample_ws = alg.getProperty("OutputWorkspace").value alg = _execute("GroupDetectors", {"InputWorkspace": empty_ws, "OutputWorkspace": empty_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True - }) + "KeepUngroupedSpectra": True}) empty_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("GroupDetectors", {"InputWorkspace": sample_ws, "OutputWorkspace": sample_mon_ws_name, "DetectorList": det_list, - "KeepUngroupedSpectra": True - }) + "KeepUngroupedSpectra": True}) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": empty_mon_ws, - "OutputWorkspace": empty_mon_ws_name - }) + "OutputWorkspace": empty_mon_ws_name}) empty_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("ConvertToMatrixWorkspace", {"InputWorkspace": sample_mon_ws, - "OutputWorkspace": sample_mon_ws_name - }) + "OutputWorkspace": sample_mon_ws_name}) sample_mon_ws = alg.getProperty("OutputWorkspace").value alg = _execute("RebinToWorkspace", {"WorkspaceToRebin": empty_mon_ws, "WorkspaceToMatch": sample_mon_ws, - "OutputWorkspace": empty_mon_ws_name - }) + "OutputWorkspace": empty_mon_ws_name}) empty_mon_ws = alg.getProperty("OutputWorkspace").value return sample_mon_ws, empty_mon_ws, first_det, output_str, monitor_det_ID @@ -287,8 +277,7 @@ def apply_transmission(self, workspace, trans_workspace): {"WorkspaceToRebin": trans_workspace, "WorkspaceToMatch": workspace, "OutputWorkspace": '__trans_rebin', - "PreserveEvents": False - }) + "PreserveEvents": False}) rebinned_ws = alg.getProperty("OutputWorkspace").value # Apply angle-dependent transmission correction using the zero-angle transmission @@ -298,8 +287,7 @@ def apply_transmission(self, workspace, trans_workspace): {"InputWorkspace": workspace, "TransmissionWorkspace": rebinned_ws, "OutputWorkspace": '__corrected_output', - "ThetaDependent": theta_dependent - }) + "ThetaDependent": theta_dependent}) output_ws = alg.getProperty("OutputWorkspace").value return output_ws @@ -327,8 +315,7 @@ def subtract_dark_current(self, workspace, property_manager): alg_props = {"InputWorkspace": ws, "PersistentCorrection": False, - "ReductionProperties": property_manager_name - } + "ReductionProperties": property_manager_name} if dark_current_file is not None: alg_props["Filename"] = dark_current_file diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py index 1244584bab704098a2642fdddac3893a5a25bb14..52ff3d99454f8827c862d61b836abfbad24aadf2 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/USANSReduction.py @@ -275,8 +275,8 @@ class USANSReduction(PythonAlgorithm): __point = _execute('CropWorkspace', InputWorkspace=sample_monitor, XMin=tof_min, XMax=tof_max, OutputWorkspace='__point') - __monitor_count = _execute('Integration', InputWorkspace=__point, - OutputWorkspace='__monitor_count') + #__monitor_count = _execute('Integration', InputWorkspace=__point, + # OutputWorkspace='__monitor_count') # The monitor count normalization cancels out when doing the transmission correction # of the scattering signal below diff --git a/Framework/PythonInterface/plugins/algorithms/sfCalculator.py b/Framework/PythonInterface/plugins/algorithms/sfCalculator.py index 1c400159897932d9001c1ec0f7458d7ab8b236dd..35e94a2784ed4d08a4cf135e96c4f70304137efb 100644 --- a/Framework/PythonInterface/plugins/algorithms/sfCalculator.py +++ b/Framework/PythonInterface/plugins/algorithms/sfCalculator.py @@ -1334,7 +1334,6 @@ def calculate(string_runs=None,\ #Make sure all the lambdaRequested are identical within a given range lambdaRequestPrecision = 0.01 #1% - _lr = lambdaRequest[0] for i in lambdaRequest: _localValue = float(lambdaRequest[i][0]) @@ -1354,7 +1353,6 @@ def calculate(string_runs=None,\ error_a = [] error_b = [] name = [] - _previous_cal = None finalS1H = [] finalS2H = [] diff --git a/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py b/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py index 705043da723bd12111ccd26abc074ccc5b7a4156..7848c59c7a5562ba4f1cb1abba0bdca460c11979 100644 --- a/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py +++ b/Framework/PythonInterface/plugins/functions/DSFinterp1DFit.py @@ -187,7 +187,7 @@ class DSFinterp1DFit(IFunction1D): # Required to have Mantid recognize the new function #pylint: disable=unused-import try: - import dsfinterp + import dsfinterp # noqa FunctionFactory.subscribe(DSFinterp1DFit) except ImportError: logger.debug('Failed to subscribe fit function DSFinterp1DFit. '+ diff --git a/Framework/PythonInterface/plugins/functions/StretchedExpFT.py b/Framework/PythonInterface/plugins/functions/StretchedExpFT.py index 35090376cee6b816aa11d5669272137e961810e2..22e01e69be162675b1717d462590937fc1b6f021 100644 --- a/Framework/PythonInterface/plugins/functions/StretchedExpFT.py +++ b/Framework/PythonInterface/plugins/functions/StretchedExpFT.py @@ -148,7 +148,7 @@ class StretchedExpFT(IFunction1D): dp = {'Tau': 1.0, # change by 1ps 'Beta': 0.01, 'Centre': 0.0001 # change by 0.1 micro-eV - } + } for name in dp.keys(): pp = copy.copy(p) pp[name] += dp[name] diff --git a/Framework/PythonInterface/test/python/mantid/CMakeLists.txt b/Framework/PythonInterface/test/python/mantid/CMakeLists.txt index 5ccf4ccb5ce9e57894594479c72690666e6d900b..7dab1ba129f06d91d790cb057560126eda7cea13 100644 --- a/Framework/PythonInterface/test/python/mantid/CMakeLists.txt +++ b/Framework/PythonInterface/test/python/mantid/CMakeLists.txt @@ -8,12 +8,15 @@ add_subdirectory( dataobjects ) set ( TEST_PY_FILES ImportModuleTest.py - PVPythonTest.py SimpleAPITest.py SimpleAPILoadTest.py SimpleAPIFitTest.py SimpleAPIRenameWorkspaceTest.py ) +if ( MAKE_VATES ) + list ( APPEND TEST_PY_FILES PVPythonTest.py ) +endif () + # Prefix for test=PythonInterface pyunittest_add_test ( ${CMAKE_CURRENT_SOURCE_DIR} PythonInterface ${TEST_PY_FILES} ) diff --git a/Framework/PythonInterface/test/python/mantid/PVPythonTest.py b/Framework/PythonInterface/test/python/mantid/PVPythonTest.py index c830b7bb4c6233c26ab7846fbd79e788fb309b0e..7ca9a94ae5fd4a5ce0dbcecb2e9daa5efa860cf4 100644 --- a/Framework/PythonInterface/test/python/mantid/PVPythonTest.py +++ b/Framework/PythonInterface/test/python/mantid/PVPythonTest.py @@ -2,11 +2,11 @@ from __future__ import (absolute_import, division, print_function) import unittest from paraview.simple import * + class PVPythonTest(unittest.TestCase): def test_PVPython(self): - self.assertEquals(str(GetParaViewVersion()),'5.1') + self.assertEqual(GetParaViewVersion().major, 5) if __name__ == '__main__': unittest.main() - diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/BayesStretchTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/BayesStretchTest.py index 9bcf14fbae0090062f999ebb5d404e00fc7a1575..1bebe08cf278427a16744ef4e2b6232751e06b7e 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/BayesStretchTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/BayesStretchTest.py @@ -1,3 +1,5 @@ +from __future__ import (absolute_import, division, print_function) + import unittest import platform from mantid.simpleapi import * diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/CalculateSampleTransmissionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/CalculateSampleTransmissionTest.py index 56fe4b407bf7f00f4dff63247156104b127465e0..39c854049a1fc8c8c99891051dbe2b65b188a1f5 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/CalculateSampleTransmissionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/CalculateSampleTransmissionTest.py @@ -2,39 +2,57 @@ from __future__ import (absolute_import, division, print_function) import unittest import numpy as np -import mantid.simpleapi from mantid.simpleapi import CalculateSampleTransmission class CalculateSampleTransmissionTest(unittest.TestCase): - def test_sample_transmission_calculation(self): """ - Test a basic transmission calculation. + Test a basic transmission calculation using number density. """ # Using water sample formula = "H2-O" - density = 0.1 + density = 0.033424 thickness = 0.1 ws = CalculateSampleTransmission(WavelengthRange='5.0,0.2,7.0', ChemicalFormula=formula, - NumberDensity=density, Thickness=thickness) + Density=density, Thickness=thickness, DensityType='Number Density') self.assertEqual(ws.getNumberHistograms(), 2) - expected_trans = [0.564272, 0.564022, 0.563772, 0.563522, 0.563272, 0.563022, 0.562772, 0.562523, 0.562273, 0.562024] - expected_scatt = [0.429309, 0.429309, 0.429309, 0.429309, 0.429309, 0.429309, 0.429309, 0.429309, 0.429309, 0.429309] + expected_trans = [0.825901, 0.825778, 0.825656, 0.825533, 0.825411, 0.825288, 0.825166, 0.825044, 0.824921, 0.824799] + expected_scatt = [0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971] trans = ws.readY(0) scatt = ws.readY(1) np.testing.assert_array_almost_equal(trans, expected_trans, decimal=4) np.testing.assert_array_almost_equal(scatt, expected_scatt, decimal=4) + def test_mass_density(self): + """ + Tests a transmission calculation using mass density + """ + formula = "H2-O" + density = 1 + thickness = 0.1 + + ws = CalculateSampleTransmission(WavelengthRange='5.0,0.2,7.0', ChemicalFormula=formula, + Density=density, Thickness=thickness, DensityType='Mass Density') + + self.assertEqual(ws.getNumberHistograms(), 2) + + expected_trans = [0.825901, 0.825778, 0.825656, 0.825533, 0.825411, 0.825288, 0.825166, 0.825044, 0.824921, 0.824799] + expected_scatt = [0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971, 0.170971] + + trans = ws.readY(0) + scatt = ws.readY(1) + np.testing.assert_array_almost_equal(trans, expected_trans, decimal=4) + np.testing.assert_array_almost_equal(scatt, expected_scatt, decimal=4) def test_validate_density(self): """ - Tests validation on NumberDensity property. + Tests validation on Density property. """ # Using water sample @@ -46,7 +64,6 @@ class CalculateSampleTransmissionTest(unittest.TestCase): WavelengthRange='5.0,0.2,7.0', ChemicalFormula=formula, NumberDensity=density, Thickness=thickness) - def test_validate_thickness(self): """ Tests validation on Thickness property. @@ -62,5 +79,5 @@ class CalculateSampleTransmissionTest(unittest.TestCase): NumberDensity=density, Thickness=thickness) -if __name__=="__main__": +if __name__ == "__main__": unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/CylinderPaalmanPingsCorrection2Test.py b/Framework/PythonInterface/test/python/plugins/algorithms/CylinderPaalmanPingsCorrection2Test.py index 657864282ca96c5c2fb38b1f0b20c7d514e74817..6be2352e7ee1749b642b51333f70637fc775e1d8 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/CylinderPaalmanPingsCorrection2Test.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/CylinderPaalmanPingsCorrection2Test.py @@ -8,7 +8,6 @@ from mantid.simpleapi import (CreateSampleWorkspace, Scale, DeleteWorkspace, class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): - def setUp(self): """ Create sample workspaces. @@ -21,6 +20,7 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): XMin=6.8, XMax=7.9, BinWidth=0.1) + self._sample_ws = sample can = Scale(InputWorkspace=sample, Factor=1.2) @@ -28,7 +28,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): self._corrections_ws_name = 'corrections' - def tearDown(self): """ Remove workspaces from ADS. @@ -40,7 +39,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): if self._corrections_ws_name in mtd: DeleteWorkspace(self._corrections_ws_name) - def _verify_workspace(self, ws_name): """ Do validation on a correction workspace. @@ -66,7 +64,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): # Check it has X binning matching sample workspace self.assertEqual(test_ws.blocksize(), self._sample_ws.blocksize()) - def _verify_workspaces_for_can(self): """ Do validation on the additional correction factors for sample and can. @@ -82,7 +79,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): for workspace in workspaces: self._verify_workspace(workspace) - def test_sampleOnly_Indirect(self): """ Test simple run with sample workspace only for indirect mode @@ -103,7 +99,7 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): """ Test simple run with sample workspace only for direct mode """ - + CylinderPaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, SampleWorkspace=self._sample_ws, SampleChemicalFormula='H2-O', @@ -111,11 +107,10 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): SampleOuterRadius=0.1, Emode='Direct', Efixed=1.845) - + ass_ws_name = self._corrections_ws_name + '_ass' self._verify_workspace(ass_ws_name) - def test_sampleAndCan(self): """ Test simple run with sample and can workspace. @@ -136,7 +131,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): self._verify_workspaces_for_can() - def test_sampleAndCanDefaults(self): """ Test simple run with sample and can workspace using the default values. @@ -150,6 +144,39 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): self._verify_workspaces_for_can() + def test_number_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + CylinderPaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, + SampleWorkspace=self._sample_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Number Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Number Density', + CanDensity=0.5) + + self._verify_workspaces_for_can() + + def test_mass_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and mass density for both + """ + + CylinderPaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, + SampleWorkspace=self._sample_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Mass Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Mass Density', + CanDensity=0.5) + + self._verify_workspaces_for_can() def test_InterpolateDisabled(self): """ @@ -170,7 +197,6 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): for workspace in corrections_ws: self.assertEqual(workspace.blocksize(), 10) - def test_validationNoCanFormula(self): """ Tests validation for no chemical formula for can when a can WS is provided. @@ -191,5 +217,5 @@ class CylinderPaalmanPingsCorrection2Test(unittest.TestCase): Efixed=1.845) -if __name__=="__main__": +if __name__ == "__main__": unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/EnggCalibrateFullTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/EnggCalibrateFullTest.py index 6e160c82c4df9ebb01dc291637aa3633feda9f0b..7dd8388b27a0c4c8a55be7ecdc4ee6a0c9305599 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/EnggCalibrateFullTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/EnggCalibrateFullTest.py @@ -28,35 +28,35 @@ class EnggCalibrateFullTest(unittest.TestCase): Input='foo', Bank='1') # Wrong workspace name - self.assertRaises(RuntimeError, + self.assertRaises(ValueError, EnggCalibrateFull, - Input='this_ws_is_not_there.not', Bank='2') + Workspace='this_ws_is_not_there.not', Bank='2') # mispelled ExpectedPeaks self.assertRaises(RuntimeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, Bank='2', Peaks='2') + Workspace=self.__class__._data_ws, Bank='2', Peaks='2') # mispelled OutDetPosFilename self.assertRaises(RuntimeError, EnggCalibrateFull, OutDetPosFile='any.csv', - InputWorkspace=self.__class__._data_ws, Bank='2', Peaks='2') + Workspace=self.__class__._data_ws, Bank='2', Peaks='2') - # all fine, except missing DetectorPositions (output) + # all fine, except missing OutDetPosTable (output) self.assertRaises(RuntimeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, Bank='2') + Workspace=self.__class__._data_ws, Bank='2') # all fine, except Bank should be a string - self.assertRaises(RuntimeError, + self.assertRaises(TypeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, DetectorPositions=[0.6, 0.9], - Bank='2') + Workspace=self.__class__._data_ws, OutDetPosTable='det_pos_tbl', + Bank=2) - # all fine, except for the wrong rebin bin width - self.assertRaises(RuntimeError, + # all fine, except for the wrong rebin bin width type + self.assertRaises(TypeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, DetectorPositions=[0.6, 0.9], + Workspace=self.__class__._data_ws, OutDetPosTable='det_pos_tbl', RebinBinWidth=[0, 2, 3], Bank='2') @@ -69,8 +69,8 @@ class EnggCalibrateFullTest(unittest.TestCase): # warnings and finally raise after a 'some peaks not found' error self.assertRaises(RuntimeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, ExpectedPeaks=[0.01], Bank='1', - DetectorPositions='out_det_positions_table') + Workspace=self.__class__._data_ws, ExpectedPeaks=[0.01], Bank='1', + OutDetPosTable='out_det_positions_table') def test_run_ok_but_bad_data(self): @@ -84,9 +84,9 @@ class EnggCalibrateFullTest(unittest.TestCase): tbl_name = 'det_peaks_tbl' self.assertRaises(RuntimeError, EnggCalibrateFull, - InputWorkspace=self.__class__._data_ws, Bank='2', + Workspace=self.__class__._data_ws, Bank='2', ExpectedPeaks='0.915, 1.257, 1.688', - DetectorPositions=tbl_name) + OutDetPosTable=tbl_name) diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py index e13b6666e232f2341db5bdad4866e7b9bc0a63a0..e8cb846a2d8469a7c128b97da6dc32412f6ce337 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/ExportExperimentLogTest.py @@ -9,6 +9,7 @@ import mantid.kernel as kernel from testhelpers import run_algorithm from mantid.api import AnalysisDataService import os +from six.moves import range class ExportExperimentLogTest(unittest.TestCase): @@ -387,7 +388,7 @@ class ExportExperimentLogTest(unittest.TestCase): self.assertEquals(len(lines), 4) # Check value - for i in xrange(1, 3): + for i in range(1, 3): currline = lines[i] curr_run = int(currline.split(",")[0]) curr_min = float(currline.split(",")[2]) @@ -503,7 +504,7 @@ class ExportExperimentLogTest(unittest.TestCase): self.assertEquals(len(lines), 4) # Check value - for i in xrange(1, 3): + for i in range(1, 3): currline = lines[i] curr_run = int(currline.split("\t")[0]) curr_min = float(currline.split("\t")[2]) @@ -599,7 +600,7 @@ class ExportExperimentLogTest(unittest.TestCase): self.assertEquals(len(lines), 4) # Check value - for i in xrange(1, 3): + for i in range(1, 3): currline = lines[i] curr_run = int(currline.split("\t")[0]) curr_min = float(currline.split("\t")[2]) diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py index cfe5d059a7b92ab9c214f3afc114c26dcdab351f..236aef0ddafee36945e730bd02a856d649deb61b 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/ExportSampleLogsToCSVFileTest.py @@ -9,6 +9,7 @@ import mantid.kernel as kernel from testhelpers import run_algorithm from mantid.api import AnalysisDataService import os +from six.moves import range class ExportVulcanSampleLogTest(unittest.TestCase): @@ -334,7 +335,7 @@ class ExportVulcanSampleLogTest(unittest.TestCase): if i > 0: numnorecord = random.randint(-1, 4) if numnorecord > 0: - for j in xrange(numnorecord): + for j in range(numnorecord): logindex = random.randint(0, 6) skiploglist.append(logindex) # ENDFOR (j) @@ -344,7 +345,7 @@ class ExportVulcanSampleLogTest(unittest.TestCase): dbbuf += "----------- %d -------------\n" % (i) # Record - for j in xrange(4): + for j in range(4): # Skip if selected if j in skiploglist: continue diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/ExportSpectraMaskTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/ExportSpectraMaskTest.py index 2ec72d02986ff0bb34e2fb781e8e60d0f75dffe7..729540239c5560f253d5c9ba3b797b80a4773bce 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/ExportSpectraMaskTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/ExportSpectraMaskTest.py @@ -1,9 +1,12 @@ +from __future__ import (absolute_import, division, print_function) + import os import sys import numpy as np import unittest import mantid from mantid.simpleapi import ExportSpectraMask,DeleteWorkspace +from six.moves import range class ExportSpectraMaskTest(unittest.TestCase): def __init__(self,method_name): @@ -11,7 +14,7 @@ class ExportSpectraMaskTest(unittest.TestCase): self.this_path = os.path.dirname(os.path.realpath(__file__)) test_path = self.this_path; - for i in xrange(0,4): + for i in range(0,4): test_path,_ = os.path.split(test_path) self.test_mod_path = os.path.join(test_path,'plugins/algorithms') sys.path.append(self.test_mod_path) diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/ExtractMonitorsTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/ExtractMonitorsTest.py index 0a0914e9583f2041c5af802bdfaabf99f57c1dfc..8deffe33afe7c257ffcc9e0f4b3a83e7471dacca 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/ExtractMonitorsTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/ExtractMonitorsTest.py @@ -1,3 +1,5 @@ +from __future__ import (absolute_import, division, print_function) + import unittest from mantid.simpleapi import * diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/FlatPlatePaalmanPingsCorrectionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/FlatPlatePaalmanPingsCorrectionTest.py index e3d68386e57abe782f4cbf4ae9abc170789ec977..9320d50aebb0805a23dcc7c3d69d6db1610db870 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/FlatPlatePaalmanPingsCorrectionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/FlatPlatePaalmanPingsCorrectionTest.py @@ -3,11 +3,10 @@ from __future__ import (absolute_import, division, print_function) import unittest from mantid.kernel import * from mantid.api import * -from mantid.simpleapi import CreateSampleWorkspace, Scale, DeleteWorkspace, FlatPlatePaalmanPingsCorrection, CreateSimulationWorkspace +from mantid.simpleapi import CreateSampleWorkspace, Scale, DeleteWorkspace, FlatPlatePaalmanPingsCorrection class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): - def setUp(self): """ Create sample workspaces. @@ -15,11 +14,11 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): # Create some test data sample = CreateSampleWorkspace(NumBanks=1, - BankPixelWidth=1, - XUnit='Wavelength', - XMin=6.8, - XMax=7.9, - BinWidth=0.1) + BankPixelWidth=1, + XUnit='Wavelength', + XMin=6.8, + XMax=7.9, + BinWidth=0.1) self._sample_ws = sample can = Scale(InputWorkspace=sample, Factor=1.2) @@ -27,7 +26,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): self._corrections_ws_name = 'corrections' - def tearDown(self): """ Remove workspaces from ADS. @@ -39,7 +37,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): if self._corrections_ws_name in mtd: DeleteWorkspace(self._corrections_ws_name) - def _verify_workspace(self, ws_name): """ Do validation on a correction workspace. @@ -65,7 +62,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): # Check it has X binning matching sample workspace self.assertEqual(test_ws.blocksize(), self._sample_ws.blocksize()) - def _verify_workspaces_for_can(self): """ Do validation on the additional correction factors for sample and can. @@ -81,7 +77,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): for workspace in workspaces: self._verify_workspace(workspace) - def test_sampleOnly_indirect(self): """ Test simple run with sample workspace only for indirect mode @@ -97,13 +92,13 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): Efixed=1.845) ass_ws_name = self._corrections_ws_name + '_ass' - self. _verify_workspace(ass_ws_name) + self._verify_workspace(ass_ws_name) def test_sampleOnly_direct(self): """ Test simple run with sample workspace only for direct mode """ - + FlatPlatePaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, SampleWorkspace=self._sample_ws, SampleChemicalFormula='H2-O', @@ -112,10 +107,9 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): NumberWavelengths=10, Emode='Direct', Efixed=1.845) - - ass_ws_name = self._corrections_ws_name + '_ass' - self. _verify_workspace(ass_ws_name) + ass_ws_name = self._corrections_ws_name + '_ass' + self._verify_workspace(ass_ws_name) def test_sampleAndCan(self): """ @@ -137,7 +131,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): self._verify_workspaces_for_can() - def test_sampleAndCanDefaults(self): """ Test simple run with sample and can workspace using the default values. @@ -151,6 +144,38 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): self._verify_workspaces_for_can() + def test_number_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + FlatPlatePaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, + SampleWorkspace=self._sample_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Number Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Number Density', + CanDensity=0.5) + self._verify_workspaces_for_can() + + def test_mass_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and mass density for both + """ + + FlatPlatePaalmanPingsCorrection(OutputWorkspace=self._corrections_ws_name, + SampleWorkspace=self._sample_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Mass Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Mass Density', + CanDensity=0.5) + + self._verify_workspaces_for_can() def test_InterpolateDisabled(self): """ @@ -172,7 +197,6 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): for workspace in corrections_ws: self.assertEqual(workspace.blocksize(), 20) - def test_validationNoCanFormula(self): """ Tests validation for no chemical formula for can when a can WS is provided. @@ -193,5 +217,5 @@ class FlatPlatePaalmanPingsCorrectionTest(unittest.TestCase): Efixed=1.845) -if __name__=="__main__": +if __name__ == "__main__": unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectAnnulusAbsorptionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectAnnulusAbsorptionTest.py index 000bb99eb225572c210fc09acd06af97122f8961..4a308a5a3d3cd4aae600ae995b3e673c28b374b9 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectAnnulusAbsorptionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectAnnulusAbsorptionTest.py @@ -102,6 +102,43 @@ class IndirectAnnulusAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 2) self._test_workspaces(corrected, fact) + def test_number_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectAnnulusAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Number Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Number Density', + CanDensity=0.5, + Events = 200, + UseCanCorrections = True) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) + + def test_mass_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectAnnulusAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Mass Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Mass Density', + CanDensity=0.5, + Events = 200, + UseCanCorrections = True) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) if __name__ == '__main__': unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectCylinderAbsorptionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectCylinderAbsorptionTest.py index a55f2a95cc243f72e7c96cb18875e07136ac3b80..65a8a308d34a9b771ed1188aee9bbbcbf93eaabc 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectCylinderAbsorptionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectCylinderAbsorptionTest.py @@ -6,7 +6,6 @@ from mantid.api import * class IndirectCylinderAbsorptionTest(unittest.TestCase): - def setUp(self): """ Loads the reduced container and sample files. @@ -18,7 +17,6 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): self._can_ws = can_ws self._red_ws = red_ws - def _test_workspaces(self, corrected, factor_group): """ Checks the units of the Ass and corrected workspaces. @@ -39,7 +37,6 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): y_unit = ws.YUnitLabel() self.assertEqual(y_unit, 'Attenuation factor') - def test_sample_corrections_only(self): """ Tests corrections for the sample only. @@ -52,7 +49,6 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_subtraction(self): """ Tests corrections for the sample and simple container subtraction. @@ -67,7 +63,6 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_subtraction_with_scale(self): """ Tests corrections for the sample and simple container subtraction @@ -84,7 +79,6 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_corrections(self): """ Tests corrections for the sample and container. @@ -100,6 +94,44 @@ class IndirectCylinderAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 2) self._test_workspaces(corrected, fact) + def test_number_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectCylinderAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Number Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Number Density', + CanDensity=0.5, + Events=200, + UseCanCorrections=True) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) + + def test_mass_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectCylinderAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Mass Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Mass Density', + CanDensity=0.5, + Events=200, + UseCanCorrections=True) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) + if __name__ == '__main__': unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectFlatPlateAbsorptionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectFlatPlateAbsorptionTest.py index c8078aad0002ac331526c6c7eab63c38c3326345..2020ba2574fdd1ff29a4fd22b77a290a86bb991b 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectFlatPlateAbsorptionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectFlatPlateAbsorptionTest.py @@ -6,7 +6,6 @@ from mantid.api import * class IndirectFlatPlateAbsorptionTest(unittest.TestCase): - def setUp(self): """ Loads the reduced container and sample files. @@ -18,7 +17,6 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): self._can_ws = can_ws self._red_ws = red_ws - def _test_workspaces(self, corrected, factor_group): """ Checks the units of the Ass and corrected workspaces. @@ -39,7 +37,6 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): y_unit = ws.YUnitLabel() self.assertEqual(y_unit, 'Attenuation factor') - def test_sample_corrections_only(self): """ Tests corrections for the sample only. @@ -52,7 +49,6 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_subtraction(self): """ Tests corrections for the sample and simple container subtraction. @@ -67,7 +63,6 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_subtraction_with_scale(self): """ Tests corrections for the sample and simple container subtraction @@ -84,7 +79,6 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 1) self._test_workspaces(corrected, fact) - def test_sample_and_can_correction(self): """ Tests corrections for the sample and container. @@ -100,6 +94,44 @@ class IndirectFlatPlateAbsorptionTest(unittest.TestCase): self.assertEqual(fact.size(), 2) self._test_workspaces(corrected, fact) + def test_mass_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectFlatPlateAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Number Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Number Density', + CanDensity=0.5, + UseCanCorrections=True, + ElementSize=1) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) + + def test_number_density_for_sample_can(self): + """ + Test simple run with sample and can workspace and number density for both + """ + + corrected, fact = IndirectFlatPlateAbsorption(SampleWorkspace=self._red_ws, + SampleChemicalFormula='H2-O', + SampleDensityType='Mass Density', + SampleDensity=0.5, + CanWorkspace=self._can_ws, + CanChemicalFormula='V', + CanDensityType='Mass Density', + CanDensity=0.5, + UseCanCorrections=True, + ElementSize=1) + + self.assertEqual(fact.size(), 2) + self._test_workspaces(corrected, fact) + if __name__ == '__main__': unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectTransmissionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectTransmissionTest.py index a4203b87ab0699f60a0c79eeea607cb2d802101f..0c562a46d5b1070c7b4a1a0a31254919274e9d95 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/IndirectTransmissionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/IndirectTransmissionTest.py @@ -2,12 +2,10 @@ from __future__ import (absolute_import, division, print_function) import unittest import numpy as np -import mantid.simpleapi from mantid.simpleapi import IndirectTransmission class IndirectTransmissionTest(unittest.TestCase): - def test_indirect_transmission_iris_graphite_002(self): """ Test a transmission calculation using IRIS, graphite, 002. @@ -23,14 +21,13 @@ class IndirectTransmissionTest(unittest.TestCase): thickness = 0.1 ws = IndirectTransmission(Instrument=instrument, Analyser=analyser, Reflection=reflection, - ChemicalFormula=formula, NumberDensity=density, Thickness=thickness) + ChemicalFormula=formula, DensityType='Number Density', Density=density, Thickness=thickness) # Expected values from table ref_result = [6.658, 0.821223, 2.58187, 53.5069, 56.0888, 0.1, 0.1, 0.566035, 0.429298] values = ws.column(1) np.testing.assert_array_almost_equal(values, ref_result, decimal=4) - def test_indirect_transmission_tosca_graphite_002(self): """ Test a transmission calculation using TOSCA, graphite, 002. @@ -46,14 +43,13 @@ class IndirectTransmissionTest(unittest.TestCase): thickness = 0.1 ws = IndirectTransmission(Instrument=instrument, Analyser=analyser, Reflection=reflection, - ChemicalFormula=formula, NumberDensity=density, Thickness=thickness) + ChemicalFormula=formula, DensityType='Number Density', Density=density, Thickness=thickness) # Expected values from table ref_result = [5.5137, 0.680081, 2.58187, 53.5069, 56.0888, 0.1, 0.1, 0.566834, 0.429298] values = ws.column(1) np.testing.assert_array_almost_equal(values, ref_result, decimal=4) - def test_indirect_transmission_basis_silicon_111(self): """ Test a transmission calculation using BASIS, silicon 111. @@ -69,14 +65,13 @@ class IndirectTransmissionTest(unittest.TestCase): thickness = 0.1 ws = IndirectTransmission(Instrument=instrument, Analyser=analyser, Reflection=reflection, - ChemicalFormula=formula, NumberDensity=density, Thickness=thickness) + ChemicalFormula=formula, DensityType='Number Density', Density=density, Thickness=thickness) # Expected values from table ref_result = [6.26761, 0.77307, 2.58187, 53.5069, 56.0888, 0.1, 0.1, 0.566307, 0.429298] values = ws.column(1) np.testing.assert_array_almost_equal(values, ref_result, decimal=4) - def test_indirect_transmission_analyser_validation(self): """ Verifies analyser validation based on instrument is working. @@ -93,10 +88,9 @@ class IndirectTransmissionTest(unittest.TestCase): Instrument=instrument, Analyser=analyser, Reflection=reflection, ChemicalFormula=formula, OutputWorkspace='__IndirectTransmissionTest_AnalyserValidation') - def test_indirect_transmission_reflection_validation(self): """ - Verified reflecction validation based on analyser is working. + Verified reflection validation based on analyser is working. """ instrument = "IRIS" @@ -110,6 +104,32 @@ class IndirectTransmissionTest(unittest.TestCase): Instrument=instrument, Analyser=analyser, Reflection=reflection, ChemicalFormula=formula, OutputWorkspace='__IndirectTransmissionTest_ReflectionValidation') + def test_mass_density(self): + """ + Tests a transmission calculation using mass density + """ + instrument = "IRIS" + analyser = "graphite" + reflection = "002" + + formula = "H2-O" + density = 1.0 + thickness = 0.1 + + ws = IndirectTransmission(Instrument=instrument, Analyser=analyser, Reflection=reflection, + ChemicalFormula=formula, DensityType='Mass Density', Density=density, Thickness=thickness) + + ref_result = [6.65800, 0.82122, 2.58186, 53.50693, 56.08880, 0.03342, 0.1, 0.82676, 0.17096] + mass_values = ws.column(1) + np.testing.assert_array_almost_equal(mass_values, ref_result, decimal=4) + + # mass density 1.0 = number density 0.033424 for water + density = 0.033424 + ws = IndirectTransmission(Instrument=instrument, Analyser=analyser, Reflection=reflection, + ChemicalFormula=formula, DensityType='Number Density', Density=density, Thickness=thickness) + num_values = ws.column(1) + np.testing.assert_array_almost_equal(mass_values, num_values, decimal=4) + -if __name__=="__main__": +if __name__ == "__main__": unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/LoadNMoldyn4Ascii1DTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/LoadNMoldyn4Ascii1DTest.py index 8a86d10f32f5d65960950076bd53fc1602b55113..46f6c4b8ca8a4e3eee4b4578f6bf33fb54620c58 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/LoadNMoldyn4Ascii1DTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/LoadNMoldyn4Ascii1DTest.py @@ -1,3 +1,5 @@ +from __future__ import (absolute_import, division, print_function) + import unittest from mantid.simpleapi import * from mantid.api import * diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/SANSDarkRunBackgroundCorrectionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/SANSDarkRunBackgroundCorrectionTest.py index 6c77772e1b15bce67de7c4730b0739dca3e5ede9..c0d770eaad502bf249c57e9c3fa5a2430f2cd51d 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/SANSDarkRunBackgroundCorrectionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/SANSDarkRunBackgroundCorrectionTest.py @@ -8,6 +8,7 @@ from testhelpers import run_algorithm import numpy as np from SANSDarkRunBackgroundCorrection import DarkRunMonitorAndDetectorRemover from SANSDarkRunBackgroundCorrection import SANSDarkRunBackgroundCorrection +from six.moves import range class SANSDarkRunBackgroundCorrectionTest(unittest.TestCase): #----- @@ -77,8 +78,8 @@ class SANSDarkRunBackgroundCorrectionTest(unittest.TestCase): e_value_scatter_run,name_scatter, spectra) bin_boundaries_dark_run = 20 - y_value_spectra_even_dark_run = [0.3 for element in xrange(bin_boundaries_dark_run - 1)] - y_value_spectra_odd_dark_run = [0.2 for element in xrange(bin_boundaries_dark_run - 1)] + y_value_spectra_even_dark_run = [0.3 for element in range(bin_boundaries_dark_run - 1)] + y_value_spectra_odd_dark_run = [0.2 for element in range(bin_boundaries_dark_run - 1)] y_value_dark_run = (y_value_spectra_even_dark_run + y_value_spectra_odd_dark_run + y_value_spectra_even_dark_run + y_value_spectra_odd_dark_run) e_value_dark_run = 0 @@ -126,13 +127,13 @@ class SANSDarkRunBackgroundCorrectionTest(unittest.TestCase): spectra = 4 bin_boundaries= 5 - y_value_scatter_run = spectra*[element for element in xrange(bin_boundaries-1)] + y_value_scatter_run = spectra*[element for element in range(bin_boundaries-1)] e_value_scatter_run = 1. name_scatter = "_scatter_SANS_test" self._provide_workspace2D(bin_boundaries, y_value_scatter_run, e_value_scatter_run,name_scatter, spectra, True) - y_value_dark_run = spectra*[element*0.2 for element in xrange(bin_boundaries - 1)] + y_value_dark_run = spectra*[element*0.2 for element in range(bin_boundaries - 1)] e_value_dark_run = 0 name_dark_run = "_dark_run_SANS_test" self._provide_workspace2D(bin_boundaries, y_value_dark_run, @@ -500,13 +501,13 @@ class SANSDarkRunBackgroundCorrectionTest(unittest.TestCase): self.assertAlmostEqual(expected, y_corrected[elem], 4) def _provide_workspace2D(self, bin_boundaries, y_value, e_value, name, spectra, use_y_list = False): - x = spectra*[element for element in xrange(bin_boundaries)] + x = spectra*[element for element in range(bin_boundaries)] y = None if use_y_list: y = y_value else: - y = spectra*[y_value for element in xrange(bin_boundaries - 1)] - e = spectra*[e_value for element in xrange(bin_boundaries - 1)] + y = spectra*[y_value for element in range(bin_boundaries - 1)] + e = spectra*[e_value for element in range(bin_boundaries - 1)] self._create_test_workspace(name, x, y, e, spectra) def _clean_up(self, ws_to_clean): diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/SaveNexusPDTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/SaveNexusPDTest.py index b33fde59a305314629ddebd149c2d6b0f3a721d1..ff7524f650685f43bf49630f00aff03ef8a2537e 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/SaveNexusPDTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/SaveNexusPDTest.py @@ -78,7 +78,7 @@ class SaveNexusPDTest(unittest.TestCase): def check(self, filename, withInstrument): with h5py.File(filename, 'r') as handle: - nxentry = handle[handle.keys()[0]] + nxentry = handle[sorted(handle.keys())[0]] nxinstrument = nxentry['instrument'] nxmoderator = nxinstrument['moderator'] diff --git a/MantidPlot/CMakeLists.txt b/MantidPlot/CMakeLists.txt index 2baea3ffc05cc66d0c60c149121c4fd634e3c06d..4903ff36886a69a6700cc90a8b2d7a9f6f8a4a1e 100644 --- a/MantidPlot/CMakeLists.txt +++ b/MantidPlot/CMakeLists.txt @@ -169,7 +169,6 @@ set ( MANTID_SRCS src/Mantid/AlgorithmMonitor.cpp src/Mantid/ImportWorkspaceDlg.cpp src/Mantid/InputHistory.cpp src/Mantid/LabelToolLogValuesDialog.cpp - src/Mantid/LoadDAEDlg.cpp src/Mantid/ManageCustomMenus.cpp src/Mantid/ManageInterfaceCategories.cpp src/Mantid/MantidAbout.cpp @@ -365,7 +364,6 @@ set ( MANTID_HDRS src/Mantid/AlgorithmMonitor.h src/Mantid/IMantidMatrixExtensionHandler.h src/Mantid/InputHistory.h src/Mantid/LabelToolLogValuesDialog.h - src/Mantid/LoadDAEDlg.h src/Mantid/ManageCustomMenus.h src/Mantid/ManageInterfaceCategories.h src/Mantid/MantidAbout.h @@ -600,7 +598,6 @@ set ( MANTID_MOC_FILES src/Mantid/AlgorithmMonitor.h src/Mantid/IFunctionWrapper.h src/Mantid/ImportWorkspaceDlg.h src/Mantid/LabelToolLogValuesDialog.h - src/Mantid/LoadDAEDlg.h src/Mantid/ManageCustomMenus.h src/Mantid/ManageInterfaceCategories.h src/Mantid/MantidAbout.h @@ -893,9 +890,12 @@ set ( MANTIDPLOT_TEST_PY_FILES MantidPlotTiledWindowTest.py MantidPlotInputArgsCheck.py MantidPlotPyplotGeneralTest.py - MantidPlotPVPythonTest.py ) +if ( MAKE_VATES ) + list ( APPEND MANTIDPLOT_TEST_PY_FILES MantidPlotPVPythonTest.py ) +endif () + if ( 0 ) message (STATUS "Your CMAKE_SYSTEM string is '${CMAKE_SYSTEM}'") message (STATUS "Your CMAKE_SYSTEM_NAME string is '${CMAKE_SYSTEM_NAME}'") diff --git a/MantidPlot/pymantidplot/__init__.py b/MantidPlot/pymantidplot/__init__.py index b1afecb677051243356dedec40f94f14e1026e9c..53c0133a6f5a1073cfa59f8fc12f3dfc4153df56 100644 --- a/MantidPlot/pymantidplot/__init__.py +++ b/MantidPlot/pymantidplot/__init__.py @@ -1224,3 +1224,59 @@ def createDetectorTable(source): return new_proxy(proxies.MDIWindow, _qti.app.mantidUI.createDetectorTable, workspace_names[0]) # ----------------------------------------------------------------------------- +def plotSubplots(source, indices, distribution = mantidqtpython.MantidQt.DistributionDefault, error_bars=False, window=None): + """Open a tiled plot. + + This plots one or more spectra, with X as the bin boundaries, + and Y as the counts in each bin. + + If one workspace, each spectrum gets its own tile. + Otherwise, each workspace gets its own tile. + + Args: + source: list of workspace names + indices: workspace index, or tuple or list of workspace indices to plot + distribution: whether or not to plot as a distribution + error_bars: bool, set to True to add error bars. + window: window used for plotting. If None a new one will be created + Returns: + A handle to window if one was specified, otherwise a handle to the created one. None in case of error. + """ + + workspace_names = getWorkspaceNames(source) + + # Deal with workspace groups that may contain various types: + # Only want to plot MatrixWorkspaces + to_plot = [] + for name in workspace_names: + if isinstance(mantid.api.mtd[name], mantid.api.MatrixWorkspace): + to_plot.append(name) + + __checkPlotWorkspaces(to_plot) + # check spectrum indices + index_list = __getWorkspaceIndices(indices) + if len(index_list) == 0: + raise ValueError("No spectrum indices given") + for idx in index_list: + if idx < 0: + raise ValueError("Wrong spectrum index (<0): %d" % idx) + for name in to_plot: + max_spec = workspace(name).getNumberHistograms() - 1 + for idx in index_list: + if idx > max_spec: + raise ValueError("Wrong spectrum index for workspace '%s': %d, which is bigger than the" + " number of spectra in this workspace - 1 (%d)" % (name, idx, max_spec)) + + # Unwrap the window object, if any specified + if window != None: + window = window._getHeldObject() + + graph = proxies.Graph(threadsafe_call(_qti.app.mantidUI.plotSubplots, + to_plot, index_list, distribution, error_bars, window)) + if graph._getHeldObject() == None: + raise RuntimeError("Cannot create graph, see log for details.") + else: + return graph + + +# ---------------------------------------------------------------------------------------------------- diff --git a/MantidPlot/src/ApplicationWindow.cpp b/MantidPlot/src/ApplicationWindow.cpp index bcefa621093fee511301dde50b0c29c15de2fbaf..f304aee942ea9ad8ee078e6fc76b863be69222bb 100644 --- a/MantidPlot/src/ApplicationWindow.cpp +++ b/MantidPlot/src/ApplicationWindow.cpp @@ -193,6 +193,7 @@ #include "MantidQtAPI/UserSubWindow.h" #include "MantidQtAPI/AlgorithmInputHistory.h" #include "MantidQtAPI/ManageUserDirectories.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtAPI/Message.h" #include "MantidQtMantidWidgets/CatalogHelper.h" @@ -13502,7 +13503,7 @@ void ApplicationWindow::disregardCol() { } void ApplicationWindow::showHomePage() { - QDesktopServices::openUrl(QUrl("http://www.mantidproject.org")); + MantidDesktopServices::openUrl(QUrl("http://www.mantidproject.org")); } void ApplicationWindow::showMantidConcepts() { HelpWindow::showConcept(this); } void ApplicationWindow::showalgorithmDescriptions() { @@ -13522,7 +13523,7 @@ void ApplicationWindow::showFirstTimeSetup() { void ApplicationWindow::showmantidplotHelp() { HelpWindow::showPage(this); } void ApplicationWindow::showBugTracker() { - QDesktopServices::openUrl(QUrl("http://forum.mantidproject.org/")); + MantidDesktopServices::openUrl(QUrl("http://forum.mantidproject.org/")); } /* diff --git a/MantidPlot/src/ApplicationWindow.h b/MantidPlot/src/ApplicationWindow.h index 1d12c1fa4580af3c7806fab0800e8152b334d4f3..6da6a2c7b36780cefa89c0513c431cd78f9da469 100644 --- a/MantidPlot/src/ApplicationWindow.h +++ b/MantidPlot/src/ApplicationWindow.h @@ -33,7 +33,6 @@ Description : QtiPlot's main window #define APPLICATION_H #include <QBuffer> -#include <QDesktopServices> #include <QFile> #include <QLocale> #include <QMainWindow> diff --git a/MantidPlot/src/FitDialog.cpp b/MantidPlot/src/FitDialog.cpp index 0bf4b0ba2cd4dd61ee68cd4b384fbb331a458bd3..9a1ba117e903e57557916d8d4ead3e7e1f3f9081 100644 --- a/MantidPlot/src/FitDialog.cpp +++ b/MantidPlot/src/FitDialog.cpp @@ -659,7 +659,7 @@ void FitDialog::saveUserFunction() { "Parent of FitDialog is not ApplicationWindow as expected."); } QString filter = tr("MantidPlot fit model") + " (*.fit);;"; - filter += tr("All files") + " (*.*)"; + filter += tr("All files") + " (*)"; QString fn = MantidQt::API::FileDialogHandler::getSaveFileName( app, tr("MantidPlot") + " - " + tr("Save Fit Model As"), app->fitModelsPath + "/" + name, filter); @@ -1420,7 +1420,7 @@ void FitDialog::saveInitialGuesses() { "Parent of FitDialog is not ApplicationWindow as expected."); } QString filter = tr("MantidPlot fit model") + " (*.fit);;"; - filter += tr("All files") + " (*.*)"; + filter += tr("All files") + " (*)"; QString fn = MantidQt::API::FileDialogHandler::getSaveFileName( app, tr("MantidPlot") + " - " + tr("Save Fit Model As"), app->fitModelsPath + "/" + d_current_fit->objectName(), filter); diff --git a/MantidPlot/src/FunctionDialog.cpp b/MantidPlot/src/FunctionDialog.cpp index 9829d9bc01160fa6d1a9219891beecbdf560205d..e97f5018b151f437a8c0feb3c0d121ee76668a21 100644 --- a/MantidPlot/src/FunctionDialog.cpp +++ b/MantidPlot/src/FunctionDialog.cpp @@ -296,7 +296,6 @@ void FunctionDialog::acceptFunction() { parser.DefineVar("x", &x); parser.SetExpr(formula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable x = end; parser.Eval(); } catch (mu::ParserError &e) { @@ -370,7 +369,6 @@ void FunctionDialog::acceptParametric() { parser.DefineVar((boxParameter->text()).toAscii().constData(), ¶meter); parser.SetExpr(xformula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable parameter = end; parser.Eval(); } catch (mu::ParserError &e) { @@ -385,7 +383,6 @@ void FunctionDialog::acceptParametric() { parser.DefineVar((boxParameter->text()).toAscii().constData(), ¶meter); parser.SetExpr(yformula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable parameter = end; parser.Eval(); } catch (mu::ParserError &e) { @@ -464,7 +461,6 @@ void FunctionDialog::acceptPolar() { ¶meter); parser.SetExpr(rformula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable parameter = end; parser.Eval(); } catch (mu::ParserError &e) { @@ -481,7 +477,6 @@ void FunctionDialog::acceptPolar() { ¶meter); parser.SetExpr(tformula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable parameter = end; parser.Eval(); } catch (mu::ParserError &e) { diff --git a/MantidPlot/src/Mantid/FirstTimeSetup.cpp b/MantidPlot/src/Mantid/FirstTimeSetup.cpp index 74aa9f638889cbcd8c5040b2e47555e25f970221..e14bbc80b54359108c95bb9ac4f798758835008d 100644 --- a/MantidPlot/src/Mantid/FirstTimeSetup.cpp +++ b/MantidPlot/src/Mantid/FirstTimeSetup.cpp @@ -2,13 +2,15 @@ #include "MantidKernel/ConfigService.h" #include "MantidKernel/MantidVersion.h" #include "MantidQtAPI/ManageUserDirectories.h" +#include "MantidQtAPI/MantidDesktopServices.h" -#include <QDesktopServices> #include <QMessageBox> #include <QPainter> #include <QSettings> #include <QUrl> +using MantidQt::API::MantidDesktopServices; + FirstTimeSetup::FirstTimeSetup(QWidget *parent) : QDialog(parent) { m_uiForm.setupUi(this); initLayout(); @@ -172,26 +174,26 @@ void FirstTimeSetup::openManageUserDirectories() { } void FirstTimeSetup::openReleaseNotes() { - QDesktopServices::openUrl(QUrl( + MantidDesktopServices::openUrl(QUrl( QString::fromStdString(Mantid::Kernel::MantidVersion::releaseNotes()))); } void FirstTimeSetup::openSampleDatasets() { - QDesktopServices::openUrl(QUrl("http://download.mantidproject.org")); + MantidDesktopServices::openUrl(QUrl("http://download.mantidproject.org")); } void FirstTimeSetup::openMantidIntroduction() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Mantid_Basic_Course")); } void FirstTimeSetup::openPythonIntroduction() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Introduction_To_Python")); } void FirstTimeSetup::openPythonInMantid() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Python_In_Mantid")); } void FirstTimeSetup::openExtendingMantid() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Extending_Mantid_With_Python")); } diff --git a/MantidPlot/src/Mantid/LoadDAEDlg.cpp b/MantidPlot/src/Mantid/LoadDAEDlg.cpp deleted file mode 100644 index 18e05d1da4b06980c797680ec528efda5bd67f98..0000000000000000000000000000000000000000 --- a/MantidPlot/src/Mantid/LoadDAEDlg.cpp +++ /dev/null @@ -1,145 +0,0 @@ - -#include <QValidator> -#include <QtGui> -#include <qfiledialog.h> - -#include "LoadDAEDlg.h" -#include "InputHistory.h" - -loadDAEDlg::loadDAEDlg(QWidget *parent) - : QDialog(parent), m_hostName(""), m_workspaceName(""), m_spectrum_min(""), - m_spectrum_max(""), m_spectrum_list(""), m_updateInterval(0) { - QGridLayout *paramsLayout = new QGridLayout; - QLabel *label = new QLabel(tr("DAE Name")); - lineHost = new QLineEdit; - label->setBuddy(lineHost); - paramsLayout->addWidget(label, 0, 0); - paramsLayout->addWidget(lineHost, 0, 1); - QString propValue = - InputHistory::Instance().algorithmProperty("LoadDAE", "DAEname"); - if (!propValue.isEmpty()) { - lineHost->setText(propValue); - } - - label = new QLabel(tr("Workspace Name")); - lineName = new QLineEdit; - label->setBuddy(lineName); - paramsLayout->addWidget(label, 1, 0); - paramsLayout->addWidget(lineName, 1, 1); - propValue = - InputHistory::Instance().algorithmProperty("LoadDAE", "OutputWorkspace"); - if (!propValue.isEmpty()) { - lineName->setText(propValue); - } - - QHBoxLayout *bottomRowLayout = new QHBoxLayout; - QPushButton *loadButton = new QPushButton(tr("Load")); - loadButton->setDefault(true); - QPushButton *cancelButton = new QPushButton(tr("Cancel")); - QPushButton *help = new QPushButton("?"); - help->setMaximumWidth(25); - connect(help, SIGNAL(clicked()), this, SLOT(helpClicked())); - - bottomRowLayout->addWidget(help); - bottomRowLayout->addStretch(); - bottomRowLayout->addWidget(cancelButton); - bottomRowLayout->addWidget(loadButton); - - connect(cancelButton, SIGNAL(clicked()), this, SLOT(close())); - connect(loadButton, SIGNAL(clicked()), this, SLOT(load())); - - QLabel *minSpLabel = new QLabel("Starting spectrum"); - minSpLineEdit = new QLineEdit; - propValue = - InputHistory::Instance().algorithmProperty("LoadRaw", "spectrum_min"); - if (!propValue.isEmpty()) { - minSpLineEdit->setText(propValue); - } - paramsLayout->addWidget(minSpLabel, 2, 0); - paramsLayout->addWidget(minSpLineEdit, 2, 1); - QLabel *maxSpLabel = new QLabel("Ending spectrum"); - maxSpLineEdit = new QLineEdit; - propValue = - InputHistory::Instance().algorithmProperty("LoadDAE", "spectrum_max"); - if (!propValue.isEmpty()) { - maxSpLineEdit->setText(propValue); - } - paramsLayout->addWidget(maxSpLabel, 3, 0); - paramsLayout->addWidget(maxSpLineEdit, 3, 1); - QLabel *listSpLabel = new QLabel("Spectrum List"); - listSpLineEdit = new QLineEdit; - propValue = - InputHistory::Instance().algorithmProperty("LoadDAE", "spectrum_list"); - if (!propValue.isEmpty()) { - listSpLineEdit->setText(propValue); - } - paramsLayout->addWidget(listSpLabel, 4, 0); - paramsLayout->addWidget(listSpLineEdit, 4, 1); - - QHBoxLayout *updateLayout = new QHBoxLayout; - updateCheck = new QCheckBox("Update every"); - updateLineEdit = new QLineEdit; - QIntValidator *ival = new QIntValidator(1, 99999999, updateLineEdit); - updateLineEdit->setValidator(ival); - propValue = - InputHistory::Instance().algorithmProperty("UpdateDAE", "update_rate"); - if (!propValue.isEmpty()) { - updateLineEdit->setText(propValue); - updateCheck->setCheckState(Qt::Checked); - } - label = new QLabel(" seconds"); - paramsLayout->addWidget(updateCheck, 5, 0); - updateLayout->addWidget(updateLineEdit); - updateLayout->addWidget(label); - paramsLayout->addLayout(updateLayout, 5, 1); - connect(updateCheck, SIGNAL(stateChanged(int)), this, - SLOT(changeUpdateState(int))); - connect(updateLineEdit, SIGNAL(textEdited(const QString &)), this, - SLOT(updateIntervalEntered(const QString &))); - - QVBoxLayout *mainLayout = new QVBoxLayout; - mainLayout->addLayout(paramsLayout); - mainLayout->addLayout(bottomRowLayout); - - setLayout(mainLayout); - setWindowTitle(tr("Load Workspace from DAE")); - setFixedHeight(sizeHint().height()); -} - -loadDAEDlg::~loadDAEDlg() {} - -void loadDAEDlg::load() { - if (!lineHost->text().isNull() && !lineHost->text().isEmpty() && - !lineName->text().isNull() && !lineName->text().isEmpty()) { - m_hostName = lineHost->text(); - m_workspaceName = lineName->text(); - m_spectrum_min = minSpLineEdit->text(); - m_spectrum_max = maxSpLineEdit->text(); - m_spectrum_list = listSpLineEdit->text(); - if (updateCheck->checkState() == Qt::Checked) - m_updateInterval = updateLineEdit->text().toInt(); - else { - m_updateInterval = 0; - InputHistory::Instance().updateAlgorithmProperty("UpdateDAE", - "update_rate", ""); - } - close(); - } -} - -void loadDAEDlg::changeUpdateState(int state) { - if (state == Qt::Checked && updateLineEdit->text().isEmpty()) - updateLineEdit->setText("10"); -} - -void loadDAEDlg::updateIntervalEntered(const QString &text) { - if (!text.isEmpty()) - updateCheck->setCheckState(Qt::Checked); - else - updateCheck->setCheckState(Qt::Unchecked); -} - -void loadDAEDlg::helpClicked() { - QDesktopServices::openUrl( - QUrl(QString("http://www.mantidproject.org/LoadDAE"))); -} diff --git a/MantidPlot/src/Mantid/LoadDAEDlg.h b/MantidPlot/src/Mantid/LoadDAEDlg.h deleted file mode 100644 index 7e6167f1bd9a9f997a59ae7009c6b2b7b6fe41ec..0000000000000000000000000000000000000000 --- a/MantidPlot/src/Mantid/LoadDAEDlg.h +++ /dev/null @@ -1,52 +0,0 @@ - -#ifndef LOADDAEDLG_H -#define LOADDAEDLG_H - -#include <QDialog> - -class QLabel; -class QLineEdit; -class QPushButton; -class QString; -class QVBoxLayout; -class QCheckBox; - -class loadDAEDlg : public QDialog { - Q_OBJECT - -public: - explicit loadDAEDlg(QWidget *parent = 0); - ~loadDAEDlg() override; - - const QString &getHostName() { return m_hostName; } - const QString &getWorkspaceName() { return m_workspaceName; } - const QString &getSpectrumMin() { return m_spectrum_min; } - const QString &getSpectrumMax() { return m_spectrum_max; } - const QString &getSpectrumList() { return m_spectrum_list; } - int updateInterval() { return m_updateInterval; } - -protected: -private slots: - void load(); - void changeUpdateState(int); - void updateIntervalEntered(const QString &text); - void helpClicked(); - -private: - QString m_hostName; - QString m_workspaceName; - QString m_spectrum_min; - QString m_spectrum_max; - QString m_spectrum_list; - int m_updateInterval; - - QLineEdit *lineHost; - QLineEdit *lineName; - QLineEdit *minSpLineEdit; - QLineEdit *maxSpLineEdit; - QLineEdit *listSpLineEdit; - QCheckBox *updateCheck; - QLineEdit *updateLineEdit; -}; - -#endif /* LOADDAEDLG_H */ diff --git a/MantidPlot/src/Mantid/ManageCustomMenus.cpp b/MantidPlot/src/Mantid/ManageCustomMenus.cpp index bb85d5de70ed9d83e89be44711d177a60b8bf625..bf18c860912d999a62b1ae36f91e5d420b565a77 100644 --- a/MantidPlot/src/Mantid/ManageCustomMenus.cpp +++ b/MantidPlot/src/Mantid/ManageCustomMenus.cpp @@ -2,9 +2,13 @@ #include "../ApplicationWindow.h" #include "MantidQtAPI/InterfaceManager.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidKernel/ConfigService.h" #include <QtGui> + +using MantidQt::API::MantidDesktopServices; + /** * Constructor for object. Performs initial setup and calls subsequent setup * functions. @@ -224,5 +228,5 @@ void ManageCustomMenus::addMenuClicked() { */ void ManageCustomMenus::helpClicked() { QUrl helpUrl("http://www.mantidproject.org/ManageCustomMenus"); - QDesktopServices::openUrl(helpUrl); + MantidDesktopServices::openUrl(helpUrl); } diff --git a/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp b/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp index 01b04baab20b8cf7c2e56e955b865229e6b45574..6071a99420648c6343ad860299e4ce8efdb87924 100644 --- a/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp +++ b/MantidPlot/src/Mantid/ManageInterfaceCategories.cpp @@ -1,10 +1,13 @@ #include "MantidKernel/ConfigService.h" #include "ManageInterfaceCategories.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "../ApplicationWindow.h" #include <QtGui> #include <QtAlgorithms> +using MantidQt::API::MantidDesktopServices; + ///////////////////////////////////////////////////// // InterfaceCategoryModel ///////////////////////////////////////////////////// @@ -175,5 +178,5 @@ void ManageInterfaceCategories::initLayout() { */ void ManageInterfaceCategories::helpClicked() { QUrl helpUrl("http://www.mantidproject.org/ManageInterfaceCategories"); - QDesktopServices::openUrl(helpUrl); + MantidDesktopServices::openUrl(helpUrl); } diff --git a/MantidPlot/src/Mantid/MantidUI.cpp b/MantidPlot/src/Mantid/MantidUI.cpp index 700b7c31740ee6ae737c6464afeba8b47d30a80e..1e8ba6c029392a78626faefa303a80f309267d94 100644 --- a/MantidPlot/src/Mantid/MantidUI.cpp +++ b/MantidPlot/src/Mantid/MantidUI.cpp @@ -3410,11 +3410,12 @@ MultiLayer *MantidUI::plotSelectedColumns(const MantidMatrix *const m, * @param toPlot :: Map of form ws -> [spectra_list] * @param distr :: if true, workspace plot as distribution (y data/bin width) * @param errs :: if true, plot the errors on the graph + * @param plotWindow :: Window to plot in - if null, create a new one * @return created MultiLayer, or null on failure */ MultiLayer *MantidUI::plotSubplots(const QMultiMap<QString, set<int>> &toPlot, - MantidQt::DistributionFlag distr, - bool errs) { + MantidQt::DistributionFlag distr, bool errs, + MultiLayer *plotWindow) { // Check if nothing to plot if (toPlot.size() == 0) return nullptr; @@ -3456,8 +3457,16 @@ MultiLayer *MantidUI::plotSubplots(const QMultiMap<QString, set<int>> &toPlot, // Set the wait cursor while we are plotting ScopedOverrideCursor waitCursor; - // Create window with correct number of layers - auto *multi = appWindow()->multilayerPlot(plotTitle, nSubplots, 1, nSubplots); + // Create window with correct number of layers, or use existing + MultiLayer *multi; + if (plotWindow) { + multi = plotWindow; + multi->setLayersNumber(0); // remove any existing plots + multi->setLayersNumber(nSubplots); + } else { + multi = appWindow()->multilayerPlot(plotTitle, nSubplots, 1, nSubplots); + } + assert(multi); multi->setCloseOnEmpty(true); multi->arrangeLayers(true, true); @@ -3555,11 +3564,12 @@ void MantidUI::plotLayerOfMultilayer(MultiLayer *multi, const bool plotErrors, * @param toPlot :: A list of workspace/spectra to be shown in the graph * @param distr :: if true, workspace plot as distribution (y data/bin width) * @param errs :: if true, plot the errors on the graph + * @param plotWindow :: Window to plot in - if null, create a new one * @return created MultiLayer, or null on failure */ MultiLayer *MantidUI::plotSubplots(const QMultiMap<QString, int> &toPlot, - MantidQt::DistributionFlag distr, - bool errs) { + MantidQt::DistributionFlag distr, bool errs, + MultiLayer *plotWindow) { // Convert the input map into a map of workspace->spectra QMultiMap<QString, std::set<int>> spectraByWorkspace; @@ -3573,7 +3583,43 @@ MultiLayer *MantidUI::plotSubplots(const QMultiMap<QString, int> &toPlot, } // Pass over to the overloaded method - return plotSubplots(spectraByWorkspace, distr, errs); + return plotSubplots(spectraByWorkspace, distr, errs, plotWindow); +} + +/** + * Plot a "tiled" plot (with subplots). + * Ask user for confirmation if lots of plots are chosen. + * If just one workspace, put each spectrum in its own subplot + * If multiple workspaces, each ws gets its own subplot + * + * This overload plots the same spectra for each workspace. + * + * @param wsNames :: A list of workspace names to be shown in the graph + * @param indexList :: list of workspace indices + * @param distr :: if true, workspace plot as distribution (y data/bin width) + * @param errs :: if true, plot the errors on the graph + * @param plotWindow :: Window to plot in - if null, create a new one + * @return created MultiLayer, or null on failure + */ +MultiLayer *MantidUI::plotSubplots(const QStringList &wsNames, + const QList<int> &indexList, + MantidQt::DistributionFlag distr, bool errs, + MultiLayer *plotWindow) { + // convert input into map of workspace->spectra + QMultiMap<QString, std::set<int>> spectraByWorkspace; + const std::set<int> wsIndices = [&indexList]() { + std::set<int> indexSet; + for (const auto &index : indexList) { + indexSet.insert(index); + } + return indexSet; + }(); + for (const auto &wsName : wsNames) { + spectraByWorkspace.insert(wsName, wsIndices); + } + + // Pass to the overloaded method + return plotSubplots(spectraByWorkspace, distr, errs, plotWindow); } Table *MantidUI::createTableFromBins( diff --git a/MantidPlot/src/Mantid/MantidUI.h b/MantidPlot/src/Mantid/MantidUI.h index bfbbf44ee5d1e438400f06a69c19670e4c555aa9..c7f642c7dc85059fc3b87a70525c2cc3ca4cf051 100644 --- a/MantidPlot/src/Mantid/MantidUI.h +++ b/MantidPlot/src/Mantid/MantidUI.h @@ -223,12 +223,17 @@ public: MultiLayer * plotSubplots(const QMultiMap<QString, std::set<int>> &toPlot, MantidQt::DistributionFlag distr = MantidQt::DistributionDefault, - bool errs = false); + bool errs = false, MultiLayer *plotWindow = nullptr); MultiLayer * plotSubplots(const QMultiMap<QString, int> &toPlot, MantidQt::DistributionFlag distr = MantidQt::DistributionDefault, - bool errs = false); + bool errs = false, MultiLayer *plotWindow = nullptr); + + MultiLayer * + plotSubplots(const QStringList &wsNames, const QList<int> &indexList, + MantidQt::DistributionFlag distr = MantidQt::DistributionDefault, + bool errs = false, MultiLayer *plotWindow = nullptr); public slots: // Create a 1d graph form specified MatrixWorkspace and index diff --git a/MantidPlot/src/PythonScripting.cpp b/MantidPlot/src/PythonScripting.cpp index abc435c54e6a38b9ec4b35633837334cbf57675e..073f2695c1aa3e62aed3f74c96a681ec7552792e 100644 --- a/MantidPlot/src/PythonScripting.cpp +++ b/MantidPlot/src/PythonScripting.cpp @@ -119,10 +119,10 @@ void PythonScripting::redirectStdOut(bool on) { setQObject(this, "stdout", m_sys); setQObject(this, "stderr", m_sys); } else { - PyDict_SetItemString(m_sys, "stdout", - PyDict_GetItemString(m_sys, "__stdout__")); - PyDict_SetItemString(m_sys, "stderr", - PyDict_GetItemString(m_sys, "__stderr__")); + PyDict_SetItem(m_sys, FROM_CSTRING("stdout"), + PyDict_GetItemString(m_sys, "__stdout__")); + PyDict_SetItem(m_sys, FROM_CSTRING("stderr"), + PyDict_GetItemString(m_sys, "__stderr__")); } } diff --git a/MantidPlot/src/SurfaceDialog.cpp b/MantidPlot/src/SurfaceDialog.cpp index 90a4a081546843f74aed347b8b2dc6d0cc2a1172..b5e5d03187bea1688ccf4a818fd65052f1846139 100644 --- a/MantidPlot/src/SurfaceDialog.cpp +++ b/MantidPlot/src/SurfaceDialog.cpp @@ -506,9 +506,7 @@ void SurfaceDialog::acceptFunction() { parser.SetExpr(formula.toAscii().constData()); parser.Eval(); - // cppcheck-suppress unreadVariable x = toX; - // cppcheck-suppress unreadVariable y = toY; parser.Eval(); } catch (mu::ParserError &e) { diff --git a/MantidPlot/src/fit_gsl.cpp b/MantidPlot/src/fit_gsl.cpp index 9366aef7b0ac886daf64dcc88fb156c7ec070aad..4040b71619db0bedb4398c5aaf6fa54e198c4984 100644 --- a/MantidPlot/src/fit_gsl.cpp +++ b/MantidPlot/src/fit_gsl.cpp @@ -502,7 +502,6 @@ int user_f(const gsl_vector *x, void *params, gsl_vector *f) { } parser.SetExpr(function); for (int j = 0; j < (int)n; j++) { - // cppcheck-suppress unreadVariable xvar = X[j]; gsl_vector_set(f, j, (parser.Eval() - Y[j]) / sigma[j]); } @@ -535,7 +534,6 @@ double user_d(const gsl_vector *x, void *params) { } parser.SetExpr(function); for (int j = 0; j < (int)n; j++) { - // cppcheck-suppress unreadVariable xvar = X[j]; double t = (parser.Eval() - Y[j]) / sigma[j]; val += t * t; @@ -567,7 +565,6 @@ int user_df(const gsl_vector *x, void *params, gsl_matrix *J) { } parser.SetExpr(function); for (int i = 0; i < (int)n; i++) { - // cppcheck-suppress unreadVariable xvar = X[i]; for (int j = 0; j < (int)p; j++) gsl_matrix_set(J, i, j, diff --git a/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp b/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp index e24ae0bbc84160bbad12563e279da25f9dcbf0cc..5e5b86ce5fbc487fff3e1bf6b03c7075b1a05c53 100644 --- a/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp +++ b/MantidPlot/src/lib/src/ExtensibleFileDialog.cpp @@ -31,7 +31,6 @@ #include "ExtensibleFileDialog.h" #include <QGridLayout> -#include <QDesktopServices> #include <QUrl> #include <QComboBox> diff --git a/MantidPlot/src/qti.sip b/MantidPlot/src/qti.sip index 5d42359e1325d9cdf5d543ddb12affa66ad5ddda..97803375bfa16827ea23d6559c2dfe331a09766f 100644 --- a/MantidPlot/src/qti.sip +++ b/MantidPlot/src/qti.sip @@ -713,7 +713,7 @@ public: bool insertCurve(Table*, const QString&, int style = 1, int startRow = 0, int endRow = -1); bool insertCurve(Table*, const QString&, const QString&, int style = 1, int startRow = 0, int endRow = -1); - bool insertCurve(QString, int, bool=false, Graph::CurveType style = Graph::Unspecified); + bool insertCurve(QString, int, bool=false, Graph::CurveType style = Graph::Unspecified, bool=false); void insertCurve(Graph*, int); bool addCurves(Table*, SIP_PYTUPLE, int=0, double=1, int=3, int=0, int=-1); %MethodCode @@ -915,6 +915,7 @@ public: Graph* layer(int num); Graph* addLayer(int = 0, int = 0, int = 0, int = 0); void insertCurve(MultiLayer* ml, int i); + void setCommonAxisScales(); void setCols(int); void setRows(int); void setName(const QString&); @@ -1486,6 +1487,10 @@ public: MultiLayer* plotMDList(const QList<QString>& wsNames, const int plotAxis, const Mantid::API::MDNormalization normalization, const bool showErrors, MultiLayer* window = NULL, bool clearWindow = false); + + MultiLayer *plotSubplots(const QList<QString>& wsNames, const QList<int> &indexList, + MantidQt::DistributionFlag distr = MantidQt::DistributionDefault, + bool errs = false, MultiLayer *plotWindow = NULL); MultiLayer* mergePlots(MultiLayer*, MultiLayer*); void convertToWaterfall(MultiLayer*); diff --git a/MantidPlot/test/MantidPlotPVPythonTest.py b/MantidPlot/test/MantidPlotPVPythonTest.py index 7d1f512ccbaddba374029c5834d27b8e76dfda2c..9d2ed809a18b31375992aea784dabecc0fe1e121 100644 --- a/MantidPlot/test/MantidPlotPVPythonTest.py +++ b/MantidPlot/test/MantidPlotPVPythonTest.py @@ -4,6 +4,7 @@ Test one can import paraview.simple in MantidPlot import mantidplottests from mantidplottests import * + class MantidPlotPVPythonTest(unittest.TestCase): def setUp(self): @@ -14,8 +15,7 @@ class MantidPlotPVPythonTest(unittest.TestCase): def test_PVPython(self): from paraview.simple import * - self.assertEquals(str(GetParaViewVersion()),'5.1') + self.assertEqual(GetParaViewVersion().major, 5) # Run the unit tests mantidplottests.runTests(MantidPlotPVPythonTest) - diff --git a/MantidQt/API/CMakeLists.txt b/MantidQt/API/CMakeLists.txt index 82d75b19f9af3f08984dfb84e9c4565d39549aaa..f05390cf2486ec1d319ec1a92a87cf5a7eaa1917 100644 --- a/MantidQt/API/CMakeLists.txt +++ b/MantidQt/API/CMakeLists.txt @@ -13,6 +13,7 @@ src/ListPropertyWidget.cpp src/ManageUserDirectories.cpp src/MantidColorMap.cpp + src/MantidDesktopServices.cpp src/MantidDialog.cpp src/MantidHelpInterface.cpp src/MantidQwtIMDWorkspaceData.cpp @@ -93,6 +94,7 @@ set ( INC_FILES inc/MantidQtAPI/InterfaceManager.h inc/MantidQtAPI/IProjectSerialisable.h inc/MantidQtAPI/MantidColorMap.h + inc/MantidQtAPI/MantidDesktopServices.h inc/MantidQtAPI/MantidQwtIMDWorkspaceData.h inc/MantidQtAPI/MantidQwtWorkspaceData.h inc/MantidQtAPI/MantidAlgorithmMetatype.h diff --git a/MantidQt/API/inc/MantidQtAPI/MantidDesktopServices.h b/MantidQt/API/inc/MantidQtAPI/MantidDesktopServices.h new file mode 100644 index 0000000000000000000000000000000000000000..ae1d95cb8b7d7eddbe4ea5cfc36f42f389debddd --- /dev/null +++ b/MantidQt/API/inc/MantidQtAPI/MantidDesktopServices.h @@ -0,0 +1,49 @@ +#ifndef MANTIDQT_API_MANTIDDESKTOPSERVICES_H_ +#define MANTIDQT_API_MANTIDDESKTOPSERVICES_H_ + +#include "DllOption.h" +#include <QDesktopServices> + +namespace MantidQt { +namespace API { + +/** + This class provides a wrapper around QDesktopServices to fix a bug in opening + URLs in firefox when tcmalloc is in the LD_PRELOAD environment variable on + Linux. All other methods are simply passed through to QDesktopServices. + + Copyright © 2016 ISIS Rutherford Appleton Laboratory, NScD Oak Ridge + National Laboratory & European Spallation Source + + 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 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/>. + + File change history is stored at: <https://github.com/mantidproject/mantid> + Code Documentation is available at: <http://doxygen.mantidproject.org> + */ +class EXPORT_OPT_MANTIDQT_API MantidDesktopServices { +public: + static bool openUrl(const QUrl &url); + static void setUrlHandler(const QString &scheme, QObject *receiver, + const char *method); + static void unsetUrlHandler(const QString &scheme); + + static QString storageLocation(QDesktopServices::StandardLocation type); + static QString displayName(QDesktopServices::StandardLocation type); +}; +} +} + +#endif // MANTIDQT_API_MANTIDDESKTOPSERVICES_H_ diff --git a/MantidQt/API/src/FilePropertyWidget.cpp b/MantidQt/API/src/FilePropertyWidget.cpp index 18de9101d347a719a5ceb16d0efaeb544bf76721..4e84296181e106943e33dfdbf808ae1f526bcc92 100644 --- a/MantidQt/API/src/FilePropertyWidget.cpp +++ b/MantidQt/API/src/FilePropertyWidget.cpp @@ -105,7 +105,7 @@ QString getFileDialogFilter(const std::vector<std::string> &exts, } filter = filter.trimmed(); } - filter.append("All Files (*.*)"); + filter.append("All Files (*)"); return filter; } diff --git a/MantidQt/API/src/HelpWindow.cpp b/MantidQt/API/src/HelpWindow.cpp index ea9fba7b53b88f95994b303d4a043ca54df0fe62..6cc16cbad48dcdaee825955d5a97aa381b131546 100644 --- a/MantidQt/API/src/HelpWindow.cpp +++ b/MantidQt/API/src/HelpWindow.cpp @@ -6,7 +6,6 @@ #include "MantidKernel/Logger.h" #include <boost/lexical_cast.hpp> -#include <QDesktopServices> #include <QUrl> #include <QWidget> diff --git a/MantidQt/API/src/ManageUserDirectories.cpp b/MantidQt/API/src/ManageUserDirectories.cpp index abd2830acdf14bd257abd574f2fb168e9a4b88fd..5c40d306a9cdd0099e4fb10ca9e646505e80b95c 100644 --- a/MantidQt/API/src/ManageUserDirectories.cpp +++ b/MantidQt/API/src/ManageUserDirectories.cpp @@ -1,4 +1,5 @@ #include "MantidQtAPI/ManageUserDirectories.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidKernel/ConfigService.h" #include <QtGui> #include <QDir> @@ -131,7 +132,7 @@ QListWidget *ManageUserDirectories::listWidget() { // SLOTS void ManageUserDirectories::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/ManageUserDirectories")); } void ManageUserDirectories::cancelClicked() { this->close(); } diff --git a/MantidQt/API/src/MantidDesktopServices.cpp b/MantidQt/API/src/MantidDesktopServices.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0eeab51edc386f1163d67642f4b102243e2538d9 --- /dev/null +++ b/MantidQt/API/src/MantidDesktopServices.cpp @@ -0,0 +1,97 @@ +#include "MantidQtAPI/MantidDesktopServices.h" + +#include <QDesktopServices> + +#ifdef __linux__ +#include <QProcessEnvironment> +#include <cstdlib> + +namespace { +// String name of LD_PRELOAD environment variable +constexpr const char *LDPRELOAD_ENV = "LD_PRELOAD"; +} +#endif + +#include <iostream> + +namespace MantidQt { +namespace API { + +/** + * Opens a url in the appropriate web browser. On Linux systems if LD_PRELOAD is + * defined as an environment variable then it is removed for the duration of the + * call + * to the web browser. This is to avoid known issues with LD_PRELOAD libraries + * and some + * web browsers, e.g. firefox. On all other systems the method simply passes + * through to + * QDesktopServies + * @param url Address to be opened + */ +bool MantidDesktopServices::openUrl(const QUrl &url) { +#ifndef __linux__ + return QDesktopServices::openUrl(url); +#else + // Remove LD_PRELOAD if present + auto systemEnv = QProcessEnvironment::systemEnvironment(); + auto ldpreload = systemEnv.value(LDPRELOAD_ENV, QString()); + if (!ldpreload.isEmpty()) { + unsetenv(LDPRELOAD_ENV); + } + auto status = QDesktopServices::openUrl(url); + if (!ldpreload.isEmpty()) { + setenv(LDPRELOAD_ENV, ldpreload.toLatin1().constData(), 1 /* overwrite*/); + } + return status; +#endif +} + +/** + * Pass through method to MantidDesktopServices::setUrlHandler. See Qt + * documentation + * for + * further details. + * @param scheme Name of scheme to handle + * @param receiver Handler object + * @param method Method called on the receiver object + */ +void MantidDesktopServices::setUrlHandler(const QString &scheme, + QObject *receiver, + const char *method) { + QDesktopServices::setUrlHandler(scheme, receiver, method); +} + +/** + * Pass through method to MantidDesktopServices::unsetUrlHandler. See Qt + * documentation for + * further details. + * @param scheme Name of scheme to drop + */ +void MantidDesktopServices::unsetUrlHandler(const QString &scheme) { + QDesktopServices::unsetUrlHandler(scheme); +} + +/** + * Pass through method to MantidDesktopServices::storageLocation. See Qt + * documentation for + * further details. + * @param type File type + */ +QString MantidDesktopServices::storageLocation( + QDesktopServices::StandardLocation type) { + return QDesktopServices::storageLocation(type); +} + +/** + * Pass through method to MantidDesktopServices::displayName. See Qt + * documentation + * for + * further details. + * @param type Location type + */ +QString +MantidDesktopServices::displayName(QDesktopServices::StandardLocation type) { + return QDesktopServices::displayName(type); +} +} +} diff --git a/MantidQt/API/src/ScriptRepositoryView.cpp b/MantidQt/API/src/ScriptRepositoryView.cpp index c0c2650bc755d0e69735968beeccf4c3d31efecc..6226c6d237287b88a4a85c11a6df7256dc7646ab 100644 --- a/MantidQt/API/src/ScriptRepositoryView.cpp +++ b/MantidQt/API/src/ScriptRepositoryView.cpp @@ -1,10 +1,12 @@ #include "MantidQtAPI/ScriptRepositoryView.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtAPI/RepoModel.h" -#include <QDebug> #include "MantidAPI/ScriptRepository.h" #include "MantidAPI/ScriptRepositoryFactory.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/Logger.h" + +#include <QDebug> #include <QMessageBox> #include <QTime> #include <QCoreApplication> @@ -13,7 +15,7 @@ #include <QPushButton> #include <QFileDialog> #include <QPainter> -#include <QDesktopServices> + namespace MantidQt { namespace API { namespace { @@ -284,7 +286,7 @@ void ScriptRepositoryView::currentChanged(const QModelIndex &in) { /** Open the ScriptRepository Page on Web Browser*/ void ScriptRepositoryView::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/ScriptRepository")); } @@ -618,7 +620,7 @@ void ScriptRepositoryView::openFolderLink(QString link) { return; } - const bool openSuccessful = QDesktopServices::openUrl(url); + const bool openSuccessful = MantidDesktopServices::openUrl(url); if (!openSuccessful) g_log.error() << error_msg << "Could not find directory.\n"; } diff --git a/MantidQt/API/src/UserSubWindow.cpp b/MantidQt/API/src/UserSubWindow.cpp index 44d28e6a3e93fde67047c3816028f28f4c472090..33b432775f22cba222e244e8103e813d19cc006f 100644 --- a/MantidQt/API/src/UserSubWindow.cpp +++ b/MantidQt/API/src/UserSubWindow.cpp @@ -125,7 +125,7 @@ QString UserSubWindow::openFileDialog(const bool save, } filter = filter.trimmed(); } - filter.append(";;All Files (*.*)"); + filter.append(";;All Files (*)"); QString filename; if (save) { diff --git a/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp b/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp index 982808cb9d92f21b20d52b185f6fe49d9f6288b5..4af8ab2f443508bdf32fd7a968a15b1ab7308ce8 100644 --- a/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp +++ b/MantidQt/CustomDialogs/src/ConvertTableToMatrixWorkspaceDialog.cpp @@ -7,7 +7,6 @@ #include <QCheckBox> #include <QComboBox> #include <QUrl> -#include <QDesktopServices> #include <QDesktopWidget> #include <QFileInfo> diff --git a/MantidQt/CustomDialogs/src/FitDialog.cpp b/MantidQt/CustomDialogs/src/FitDialog.cpp index c7380605176331253d72ab0c2db555a22f34e18a..044fcc1e98b64ab332bae8145e532e67fae48076 100644 --- a/MantidQt/CustomDialogs/src/FitDialog.cpp +++ b/MantidQt/CustomDialogs/src/FitDialog.cpp @@ -8,7 +8,6 @@ #include <QComboBox> #include <QSpinBox> #include <QUrl> -#include <QDesktopServices> #include <QDesktopWidget> #include <QFileInfo> diff --git a/MantidQt/CustomDialogs/src/LoadDialog.cpp b/MantidQt/CustomDialogs/src/LoadDialog.cpp index ab6bf93645314511c8c71476f99e5c46de05bebb..82cc328ea83eba5d6579b4395bd5f5a8ad0c7d27 100644 --- a/MantidQt/CustomDialogs/src/LoadDialog.cpp +++ b/MantidQt/CustomDialogs/src/LoadDialog.cpp @@ -8,7 +8,6 @@ #include <QCheckBox> #include <QComboBox> #include <QUrl> -#include <QDesktopServices> #include <QDesktopWidget> #include <QFileInfo> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui index cd854f35925fe1d947bf1e3edcbc10799af7fdea..0d410a37b4fc4bff22824577a8718d9733ec8236 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/AbsorptionCorrections.ui @@ -462,10 +462,7 @@ </property> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="spSampleNumberDensity"> - <property name="suffix"> - <string> A^-3</string> - </property> + <widget class="QDoubleSpinBox" name="spSampleDensity"> <property name="decimals"> <number>5</number> </property> @@ -484,13 +481,6 @@ </property> </widget> </item> - <item row="0" column="0"> - <widget class="QLabel" name="lbSampleNumberDensity"> - <property name="text"> - <string>Number Density: </string> - </property> - </widget> - </item> <item row="0" column="3"> <widget class="QLineEdit" name="leSampleChemicalFormula"> <property name="sizePolicy"> @@ -501,6 +491,20 @@ </property> </widget> </item> + <item row="0" column="0"> + <widget class="QComboBox" name="cbSampleDensity"> + <item> + <property name="text"> + <string>Mass Density</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density</string> + </property> + </item> + </widget> + </item> </layout> </widget> </item> @@ -520,20 +524,13 @@ </property> </widget> </item> - <item row="4" column="0"> - <widget class="QLabel" name="lbCanNumberDensity"> - <property name="text"> - <string>Number Density:</string> - </property> - </widget> - </item> <item row="4" column="1"> - <widget class="QDoubleSpinBox" name="spCanNumberDensity"> + <widget class="QDoubleSpinBox" name="spCanDensity"> <property name="enabled"> <bool>false</bool> </property> <property name="suffix"> - <string> A^-3</string> + <string/> </property> <property name="decimals"> <number>5</number> @@ -618,6 +615,20 @@ </property> </widget> </item> + <item row="4" column="0"> + <widget class="QComboBox" name="cbCanDensity"> + <item> + <property name="text"> + <string>Mass Density</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density</string> + </property> + </item> + </widget> + </item> </layout> </widget> </item> @@ -715,14 +726,14 @@ <tabstop>spCylSampleRadius</tabstop> <tabstop>spCylCanRadius</tabstop> <tabstop>spCylEvents</tabstop> - <tabstop>spSampleNumberDensity</tabstop> + <tabstop>spSampleDensity</tabstop> <tabstop>leSampleChemicalFormula</tabstop> <tabstop>ckUseCanCorrections</tabstop> <tabstop>ckScaleCan</tabstop> <tabstop>spCanScale</tabstop> <tabstop>ckShiftCan</tabstop> <tabstop>spCanShift</tabstop> - <tabstop>spCanNumberDensity</tabstop> + <tabstop>spCanDensity</tabstop> <tabstop>leCanChemicalFormula</tabstop> <tabstop>ckKeepFactors</tabstop> <tabstop>pbPlot</tabstop> @@ -829,7 +840,7 @@ <connection> <sender>ckUseCanCorrections</sender> <signal>toggled(bool)</signal> - <receiver>spCanNumberDensity</receiver> + <receiver>spCanDensity</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalculatePaalmanPings.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalculatePaalmanPings.ui index 281d2266e9c2abadde81072ba32d6d077bf3b7cd..8984dec53a01e2f1c5e49ba64da0016232b4f189 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalculatePaalmanPings.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/CalculatePaalmanPings.ui @@ -488,7 +488,7 @@ </property> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="spSampleNumberDensity"> + <widget class="QDoubleSpinBox" name="spSampleDensity"> <property name="maximum"> <double>9999.989999999999782</double> </property> @@ -498,10 +498,17 @@ </widget> </item> <item row="0" column="0"> - <widget class="QLabel" name="lbSampleNumberDensity"> - <property name="text"> - <string>Number Density:</string> - </property> + <widget class="QComboBox" name="cbSampleDensity"> + <item> + <property name="text"> + <string>Mass Density</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density</string> + </property> + </item> </widget> </item> <item row="0" column="2"> @@ -556,10 +563,17 @@ </property> <layout class="QGridLayout" name="gridLayout_3"> <item row="0" column="0"> - <widget class="QLabel" name="lbCanNumberDensity"> - <property name="text"> - <string>Number Density:</string> - </property> + <widget class="QComboBox" name="cbCanDensity"> + <item> + <property name="text"> + <string>Mass Density</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density</string> + </property> + </item> </widget> </item> <item row="0" column="3"> @@ -573,7 +587,7 @@ </widget> </item> <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="spCanNumberDensity"> + <widget class="QDoubleSpinBox" name="spCanDensity"> <property name="maximum"> <double>9999.989999999999782</double> </property> @@ -709,9 +723,7 @@ <tabstop>spAnnBeamHeight</tabstop> <tabstop>spAnnBeamWidth</tabstop> <tabstop>spAnnStepSize</tabstop> - <tabstop>spSampleNumberDensity</tabstop> <tabstop>leSampleChemicalFormula</tabstop> - <tabstop>spCanNumberDensity</tabstop> <tabstop>leCanChemicalFormula</tabstop> <tabstop>cbPlotOutput</tabstop> <tabstop>pbSave</tabstop> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui index a736badc40e212cac75582ea57aab842d8d6dc58..0ead455b0cb85e44c6734292992991639f619a3a 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.ui @@ -67,13 +67,6 @@ </property> </widget> </item> - <item row="1" column="0"> - <widget class="QLabel" name="lbNumberDensity"> - <property name="text"> - <string>Number Density</string> - </property> - </widget> - </item> <item row="2" column="0"> <widget class="QLabel" name="lbThickness"> <property name="text"> @@ -101,9 +94,9 @@ </widget> </item> <item row="1" column="1"> - <widget class="QDoubleSpinBox" name="spNumberDensity"> + <widget class="QDoubleSpinBox" name="spDensity"> <property name="suffix"> - <string> atoms/Ã…^3</string> + <string/> </property> <property name="decimals"> <number>5</number> @@ -136,6 +129,20 @@ </item> </layout> </item> + <item row="1" column="0"> + <widget class="QComboBox" name="cbDensityType"> + <item> + <property name="text"> + <string>Mass Density (g/cm^3)</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density (atoms/Ã…^3)</string> + </property> + </item> + </widget> + </item> </layout> </widget> </item> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui index 7fdb9efac28f61005e227d841369c5d04cf43f9b..327a289f30771fb0ebd90250b13622d062e9817b 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/SampleTransmission.ui @@ -160,10 +160,10 @@ <string>Sample Details</string> </property> <layout class="QGridLayout" name="loSampleDetails"> - <item row="1" column="0"> - <widget class="QLabel" name="lbNumberDensity"> + <item row="2" column="2"> + <widget class="QLabel" name="valThickness"> <property name="text"> - <string>Number Density</string> + <string/> </property> </widget> </item> @@ -174,17 +174,10 @@ </property> </widget> </item> - <item row="0" column="0"> - <widget class="QLabel" name="lbChemicalFormula"> - <property name="text"> - <string>Chemical Formula</string> - </property> - </widget> - </item> <item row="1" column="1"> - <widget class="QDoubleSpinBox" name="spNumberDensity"> + <widget class="QDoubleSpinBox" name="spDensity"> <property name="suffix"> - <string notr="true"> atoms/ų</string> + <string notr="true"/> </property> <property name="decimals"> <number>5</number> @@ -197,6 +190,13 @@ </property> </widget> </item> + <item row="1" column="2"> + <widget class="QLabel" name="valDensity"> + <property name="text"> + <string/> + </property> + </widget> + </item> <item row="2" column="1"> <widget class="QDoubleSpinBox" name="spThickness"> <property name="suffix"> @@ -213,25 +213,32 @@ </property> </widget> </item> - <item row="2" column="2"> - <widget class="QLabel" name="valThickness"> + <item row="0" column="2"> + <widget class="QLabel" name="valChemicalFormula"> <property name="text"> <string/> </property> </widget> </item> - <item row="1" column="2"> - <widget class="QLabel" name="valNumberDensity"> + <item row="0" column="0"> + <widget class="QLabel" name="lbChemicalFormula"> <property name="text"> - <string/> + <string>Chemical Formula</string> </property> </widget> </item> - <item row="0" column="2"> - <widget class="QLabel" name="valChemicalFormula"> - <property name="text"> - <string/> - </property> + <item row="1" column="0"> + <widget class="QComboBox" name="cbDensity"> + <item> + <property name="text"> + <string>Mass Density</string> + </property> + </item> + <item> + <property name="text"> + <string>Number Density</string> + </property> + </item> </widget> </item> <item row="0" column="1"> @@ -356,7 +363,7 @@ <tabstop>spSingleHigh</tabstop> <tabstop>leMultiple</tabstop> <tabstop>leChemicalFormula</tabstop> - <tabstop>spNumberDensity</tabstop> + <tabstop>spDensity</tabstop> <tabstop>spThickness</tabstop> <tabstop>twResults</tabstop> <tabstop>pbCalculate</tabstop> diff --git a/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp b/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp index d3fb62bd429a052cd2f19d8b37e88b3dfe45906b..a5484db349730ef1b371991e94f1bab9e84ad466 100644 --- a/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp +++ b/MantidQt/CustomInterfaces/src/DirectConvertToEnergy.cpp @@ -13,9 +13,6 @@ #include <QMessageBox> #include <QDir> -#include <QDesktopServices> -#include <QUrl> - // Add this class to the list of specialized dialogs in this namespace namespace MantidQt { namespace CustomInterfaces { diff --git a/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffFittingViewQtWidget.cpp b/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffFittingViewQtWidget.cpp index 4578385c19cfe9dd9bbb9a15d5a4e9fb84352c71..893675a1e973af1be9daa7a7ead567b39d07c568 100644 --- a/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffFittingViewQtWidget.cpp +++ b/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffFittingViewQtWidget.cpp @@ -34,7 +34,7 @@ const std::string EnggDiffFittingViewQtWidget::g_settingsGroup = const std::string EnggDiffFittingViewQtWidget::g_peaksListExt = "Peaks list File: CSV " "(*.csv *.txt);;" - "Other extensions/all files (*.*)"; + "Other extensions/all files (*)"; bool EnggDiffFittingViewQtWidget::m_fittingMutliRunMode = false; bool EnggDiffFittingViewQtWidget::m_fittingSingleRunMode = false; diff --git a/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffractionViewQtGUI.cpp b/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffractionViewQtGUI.cpp index 1970d5c8e854f04868eb2f47e45ca96fc605ade6..fa97dab139e1c64d11e79b77f6815166429c8dfa 100644 --- a/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffractionViewQtGUI.cpp +++ b/MantidQt/CustomInterfaces/src/EnggDiffraction/EnggDiffractionViewQtGUI.cpp @@ -33,7 +33,7 @@ int EnggDiffractionViewQtGUI::g_currentCropCalibBankName = 0; const std::string EnggDiffractionViewQtGUI::g_iparmExtStr = "GSAS instrument parameters, IPARM file: PRM, PAR, IPAR, IPARAM " "(*.prm *.par *.ipar *.iparam);;" - "Other extensions/all files (*.*)"; + "Other extensions/all files (*)"; const std::string EnggDiffractionViewQtGUI::g_pixelCalibExt = "Comma separated values text file with calibration table, CSV" @@ -42,12 +42,12 @@ const std::string EnggDiffractionViewQtGUI::g_pixelCalibExt = "(*.nxs *.nexus);;" "Supported formats: CSV, NXS " "(*.csv *.nxs *.nexus);;" - "Other extensions/all files (*.*)"; + "Other extensions/all files (*)"; const std::string EnggDiffractionViewQtGUI::g_DetGrpExtStr = "Detector Grouping File: CSV " "(*.csv *.txt);;" - "Other extensions/all files (*.*)"; + "Other extensions/all files (*)"; const std::string EnggDiffractionViewQtGUI::g_settingsGroup = "CustomInterfaces/EnggDiffractionView"; diff --git a/MantidQt/CustomInterfaces/src/Homer.cpp b/MantidQt/CustomInterfaces/src/Homer.cpp index 02527955f93d68f2546f90e412d5a9e3674c3098..19effc35cdceb15fdf1e7b72b24f415a09e6492c 100644 --- a/MantidQt/CustomInterfaces/src/Homer.cpp +++ b/MantidQt/CustomInterfaces/src/Homer.cpp @@ -3,6 +3,7 @@ #include "MantidQtCustomInterfaces/deltaECalc.h" #include "MantidQtMantidWidgets/MWDiag.h" #include "MantidQtAPI/FileDialogHandler.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidKernel/ConfigService.h" #include "MantidAPI/FileProperty.h" @@ -17,7 +18,6 @@ #include <QStringList> #include <QUrl> #include <QSignalMapper> -#include <QDesktopServices> #include <QFileDialog> #include <QButtonGroup> #include <QAbstractButton> @@ -28,6 +28,7 @@ using namespace Mantid::Kernel; using namespace Mantid::API; +using MantidQt::API::MantidDesktopServices; using namespace MantidQt::MantidWidgets; using namespace MantidQt::CustomInterfaces; @@ -387,7 +388,7 @@ QString Homer::openFileDia(const bool save, const QStringList &exts) { } filter = filter.trimmed(); } - filter.append(";;All Files (*.*)"); + filter.append(";;All Files (*)"); QString filename; if (save) { @@ -611,7 +612,7 @@ void Homer::browseSaveFile() { * A slot to handle the help button click */ void Homer::helpClicked() { - QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Homer")); + MantidDesktopServices::openUrl(QUrl("http://www.mantidproject.org/Homer")); } /** This slot updates the MWDiag and SPE filename suggester with the diff --git a/MantidQt/CustomInterfaces/src/Indirect/AbsorptionCorrections.cpp b/MantidQt/CustomInterfaces/src/Indirect/AbsorptionCorrections.cpp index d755b3f6d294bb98fbd0a230c0cdc9def42945fd..bcef681c67af7874606d4a0e374117a0508cbd59 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/AbsorptionCorrections.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/AbsorptionCorrections.cpp @@ -47,8 +47,10 @@ void AbsorptionCorrections::run() { QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName(); absCorAlgo->setProperty("SampleWorkspace", sampleWsName.toStdString()); - double sampleNumberDensity = m_uiForm.spSampleNumberDensity->value(); - absCorAlgo->setProperty("SampleNumberDensity", sampleNumberDensity); + absCorAlgo->setProperty( + "SampleDensityType", + m_uiForm.cbSampleDensity->currentText().toStdString()); + absCorAlgo->setProperty("SampleDensity", m_uiForm.spSampleDensity->value()); QString sampleChemicalFormula = m_uiForm.leSampleChemicalFormula->text(); absCorAlgo->setProperty("SampleChemicalFormula", @@ -94,8 +96,10 @@ void AbsorptionCorrections::run() { absCorAlgo->setProperty("UseCanCorrections", useCanCorrections); if (useCanCorrections) { - double canNumberDensity = m_uiForm.spCanNumberDensity->value(); - absCorAlgo->setProperty("CanNumberDensity", canNumberDensity); + + absCorAlgo->setProperty( + "CanDensityType", m_uiForm.cbCanDensity->currentText().toStdString()); + absCorAlgo->setProperty("CanDensity", m_uiForm.spCanDensity->value()); QString canChemicalFormula = m_uiForm.leCanChemicalFormula->text(); absCorAlgo->setProperty("CanChemicalFormula", @@ -206,7 +210,7 @@ bool AbsorptionCorrections::validate() { if (uiv.checkFieldIsNotEmpty("Sample Chemical Formula", m_uiForm.leSampleChemicalFormula)) - uiv.checkFieldIsValid("Sample Chamical Formula", + uiv.checkFieldIsValid("Sample Chemical Formula", m_uiForm.leSampleChemicalFormula); const auto sampleChem = m_uiForm.leSampleChemicalFormula->text().toStdString(); @@ -231,9 +235,9 @@ bool AbsorptionCorrections::validate() { bool useCanCorrections = m_uiForm.ckUseCanCorrections->isChecked(); if (useCanCorrections) { - if (uiv.checkFieldIsNotEmpty("Container Chamical Formula", + if (uiv.checkFieldIsNotEmpty("Container Chemical Formula", m_uiForm.leCanChemicalFormula)) - uiv.checkFieldIsValid("Container Chamical Formula", + uiv.checkFieldIsValid("Container Chemical Formula", m_uiForm.leCanChemicalFormula); } } diff --git a/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp b/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp index 7518590bbc09b26266779d14907fc7fe33b3e17f..e870bf063f7ee59a0ed55939988e91f64bd325e4 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/CalculatePaalmanPings.cpp @@ -83,8 +83,10 @@ void CalculatePaalmanPings::run() { absCorProps["SampleWorkspace"] = sampleWsName.toStdString(); } - absCorAlgo->setProperty("SampleNumberDensity", - m_uiForm.spSampleNumberDensity->value()); + absCorAlgo->setProperty( + "SampleDensityType", + m_uiForm.cbSampleDensity->currentText().toStdString()); + absCorAlgo->setProperty("SampleDensity", m_uiForm.spSampleDensity->value()); absCorAlgo->setProperty( "SampleChemicalFormula", @@ -109,8 +111,9 @@ void CalculatePaalmanPings::run() { absCorProps["CanWorkspace"] = canWsName; } - absCorAlgo->setProperty("CanNumberDensity", - m_uiForm.spCanNumberDensity->value()); + absCorAlgo->setProperty("CanDensityType", + m_uiForm.cbCanDensity->currentText().toStdString()); + absCorAlgo->setProperty("CanDensity", m_uiForm.spCanDensity->value()); const auto canChemicalFormula = m_uiForm.leCanChemicalFormula->text(); absCorAlgo->setProperty("CanChemicalFormula", diff --git a/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp b/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp index a25331a27d5c11df4a18b64e7c77e79fd9cbb10e..43e40be299f454234983cfb68a9975a91dca426f 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/ISISCalibration.cpp @@ -110,7 +110,7 @@ ISISCalibration::ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent) connect(resPeak, SIGNAL(rangeChanged(double, double)), resBackground, SLOT(setRange(double, double))); - // Update property map when a range seclector is moved + // Update property map when a range selector is moved connect(calPeak, SIGNAL(minValueChanged(double)), this, SLOT(calMinChanged(double))); connect(calPeak, SIGNAL(maxValueChanged(double)), this, @@ -128,7 +128,7 @@ ISISCalibration::ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent) connect(resBackground, SIGNAL(maxValueChanged(double)), this, SLOT(calMaxChanged(double))); - // Update range selctor positions when a value in the double manager changes + // Update range selector positions when a value in the double manager changes connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this, SLOT(calUpdateRS(QtProperty *, double))); // Plot miniplots after a file has loaded @@ -139,7 +139,7 @@ ISISCalibration::ISISCalibration(IndirectDataReduction *idrUI, QWidget *parent) connect(m_uiForm.ckCreateResolution, SIGNAL(toggled(bool)), this, SLOT(resCheck(bool))); - // Shows message on run buton when user is inputting a run number + // Shows message on run button when user is inputting a run number connect(m_uiForm.leRunNo, SIGNAL(fileTextChanged(const QString &)), this, SLOT(pbRunEditing())); // Shows message on run button when Mantid is finding the file for a given run @@ -171,27 +171,9 @@ void ISISCalibration::run() { // Get properties QStringList filenameList = m_uiForm.leRunNo->getFilenames(); QString filenames = filenameList.join(","); - QString userInFiles = m_uiForm.leRunNo->getText(); - QString firstFileNumber(""); - auto cutIndexDash = userInFiles.indexOf("-"); - auto cutIndexComma = userInFiles.indexOf(","); - - if (cutIndexDash == -1 && cutIndexComma == -1) { - firstFileNumber = userInFiles; - } else { - if (cutIndexDash != -1) { - firstFileNumber = userInFiles.left(cutIndexDash); - } else { - firstFileNumber = userInFiles.left(cutIndexComma); - } - if (cutIndexDash != -1 && cutIndexComma != -1) { - if (cutIndexDash < cutIndexComma) { - firstFileNumber = userInFiles.left(cutIndexDash); - } else { - firstFileNumber = userInFiles.left(cutIndexComma); - } - } - } + QString rawFile = m_uiForm.leRunNo->getFirstFilename(); + QFileInfo rawFileInfo(rawFile); + QString name = rawFileInfo.baseName(); auto instDetails = getInstrumentDetails(); QString instDetectorRange = @@ -203,8 +185,7 @@ void ISISCalibration::run() { m_properties["CalBackMax"]->valueText(); QString outputWorkspaceNameStem = - getInstrumentConfiguration()->getInstrumentName() + firstFileNumber + - QString::fromStdString("_") + + name + QString::fromStdString("_") + getInstrumentConfiguration()->getAnalyserName() + getInstrumentConfiguration()->getReflectionName(); @@ -237,7 +218,6 @@ void ISISCalibration::run() { // Initially take the calibration workspace as the result m_pythonExportWsName = m_outputCalibrationName.toStdString(); - // Configure the resolution algorithm if (m_uiForm.ckCreateResolution->isChecked()) { m_outputResolutionName = outputWorkspaceNameStem; @@ -527,10 +507,10 @@ void ISISCalibration::calPlotEnergy() { } /** - * Set default background and rebinning properties for a given instument + * Set default background and rebinning properties for a given instrument * and analyser * - * @param ws :: Mantid workspace containing the loaded instument + * @param ws :: Mantid workspace containing the loaded instrument */ void ISISCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws) { auto inst = ws->getInstrument(); @@ -567,10 +547,10 @@ void ISISCalibration::calSetDefaultResolution(MatrixWorkspace_const_sptr ws) { } /** - * Handles a range selector having it's minumum value changed. + * Handles a range selector having it's minimum value changed. * Updates property in property map. * - * @param val :: New minumum value + * @param val :: New minimum value */ void ISISCalibration::calMinChanged(double val) { auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); @@ -594,10 +574,10 @@ void ISISCalibration::calMinChanged(double val) { } /** - * Handles a range selector having it's maxumum value changed. + * Handles a range selector having it's maximum value changed. * Updates property in property map. * - * @param val :: New maxumum value + * @param val :: New maximum value */ void ISISCalibration::calMaxChanged(double val) { auto calPeak = m_uiForm.ppCalibration->getRangeSelector("CalPeak"); @@ -671,7 +651,7 @@ void ISISCalibration::resCheck(bool state) { */ void ISISCalibration::pbRunEditing() { emit updateRunButton(false, "Editing...", - "Run numbers are curently being edited."); + "Run numbers are currently being edited."); } /** @@ -680,7 +660,7 @@ void ISISCalibration::pbRunEditing() { void ISISCalibration::pbRunFinding() { emit updateRunButton( false, "Finding files...", - "Searchig for data files for the run numbers entered..."); + "Searching for data files for the run numbers entered..."); m_uiForm.leRunNo->setEnabled(false); } @@ -691,7 +671,7 @@ void ISISCalibration::pbRunFinished() { if (!m_uiForm.leRunNo->isValid()) { emit updateRunButton( false, "Invalid Run(s)", - "Cannot find data files for some of the run numbers enetered."); + "Cannot find data files for some of the run numbers entered."); } else { emit updateRunButton(); } @@ -704,8 +684,11 @@ void ISISCalibration::pbRunFinished() { void ISISCalibration::saveClicked() { checkADSForPlotSaveWorkspace(m_outputCalibrationName.toStdString(), false); addSaveWorkspaceToQueue(m_outputCalibrationName); - checkADSForPlotSaveWorkspace(m_outputResolutionName.toStdString(), false); - addSaveWorkspaceToQueue(m_outputResolutionName); + + if (m_uiForm.ckCreateResolution->isChecked()) { + checkADSForPlotSaveWorkspace(m_outputResolutionName.toStdString(), false); + addSaveWorkspaceToQueue(m_outputResolutionName); + } m_batchAlgoRunner->executeBatchAsync(); } diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectBayes.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectBayes.cpp index cef1e339c52abd6d71d425a2422311a9178af01d..df5f6d247173761e35848395183ca26327e1262c 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectBayes.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectBayes.cpp @@ -5,9 +5,6 @@ #include "MantidQtCustomInterfaces/Indirect/ResNorm.h" #include "MantidQtCustomInterfaces/Indirect/Stretch.h" -#include <QDesktopServices> -#include <QUrl> - // Add this class to the list of specialised dialogs in this namespace namespace MantidQt { namespace CustomInterfaces { diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectCorrections.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectCorrections.cpp index 004dc8b88a1d33530a42a2b15358e882fdf8d486..c2a8ff118e27a2efeecd83e733712bc8de6d406e 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectCorrections.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectCorrections.cpp @@ -13,9 +13,6 @@ #include "MantidAPI/AnalysisDataService.h" -#include <QDesktopServices> -#include <QUrl> - namespace MantidQt { namespace CustomInterfaces { // Add this class to the list of specialised dialogs in this namespace diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysis.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysis.cpp index 92969722d4066e392bab68613c966eab505517b1..44d7112d0663f1d9df0331c3d82a8fd8b51b2605 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysis.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataAnalysis.cpp @@ -15,9 +15,6 @@ #include "MantidAPI/AnalysisDataService.h" -#include <QDesktopServices> -#include <QUrl> - namespace MantidQt { namespace CustomInterfaces { namespace IDA { diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp index f13811d4678c0870e8bfbda91a2b0497bb79ba83..24f8b629509f5a1fc88e8287ff8c10c45470550d 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDataReduction.cpp @@ -21,10 +21,8 @@ #include "MantidQtCustomInterfaces/Indirect/ILLCalibration.h" #include "MantidQtCustomInterfaces/Indirect/ILLEnergyTransfer.h" -#include <QDesktopServices> #include <QDir> #include <QMessageBox> -#include <QUrl> // Add this class to the list of specialised dialogs in this namespace namespace MantidQt { diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp index 969e18ebc66b1f874ef79f232bcf1cfe1fdab6f0..b5e4846b5985deb962a055cc197d26a5e5259b85 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectDiffractionReduction.cpp @@ -11,9 +11,6 @@ #include "MantidQtAPI/HelpWindow.h" #include "MantidQtAPI/ManageUserDirectories.h" -#include <QDesktopServices> -#include <QUrl> - using namespace Mantid::API; using namespace Mantid::Geometry; diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp index 895565b444881f36daab527d84a26baaa312ab05..4a913571fd4e7bd950dfad7dcf53bbf9293cb51f 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectSimulation.cpp @@ -6,9 +6,6 @@ #include "MantidQtCustomInterfaces/Indirect/IndirectMolDyn.h" #include "MantidQtCustomInterfaces/Indirect/IndirectSassena.h" -#include <QDesktopServices> -#include <QUrl> - // Add this class to the list of specialised dialogs in this namespace namespace MantidQt { namespace CustomInterfaces { diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp index f5d71e115dec9754ee849388f7e8dd9fb6c9bb97..607d895b885f8891d4421b473935b5ec733c82bb 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTools.cpp @@ -5,9 +5,6 @@ #include "MantidQtCustomInterfaces/Indirect/IndirectTransmissionCalc.h" #include "MantidQtCustomInterfaces/Indirect/IndirectLoadILL.h" -#include <QDesktopServices> -#include <QUrl> - // Add this class to the list of specialised dialogs in this namespace namespace MantidQt { namespace CustomInterfaces { diff --git a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp index afd13961a70f7c3c718a3300d65830a4852ca5ba..6227ab90c3bec9a7df5d875fd731ce902d5c0857 100644 --- a/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp +++ b/MantidQt/CustomInterfaces/src/Indirect/IndirectTransmissionCalc.cpp @@ -71,7 +71,11 @@ void IndirectTransmissionCalc::run() { m_uiForm.iicInstrumentConfiguration->getReflectionName().toStdString()); transAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString()); - transAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value()); + if (m_uiForm.cbDensityType->currentIndex() == 0) + transAlg->setProperty("DensityType", "Mass Density"); + else + transAlg->setProperty("DensityType", "Number Density"); + transAlg->setProperty("Density", m_uiForm.spDensity->value()); transAlg->setProperty("Thickness", m_uiForm.spThickness->value()); transAlg->setProperty("OutputWorkspace", outWsName); diff --git a/MantidQt/CustomInterfaces/src/MantidEV.cpp b/MantidQt/CustomInterfaces/src/MantidEV.cpp index 86a7ec583e882f7bac8776ac18d33aa3f1878f58..4f26388871defd24ed8311ae8875006e4aa15a2d 100644 --- a/MantidQt/CustomInterfaces/src/MantidEV.cpp +++ b/MantidQt/CustomInterfaces/src/MantidEV.cpp @@ -2,15 +2,17 @@ #include <QMessageBox> #include <QFileDialog> #include <QSettings> -#include <QDesktopServices> #include <QDesktopWidget> #include <Poco/Path.h> #include "MantidQtCustomInterfaces/MantidEV.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/AlgorithmManager.h" #include "MantidAPI/IEventWorkspace.h" namespace MantidQt { +using API::MantidDesktopServices; + namespace CustomInterfaces { // Register the class with the factory @@ -510,7 +512,7 @@ void MantidEV::setDefaultState_slot() { * Go to MantidEV web page when help menu item is chosen */ void MantidEV::help_slot() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/" "SCD_Event_Data_Reduction_Interface_(MantidEV)")); } @@ -631,7 +633,7 @@ void MantidEV::loadEventFile_slot() { QString file_path = getFilePath(last_event_file); QString Qfile_name = QFileDialog::getOpenFileName(this, tr("Load event file"), file_path, - tr("Nexus Files (*.nxs);; All files(*.*)")); + tr("Nexus Files (*.nxs);; All files(*)")); if (Qfile_name.length() > 0) { m_uiForm.EventFileName_ledt->setText(Qfile_name); @@ -647,7 +649,7 @@ void MantidEV::selectDetCalFile_slot() { QString file_path = getFilePath(last_cal_file); QString Qfile_name = QFileDialog::getOpenFileName( this, tr("Load calibration file"), file_path, - tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)")); + tr("ISAW .DetCal Files (*.DetCal);; All files(*)")); if (Qfile_name.length() > 0) { m_uiForm.CalFileName_ledt->setText(Qfile_name); @@ -663,7 +665,7 @@ void MantidEV::selectDetCalFile2_slot() { QString file_path = getFilePath(last_cal_file2); QString Qfile_name = QFileDialog::getOpenFileName( this, tr("Load calibration file"), file_path, - tr("ISAW .DetCal Files (*.DetCal);; All files(*.*)")); + tr("ISAW .DetCal Files (*.DetCal);; All files(*)")); if (Qfile_name.length() > 0) { m_uiForm.CalFileName2_ledt->setText(Qfile_name); @@ -762,7 +764,7 @@ void MantidEV::getLoadPeaksFileName_slot() { QString file_path = getFilePath(last_peaks_file); QString Qfile_name = QFileDialog::getOpenFileName( this, tr("Load peaks file"), file_path, - tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)")); + tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*)")); if (Qfile_name.length() > 0) { last_peaks_file = Qfile_name.toStdString(); @@ -778,7 +780,7 @@ void MantidEV::getSavePeaksFileName() { QString file_path = getFilePath(last_peaks_file); QString Qfile_name = QFileDialog::getSaveFileName( this, tr("Save peaks file"), file_path, - tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*.*)"), 0, + tr("Peaks Files (*.peaks *.integrate *.nxs *.h5);; All files(*)"), 0, QFileDialog::DontConfirmOverwrite); if (Qfile_name.length() > 0) { @@ -926,7 +928,7 @@ void MantidEV::getLoadUB_FileName_slot() { QString file_path = getFilePath(last_UB_file); QString Qfile_name = QFileDialog::getOpenFileName(this, tr("Load matrix file"), file_path, - tr("Matrix Files (*.mat);; All files(*.*)")); + tr("Matrix Files (*.mat);; All files(*)")); if (Qfile_name.length() > 0) { last_UB_file = Qfile_name.toStdString(); m_uiForm.SelectUBFile_ledt->setText(Qfile_name); @@ -940,7 +942,7 @@ void MantidEV::getSaveUB_FileName() { QString file_path = getFilePath(last_UB_file); QString Qfile_name = QFileDialog::getSaveFileName(this, tr("Save matrix file"), file_path, - tr("Matrix Files (*.mat);; All files(*.*)")); + tr("Matrix Files (*.mat);; All files(*)")); if (Qfile_name.length() > 0) { last_UB_file = Qfile_name.toStdString(); @@ -1271,7 +1273,7 @@ void MantidEV::saveState_slot() { QString file_path = getFilePath(last_ini_file); QString Qfile_name = QFileDialog::getSaveFileName( this, tr("Save Settings File(.ini)"), file_path, - tr("Settings Files (*.ini);; All files(*.*) ")); + tr("Settings Files (*.ini);; All files(*) ")); if (Qfile_name.length() > 0) { last_ini_file = Qfile_name.toStdString(); @@ -1286,7 +1288,7 @@ void MantidEV::loadState_slot() { QString file_path = getFilePath(last_ini_file); QString Qfile_name = QFileDialog::getOpenFileName( this, tr("Load Settings File(.ini)"), file_path, - tr("Settings Files (*.ini);; All files(*.*)")); + tr("Settings Files (*.ini);; All files(*)")); if (Qfile_name.length() > 0) { last_ini_file = Qfile_name.toStdString(); diff --git a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp index b0de032c2febb6fe2fa6931dc99f8e709e51b12b..635c005d93de562a22ad7cf248da162dcb4deb81 100644 --- a/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp +++ b/MantidQt/CustomInterfaces/src/Muon/MuonAnalysis.cpp @@ -564,7 +564,7 @@ void MuonAnalysis::runSaveGroupButton() { QString filter; filter.append("Files (*.xml *.XML)"); - filter += ";;AllFiles (*.*)"; + filter += ";;AllFiles (*)"; QString groupingFile = MantidQt::API::FileDialogHandler::getSaveFileName( this, "Save Grouping file as", prevPath, filter); @@ -603,7 +603,7 @@ void MuonAnalysis::runLoadGroupButton() { QString filter; filter.append("Files (*.xml *.XML)"); - filter += ";;AllFiles (*.*)"; + filter += ";;AllFiles (*)"; QString groupingFile = QFileDialog::getOpenFileName( this, "Load Grouping file", prevPath, filter); if (groupingFile.isEmpty() || QFileInfo(groupingFile).isDir()) @@ -2899,7 +2899,7 @@ std::string MuonAnalysis::getSubtractedPeriods() const { * Pass this information to the fit helper */ void MuonAnalysis::dataToFitChanged() { - if (m_fitDataPresenter) { + if (m_fitDataPresenter && m_loaded) { // Only act if some data is loaded m_fitDataPresenter->setGrouping(m_groupingHelper.parseGroupingTable()); m_fitDataPresenter->setPlotType(parsePlotType(m_uiForm.frontPlotFuncs)); // Set busy cursor while workspaces are being created diff --git a/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp b/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp index 64adcbf366e23652c3c83cbb8d8e06a96f0d8b6c..42298369b880b628fe2d4accc96a32fe1966241c 100644 --- a/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp +++ b/MantidQt/CustomInterfaces/src/SANSRunWindow.cpp @@ -18,13 +18,13 @@ #include "MantidAPI/WorkspaceGroup.h" #include "MantidQtAPI/FileDialogHandler.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtAPI/ManageUserDirectories.h" #include "MantidQtCustomInterfaces/SANSAddFiles.h" #include "MantidQtCustomInterfaces/SANSBackgroundCorrectionSettings.h" #include "MantidQtCustomInterfaces/SANSEventSlicing.h" #include <QClipboard> -#include <QDesktopServices> #include <QTemporaryFile> #include <QTextStream> #include <QUrl> @@ -1940,7 +1940,7 @@ void SANSRunWindow::saveFileBrowse() { ConfigService::Instance().getString( "defaultsave.directory"))).toString(); - const QString filter = ";;AllFiles (*.*)"; + const QString filter = ";;AllFiles (*)"; QString oFile = FileDialogHandler::getSaveFileName( this, title, prevPath + "/" + m_uiForm.outfile_edit->text()); @@ -1971,7 +1971,7 @@ bool SANSRunWindow::browseForFile(const QString &box_title, if (box_text.isEmpty()) { start_path = m_last_dir; } - file_filter += ";;AllFiles (*.*)"; + file_filter += ";;AllFiles (*)"; QString file_path = QFileDialog::getOpenFileName(this, box_title, start_path, file_filter); if (file_path.isEmpty() || QFileInfo(file_path).isDir()) @@ -3886,7 +3886,7 @@ void SANSRunWindow::handleSlicePushButton() { void SANSRunWindow::openHelpPage() { const auto helpPageUrl = m_helpPageUrls[static_cast<Tab>(m_uiForm.tabWidget->currentIndex())]; - QDesktopServices::openUrl(QUrl(helpPageUrl)); + MantidDesktopServices::openUrl(QUrl(helpPageUrl)); } // Set the validators for inputs diff --git a/MantidQt/CustomInterfaces/src/SampleTransmission.cpp b/MantidQt/CustomInterfaces/src/SampleTransmission.cpp index 969378233a87772fe533bb8a2a74202addf3ffe9..0bd502591a60582487b1c89d2436d1cdd8bf7067 100644 --- a/MantidQt/CustomInterfaces/src/SampleTransmission.cpp +++ b/MantidQt/CustomInterfaces/src/SampleTransmission.cpp @@ -83,9 +83,8 @@ bool SampleTransmission::validate(bool silent) { m_uiForm.valChemicalFormula); // Ensure number density is not zero - uiv.setErrorLabel( - m_uiForm.valNumberDensity, - uiv.checkNotEqual("Number Density", m_uiForm.spNumberDensity->value())); + uiv.setErrorLabel(m_uiForm.valDensity, + uiv.checkNotEqual("Density", m_uiForm.spDensity->value())); // Ensure thickness is not zero uiv.setErrorLabel( @@ -135,7 +134,11 @@ void SampleTransmission::calculate() { // Set sample material properties transCalcAlg->setProperty("ChemicalFormula", m_uiForm.leChemicalFormula->text().toStdString()); - transCalcAlg->setProperty("NumberDensity", m_uiForm.spNumberDensity->value()); + + transCalcAlg->setProperty("DensityType", + m_uiForm.cbDensity->currentText().toStdString()); + transCalcAlg->setProperty("Density", m_uiForm.spDensity->value()); + transCalcAlg->setProperty("Thickness", m_uiForm.spThickness->value()); transCalcAlg->setProperty("OutputWorkspace", "CalculatedSampleTransmission"); diff --git a/MantidQt/CustomInterfaces/src/StepScan.cpp b/MantidQt/CustomInterfaces/src/StepScan.cpp index f1d7f4108dc1b6197a93289e1235750b0ef0f93c..0aafa658bc16f2589d0d53a564f685602205d5c7 100644 --- a/MantidQt/CustomInterfaces/src/StepScan.cpp +++ b/MantidQt/CustomInterfaces/src/StepScan.cpp @@ -1,4 +1,5 @@ #include "MantidQtCustomInterfaces/StepScan.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/AlgorithmManager.h" #include "MantidAPI/IEventWorkspace.h" #include "MantidAPI/InstrumentDataService.h" @@ -7,13 +8,14 @@ #include "MantidKernel/InstrumentInfo.h" #include "MantidKernel/TimeSeriesProperty.h" #include <QFileInfo> -#include <QDesktopServices> #include <QUrl> #include <Poco/ActiveResult.h> #include <Poco/Thread.h> namespace MantidQt { +using API::MantidDesktopServices; + namespace CustomInterfaces { // Register the class with the factory @@ -710,7 +712,7 @@ void StepScan::checkForVaryingLogs(const std::string &wsName) { } void StepScan::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Step_Scan_Interface")); } diff --git a/MantidQt/CustomInterfaces/src/Tomography/ImageROIViewQtWidget.cpp b/MantidQt/CustomInterfaces/src/Tomography/ImageROIViewQtWidget.cpp index c5b1c5e74f746821c4527e118a05399f27653961..56e0b1ea8d526fb6703d6f404090f6c4d6f8c2c1 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/ImageROIViewQtWidget.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/ImageROIViewQtWidget.cpp @@ -340,7 +340,7 @@ std::string ImageROIViewQtWidget::askImgOrStackPath() { "(*.tif *.tiff);;" "PNG, Portable Network Graphics " "(*.png);;" - "Other extensions/all files (*.*)"); + "Other extensions/all files (*)"); QString prevPath = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); QString path(QFileDialog::getExistingDirectory( @@ -364,7 +364,7 @@ std::string ImageROIViewQtWidget::askSingleImagePath() { "(*.tif *.tiff);;" "PNG, Portable Network Graphics " "(*.png);;" - "Other extensions/all files (*.*)"); + "Other extensions/all files (*)"); QString prevPath = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); QString filepath( diff --git a/MantidQt/CustomInterfaces/src/Tomography/ImggFormatsConvertViewQtWidget.cpp b/MantidQt/CustomInterfaces/src/Tomography/ImggFormatsConvertViewQtWidget.cpp index 8b7bb3ecb71e957932515d06e834fcd9d52fcab5..b0e18f97b8558e6ffabd09a3fe050cef2ea96228 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/ImggFormatsConvertViewQtWidget.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/ImggFormatsConvertViewQtWidget.cpp @@ -355,7 +355,7 @@ std::string ImggFormatsConvertViewQtWidget::askImgOrStackPath() { "(*.tif *.tiff);;" "PNG, Portable Network Graphics " "(*.png);;" - "Other extensions/all files (*.*)"); + "Other extensions/all files (*)"); QString prevPath = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); QString path(QFileDialog::getExistingDirectory( diff --git a/MantidQt/CustomInterfaces/src/Tomography/SavuConfigDialog.cpp b/MantidQt/CustomInterfaces/src/Tomography/SavuConfigDialog.cpp index 150433cbbe81cdde5c40710a39f5c511305498ee..0c2f23c5077750a3f4b96d257f574c8a3294f734 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/SavuConfigDialog.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/SavuConfigDialog.cpp @@ -240,10 +240,9 @@ void TomographyIfaceViewQtGUI::removeClicked() { } void TomographyIfaceViewQtGUI::menuOpenClicked() { - QString s = - QFileDialog::getOpenFileName(0, "Open file", QDir::currentPath(), - "NeXus files (*.nxs);;All files (*.*)", - new QString("NeXus files (*.nxs)")); + QString s = QFileDialog::getOpenFileName(0, "Open file", QDir::currentPath(), + "NeXus files (*.nxs);;All files (*)", + new QString("NeXus files (*.nxs)")); std::string name = s.toStdString(); if ("" == name) @@ -299,10 +298,9 @@ void TomographyIfaceViewQtGUI::menuSaveClicked() { } void TomographyIfaceViewQtGUI::menuSaveAsClicked() { - QString s = - QFileDialog::getSaveFileName(0, "Save file", QDir::currentPath(), - "NeXus files (*.nxs);;All files (*.*)", - new QString("NeXus files (*.nxs)")); + QString s = QFileDialog::getSaveFileName(0, "Save file", QDir::currentPath(), + "NeXus files (*.nxs);;All files (*)", + new QString("NeXus files (*.nxs)")); std::string name = s.toStdString(); if ("" == name) return; diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp index 796fd818a02689dee91333b3415ac622843a7573..7947ea1b8c8001e5172ff8e751fc3bb8637e68a0 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp @@ -1319,7 +1319,7 @@ void TomographyIfaceViewQtGUI::browseImageClicked() { "(*.tif *.tiff);;" "PNG, Portable Network Graphics " "(*.png);;" - "Other extensions/all files (*.*)"); + "Other extensions/all files (*)"); // Note that this could be done using UserSubWindow::openFileDialog(), // but that method doesn't give much control over the text used for the // allowed extensions. diff --git a/MantidQt/MantidWidgets/src/CatalogSearch.cpp b/MantidQt/MantidWidgets/src/CatalogSearch.cpp index a2dd89e6330fd76757909e52c0dccbe393c151a7..95faa08dfeedcb14a3de0e71b6689c60a48f81ae 100644 --- a/MantidQt/MantidWidgets/src/CatalogSearch.cpp +++ b/MantidQt/MantidWidgets/src/CatalogSearch.cpp @@ -1,3 +1,5 @@ +#include "MantidQtMantidWidgets/CatalogSearch.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/AlgorithmManager.h" #include "MantidAPI/AnalysisDataService.h" #include "MantidAPI/ITableWorkspace.h" @@ -5,11 +7,10 @@ #include "MantidKernel/UserCatalogInfo.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/FacilityInfo.h" -#include "MantidQtMantidWidgets/CatalogSearch.h" + #include <Poco/ActiveResult.h> #include <Poco/Path.h> -#include <QDesktopServices> #include <QFileDialog> #include <QSettings> #include <QStyle> @@ -179,7 +180,8 @@ void CatalogSearch::onFacilityLogin() {} * Sends the user to relevant search page on the Mantid project site. */ void CatalogSearch::helpClicked() { - QDesktopServices::openUrl( + using MantidQt::API::MantidDesktopServices; + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/Catalog_Search")); } diff --git a/MantidQt/MantidWidgets/src/DataProcessorUI/QDataProcessorWidget.cpp b/MantidQt/MantidWidgets/src/DataProcessorUI/QDataProcessorWidget.cpp index fb8b8b26e0fc952385c5240c4e657be233883c4d..73d2f0d176ff5a9c14b4f2d86af7dda51a55dec2 100644 --- a/MantidQt/MantidWidgets/src/DataProcessorUI/QDataProcessorWidget.cpp +++ b/MantidQt/MantidWidgets/src/DataProcessorUI/QDataProcessorWidget.cpp @@ -186,7 +186,7 @@ std::string QDataProcessorWidget::requestNotebookPath() { // causes problems on MacOS. QString qfilename = API::FileDialogHandler::getSaveFileName( this, "Save notebook file", QDir::currentPath(), - "IPython Notebook files (*.ipynb);;All files (*.*)", + "IPython Notebook files (*.ipynb);;All files (*)", new QString("IPython Notebook files (*.ipynb)")); // There is a Qt bug (QTBUG-27186) which means the filename returned diff --git a/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp b/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp index d0176bdcea60c33c8bcdd2ce17c1324ab4071cd0..b7db9d66fd463475f605545d76d633f18529a24d 100644 --- a/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp +++ b/MantidQt/MantidWidgets/src/FitPropertyBrowser.cpp @@ -2,6 +2,7 @@ #include "MantidQtMantidWidgets/PropertyHandler.h" #include "MantidQtMantidWidgets/SequentialFitDialog.h" #include "MantidQtMantidWidgets/MultifitSetupDialog.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/ITableWorkspace.h" #include "MantidAPI/IPeakFunction.h" @@ -51,12 +52,13 @@ #include <QSignalMapper> #include <QMetaMethod> #include <QTreeWidget> -#include <QDesktopServices> #include <QUrl> #include <algorithm> namespace MantidQt { +using API::MantidDesktopServices; + namespace MantidWidgets { /** @@ -3033,7 +3035,7 @@ void FitPropertyBrowser::functionHelp() { QString url = QString::fromStdString("http://docs.mantidproject.org/fitfunctions/" + handler->ifun()->name()); - QDesktopServices::openUrl(QUrl(url)); + MantidDesktopServices::openUrl(QUrl(url)); } } @@ -3041,9 +3043,10 @@ void FitPropertyBrowser::functionHelp() { * Show online browser help */ void FitPropertyBrowser::browserHelp() { - QDesktopServices::openUrl(QUrl("http://www.mantidproject.org/" - "MantidPlot:_Simple_Peak_Fitting_with_the_Fit_" - "Wizard#Fit_Properties_Browser")); + MantidDesktopServices::openUrl( + QUrl("http://www.mantidproject.org/" + "MantidPlot:_Simple_Peak_Fitting_with_the_Fit_" + "Wizard#Fit_Properties_Browser")); } /**================================================================================================= diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp index a0485ff31dd5f21cdb7dc4cc14614360c5063d1e..aef9bea4e6f2dfff6267cde040cc2571741ac060 100644 --- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp +++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidget.cpp @@ -1,5 +1,6 @@ #include "MantidQtMantidWidgets/InstrumentView/InstrumentWidget.h" #include "MantidQtAPI/TSVSerialiser.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtMantidWidgets/InstrumentView/DetXMLFile.h" #include "MantidQtMantidWidgets/InstrumentView/InstrumentActor.h" #include "MantidQtMantidWidgets/InstrumentView/InstrumentWidgetMaskTab.h" @@ -25,7 +26,6 @@ #include <QCheckBox> #include <QColorDialog> #include <QComboBox> -#include <QDesktopServices> #include <QDoubleValidator> #include <QDragEnterEvent> #include <QDropEvent> @@ -678,7 +678,7 @@ void InstrumentWidget::saveImage(QString filename) { QString InstrumentWidget::getSaveGroupingFilename() { QString filename = MantidQt::API::FileDialogHandler::getSaveFileName( this, "Save grouping file", m_savedialog_dir, - "Grouping (*.xml);;All files (*.*)"); + "Grouping (*.xml);;All files (*)"); // If its empty, they cancelled the dialog if (!filename.isEmpty()) { @@ -723,7 +723,7 @@ void InstrumentWidget::saveSettings() { } void InstrumentWidget::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/MantidPlot:_Instrument_View")); } diff --git a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetMaskTab.cpp b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetMaskTab.cpp index 24d926a82f94cd5c5f9b764e6b650152279e6e77..e78ba4deb84688dc8aa2cbdb972c0b92eb28f4f9 100644 --- a/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetMaskTab.cpp +++ b/MantidQt/MantidWidgets/src/InstrumentView/InstrumentWidgetMaskTab.cpp @@ -754,8 +754,8 @@ void InstrumentWidgetMaskTab::sumDetsToWorkspace() { } void InstrumentWidgetMaskTab::saveIncludeGroupToFile() { - QString fname = m_instrWidget->getSaveFileName( - "Save grouping file", "XML files (*.xml);;All (*.* *)"); + QString fname = m_instrWidget->getSaveFileName("Save grouping file", + "XML files (*.xml);;All (*)"); if (!fname.isEmpty()) { QList<int> dets; m_instrWidget->getSurface()->getMaskedDetectors(dets); @@ -764,8 +764,8 @@ void InstrumentWidgetMaskTab::saveIncludeGroupToFile() { } void InstrumentWidgetMaskTab::saveExcludeGroupToFile() { - QString fname = m_instrWidget->getSaveFileName( - "Save grouping file", "XML files (*.xml);;All (*.* *)"); + QString fname = m_instrWidget->getSaveFileName("Save grouping file", + "XML files (*.xml);;All (*)"); if (!fname.isEmpty()) { QList<int> dets; m_instrWidget->getSurface()->getMaskedDetectors(dets); @@ -845,7 +845,7 @@ void InstrumentWidgetMaskTab::saveMaskingToFile(bool invertMask) { QApplication::restoreOverrideCursor(); QString fileName = m_instrWidget->getSaveFileName( "Select location and name for the mask file", - "XML files (*.xml);;All (*.* *)"); + "XML files (*.xml);;All (*)"); QApplication::setOverrideCursor(QCursor(Qt::WaitCursor)); if (!fileName.isEmpty()) { diff --git a/MantidQt/MantidWidgets/src/MWDiag.cpp b/MantidQt/MantidWidgets/src/MWDiag.cpp index e393a21b54a0d62b9b12f57080be8dcde2956eae..bc6867f12cb989ac9cdb25828204bd7c4c1452df 100644 --- a/MantidQt/MantidWidgets/src/MWDiag.cpp +++ b/MantidQt/MantidWidgets/src/MWDiag.cpp @@ -488,7 +488,7 @@ QString MWDiag::openFileDialog(const bool save, const QStringList &exts) { } filter = filter.trimmed(); } - filter.append(";;All Files (*.*)"); + filter.append(";;All Files (*)"); QString filename; if (save) { diff --git a/MantidQt/MantidWidgets/src/MWRunFiles.cpp b/MantidQt/MantidWidgets/src/MWRunFiles.cpp index 30f30fc2ee2a1b26460200a40aad1a91bce1a013..a5addee02c46f293b713933a22b1833408911e85 100644 --- a/MantidQt/MantidWidgets/src/MWRunFiles.cpp +++ b/MantidQt/MantidWidgets/src/MWRunFiles.cpp @@ -870,7 +870,7 @@ QString MWRunFiles::createFileFilter() { } } - QString allFiles("All Files (*.*)"); + QString allFiles("All Files (*)"); if (!fileExts.isEmpty()) { // The list may contain upper and lower cased versions, ensure these are on diff --git a/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp b/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp index 4a72cdb994c756f14250774a3e23d7fa35feecfe..e84f06684128141a81d1d558e71fd03c7b9096cd 100644 --- a/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp +++ b/MantidQt/MantidWidgets/src/MantidHelpWindow.cpp @@ -1,6 +1,7 @@ #include "MantidQtMantidWidgets/MantidHelpWindow.h" #include "MantidQtMantidWidgets/pqHelpWindow.h" #include "MantidQtAPI/InterfaceManager.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/Logger.h" #include "MantidKernel/RegistrationHelper.h" @@ -8,7 +9,6 @@ #include <boost/lexical_cast.hpp> #include <Poco/File.h> #include <Poco/Path.h> -#include <QDesktopServices> #include <QDir> #include <QFileInfo> #include <QHelpEngine> @@ -122,7 +122,7 @@ void MantidHelpWindow::showHelp(const QString &url) { void MantidHelpWindow::openWebpage(const QUrl &url) { g_log.debug() << "open url \"" << url.toString().toStdString() << "\"\n"; - QDesktopServices::openUrl(url); + MantidDesktopServices::openUrl(url); } void MantidHelpWindow::showPage(const QString &url) { @@ -423,7 +423,7 @@ void MantidHelpWindow::determineFileLocs() { // determine cache file location m_cacheFile = COLLECTION_FILE.toStdString(); QString dataLoc = - QDesktopServices::storageLocation(QDesktopServices::DataLocation); + MantidDesktopServices::storageLocation(QDesktopServices::DataLocation); if (dataLoc.endsWith("mantidproject")) { Poco::Path path(dataLoc.toStdString(), m_cacheFile); m_cacheFile = path.absolute().toString(); diff --git a/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp b/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp index c35d5a99eec4b63445c2292ff7ee9f7312edc4b2..7767b14d5f90f0b5acde176ca91a52668b649300 100644 --- a/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp +++ b/MantidQt/MantidWidgets/src/SaveWorkspaces.cpp @@ -369,7 +369,7 @@ void SaveWorkspaces::saveFileBrowse() { ConfigService::Instance().getString( "defaultsave.directory"))).toString(); - QString filter = ";;AllFiles (*.*)"; + QString filter = ";;AllFiles (*)"; QFileDialog::Option userCon = m_append->isChecked() ? QFileDialog::DontConfirmOverwrite : static_cast<QFileDialog::Option>(0); diff --git a/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp b/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp index 58ff125c81648576814c4e7703419355136e624c..bb55ffa79376e1fc7815375fe9a7a4f642baee7d 100644 --- a/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp +++ b/MantidQt/MantidWidgets/src/SequentialFitDialog.cpp @@ -1,6 +1,7 @@ #include "MantidQtMantidWidgets/SequentialFitDialog.h" #include "MantidQtMantidWidgets/FitPropertyBrowser.h" #include "MantidQtMantidWidgets/SelectWorkspacesDialog.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/AlgorithmManager.h" #include "MantidAPI/Axis.h" #include "MantidAPI/CompositeFunction.h" @@ -15,10 +16,11 @@ #include <QInputDialog> #include <QFileDialog> #include <QMessageBox> -#include <QDesktopServices> #include <QUrl> namespace MantidQt { +using API::MantidDesktopServices; + namespace MantidWidgets { /// Constructor @@ -357,7 +359,7 @@ void SequentialFitDialog::finishHandle(const Mantid::API::IAlgorithm *) { } void SequentialFitDialog::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/PlotPeakByLogValue")); } diff --git a/MantidQt/MantidWidgets/src/UserFunctionDialog.cpp b/MantidQt/MantidWidgets/src/UserFunctionDialog.cpp index e56911c99fa54a9c1ab5a6eacd29621c92c5ce84..cef8dcddcc316912917309e341a25dce83f8c7fc 100644 --- a/MantidQt/MantidWidgets/src/UserFunctionDialog.cpp +++ b/MantidQt/MantidWidgets/src/UserFunctionDialog.cpp @@ -1,5 +1,6 @@ #include "MantidQtMantidWidgets/UserFunctionDialog.h" #include "MantidQtMantidWidgets/RenameParDialog.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidAPI/Expression.h" #include "MantidKernel/ConfigService.h" @@ -10,11 +11,11 @@ #include <QKeyEvent> #include <QFile> #include <QTextStream> -#include <QDesktopServices> #include <QUrl> #include <algorithm> +using MantidQt::API::MantidDesktopServices; using namespace MantidQt::MantidWidgets; UserFunctionDialog::UserFunctionDialog(QWidget *parent, const QString &formula) @@ -496,7 +497,7 @@ bool UserFunctionDialog::isBuiltin(const QString &cat) const { * Open the help wiki page in the web browser. */ void UserFunctionDialog::helpClicked() { - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl("http://www.mantidproject.org/MantidPlot:_User_Function_Dialog")); } diff --git a/MantidQt/MantidWidgets/src/pqHelpWindow.cxx b/MantidQt/MantidWidgets/src/pqHelpWindow.cxx index 3ec46d1383dbb3ab023f511699ad0387b349c8e5..9722259573c477150da52de0aa5e4c071a00fd39 100644 --- a/MantidQt/MantidWidgets/src/pqHelpWindow.cxx +++ b/MantidQt/MantidWidgets/src/pqHelpWindow.cxx @@ -7,7 +7,7 @@ All rights reserved. ParaView is a free software; you can redistribute it and/or modify it - under the terms of the ParaView license version 1.2. + under the terms of the ParaView license version 1.2. See License_v1.2.txt for the full ParaView license. A copy of this license can be obtained by contacting @@ -30,9 +30,9 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ========================================================================*/ #include "MantidQtMantidWidgets/pqHelpWindow.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "ui_pqHelpWindow.h" -#include <QDesktopServices> #include <QFileInfo> #include <QHelpContentWidget> #include <QHelpEngine> @@ -53,6 +53,8 @@ SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include <QWebView> #include <iostream> +using MantidQt::API::MantidDesktopServices; + // **************************************************************************** // CLASS pqHelpWindowNetworkReply // **************************************************************************** @@ -313,7 +315,7 @@ void pqHelpWindow::showPage(const QUrl& url) } else { - QDesktopServices::openUrl(url); + MantidDesktopServices::openUrl(url); } } diff --git a/MantidQt/Python/mantidqt.sip b/MantidQt/Python/mantidqt.sip index d2751520e53e7217eda958f8f848488eaff75247..0e0ab6ff43c8061464015bb54c9d76f69f0034f3 100644 --- a/MantidQt/Python/mantidqt.sip +++ b/MantidQt/Python/mantidqt.sip @@ -151,6 +151,20 @@ public: void showCustomInterfaceHelp(const QString &name); }; +class MantidDesktopServices +{ +%TypeHeaderCode +#include "MantidQtAPI/MantidDesktopServices.h" +%End +public: + static bool openUrl(const QUrl &url); + static void setUrlHandler(const QString &scheme, QObject *receiver, + const char *method); + static void unsetUrlHandler(const QString &scheme); + static QString storageLocation(QDesktopServices::StandardLocation type); + static QString displayName(QDesktopServices::StandardLocation type); +}; + }; namespace MantidWidgets @@ -1162,7 +1176,7 @@ Mantid::API::MDNormalization SliceViewer::getNormalization() void SliceViewer::setColorBarAutoScale(bool autoscale) ------------------------------------------------------ Set autoscaling for the color scale on or off - + Args: autoscale :: on/off status for autoscaling @@ -1610,7 +1624,7 @@ public: SPHERICAL_X, SPHERICAL_Y, SPHERICAL_Z, RENDERMODE_SIZE }; enum Tab { RENDER, PICK, MASK, TREE }; - + InstrumentWidget(const QString &wsName, QWidget *parent = nullptr, bool resetGeometry = true, bool autoscaling = true, double scaleMin = 0.0, double scaleMax = 0.0, @@ -1884,6 +1898,3 @@ private: };//end namespace MantidWidgets };//end namespace MantidQt - - - diff --git a/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp b/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp index 7e8486efb7b5bc907aeddcdd427bf8a2d9d53156..d63b231a64fb308874412a0b60aeb6de9ac3c619 100644 --- a/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp +++ b/MantidQt/SliceViewer/src/PeaksViewerOverlayDialog.cpp @@ -1,10 +1,12 @@ #include <QDialogButtonBox> #include <QUrl> -#include <QDesktopServices> #include "MantidQtSliceViewer/PeaksViewerOverlayDialog.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "ui_PeaksViewerOverlayDialog.h" namespace MantidQt { +using API::MantidDesktopServices; + namespace SliceViewer { /** * Calculate the conversion factor from slider position to fractional occupancy. @@ -157,7 +159,7 @@ void PeaksViewerOverlayDialog::reject() { */ void PeaksViewerOverlayDialog::onHelp() { QString helpPage = "PeaksViewer#Preference_Options"; - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl(QString("http://www.mantidproject.org/") + helpPage)); } } diff --git a/MantidQt/SliceViewer/src/SliceViewer.cpp b/MantidQt/SliceViewer/src/SliceViewer.cpp index 116019d6e974bda748ccc07967c707b31c1c8784..8b9ee0bdc7d2ccb21225a1251db6e448f0b09486 100644 --- a/MantidQt/SliceViewer/src/SliceViewer.cpp +++ b/MantidQt/SliceViewer/src/SliceViewer.cpp @@ -22,6 +22,7 @@ #include "MantidKernel/ReadLock.h" #include "MantidQtAPI/FileDialogHandler.h" #include "MantidQtAPI/PlotAxis.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtAPI/MdSettings.h" #include "MantidQtAPI/SignalBlocker.h" #include "MantidQtAPI/SignalRange.h" @@ -54,6 +55,7 @@ using namespace Mantid; using namespace Mantid::Kernel; using namespace Mantid::Geometry; using namespace Mantid::API; +using MantidQt::API::MantidDesktopServices; using MantidQt::API::SyncedCheckboxes; using MantidQt::API::SignalBlocker; using Poco::XML::DOMParser; @@ -1158,20 +1160,20 @@ void SliceViewer::zoomRectSlot(const QwtDoubleRect &rect) { /// Slot for opening help page void SliceViewer::helpSliceViewer() { QString helpPage = "MantidPlot:_SliceViewer"; - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl(QString("http://www.mantidproject.org/") + helpPage)); } /// Slot for opening help page void SliceViewer::helpLineViewer() { QString helpPage = "MantidPlot:_LineViewer"; - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl(QString("http://www.mantidproject.org/") + helpPage)); } void SliceViewer::helpPeaksViewer() { QString helpPage = "PeaksViewer"; - QDesktopServices::openUrl( + MantidDesktopServices::openUrl( QUrl(QString("http://www.mantidproject.org/") + helpPage)); } diff --git a/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp b/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp index 143aad4113d9e034bbadc62607acb7c38b57548c..998a2b34757dc97815b994bd4abf4e935414009f 100644 --- a/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp +++ b/MantidQt/SpectrumViewer/src/MatrixWSDataSource.cpp @@ -285,8 +285,8 @@ std::vector<std::string> MatrixWSDataSource::getInfoList(double x, double y) { azi = det->getPhi(); } SVUtils::PushNameValue("L2", 8, 4, l2, list); - SVUtils::PushNameValue("TwoTheta", 8, 2, two_theta * deg2rad, list); - SVUtils::PushNameValue("Azimuthal", 8, 2, azi * deg2rad, list); + SVUtils::PushNameValue("TwoTheta", 8, 2, two_theta * rad2deg, list); + SVUtils::PushNameValue("Azimuthal", 8, 2, azi * rad2deg, list); /* For now, only support diffractometers and monitors. */ /* We need a portable way to determine emode and */ diff --git a/MantidQt/SpectrumViewer/src/SVConnections.cpp b/MantidQt/SpectrumViewer/src/SVConnections.cpp index 73d6e04b9a3b7f6c60a7f57fcde718f1d102c816..76e19dd8fa9293e270bd32a635ea5b473ab5ea8b 100644 --- a/MantidQt/SpectrumViewer/src/SVConnections.cpp +++ b/MantidQt/SpectrumViewer/src/SVConnections.cpp @@ -1,7 +1,5 @@ #include <qwt_plot_canvas.h> -#include <QDesktopServices> - #include "MantidQtAPI/HelpWindow.h" #include "MantidQtAPI/MantidColorMap.h" diff --git a/Testing/SystemTests/tests/analysis/BuildSQWTest.py b/Testing/SystemTests/tests/analysis/BuildSQWTest.py index c026059f53151d484f83c6e9c741b3fd4ba82a2c..00d160b73e13d27e4b648e2c01da3c7176fc9eb0 100644 --- a/Testing/SystemTests/tests/analysis/BuildSQWTest.py +++ b/Testing/SystemTests/tests/analysis/BuildSQWTest.py @@ -88,7 +88,7 @@ class BuildSQWTest(stresstesting.MantidStressTest): # Do the final merge sqw_file = os.path.join(config["defaultsave.directory"],"BuildSQWTestCurrent.nxs") - dummy_finalSQW = MergeMDFiles(",".join(self._created_files),OutputFilename=sqw_file,Parallel='0') + MergeMDFiles(",".join(self._created_files),OutputFilename=sqw_file,Parallel='0',OutputWorkspace='dummy_finalSQW') self._created_files.append(sqw_file) def validate(self): @@ -117,7 +117,7 @@ class LoadSQW_FileBasedTest(BuildSQWTest): MDws_file = os.path.join(config["defaultsave.directory"],"LoadSQWTestFileBased.nxs") sqw_file = os.path.join(self._input_location,self._input_data[0]) - dummy_wsMD=LoadSQW(Filename=sqw_file, OutputFilename=MDws_file) + LoadSQW(Filename=sqw_file, OutputFilename=MDws_file, OutputWorkspace='dummy_wsMD') self._created_files=MDws_file @@ -143,7 +143,7 @@ class LoadSQW_MemBasedTest(BuildSQWTest): sqw_file = os.path.join(self._input_location,self._input_data[0]) - dummy_wsMD=LoadSQW(Filename=sqw_file) + LoadSQW(Filename=sqw_file, OutputWorkspace='dummy_wsMD') self._created_files=[] diff --git a/Testing/SystemTests/tests/analysis/CodeConventions.py b/Testing/SystemTests/tests/analysis/CodeConventions.py index ad1699771fbe79a9aaeab1b9e84596657f958cba..687c5c8e436d275792ecc95f3c94735230d4b063 100644 --- a/Testing/SystemTests/tests/analysis/CodeConventions.py +++ b/Testing/SystemTests/tests/analysis/CodeConventions.py @@ -110,7 +110,7 @@ class Algorithms(stresstesting.MantidStressTest): def verifyProperty(self, alg_descr, name): upper = name.upper() - if (upper in SPECIAL_UPPER) and (not name in SPECIAL): + if (upper in SPECIAL_UPPER) and (name not in SPECIAL): index = SPECIAL_UPPER.index(upper) print alg_descr + " property (" + name + ") has special name "\ + "with wrong case: " + name + " should be " + SPECIAL[index] diff --git a/Testing/SystemTests/tests/analysis/ISISDirectReductionComponents.py b/Testing/SystemTests/tests/analysis/ISISDirectReductionComponents.py index 2b82a0bf7bdf8a2f0e9f4a74f7e47e96e8ee732a..2803fd76b482632523a48cf4ad275a60152077d4 100644 --- a/Testing/SystemTests/tests/analysis/ISISDirectReductionComponents.py +++ b/Testing/SystemTests/tests/analysis/ISISDirectReductionComponents.py @@ -34,7 +34,7 @@ class ISIS_ReductionWebLike(stresstesting.MantidStressTest): mr.web_var.advanced_vars['save_format']='nxs' # web services currently needs input file to be defined input_file = 'MAR11001.RAW' - dummy_rez = mr.main(input_file,web_var_folder) + mr.main(input_file,web_var_folder) # verify if result was indeed written self.rd.reducer.sample_run = input_file @@ -54,8 +54,7 @@ class ISIS_ReductionWebLike(stresstesting.MantidStressTest): if 'outWS' in mtd: return 'outWS' saveFileName = self.rd.reducer.save_file_name -#pylint: disable=unused-variable - outWS = Load(Filename=saveFileName+'.nxs') + Load(Filename=saveFileName+'.nxs', OutputWorkspace="outWS") #outWS *= 0.997979227566217 fullRezPath =FileFinder.getFullPath(saveFileName+'.nxs') os.remove(fullRezPath) @@ -188,7 +187,7 @@ class ISISLoadFilesMER(stresstesting.MantidStressTest): propman.load_monitors_with_workspace = False mon_ws = PropertyManager.sample_run.get_monitors_ws() - self.assertTrue(not mon_ws is None) + self.assertTrue(mon_ws is not None) ws = PropertyManager.sample_run.get_workspace() self.assertTrue(isinstance(ws,Workspace)) @@ -201,7 +200,7 @@ class ISISLoadFilesMER(stresstesting.MantidStressTest): propman.sample_run = 6398 mon_ws = PropertyManager.sample_run.get_monitors_ws() - self.assertTrue(not mon_ws is None) + self.assertTrue(mon_ws is not None) ws = PropertyManager.sample_run.get_workspace() self.assertTrue(isinstance(ws,Workspace)) self.assertEqual(ws.getNumberHistograms(),69641) @@ -211,7 +210,7 @@ class ISISLoadFilesMER(stresstesting.MantidStressTest): propman.det_cal_file = None mon_ws = PropertyManager.sample_run.get_monitors_ws() self.assertTrue('SR_MER018492' in mtd) - self.assertTrue(not mon_ws is None) + self.assertTrue(mon_ws is not None) ws = PropertyManager.sample_run.get_workspace() self.assertTrue(isinstance(ws,Workspace)) self.assertEqual(ws.getNumberHistograms(),69641) @@ -229,7 +228,7 @@ class ISISLoadFilesMER(stresstesting.MantidStressTest): propman.load_monitors_with_workspace = False propman.det_cal_file = None mon_ws = PropertyManager.sample_run.get_monitors_ws() - self.assertTrue(not mon_ws is None) + self.assertTrue(mon_ws is not None) self.assertTrue('SR_MER018492_monitors' in mtd) ws = PropertyManager.sample_run.get_workspace() @@ -287,7 +286,7 @@ class ISISLoadFilesLET(stresstesting.MantidStressTest): self.assertEqual(propman.ei_mon1_spec,40966) mon_ws = PropertyManager.sample_run.get_monitors_ws() - self.assertTrue(not mon_ws is None) + self.assertTrue(mon_ws is not None) self.assertTrue(isinstance(ws,IEventWorkspace)) self.assertEqual(ws.getNumberHistograms(),40960) diff --git a/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py b/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py index 537548af21c6229415eb8d952b8889826e6f08ec..2618f1e630fc52cc023b39b8a5756e407ddc30a5 100644 --- a/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py +++ b/Testing/SystemTests/tests/analysis/ISIS_LETReduction.py @@ -20,7 +20,7 @@ def find_binning_range(energy,ebin): """ InstrName = config['default.instrument'][0:3] - if not InstrName in ['MER','LET']: + if InstrName not in ['MER','LET']: InstrName = 'LET' if InstrName.find('LET')>-1: ls =25 diff --git a/Testing/SystemTests/tests/analysis/ImagingAggregateWavelengths.py b/Testing/SystemTests/tests/analysis/ImagingAggregateWavelengths.py index 10d0811cf9ca2f6a6d94f4adb065512993532cde..203c9baf428500496ff5165df7e71f572add7ab8 100644 --- a/Testing/SystemTests/tests/analysis/ImagingAggregateWavelengths.py +++ b/Testing/SystemTests/tests/analysis/ImagingAggregateWavelengths.py @@ -21,8 +21,7 @@ class ImagingAggregateTests(unittest.TestCase): self._raw_files_subdirs = [ 'wavelength_dependent_images/angle0/', 'wavelength_dependent_images/angle1/', 'wavelength_dependent_images/angle2/', - 'wavelength_dependent_images/angle5/' - ] + 'wavelength_dependent_images/angle5/'] self._out_dir = os.path.join(os.getcwd(), 'summed_wavelengths_metals') @@ -116,8 +115,7 @@ class ImagingAggregateWavelengths(stresstesting.MantidStressTest): 'wavelength_dependent_images/angle2/LARMOR00005330_Metals_000_01344.fits', 'wavelength_dependent_images/angle5/LARMOR00005333_Metals_000_00690.fits', 'wavelength_dependent_images/angle5/bogus.txt', - 'wavelength_dependent_images/angle5/more_bogus', - ] + 'wavelength_dependent_images/angle5/more_bogus'] def requiredFiles(self): return set(self._raw_in_files) diff --git a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py index 3b98795e5fbe33914daf277b0b2763cd4cbf4564..11761ea0ce70109a874c94c0f15d00150cbda3ef 100644 --- a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py +++ b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py @@ -28,8 +28,7 @@ class ImagingIMATTomoTests(unittest.TestCase): 'LARMOR00005329_Metals_000_SummedImg_2.fits', 'LARMOR00005330_Metals_000_SummedImg_3.fits', 'LARMOR00005331_Metals_000_SummedImg_4.fits', - 'LARMOR00005332_Metals_000_SummedImg_5.fits' - ] + 'LARMOR00005332_Metals_000_SummedImg_5.fits'] # a name for the stack / group of workspaces _data_wsname = 'small_img_stack' diff --git a/Testing/SystemTests/tests/analysis/LOQReductionGUI.py b/Testing/SystemTests/tests/analysis/LOQReductionGUI.py index 82d63d68f7231eed98009335b978a9a418f39074..3c0c489eafc574ba237b02b56eb5336984f15af1 100644 --- a/Testing/SystemTests/tests/analysis/LOQReductionGUI.py +++ b/Testing/SystemTests/tests/analysis/LOQReductionGUI.py @@ -16,7 +16,7 @@ class LOQMinimalBatchReduction(stresstesting.MantidStressTest): import SANSBatchMode as batch i.LOQ() i.MaskFile(MASKFILE) - fit_settings = batch.BatchReduce(BATCHFILE, '.nxs', combineDet='merged', saveAlgs={}) + batch.BatchReduce(BATCHFILE, '.nxs', combineDet='merged', saveAlgs={}) def validate(self): # note increased tolerance to something which quite high diff --git a/Testing/SystemTests/tests/analysis/LoadEmbeddedInstrumentInfo.py b/Testing/SystemTests/tests/analysis/LoadEmbeddedInstrumentInfo.py index 58f42b3ca0f49b776348d21615215980f47d147b..3ecf7b48060a9fb57409b55b03dd57767a6c1374 100644 --- a/Testing/SystemTests/tests/analysis/LoadEmbeddedInstrumentInfo.py +++ b/Testing/SystemTests/tests/analysis/LoadEmbeddedInstrumentInfo.py @@ -18,8 +18,7 @@ class ISISRawHistNexus(stresstesting.MantidStressTest): def runTest(self): # ISIS raw hist nexus file with A1_window at location (0,3,0) - #pylint: disable=unused-variable - MAPS00018314_raw_ISIS_hist = Load('MAPS00018314.nxs') + Load('MAPS00018314.nxs', OutputWorkspace='MAPS00018314_raw_ISIS_hist') def validate(self): MAPS00018314_raw_ISIS_hist = mtd['MAPS00018314_raw_ISIS_hist'] diff --git a/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py b/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py index 682f9a5e00a20dec4266a2b5a1972a5512316541..65f4d8b72818531dc546bbe81d9c087814f82c92 100644 --- a/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py +++ b/Testing/SystemTests/tests/analysis/LoadLotsOfFiles.py @@ -84,8 +84,7 @@ BANNED_FILES = ['80_tubes_Top_and_Bottom_April_2015.xml', 'USER_SANS2D_143ZC_2p4_4m_M4_Knowles_12mm.txt', 'USER_LARMOR_151B_LarmorTeam_80tubes_BenchRot1p4_M4_r3699.txt', 'Vesuvio_IP_file_test.par', - 'IP0004_10.par' - ] + 'IP0004_10.par'] EXPECTED_EXT = '.expected' @@ -180,7 +179,7 @@ class LoadLotsOfFiles(stresstesting.MantidStressTest): cur_index = datafiles.index(fname) except ValueError: continue - dummy_value = datafiles.pop(cur_index) + datafiles.pop(cur_index) datafiles.insert(insertion_index, fname) return datafiles @@ -196,7 +195,7 @@ class LoadLotsOfFiles(stresstesting.MantidStressTest): # Eval statement will use current scope. Allow access to # mantid module - import mantid + import mantid # noqa print "Found an expected file '%s' file" % expected expectedfile = open(expected) @@ -218,7 +217,6 @@ class LoadLotsOfFiles(stresstesting.MantidStressTest): print "----------------------------------------" print "Loading '%s'" % filename from mantid.api import Workspace - from mantid.api import IMDEventWorkspace # Output can be a tuple if the Load algorithm has extra output properties # but the output workspace should always be the first argument outputs = Load(filename) diff --git a/Testing/SystemTests/tests/analysis/PVPythonTest.py b/Testing/SystemTests/tests/analysis/PVPythonTest.py index ebee17161ce09ecf51d5a190fa0c11295938b862..24432256fde93f34aafb1ab8af6cba20bea840b5 100644 --- a/Testing/SystemTests/tests/analysis/PVPythonTest.py +++ b/Testing/SystemTests/tests/analysis/PVPythonTest.py @@ -2,10 +2,8 @@ import stresstesting from paraview.simple import * -#------------------------------------------------------------------------------------ class PVPythonTest(stresstesting.MantidStressTest): def runTest(self): - self.assertEquals(str(GetParaViewVersion()),'5.1') - + self.assertEqual(GetParaViewVersion().major, 5) diff --git a/Testing/SystemTests/tests/analysis/Peak2ConvCell_Test.py b/Testing/SystemTests/tests/analysis/Peak2ConvCell_Test.py index d5308f98b785a4e4a06ebda5b393b24a72b81591..7e7ab7cea60cc85c6ead2b3ff59c244e11df5e18 100644 --- a/Testing/SystemTests/tests/analysis/Peak2ConvCell_Test.py +++ b/Testing/SystemTests/tests/analysis/Peak2ConvCell_Test.py @@ -251,7 +251,7 @@ class Peak2ConvCell_Test(object): # (stresstesting.MantidStressTest): if celltype != 'H' or alpha > 120: # alpha =120 planar, >120 no go or c under a-b plane. - self.conventionalUB = NiggliUB = None + self.conventionalUB = None return None # Did not work with 0 error. FindUBUsingFFT failed @@ -367,7 +367,6 @@ class Peak2ConvCell_Test(object): # (stresstesting.MantidStressTest): def FixUpPlusMinus(self, UB): # TODO make increasing lengthed sides too M = matrix([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) - M1 = matrix([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) G = UB.T * UB #G.I @@ -497,9 +496,6 @@ class Peak2ConvCell_Test(object): # (stresstesting.MantidStressTest): Error = error * MinAbsQ npeaks = 0 - a1 = hkl[0, 0] - a2 = hkl[1, 0] - a3 = hkl[2, 0] done = False while not done: diff --git a/Testing/SystemTests/tests/analysis/RawVNexus.py b/Testing/SystemTests/tests/analysis/RawVNexus.py index 8cd74a8bc6402df82ef491c5b871772ddfefceb2..e5d59cb0ee5b78bc75513cdd4744b548bbe90006 100644 --- a/Testing/SystemTests/tests/analysis/RawVNexus.py +++ b/Testing/SystemTests/tests/analysis/RawVNexus.py @@ -7,7 +7,7 @@ class RawVNexus(stresstesting.MantidStressTest): ''' Simply tests that our LoadRaw and LoadISISNexus algorithms produce the same workspace''' def runTest(self): - Raw = LoadRaw(Filename='SANS2D00000808.raw') + LoadRaw(Filename='SANS2D00000808.raw', OutputWorkspace='Raw') def validate(self): return 'Raw','SANS2D00000808.nxs' diff --git a/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py b/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py index 733c5fb937fab5b32d114215d07abfcb3c2e6d8c..b72e11cd528c94d71e89443ada929b7bf218f8c9 100644 --- a/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py +++ b/Testing/SystemTests/tests/analysis/ReduceOneSCD_Run.py @@ -195,7 +195,7 @@ class ReduceOneSCD_Run( stresstesting.MantidStressTest): # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # - if (not cell_type is None) and (not centering is None) : + if (cell_type is not None) and (centering is not None) : self.run_conventional_matrix_file = self.output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".mat" # run_conventional_integrate_file = self.output_directory + "/" + run + "_" + \ diff --git a/Testing/SystemTests/tests/analysis/RelectometryInstrumentSignedThetaTest.py b/Testing/SystemTests/tests/analysis/RelectometryInstrumentSignedThetaTest.py index 6f53653f785367815e3396486324f712edc6e4db..452e18d42b9581694880357892877e03e8ae5562 100644 --- a/Testing/SystemTests/tests/analysis/RelectometryInstrumentSignedThetaTest.py +++ b/Testing/SystemTests/tests/analysis/RelectometryInstrumentSignedThetaTest.py @@ -27,7 +27,8 @@ class ReflectometryInstrumentSignedThetaTest(stresstesting.MantidStressTest): # Retrieve point detector from IDF (after translation) detector = theta_spectrum_axis.getInstrument().getComponentByName(detector_name) # Compare det-position * detector two theta with signed 2 theta (they should always be equal) - self.assertTrue(detector_vertical_position * theta_spectrum_axis.detectorTwoTheta(detector) == theta_spectrum_axis.detectorSignedTwoTheta(detector)) + self.assertTrue(detector_vertical_position * theta_spectrum_axis.detectorTwoTheta(detector) + == theta_spectrum_axis.detectorSignedTwoTheta(detector)) return True diff --git a/Testing/SystemTests/tests/analysis/SANS2DBatch.py b/Testing/SystemTests/tests/analysis/SANS2DBatch.py index 5cc8a92a46bd212b7075f7dffe579424ddea303d..b4cfda4a413e6c716507d252f096990f2db90880 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DBatch.py +++ b/Testing/SystemTests/tests/analysis/SANS2DBatch.py @@ -3,7 +3,6 @@ import stresstesting from mantid.simpleapi import * from ISISCommandInterface import * -from mantid.simpleapi import * from mantid import config from SANSBatchMode import * import os.path diff --git a/Testing/SystemTests/tests/analysis/SANS2DLimitEventsTime.py b/Testing/SystemTests/tests/analysis/SANS2DLimitEventsTime.py index 2adba6d3f704d9a845931cb57da0a5df10330ab7..76d389cc13590b71f86e90b9b8fc0177d53b9c29 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DLimitEventsTime.py +++ b/Testing/SystemTests/tests/analysis/SANS2DLimitEventsTime.py @@ -10,7 +10,7 @@ class SANS2DLimitEventsTime(stresstesting.MantidStressTest): SANS2D() MaskFile('MaskSANS2DReductionGUI_LimitEventsTime.txt') AssignSample('22048') - reduced = WavRangeReduction() + WavRangeReduction() def validate(self): self.disableChecking.append('SpectraMap') diff --git a/Testing/SystemTests/tests/analysis/SANS2DReductionGUI.py b/Testing/SystemTests/tests/analysis/SANS2DReductionGUI.py index 6a232658c955c980e22f429cff6e8228f3443b02..5a76d8cab1dafcd94193e2039918a8d1c1960dda 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DReductionGUI.py +++ b/Testing/SystemTests/tests/analysis/SANS2DReductionGUI.py @@ -13,12 +13,6 @@ The first 2 Tests ensures that the result provided by the GUI are the same for t Test was first created to apply to Mantid Release 3.0. """ -import sys - -if __name__ == "__main__": - # it is just to allow running this test in Mantid, allowing the following import - sys.path.append('/apps/mantid/systemtests/StressTestFramework/') - import stresstesting from mantid.simpleapi import * import isis_reducer @@ -49,7 +43,7 @@ class SANS2DMinimalBatchReduction(stresstesting.MantidStressTest): import SANSBatchMode as batch i.SANS2D() i.MaskFile(MASKFILE) - fit_settings = batch.BatchReduce(BATCHFILE,'.nxs', combineDet='rear') + batch.BatchReduce(BATCHFILE,'.nxs', combineDet='rear') def validate(self): self.disableChecking.append('Instrument') @@ -195,8 +189,6 @@ class SANS2DGUIBatchReduction(SANS2DMinimalBatchReduction): self.applyGUISettings() - _user_settings_copy = copy.deepcopy(i.ReductionSingleton().user_settings) - fit_settings={'scale':1.0,'shift':0.0} fit_settings = batch.BatchReduce(BATCHFILE,'.nxs', saveAlgs={}, reducer=i.ReductionSingleton().reference(),combineDet='rear') @@ -225,16 +217,10 @@ class SANS2DGUIReduction(SANS2DGUIBatchReduction): i.SetCentre('155.45','-169.6','front') SCATTER_SAMPLE, logvalues = i.AssignSample(r'SANS2D00022048.nxs', reload = True, period = 1) - dummy_1 = SCATTER_SAMPLE - dummy_2 = logvalues - i.SetCentre('155.45','-169.6','rear') i.SetCentre('155.45','-169.6','front') SCATTER_SAMPLE, logvalues = i.AssignCan(r'SANS2D00022023.nxs', reload = True, period = 1) - dummy_3 = SCATTER_SAMPLE - dummy_4 = logvalues - t1, t2 = i.TransmissionSample(r'SANS2D00022041.nxs', r'SANS2D00022024.nxs', period_t=1, period_d=1) t1, t2 = i.TransmissionCan(r'SANS2D00022024.nxs', r'SANS2D00022024.nxs', period_t=1, period_d=1) diff --git a/Testing/SystemTests/tests/analysis/SANS2DReductionGUIAdded.py b/Testing/SystemTests/tests/analysis/SANS2DReductionGUIAdded.py index 194d9cac48864c159dccd9282c7529150c8a3191..c94f1aa7064287617b81cd83e2e74443fed05169 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DReductionGUIAdded.py +++ b/Testing/SystemTests/tests/analysis/SANS2DReductionGUIAdded.py @@ -1,10 +1,4 @@ #pylint: disable=invalid-name -import sys - -if __name__ == "__main__": - # it is just to allow running this test in Mantid, allowing the following import - sys.path.append('/apps/mantid/systemtests/StressTestFramework/') - from mantid.simpleapi import * import ISISCommandInterface as i import copy diff --git a/Testing/SystemTests/tests/analysis/SANS2DSearchCentreGUI.py b/Testing/SystemTests/tests/analysis/SANS2DSearchCentreGUI.py index f6d2a653b1ed4c14fd9c51aa6320d27c14db09bc..c6619f5e092c1d1871cb9bed6f4c7636da53e394 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DSearchCentreGUI.py +++ b/Testing/SystemTests/tests/analysis/SANS2DSearchCentreGUI.py @@ -1,8 +1,4 @@ #pylint: disable=invalid-name -import sys -if __name__ == "__main__": - # it is just to allow running this test in Mantid, allowing the following import - sys.path.append('/apps/mantid/systemtests/StressTestFramework/') from mantid.simpleapi import * import ISISCommandInterface as i import isis_reducer diff --git a/Testing/SystemTests/tests/analysis/SANS2DSlicing.py b/Testing/SystemTests/tests/analysis/SANS2DSlicing.py index 5e7d07e67c0073bb5007c300a97fd87b6ba77b9a..0b78a2ce374744f21aceb3bd4cc9bf6176503777 100644 --- a/Testing/SystemTests/tests/analysis/SANS2DSlicing.py +++ b/Testing/SystemTests/tests/analysis/SANS2DSlicing.py @@ -1,9 +1,4 @@ #pylint: disable=invalid-name,attribute-defined-outside-init -import sys - -if __name__ == "__main__": - # it is just to allow running this test in Mantid, allowing the following import - sys.path.append('/apps/mantid/systemtests/StressTestFramework/') import stresstesting @@ -24,7 +19,7 @@ class SANS2DMinimalBatchReductionSliced(stresstesting.MantidStressTest): i.SANS2D() i.MaskFile(MASKFILE) i.SetEventSlices("0.0-451, 5-10") - fit_settings = batch.BatchReduce(BATCHFILE, '.nxs',saveAlgs={}, combineDet='rear') + batch.BatchReduce(BATCHFILE, '.nxs',saveAlgs={}, combineDet='rear') def validate(self): self.tolerance = 0.02 diff --git a/Testing/SystemTests/tests/analysis/SANSDarkRunSubtractionTest.py b/Testing/SystemTests/tests/analysis/SANSDarkRunSubtractionTest.py index 58ead5b03c26d6de8a7a0e41987ee0aedb3bd6f4..81bb671ed5b9179c06399bfe492ce3dfd1f89918 100644 --- a/Testing/SystemTests/tests/analysis/SANSDarkRunSubtractionTest.py +++ b/Testing/SystemTests/tests/analysis/SANSDarkRunSubtractionTest.py @@ -85,14 +85,10 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) - - for i in range(0, scatter_workspace.getNumberHistograms()): - self.assertTrue(all_entries_zero(scatter_workspace, i), "Detector entries should all be 0") + self.assertFalse(scatter_workspace.extractY().any(), "Detector entries should all be 0") # The monitors should not be affected, but we only have data in ws_index 0-3 - for i in [0,3]: - self.assertFalse(all_entries_zero(monitor_workspace, i), "Monitor entries should not all be 0") + self.assertTrue(monitor_workspace.extractY()[:,0:3].any(), "Monitor entries should not all be 0") def test_that_subtracts_with_correct_single_dark_run_and_multiple_settings(self): # Arrange @@ -124,16 +120,14 @@ class DarkRunSubtractionTest(unittest.TestCase): # Expect all entries to be 0 except for monitor 0. We selected monitor 1 and all detectors # for the subtraction. Hence only moniotr 0 would have been spared. - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) - for i in range(0, scatter_workspace.getNumberHistograms()): - self.assertTrue(all_entries_zero(scatter_workspace, i), "Detector entries should all be 0") + self.assertFalse(scatter_workspace.extractY().any(), "Detector entries should all be 0") for i in [0,2,3]: - self.assertFalse(all_entries_zero(monitor_workspace, i), "Monitor entries should not all be 0") + self.assertTrue(monitor_workspace.dataY(i).any(), "Monitor entries should not all be 0") for i in ws_index2: - self.assertTrue(all_entries_zero(monitor_workspace, i), "Entries should all be 0") + self.assertFalse(monitor_workspace.dataY(i).any(), "Entries should all be 0") def test_that_subtracts_correct_added_file_type(self): # Arrange @@ -160,14 +154,12 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) - for i in range(0, scatter_workspace.getNumberHistograms()): - self.assertTrue(all_entries_zero(scatter_workspace, i), "Detector entries should all be 0") + self.assertFalse(scatter_workspace.extractY().any(), "Detector entries should all be 0") # The monitors should not be affected, but we only have data in ws_index 0-3 for i in [0,3]: - self.assertFalse(all_entries_zero(monitor_workspace, i), "Monitor entries should not all be 0") + self.assertTrue(monitor_workspace.dataY(i).any(), "Monitor entries should not all be 0") os.remove(os.path.join(config['defaultsave.directory'],run_number)) @@ -198,21 +190,17 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # Some spectra might be zero, so we have to check that there is something which is not zero - all_detectors_zero = True - for i in range(0, scatter_workspace.getNumberHistograms()): - all_detectors_zero = all_detectors_zero & all_entries_zero(scatter_workspace, i) - self.assertFalse(all_detectors_zero, "There should be some detectors which are not zero") + self.assertTrue(scatter_workspace.extractY().any(), "There should be some detectors which are not zero") # The monitors should not be affected, but we only have data in ws_index 0-3 for i in [0,2,3]: - self.assertFalse(all_entries_zero(monitor_workspace, i), "Monitor1, Monitor3, Monitor4 entries should not all be 0") + self.assertTrue(monitor_workspace.dataY(i).any(), "Monitor1, Monitor3, Monitor4 entries should not all be 0") # Monitor 2 (workspace index 1 should be 0 for i in ws_index: - self.assertTrue(all_entries_zero(monitor_workspace, i), "Monitor2 entries should all be 0") + self.assertFalse(monitor_workspace.dataY(i).any(), "Monitor2 entries should all be 0") os.remove(os.path.join(config['defaultsave.directory'],run_number)) @@ -238,21 +226,17 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # Some spectra might be zero, so we have to check that there is something which is not zero - all_detectors_zero = True - for i in range(0, scatter_workspace.getNumberHistograms()): - all_detectors_zero = all_detectors_zero & all_entries_zero(scatter_workspace, i) - self.assertFalse(all_detectors_zero, "There should be some detectors which are not zero") + self.assertTrue(scatter_workspace.extractY().any(), "There should be some detectors which are not zero") # The monitors should not be affected, but we only have data in ws_index 0-3 for i in [0,2,3]: - self.assertFalse(all_entries_zero(monitor_workspace, i), "Monitor1, Monitor3, Monitor4 entries should not all be 0") + self.assertTrue(monitor_workspace.dataY(i).any(), "Monitor1, Monitor3, Monitor4 entries should not all be 0") # Monitor 1 should be 0 for i in ws_index: - self.assertTrue(all_entries_zero(monitor_workspace, i), "Monitor2 entries should all be 0") + self.assertFalse(monitor_workspace.dataY(i).any(), "Monitor2 entries should all be 0") def test_that_subtracts_correct_for_transmission_workspace_with_only_monitors(self): # Arrange @@ -277,15 +261,14 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # We only have monitors in our transmission file, monitor 2 should be 0 for i in [0,2,3]: - self.assertFalse(all_entries_zero(transmission_workspace, i), "Monitor1, Monitor3, Monitor4 entries should not all be 0") + self.assertTrue(transmission_workspace.dataY(i).any(), "Monitor1, Monitor3, Monitor4 entries should not all be 0") # Monitor2 should be 0 for i in ws_index: - self.assertTrue(all_entries_zero(transmission_workspace, i), "Monitor2 entries should all be 0") + self.assertFalse(transmission_workspace.dataY(i).any(), "Monitor2 entries should all be 0") def test_that_subtracts_nothing_when_selecting_detector_subtraction_for_transmission_workspace_with_only_monitors(self): # Arrange @@ -309,12 +292,11 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # We only have monitors in our transmission file for i in [0,1,2,3]: - self.assertFalse(all_entries_zero(transmission_workspace, i), - ("Monitor1, Monitor2, Monitor3 and Monitor4 entries should not all be 0")) + self.assertTrue(transmission_workspace.dataY(i).any(), + ("Monitor1, Monitor2, Monitor3 and Monitor4 entries should not all be 0")) def test_that_subtracts_monitors_and_detectors_for_transmission_workspace_with_monitors_and_detectors(self): # Arrange @@ -351,20 +333,19 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # We only have monitors in our transmission file, monitor 1 should be 0 for i in [0,2,3]: - self.assertFalse(all_entries_zero(transmission_workspace, i), "Monitor0, Monitor2, Monitor3 entries should not all be 0") + self.assertTrue(transmission_workspace.dataY(i).any(), "Monitor0, Monitor2, Monitor3 entries should not all be 0") # Monitor 2 should be set to 0 for i in ws_index2: - self.assertTrue(all_entries_zero(transmission_workspace, i), "Monitor2 entries should be 0") + self.assertFalse(transmission_workspace.dataY(i).any(), "Monitor2 entries should be 0") # Detectors should be set to 0 detector_indices = range(4,14) for i in detector_indices: - self.assertTrue(all_entries_zero(transmission_workspace, i), "All detectors entries should be 0") + self.assertFalse(transmission_workspace.dataY(i).any(), "All detectors entries should be 0") def test_that_subtracts_monitors_only_for_transmission_workspace_with_monitors_and_detectors(self): # Arrange @@ -392,22 +373,17 @@ class DarkRunSubtractionTest(unittest.TestCase): # Since in this test we use the same file for the scatterer and the dark run, we expect # that the detectors are 0. This is because we subtract bin by bin when using UAMP - all_entries_zero = lambda ws, index : all([0.0 == element for element in ws.dataY(index)]) # We only have monitors in our transmission file, monitor 1 should be 0 for i in [0,2,3]: - self.assertFalse(all_entries_zero(transmission_workspace, i), "Monitor0, Monitor2, Monitor3 entries should not all be 0") + self.assertTrue(transmission_workspace.dataY(i).any(), "Monitor0, Monitor2, Monitor3 entries should not all be 0") # Monitor 2 should be set to 0 for i in ws_index: - self.assertTrue(all_entries_zero(transmission_workspace, i), "Monitor2 entries should be 0") + self.assertFalse(transmission_workspace.dataY(i).any(), "Monitor2 entries should be 0") # Detectors should NOT all be set to 0 - detector_indices = set(range(0, transmission_workspace.getNumberHistograms())) - set(range(0,8)) - all_detectors_zero = True - for i in detector_indices: - all_detectors_zero = all_detectors_zero & all_entries_zero(transmission_workspace, i) - self.assertFalse(all_detectors_zero, "There should be some detectors which are not zero") + self.assertTrue(transmission_workspace.extractY().any(), "There should be some detectors which are not zero") #------- HELPER Methods def _do_test_valid(self, settings, is_input_event= True, run_number = None) : diff --git a/Testing/SystemTests/tests/analysis/SANSWorkspaceTypeTest.py b/Testing/SystemTests/tests/analysis/SANSWorkspaceTypeTest.py index 8410a66aaf8245240b90f8c258c247af38eb861e..53a8a428eca473f65890a64637bf60646604d5ec 100644 --- a/Testing/SystemTests/tests/analysis/SANSWorkspaceTypeTest.py +++ b/Testing/SystemTests/tests/analysis/SANSWorkspaceTypeTest.py @@ -7,7 +7,7 @@ import os # WORKAROUND FOR IMPORT ISSUE IN UBUNTU --- START CAN_IMPORT_NXS_TEST = True try: - import nxs # pylint: disable=unused-import + import nxs # pylint: disable=unused-import # noqa except ImportError: CAN_IMPORT_NXS_TEST = False # WORKAROUND FOR IMPORT ISSUE IN UBUNTU --- STOP diff --git a/Testing/SystemTests/tests/analysis/ValidateFacilitiesFile.py b/Testing/SystemTests/tests/analysis/ValidateFacilitiesFile.py index a77bf66c29831f2cf2fc3903417e8a2cfd71c0d1..9220c37a17b9e78f06f3eaba1c67637dd3b5d47e 100644 --- a/Testing/SystemTests/tests/analysis/ValidateFacilitiesFile.py +++ b/Testing/SystemTests/tests/analysis/ValidateFacilitiesFile.py @@ -11,15 +11,13 @@ class ValidateFacilitiesFile(stresstesting.MantidStressTest): def skipTests(self): try: - import genxmlif - import minixsv + import minixsv # noqa except ImportError: return True return False def runTest(self): """Main entry point for the test suite""" - from genxmlif import GenXmlIfError from minixsv import pyxsval direc = config['instrumentDefinition.directory'] filename = os.path.join(direc,'Facilities.xml') diff --git a/Testing/SystemTests/tests/analysis/ValidateGroupingFiles.py b/Testing/SystemTests/tests/analysis/ValidateGroupingFiles.py index e2fdf124a649bb0d2932794cd86ba988a724c991..70de8fc3845747d75296ee1a9d81e8bf47399f0a 100644 --- a/Testing/SystemTests/tests/analysis/ValidateGroupingFiles.py +++ b/Testing/SystemTests/tests/analysis/ValidateGroupingFiles.py @@ -13,8 +13,7 @@ class ValidateGroupingFiles(stresstesting.MantidStressTest): def skipTests(self): try: - import genxmlif - import minixsv + import minixsv # noqa except ImportError: return True return False @@ -35,7 +34,6 @@ class ValidateGroupingFiles(stresstesting.MantidStressTest): def runTest(self): """Main entry point for the test suite""" - from genxmlif import GenXmlIfError from minixsv import pyxsval direc = config['instrumentDefinition.directory'] self.xsdFile = os.path.join(direc,'Schema/Grouping/1.0/','GroupingSchema.xsd') diff --git a/Testing/SystemTests/tests/analysis/ValidateInstrumentDefinitionFiles.py b/Testing/SystemTests/tests/analysis/ValidateInstrumentDefinitionFiles.py index 768206aaa656a70ed8ded2ea432e52ccda0944d7..ba4704aa4338846255cebc41ac66990c184132f0 100644 --- a/Testing/SystemTests/tests/analysis/ValidateInstrumentDefinitionFiles.py +++ b/Testing/SystemTests/tests/analysis/ValidateInstrumentDefinitionFiles.py @@ -17,8 +17,8 @@ class ValidateInstrumentDefinitionFiles(stresstesting.MantidStressTest): def skipTests(self): try: - from genxmlif import GenXmlIfError - from minixsv import pyxsval + from genxmlif import GenXmlIfError # noqa + from minixsv import pyxsval # noqa except ImportError: return True return False diff --git a/Testing/SystemTests/tests/analysis/ValidateParameterFiles.py b/Testing/SystemTests/tests/analysis/ValidateParameterFiles.py index 14aa9a78b200ad1439245f368aa7466bf6c0ee16..084e52746e735fcc744290a1ea074c6d4bbcccb3 100644 --- a/Testing/SystemTests/tests/analysis/ValidateParameterFiles.py +++ b/Testing/SystemTests/tests/analysis/ValidateParameterFiles.py @@ -13,8 +13,8 @@ class ValidateParameterFiles(stresstesting.MantidStressTest): def skipTests(self): try: - from genxmlif import GenXmlIfError - from minixsv import pyxsval + from genxmlif import GenXmlIfError # noqa + from minixsv import pyxsval # noqa except ImportError: return True return False @@ -34,7 +34,7 @@ class ValidateParameterFiles(stresstesting.MantidStressTest): def runTest(self): """Main entry point for the test suite""" - from minixsv import pyxsval + from minixsv import pyxsval # noqa direc = config['instrumentDefinition.directory'] print direc self.xsdFile = os.path.join(direc,'Schema/ParameterFile/1.0/','ParameterFileSchema.xsd') diff --git a/Testing/SystemTests/tests/analysis/WeightedLeastSquaresTest.py b/Testing/SystemTests/tests/analysis/WeightedLeastSquaresTest.py index 1e1e038eecc35e84b1eb233016e292712a23d3a5..0233cac36fa657a346e04f0c7f06c4483775d46f 100644 --- a/Testing/SystemTests/tests/analysis/WeightedLeastSquaresTest.py +++ b/Testing/SystemTests/tests/analysis/WeightedLeastSquaresTest.py @@ -219,8 +219,7 @@ class VanadiumPatternFromENGINXSmoothing(unittest.TestCase): 103.07539466368209, 88.69333062995749, 73.2453746596794, 57.94761712646885, 46.150107399338026, 33.49607446438909, 27.023391825663943, 19.660388795715143, 14.846016985914035, 9.65919973049868, 5.724008517073549, 1.9527932349469075, - -0.9197805852038337, 10.656047152998436, 0.0 - ] + -0.9197805852038337, 10.656047152998436, 0.0] # Note: ignoring parameter errors. Note the higher tolerance so that it works on all platforms fitted_params, _ = run_fit(self.workspace, function_definition) @@ -234,8 +233,7 @@ class VanadiumPatternFromENGINXSmoothing(unittest.TestCase): expected_params = [575.5043460508207, -362.0695583401004, 722.7394915082397, 2621.9749776340186, 1572.450059153195, 836.417481475315, 361.6875979793134, 240.00983642384153, 132.46098325093416, 63.95362315830608, 17.41805806345004, 0.8684078907341928, - -5.204195324981802 - ] + -5.204195324981802] # Note: ignoring parameter errors. Note the higher tolerance so that it works on all platforms fitted_params, _ = run_fit(self.workspace, function_definition) diff --git a/Testing/SystemTests/tests/analysis/WishMasking.py b/Testing/SystemTests/tests/analysis/WishMasking.py index 5550bf62119ba1b26c6f406fc885100d28731177..b34e9bd7fdb5366cf9627e31b79a0f9cc705ffa7 100644 --- a/Testing/SystemTests/tests/analysis/WishMasking.py +++ b/Testing/SystemTests/tests/analysis/WishMasking.py @@ -21,7 +21,7 @@ class WishMasking(stresstesting.MantidStressTest): try: index = int(line_contents[0].strip()) select = int(line_contents[3].strip()) - dummy_group = int(line_contents[4].strip()) + int(line_contents[4].strip()) if index == requested_index: return select except ValueError: diff --git a/Testing/SystemTests/tests/analysis/utils.py b/Testing/SystemTests/tests/analysis/utils.py index ac5f7fdcd978614303d673e4f5a48c2c7c4ee2c9..b96857118b229ee480557f663674d8dd5535d04f 100644 --- a/Testing/SystemTests/tests/analysis/utils.py +++ b/Testing/SystemTests/tests/analysis/utils.py @@ -1,9 +1,9 @@ #pylint: disable=invalid-name -''' SVN Info: The variables below will only get subsituted at svn checkout if - the repository is configured for variable subsitution. +''' SVN Info: The variables below will only get subsituted at svn checkout if + the repository is configured for variable subsitution. - $Id$ - $HeadURL$ + $Id$ + $HeadURL$ |=============================================================================|=======| 1 80 <tab> ''' diff --git a/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp b/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp index 5e707eeb4572bb56f0ec6d63f0e8bfd438c665cb..8174343d80934e226a70887cfbe33e5f02958735 100644 --- a/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp +++ b/Vates/VatesSimpleGui/ViewWidgets/src/MdViewerWidget.cpp @@ -14,6 +14,7 @@ #include "MantidKernel/Logger.h" #include "MantidKernel/UsageService.h" #include "MantidQtAPI/InterfaceManager.h" +#include "MantidQtAPI/MantidDesktopServices.h" #include "MantidQtAPI/MdConstants.h" #include "MantidQtAPI/MdSettings.h" #include "MantidQtAPI/TSVSerialiser.h" @@ -111,7 +112,6 @@ #endif #include <QAction> -#include <QDesktopServices> #include <QDragEnterEvent> #include <QDropEvent> #include <QHBoxLayout> @@ -1404,8 +1404,8 @@ void MdViewerWidget::onRotationPoint() { * browser. */ void MdViewerWidget::onWikiHelp() { - QDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") + - "VatesSimpleInterface_v2")); + MantidDesktopServices::openUrl(QUrl(QString("http://www.mantidproject.org/") + + "VatesSimpleInterface_v2")); } /** diff --git a/buildconfig/CMake/conda.cmake b/buildconfig/CMake/conda.cmake index 9ff8accbc1abe7fbb7cc96c660853b20968646b1..25d5df0375c06885400a6e5da58693b00db06051 100644 --- a/buildconfig/CMake/conda.cmake +++ b/buildconfig/CMake/conda.cmake @@ -1,7 +1,7 @@ set(CONDA_WORKDIR "conda-packaging") -configure_file(buildconfig/CMake/conda-update-recipe.py.in ${CONDA_WORKDIR}/conda-update-recipe.py) +configure_file(buildconfig/CMake/conda_update_recipe.py.in ${CONDA_WORKDIR}/conda_update_recipe.py) add_custom_target( conda-update-recipe - COMMAND python conda-update-recipe.py + COMMAND python conda_update_recipe.py WORKING_DIRECTORY ${CONDA_WORKDIR} ) diff --git a/buildconfig/CMake/conda-update-recipe.py.in b/buildconfig/CMake/conda_update_recipe.py.in similarity index 55% rename from buildconfig/CMake/conda-update-recipe.py.in rename to buildconfig/CMake/conda_update_recipe.py.in index 41e54936783860fef4446bb41af8a1b6e683ea91..1723c8781dc19f9d74da3bbe5b77fffa79eabbfa 100644 --- a/buildconfig/CMake/conda-update-recipe.py.in +++ b/buildconfig/CMake/conda_update_recipe.py.in @@ -5,17 +5,24 @@ git_rev = "@MtdVersion_WC_LAST_CHANGED_SHA_LONG@" import subprocess as sp, shlex, os -def main(): +def checkout(repo_path): # checkout recipe - if not os.path.exists('conda-recipes'): + if not os.path.exists(repo_path): cmd = 'git clone git@github.com:mantidproject/conda-recipes' sp.check_call(cmd.split()) else: cmd = 'git pull' - sp.check_call(cmd.split(), cwd='conda-recipes') + sp.check_call(cmd.split(), cwd=repo_path) + return + +def update_meta_yaml(repo_path, recipe_path=None): + "return: True if updated" + recipe_path = recipe_path or 'framework' + if not os.path.isabs(recipe_path): + recipe_path = os.path.join(repo_path, recipe_path) # change framework meta.yaml - path = 'conda-recipes/framework/meta.yaml' + path = os.path.join(recipe_path, 'meta.yaml') header = [] header.append('{% set version = "' + '%s' % version + '" %}') header.append('{% set git_rev = "' + '%s' % git_rev + '" %}') @@ -25,16 +32,32 @@ def main(): # if nothing changed just exit if header == old_header: print "Nothing changed. Skipping." - return + return False open(path, 'wt').write('\n'.join(header+body)) + return True + +def commit(repo_path): # commit cmd = 'git commit -m "update version and git_rev" framework/meta.yaml' - sp.check_call(shlex.split(cmd), cwd="conda-recipes") + sp.check_call(shlex.split(cmd), cwd=repo_path) + return + +def push(repo_path): # push cmd = 'git push' - sp.check_call(cmd.split(), cwd="conda-recipes") + sp.check_call(cmd.split(), cwd=repo_path) return + +def main(): + repo_path = 'conda-recipes' + checkout(repo_path) + if update_meta_yaml(repo_path): + commit(repo_path) + push(repo_path) + return + + if __name__ == '__main__': main() diff --git a/buildconfig/dev-packages/rpm/mantid-developer/mantid-developer.spec b/buildconfig/dev-packages/rpm/mantid-developer/mantid-developer.spec index 4f5e0580c079423e19e368957e2ba729b235c52a..1224556100e5e39069e98b6e675f30464951b4eb 100644 --- a/buildconfig/dev-packages/rpm/mantid-developer/mantid-developer.spec +++ b/buildconfig/dev-packages/rpm/mantid-developer/mantid-developer.spec @@ -1,5 +1,5 @@ Name: mantid-developer -Version: 1.18 +Version: 1.19 Release: 1%{?dist} Summary: Meta Package to install dependencies for Mantid Development @@ -31,7 +31,11 @@ Requires: muParser-devel Requires: mxml-devel Requires: nexus >= 4.2 Requires: nexus-devel >= 4.2 +%if 0%{?el6} +Requires: ninja +%else Requires: ninja-build +%endif Requires: numpy Requires: OCE-devel Requires: poco-devel >= 1.4.6 @@ -41,7 +45,7 @@ Requires: python-ipython >= 1.1 %{?el6:Conflicts: python-ipython >= 2.0} Requires: python-matplotlib %{?fedora:Requires: python2-matplotlib-qt4} -%{?rhel:Requires: python-matplotlib-qt4} +%{?el7:Requires: python-matplotlib-qt4} Requires: python-pip Requires: python-sphinx Requires: python-sphinx-theme-bootstrap diff --git a/docs/source/algorithms/BASISReduction-v1.rst b/docs/source/algorithms/BASISReduction-v1.rst index 8bada309a3d6d740ca0daefa2524c3b4928c81d9..93417d59abbe7e5273758911335ea38ec0881c25 100644 --- a/docs/source/algorithms/BASISReduction-v1.rst +++ b/docs/source/algorithms/BASISReduction-v1.rst @@ -52,15 +52,15 @@ There are typical values for the properties of each reflection: | silicon311 | -740, 1.6, 740 | 0.5, 0.2, 3.7 | +------------+----------------+------------------------+ -Also the following mask files are associated to each reflection: - -+-----------+------------------------------------------------------------------------------------------------+ -|Reflection | Mask file | -+===========+================================================================================================+ -|silicon111 | BASIS_Mask_ThreeQuartersRemain_SouthTop_NorthTop_NorthBottom_MorePixelsEliminated_08122015.xml | -+-----------+------------------------------------------------------------------------------------------------+ -|silicon311 | BASIS_Mask_OneQuarterRemains_SouthBottom.xml | -+-----------+------------------------------------------------------------------------------------------------+ +Also the following default mask files are associated to each reflection: + ++-----------+----------------------------+ +|Reflection | Mask file | ++===========+============================+ +|silicon111 | BASIS_Mask_default_111.xml | ++-----------+----------------------------+ +|silicon311 | BASIS_Mask_default_311.xml | ++-----------+----------------------------+ These mask files can be found in the SNS filesystem (**/SNS/BSS/shared/autoreduce/new_masks_08_12_2015/**) diff --git a/docs/source/algorithms/CalculateFlatBackground-v1.rst b/docs/source/algorithms/CalculateFlatBackground-v1.rst index 9c33f07c1e05eff40bbefbd778cf9a1bd1b6cb41..391ceee444f1d927ffb2e9b3348705ad3f526564 100644 --- a/docs/source/algorithms/CalculateFlatBackground-v1.rst +++ b/docs/source/algorithms/CalculateFlatBackground-v1.rst @@ -9,18 +9,23 @@ Description ----------- -This algorithm takes a list of spectra and for each spectrum calculates -an average count rate in the given region, usually a region when there -are only background neutrons. This count rate is then subtracted from -the counts in all the spectrum's bins. However, no bin will take a -negative value as bins with count rates less than the background are set -to zero (and their error is set to the backgound value). - -The average background count rate is estimated in one of two ways. When -*Mode* is set to "Mean" it is the sum of the values in the bins in the -background region divided by the width of the X range. Selecting "Linear -Fit" sets the background value to the height in the centre of the -background region of a line of best fit through that region. +This algorithm takes a list of spectra and for each spectrum +calculates an average count rate in a region, usually a region when +there are only background neutrons. This count rate is then +subtracted from the counts in all the spectrum's bins. However, no +bin will take a negative value as bins with count rates less than +the background are set to zero (and their error is set to the +backgound value). + +The average background count rate is estimated in one of three ways. +When *Mode* is set to "Mean" it is the sum of the values in the bins +in the background region divided by the width of the X range. +Selecting "Linear Fit" sets the background value to the height in +the centre of the background region of a line of best fit through +that region. The "Averaging Window" *Mode* in turn calculates a +moving window average over each spectrum and takes the minimum as +the background. The values of the bins half-*AveragingWindowWidth* +from the beginning and end of a spectrum are taken as-is. The error on the background value is only calculated when "Mean" is used. It is the errors in all the bins in the background region summed @@ -78,6 +83,40 @@ Output: Calculated Mean background: [ 3. 3. 3. 3. 3.] +**Example - Returning background using Moving Average:** + +.. testcode:: ExReturnMovingAverage + + import numpy as np + from scipy.constants import pi + + def spectrum(x): + # A fancy triple-peak-shaped spectrum + z = x / 10.0 - 0.5 + return np.sin(5.5 * (z + 0.1) * pi) + 2.0 * np.exp(-((z / 0.1)**2)) + 1.0 + + # Equidistant x grid. Represents bin boundaries + x = np.arange(0.5, 9.1, 0.2) + # y is a bin shorter than x and has to be evaluated at bin centres. + y = spectrum(x[:-1] + 0.5 * (x[1] - x[0])) + input = CreateWorkspace(x,y) + + output = CalculateFlatBackground('input', + AveragingWindowWidth=3, + Mode='Moving Average', + OutputMode='Return Background') + + print('Background using moving window average: {0:.4}'.format(output.readY(0)[0])) + print('True minimum: {0:.4}'.format(np.amin(input.readY(0)))) + +Output: + +.. testoutput:: ExReturnMovingAverage + + Background using moving window average: 0.09483 + True minimum: 0.04894 + + .. categories:: .. sourcelink:: diff --git a/docs/source/algorithms/CalculateSampleTransmission-v1.rst b/docs/source/algorithms/CalculateSampleTransmission-v1.rst index cd732afa6d0e00f1c103d000e4caad819452ec83..2bb695aacbe47e286a70328df6f576f11f285ba7 100644 --- a/docs/source/algorithms/CalculateSampleTransmission-v1.rst +++ b/docs/source/algorithms/CalculateSampleTransmission-v1.rst @@ -14,8 +14,8 @@ given wavelength range. The sample chemical formula is input for the :ref:`SetSampleMaterial <algm-SetSampleMaterial>` algorithm to calculate the cross-sections. The sample -number density & thickness is input to then calculate the percentage scattering -& transmission. +mass density/number density & thickness is input to then calculate the percentage +scattering & transmission. A flat plate sample which is perpendicular to the beam is assumed. @@ -37,8 +37,8 @@ Output: .. testoutput:: ExCalculateSampleTransmissionSimple - Transmission: 0.568102, 0.567976, 0.567851 ... - Scattering: 0.429309, 0.429309, 0.429309 ... + Transmission: 0.981276, 0.981268, 0.981261 ... + Scattering: 0.018575, 0.018575, 0.018575 ... **Example - Running CalculateSampleTransmission with a specified number density and thickness.** @@ -47,7 +47,8 @@ Output: ws = CalculateSampleTransmission(WavelengthRange='2.0, 0.1, 10.0', ChemicalFormula='H2-O', - NumberDensity=0.2, + DensityType='Number Density', + Density=0.2, Thickness=0.58) print 'Transmission: %f, %f, %f ...' % tuple(ws.readY(0)[:3]) diff --git a/docs/source/algorithms/IndirectTransmission-v1.rst b/docs/source/algorithms/IndirectTransmission-v1.rst index 952bb8584dc0870db85acbb0c4e8007ec64e1db3..670956e5d9bad123fefb5c3539b1b61b31c92916 100644 --- a/docs/source/algorithms/IndirectTransmission-v1.rst +++ b/docs/source/algorithms/IndirectTransmission-v1.rst @@ -16,8 +16,8 @@ substantial. The sample chemical formula is input for the :ref:`SetSampleMaterial <algm-SetSampleMaterial>` algorithm to calculate the cross-sections. The instrument analyser reflection is selected to obtain the wavelength of the -elastic peak to calculate the absorption cross-section. The sample number -density & thickness is input to then calculate the percentage scattering & +elastic peak to calculate the absorption cross-section. The sample mass +density/number density & thickness is input to then calculate the percentage scattering & transmission. Usage @@ -43,16 +43,16 @@ Output: Coherent Xsection : 5.551 Incoherent Xsection : 0.001 Total scattering Xsection : 5.552 - Number density : 0.1 + Number density : 0.00501398069222 Thickness : 0.1 - Transmission (abs+scatt) : 0.945870519609 - Total scattering : 0.0540068963808 + Transmission (abs+scatt) : 0.997213629421 + Total scattering : 0.00277989100754 **Example - Running IndirectTransmission with a specified number density and thickness.** .. testcode:: ExIndirectTransmissionParams - table_ws = IndirectTransmission(Instrument='OSIRIS', NumberDensity=0.5, Thickness=0.3, ChemicalFormula="C") + table_ws = IndirectTransmission(Instrument='OSIRIS', DensityType='Number Density', Density=0.5, Thickness=0.3, ChemicalFormula="C") param_names = table_ws.column(0) param_values = table_ws.column(1) diff --git a/docs/source/algorithms/Rebin-v1.rst b/docs/source/algorithms/Rebin-v1.rst index e6519ed3f115defb22de5aa6302897fb8cce703a..2e50eefa0b95588a5506587a284bc6d8802de82c 100644 --- a/docs/source/algorithms/Rebin-v1.rst +++ b/docs/source/algorithms/Rebin-v1.rst @@ -196,3 +196,5 @@ Output: .. categories:: .. sourcelink:: + :h: Framework/Algorithms/inc/MantidAlgorithms/Rebin.h + :cpp: Framework/Algorithms/src/Rebin.cpp diff --git a/docs/source/images/MuonAnalysisDevDocs/MUSR22725-fwd.png b/docs/source/images/MuonAnalysisDevDocs/MUSR22725-fwd.png new file mode 100644 index 0000000000000000000000000000000000000000..bb448da9f44a02802ae3e723f5112f6d7de49015 Binary files /dev/null and b/docs/source/images/MuonAnalysisDevDocs/MUSR22725-fwd.png differ diff --git a/docs/source/images/MuonAnalysisDevDocs/MUSR60625-long.png b/docs/source/images/MuonAnalysisDevDocs/MUSR60625-long.png new file mode 100644 index 0000000000000000000000000000000000000000..9866d01d8f7d1d725fabcedb5c682b96054f30ff Binary files /dev/null and b/docs/source/images/MuonAnalysisDevDocs/MUSR60625-long.png differ diff --git a/docs/source/images/MuonAnalysisDevDocs/blackbox.png b/docs/source/images/MuonAnalysisDevDocs/blackbox.png new file mode 100644 index 0000000000000000000000000000000000000000..cb183670175e31c282cbb7a904cefecf766e1d00 Binary files /dev/null and b/docs/source/images/MuonAnalysisDevDocs/blackbox.png differ diff --git a/docs/source/images/MuonAnalysisDevDocs/mvp_muon.png b/docs/source/images/MuonAnalysisDevDocs/mvp_muon.png new file mode 100644 index 0000000000000000000000000000000000000000..313538f6e875a28265fa13a687bdff1f3c71d4ef Binary files /dev/null and b/docs/source/images/MuonAnalysisDevDocs/mvp_muon.png differ diff --git a/docs/source/images/multilayer_3.9.png b/docs/source/images/multilayer_3.9.png new file mode 100644 index 0000000000000000000000000000000000000000..fbab36c834406b353408ea0677e4e6fb725183b3 Binary files /dev/null and b/docs/source/images/multilayer_3.9.png differ diff --git a/docs/source/images/release38.png b/docs/source/images/release38.png deleted file mode 100644 index 433124b8bd2a1a2a6b0aa0588da0fb3cad0c85fd..0000000000000000000000000000000000000000 Binary files a/docs/source/images/release38.png and /dev/null differ diff --git a/docs/source/interfaces/Muon_ALC.rst b/docs/source/interfaces/Muon_ALC.rst index 8518af230d83877a21f46153932589c09dd53fa1..8b6cbff193e7a8ae49154da9c7073946381c4f30 100644 --- a/docs/source/interfaces/Muon_ALC.rst +++ b/docs/source/interfaces/Muon_ALC.rst @@ -64,14 +64,14 @@ operations hiding the complexity of the underlying algorithms. Global Options -------------- -Gloabl options are options visible and accesible from any step in the +Global options are options visible and accessible from any step in the interface. Currently, there are two buttons that can be used at any point during the analysis. Export Results ~~~~~~~~~~~~~~ The 'Export results...' button allows the user to export intermediate results at any step. When clicked, -it propmts the user to enter a label for the workspace group that will gather the ALC results. This +it prompts the user to enter a label for the workspace group that will gather the ALC results. This label is defaulted to 'ALCResults'. In the DataLoading step, data are exported in a workspace named <Label>_Loaded_Data, which contains a single spectrum. In the BaselineModelling step, data and model are exported in a set of three workspaces: a workspace named <Label>_Baseline_Workspace, which contains @@ -99,7 +99,7 @@ Import Results ~~~~~~~~~~~~~~ The 'Import results...' button allows the user to load previously analysed data, ideally saved using -'Export results...'. When clicked, it propmts the user to enter a label for the workspace group from which +'Export results...'. When clicked, it prompts the user to enter a label for the workspace group from which data will be imported, which is defaulted to 'ALCResults'. The interface then searches for a workspace corresponding to the interface's step from which it was called. This means that if the user is currently in the diff --git a/docs/source/interfaces/Muon_Analysis_developers_guide.rst b/docs/source/interfaces/Muon_Analysis_developers_guide.rst new file mode 100644 index 0000000000000000000000000000000000000000..ef02984f6be45792195fd30ea5a80f5c49e2fed5 --- /dev/null +++ b/docs/source/interfaces/Muon_Analysis_developers_guide.rst @@ -0,0 +1,355 @@ +.. _Muon_Analysis_DevelopersGuide-ref: + +Muon Analysis: a guide for Mantid developers +============================================ + +.. contents:: Table of Contents + :local: + +Introduction +^^^^^^^^^^^^ +This document is intended for Mantid developers as a guide to the architecture of the Muon Analysis custom interface. +User documentation for this interface can be found at :ref:`Muon_Analysis-ref`. +There is also an unscripted testing guide for developers at :ref:`Muon_Analysis_TestGuide-ref`. + +There will be a particular focus on the *Data Analysis* tab, which has been significantly changed for Mantid 3.8. + +Note that there is also another custom interface for muons: ALC. Development on this is much easier as it has an MVP architecture and is far better tested, so it will not be covered in this document. + +What the interface is for +^^^^^^^^^^^^^^^^^^^^^^^^^ + +Muon Analysis is for reducing and analysing data from muon instruments at ISIS and SMuS. +Muons are implanted into the sample and decay with a lifetime of about 2.2 microseconds. +The decay products (positrons) are detected and the signal measured is the count of positrons over time. + +The instruments have many detectors (sometimes up to 600) in different positions, grouped spatially into "groups". +In a typical muon spin resonance experiment, the muon spins precess in a magnetic field, meaning that the positron count seen on a particular detector will be modulated with time. This gives information about the local fields in the sample at the location where the muon is implanted. + +Data is loaded into the interface, corrected for dead time, and the detectors grouped into groups. +For example, MuSR (64 detectors) uses two groups, *fwd* (forward, detectors 33-64) and *bwd* (backward, detectors 1-32) in its longitudinal field configuration, corresponding to the two detector rings. +(MuSR is special in that the main field direction can be rotated either longitudinal or transverse). +In this case scientists will usually look at a "group pair" called *long*, defined as *fwd - bwd*. + +The grouping used is taken from the IDF by default, or from the data file if not present. +The user can also specify their own grouping. + +The counts or log counts can be plotted, but what scientists usually want to look at is the **asymmetry** (see below). + +Processing is done using the workflow algorithm :ref:`algm-MuonProcess` - see there for a fuller explanation and diagram of the steps performed. + +The "Data Analysis" tab is then used to fit a function to the data, and tables of the results from such fits can be generated with the "Results Table" tab. + +For a full explanation of what the interface does and how to use it, please see the user docs. +Other useful documents are the "Mantid 4 Muons" document and the training school workbook, both of which can be found on the `Muon page <http://www.mantidproject.org/Muon>`_. + +Groups and Periods +################## + +Groups are explained above, as sets of detectors corresponding to physical arrangements. +For example, the MuSR instrument has two rings of detectors, leading to two detector groups in the longitudinal field arrangement. + +*Periods* refers to collecting data in several periods of time - for example you might have two periods "RF on" and "RF off" or "laser on" and "laser off". +The interface allows users to analyse one period at a time, or a sum/difference (such as "1+2", "1-2" or even "1+2-3+4"). + +.. warning:: Note that for summed periods (1+2), you sum the periods 1 and 2 first, then calculate the asymmetry of the sum. For subtracted periods (1-2), you calculate the asymmetry of each period separately, then subtract the asymmetry of period 2 from that of period 1. So for 1+2-3+4, you sum 1+2 and 3+4, calculate asymmetry of each sum, then subtract the asymmetry of (3+4) from that of (1+2). + +.. note:: We don't support names of periods yet, they are referred to by number. This is something scientists would like to have in the future, though. The names are stored in the NeXus file. + +.. topic:: Asymmetry example + + Let's look at a group first - the *fwd* group of ``MUSR00022725.nxs``. + For a group, you get the asymmetry simply by removing the exponential decay: + + .. image:: ../images/MuonAnalysisDevDocs/MUSR22725-fwd.png + :align: center + + Now let's look at a group pair - the *long* pair (*fwd - bwd*) of ``MUSR00060625.nxs``. + For this, the asymmetry is defined as (see :ref:`algm-AsymmetryCalc`) + + .. math:: \textrm{Asymmetry} = \frac{F-\alpha B}{F+\alpha B} + + where :math:`F` is the front spectra, :math:`B` is the back spectra + and :math:`\alpha` is the balance parameter - see :ref:`algm-AlphaCalc`. + + .. image:: ../images/MuonAnalysisDevDocs/MUSR60625-long.png + :align: center + + +Loading data +^^^^^^^^^^^^ + +Data is loaded into the interface as NeXus files. This is the only file type supported at the moment. + +.. note:: Converters exist to translate most other formats (e.g. older ISIS files) to NeXus. PSI have a program called ``any2many`` that will convert their ``BIN`` files to NeXus. + +Muon NeXus files come in two versions, v1 and v2, and there are two versions of the :ref:`algm-LoadMuonNexus` algorithm to handle them. +Both v1 and v2 are in active use (in fact most ISIS data is v1 at the moment). +The schema can be found on the `muon group website <http://www.isis.stfc.ac.uk/groups/muons/muons3385.html>`_, and Steve Cottrell is the best person to ask about NeXus-related questions at ISIS. +Version 2 files support multiple detectors per spectrum, which version 1 files don't. This isn't used on any instruments at ISIS at the time of writing. + +Which data is loaded from which place in the NeXus file, and where it is put in the workspace/run object, is well documented for both versions of the algorithm in their algorithm doc pages. + +There are also some "version 0" muon NeXus files. These are old, pre-NeXus files that have been converted to NeXus. +These mostly load OK into Mantid, but sometimes may be missing something that the loader is expecting. +In one case, there used to be an instrument at ISIS called DEVA, which is not there any more and does not have an IDF (at the moment there is a hack to allow old DEVA files to be loaded). + +The class ``MuonAnalysisDataLoader`` handles loading files and creating analysis workspaces using :ref:`algm-MuonProcess`. +It is fully tested, in addition to the tests that the algorithms themselves have. + +The grouping is stored in a ``Mantid::API::Grouping`` struct. The user can specify their own grouping on the "Grouping Options" tab, and a ``MuonGroupingHelper`` object is used to deal with this. (This is not tested as it is too coupled to the GUI - needs refactoring). + +Load current run +################ + +**ISIS only** + +Scientists at ISIS often use the "load current run" feature - a button on the front tab that will load the most recent data file from the selected instrument. The button is not enabled at other facilities, where this feature is not available. + +The location of the current run is kept in ``\\<instrument>\data\autosave.run``, a file that points to another file in the same directory where the data is. +For example, ``\\MUSR\data\autosave.run`` might contain the file name ``auto_B.tmp``, meaning that the current data is in ``\\MUSR\data\auto_B.tmp``. + +After loading the current run, the left/right buttons are used to cycle through recent datasets. + +At present the "load current run" feature is Windows only, due to how the shared data folder is accessed - at the moment this is OK, as most muon scientists at ISIS tend to use Windows, but it would be good to fix in the long run. + +MuonAnalysisHelper +################## + +On the whole, the main part of MuonAnalysis uses the "big ball of mud" design pattern. +It is very difficult to write tests because the logic is mixed up with the GUI code. +There is, however, a namespace called ``MuonAnalysisHelper`` which contains non-GUI MuonAnalysis-related functions, and these do have tests. + +As noted above, data loading/processing is handled with ``MuonAnalysisDataLoader``, which is also tested. + +.. topic:: Workspace names in MuonAnalysis + + ``MuonAnalysisHelper`` is also where the generation and parsing of workspace names is done. + In the Muon Analysis interface, these follow a strict format delimited by semicolons: + + ``INST00012345; Pair; long; Asym;[ 1;] #1`` + + 1. Run label, made up of instrument and run number. + 2. "Item type": Group (e.g. *fwd*, *bwd*) or Pair (e.g. *long*). + 3. Name of the group or pair. + 4. Plot type: Counts, Logs (logarithm) or Asym (asymmetry). + 5. **Optional:** Period number, or combination like ``1+2``. If not present, data is single-period OR all periods are summed together. + 6. Version: always ``#1`` if overwrite is on (Settings tab of interface), otherwise auto-increments. + + The suffix ``_Raw`` is appended if rebinning is used, to denote the un-rebinned data. + +Plotting data +^^^^^^^^^^^^^ + +To plot data, Muon Analysis uses a hard-coded Python script in the ``plotSpectrum`` method, which is run via the ``runPythonScript`` method common to all Mantid custom interfaces. +(I wonder if there is a better way to do this? It is difficult to maintain the plotting script when it is a string within a C++ method). + +There are various options set on the Settings page - see the user docs for more information on these: + +- Use a new window each time, or the previous window +- Whether it replots automatically, or waits for the "Plot" button to be pressed +- Y autoscale or fixed scale +- Curve type and errors on/off + +Note that, as well as plotting from the front tab, there are "Plot" buttons on the "Grouping Options" tab too. + +Another important point is the setting for "rebin options" on the settings page. +If set, rebinned data will be plotted, and analysis workspaces will be created for *both* rebinned and raw data. +Often, scientists will use the rebinning option but choose the "Fit to raw data" option on the fitting tab. + +If reusing the previous plot window, previous fit curves are kept when new raw data is loaded. +The number of such curves kept is user-configurable. +The script recognises which curves are fits by their name: ``Workspace-Calc``. +It will also keep any "plot guesses", which are recognised by the name ``CompositeFunction``. + +Fitting data +^^^^^^^^^^^^ + +The Muon Analysis fitting ("Data Analysis") tab was updated in Mantid 3.8 to support multi-dataset fitting. +Its features are described in the user documentation; this section concentrates on its architecture. + +Prior to Mantid 3.8, this tab contained one thing: a ``FitPropertyBrowser`` (actually a ``MuonFitPropertyBrowser``). + +.. image:: ../images/MuonAnalysisDataAnalysis.png + :align: center + +This is still there, but only the bottom section ("Settings") and the three buttons at the top are visible. +The "Function" and "Data" sections are hidden. +In their place are two new widgets - this is achieved by inserting an extra ``Layout`` into the muon fit property browser and adding the widgets to this layout. + +Since the ``MuonFitPropertyBrowser`` is all still there underneath, this is how "Compatibility mode" works - an option on the Settings tab that hides the new widgets and shows the previously hidden sections of the fit browser. + +This tab can be thought of as something like an MVP (model-view-presenter) architecture. +Of course, it's not *properly* MVP, as that would have required a rewrite - the focus was on reusing as much existing code as possible! + +.. topic:: "MVP-like" design + + .. image:: ../images/MuonAnalysisDevDocs/mvp_muon.png + :align: center + + **Model:** the ``MuonFitPropertyBrowser``. Still performs the actual fit, keeps track of the workspace(s) fitted, and raises events (Qt signals) to notify the presenters. + + This model is shared between two presenter/view pairs, one to deal with the fitting function and one to deal with the data that will be fitted. + + It inherits from two new abstract base classes (i.e. implements two interfaces), so that it can be mocked when testing the two presenters. + + **Views:** + + - Fit function: ``FunctionBrowser`` - the same one used in the general multi-fitting interface. It is reused here, with the only change being to restrict the range of functions shown to only those that are of interest to muon scientists. + + The ``FunctionBrowser``, as a pre-existing Mantid widget, is not a very humble view and has some logic inside it which unfortunately cannot be tested. + + - Data: a ``MuonFitDataSelector``, a new widget written as a humble view. It does as little as possible and leaves all the logic to the presenter. + + Both these views inherit from abstract base classes - this is for mocking purposes when testing the presenters. + + **Presenters:** + + - Fit function: ``MuonAnalysisFitFunctionPresenter`` + + - Data: ``MuonAnalysisFitDataPresenter`` + + Both presenters have unit tests. The relevant views, and relevant part of the model, are mocked out for this purpose. + + +Fit function +############ + +The actual function that is going to be fitted to the data is stored in the ``MuonFitPropertyBrowser`` (model) and, after the fit, this function will have the correct parameter values. + +It is therefore the job of the presenter to + +- Update the model's function when the user changes the function in the view +- Update the view's displayed function parameters when the fit has finished. + +There are also some signals that come from the data presenter, when the user has used the ``<<`` or ``>>`` buttons to change datasets, or changed the number of workspaces to fit. In these cases the ``FunctionBrowser`` must be updated with this information, to set the number of datasets or to change which dataset's parameters are being displayed. + +Data +#### + +When the user changes something in the ``MuonFitDataSelector`` view, for example the runs to fit, selected groups/periods, fit type (single/co-add/simultaneous) or simultaneous fit label, an event is raised to notify the presenter. +This gets the relevant information from the view and updates the model with it. + +(In a couple of cases, the signal actually goes via ``MuonAnalysis`` itself - because the grouping and plot type may have been changed by the user in that GUI, and so they need to be updated too). + +If the user's chosen runs/groups/periods include datasets that haven't had workspaces created for them yet, they will be created at that point, rather than just before the fit. +Note that, when "Fit raw data" has been ticked, two workspaces must be created per dataset - one binned and one raw. +The data presenter uses a ``MuonAnalysisDataLoader`` (see earlier) to create the analysis workspaces. + +The case where the user updates the fitting range by dragging lines on the graph is also dealt with by the data presenter. + +When a new dataset is loaded on the Home tab, this assigns a new "first run". +(Intended use case is that the first run will always be the one specified on the Home tab). +The presenter therefore updates the view's selected group/period in this case. + +When a fit is finished, the data presenter is notified so that it can process the results. +This is only relevant in the case of a simultaneous fit, because the :ref:`algm-Fit` algorithm produces output in a very different form to its regular output format. +The presenter reorganises the output workspaces so that they are in the same format as they would have been for a regular fit - and then they can be easily read by the "Results table" tab. + +Sequential fit dialog +^^^^^^^^^^^^^^^^^^^^^ + +This is opened when the user selects *Fit/Sequential Fit*. +A sequential fit runs the same fit (either one group/period or a simultaneous fit over groups/periods for one run) for one run at a time, over several runs in sequence. +For example, fits group *fwd*, period 1 for run 15189, then the same group/period for run 15190, then run 15191... + +The dialog ``MuonSequentialFitDialog`` is part of the ``CustomInterfaces`` project. +It holds pointers to the ``MuonAnalysisFitDataPresenter`` (which creates the workspaces to fit and processes the fitted workspaces) and to the ``MuonFitPropertyBrowser`` ("Model" - the dialog gets the fit function and properties from here). + +The actual fit is done by calling the :ref:`algm-Fit` algorithm from the sequential fit dialog. + +One point to note is that the fit is done in two stages. +On pressing the Fit button, the ``startFit`` method is called - this starts running the file search from the ``MWRunFiles`` (run number input widget). +When the ``MWRunFiles`` widget signals that it has found the relevant files, only then does the fit process continue in ``continueFit``. +The reason for this is because users can type a range of runs into the box and then immediately hit Return or click Fit, without first clicking outside the box - and we need time to do the file search before starting. + +.. note:: Despite their names, ``MuonSequentialFitDialog`` does *not* inherit from ``SequentialFitDialog`` - they are completely separate classes. I assume this is for historical reasons. Amongst other differences, the muon sequential fit dialog calls :ref:`algm-Fit` multiple times while the general sequential fit dialog uses :ref:`algm-PlotPeakByLogValue`. + +After a fit +^^^^^^^^^^^ + +After fitting a single dataset, the plot is automatically updated with the fit curve and difference (if "Plot Difference" is selected). +This is done by the ``PeakPickerTool`` from MantidPlot, not by anything within Muon Analysis. + +(The ``PeakPickerTool`` is set to the plot when the Data Analysis tab is selected - see box below.) + +The ``PeakPickerTool`` can recognise muon data by noticing that the fit property browser is a ``MuonFitPropertyBrowser``. +In this case it doesn't remove previous fit curves like it would for other graphs, because this is handled by Muon Analysis instead - we have the option there to keep *n* previous fits as selected by the user... + +If it notes that the fit was a *simultaneous* fit of muon data, then **nothing is plotted**. +This is a temporary solution. +In the long run, we need to discuss with scientists what they would like to be plotted when a simultaneous fit ends. +(N.B. We need to avoid the situation of automatically trying to make a tiled plot of hundreds of datasets at once!) + +What users can currently do to plot the results of a simultaneous or sequential fit is to right-click on the workspace group (``MuonSimulFit_<Label>`` or ``MuonSeqFit_<Label>``) and select *Plot Spectrum...*, then use the *Tiled Plot* option. +Probably it would be best to make this automatic when a multiple fit ends, or provide a "Plot" button in Muon Analysis - this would most likely require exposing the relevant tiled plot functionality to Python first. + +.. topic:: Changing tabs in Muon Analysis + + Changing tabs is handled by the ``changeTab`` method in ``MuonAnalysis.cpp``. + When entering the *Data Analysis* tab: + + - The ``MuonFitPropertyBrowser`` on this tab is set as the default, rather than Mantid's general fit property browser + - Fitting range (start/end) is initialised, unless one is already set + - The ``PeakPickerTool`` is attached to the current plot + - The currently selected workspace is set in the fit data presenter + - The current value of the Mantid-wide setting ``curvefitting.peakRadius`` is cached, and its value is changed to 99. Muon scientists requested this as they don't fit peaks on this tab. The change is localised only to while the *Data Analysis* tab is open, and the cached value will be restored on leaving this tab. + + When leaving the *Data Analysis* tab, the reverse happens: + + - Default fit browser in MantidPlot is reset to Mantid's default + - The config option ``curvefitting.peakRadius`` is reset to its cached value + - The ``PeakPickerTool`` is disconnected from the plot + + +Generating results tables +^^^^^^^^^^^^^^^^^^^^^^^^^ + +The "Results table" tab is structured with ``MuonAnalysisResultTableTab`` handling the GUI parts - populating the tables and getting the user's choice - and uses a ``MuonAnalysisResultTableCreator`` object to actually create the table. + +The ``MuonAnalysisResultTableCreator`` is tested as it doesn't use the GUI, but the tab class itself does not have tests. + +The user can tick time-series logs to add to the table, and a few non-timeseries logs are available too. These are: + +- ``run_number`` +- ``run_start``, ``run_end``: either as seconds relative to first run start, or ISO-formatted text +- ``sample_temp`` +- ``sample_magn_field`` +- ``group`` and ``period`` - these are not logs from the NeXus file but, in the case of a simultaneous fit, the ``MuonFitDataPresenter`` adds them to the fitted workspace (in ``addSpecialLogs``). + +The results table creator must check the workspaces have the same fit model, add the right columns and populate them with values. +The columns must have the correct plot type (X, Y, YError or Label). +If a parameter was fixed in the fit, its error will be zero for each row - so that error column can be removed. + +The *Multiple* option is a little different to the others. +While the single, sequential or simultaneous fit tables have one row per dataset, the multiple fit table has one row per label - showing many fits in the same table, one row per fit. +A *global* parameter has just one value column and one error column, while other (non-global) parameters have one value and one error column per dataset. + +The results table creator can recognise a global parameter by the fact that it has the same value for all datasets. + +Miscellaneous notable points +^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +For a long time, using the Muon Analysis interface has produced a mysterious black box in the toolbars of MantidPlot: + + +.. image:: ../images/MuonAnalysisDevDocs/blackbox.png + :align: center + +This is caused by using the "Hide Toolbars" option on the Settings tab. +If selected, MantidPlot emits a ``setToolbarsHidden(true)`` signal, which is caught by MantidPlot, hiding all the toolbars. +The option is meant to be helpful for users with small laptop screens. + +However, when the interface is closed/hidden, the reverse ``setToolbarsHidden(false)`` tells MantidPlot to show *all* the toolbars, even ones that the user didn't have displayed in the first place! +There is no cache of which toolbars were displayed, and no control over which to show - it's all or none. + +The "black box" seen in the image is, in fact, one of the toolbars - the "Data Display" one. +This is used by the "Screen reader" feature in MantidPlot, which displays coordinates from a graph. +When no graph is being read, the toolbar appears as an empty black box, as above. + +Future work +^^^^^^^^^^^ + +Open muon issues can be found on Github with the `Component: Muon <https://github.com/mantidproject/mantid/issues?q=is%3Aopen+is%3Aissue+label%3A%22Component%3A+Muon%22>`_ label. +Those marked ``Misc: Roadmap`` are the most important. + diff --git a/docs/source/release/v3.9.0/diffraction.rst b/docs/source/release/v3.9.0/diffraction.rst index 77765745954c903bfcf21684414c3be7de0c2491..f5fe77bec6ed9973372f31cb3a5a0ab01698ac89 100644 --- a/docs/source/release/v3.9.0/diffraction.rst +++ b/docs/source/release/v3.9.0/diffraction.rst @@ -11,7 +11,11 @@ Crystal Improvements Engineering Diffraction ----------------------- -| +Powder Diffraction +------------------ + +:ref:`algm-SNSPowderReduction` had an error in logic of subtracting the vanadium background. It was not being subtracted when ``PreserveEvents=True``. + Full list of `diffraction <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.9%22+is%3Amerged+label%3A%22Component%3A+Diffraction%22>`_ and diff --git a/docs/source/release/v3.9.0/framework.rst b/docs/source/release/v3.9.0/framework.rst index 66ce40512b027b4ad4336d1d64985f88889f9bb7..ea24ec6c31bc9599c7942d680b8e0ae564b6510e 100644 --- a/docs/source/release/v3.9.0/framework.rst +++ b/docs/source/release/v3.9.0/framework.rst @@ -15,6 +15,7 @@ New Improved ######## +- :ref:`CalculateFlatBackground <algm-CalculateFlatBackground>` has now a new mode 'Moving Average' which takes the minimum of a moving window average as the flat background. Deprecated ########## @@ -38,11 +39,13 @@ Python Algorithms ################# - :ref:`MatchPeaks <algm-MatchPeaks>` performs circular shift operation (numpy roll) along the x-axis to align the peaks in the spectra. +- :ref:`FindEPP <algm-FindEPP>` is improved to better determine the initial parameters and range for the fitting. Bug Fixes --------- - Bin masking information was wrongly saved when saving workspaces into nexus files, which is now fixed. +- :ref:`LoadEventNexus <algm-LoadEventNexus>` should no longer leak memory when the execution is cancelled. Full list of `Framework <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.9%22+is%3Amerged+label%3A%22Component%3A+Framework%22>`__ diff --git a/docs/source/release/v3.9.0/indirect_inelastic.rst b/docs/source/release/v3.9.0/indirect_inelastic.rst index 57381470e0a61699a36d2fc5b88bd43031e1cd4e..e1f7930c7f8753f7506c991728c449bd731e5339 100644 --- a/docs/source/release/v3.9.0/indirect_inelastic.rst +++ b/docs/source/release/v3.9.0/indirect_inelastic.rst @@ -14,24 +14,46 @@ Algorithms Data Reduction ############## -- Q-vaues in :ref:`BASISReduction <algm-BASISReduction>` output are now point data so that their values display correctly when plotted +- Q-values in :ref:`BASISReduction <algm-BASISReduction>` output are now point data so that their values display correctly when plotted Data Analysis ############# - :ref:`TeixeiraWaterSQE <func-TeixeiraWaterSQE>` models translation of water-like molecules (jump diffusion). + +Corrections +########### + +CalculatePaalmanPings +~~~~~~~~~~~~~~~~~~~~~ + +- Option to calculate number density from mass density + +Absorption +~~~~~~~~~~~ + +- Option to calculate number density from mass density + +Tools +##### + +Transmission +~~~~~~~~~~~~ + +- Option to calculate number density from mass density + - :ref:`IsoRotDiff <func-IsoRotDiff>` models isotropic rotational diffusion of a particle -tethered to the origin at a constant distance. + tethered to the origin at a constant distance. -Jump Fit -~~~~~~~~ Improvements ------------ - + - Data saved in an ASCII format using the *EnergyTransfer* interface can be re-loaded into Mantid Bugfixes -------- +- Clicking 'Save' without creating a res file in *ISISCalibration* no longer causes an error + `Full list of changes on GitHub <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.9%22+is%3Amerged+label%3A%22Component%3A+Indirect+Inelastic%22>`_ diff --git a/docs/source/release/v3.9.0/ui.rst b/docs/source/release/v3.9.0/ui.rst index 55bb52f5082daf8395c2613fb11db6567f61f112..082d2952cff875255d9ec754aa4be55091adbf8a 100644 --- a/docs/source/release/v3.9.0/ui.rst +++ b/docs/source/release/v3.9.0/ui.rst @@ -18,7 +18,7 @@ User Interface -------------- - ParaView's python scripting interface is available from within MantidPlot and mantidpython. Type `from paraview.simple import *` to get started. - `Additional documentation <http://www.paraview.org/ParaView3/Doc/Nightly/www/py-doc/>`_ + `Additional documentation <http://www.paraview.org/ParaView3/Doc/Nightly/www/py-doc/>`_ Instrument View ############### @@ -26,11 +26,19 @@ Instrument View Plotting Improvements ##################### - Fixed a bug where left and right Y axes went out of sync when a fit was run. +- Exposed the ``plotSubplots`` command to Python. This creates a tiled (multilayer) plot with one workspace per tile. + +.. figure:: ../../images/multilayer_3.9.png + :class: screenshot + :width: 550px + :align: right + + plotSubplots image Algorithm Toolbox ################# - - Add compressorType option to SaveMDWorkspaceToVTK. +- Add compressorType option to SaveMDWorkspaceToVTK. Scripting Window ################ @@ -42,6 +50,8 @@ Bugs Resolved ------------- - Fixed a bug where checking or unchecking "show invisible workspaces" in View->Preferences->Mantid->Options would have no effect on workspaces loaded in the dock. +- The Spectrum Viewer now reports two theta and azimuthal angle correctly. +- Fixed crash when clicking "Help->Ask for Help" on Linux-based systems with Firefox set as the default browser. SliceViewer Improvements ------------------------ diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py index 74b504d6d75ec73d91ccf0781dd0c3275f394a7f..9054bd94ec97217b7ceab4e5330602e19dffd887 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py +++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_All.py @@ -197,7 +197,6 @@ def improvingCalibrationSingleTube(filename): This example shows how to use **overridePeaks** option """ from tube_calib_fit_params import TubeCalibFitParams - import time CalibInstWS = loadingStep(filename) # == Set parameters for calibration == # Set what we want to calibrate (e.g whole intrument or one door ) @@ -249,7 +248,7 @@ def improvingCalibrationOfListOfTubes(filename): """ from tube_calib_fit_params import TubeCalibFitParams - not_good = [19,37, 71, 75, 181, 186, 234, 235, 245, 273, 345] + # not_good = [19,37, 71, 75, 181, 186, 234, 235, 245, 273, 345] CalibInstWS = loadingStep(filename) # == Set parameters for calibration == @@ -281,7 +280,7 @@ def improvingCalibrationOfListOfTubes(filename): 245: [9.88089, 93.0593, 136.911, 179.5, 255], # the third peak was bad 273: [18.3711, 105.5, 145.5, 181.6, 243.252], # lost first and third peaks 345: [4.6084, 87.0351, 128.125, 169.923, 245.3] # the last one was bad - } + } calibrationTable, peakTable= tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, fitPar=fitPar, outputPeak=True, overridePeaks=define_peaks) @@ -387,7 +386,7 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): print 'Creating the Peaks Workspace that shows the distance from the expected value for all peaks for each tube' # Let's see these peaks: - Peaks = CreateWorkspace(range(n),distance_from_expected,NSpec=5) + CreateWorkspace(range(n),distance_from_expected,NSpec=5,OutputWorkspace='Peaks') # plot all the 5 peaks for Peaks Workspace. You will see that most of the tubes differ # at most 12 pixels from the expected values. @@ -405,8 +404,8 @@ def findThoseTubesThatNeedSpecialCareForCalibration(filename): print 'Calibrating again only these tubes' #let's confir that our suspect works CalibInstWS = loadingStep(filename) - calibrationTable = tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, - fitPar=fitPar, rangeList= problematic_tubes, plotTube=problematic_tubes) + tube.calibrate(CalibInstWS, CalibratedComponent, knownPos, funcFactor, + fitPar=fitPar, rangeList= problematic_tubes, plotTube=problematic_tubes) # plot the FittedTube agains TubePlot for each detector and you will see that there were problems on those tubes. diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py index 4d22a52b0b76c1a2eadd47aa69aad6b027cda9d2..5413f517d0750a6bf9e7812f43a568e5645a08ed 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py +++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_C4C3.py @@ -7,7 +7,6 @@ # import tube -from mantid.api import WorkspaceFactory # For table worskspace of calibrations from tube_spec import TubeSpec #from tube_calib_fit_params import # To handle fit parameters diff --git a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py index f0f2702ed262dbeb5daac3d6b1d6e328d499a9ce..5a725371cdcdd4811124ec2a0ed2d78b6ca8dc67 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py +++ b/scripts/Calibration/Examples/TubeCalibDemoMaps_D2.py @@ -35,7 +35,8 @@ funcForm = [2,1,1,1,2] # Set initial parameters for peak finding ExpectedHeight = -1000.0 # Expected Height of Gaussian Peaks (initial value of fit parameter) ExpectedWidth = 8.0 # Expected width of Gaussian peaks in pixels (initial value of fit parameter) -ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] # Expected positions of the edges and Gaussian peaks in pixels (initial values of fit parameters) +ExpectedPositions = [4.0, 85.0, 128.0, 161.0, 252.0] # Expected positions of the edges and Gaussian peaks + # in pixels (initial values of fit parameters) fitPar = TubeCalibFitParams( ExpectedPositions, ExpectedHeight, ExpectedWidth) fitPar.setAutomatic(True) diff --git a/scripts/Calibration/Examples/TubeCalibDemoMerlin.py b/scripts/Calibration/Examples/TubeCalibDemoMerlin.py index 5b939b7eb93acf667b3cb1430eb7b5a4bf06c95b..f6b27a28541094f3a1e78a911b6b66a7f1b7e9a8 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoMerlin.py +++ b/scripts/Calibration/Examples/TubeCalibDemoMerlin.py @@ -23,7 +23,8 @@ This example shows: * How to calibrate regions of the instrument separetelly. * How to use **calibTable** parameter to append information in order to create a calibration table for the whole instrument. - * How to use the **outputPeak** to check how the calibration is working as well as the usage of analisePeakTable method to look into the details of the operation to improve the calibration. + * How to use the **outputPeak** to check how the calibration is working as well as the usage of analisePeakTable method to + look into the details of the operation to improve the calibration. * It deals with defining different known positions for the different tube lengths. @@ -65,7 +66,7 @@ def analisePeakTable(pTable, peaksName='Peaks'): #calculate how far from the expected position each peak position is distance_from_expected = numpy.abs(data - expected_peak_pos) - Peaks = CreateWorkspace(range(n),distance_from_expected,NSpec=peaks, OutputWorkspace=peaksName) + CreateWorkspace(range(n),distance_from_expected,NSpec=peaks, OutputWorkspace=peaksName) check = numpy.where(distance_from_expected > 10)[0] problematic_tubes = list(set(check)) print 'Tubes whose distance is far from the expected value: ', problematic_tubes @@ -104,7 +105,7 @@ def calibrateMerlin(filename): outputPeak=True, margin=30, rangeList=range(20) # because 20, 21, 22, 23 are defective detectors - ) + ) print "Got calibration (new positions of detectors) and put slit peaks into file TubeDemoMerlin01.txt" analisePeakTable(peakTable, 'door9_tube1_peaks') diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish1.py b/scripts/Calibration/Examples/TubeCalibDemoWish1.py index 49b55f4aeb627a08dea06285aee25a275462a029..b56785e2f74c98966d21e3c465bb5134cd6b3b34 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoWish1.py +++ b/scripts/Calibration/Examples/TubeCalibDemoWish1.py @@ -6,7 +6,7 @@ # We base the ideal tube on one tube of this door. # import tube -reload(tube) +reload(tube) # noqa from tube_spec import TubeSpec import tube_calib #from tube_calib import constructIdealTubeFromRealTube from tube_calib_fit_params import TubeCalibFitParams diff --git a/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py b/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py index 80e16d3f9b3a8b6e4fac36d9acf273ce3292b6fe..f3cfb7e655f795744f1dd645f5241166ceaa6592 100644 --- a/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py +++ b/scripts/Calibration/Examples/TubeCalibDemoWish_Simple.py @@ -47,7 +47,7 @@ def CalibrateWish( RunNumber, PanelNumber): rangeList = range(76,152), calibTable=calibrationTable,#give the calibration table to append data outputPeak = peakTable#give peak table to append data - ) + ) print "Got calibration (new positions of detectors)" diff --git a/scripts/Calibration/ideal_tube.py b/scripts/Calibration/ideal_tube.py index e668b91c709a8b2046dde1451aed437f6cf1fcce..4a265fd49d38253c9298822d630f27e965293a24 100644 --- a/scripts/Calibration/ideal_tube.py +++ b/scripts/Calibration/ideal_tube.py @@ -1,5 +1,3 @@ -from mantid.simpleapi import * -from mantid.kernel import * import numpy # This class is the ideal tube, which specifies where the peaks formed by slits or edges should occur diff --git a/scripts/Calibration/tube_calib.py b/scripts/Calibration/tube_calib.py index 3816273613c11cb2ebd80861890adc6878987a58..2064245b351be662fa9de98467b8b12abdccadc1 100644 --- a/scripts/Calibration/tube_calib.py +++ b/scripts/Calibration/tube_calib.py @@ -22,7 +22,8 @@ import os import copy -def createTubeCalibtationWorkspaceByWorkspaceIndexList ( integratedWorkspace, outputWorkspace, workspaceIndexList, xUnit='Pixel', showPlot=False): +def createTubeCalibtationWorkspaceByWorkspaceIndexList ( integratedWorkspace, outputWorkspace, workspaceIndexList, + xUnit='Pixel', showPlot=False): """ Creates workspace with integrated data for one tube against distance along tube The tube is specified by a list of workspace indices of its spectra @@ -230,8 +231,9 @@ def getPoints ( IntegratedWorkspace, funcForms, fitParams, whichTube, showPlot=F fitt_x_values.append(copy.copy(ws.dataX(1))) if showPlot: - FittedData = CreateWorkspace(numpy.hstack(fitt_x_values), - numpy.hstack(fitt_y_values)) + CreateWorkspace(OutputWorkspace='FittedData', + DataX=numpy.hstack(fitt_x_values), + DataY=numpy.hstack(fitt_y_values)) return results @@ -414,7 +416,6 @@ def getCalibratedPixelPositions( ws, tubePts, idealTubePts, whichTube, peakTestM # Move the pixel detectors (might not work for sloping tubes) for i in range(nDets): deti = ws.getDetector( whichTube[i]) - det_pos = deti.getPos() pNew = pixels[i] # again, the opeartion float * v3d is not defined, but v3d * float is, # so, I wrote the new pos as center + unit_vector * (float) @@ -477,11 +478,14 @@ def getCalibration( ws, tubeSet, calibTable, fitPar, iTube, peaksTable, :param ws: Integrated Workspace with tubes to be calibrated :param tubeSet: Specification of Set of tubes to be calibrated ( :class:`~tube_spec.TubeSpec` object) - :param calibTable: Empty calibration table into which the calibration results are placed. It is composed by 'Detector ID' and a V3D column 'Detector Position'. It will be filled with the IDs and calibrated positions of the detectors. + :param calibTable: Empty calibration table into which the calibration results are placed. It is composed by 'Detector ID' + and a V3D column 'Detector Position'. It will be filled with the IDs and calibrated positions of the detectors. :param fitPar: A :class:`~tube_calib_fit_params.TubeCalibFitParams` object for fitting the peaks - :param iTube: The :class:`~ideal_tube.IdealTube` which contains the positions in metres of the shadows of the slits, bars or edges used for calibration. + :param iTube: The :class:`~ideal_tube.IdealTube` which contains the positions in metres of the shadows of the slits, + bars or edges used for calibration. :param peaksTable: Peaks table into wich the peaks positions will be put - :param overridePeak: dictionary with tube indexes keys and an array of peaks in pixels to override those that would be fitted for one tube + :param overridePeak: dictionary with tube indexes keys and an array of peaks in pixels to override those that would be + fitted for one tube :param exludeShortTubes: Exlude tubes shorter than specified length from calibration :param plotTube: List of tube indexes that will be ploted :param rangelist: list of the tube indexes that will be calibrated. Default None, means all the tubes in tubeSet diff --git a/scripts/Calibration/tube_calib_fit_params.py b/scripts/Calibration/tube_calib_fit_params.py index 298c16519d5b4d24cfb03fa5abcc365d34251df5..345bd62a1bf034bfc8be6eda7983f6eb80606473 100644 --- a/scripts/Calibration/tube_calib_fit_params.py +++ b/scripts/Calibration/tube_calib_fit_params.py @@ -1,7 +1,3 @@ -from mantid.simpleapi import * -from mantid.kernel import * - - class TubeCalibFitParams(object): # This class is to take the fitting method and parameters for fitting the peaks crated by the calibration slits etc @@ -67,4 +63,5 @@ class TubeCalibFitParams(object): return self.automatic def __str__(self): - return 'peaks'+str(self.peaks)+'height'+str(self.height)+'width'+str(self.width)+'margin'+str(self.margin)+'outedge'+str(self.outEdge)+'inedge'+str(self.inEdge)+'edgegrad'+str(self.edgeGrad ) + return ('peaks'+str(self.peaks)+'height'+str(self.height)+'width'+str(self.width)+'margin'+ + str(self.margin)+'outedge'+str(self.outEdge)+'inedge'+str(self.inEdge)+'edgegrad'+str(self.edgeGrad)) diff --git a/scripts/Calibration/tube_spec.py b/scripts/Calibration/tube_spec.py index 07d9dfe39ed4f23225ec973a50bcdb4bd829bb2e..10b5bb3ace31578f45840bace0b9f19f3f9521d4 100644 --- a/scripts/Calibration/tube_spec.py +++ b/scripts/Calibration/tube_spec.py @@ -1,6 +1,4 @@ #pylint: disable=invalid-name -from mantid.simpleapi import * -from mantid.kernel import * # This class is to take a specification of a set of tubes for an instrument provided by a user # and then provide a list of workspace index ranges corresponding to each of the specified tubes @@ -263,7 +261,6 @@ class TubeSpec: comp = self.tubes[tubeIx] if comp != 0: - firstDet = comp[0].getID() numDet = comp.nelements() return comp[0].getDistance( comp[numDet-1] ) else: diff --git a/scripts/CryPowderISIS/cry_ini.py b/scripts/CryPowderISIS/cry_ini.py index d6116b1dbad9e8d944d282cf44334df96197e266..2ce6567dc149de1266b5981e67df258e5674acea 100644 --- a/scripts/CryPowderISIS/cry_ini.py +++ b/scripts/CryPowderISIS/cry_ini.py @@ -1,6 +1,5 @@ #pylint: disable=attribute-defined-outside-init,undefined-loop-variable,too-many-arguments,too-many-branches,too-many-instance-attributes,old-style-class,global-variable-not-assigned -from mantid.simpleapi import * import cry_utils import re import os.path diff --git a/scripts/DGSPlanner.py b/scripts/DGSPlanner.py index 1df81b646397a7d1cf711fa6f60992b69223d961..70b6858c25740abafaaa816e60113d23adee787f 100644 --- a/scripts/DGSPlanner.py +++ b/scripts/DGSPlanner.py @@ -16,6 +16,6 @@ if __name__ == '__main__': planner = DGSPlannerGUI.DGSPlannerGUI() planner.show() try: #check if started from within mantidplot - import mantidplot + import mantidplot # noqa except ImportError: sys.exit(app.exec_()) diff --git a/scripts/DGSPlanner/DGSPlannerGUI.py b/scripts/DGSPlanner/DGSPlannerGUI.py index e5d6c75447675641d313af2d8a2e6b4c3acd1257..5038029e873bcd032adae7679bac7e8550a0414b 100644 --- a/scripts/DGSPlanner/DGSPlannerGUI.py +++ b/scripts/DGSPlanner/DGSPlannerGUI.py @@ -6,6 +6,7 @@ import DimensionSelectorWidget from PyQt4 import QtCore, QtGui import sys import mantid +import mantidqtpython as mqt from ValidateOL import ValidateOL from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure @@ -137,12 +138,12 @@ class DGSPlannerGUI(QtGui.QWidget): helpapp = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator() helpapp += 'assistant' args = ['-enableRemoteControl', '-collectionFile',self.collectionFile,'-showUrl',self.qtUrl] - if os.path.isfile(helpapp): + if os.path.isfile(helpapp) and os.path.isfile(self.collectionFile): self.assistantProcess.close() self.assistantProcess.waitForFinished() self.assistantProcess.start(helpapp, args) else: - QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.externalUrl)) + mqt.MantidQt.API.MantidDesktopServices.openUrl(QtCore.QUrl(self.externalUrl)) def closeEvent(self,event): self.assistantProcess.close() diff --git a/scripts/DGSPlanner/DimensionSelectorWidget.py b/scripts/DGSPlanner/DimensionSelectorWidget.py index 665670032469256523d3b53852c23261dd72bf02..9ea9a3d1b9c75626c10d6cbb6e1fc86f7af3db66 100644 --- a/scripts/DGSPlanner/DimensionSelectorWidget.py +++ b/scripts/DGSPlanner/DimensionSelectorWidget.py @@ -24,12 +24,12 @@ class EmptyOrDoubleValidator(QtGui.QValidator): return returnValid(QtGui.QValidator.Acceptable,teststring,pos) else: try: - dummy=float(str(teststring)) + float(str(teststring)) return returnValid(QtGui.QValidator.Acceptable,teststring,pos) except ValueError: try: #this is the case when you start typing - or 1e or 1e- and putting 1 at the end would make it a float - dummy=float(str(teststring)+'1') + float(str(teststring)+'1') return returnValid(QtGui.QValidator.Intermediate,teststring,pos) except ValueError: return returnValid(QtGui.QValidator.Invalid,teststring,pos) @@ -45,15 +45,15 @@ class V3DValidator(QtGui.QValidator): return returnValid(QtGui.QValidator.Invalid,teststring,pos) if len(parts)==3: try: - dummy_0=float(parts[0]) - dummy_1=float(parts[1]) - dummy_2=float(parts[2]) + float(parts[0]) + float(parts[1]) + float(parts[2]) return returnValid(QtGui.QValidator.Acceptable,teststring,pos) except ValueError: try: - dummy_0=float(parts[0]+'1') - dummy_1=float(parts[1]+'1') - dummy_2=float(parts[2]+'1') + float(parts[0]+'1') + float(parts[1]+'1') + float(parts[2]+'1') return returnValid(QtGui.QValidator.Intermediate,teststring,pos) except ValueError: return returnValid(QtGui.QValidator.Invalid,teststring,pos) diff --git a/scripts/DGSPlanner/InstrumentSetupWidget.py b/scripts/DGSPlanner/InstrumentSetupWidget.py index d9d048af71cbe777b8372137f2fe0369321d6063..dd48a3031762e6d00df70de47677720a860c6e21 100644 --- a/scripts/DGSPlanner/InstrumentSetupWidget.py +++ b/scripts/DGSPlanner/InstrumentSetupWidget.py @@ -6,10 +6,10 @@ import numpy import matplotlib matplotlib.use('Qt4Agg') matplotlib.rcParams['backend.qt4']='PyQt4' -from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.figure import Figure -from mpl_toolkits.mplot3d import Axes3D -import matplotlib.pyplot +from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas # noqa +from matplotlib.figure import Figure # noqa +from mpl_toolkits.mplot3d import Axes3D # noqa +import matplotlib.pyplot # noqa try: from PyQt4.QtCore import QString except ImportError: diff --git a/scripts/Engineering/EnggUtils.py b/scripts/Engineering/EnggUtils.py index ec942fa23e916682daf3d5ebd3dc6096de2e6665..6514f44832d1e0dd2de7a0549422b421d87a34db 100644 --- a/scripts/Engineering/EnggUtils.py +++ b/scripts/Engineering/EnggUtils.py @@ -24,8 +24,7 @@ def default_ceria_expected_peaks(): 0.901900955, 0.855618487, 0.825231622, 0.815800156, 0.781069134, 0.757748432, 0.750426918, 0.723129589, 0.704504971, 0.676425777, 0.66110842, 0.656229382, - 0.637740216, 0.624855346, 0.620730846, 0.605013529 - ] + 0.637740216, 0.624855346, 0.620730846, 0.605013529] return _CERIA_EXPECTED_PEAKS @@ -416,7 +415,7 @@ def write_ENGINX_GSAS_iparam_file(output_file, difc, tzero, bank_names=None, patterns = ["INS %d ICONS"%(b_idx + 1), # bank calibration parameters: DIFC, DIFA, TZERO "INS CALIB", # calibration run numbers (Vanadium and Ceria) "INS INCBM" # A his file for open genie (with ceria run number in the name) - ] + ] difa = 0.0 # the ljust(80) ensures a length of 80 characters for the lines (GSAS rules...) replacements = [ ("INS {0} ICONS {1:.2f} {2:.2f} {3:.2f}". diff --git a/scripts/FilterEvents/MplFigureCanvas.py b/scripts/FilterEvents/MplFigureCanvas.py index 97fc301275292fbac945239dbc9c71a6652cd670..29e109f5510e68adc56ffcba34b8bb406f9650d7 100644 --- a/scripts/FilterEvents/MplFigureCanvas.py +++ b/scripts/FilterEvents/MplFigureCanvas.py @@ -1,9 +1,7 @@ #pylint: disable=invalid-name from PyQt4 import QtGui -import matplotlib from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas -from matplotlib.backends.backend_qt4agg import NavigationToolbar2QT as NavigationToolbar from matplotlib.figure import Figure diff --git a/scripts/FilterEvents/eventFilterGUI.py b/scripts/FilterEvents/eventFilterGUI.py index 1b6786f6dc7c357b01b1ca68ed5fab561d801575..89b57105b65e2caead38e0e2bb518c53aaae5c7e 100644 --- a/scripts/FilterEvents/eventFilterGUI.py +++ b/scripts/FilterEvents/eventFilterGUI.py @@ -635,7 +635,7 @@ class MainWindow(QtGui.QMainWindow): """ Open a file dialog to get file """ filename = QtGui.QFileDialog.getOpenFileName(self, 'Input File Dialog', - self._defaultdir, "Data (*.nxs *.dat);;All files (*.*)") + self._defaultdir, "Data (*.nxs *.dat);;All files (*)") self.ui.lineEdit.setText(str(filename)) diff --git a/scripts/HFIRPowderReduction/HfirPDReductionControl.py b/scripts/HFIRPowderReduction/HfirPDReductionControl.py index ee011c3a523dcce9d897db8d1ff02ecc88a94acc..be3b265ba0fa1198bfed47c7c783c0df216493f9 100644 --- a/scripts/HFIRPowderReduction/HfirPDReductionControl.py +++ b/scripts/HFIRPowderReduction/HfirPDReductionControl.py @@ -5,7 +5,6 @@ # Key Words: FUTURE # ############################################################################ -import sys import os import urllib2 import math @@ -15,11 +14,6 @@ import numpy import HfirUtility as hutil # Import mantid -curdir = os.getcwd() -libpath = os.path.join(curdir.split('Code')[0], 'Code/debug/bin') -if os.path.exists(libpath) is False: - libpath = os.path.join(curdir.split('Code')[0], 'Code/release/bin') -sys.path.append(libpath) import mantid.simpleapi as api from mantid.simpleapi import AnalysisDataService #from mantid.kernel import ConfigService diff --git a/scripts/HFIRPowderReduction/HfirPDReductionGUI.py b/scripts/HFIRPowderReduction/HfirPDReductionGUI.py index d0ca2092b64a80626f9e5be2a3f1666377169ebe..286b1d71836f2c8430cf46e8431d9d771844bd92 100644 --- a/scripts/HFIRPowderReduction/HfirPDReductionGUI.py +++ b/scripts/HFIRPowderReduction/HfirPDReductionGUI.py @@ -16,6 +16,7 @@ except AttributeError: return s import mantid +import mantidqtpython as mqt from HfirPDReductionControl import * #----- default configuration --------------- @@ -453,7 +454,7 @@ class MainWindow(QtGui.QMainWindow): Return :: None """ # Get file name - filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)" + filefilter = "Text (*.txt);;Data (*.dat);;All files (*)" curDir = os.getcwd() excldetfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter) try: @@ -594,13 +595,13 @@ class MainWindow(QtGui.QMainWindow): helpapp = QtCore.QLibraryInfo.location(QtCore.QLibraryInfo.BinariesPath) + QtCore.QDir.separator() helpapp += 'assistant' args = ['-enableRemoteControl', '-collectionFile',self.collectionFile,'-showUrl',self.qtUrl] - if os.path.isfile(helpapp): + if os.path.isfile(helpapp) and os.path.isfile(self.collectionFile): self.assistantProcess.close() self.assistantProcess.waitForFinished() self.assistantProcess.start(helpapp, args) print "Show help from (app) ", helpapp else: - QtGui.QDesktopServices.openUrl(QtCore.QUrl(self.externalUrl)) + mqt.MantidQt.API.MantidDesktopServices.openUrl(QtCore.QUrl(self.externalUrl)) print "Show help from (url)", QtCore.QUrl(self.externalUrl) return @@ -736,7 +737,7 @@ class MainWindow(QtGui.QMainWindow): # Apply detector efficiency correction if vancorrfname is None: # browse vanadium correction file - filefilter = "Text (*.txt);;Data (*.dat);;All files (*.*)" + filefilter = "Text (*.txt);;Data (*.dat);;All files (*)" curDir = os.getcwd() vancorrfnames = QtGui.QFileDialog.getOpenFileNames(self, 'Open File(s)', curDir, filefilter) if len(vancorrfnames) > 0: @@ -1423,7 +1424,7 @@ class MainWindow(QtGui.QMainWindow): else: homedir = os.getcwd() # launch a dialog to get data - filefilter = "All files (*.*);;Fullprof (*.dat);;GSAS (*.gsa)" + filefilter = "All files (*);;Fullprof (*.dat);;GSAS (*.gsa)" sfilename = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File', homedir, filefilter)) except NotImplementedError as e: self._logError(str(e)) diff --git a/scripts/HFIR_4Circle_Reduction/NTableWidget.py b/scripts/HFIR_4Circle_Reduction/NTableWidget.py index c3dbe1f7c71e4b33d28a2980db5dce298f558fcd..168ac1470f9a8b00c20a779f8d786489f14061f0 100644 --- a/scripts/HFIR_4Circle_Reduction/NTableWidget.py +++ b/scripts/HFIR_4Circle_Reduction/NTableWidget.py @@ -7,7 +7,8 @@ from PyQt4 import QtGui, QtCore try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s class NTableWidget(QtGui.QTableWidget): diff --git a/scripts/HFIR_4Circle_Reduction/peakprocesshelper.py b/scripts/HFIR_4Circle_Reduction/peakprocesshelper.py index 2afabda1ef90cc66d61e4dd65c4d21bcfc0d662c..9fbade5d30b1aa00ae10df0f62ed3b7c868ba0eb 100644 --- a/scripts/HFIR_4Circle_Reduction/peakprocesshelper.py +++ b/scripts/HFIR_4Circle_Reduction/peakprocesshelper.py @@ -1,9 +1,5 @@ #pylint: disable=W0403,R0902 from fourcircle_utility import * - -import sys -sys.path.append('/Users/wzz/MantidBuild/debug/bin/') - from mantid.api import AnalysisDataService from mantid.kernel import V3D diff --git a/scripts/HFIR_4Circle_Reduction/reduce4circleGUI.py b/scripts/HFIR_4Circle_Reduction/reduce4circleGUI.py index 11b6a6f062609dad1d500cd227481c18fa7aa989..b863c81bc401b3706ff21d64b3ccf9885e6a4590 100644 --- a/scripts/HFIR_4Circle_Reduction/reduce4circleGUI.py +++ b/scripts/HFIR_4Circle_Reduction/reduce4circleGUI.py @@ -16,7 +16,6 @@ from scipy.optimize import curve_fit from PyQt4 import QtCore, QtGui -from PyQt4.QtCore import QThread try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: @@ -1343,7 +1342,7 @@ class MainWindow(QtGui.QMainWindow): num_rows = int(self.ui.lineEdit_numSurveyOutput.text()) # get the csv file - file_filter = 'CSV Files (*.csv);;All Files (*.*)' + file_filter = 'CSV Files (*.csv);;All Files (*)' csv_file_name = str(QtGui.QFileDialog.getOpenFileName(self, 'Open Exp-Scan Survey File', self._homeDir, file_filter)) if csv_file_name is None or len(csv_file_name) == 0: @@ -1932,7 +1931,7 @@ class MainWindow(QtGui.QMainWindow): :return: """ # Get file name - file_filter = 'CSV Files (*.csv);;All Files (*.*)' + file_filter = 'CSV Files (*.csv);;All Files (*)' out_file_name = str(QtGui.QFileDialog.getSaveFileName(self, 'Save scan survey result', self._homeDir, file_filter)) @@ -1946,7 +1945,7 @@ class MainWindow(QtGui.QMainWindow): :return: """ # get file name - file_filter = 'Data Files (*.dat);;All Files (*.*)' + file_filter = 'Data Files (*.dat);;All Files (*)' ub_file_name = str(QtGui.QFileDialog.getSaveFileName(self, 'ASCII File To Save UB Matrix', self._homeDir, file_filter)) @@ -2098,7 +2097,7 @@ class MainWindow(QtGui.QMainWindow): """ Get UB matrix from an Ascii file :return: """ - file_filter = 'Data Files (*.dat);;Text Files (*.txt);;All Files (*.*)' + file_filter = 'Data Files (*.dat);;Text Files (*.txt);;All Files (*)' file_name = QtGui.QFileDialog.getOpenFileName(self, 'Open UB ASCII File', self._homeDir, file_filter) # quit if cancelled diff --git a/scripts/Imaging/IMAT/prep/energy_bands_aggregator.py b/scripts/Imaging/IMAT/prep/energy_bands_aggregator.py index 9057012cebb042f5d83777f8202924dea21e8818..a1f0a96a0db3676652996de6495377d4a4ed3e6d 100644 --- a/scripts/Imaging/IMAT/prep/energy_bands_aggregator.py +++ b/scripts/Imaging/IMAT/prep/energy_bands_aggregator.py @@ -59,7 +59,7 @@ except RuntimeError: _USING_PLUGIN_TIFFFILE = True except ImportError: try: - import tifffile + import tifffile # noqa _USING_PLUGIN_TIFFFILE = True except ImportError: raise ImportError("Cannot find the package 'tifffile' in the system or together with this " @@ -207,7 +207,6 @@ class EnergyBandsAggregator(object): acc = np.add(acc, img_data) elif 'average' == agg_method: acc = np.add((index-1)*acc/index, img_data/index) - __img_idx += 1 return acc @@ -248,10 +247,6 @@ class EnergyBandsAggregator(object): data_dtype = np.uint16 accum = np.zeros((imgs[0].shape[0], imgs[0].shape[1]), dtype=data_dtype) - # methods that require incremental calculations should remember to do this - if 'average' == agg_method: - __img_idx = 1 - # filter, keep only the files between min and max indices given if band_indices: img_files = [f for idx,f in enumerate(img_files) if @@ -286,12 +281,12 @@ class EnergyBandsAggregator(object): if not in_path: raise ValueError("The input path cannot be empty") - if None == output_path: + if output_path is None: output_path = self.default_out_path if out_format: self._out_format = out_format - if not isinstance(self._out_format, str) or not self._out_format in self.supported_out_formats: + if not isinstance(self._out_format, str) or self._out_format not in self.supported_out_formats: raise ValueError("Only the following output formats are supported: {0}. Format requested: {1}". format(self.supported_out_formats, self._out_format)) diff --git a/scripts/Imaging/IMAT/tomo_reconstruct.py b/scripts/Imaging/IMAT/tomo_reconstruct.py index 8314ae97ce6e5619bed7f987c5c4777190265209..875d4e66bc2d9f156854df4bb0a9fba82ea7ffbd 100644 --- a/scripts/Imaging/IMAT/tomo_reconstruct.py +++ b/scripts/Imaging/IMAT/tomo_reconstruct.py @@ -50,11 +50,10 @@ ipython -- scripts/Imaging/IMAT/tomo_reconstruct.py\ # find first the package/subpackages in the path of this file. import sys -from sys import path import os from os import path # So insert in the path the directory that contains this file -sys.path.insert(0, os.path.split(path.dirname(__file__))[0]) +sys.path.insert(0, os.path.split(path.dirname(__file__))[0]) # noqa from IMAT.tomorec import reconstruction_command as tomocmd import IMAT.tomorec.configs as tomocfg @@ -270,8 +269,8 @@ def main_tomo_rec(): # distributions, as found for example on rhel6 vers = sys.version_info if vers < (2,7,0): - raise RuntimeErrorn("Not running this test as it requires Python >= 2.7. Version found: {0}". - format(vers)) + raise RuntimeError("Not running this test as it requires Python >= 2.7. Version found: {0}". + format(vers)) import inspect diff --git a/scripts/Imaging/IMAT/tomorec/io.py b/scripts/Imaging/IMAT/tomorec/io.py index d51e982fb55b74143fa48818a97342b171b8740c..716950383951a9e089a9bf245422e4507ba834dc 100644 --- a/scripts/Imaging/IMAT/tomorec/io.py +++ b/scripts/Imaging/IMAT/tomorec/io.py @@ -30,8 +30,6 @@ import re import numpy as np -__AGG_IMG_IDX = 0 - def _import_pyfits(): """ @@ -183,9 +181,6 @@ def avg_image_files(path, base_path, file_extension=None, agg_method='average'): accum = np.zeros((imgs[0].shape[0], imgs[0].shape[1]), dtype=data_dtype) - if 'average' == agg_method: - __AGG_IMG_IDX = 1 - for ifile in img_files: hdu = None try: @@ -221,7 +216,6 @@ def _agg_img(acc, img_data, agg_method=None, index=1): acc = np.add(acc, img_data) elif 'average' == agg_method: acc = np.add((index-1)*acc/index, img_data/index) - __AGG_IMG_IDX += 1 return acc diff --git a/scripts/Inelastic/Direct/CommonFunctions.py b/scripts/Inelastic/Direct/CommonFunctions.py index d4fe77148e8c26e0180d18254ac06059ef1eef45..9fb5d17b27df5064e4ed4e68d2509ef8ca907716 100644 --- a/scripts/Inelastic/Direct/CommonFunctions.py +++ b/scripts/Inelastic/Direct/CommonFunctions.py @@ -1,11 +1,3 @@ -#pylint: disable=invalid-name -import mantid -from mantid.simpleapi import * -from mantid import api -import os -import string - - class switch(object): """ Helper class providing nice switch statement""" diff --git a/scripts/Inelastic/Direct/DirectEnergyConversion.py b/scripts/Inelastic/Direct/DirectEnergyConversion.py index 443ea8b4be68972376eddc4a025ec4d930d89611..a770535b0567d0e36fc9415f6b08e65c332afa63 100644 --- a/scripts/Inelastic/Direct/DirectEnergyConversion.py +++ b/scripts/Inelastic/Direct/DirectEnergyConversion.py @@ -228,7 +228,7 @@ class DirectEnergyConversion(object): DeleteWorkspace(Workspace='white_ws_clone') DeleteWorkspace(Workspace='hard_mask_ws') diag_mask = white.get_masking(1) - if not out_ws_name is None: + if out_ws_name is not None: dm = CloneWorkspace(diag_mask,OutputWorkspace=out_ws_name) return dm else: @@ -240,13 +240,13 @@ class DirectEnergyConversion(object): if self.second_white: #TODO: fix THIS DOES NOT WORK! #pylint: disable=unused-variable - second_white = self.second_white + # second_white = self.second_white other_whiteintegrals = self.do_white(PropertyManager.second_white, None, None) # No grouping yet #pylint: disable=attribute-defined-outside-init self.second_white = other_whiteintegrals # Get the background/total counts from the sample run if present - if not diag_sample is None: + if diag_sample is not None: diag_sample = self.get_run_descriptor(diag_sample) sample_mask = diag_sample.get_masking(1) if sample_mask is None: @@ -303,7 +303,7 @@ class DirectEnergyConversion(object): # Check how we should run diag diag_spectra_blocks = self.diag_spectra - if not white_mask is None: + if white_mask is not None: diag_params['white_mask'] = white # keep white mask workspace for further usage if diag_spectra_blocks is None: @@ -322,7 +322,7 @@ class DirectEnergyConversion(object): DeleteWorkspace(white_masked_ws) if out_ws_name: - if not diag_sample is None: + if diag_sample is not None: diag_sample.add_masked_ws(whiteintegrals) mask = diag_sample.get_masking(1) diag_mask = CloneWorkspace(mask,OutputWorkspace=out_ws_name) @@ -461,7 +461,7 @@ class DirectEnergyConversion(object): #-------------------------------------------------------------------------------------------------- # ISIS or GUI motor stuff psi = PropertyManager.psi.read_psi_from_workspace(sample_ws) - if not prop_man.motor_offset is None and np.isnan(psi): + if prop_man.motor_offset is not None and np.isnan(psi): #logs have a problem prop_man.log("*** Can not retrieve rotation value from sample environment logs: {0}.\n" " Rotation angle remains undefined".format(prop_man.motor_log_names)) @@ -516,7 +516,7 @@ class DirectEnergyConversion(object): format(cut_ind,num_ei_cuts,ei_guess),'notice') # do bleed corrections for chunk if necessary bleed_mask = self._do_bleed_corrections(PropertyManager.sample_run,cut_ind) - if not bleed_mask is None: + if bleed_mask is not None: mask_ws_name = PropertyManager.sample_run.get_workspace().name()+'_bleed_mask' RenameWorkspace(bleed_mask,OutputWorkspace=mask_ws_name) self._old_runs_list.append(mask_ws_name) @@ -886,9 +886,9 @@ class DirectEnergyConversion(object): Mask and group detectors based on input parameters """ ws_name = result_ws.getName() - if not spec_masks is None: + if spec_masks is not None: MaskDetectors(Workspace=ws_name, MaskedWorkspace=spec_masks) - if not map_file is None: + if map_file is not None: GroupDetectors(InputWorkspace=ws_name,OutputWorkspace=ws_name, MapFile= map_file, KeepUngroupedSpectra=0, Behaviour='Average') @@ -1287,7 +1287,7 @@ class DirectEnergyConversion(object): # check if spectra masks is defined if hasattr(self,'_spectra_masks'): - if not self._spectra_masks is None and self._spectra_masks in mtd: + if self._spectra_masks is not None and self._spectra_masks in mtd: return mtd[self._spectra_masks] else: self._spectra_masks = None @@ -1299,7 +1299,7 @@ class DirectEnergyConversion(object): def spectra_masks(self,value): """ set up spectra masks """ if value is None: - if hasattr(self,'_spectra_masks') and not self._spectra_masks is None: + if hasattr(self,'_spectra_masks') and self._spectra_masks is not None: if self._spectra_masks in mtd: DeleteWorkspace(self._spectra_masks) self._spectra_masks=None diff --git a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py index 1c292af06922e429ce4c0b73059ef435026c18de..76d09d7bb5b7bd5a01c8a8ef2fd2ce09601bf6e4 100644 --- a/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py +++ b/scripts/Inelastic/Direct/ISISDirecInelasticConfig.py @@ -101,9 +101,10 @@ class UserProperties(object): for prop in USER_PROPERTIES: try: ind = str_parts.index(prop) + # pylint: disable=W0703 except Exception: ind = None - if not ind is None: + if ind is not None: str_parts[ind] = str(getattr(self, prop)) data_string = "".join(str_parts) return data_string @@ -162,7 +163,7 @@ class UserProperties(object): # def get_rb_dir(self,exp_date): - """Returns full name name of user's RB folder correspinding to the + """Returns full name name of user's RB folder corresponding to the experiment, with the data provided. """ return self._rb_dirs[exp_date] @@ -235,20 +236,26 @@ class UserProperties(object): def userID(self, val): self._user_id = str(val) - # + # number of branches as necessary + # pylint: disable=R0912 def check_input(self, instrument, start_date, cycle, rb_folder_or_id): """Verify that input is correct""" if instrument not in INELASTIC_INSTRUMENTS: raise RuntimeError("Instrument {0} has to be one of " "ISIS inelastic instruments".format(instrument)) if isinstance(start_date, str): - start_date = start_date.replace('-', '') - if len(start_date) != 8: - start_date = '20' + start_date - if len(start_date) == 8: + # the date of express -- let's make it long in the past + if start_date.lower() == 'none': + start_date = '19800101' error = False else: - error = True + start_date = start_date.replace('-', '') + if len(start_date) != 8: + start_date = '20' + start_date + if len(start_date) == 8: + error = False + else: + error = True else: error = True if error: @@ -309,6 +316,11 @@ class UserProperties(object): """Return list of all cycles the user participates in""" return self._instrument.keys() + def get_all_rb(self): + """Return list of all rb folders the user participates in""" + return self._rb_dirs.values() + + # # --------------------------------------------------------------------# # @@ -512,16 +524,18 @@ class MantidConfigDirectInelastic(object): return full_source, full_target # - def copy_reduction_sample(self, user_file_description=None,cycle_id=None): + def copy_reduction_sample(self, user_file_description=None,cycle_id=None,rb_group=None): """copy sample reduction scripts from Mantid script repository to user folder. """ if user_file_description is None: user_file_description = self.get_user_file_description() + if rb_group is None: + rb_group = self._user.userID info_to_copy = self._parse_user_files_description(user_file_description,cycle_id) for source_file,dest_file,subst_list in info_to_copy: - self._copy_user_file_job(source_file,dest_file,subst_list) + self._copy_user_file_job(source_file,dest_file,rb_group,subst_list) def _copy_and_parse_user_file(self, input_file, output_file, replacemets_list): """Method processes file provided for user and replaces list of keywords, describing user @@ -541,7 +555,7 @@ class MantidConfigDirectInelastic(object): fh_targ.close() # - def _copy_user_file_job(self, input_file, output_file, replacement_list=None): + def _copy_user_file_job(self, input_file, output_file, rb_group,replacement_list=None): """Method copies file provided into the requested destination and replaces keys specified in replacement list dictionary with their values if replacement_list is provided. @@ -560,8 +574,9 @@ class MantidConfigDirectInelastic(object): self._copy_and_parse_user_file(input_file, output_file, replacement_list) os.chmod(output_file, 0777) + ownership_str = "chown {0}:{1} {2}".format(self._user.userID,rb_group, output_file) if platform.system() != 'Windows': - os.system("chown {0}:{1} {2}".format(self._user.userID, self._user.rb_id, output_file)) + os.system(ownership_str) # Set up the file creation and modification dates to the users start date start_date = self._user.start_date file_time = time.mktime(start_date.timetuple()) @@ -626,6 +641,8 @@ class MantidConfigDirectInelastic(object): # user files description is not there try: domObj = minidom.parse(job_description_file) + # have no idea what minidom specific exception is: + # pylint: disable=W0703 except Exception: input_file, output_file = self._fullpath_to_copy(None,None,cycle_id) filenames_to_copy.append((input_file, output_file, None)) @@ -705,9 +722,9 @@ class MantidConfigDirectInelastic(object): user_folder = os.path.join(self._home_path, self._fedid) if not os.path.exists(user_folder): raise RuntimeError("User with fedID {0} does not exist. Create such user folder first".format(self._fedid)) - # pylint: disable=W0212 - # bad practice but I need all rb_dires, not the current one - for rb_folder in theUser._rb_dirs.values(): + # get RB folders for all experiments user participates in. + all_rbf = theUser.get_all_rb() + for rb_folder in all_rbf: if not os.path.exists(str(rb_folder)): raise RuntimeError( "Experiment folder with {0} does not exist. Create such folder first".format(rb_folder)) @@ -804,24 +821,21 @@ class MantidConfigDirectInelastic(object): for folder in all_data_folders[1:]: data_dir += ';' + os.path.abspath('{0}'.format(folder)) - # pylint: disable=W0212 - all_rb_folders = self._user._rb_dirs - for folder in all_rb_folders.values(): + all_rb_folders = self._user.get_all_rb() + for folder in all_rb_folders: data_dir += ';' + os.path.abspath('{0}'.format(folder)) self._dynamic_configuration.append('datasearch.directories=' + map_mask_dir + ';' + data_dir) # - def generate_config(self): + def generate_config(self,key_users_list=None): """Save generated Mantid configuration file into user's home folder and copy other files, necessary for Mantid to work properly """ user_path = os.path.join(self._home_path, self._fedid) config_path = os.path.join(user_path, '.mantid') if not os.path.exists(config_path): - err = os.makedirs(config_path) - if err: - raise RuntimeError('can not find or create Mantid configuration path {0}'.format(config_path)) + os.makedirs(config_path) config_file = os.path.join(config_path, 'Mantid.user.properties') if self.config_need_replacing(config_file): @@ -833,10 +847,18 @@ class MantidConfigDirectInelastic(object): self.make_map_mask_links(user_path) users_cycles = self._user.get_all_cycles() + users_rb = self._user.get_all_rb() + # extract rb folder without path, which gives RB group name + users_rb = map(os.path.basename,users_rb) # - for cycle in users_cycles: + for cycle,rb_name in zip(users_cycles,users_rb): + if key_users_list: + key_user = str(key_users_list[rb_name]) + if self._fedid.lower() != key_user.lower(): + continue + instr = self._user.get_instrument(cycle) - self.copy_reduction_sample(self.get_user_file_description(instr),cycle) + self.copy_reduction_sample(self.get_user_file_description(instr),cycle,rb_name) # # @@ -922,7 +944,8 @@ if __name__ == "__main__": analysisDir = "/instrument/" # initialize Mantid configuration - + # its testing route under main so it rightly imports itself + #pylint: disable=W0406 from ISISDirecInelasticConfig import MantidConfigDirectInelastic, UserProperties mcf = MantidConfigDirectInelastic(MantidDir, rootDir, UserScriptRepoDir, MapMaskDir) diff --git a/scripts/Inelastic/Direct/NonIDF_Properties.py b/scripts/Inelastic/Direct/NonIDF_Properties.py index 7ec4e98407e3bbe9a8f64bb00122f4bf3c6b3636..e1236a0cf65025993223d30a6e925c575f413806 100644 --- a/scripts/Inelastic/Direct/NonIDF_Properties.py +++ b/scripts/Inelastic/Direct/NonIDF_Properties.py @@ -28,7 +28,7 @@ class NonIDF_Properties(object): deployed in reduction """ # - if not run_workspace is None: + if run_workspace is not None: object.__setattr__(self,'sample_run',run_workspace) # Helper properties, defining logging options diff --git a/scripts/Inelastic/Direct/PropertiesDescriptors.py b/scripts/Inelastic/Direct/PropertiesDescriptors.py index b3bc3d48e4adea56a1ec6a71e6cd2574e974fe34..1fe7d4fab941d966ab44afbf99dbd59e02f7e97d 100644 --- a/scripts/Inelastic/Direct/PropertiesDescriptors.py +++ b/scripts/Inelastic/Direct/PropertiesDescriptors.py @@ -114,6 +114,13 @@ class AvrgAccuracy(PropDescriptor): vallist = [value] rez = [] lim = 10**(self._accuracy-1) + + def out(a,b,mult): + if mult>1: + return a<b + else: + return false + for val in vallist: if abs(val) > lim: rez.append(round(val,0)) @@ -123,14 +130,9 @@ class AvrgAccuracy(PropDescriptor): else: mult = 1 - def out(a,b): - if mult>1: - return a<b - else: - return false tv = abs(val) fin_mult = 1 - while out(tv,lim): + while out(tv,lim,mult): fin_mult*=mult tv *= mult fin_rez = math.copysign(round(tv,0)/fin_mult,val) @@ -315,7 +317,7 @@ class IncidentEnergy(PropDescriptor): ei_ref,_,_,_=GetEi(InputWorkspace=monitor_ws, Monitor1Spec=ei_mon_spec[0], Monitor2Spec=ei_mon_spec[1], EnergyEstimate=ei) fin_ei.append(ei_ref) -#pylint: disable=broad-except +#pylint: disable=bare-except except: instance.log("Can not refine guess energy {0:f}. Ignoring it.".format(ei),'warning') if len(fin_ei) == 0: @@ -472,40 +474,48 @@ class SaveFileName(PropDescriptor): self._custom_print = None def __get__(self,instance,owner=None): - + # getter functional interface. if instance is None: return self - if not self._custom_print is None: - return self._custom_print() + # if custom file name provided, use it if self._file_name: return self._file_name + + # if custom function to generate file name is proivede, use this function + if self._custom_print is not None: + return self._custom_print() + + # user provided nothing. + # calculate default target file name from + # instrument, energy and run number. + if instance.instr_name: + name = instance.short_inst_name else: - if instance.instr_name: - name = instance.short_inst_name - else: - name = '_EMPTY' + name = '_EMPTY' - sr = owner.sample_run.run_number() - if not sr: - sr = 0 - try: - ei = owner.incident_energy.get_current() - name +='{0:0<5}Ei{1:<4.2f}meV'.format(sr,ei) - if instance.sum_runs: - name +='sum' - if owner.monovan_run.run_number(): - name +='_Abs' - name = name.replace('.','d') + sr = owner.sample_run.run_number() + if not sr: + sr = 0 + try: + ei = owner.incident_energy.get_current() + name +='{0:0<5}Ei{1:_<4.2f}meV'.format(sr,ei) + if instance.sum_runs: + name +='sum' + if owner.monovan_run.run_number(): + name +='_Abs' + name = name.replace('.','d') #pylint: disable=bare-except - except: - name = None + except: + name = None return name def __set__(self,instance,value): if value is None: self._file_name = None + elif callable(value): + self._custom_print = value else: self._file_name = str(value) @@ -767,6 +777,7 @@ class DetCalFile(PropDescriptor): file_hint = inst_short_name+str(dcf_val).zfill(zero_padding) try: file_name = FileFinder.findRuns(file_hint)[0] +#pylint: disable=bare-except except: return (False,"Can not find run file corresponding to run N: {0}".format(file_hint)) self._det_cal_file = file_name @@ -796,7 +807,7 @@ class MapMaskFile(PropDescriptor): self._file_ext = file_ext self._prop_name = prop_name - if not doc_string is None: + if doc_string is not None: self.__doc__ = doc_string def __get__(self,instance,class_type=None): @@ -806,7 +817,7 @@ class MapMaskFile(PropDescriptor): return self._file_name def __set__(self,instance,value): - if not value is None: + if value is not None: #pylint: disable=unused-variable fileName, fileExtension = os.path.splitext(value) if not fileExtension: diff --git a/scripts/Inelastic/Direct/PropertyManager.py b/scripts/Inelastic/Direct/PropertyManager.py index 2614d1dbe119668e9f6d01ac7e685527af483a7c..e74ec4c7085453e8497d3e55333bb0d93f3f3706 100644 --- a/scripts/Inelastic/Direct/PropertyManager.py +++ b/scripts/Inelastic/Direct/PropertyManager.py @@ -282,7 +282,7 @@ class PropertyManager(NonIDF_Properties): """ for par_name,value in kwargs.items() : - if not value is None: + if value is not None: setattr(self,par_name,value) # @@ -531,7 +531,7 @@ class PropertyManager(NonIDF_Properties): run_files_prop=['wb_run','monovan_run','mask_run','wb_for_monovan_run','second_white'] map_mask_prop =['det_cal_file','map_file','hard_mask_file'] - abs_units = not self.monovan_run is None + abs_units = self.monovan_run is not None files_to_check =[] # run files to check for prop_name in run_files_prop: @@ -540,7 +540,7 @@ class PropertyManager(NonIDF_Properties): if theProp.is_existing_ws(): # it is loaded workspace continue # we do not care if it has file or not val = theProp.__get__(self,PropertyManager) - if not val is None : + if val is not None : files_to_check.append(prop_name) # other files to check: @@ -551,7 +551,7 @@ class PropertyManager(NonIDF_Properties): # Absolute units files (only one?) if abs_units: val = self.monovan_mapfile - if not val is None : + if val is not None : files_to_check.append('monovan_mapfile') # return files_to_check @@ -747,7 +747,7 @@ class PropertyManager(NonIDF_Properties): save_dir = config.getString('defaultsave.directory') self.log("****************************************************************",log_level) - if self.monovan_run is not None and not 'van_mass' in changed_Keys: # This output is Adroja request from may 2014 + if self.monovan_run is not None and 'van_mass' not in changed_Keys: # This output is Adroja request from may 2014 self.log("*** Monochromatic vanadium mass used : {0} ".format(self.van_mass),log_level) # self.log("*** By default results are saved into: {0}".format(save_dir),log_level) diff --git a/scripts/Inelastic/Direct/ReductionHelpers.py b/scripts/Inelastic/Direct/ReductionHelpers.py index 3035d748f965d69a746934659f08799002b6f319..1d8a8de7e4978016a607f32c0d741225c4394b90 100644 --- a/scripts/Inelastic/Direct/ReductionHelpers.py +++ b/scripts/Inelastic/Direct/ReductionHelpers.py @@ -228,10 +228,12 @@ def build_subst_dictionary(synonims_list=None) : if len(keys) < 2 : raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present") if len(keys[0]) == 0: - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the first key is empty") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, " + "but the first key is empty") for i in xrange(1,len(keys)) : if len(keys[i]) == 0 : - raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, but the key"+str(i)+" is empty") + raise AttributeError("The pairs in the synonyms fields have to have form key1=key2=key3 with at least two values present, " + "but the key"+str(i)+" is empty") kkk = keys[i].strip() rez[kkk]=keys[0].strip() @@ -292,7 +294,7 @@ def check_instrument_name(old_name,new_name): """ function checks if new instrument name is acceptable instrument name""" if new_name is None: - if not old_name is None: + if old_name is not None: return (None,None,config.getFacility()) else: raise KeyError("No instrument name is defined") @@ -339,7 +341,8 @@ def parse_single_name(filename): path1,ind1,ext1=parse_single_name(fl) path2,ind2,ext2=parse_single_name(fr) if ind1>ind2: - raise ValueError('Invalid file number defined using colon : left run number {0} has to be large then right {1}'.format(ind1,ind2)) + raise ValueError('Invalid file number defined using colon : left run number ' + '{0} has to be large then right {1}'.format(ind1,ind2)) number = range(ind1[0],ind2[0]+1) if len(filepath)>0: filepath=[filepath]*len(number) diff --git a/scripts/Inelastic/Direct/ReductionWrapper.py b/scripts/Inelastic/Direct/ReductionWrapper.py index 5e025027bab97cf9d0e861a37e384f0889cb6ec7..e54d91d41116e14de2cdbcc43c8ff6ac96a94755 100644 --- a/scripts/Inelastic/Direct/ReductionWrapper.py +++ b/scripts/Inelastic/Direct/ReductionWrapper.py @@ -205,7 +205,7 @@ class ReductionWrapper(object): or workspace name to validate results against. """ #pylint: disable=protected-access - if not PropertyManager.save_file_name._file_name is None: + if PropertyManager.save_file_name._file_name is not None: #pylint: disable=protected-access file_name = PropertyManager.save_file_name._file_name if isinstance(file_name,api.Workspace): @@ -378,7 +378,7 @@ class ReductionWrapper(object): instead of pause in debug mode """ - if not self._debug_wait_for_files_operation is None: + if self._debug_wait_for_files_operation is not None: # it is callable and the main point of this method is that it is callable #pylint: disable=E1102 self._debug_wait_for_files_operation() @@ -706,7 +706,7 @@ def iliad(reduce): pass # we should set already set up variables using custom_print_function = host.set_custom_output_filename() - if not custom_print_function is None: + if custom_print_function is not None: PropertyManager.save_file_name.set_custom_print(custom_print_function) # rez = reduce(*args) diff --git a/scripts/Inelastic/Direct/RunDescriptor.py b/scripts/Inelastic/Direct/RunDescriptor.py index 13b796deaa89b760c563542592facec0eaa9072e..92fa99c872889109da89ce505008292300b23b08 100644 --- a/scripts/Inelastic/Direct/RunDescriptor.py +++ b/scripts/Inelastic/Direct/RunDescriptor.py @@ -51,7 +51,7 @@ class RunList(object): if not fnames_given: local_fnames.append(file_path) if not fext_given: - if not fext is None: + if fext is not None: if len(fext)==0: fext=None local_fext.append(fext) @@ -354,7 +354,7 @@ class RunDescriptor(PropDescriptor): def __init__(self,prop_name,DocString=None): """ """ self._prop_name = prop_name - if not DocString is None: + if DocString is not None: self.__doc__ = DocString self._ws_name = None @@ -500,7 +500,7 @@ class RunDescriptor(PropDescriptor): # Change existing file path and file extension if alternatives are provided if len(file_path)>0: self._run_file_path = file_path - if not fext is None: # Change only if real new extension is provided + if fext is not None: # Change only if real new extension is provided self._fext = fext @@ -790,7 +790,7 @@ class RunDescriptor(PropDescriptor): self.apply_calibration(ws,RunDescriptor._holder.det_cal_file,prefer_ws_calibration) return ws else: - if not self._run_number is None: + if self._run_number is not None: prefer_ws_calibration = self._check_calibration_source() inst_name = RunDescriptor._holder.short_inst_name calibration = RunDescriptor._holder.det_cal_file @@ -1054,7 +1054,7 @@ class RunDescriptor(PropDescriptor): except RuntimeError: message = '*** Cannot find file matching hint {0} on Mantid search paths '.\ format(file_hint) - if not 'be_quet' in kwargs: + if 'be_quet' not in kwargs: RunDescriptor._logger(message,'warning') return (False,message) #-------------------------------------------------------------------------------------------------------------------- @@ -1178,7 +1178,7 @@ class RunDescriptor(PropDescriptor): else: targ_ws = mtd[other_workspace] - if not 'NormalizationFactor' in source_ws.getRun(): + if 'NormalizationFactor' not in source_ws.getRun(): raise RuntimeError(""" Can not change normalization of target workspace {0} as source workspace {1} is not normalized""" .format(source_ws.name(),targ_ws.name())) @@ -1661,7 +1661,7 @@ def build_run_file_name(run_num,inst,file_path='',fext=''): run_num_str = str(run_num).zfill(zero_padding) fname = '{0}{1}{2}'.format(inst,run_num_str,fext) - if not file_path is None: + if file_path is not None: if os.path.exists(file_path): fname = os.path.join(file_path,fname) return fname diff --git a/scripts/Inelastic/Direct/dgreduce.py b/scripts/Inelastic/Direct/dgreduce.py index 93363709c7cce9d335bad3f3ca891ff62f494aa9..53da051137e7ec56d90377d0efb6d8fd7ce723d6 100644 --- a/scripts/Inelastic/Direct/dgreduce.py +++ b/scripts/Inelastic/Direct/dgreduce.py @@ -171,7 +171,7 @@ def runs_are_equal(ws1,ws2): raise AttributeError except Exception as err: pass - if not err is None: + if err is not None: raise AttributeError("Input parameter is neither workspace nor ws name") return run_num #----------------------------------------------- @@ -186,7 +186,8 @@ def runs_are_equal(ws1,ws2): return run_num1==run_num2 -def abs_units(wb_for_run,sample_run,monovan_run,wb_for_monovanadium,samp_rmm,samp_mass,ei_guess,rebin,map_file='default',monovan_mapfile='default',**kwargs): +def abs_units(wb_for_run,sample_run,monovan_run,wb_for_monovanadium,samp_rmm,samp_mass, + ei_guess,rebin,map_file='default',monovan_mapfile='default',**kwargs): """ dgreduce.abs_units(wb_run Whitebeam run number or file name or workspace sample_run Sample run run number or file name or workspace diff --git a/scripts/Inelastic/Direct/diagnostics.py b/scripts/Inelastic/Direct/diagnostics.py index 9395529f44743f65af880fdb0f28b6a2b1db3e72..0387017ea7f1d93e0e20760de33ec83d4159ad4c 100644 --- a/scripts/Inelastic/Direct/diagnostics.py +++ b/scripts/Inelastic/Direct/diagnostics.py @@ -77,7 +77,7 @@ def diagnose(white_int,**kwargs): # process subsequent calls to this routine, when white mask is already defined white= kwargs.get('white_mask',None) # and white beam is not changed #white mask assumed to be global so no sectors in there - if not white is None and isinstance(white,RunDescriptor.RunDescriptor): + if white is not None and isinstance(white,RunDescriptor.RunDescriptor): hardmask_file = None white_mask,num_failed = white.get_masking(2) add_masking(white_int, white_mask) @@ -86,7 +86,7 @@ def diagnose(white_int,**kwargs): white_mask = None van_mask = CloneWorkspace(white_int) - if not hardmask_file is None: + if hardmask_file is not None: if parser.mapmask_ref_ws is None: ref_ws = white_int else: @@ -334,13 +334,6 @@ def do_background_test(background_int, median_lo, median_hi, sigma, mask_zero, """ logger.notice('Running background count test') - # What shall we call the output - lhs_names = lhs_info('names') - if len(lhs_names) > 0: - ws_name = lhs_names[0] - else: - ws_name = '__do_background_test' - mask_bkgd, num_failures = MedianDetectorTest(InputWorkspace=background_int, StartWorkspaceIndex=start_index, EndWorkspaceIndex=end_index, SignificanceTest=sigma, diff --git a/scripts/Inelastic/IndirectBayes.py b/scripts/Inelastic/IndirectBayes.py index 0cb61bca7a26ee46cc7e67a61171c537be84c8d4..92b59b798976fffa0c28dc3e9a3c6dfc736a02a2 100644 --- a/scripts/Inelastic/IndirectBayes.py +++ b/scripts/Inelastic/IndirectBayes.py @@ -8,7 +8,7 @@ Output : the Fortran numpy array is sliced to Python length using dataY = yout[: """ from IndirectImport import * -if is_supported_f2py_platform(): +if is_supported_f2py_platform(): # noqa QLr = import_f2py("QLres") QLd = import_f2py("QLdata") Qse = import_f2py("QLse") @@ -17,11 +17,8 @@ else: unsupported_message() from mantid.simpleapi import * -from mantid import config, logger, mtd +from mantid import logger, mtd from IndirectCommon import * -import sys -import platform -import math import os.path import numpy as np MTD_PLOT = import_mantidplot() diff --git a/scripts/Inelastic/IndirectMuscat.py b/scripts/Inelastic/IndirectMuscat.py index 9b911a54e615dc25f7a6c9ec53c3d4a33e64b5fa..a7664d1cc7f68ab8ee967e61b8b2d2ed6b4f23e8 100644 --- a/scripts/Inelastic/IndirectMuscat.py +++ b/scripts/Inelastic/IndirectMuscat.py @@ -5,7 +5,7 @@ MUSIC : Version of Minus for MIDAS """ from IndirectImport import * -if is_supported_f2py_platform(): +if is_supported_f2py_platform(): # noqa muscat = import_f2py("muscat") else: unsupported_message() @@ -14,7 +14,6 @@ from mantid.simpleapi import * from mantid import config, logger, mtd from IndirectCommon import * import sys -import platform import math import os.path import numpy as np @@ -245,11 +244,9 @@ def MuscatRun(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): # ims = [NMST, NQ, NW, Nel, KR1] nmst = neut[4] ims = [neut[4], nq, nw, nel, 1] - nw2 = 2*ims[2]+1 # dqw = [DQ, DW] dqw = [dq, dw] sname = sname[:-4] - ySin = [] Qaxis = '' for m in range(0,mang): # rinstr = [efixed, theta, alfa] @@ -387,6 +384,6 @@ def MuscatDataStart(sname,geom,neut,beam,sam,sqw,kr1,Verbose,Plot,Save): def plotMuscat(inWS,spec_list,Plot): if Plot == 'Totals' or Plot == 'All': - tot_plot=mp.plotSpectrum(inWS+'_Totals',spec_list) + mp.plotSpectrum(inWS+'_Totals',spec_list) if Plot == 'Scat1' or Plot == 'All': mp.importMatrixWorkspace(inWS+'_1').plotGraph2D() diff --git a/scripts/Inelastic/IndirectNeutron.py b/scripts/Inelastic/IndirectNeutron.py index 2ff6783437ba80bbc762889dae070b8339ae2ad5..1cd73dc7321f70fda66d59d290f80df1ea371de4 100644 --- a/scripts/Inelastic/IndirectNeutron.py +++ b/scripts/Inelastic/IndirectNeutron.py @@ -79,7 +79,7 @@ def ReadIbackGroup(a, first): # read Ascii block of spectrum values next = first line1 = a[next] next += 1 - _val = ExtractInt(a[next]) + if line1.startswith('S'): error = '' else: @@ -146,7 +146,6 @@ def IbackStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): # As logger.information('Reading file : ' + path) asc = loadFile(path) - _lasc = len(asc) # raw head text = asc[1] @@ -157,8 +156,6 @@ def IbackStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): # As title = asc[next] # title line next += 1 text = asc[next] # user line - _user = text[20:32] - _time = text[40:50] next += 6 # 5 lines of text # back head1 next, Fval = Fblock(asc, next) @@ -168,15 +165,11 @@ def IbackStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): # As freq = Fval[2] amp = Fval[3] wave = Fval[69] - _Ef = 81.787 / (4.0 * wave * wave) npt = int(Fval[6]) nsp = int(Fval[7]) # back head2 next, Fval = Fblock(asc, next) - _k0 = 4.0 * math.pi / wave - _d2r = math.pi / 180.0 theta = [] - _Q = [] for m in range(0, nsp): theta.append(Fval[m]) # raw spectra @@ -253,14 +246,14 @@ def IbackStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): # As AllowDifferentNumberSpectra=True) DeleteWorkspace(monWS) # delete monitor WS InstrParas(ascWS, instr, ana, refl) - _efixed = RunParas(ascWS, instr, run, title) + RunParas(ascWS, instr, run, title) ChangeAngles(ascWS, instr, theta) if useM: map = ReadMap(mapPath) UseMap(ascWS, map) if rejectZ: RejectZero(ascWS, tot) - if useM == False and rejectZ == False: + if not useM and not rejectZ: CloneWorkspace(InputWorkspace=ascWS, OutputWorkspace=outWS) if Save: opath = os.path.join(workdir, outWS + '.nxs') @@ -304,7 +297,6 @@ def InxStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): val = ExtractInt(asc[0]) lgrp = int(val[0]) ngrp = int(val[2]) - _npt = int(val[7]) title = asc[1] ltot = ngrp * lgrp logger.information('Number of spectra : ' + str(ngrp)) @@ -354,7 +346,7 @@ def InxStart(instr, run, ana, refl, rejectZ, useM, mapPath, Plot, Save): UseMap(ascWS, map) if rejectZ: RejectZero(ascWS, tot) - if useM == False and rejectZ == False: + if not useM and not rejectZ: CloneWorkspace(InputWorkspace=ascWS, OutputWorkspace=outWS) if Save: opath = os.path.join(workdir, outWS + '.nxs') @@ -386,8 +378,6 @@ def RejectZero(inWS, tot): def ReadMap(path): - _workdir = config['defaultsave.directory'] - asc = loadFile(path) lasc = len(asc) @@ -486,7 +476,7 @@ def RunParas(ascWS, _instr, run, title): def IN13Start(instr, run, ana, refl, _rejectZ, _useM, _mapPath, Plot, Save): # Ascii start routine StartTime('IN13') - _samWS = IN13Read(instr, run, ana, refl, Plot, Save) + IN13Read(instr, run, ana, refl, Plot, Save) EndTime('IN13') @@ -498,14 +488,12 @@ def IN13Read(instr, run, ana, refl, Plot, Save): # Ascii start routine logger.information('Reading file : ' + path) asc = loadFile(path) - _lasc = len(asc) # header block text = asc[1] run = text[:8] text = asc[4] # run line instr = text[:4] - _time = text[14:33] # user line next, Ival = Iblock(asc, 5) nsubsp = Ival[0] nspec = Ival[153] - 2 @@ -540,7 +528,6 @@ def IN13Read(instr, run, ana, refl, Plot, Save): # Ascii start routine # monitors psd = next + (nspec + 2048) * lspec l1m1 = psd + 1 - _txt = asc[l1m1] l2m1 = l1m1 + 3 mon1 = ExtractFloat(asc[l2m1]) logger.information('Mon1 : Line ' + str(l2m1) + ' : ' + asc[l2m1]) diff --git a/scripts/Inelastic/IndirectReductionCommon.py b/scripts/Inelastic/IndirectReductionCommon.py index 05cd700e50d941ccc134cb8af0f072cad5ebfee6..09994c89695a5b5378d4ee2d4415e536933f193b 100644 --- a/scripts/Inelastic/IndirectReductionCommon.py +++ b/scripts/Inelastic/IndirectReductionCommon.py @@ -1,4 +1,5 @@ #pylint: disable=invalid-name,too-many-branches,too-many-arguments,deprecated-module,no-name-in-module,too-many-locals +from __future__ import (absolute_import, division, print_function) from mantid.api import WorkspaceGroup, AlgorithmManager from mantid import mtd, logger, config @@ -13,7 +14,7 @@ def load_files(data_files, ipf_filename, spec_min, spec_max, sum_files=False, lo Loads a set of files and extracts just the spectra we care about (i.e. detector range and monitor). @param data_files List of data file names - @param ipf_filename FIle path/name for the instrument parameter file to load + @param ipf_filename File path/name for the instrument parameter file to load @param spec_min Minimum spectra ID to load @param spec_max Maximum spectra ID to load @param sum_files Sum loaded files @@ -67,7 +68,7 @@ def load_files(data_files, ipf_filename, spec_min, spec_max, sum_files=False, lo chopped_data = x_max > chop_threshold except IndexError: chopped_data = False - logger.information('Workspace %s need data chop: %s' % (ws_name, str(chopped_data))) + logger.information('Workspace {0} need data chop: {1}'.format(ws_name, str(chopped_data))) workspaces = [ws_name] if chopped_data: @@ -222,7 +223,7 @@ def identify_bad_detectors(workspace_name): """ Identify detectors which should be masked - @param workspace_name Name of worksapce to use ot get masking detectors + @param workspace_name Name of workspace to use to get masking detectors @return List of masked spectra """ from mantid.simpleapi import (IdentifyNoisyDetectors, DeleteWorkspace) @@ -543,7 +544,7 @@ def fold_chopped(workspace_name): def rename_reduction(workspace_name, multiple_files): """ - Renames a worksapce according to the naming policy in the Workflow.NamingConvention parameter. + Renames a workspace according to the naming policy in the Workflow.NamingConvention parameter. @param workspace_name Name of workspace @param multiple_files Insert the multiple file marker @@ -564,7 +565,7 @@ def rename_reduction(workspace_name, multiple_files): try: convention = instrument.getStringParameter('Workflow.NamingConvention')[0] except IndexError: - # Defualt to run title if naming convention parameter not set + # Default to run title if naming convention parameter not set convention = 'RunTitle' logger.information('Naming convention for workspace %s is %s' % (workspace_name, convention)) @@ -642,11 +643,12 @@ def plot_reduction(workspace_name, plot_type): #------------------------------------------------------------------------------- -def save_reduction(worksspace_names, formats, x_units='DeltaE'): +def save_reduction(workspace_names, formats, x_units='DeltaE'): + """ Saves the workspaces to the default save directory. - @param worksspace_names List of workspace names to save + @param workspace_names List of workspace names to save @param formats List of formats to save in @param Output X units """ @@ -654,7 +656,7 @@ def save_reduction(worksspace_names, formats, x_units='DeltaE'): SaveAscii, Rebin, DeleteWorkspace, ConvertSpectrumAxis, SaveDaveGrp) - for workspace_name in worksspace_names: + for workspace_name in workspace_names: if 'spe' in formats: SaveSPE(InputWorkspace=workspace_name, Filename=workspace_name + '.spe') @@ -668,10 +670,9 @@ def save_reduction(worksspace_names, formats, x_units='DeltaE'): Filename=workspace_name + '.nxspe') if 'ascii' in formats: - # Version 1 of SaveAscii produces output that works better with excel/origin - # For some reason this has to be done with an algorithm object, using the function - # wrapper with Version did not change the version that was run - saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 1) + + # Changed to version 2 to enable re-loading of files into mantid + saveAsciiAlg = AlgorithmManager.createUnmanaged('SaveAscii', 2) saveAsciiAlg.initialize() saveAsciiAlg.setProperty('InputWorkspace', workspace_name) saveAsciiAlg.setProperty('Filename', workspace_name + '.dat') diff --git a/scripts/Inelastic/dos/load_castep.py b/scripts/Inelastic/dos/load_castep.py index 30298274e02dcdf7518cbbe1f0da1852fa5df154..04ebc9c8ec028fa7bcfe4fb5dee27552c1faf136 100644 --- a/scripts/Inelastic/dos/load_castep.py +++ b/scripts/Inelastic/dos/load_castep.py @@ -84,7 +84,7 @@ def _parse_castep_file_header(f_handle): @param f_handle - handle to the file. @return tuple of the number of ions and branches in the file """ - num_species, num_ions = 0, 0 + num_species = 0 file_data = {} while True: line = f_handle.readline() diff --git a/scripts/Inelastic/vesuvio/base.py b/scripts/Inelastic/vesuvio/base.py index c058e5bf950575ed52404bd0b3c49a3da5a47dae..d8de87fdb7f1eb0b0266ac7c5f86a8ba4f128d96 100644 --- a/scripts/Inelastic/vesuvio/base.py +++ b/scripts/Inelastic/vesuvio/base.py @@ -11,21 +11,37 @@ class VesuvioBase(Algorithm): # defining a __init__ method _INST = None - # ---------------------------------------------------------------------------------------- - def _execute_child_alg(self, name, **kwargs): + """Execute an algorithms as a child. + By default all outputs are returned but this can be limited + by providing the return_values=[] keyword + """ alg = self.createChildAlgorithm(name) - # Function needs to be set before input ws for fit algs - function_key = 'Function' - if function_key in kwargs: - alg.setProperty(function_key, kwargs[function_key]) - del kwargs[function_key] + # For Fit algorithm, Function & InputWorkspace have to + # be set first and in that order. + if name == 'Fit': + for key in ('Function', 'InputWorkspace'): + alg.setProperty(key, kwargs[key]) + del kwargs[key] + + ret_props = None + if 'return_values' in kwargs: + ret_props = kwargs['return_values'] + if type(ret_props) is str: + ret_props = [ret_props] + del kwargs['return_values'] for name, value in iteritems(kwargs): alg.setProperty(name, value) alg.execute() - outputs = list() - for name in alg.outputProperties(): + + # Assemble return values + if ret_props is None: + # This must be AFTER execute just in case that attached more + # output properties + ret_props = alg.outputProperties() + outputs = [] + for name in ret_props: outputs.append(alg.getProperty(name).value) if len(outputs) == 1: return outputs[0] diff --git a/scripts/Inelastic/vesuvio/commands.py b/scripts/Inelastic/vesuvio/commands.py index 3b28f7ca9de41cf8c94cfa4dfb7a73d5d38ecc92..46d71cd3b24d0f66b51844e0de9e6f64ef378090 100644 --- a/scripts/Inelastic/vesuvio/commands.py +++ b/scripts/Inelastic/vesuvio/commands.py @@ -451,7 +451,6 @@ def _create_user_defined_ties_str(masses): for index, mass in enumerate(masses): if 'ties' in mass: ties = mass['ties'].split(',') - function_dependant_ties= [] function_indentifier = 'f' + str(index) + '.' for t in ties: tie_str = function_indentifier + t diff --git a/scripts/Interface/compile_dgs_ui.py b/scripts/Interface/compile_dgs_ui.py index 95f2ed35ee4a217e6ed4b57bf930cb1dba639c12..58bffea7779c44f4796f1e5c0a20b999ff716a86 100755 --- a/scripts/Interface/compile_dgs_ui.py +++ b/scripts/Interface/compile_dgs_ui.py @@ -1,6 +1,5 @@ #!/usr/bin/env python from compile_util import compile_ui -from distutils.core import setup # Compile resource files for DGS instruments try: diff --git a/scripts/Interface/compile_pd_ui.py b/scripts/Interface/compile_pd_ui.py index 429546a42994e5d4204f6880c9c92c2a057a4735..c0efc722af26be6f34f1b9d55a0d945f87de99da 100755 --- a/scripts/Interface/compile_pd_ui.py +++ b/scripts/Interface/compile_pd_ui.py @@ -1,6 +1,5 @@ #!/usr/bin/env python from compile_util import compile_ui -from distutils.core import setup # Compile resource files for Diffraction instruments try: diff --git a/scripts/Interface/compile_refm_ui.py b/scripts/Interface/compile_refm_ui.py index 6d730cffcce19fa2c45e1b7798ea01697afbd272..10eaf0bf7e0ac80ff6672efa1b1ab5490ab7c6bf 100755 --- a/scripts/Interface/compile_refm_ui.py +++ b/scripts/Interface/compile_refm_ui.py @@ -1,6 +1,5 @@ #!/usr/bin/env python from compile_util import compile_ui -from distutils.core import setup # Compile resource file try: diff --git a/scripts/Interface/compile_sans_ui.py b/scripts/Interface/compile_sans_ui.py index d7a8e65a946f8d347f32b2979646f9778f97f6d1..9913979a7904f5db1e88866157a8fba84b172834 100644 --- a/scripts/Interface/compile_sans_ui.py +++ b/scripts/Interface/compile_sans_ui.py @@ -1,8 +1,6 @@ #!/usr/bin/env python import os -from distutils.core import setup - # Compile resource file for HFIR SANS and EQSANS try: diff --git a/scripts/Interface/reduction_application.py b/scripts/Interface/reduction_application.py index 7e74abf72c249de31e84ba2d3487fe5a34561b10..4625a3aaf5f1fb4078d99a40ab951fff49dbcb04 100644 --- a/scripts/Interface/reduction_application.py +++ b/scripts/Interface/reduction_application.py @@ -9,7 +9,7 @@ import traceback # Check whether Mantid is available IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa IS_IN_MANTIDPLOT = True from mantid.kernel import ConfigService from mantid.api import AlgorithmFactory @@ -19,7 +19,7 @@ except: sip.setapi('QString',2) sip.setapi('QVariant',2) -from PyQt4 import QtGui, QtCore +from PyQt4 import QtGui, QtCore # noqa REDUCTION_WARNING = False WARNING_MESSAGE = "" @@ -40,11 +40,11 @@ if IS_IN_MANTIDPLOT: WARNING_MESSAGE = "Please contact the Mantid team with the following message:\n\n\n" WARNING_MESSAGE += unicode(traceback.format_exc()) -from reduction_gui.instruments.instrument_factory import instrument_factory, INSTRUMENT_DICT -from reduction_gui.settings.application_settings import GeneralSettings -import ui.ui_reduction_main -import ui.ui_instrument_dialog -import ui.ui_cluster_details_dialog +from reduction_gui.instruments.instrument_factory import instrument_factory, INSTRUMENT_DICT # noqa +from reduction_gui.settings.application_settings import GeneralSettings # noqa +import ui.ui_reduction_main # noqa +import ui.ui_instrument_dialog # noqa +import ui.ui_cluster_details_dialog # noqa class ReductionGUI(QtGui.QMainWindow, ui.ui_reduction_main.Ui_SANSReduction): @@ -272,7 +272,7 @@ class ReductionGUI(QtGui.QMainWindow, ui.ui_reduction_main.Ui_SANSReduction): recent_files = [] for fname in self._recent_files: - if fname != self._filename and QtCore.QFile.exists(fname) and not fname in recent_files: + if fname != self._filename and QtCore.QFile.exists(fname) and fname not in recent_files: recent_files.append(fname) if len(recent_files)>0: @@ -393,7 +393,8 @@ class ReductionGUI(QtGui.QMainWindow, ui.ui_reduction_main.Ui_SANSReduction): """ if False: reply = QtGui.QMessageBox.question(self, 'Message', - "Are you sure you want to quit this application?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) + "Are you sure you want to quit this application?", + QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.Yes: event.accept() diff --git a/scripts/Interface/reduction_gui/instruments/dgs_interface_dev.py b/scripts/Interface/reduction_gui/instruments/dgs_interface_dev.py index b80157a4fb94d75bb85602a3a3bfcef8df491281..6bcd498d41472a2d02bc6eb86d3f64cc367073f6 100644 --- a/scripts/Interface/reduction_gui/instruments/dgs_interface_dev.py +++ b/scripts/Interface/reduction_gui/instruments/dgs_interface_dev.py @@ -3,7 +3,6 @@ from reduction_gui.widgets.inelastic.dgs_sample_setup import SampleSetupWidget from reduction_gui.widgets.inelastic.dgs_data_corrections import DataCorrectionsWidget from reduction_gui.widgets.inelastic.dgs_diagnose_detectors import DiagnoseDetectorsWidget from reduction_gui.widgets.inelastic.dgs_absolute_units import AbsoluteUnitsWidget -from reduction_gui.widgets.inelastic.dgs_pd_sc_conversion import PdAndScConversionWidget from reduction_gui.widgets.cluster_status import RemoteJobsWidget from reduction_gui.reduction.inelastic.dgs_reduction_script import DgsReductionScripter @@ -13,7 +12,7 @@ class DgsInterface(InstrumentInterface): Defines the widgets for direct geometry spectrometer reduction """ # Allowed extensions for loading data files - data_type = "Data files *.* (*.*)" + data_type = "Data files * (*)" def __init__(self, name, settings): super(DgsInterface, self).__init__(name, settings) diff --git a/scripts/Interface/reduction_gui/instruments/diffraction_interface_dev.py b/scripts/Interface/reduction_gui/instruments/diffraction_interface_dev.py index cc8292e44495fde919428988dd7842d48b58fdff..95bb5ba0d2636d020ccb09d5d2874178998d52a3 100644 --- a/scripts/Interface/reduction_gui/instruments/diffraction_interface_dev.py +++ b/scripts/Interface/reduction_gui/instruments/diffraction_interface_dev.py @@ -13,7 +13,7 @@ class DiffractionInterface(InstrumentInterface): Defines the widgets for direct geometry spectrometer reduction """ # Allowed extensions for loading data files - data_type = "Data files *.* (*.*)" + data_type = "Data files * (*)" def __init__(self, name, settings): """ diff --git a/scripts/Interface/reduction_gui/instruments/eqsans_interface_dev.py b/scripts/Interface/reduction_gui/instruments/eqsans_interface_dev.py index 0874d9d6063de283097fafd63c20ac63223cdf9c..3b445b475b6e16bd080eadfd8846c5fb52614b74 100644 --- a/scripts/Interface/reduction_gui/instruments/eqsans_interface_dev.py +++ b/scripts/Interface/reduction_gui/instruments/eqsans_interface_dev.py @@ -19,7 +19,7 @@ from reduction_gui.widgets.cluster_status import RemoteJobsWidget IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa from reduction_gui.widgets.sans.stitcher import StitcherWidget IS_IN_MANTIDPLOT = True except: diff --git a/scripts/Interface/reduction_gui/instruments/hfir_interface_dev.py b/scripts/Interface/reduction_gui/instruments/hfir_interface_dev.py index 1a33153ace0866cbc5a25a5ab91683d5c080a4c7..791e3e1d9ab56bf4713c4f0a2887e368ee4adb01 100644 --- a/scripts/Interface/reduction_gui/instruments/hfir_interface_dev.py +++ b/scripts/Interface/reduction_gui/instruments/hfir_interface_dev.py @@ -19,7 +19,7 @@ from reduction_gui.reduction.sans.hfir_data_proxy import DataProxy IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa from reduction_gui.widgets.sans.stitcher import StitcherWidget IS_IN_MANTIDPLOT = True except: diff --git a/scripts/Interface/reduction_gui/instruments/instrument_factory.py b/scripts/Interface/reduction_gui/instruments/instrument_factory.py index 81fe389f70f455077297ab3e836af08769572d20..9c2dcfeea9a184b99d169444d61bd927e781c84f 100644 --- a/scripts/Interface/reduction_gui/instruments/instrument_factory.py +++ b/scripts/Interface/reduction_gui/instruments/instrument_factory.py @@ -29,7 +29,7 @@ INSTRUMENT_DICT = {"HFIR": {"BIOSANS": HFIRInterface, "PG3": DiffractionInterface, "NOM": DiffractionInterface, "VULCAN": DiffractionInterface} - } + } def instrument_factory(instrument_name, settings=None): diff --git a/scripts/Interface/reduction_gui/instruments/interface.py b/scripts/Interface/reduction_gui/instruments/interface.py index fb2f00e4ae499edf74a1b6d0ea254ad6bf2034bd..6e1be59a92a53a08e8fa01c62757b57a53b3c7ae 100644 --- a/scripts/Interface/reduction_gui/instruments/interface.py +++ b/scripts/Interface/reduction_gui/instruments/interface.py @@ -6,7 +6,6 @@ from PyQt4 import QtGui import sys import os import traceback -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.reduction.scripter import BaseReductionScripter @@ -207,7 +206,7 @@ class InstrumentInterface(object): # Otherwise take the 'normal' path self.scripter.apply() self.set_running(False) - except RuntimeError, e: + except RuntimeError: if self._settings.debug: msg = "Reduction could not be executed:\n\n%s" % unicode(traceback.format_exc()) else: diff --git a/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py b/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py index 120408e4cc0d50c89835b0494f55e3b548960dcb..309cc73e1f485962fca0b20deec71c455ceb57d1 100644 --- a/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py +++ b/scripts/Interface/reduction_gui/reduction/diffraction/diffraction_filter_setup_script.py @@ -4,8 +4,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py index 14cc8d42619f128549d647e473ed3fb2978affc2..405c3d7699480d890031f8ee550f01d939859d1f 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_absolute_units_script.py @@ -4,8 +4,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py index 128097da2321beba93893c7cad55d8bd51f6ce68..3dfe780709f6fb5138e90793844df077d7a1851b 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_data_corrections_script.py @@ -4,8 +4,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py index 7d570a645e496747be413ebcb856aa904e0dca4c..7acb23c5f93562a348af24fc83c983733cc55594 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_diagnose_detectors_script.py @@ -4,8 +4,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_pd_sc_conversion_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_pd_sc_conversion_script.py index d0fc6e59415031244c59643c537cad91883e3492..1280952723a3493af03b2fa2c1313de40bc6b4c0 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_pd_sc_conversion_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_pd_sc_conversion_script.py @@ -3,8 +3,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py index 3f95b51454fc56da6ad5ead301b5a462406a362a..be1813e5d6facd3f873eb8d0ed9908ca4e5b841c 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_reduction_script.py @@ -4,8 +4,6 @@ from the the interface class so that the DgsReduction class could be used independently of the interface implementation """ -import xml.dom.minidom -import os import time import mantid from reduction_gui.reduction.scripter import BaseReductionScripter @@ -121,7 +119,6 @@ class DgsReductionScripter(BaseReductionScripter): """ """ data_files = [] - data_options = None for item in self._observers: state = item.state() if state is not None: diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py index 74c8389dc3cecbaf5c064a2456c3c0db4d37e1e7..030a1a77cb9e9df11675538447c702e283e7305c 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_sample_data_setup_script.py @@ -5,7 +5,6 @@ be used independently of the interface implementation """ import os -import time import xml.dom.minidom from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py index 587ca4a0d32785b8050e89548d1cb320d9965d29..a875acfc41178c365996564beb942175d4a2dca7 100644 --- a/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py +++ b/scripts/Interface/reduction_gui/reduction/inelastic/dgs_utils.py @@ -1,6 +1,8 @@ +import os + IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa from mantid.kernel import config from mantid.api import AnalysisDataService from mantid.simpleapi import LoadEmptyInstrument @@ -8,8 +10,6 @@ try: except: pass -import os - class InstrumentParameters(object): instrument_name = None diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_series.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_series.py index 4651bbeabace2b8716f2cfccd0820c786aa392cb..7061a8ec7e6b1a084646f95ecd7ca754551a865d 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_series.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_data_series.py @@ -3,12 +3,11 @@ from the the interface class so that the HFIRReduction class could be used independently of the interface implementation """ +from __future__ import (absolute_import, division, print_function) import xml.dom.minidom -import os -import time from reduction_gui.reduction.scripter import BaseScriptElement -from refl_data_script import DataSets as REFLDataSets -from refm_data_script import DataSets as REFMDataSets +from reduction_gui.reduction.reflectometer.refl_data_script import DataSets as REFLDataSets +from reduction_gui.reduction.reflectometer.refm_data_script import DataSets as REFMDataSets class DataSeries(BaseScriptElement): diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py index a58528a229e8caf508b9ea0e0891b160c6414aeb..f3a913d929a2894de4df69d37535447b4ae5420d 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_reduction.py @@ -3,7 +3,6 @@ This class holds all the necessary information to create a reduction script. """ import time -import os from reduction_gui.reduction.scripter import BaseReductionScripter diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py index 90fe8454d5885b8238a33f75135233333afc40d4..2f6aa39f0c87a6090c653599e721b0d702f811ee 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator.py @@ -9,7 +9,7 @@ import sys # Check whether Mantid is available try: - import mantidplot + import mantidplot # noqa HAS_MANTID = True except: HAS_MANTID = False diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py index 9d8ead30170ab8918ee939277e70e5483bb80edc..1d79a37982c377cb9182dddfd30a8bab1adda390 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_script.py @@ -4,8 +4,6 @@ be used independently of the interface implementation """ import xml.dom.minidom -import os -import time from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_series.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_series.py index c5d24e8b25b2584adbc6fe96567d113057e2464f..9719d8e146bed19528f499297be87de03b3ee435 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_series.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refl_sf_calculator_data_series.py @@ -4,11 +4,8 @@ be used independently of the interface implementation """ import xml.dom.minidom -import os -import time from reduction_gui.reduction.scripter import BaseScriptElement from refl_sf_calculator_data_script import DataSets as REFLDataSets -from refm_data_script import DataSets as REFMDataSets class DataSeries(BaseScriptElement): diff --git a/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py b/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py index bab9968cf68205b823b3e0b6d518ee2bca226a3e..2e86224f60fb60818b47c2f0d8598db9ec2be596 100644 --- a/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py +++ b/scripts/Interface/reduction_gui/reduction/reflectometer/refm_data_script.py @@ -3,7 +3,6 @@ """ import xml.dom.minidom import os -import time from reduction_gui.reduction.scripter import BaseScriptElement diff --git a/scripts/Interface/reduction_gui/reduction/sans/data_cat.py b/scripts/Interface/reduction_gui/reduction/sans/data_cat.py index 595b8aedddedcb267171ae5de456b2cb6a23e471..71ff24832a555e7ca21d34788148249334ff10a0 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/data_cat.py +++ b/scripts/Interface/reduction_gui/reduction/sans/data_cat.py @@ -12,7 +12,7 @@ import traceback # Only way that I have found to use the logger from both the command line # and mantiplot try: - import mantidplot + import mantidplot # noqa from mantid.kernel import logger except ImportError: import logging @@ -44,7 +44,7 @@ class DataType(object): """ Add a data type entry to the datatype table """ - if not type_id in cls.DATA_TYPES.keys(): + if type_id not in cls.DATA_TYPES.keys(): raise RuntimeError("DataType got an unknown type ID: %s" % type_id) t = (type_id, dataset_id,) diff --git a/scripts/Interface/reduction_gui/reduction/sans/eqsans_background_script.py b/scripts/Interface/reduction_gui/reduction/sans/eqsans_background_script.py index 35d5aab385d68faa6e45de77f19855cffafba179..4524230253fc944c26270af0471eb9d695a77fef 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/eqsans_background_script.py +++ b/scripts/Interface/reduction_gui/reduction/sans/eqsans_background_script.py @@ -22,7 +22,8 @@ class Background(BaseBackground): Generate reduction script """ if len(str(self.sample_file).strip())==0 or len(str(self.direct_beam).strip())==0: - raise RuntimeError("Direct beam method for background transmission was selected but was selected but all the appropriate data files were not entered.") + raise RuntimeError("Direct beam method for background transmission was selected but was selected " + "but all the appropriate data files were not entered.") return "BckDirectBeamTransmission(\"%s\", \"%s\", beam_radius=%g)\n" % \ (self.sample_file, self.direct_beam, self.beam_radius) diff --git a/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py b/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py index e2b02504b08b3809a1fe94fdc397bcee49495b9f..56378304450f961c64883b920dfff48289b48126 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py +++ b/scripts/Interface/reduction_gui/reduction/sans/eqsans_catalog.py @@ -6,7 +6,6 @@ from reduction_gui.reduction.sans.data_cat import DataCatalog as BaseCatalog from reduction_gui.reduction.sans.data_cat import DataSet from data_cat import DataType import re -import time import datetime # Check whether Mantid is available @@ -61,7 +60,7 @@ class EQSANSDataSet(DataSet): else: # Check whether we simply have a run number try: - run = int(file_path) + int(file_path) return file_path except: return None diff --git a/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_proxy.py b/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_proxy.py index f1296b6f093d4469089808c7af7bace08a4e0146..23666f36a7651e0e9e139f320c4fca13ef41ac5a 100755 --- a/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_proxy.py +++ b/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_proxy.py @@ -1,8 +1,8 @@ import sys # Check whether Mantid is available try: - from mantid.api import AnalysisDataService - from mantid.kernel import Logger + from mantid.api import AnalysisDataService # noqa + from mantid.kernel import Logger # noqa import mantid.simpleapi as api HAS_MANTID = True except: diff --git a/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py b/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py index 9c0fd15c0bd460926f033c8fefc87758d66b005d..45f76ccc2636b04d8e8c865deec38249fd5e6bc0 100755 --- a/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py +++ b/scripts/Interface/reduction_gui/reduction/sans/eqsans_data_script.py @@ -1,8 +1,6 @@ """ Data set options for EQSANS reduction """ -import xml.dom.minidom -from reduction_gui.reduction.scripter import BaseScriptElement from reduction_gui.reduction.sans.eqsans_sample_script import SampleData as BaseSampleData from reduction_gui.reduction.sans.eqsans_background_script import Background diff --git a/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py b/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py index bde0a2e322d120034b49fbc9de3dc6362c9c4a63..4f60d35536b500187ec8a6e03885cf5057a6d96e 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py +++ b/scripts/Interface/reduction_gui/reduction/sans/hfir_background_script.py @@ -11,7 +11,7 @@ from reduction_gui.reduction.sans.hfir_sample_script import SampleData # Disable unused import warning # pylint: disable=W0611 try: - import mantidplot + import mantidplot # noqa IS_IN_MANTIDPLOT = True except(ImportError, ImportWarning): IS_IN_MANTIDPLOT = False diff --git a/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py b/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py index 3b5e04574a406213f3deb24a609afd365dbd3a2d..573be130556bb6b04cbea5e500b8ba144bb2354b 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py +++ b/scripts/Interface/reduction_gui/reduction/sans/hfir_detector_script.py @@ -9,7 +9,7 @@ from reduction_gui.reduction.scripter import BaseScriptElement # Disable unused import warning # pylint: disable=W0611 try: - import mantidplot + import mantidplot # noqa IS_IN_MANTIDPLOT = True except(ImportError, ImportWarning): IS_IN_MANTIDPLOT = False diff --git a/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py b/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py index 948f4b5470f67f1cf14362ec4aa79389c941ae46..576e07130d23d6bdd097f9ec12b61f677fd602b1 100644 --- a/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py +++ b/scripts/Interface/reduction_gui/reduction/sans/hfir_sample_script.py @@ -12,7 +12,7 @@ from reduction_gui.reduction.scripter import BaseScriptElement # Disable unused import warning # pylint: disable=W0611 try: - import mantidplot + import mantidplot # noqa IS_IN_MANTIDPLOT = True except(ImportError, ImportWarning): IS_IN_MANTIDPLOT = False diff --git a/scripts/Interface/reduction_gui/reduction/scripter.py b/scripts/Interface/reduction_gui/reduction/scripter.py index efeb532ebd6f3a14adadf796550f91fa1a33648f..ff64214ad7700290bd418afeed4f86605fc22f6d 100644 --- a/scripts/Interface/reduction_gui/reduction/scripter.py +++ b/scripts/Interface/reduction_gui/reduction/scripter.py @@ -3,6 +3,7 @@ Reduction scripter used to take reduction parameters end produce a Mantid reduction script """ +from __future__ import (absolute_import, division, print_function) # Check whether Mantid is available # Disable unused import warning # pylint: disable=W0611 @@ -613,7 +614,7 @@ class BaseReductionScripter(object): if HAS_MANTIDPLOT: mantidplot.runPythonScript(script, True) else: - exec script + exec(script) def reset(self): """ diff --git a/scripts/Interface/reduction_gui/reduction/toftof/toftof_reduction.py b/scripts/Interface/reduction_gui/reduction/toftof/toftof_reduction.py index ebd34a166014897d1447e8256cb092f545345b3a..9bdd3e5e3201467b5f1597c60aacc5eec5314d42 100644 --- a/scripts/Interface/reduction_gui/reduction/toftof/toftof_reduction.py +++ b/scripts/Interface/reduction_gui/reduction/toftof/toftof_reduction.py @@ -7,9 +7,6 @@ TOFTOF reduction workflow gui. """ import xml.dom.minidom -from PyQt4.QtCore import * -from PyQt4.QtGui import * - from reduction_gui.reduction.scripter import BaseScriptElement, BaseReductionScripter #------------------------------------------------------------------------------- diff --git a/scripts/Interface/reduction_gui/widgets/base_widget.py b/scripts/Interface/reduction_gui/widgets/base_widget.py index 3fee1b7df10a9ae73a3b4d2eed17123b5e11ec1e..1d4333d41e0344060947039999d82e22d5e1cf49 100644 --- a/scripts/Interface/reduction_gui/widgets/base_widget.py +++ b/scripts/Interface/reduction_gui/widgets/base_widget.py @@ -1,5 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import os import types from reduction_gui.settings.application_settings import GeneralSettings diff --git a/scripts/Interface/reduction_gui/widgets/cluster_status.py b/scripts/Interface/reduction_gui/widgets/cluster_status.py index a1381e50835635c01da68a798c2d70a897b4defd..3ef09b14c0f62a5295513b9d25765e3e570dcd62 100644 --- a/scripts/Interface/reduction_gui/widgets/cluster_status.py +++ b/scripts/Interface/reduction_gui/widgets/cluster_status.py @@ -1,15 +1,12 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -import os +from PyQt4 import QtGui, QtCore import sys -import datetime from functools import partial from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.widgets import util import ui.ui_cluster_status -import mantid.simpleapi as api from mantid.kernel import ConfigService, DateAndTime, Logger from mantid.api import AlgorithmManager @@ -172,7 +169,6 @@ class RemoteJobsWidget(BaseWidget): job_name = alg.getProperty("JobName").value job_trans_id = alg.getProperty("TransID").value - njobs = len(job_name) job_start = alg.getProperty("StartDate").value job_end = alg.getProperty("CompletionDate").value diff --git a/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py b/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py index c85e4aad7b532d43d59b1ff863de740a2035ab1b..00716470a2d499fbe7e5e36db53e8bcba21caf77 100644 --- a/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py +++ b/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_filter_setup.py @@ -2,10 +2,8 @@ ################################################################################ # Event Filtering (and advanced) Setup Widget ################################################################################ -from PyQt4 import QtGui, uic, QtCore -from functools import partial +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget -import reduction_gui.widgets.util as util from reduction_gui.reduction.diffraction.diffraction_filter_setup_script import FilterSetupScript import ui.diffraction.ui_diffraction_filter_setup @@ -195,7 +193,8 @@ class FilterSetupWidget(BaseWidget): self._content.valuechange_combo.setCurrentIndex(index) else: self._content.valuechange_combo.setCurrentIndex(0) - print "Input value of filter log value by changing direction '%s' is not allowed." % (state.filterlogvaluebychangingdirection) + print "Input value of filter log value by changing direction '%s' is not allowed." % \ + (state.filterlogvaluebychangingdirection) else: # Default self._content.valuechange_combo.setCurrentIndex(0) @@ -263,7 +262,6 @@ class FilterSetupWidget(BaseWidget): """ Handling event if run number is changed... If it is a valid run number, the load the meta data """ - from datetime import datetime # 1. Form the file newrunnumberstr = self._content.run_number_edit.text() @@ -335,7 +333,7 @@ class FilterSetupWidget(BaseWidget): # Get property run = self._metaws.getRun() try: - logproperty = run.getProperty(str(logname)) + run.getProperty(str(logname)) except RuntimeError: # Unable to plot msg3 = str("Error! Workspace %s does not contain log %s. " % (str(self._metaws), diff --git a/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py b/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py index 1c75c1d43b7642312465bef7618bde53b0b53c2e..461db0b6b959d27f274a33161327d8153ea0ce4f 100644 --- a/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py +++ b/scripts/Interface/reduction_gui/widgets/diffraction/diffraction_run_setup.py @@ -10,11 +10,10 @@ from reduction_gui.reduction.diffraction.diffraction_run_setup_script import Run import ui.diffraction.ui_diffraction_run_setup import ui.diffraction.ui_diffraction_info -#import mantid.simpleapi as api IS_IN_MANTIDPLOT = False try: - from mantid.api import * - from mantid.kernel import * + from mantid.api import * # noqa + from mantid.kernel import * # noqa IS_IN_MANTIDPLOT = True except: pass @@ -280,7 +279,7 @@ class RunSetupWidget(BaseWidget): s.doresamplex = False try: s.binning = float(self._content.binning_edit.text()) - except ValueError as e: + except ValueError: raise RuntimeError('Binning parameter is not given!') if s.binning < 0. and bintypestr.startswith('Linear'): @@ -309,7 +308,7 @@ class RunSetupWidget(BaseWidget): def _calfile_browse(self): """ Event handing for browsing calibrtion file """ - fname = self.data_browse_dialog(data_type="*.h5;;*.cal;;*.hd5;;*.hdf;;*.*") + fname = self.data_browse_dialog(data_type="*.h5;;*.cal;;*.hd5;;*.hdf;;*") if fname: self._content.calfile_edit.setText(fname) @@ -318,7 +317,7 @@ class RunSetupWidget(BaseWidget): def _charfile_browse(self): """ Event handing for browsing calibrtion file """ - fname = self.data_browse_dialog("*.txt;;*.*") + fname = self.data_browse_dialog("*.txt;;*") if fname: self._content.charfile_edit.setText(fname) @@ -328,7 +327,7 @@ class RunSetupWidget(BaseWidget): """ Event handling for browsing Exp Ini file :return: """ - exp_ini_file_name = self.data_browse_dialog(data_type="*.ini;;*.*") + exp_ini_file_name = self.data_browse_dialog(data_type="*.ini;;*") if exp_ini_file_name: self._content.lineEdit_expIniFile.setText(exp_ini_file_name) diff --git a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py index d0a13e743edf73ccf57387db267648f03076cf05..ffc55b4468aa20a58d24c9c8ae6af4b4c34a2c58 100644 --- a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py +++ b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_data_corrections.py @@ -1,6 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -from functools import partial +from PyQt4 import QtGui, QtCore from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_data_corrections_script import DataCorrectionsScript import reduction_gui.widgets.util as util diff --git a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py index 60127521ecaabce6df284429bdc6a8e71973ef5b..1006cc6bf6f18f3e949aec6f663f4678a500575b 100644 --- a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py +++ b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_pd_sc_conversion.py @@ -1,5 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_pd_sc_conversion_script import PdAndScConversionScript diff --git a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py index af70e5a237b82618f8a36d4287f150bbb0a04157..fc6c562eff5eef37525ba791d1a273d96df32542 100644 --- a/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py +++ b/scripts/Interface/reduction_gui/widgets/inelastic/dgs_sample_setup.py @@ -1,5 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore from functools import partial from reduction_gui.widgets.base_widget import BaseWidget from reduction_gui.reduction.inelastic.dgs_sample_data_setup_script import SampleSetupScript diff --git a/scripts/Interface/reduction_gui/widgets/output.py b/scripts/Interface/reduction_gui/widgets/output.py index 4b9ed1a8ea08fca83c13731affc56897700f7f29..523fb4d45f93e583e9166908b4f3408349cf4385 100644 --- a/scripts/Interface/reduction_gui/widgets/output.py +++ b/scripts/Interface/reduction_gui/widgets/output.py @@ -1,4 +1,4 @@ -from PyQt4 import QtGui, QtCore +from PyQt4 import QtGui from reduction_gui.reduction.output_script import Output from base_widget import BaseWidget import ui.ui_hfir_output diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py b/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py index a01cc28da4beba28e30224a0dd4b3ffece1ec8c7..5acf3b6f02447462020d0cf6206ccfb9d8af79ae 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/LoadSNSRoi.py @@ -1,5 +1,4 @@ #pylint: disable=invalid-name -import sys """ This algorithm reads the SNS ROI files (used in M. Reuter data reduction). diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py b/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py index 0ea9f4504ae548c951940e1c62952a72f95d69c3..d06336dbf6016858ef24eb2876b315f68085f6ca 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/base_ref_reduction.py @@ -506,14 +506,12 @@ class BaseRefWidget(BaseWidget): for ws in scaled_ws_list: # print 'file_number: ' , file_number data_y = mtd[ws].dataY(0) - _data_e = mtd[ws].dataE(0) # cleanup data 0-> NAN for y_val in data_y: # print '-> data_y[j]: ' , data_y[j] , ' data_e[j]: ' , data_y[j] if y_val < 1e-12: _y_val = np.nan - _y_val = np.nan _file_number += 1 @@ -712,7 +710,6 @@ class BaseRefWidget(BaseWidget): def _edit_event(self, text=None, ctrl=None): if text is None: text = "" - _text = text self._summary.edited_warning_label.show() util.set_edited(ctrl, True) @@ -1004,7 +1001,6 @@ class BaseRefWidget(BaseWidget): For REFM, this is X For REFL, this is Y """ - _is_peak = is_peak # run_number = self._summary.data_run_number_edit.text() # f = FileFinder.findRuns("%s%s" % (self.instrument_name, str(run_number)))[0] # diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py b/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py index 019049b34084e100f9364159f21574be097bd281..596b128faf1df59471b94aad142db3d7756cfedd 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/launch_peak_back_selection_1d.py @@ -450,7 +450,6 @@ class DesignerMainWindow(QtGui.QMainWindow): def on_release(self, event): """on release we reset the press data""" - _event = event self.xpress = None self.rect.figure.canvas.draw() diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py index 10051b3849d60555ab8f65f8caae429a41a8a2c5..7fc353981cea95ad94d933256ebe06df403cd7aa 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_data_simple.py @@ -243,7 +243,6 @@ class DataReflWidget(BaseWidget): self._edit_event(ctrl=self._summary.data_run_number_edit) def _edit_event(self, text=None, ctrl=None): - _text = text self._summary.edited_warning_label.show() util.set_edited(ctrl, True) @@ -648,7 +647,6 @@ class DataReflWidget(BaseWidget): For REFM, this is X For REFL, this is Y """ - _is_peak = is_peak minimum, maximum = self._integrated_plot(True, self._summary.data_run_number_edit, self._summary.data_peak_from_pixel, self._summary.data_peak_to_pixel) diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py index 5283b00bd82b84a3f158487b42ae837bc5a24d10..18ce93ea1561633a963be8c4ef2b93325f6240dc 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_reduction.py @@ -1,14 +1,8 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -import reduction_gui.widgets.util as util +from PyQt4 import QtGui, QtCore import math -import os -import time -import sys -from functools import partial from reduction_gui.reduction.reflectometer.refl_data_script import DataSets as REFLDataSets from reduction_gui.reduction.reflectometer.refl_data_series import DataSeries -from reduction_gui.settings.application_settings import GeneralSettings from base_ref_reduction import BaseRefWidget import ui.reflectometer.ui_data_refl_simple diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py index d85d073c0ef82e91371220b18c9a5739e0bcace8..6b360758b469249f15f2d047bdb75d5bf43bc6b8 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/refl_sf_calculator.py @@ -1,20 +1,17 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util import math import os -import time -import sys from functools import partial from reduction_gui.reduction.reflectometer.refl_sf_calculator_data_script import DataSets as REFLDataSets from reduction_gui.reduction.reflectometer.refl_sf_calculator_data_series import DataSeries -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget as BaseRefWidget import ui.reflectometer.ui_refl_sf_calculator IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa from mantid.simpleapi import * from reduction.instruments.reflectometer import data_manipulation IS_IN_MANTIDPLOT = True @@ -287,7 +284,6 @@ class DataReflSFCalculatorWidget(BaseRefWidget): def _add_data(self): state = self.get_editing_state() # state = self.get_state() - in_list = False # Check whether it's already in the list run_numbers = self._summary.data_run_number_edit.text() if run_numbers == '': @@ -297,7 +293,6 @@ class DataReflSFCalculatorWidget(BaseRefWidget): if len(list_items)>0: list_items[0].setData(QtCore.Qt.UserRole, state) - in_list = True #loop over all the already defined states and give all of them the #same tof_min, tof_max and incident_medium list and index selected... diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py b/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py index 56a48efc3b43fd52e661dc9f8f6460f90c3ab25d..f2ee72f0a4b6cd40cb0dcb63c93298b645e63fde 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/refm_reduction.py @@ -1,20 +1,17 @@ #pylint: disable=invalid-name, too-many-arguments -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util import math import os -import time -import sys from functools import partial from reduction_gui.reduction.reflectometer.refm_data_script import DataSets as REFMDataSets from reduction_gui.reduction.reflectometer.refl_data_series import DataSeries -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget import ui.reflectometer.ui_refm_reduction IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa from mantid.api import * #TODO: this will need to change once we get rid of the old python API from reduction.instruments.reflectometer import data_manipulation @@ -219,7 +216,6 @@ class DataReflWidget(BaseWidget): self._edit_event(ctrl=self._summary.data_run_number_edit) def _edit_event(self, text=None, ctrl=None): - _text = text self._summary.edited_warning_label.show() util.set_edited(ctrl,True) @@ -483,7 +479,6 @@ class DataReflWidget(BaseWidget): def _plot_count_vs_y(self, is_peak=True): # removes un-used argument warning for pylint - _is_peak = is_peak """ Plot counts as a function of high-resolution pixels and select peak range @@ -614,13 +609,11 @@ class DataReflWidget(BaseWidget): def _add_data(self): state = self.get_editing_state() - _in_list = False # Check whether it's already in the list run_numbers = self._summary.data_run_number_edit.text() list_items = self._summary.angle_list.findItems(run_numbers, QtCore.Qt.MatchFixedString) if len(list_items) > 0: list_items[0].setData(QtCore.Qt.UserRole, state) - _in_list = True else: item_widget = QtGui.QListWidgetItem(run_numbers, self._summary.angle_list) item_widget.setData(QtCore.Qt.UserRole, state) diff --git a/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py b/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py index 3db6edabb03803c1c8d74c654484cd9257917e0a..ac64f2308d82ad9eca85f5119e83cfec16d48c89 100644 --- a/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py +++ b/scripts/Interface/reduction_gui/widgets/reflectometer/stitcher.py @@ -1,16 +1,14 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import sip import os import sys -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget -import reduction_gui.widgets.util as util import ui.reflectometer.ui_refl_stitching import mantidplot from mantid.simpleapi import * -from LargeScaleStructures.data_stitching import DataSet, Stitcher, RangeSelector +from LargeScaleStructures.data_stitching import DataSet, Stitcher from reduction_gui.reduction.scripter import BaseScriptElement @@ -560,7 +558,8 @@ class StitcherWidget(BaseWidget): else: #REF_M for item in AnalysisDataService.getObjectNames(): - if item.startswith("reflectivity") and not item.endswith("scaled") and item.find('On_Off')<0 and item.find('Off_On')<0 and item.find('On_On')<0: + if item.startswith("reflectivity") and not item.endswith("scaled") and \ + item.find('On_Off')<0 and item.find('Off_On')<0 and item.find('On_On')<0: self._add_entry(item) if len(self._workspace_list)>0: diff --git a/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py b/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py index ca89c4804f53463a63ea2ac8decb67314b65f7ae..856499ff4020531fa10dada6cc513d9b6fca5822 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py +++ b/scripts/Interface/reduction_gui/widgets/sans/eqsans_data.py @@ -1,9 +1,8 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util import os from reduction_gui.reduction.sans.eqsans_data_script import DataSets -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget import ui.sans.ui_eqsans_sample_data @@ -213,7 +212,8 @@ class DataSetsWidget(BaseWidget): # things will look weird. if len(popup_warning)==0: popup_warning = "Turn on debug mode to see all options:\n\n" - popup_warning += "The background transmission for the loaded reduction was set in debug mode to %-6.1g\n" % state.background.bck_transmission + popup_warning += "The background transmission for the loaded reduction was set in debug mode to %-6.1g\n" % \ + state.background.bck_transmission self._content.bck_theta_dep_chk.setChecked(state.background.theta_dependent) self._content.bck_fit_together_check.setChecked(state.background.combine_transmission_frames) diff --git a/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py b/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py index 0f22c2aa3cf1e45baf994083efdb8d66ef24b21d..452c1fcdec13bf0080032a5267c3fa4b6ea25bdc 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py +++ b/scripts/Interface/reduction_gui/widgets/sans/eqsans_instrument.py @@ -1,7 +1,6 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util -import math import os from reduction_gui.reduction.sans.eqsans_options_script import ReductionOptions from reduction_gui.settings.application_settings import GeneralSettings @@ -199,7 +198,8 @@ class SANSInstrumentWidget(BaseWidget): def _mask_plot_clicked(self): ws_name = os.path.basename(str(self._summary.mask_edit.text())) self.mask_ws = "__mask_%s" % ws_name - self.show_instrument(self._summary.mask_edit.text, workspace=self.mask_ws, tab=2, reload=self.mask_reload, mask=self._masked_detectors) + self.show_instrument(self._summary.mask_edit.text, workspace=self.mask_ws, tab=2, + reload=self.mask_reload, mask=self._masked_detectors) self._masked_detectors = [] self.mask_reload = False diff --git a/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py b/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py index 197a306450faceee4596a6baa958a12951f29d43..2a33363585f5564d56c787ff3ef9eb5d00088786 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py +++ b/scripts/Interface/reduction_gui/widgets/sans/hfir_background.py @@ -1,9 +1,7 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util -import os from reduction_gui.reduction.sans.hfir_background_script import Background -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget from hfir_sample_data import BeamSpreader, DirectBeam import ui.sans.ui_hfir_background diff --git a/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py b/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py index 34e1c5744c1ceb782875470df8e990fa626339a9..5841534d7127e2844a636038d28766c999e68b53 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py +++ b/scripts/Interface/reduction_gui/widgets/sans/hfir_detector.py @@ -1,10 +1,8 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore +from PyQt4 import QtGui, QtCore import reduction_gui.widgets.util as util -import os import sys from reduction_gui.reduction.sans.hfir_detector_script import Detector -from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget import ui.sans.ui_hfir_detector @@ -147,7 +145,6 @@ class DetectorWidget(BaseWidget): try: reduction_table_ws = self.options_callback() - patch_output = AnalysisDataService.doesExist(patch_ws) filename = self._content.sensitivity_file_edit.text() script = "ComputeSensitivity(Filename='%s',\n" % filename script += " ReductionProperties='%s',\n" % reduction_table_ws diff --git a/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py b/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py index 0e504939ed3a59be4daa69e5fd15079b1da63dcf..0c7ecbdd39b53d51025acf782bfdd4c2d930cd6f 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py +++ b/scripts/Interface/reduction_gui/widgets/sans/hfir_instrument.py @@ -9,7 +9,7 @@ import ui.sans.ui_hfir_instrument IS_IN_MANTIDPLOT = False try: - import mantidplot + import mantidplot # noqa IS_IN_MANTIDPLOT = True except ImportError: pass diff --git a/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py b/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py index bb58d7763b8eba14650736d70ac1ac816d71f512..c756b9bfff3f09ec9bd33c030d1bd283cf37fc9d 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py +++ b/scripts/Interface/reduction_gui/widgets/sans/sans_catalog.py @@ -1,6 +1,5 @@ #pylint: disable=invalid-name -from PyQt4 import QtGui, uic, QtCore -import os +from PyQt4 import QtGui, QtCore from reduction_gui.settings.application_settings import GeneralSettings from reduction_gui.widgets.base_widget import BaseWidget import ui.ui_data_catalog @@ -55,7 +54,8 @@ class SANSCatalogWidget(BaseWidget): self.connect(self._content.browse_button, QtCore.SIGNAL("clicked()"), self._browse_directory) self.connect(self._content.directory_edit, QtCore.SIGNAL("returnPressed()"), self._update_content) self._content.directory_edit.setText(self._settings.catalog_data_path) - self._content.directory_edit.setToolTip("Use a path of the form: /SNS/<instrument>/IPTS-<number>/data\nE.g.: /SNS/EQSANS/IPTS-1234/data") + self._content.directory_edit.setToolTip("Use a path of the form: /SNS/<instrument>/IPTS-<number>/data\nE.g.: " + "/SNS/EQSANS/IPTS-1234/data") self._update_content(False) def tableWidgetContext(self, point): diff --git a/scripts/Interface/reduction_gui/widgets/sans/stitcher.py b/scripts/Interface/reduction_gui/widgets/sans/stitcher.py index 20f39d3aab25dda4c7e72970d082d93f82b055d7..7138a6b3c0666e7f1f73f3e262bc6d83154b05d4 100644 --- a/scripts/Interface/reduction_gui/widgets/sans/stitcher.py +++ b/scripts/Interface/reduction_gui/widgets/sans/stitcher.py @@ -275,7 +275,6 @@ class StitcherWidget(BaseWidget): scale = util._check_and_get_float_line_edit(scale_control) data_object.set_scale(scale) - _npts = data_object.get_number_of_points() util.set_valid(dataset_control.lineEdit(), True) else: data_object = None @@ -328,7 +327,6 @@ class StitcherWidget(BaseWidget): "Could not load %s.\nMake sure you pick the XML output from the reduction." % file_in) return self._content.high_scale_edit.setText("1.0") - _npts = self._high_q_data.get_number_of_points() util.set_valid(self._content.high_q_combo.lineEdit(), True) else: self._high_q_data = None @@ -344,7 +342,7 @@ class StitcherWidget(BaseWidget): fname = QtCore.QFileInfo(QtGui.QFileDialog.getOpenFileName(self, title, self._output_dir, "Reduced XML files (*.xml);; Reduced Nexus files" - " (*.nxs);; All files (*.*)")).filePath() + " (*.nxs);; All files (*)")).filePath() if fname: # Store the location of the loaded file self._output_dir = str(QtCore.QFileInfo(fname).path()) diff --git a/scripts/Interface/ui/reflectometer/refl_choose_col.py b/scripts/Interface/ui/reflectometer/refl_choose_col.py index e411aa21c832332294ea7d435414747be80db0b1..8549d49c07337703a47620f4707492bb8f19a9c0 100644 --- a/scripts/Interface/ui/reflectometer/refl_choose_col.py +++ b/scripts/Interface/ui/reflectometer/refl_choose_col.py @@ -8,7 +8,8 @@ from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s class ReflChoose(QtGui.QDialog, ui_refl_columns.Ui_chooseColumnsDialog): diff --git a/scripts/Interface/ui/reflectometer/refl_gui.py b/scripts/Interface/ui/reflectometer/refl_gui.py index c6051830258892306e6eac4273ef3333252315ab..682af79e8f4db33b068de7d1cf2ea2876794787a 100644 --- a/scripts/Interface/ui/reflectometer/refl_gui.py +++ b/scripts/Interface/ui/reflectometer/refl_gui.py @@ -27,7 +27,8 @@ from mantid import UsageService try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s canMantidPlot = True @@ -82,7 +83,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): #Setup instrument with defaults assigned. self.instrument_list = ['INTER', 'SURF', 'CRISP', 'POLREF', 'OFFSPEC'] self.polarisation_instruments = ['CRISP', 'POLREF'] - self.polarisation_options = {'None': PolarisationCorrection.NONE, '1-PNR': PolarisationCorrection.PNR, '2-PA': PolarisationCorrection.PA} + self.polarisation_options = {'None': PolarisationCorrection.NONE, + '1-PNR': PolarisationCorrection.PNR, + '2-PA': PolarisationCorrection.PA} #Set the live data settings, use default if none have been set before settings = QtCore.QSettings() @@ -447,7 +450,6 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): """ copy the contents of the selected cells to the row below as long as the row below contains a run number in the first cell """ - _col = 0 # make sure all selected cells are in the same row sum = 0 howMany = len(self.tableMain.selectedItems()) @@ -468,7 +470,10 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): row = row + 1 filled = filled + 1 if not filled: - QtGui.QMessageBox.critical(self.tableMain, 'Cannot perform Autofill', "No target cells to autofill. Rows to be filled should contain a run number in their first cell, and start from directly below the selected line.") + QtGui.QMessageBox.critical(self.tableMain, + 'Cannot perform Autofill', + "No target cells to autofill. Rows to be filled should contain a run number in their " + "first cell, and start from directly below the selected line.") else: QtGui.QMessageBox.critical(self.tableMain, 'Cannot perform Autofill', "Selected cells must all be in the same row.") else: @@ -684,7 +689,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): for idx in rows: rowIndexes.append(idx.row()) if not len(rowIndexes): - reply = QtGui.QMessageBox.question(self.tableMain, 'Process all rows?', "This will process all rows in the table. Continue?", QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) + reply = QtGui.QMessageBox.question(self.tableMain, 'Process all rows?', + "This will process all rows in the table. Continue?", + QtGui.QMessageBox.Yes, QtGui.QMessageBox.No) if reply == QtGui.QMessageBox.No: logger.notice("Cancelled!") willProcess = False @@ -693,11 +700,9 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): if willProcess: for row in rowIndexes: # range(self.tableMain.rowCount()): runno = [] - _loadedRuns = [] wksp = [] overlapLow = [] overlapHigh = [] - _theta = [0, 0, 0] if self.tableMain.item(row, 0).text() != '': self.statusMain.showMessage("Processing row: " + str(row + 1)) logger.debug("Processing row: " + str(row + 1)) @@ -716,7 +721,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): if self.tableMain.item(row, 15).text() == '': loadedRun = None if load_live_runs.is_live_run(runno[0]): - loadedRun = load_live_runs.get_live_data(config['default.instrument'], frequency=self.live_freq, accumulation=self.live_method) + loadedRun = load_live_runs.get_live_data(config['default.instrument'], frequency=self.live_freq, + accumulation=self.live_method) else: Load(Filename=runno[0], OutputWorkspace="_run") loadedRun = mtd["_run"] @@ -746,12 +752,14 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): logger.notice("Calculated resolution: " + str(dqq)) except: self.statusMain.clearMessage() - logger.error("Failed to calculate dq/q because we could not find theta in the workspace's sample log. Try entering theta or dq/q manually.") + logger.error("Failed to calculate dq/q because we could not find theta in the workspace's sample log. " + "Try entering theta or dq/q manually.") return else: dqq = float(self.tableMain.item(row, 15).text()) - #Check secondary and tertiary two_theta columns, if they're blank and their corresponding run columns are set, fill them. + # Check secondary and tertiary two_theta columns, if they're + # blank and their corresponding run columns are set, fill them. for run_col in [5, 10]: tht_col = run_col + 1 run_val = str(self.tableMain.item(row, run_col).text()) @@ -799,7 +807,6 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): outputwksp = runno[0] + '_' + runno[1][3:] else: outputwksp = runno[0] + '_' + runno[-1][3:] - _begoverlap = w2.readX(0)[0] # get Qmax if self.tableMain.item(row, i * 5 + 4).text() == '': overlapHigh = 0.3 * max(w1.readX(0)) @@ -864,7 +871,6 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): self.__reset_plot_button(plotbutton) return for i in range(len(runno)): - _ws = getWorkspace(wksp[i]) if len(overlapLow): Qmin = overlapLow[0] else: @@ -974,17 +980,19 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): # Only make a transmission workspace if we need one. if transrun and not transmission_ws: converter = ConvertToWavelength(transrun) - _trans_run_names = converter.get_name_list() size = converter.get_ws_list_size() out_ws_name = transrun_named if size == 1: trans1 = converter.get_workspace_from_list(0) - transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name, Params=0.02, StartOverlap=10.0, EndOverlap=12.0) + transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name, + Params=0.02, StartOverlap=10.0, EndOverlap=12.0) elif size == 2: trans1 = converter.get_workspace_from_list(0) trans2 = converter.get_workspace_from_list(1) - transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name, SecondTransmissionRun=trans2, Params=0.02, StartOverlap=10.0, EndOverlap=12.0) + transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name, + SecondTransmissionRun=trans2, Params=0.02, + StartOverlap=10.0, EndOverlap=12.0) else: raise RuntimeError("Up to 2 transmission runs can be specified. No more than that.") @@ -1019,8 +1027,10 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): #If the transmission workspace is a group, we'll use it pair-wise with the tof workspace group if isinstance(transmission_ws, WorkspaceGroup): group_trans_ws = transmission_ws[i] - wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws[i], FirstTransmissionRun=group_trans_ws, thetaIn=angle, OutputWorkspace=runno+'_IvsQ_'+str(i+1), - OutputWorkspaceWavelength=runno+'_IvsLam_'+str(i+1),ScaleFactor=factor,MomentumTransferStep=Qstep, + wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws[i], FirstTransmissionRun=group_trans_ws, + thetaIn=angle, OutputWorkspace=runno+'_IvsQ_'+str(i+1), + OutputWorkspaceWavelength=runno+'_IvsLam_'+str(i+1), + ScaleFactor=factor,MomentumTransferStep=Qstep, MomentumTransferMinimum=Qmin, MomentumTransferMaximum=Qmax) wqGroup.append(wq) wlamGroup.append(wlam) @@ -1030,8 +1040,10 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): wlam = GroupWorkspaces(InputWorkspaces=wlamGroup, OutputWorkspace=runno+'_IvsLam') th = thetaGroup[0] else: - wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws, FirstTransmissionRun=transmission_ws, thetaIn=angle, OutputWorkspace=runno+'_IvsQ', - OutputWorkspaceWavelength=runno+'_IvsLam', ScaleFactor=factor,MomentumTransferStep=Qstep, + wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws, FirstTransmissionRun=transmission_ws, + thetaIn=angle, OutputWorkspace=runno+'_IvsQ', + OutputWorkspaceWavelength=runno+'_IvsLam', + ScaleFactor=factor,MomentumTransferStep=Qstep, MomentumTransferMinimum=Qmin, MomentumTransferMaximum=Qmax) cleanup() @@ -1091,7 +1103,8 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): #this is an emergency autosave as the program is failing logger.error("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.") msgBox = QtGui.QMessageBox() - msgBox.setText("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.\nPlease check the log for details.") + msgBox.setText("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.\n" + "Please check the log for details.") msgBox.setStandardButtons(QtGui.QMessageBox.Ok) msgBox.setIcon(QtGui.QMessageBox.Critical) msgBox.setDefaultButton(QtGui.QMessageBox.Ok) @@ -1116,7 +1129,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): else: saveDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Save Table") saveDialog.setFileMode(QtGui.QFileDialog.AnyFile) - saveDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)") + saveDialog.setNameFilter("Table Files (*.tbl);;All files (*)") saveDialog.setDefaultSuffix("tbl") saveDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) if saveDialog.exec_(): @@ -1131,7 +1144,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): """ saveDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Save Table") saveDialog.setFileMode(QtGui.QFileDialog.AnyFile) - saveDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)") + saveDialog.setNameFilter("Table Files (*.tbl);;All files (*)") saveDialog.setDefaultSuffix("tbl") saveDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) if saveDialog.exec_(): @@ -1145,7 +1158,7 @@ class ReflGui(QtGui.QMainWindow, ui_refl_window.Ui_windowRefl): self.loading = True loadDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Open Table") loadDialog.setFileMode(QtGui.QFileDialog.ExistingFile) - loadDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)") + loadDialog.setNameFilter("Table Files (*.tbl);;All files (*)") if loadDialog.exec_(): try: #before loading make sure you give them a chance to save diff --git a/scripts/Interface/ui/reflectometer/refl_gui_run.py b/scripts/Interface/ui/reflectometer/refl_gui_run.py index 459c1018ebb73607da2a318d974244c60ac61406..7bed9815beffb7de1937cef2954cabf55e2119f0 100644 --- a/scripts/Interface/ui/reflectometer/refl_gui_run.py +++ b/scripts/Interface/ui/reflectometer/refl_gui_run.py @@ -1,6 +1,6 @@ #pylint: disable=invalid-name import refl_gui -from PyQt4 import QtCore, QtGui +from PyQt4 import QtGui if __name__ == "__main__": import sys diff --git a/scripts/Interface/ui/reflectometer/refl_options.py b/scripts/Interface/ui/reflectometer/refl_options.py index f43be9d745b1f6d945e2bb1b3cb230b4bb5cdc8f..32b7c10394c28094e077091cbd5b597eff441fc6 100644 --- a/scripts/Interface/ui/reflectometer/refl_options.py +++ b/scripts/Interface/ui/reflectometer/refl_options.py @@ -5,7 +5,8 @@ from PyQt4 import QtCore, QtGui try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s class ReflOptions(QtGui.QDialog, ui_refl_options_window.Ui_OptionsDialog): diff --git a/scripts/Interface/ui/reflectometer/refl_save.py b/scripts/Interface/ui/reflectometer/refl_save.py index b96bc740b623adc6629c6cfc243017aff05df848..9350b8b3281d0b518c041b0f0d94d7d64f6d707b 100644 --- a/scripts/Interface/ui/reflectometer/refl_save.py +++ b/scripts/Interface/ui/reflectometer/refl_save.py @@ -8,12 +8,13 @@ from isis_reflectometry.quick import * from isis_reflectometry.procedures import * from isis_reflectometry.combineMulti import * from isis_reflectometry.saveModule import * -from isis_reflectometry.settings import MissingSettings, Settings +from isis_reflectometry.settings import Settings try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s class Ui_SaveWindow(object): @@ -282,7 +283,6 @@ class Ui_SaveWindow(object): self.listWidget.setCurrentItem(self.listWidget.item(0)) # try to get correct user directory - currentInstrument=config['default.instrument'] if self.SavePath!='': self.lineEdit.setText(self.SavePath) else: @@ -314,15 +314,13 @@ class Ui_SaveWindow(object): #--------- If "Save" button pressed, selcted workspaces are saved ------------- def buttonClickHandler1(self): - names = mtd.getObjectNames() - dataToSave=[] prefix = str(self.lineEdit2.text()) if not (self.lineEdit.text() and os.path.exists(self.lineEdit.text())): logger.notice("Directory specified doesn't exist or was invalid for your operating system") - QtGui.QMessageBox.critical(self.lineEdit, 'Could not save',"Directory specified doesn't exist or was invalid for your operating system") + QtGui.QMessageBox.critical(self.lineEdit, 'Could not save', + "Directory specified doesn't exist or was invalid for your operating system") return for idx in self.listWidget.selectedItems(): - runlist=parseRunList(str(self.spectraEdit.text())) fname=os.path.join(self.lineEdit.text(),prefix + idx.text()) if self.comboBox.currentIndex() == 0: print "Custom Ascii format" diff --git a/scripts/LargeScaleStructures/EQSANS_geometry.py b/scripts/LargeScaleStructures/EQSANS_geometry.py index 049dcf884ab16e7473dc53b344fe0105b15df739..924de31a7c314a1d1343dd6afd91505b401f8014 100644 --- a/scripts/LargeScaleStructures/EQSANS_geometry.py +++ b/scripts/LargeScaleStructures/EQSANS_geometry.py @@ -64,8 +64,6 @@ def create_geometry(file_name=None, tube_width=TUBE_WIDTH, tube_length=TUBE_SIZE for i in range(0, NUM_BANKS/2): i_low_bank = i i_high_bank = i+NUM_BANKS/2 - low_bank = "bank"+str(i_low_bank+1) - high_bank = "bank"+str(i_high_bank+1) # FRONT plane for j in range(NUM_TUBES_PER_BANK): diff --git a/scripts/LargeScaleStructures/PolrefTest.py b/scripts/LargeScaleStructures/PolrefTest.py index 5692c220c0d8ca17200f285052a8448b9c5e6caa..45da391ba81e985a85337c0ca95e71df726a3b63 100644 --- a/scripts/LargeScaleStructures/PolrefTest.py +++ b/scripts/LargeScaleStructures/PolrefTest.py @@ -13,7 +13,8 @@ def quick(run): # Load a data set. single period LoadRaw(Filename=run,OutputWorkspace="W",SpectrumMax="4",LoadMonitors="Separate") ConvertUnits(InputWorkspace="W_Monitors",OutputWorkspace="M",Target="Wavelength",AlignBins="1") - CalculateFlatBackground(InputWorkspace="M",OutputWorkspace="M",WorkspaceIndexList=MonitorsToCorrect,StartX=MonitorBackground[0],EndX=MonitorBackground[1]) + CalculateFlatBackground(InputWorkspace="M",OutputWorkspace="M",WorkspaceIndexList=MonitorsToCorrect, + StartX=MonitorBackground[0],EndX=MonitorBackground[1]) ConvertUnits(InputWorkspace="W",OutputWorkspace="D",Target="Wavelength",AlignBins="1") heliumDetectorEff('D') diff --git a/scripts/LargeScaleStructures/REF_L_geometry.py b/scripts/LargeScaleStructures/REF_L_geometry.py index 2a15094a9d1f7ff3e530e833262e3ec6742657a9..1760ced42023eddafde54dc9ac16f065cb95aa24 100644 --- a/scripts/LargeScaleStructures/REF_L_geometry.py +++ b/scripts/LargeScaleStructures/REF_L_geometry.py @@ -59,7 +59,6 @@ def create_grouping(workspace=None): def create_geometry(file_name=None, pixel_width=None, pixel_height=None): inst_name = "REF_L" - short_name = "REF_L" if pixel_width is None: pixel_width = PIXEL_WIDTH diff --git a/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py b/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py index d8bc3693c47d547c385e03fbf3eb9bde7513df3f..fca048ea6cb98d0456722182b3fda89d7b6c3f8e 100644 --- a/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py +++ b/scripts/LargeScaleStructures/ScalingFactorCalculation/sfCalculator.py @@ -846,7 +846,6 @@ def calculate(string_runs=None, #Make sure all the lambdaRequested are identical within a given range lambdaRequestPrecision = 0.01 #1% - _lr = lambdaRequest[0] for i in lambdaRequest: _localValue = float(lambdaRequest[i][0]) _localValueRate = lambdaRequestPrecision * _localValue @@ -865,7 +864,6 @@ def calculate(string_runs=None, error_a = [] error_b = [] name = [] - _previous_cal = None finalS1H = [] finalS2H = [] @@ -916,8 +914,7 @@ def calculate(string_runs=None, recordSettings(a, b, error_a, error_b, name, cal) - if (i < (len(list_runs) - 1) and - list_attenuator[i + 1] == (_attenuator+1)): + if (i < (len(list_runs) - 1) and list_attenuator[i + 1] == (_attenuator+1)): list_objects.append(cal) #record S1H and S2H diff --git a/scripts/LargeScaleStructures/geometry_writer.py b/scripts/LargeScaleStructures/geometry_writer.py index da590d74311cd67a1624d6a3499556113bfa8580..632e8d4c13e182dccec6b211d1c438cf2a6f3bc2 100644 --- a/scripts/LargeScaleStructures/geometry_writer.py +++ b/scripts/LargeScaleStructures/geometry_writer.py @@ -154,7 +154,6 @@ class MantidGeom(object): basecomponent.setAttribute("mark-as", "monitor") for i in range(len(distance)): - dummy_zi = float(distance[i]) self._append_child("location", basecomponent, z=distance[i], name=names[i]) def addComponent(self, type_name, idlist=None, root=None, blank_location=True): @@ -249,17 +248,17 @@ class MantidGeom(object): def addLocationPolar(self, root, r, theta, phi, name=None): if name is not None: - _pos_loc = self._append_child("location", root, r=r, t=theta, p=phi, name=name) + self._append_child("location", root, r=r, t=theta, p=phi, name=name) else: - _pos_loc = self._append_child("location", root, r=r, t=theta, p=phi) + self._append_child("location", root, r=r, t=theta, p=phi) def addLocationRTP(self, root, r, t, p, rot_x, rot_y, rot_z, name=None): """ Add a location element to a specific parent node given by root, using r, theta, phi coordinates. """ - dummy_rf = float(r) - dummy_tf = float(f) - dummy_pf = float(p) + float(r) + float(t) + float(p) if name is not None: pos_loc = self._append_child("location", root, r=r, t=t, p=p, name=name) else: @@ -269,15 +268,15 @@ class MantidGeom(object): # the combined rotation is equals that obtained by applying rotx, then roty and finally rotz. if rot_x is not None: log = self._append_child("parameter", pos_loc, name="rotx") - _rotxf = float(rot_x) + float(rot_x) self._append_child("value", log, val=rot_x) if rot_y is not None: log = self._append_child("parameter", pos_loc, name="roty") - _rotyf = float(rot_y) + float(rot_y) self._append_child("value", log, val=rot_y) if rot_z is not None: log = self._append_child("parameter", pos_loc, name="rotz") - _rotzf = float(rot_z) + float(rot_z) self._append_child("value", log, val=rot_z) def addNPack(self, name, num_tubes, tube_width, air_gap, type_name="tube"): diff --git a/scripts/PearlPowderISIS/pearl_calib_factory.py b/scripts/PearlPowderISIS/pearl_calib_factory.py index aafd3a7e0017d1febb5d074e8fd5bf8a016d1c14..de405cb0e7f3233fdddd1dfd74301911234c9ea8 100644 --- a/scripts/PearlPowderISIS/pearl_calib_factory.py +++ b/scripts/PearlPowderISIS/pearl_calib_factory.py @@ -1,7 +1,5 @@ # pylint: disable=too-many-branches,too-many-statements, superfluous-parens -from mantid.simpleapi import * - def get_calibration_dir(cycle, tt_mode, pearl_file_dir): if (cycle == "15_4"): diff --git a/scripts/PearlPowderISIS/pearl_cycle_factory.py b/scripts/PearlPowderISIS/pearl_cycle_factory.py index a368d8e2a2da86c711bfc52f74ced980c1e63d29..fb68d5162b0dd665d3358c4a02aa47f398ae6ea2 100644 --- a/scripts/PearlPowderISIS/pearl_cycle_factory.py +++ b/scripts/PearlPowderISIS/pearl_cycle_factory.py @@ -1,6 +1,5 @@ # pylint: disable=anomalous-backslash-in-string, too-many-branches, superfluous-parens -from mantid.simpleapi import * import pearl_routines diff --git a/scripts/PearlPowderISIS/pearl_routines.py b/scripts/PearlPowderISIS/pearl_routines.py index 432a0163819c802553a20601e7a85e6f01c17e17..ca4dca826deb5db9364a159f41139327957bfc2a 100644 --- a/scripts/PearlPowderISIS/pearl_routines.py +++ b/scripts/PearlPowderISIS/pearl_routines.py @@ -200,7 +200,7 @@ def PEARL_getfilename(run_number, ext): # # Check if file exists in default data folder & if not use alternate folder stored in "datadir"... # - if (os.path.exists(full_filename) == False): + if not os.path.exists(full_filename): print "No such file as ", full_filename, "; trying X-drive folder..." full_filename = datadir + filename @@ -380,7 +380,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, AlignDetectors(InputWorkspace=work, OutputWorkspace=work, CalibrationFile=calfile) DiffractionFocussing(InputWorkspace=work, OutputWorkspace=focus, GroupingFileName=groupfile) - if (debug != True): + if not debug: mtd.remove(work) for i in range(0, alg_range): @@ -410,7 +410,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, Rebin(InputWorkspace=rdata, OutputWorkspace=output, Params=tofbinning) # Divide(rdata,van,output) CropWorkspace(InputWorkspace=output, OutputWorkspace=output, XMin=0.1) - if (debug != True): + if not debug: mtd.remove(focus) if (mode == "all"): @@ -442,7 +442,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, SaveNexus(Filename=outfile, InputWorkspace=tosave, Append=True) - if (debug != True): + if not debug: for i in range(0, alg_range): output = outwork + "_mod" + str(i + 1) @@ -511,7 +511,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, SaveNexus(Filename=outfile, InputWorkspace=tosave, Append=True) - if (debug != True): + if not debug: for i in range(0, alg_range): output = outwork + "_mod" + str(i + 1) @@ -562,7 +562,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, ConvertUnits(InputWorkspace=tosave, OutputWorkspace=tosave, Target="dSpacing") SaveNexus(Filename=outfile, InputWorkspace=tosave, Append=True) - if (debug != True): + if not debug: for i in range(0, alg_range): output = outwork + "_mod" + str(i + 1) van = "van" + str(i + 1) @@ -593,7 +593,7 @@ def pearl_run_focus(number, ext="raw", fmode="trans", ttmode="TT70", atten=True, SaveNexus(Filename=outfile, InputWorkspace=output, Append=status) - if (debug != True): + if not debug: mtd.remove(rdata) mtd.remove(van) mtd.remove(output) @@ -638,7 +638,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", PEARL_read(empty, ext, wempty) Minus(LHSWorkspace=wvan, RHSWorkspace=wempty, OutputWorkspace=wvan) print "read van and empty" - if (debug != True): + if not debug: mtd.remove(wempty) if (absorb): @@ -654,7 +654,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", LoadNexus(Filename=vabsorbfile, OutputWorkspace="T") RebinToWorkspace(WorkspaceToRebin=wvan, WorkspaceToMatch="T", OutputWorkspace=wvan) Divide(LHSWorkspace=wvan, RHSWorkspace="T", OutputWorkspace=wvan) - if (debug != True): + if not debug: mtd.remove("T") ConvertUnits(InputWorkspace=wvan, OutputWorkspace=wvan, Target="TOF") @@ -675,12 +675,12 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", Rebin(InputWorkspace=vanfoc, OutputWorkspace=vanfoc, Params=trange) ConvertUnits(InputWorkspace=vanfoc, OutputWorkspace=vanfoc, Target="dSpacing") - if (debug != True): + if not debug: mtd.remove(wvan) if (instver == "new2"): ConvertUnits(InputWorkspace=vanfoc, OutputWorkspace="vanmask", Target="dSpacing") - if (debug != True): + if not debug: mtd.remove(vanfoc) # remove bragg peaks before spline @@ -702,10 +702,10 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", print "Finished striping-out peaks..." - if (debug != True): + if not debug: mtd.remove("vanmask") - if (debug != True): + if not debug: print "Not in debug mode so will delete all temporary workspaces" ConvertUnits(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", Target="TOF") @@ -734,14 +734,14 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", for i in range(2, 15): SaveNexus(Filename=nvanfile, InputWorkspace="spline" + str(i), Append=True) - if (debug != True): + if not debug: mtd.remove("vanstrip") for i in range(1, 15): mtd.remove("spline" + str(i)) elif (instver == "new"): ConvertUnits(InputWorkspace=vanfoc, OutputWorkspace="vanmask", Target="dSpacing") - if (debug != True): + if not debug: mtd.remove(vanfoc) # remove bragg peaks before spline @@ -750,10 +750,10 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", for i in range(1, 12): StripPeaks(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", FWHM=15, Tolerance=8, WorkspaceIndex=i) - if (debug != True): + if not debug: mtd.remove("vanmask") - if (debug != True): + if not debug: print "Not in debug mode so will delete all temporary workspaces" ConvertUnits(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", Target="TOF") @@ -779,7 +779,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", for i in range(2, 13): SaveNexus(Filename=nvanfile, InputWorkspace="spline" + str(i), Append=True) - if (debug != True): + if not debug: mtd.remove("vanstrip") for i in range(1, 13): @@ -787,7 +787,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", elif (instver == "old"): ConvertUnits(InputWorkspace=vanfoc, OutputWorkspace="vanmask", Target="dSpacing") - if (debug != True): + if not debug: mtd.remove(vanfoc) # remove bragg peaks before spline @@ -797,7 +797,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", StripPeaks(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", FWHM=40, Tolerance=12, WorkspaceIndex=1) StripPeaks(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", FWHM=60, Tolerance=12, WorkspaceIndex=1) - if (debug != True): + if not debug: mtd.remove("vanmask") # Mask low d region that is zero before spline @@ -807,7 +807,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", else: MaskBins(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", XMin=0, XMax=0.06, SpectraList=reg) - if (debug != True): + if not debug: print "Not in debug mode so will delete all temporary workspaces" ConvertUnits(InputWorkspace="vanstrip", OutputWorkspace="vanstrip", Target="TOF") @@ -828,7 +828,7 @@ def PEARL_createvan(van, empty, ext="raw", fmode="all", ttmode="TT88", for i in range(1, 4): SaveNexus(Filename=nvanfile, InputWorkspace="spline" + str(i), Append=True) - if (debug != True): + if not debug: mtd.remove("vanstrip") for i in range(1, 5): mtd.remove("spline" + str(i)) @@ -963,7 +963,7 @@ def PEARL_atten(work, outwork, debug=False): ConvertToHistogram(InputWorkspace="wc_atten", OutputWorkspace="wc_atten") RebinToWorkspace(WorkspaceToRebin="wc_atten", WorkspaceToMatch=work, OutputWorkspace="wc_atten") Divide(LHSWorkspace=work, RHSWorkspace="wc_atten", OutputWorkspace=outwork) - if (debug != True): + if not debug: mtd.remove("wc_atten") return diff --git a/scripts/Powder_Diffraction_Reduction.py b/scripts/Powder_Diffraction_Reduction.py index 18cfdb72f1cb0cb72263a73ddf2e2d17d79c4005..d49fb49dc88158ce8b025eb680219bc82e78bf0f 100644 --- a/scripts/Powder_Diffraction_Reduction.py +++ b/scripts/Powder_Diffraction_Reduction.py @@ -5,7 +5,6 @@ import os from reduction_application import ReductionGUI -from PyQt4 import QtCore, uic reducer = ReductionGUI(instrument_list=["PG3", "NOM", "VULCAN"]) if reducer.setup_layout(load_last=True): diff --git a/scripts/PyChop.py b/scripts/PyChop.py index 3de587abb930ecd1dc2cef9b643f6c959feb404c..57e4b83a94fda9b0aa56e3fb2870b35e4af4e2cc 100644 --- a/scripts/PyChop.py +++ b/scripts/PyChop.py @@ -16,6 +16,6 @@ if __name__ == '__main__': window = PyChopGui.PyChopGui() window.show() try: # check if started from within mantidplot - import mantidplot + import mantidplot # noqa except ImportError: sys.exit(app.exec_()) diff --git a/scripts/PyChop/Chop.py b/scripts/PyChop/Chop.py index e6af4fdf1906c4a991d609226a2988b13c05f8f4..a6a03f9f1df19d4f0362cb95659850b862ed0b8d 100644 --- a/scripts/PyChop/Chop.py +++ b/scripts/PyChop/Chop.py @@ -427,7 +427,6 @@ def chbmts(a, b, c, m, x): d = 0.0 ddd = 0.0 y = (2.0*x-a-b)/(b-a) - y2 = 2.0*y for j in range(m-1, 0, -1): sv = d d = 2.*y*d - ddd + c[j] diff --git a/scripts/PyChop/ISISFermi.py b/scripts/PyChop/ISISFermi.py index 3be68c442c5cdcc77b0e9083cd6005931a843200..f8228771949069b608485c2023c11af21ab04165 100644 --- a/scripts/PyChop/ISISFermi.py +++ b/scripts/PyChop/ISISFermi.py @@ -184,10 +184,8 @@ class ISISFermi: raise ValueError('Incident energy has not be specified') chop_par = self.__chopperParameters[self.instname][self.choppername]['par'] pslit = chop_par[0] / 1000.00 - dslat = (chop_par[0] + chop_par[1]) / 1000.00 radius = chop_par[2] / 1000.00 rho = chop_par[3] / 1000.00 - tjit = chop_par[5] * 1.0e-6 return Chop.tchop(self.freq, Ei, pslit, radius, rho) def getModWidth(self, Ei_in=None): @@ -298,19 +296,15 @@ class ISISFermi: gg2 = g2 / (omega*(xa+x1)) ff1 = f1 / (omega*(xa+x1)) ff2 = f2 / (omega*(xa+x1)) - aa = ((np.cos(gam)/veli) - (np.cos(gam-phi)/velf)) - (ff2*np.sin(gam)) bb = ((-np.sin(gam)/veli) + (np.sin(gam-phi)/velf)) - (ff2*np.cos(gam)) aya = ff1 + ((rat*x2/x0)*gg1) - ax = aa - ((rat*x2/x0)*gg2*np.sin(gam)) ay = bb - ((rat*x2/x0)*gg2*np.cos(gam)) a_dd = 1.00/velf v_van_m = am**2 * v_mod v_van_ch = ach**2 * v_ch v_van_jit = ach**2 * v_jit v_van_ya = aya**2 * (wa**2/12.00) - v_van_x = ax**2 * v_x v_van_y = ay**2 * v_y - v_van_xy = ax*ay * v_xy v_van_dd = a_dd**2* v_dd # Old version: #v_van = (v_van_m + v_van_ch + v_van_jit + v_van_ya) diff --git a/scripts/PyChop/PyChopGui.py b/scripts/PyChop/PyChopGui.py index 6e2438efd460eccdb043160951d4ebc8226946bb..aa80cab54d25b7227503077ff3f257235423fa42 100755 --- a/scripts/PyChop/PyChopGui.py +++ b/scripts/PyChop/PyChopGui.py @@ -732,6 +732,6 @@ if __name__ == '__main__': window = PyChopGui() window.show() try: # check if started from within mantidplot - import mantidplot + import mantidplot # noqa except ImportError: sys.exit(app.exec_()) diff --git a/scripts/Reflectometry/isis_reflectometry/combineMulti.py b/scripts/Reflectometry/isis_reflectometry/combineMulti.py index 89c7e66d0275b3c8f969d7827126da66b14c2202..d63deb17dbeb187eedf95c1175e7ad0ab2dd3528 100644 --- a/scripts/Reflectometry/isis_reflectometry/combineMulti.py +++ b/scripts/Reflectometry/isis_reflectometry/combineMulti.py @@ -1,7 +1,6 @@ # pylint: disable=invalid-name from l2q import * from mantid.simpleapi import * -import math from mantid.api import WorkspaceGroup diff --git a/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py b/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py index c46de76f87290ef0b9646f385134c499fa3d40ab..46d7ac1b7688292e75ffc542fcf1f5fb9d3733fb 100644 --- a/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py +++ b/scripts/Reflectometry/isis_reflectometry/convert_to_wavelength.py @@ -119,7 +119,8 @@ class ConvertToWavelength(object): return _in_rng - def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, monitor_workspace_index, correct_monitor=False, bg_min=None, bg_max=None): + def convert(self, wavelength_min, wavelength_max, detector_workspace_indexes, monitor_workspace_index, + correct_monitor=False, bg_min=None, bg_max=None): """ Run the conversion @@ -153,7 +154,8 @@ class ConvertToWavelength(object): logger.debug("Monitor detector index %s" % str(monitor_workspace_index)) # Crop out the monitor workspace - _monitor_ws = msi.CropWorkspace(InputWorkspace=sum_wavelength, StartWorkspaceIndex=monitor_workspace_index,EndWorkspaceIndex=monitor_workspace_index) + _monitor_ws = msi.CropWorkspace(InputWorkspace=sum_wavelength, + StartWorkspaceIndex=monitor_workspace_index,EndWorkspaceIndex=monitor_workspace_index) # Crop out the detector workspace then chop out the x-ranges of interest. _detector_ws = ConvertToWavelength.crop_range(sum_wavelength, detector_workspace_indexes) diff --git a/scripts/Reflectometry/isis_reflectometry/load_live_runs.py b/scripts/Reflectometry/isis_reflectometry/load_live_runs.py index a7538f062725610fce742562422ced702883a0d2..a8cddb5d8ca2d5a6a85bcd2ea0a652f5750257ba 100644 --- a/scripts/Reflectometry/isis_reflectometry/load_live_runs.py +++ b/scripts/Reflectometry/isis_reflectometry/load_live_runs.py @@ -3,7 +3,8 @@ from mantid.simpleapi import * def get_live_data(instrument_name, frequency = 60, accumulation = "Add", output_name = "live"): - StartLiveData(Instrument=str(instrument_name), UpdateEvery = frequency, Outputworkspace=str(output_name), AccumulationMethod = accumulation) + StartLiveData(Instrument=str(instrument_name), UpdateEvery = frequency, + Outputworkspace=str(output_name), AccumulationMethod = accumulation) ws = mtd[output_name] return ws diff --git a/scripts/Reflectometry/isis_reflectometry/procedures.py b/scripts/Reflectometry/isis_reflectometry/procedures.py index 6d7bff7c2d976adba607ddae7a161e259317d506..f611e775a2af843da161d7d254f9820cf9964652 100644 --- a/scripts/Reflectometry/isis_reflectometry/procedures.py +++ b/scripts/Reflectometry/isis_reflectometry/procedures.py @@ -677,8 +677,6 @@ def nrNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpec # Rebin using internal parameters to avoid problems with summing in Q # internalreb=gparams[0]+",0.01,"+gparams[2] # Rebin(InputWorkspace=i,OutputWorkspace=i,Params=internalreb) - _minSp = int(minSpec) - _maxSp = int(maxSpec) CropWorkspace(InputWorkspace=i, OutputWorkspace=i + "det", StartWorkspaceIndex=4, EndWorkspaceIndex=243) floodnorm(i + "det", floodfile) # move the first spectrum in the list onto the beam centre so that when the bench is rotated it's in the right place @@ -737,7 +735,6 @@ def nrNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpec def findbin(wksp, val): a1 = mtd[wksp] x1 = a1.readX(0) - _bnum = -1 i = None for i in range(len(x1) - 1): @@ -760,8 +757,6 @@ def nrDBFn(runListShort, nameListShort, runListLong, nameListLong, nameListComb, addRuns(rlistL[i], nlistL[i]) mon_spec = int(gparams[3]) - 1 - _minSp = int(minSpec) - 1 - _maxSp = int(maxSpec) - 1 reb = gparams[0] + "," + gparams[1] + "," + gparams[2] for i in nlistS: @@ -952,7 +947,6 @@ def NRCombineDatafn(RunsNameList, CombNameList, applySFs, SFList, SFError, scale # if applying a global scale factor do it here if applyGlobalSF == "2": - _scaledData = mtd['currentSum'] / float(globalSF) RenameWorkspace('scaledData', CombNameList) mtd.deleteWorkspace('currentSum') else: @@ -998,8 +992,6 @@ def nrPNRCorrection(UpWksp, DownWksp): Ia = mtd[DownWksp] CloneWorkspace(Ip, "PCalpha") CropWorkspace(InputWorkspace="PCalpha", OutputWorkspace="PCalpha", StartWorkspaceIndex="0", EndWorkspaceIndex="0") - _PCalpha = (mtd['PCalpha'] * 0.0) + 1.0 - _alpha = mtd['PCalpha'] # a1=alpha.readY(0) # for i in range(0,len(a1)): # alpha.dataY(0)[i]=0.0 @@ -1008,7 +1000,6 @@ def nrPNRCorrection(UpWksp, DownWksp): CloneWorkspace("PCalpha", "PCAp") CloneWorkspace("PCalpha", "PCPp") rho = mtd['PCrho'] - _Ap = mtd['PCAp'] Pp = mtd['PCPp'] # for i in range(0,len(a1)): # x=(alpha.dataX(0)[i]+alpha.dataX(0)[i])/2.0 @@ -1057,7 +1048,6 @@ def nrPACorrection(UpUpWksp, UpDownWksp, DownUpWksp, DownDownWksp): Iaa = mtd[DownDownWksp] CloneWorkspace(Ipp, "PCalpha") CropWorkspace(InputWorkspace="PCalpha", OutputWorkspace="PCalpha", StartWorkspaceIndex="0", EndWorkspaceIndex="0") - _PCalpha = (mtd['PCalpha'] * 0.0) + 1.0 alpha = mtd['PCalpha'] # a1=alpha.readY(0) # for i in range(0,len(a1)): @@ -1153,8 +1143,6 @@ def nrPNRFn(runList, nameList, incidentAngles, DBList, specChan, minSpec, maxSpe addRuns(rlist[i], nlist[i]) mon_spec = int(gparams[3]) - 1 - _minSp = int(minSpec) - _maxSp = int(maxSpec) reb = gparams[0] + "," + gparams[1] + "," + gparams[2] k = 0 diff --git a/scripts/Reflectometry/isis_reflectometry/quick.py b/scripts/Reflectometry/isis_reflectometry/quick.py index 27e925b0a7b91695110edcd6e8dc44881159b054..75a4653bf81e777d4a0ee39074aedc5f851e79ce 100644 --- a/scripts/Reflectometry/isis_reflectometry/quick.py +++ b/scripts/Reflectometry/isis_reflectometry/quick.py @@ -179,7 +179,6 @@ def quick_explicit(run, i0_monitor_index, lambda_min, lambda_max, background_min else: # we have a transmission run _monInt = Integration(InputWorkspace=_I0P, RangeLower=int_min, RangeUpper=int_max) IvsLam = Divide(LHSWorkspace=_detector_ws, RHSWorkspace=_monInt) - _names = mtd.getObjectNames() IvsLam = transCorr(trans, IvsLam, lambda_min, lambda_max, background_min, background_max, int_min, int_max, detector_index_ranges, i0_monitor_index, stitch_start_overlap, @@ -441,8 +440,6 @@ def nrPNRCorrection(Wksp, crho, calpha, cAp, cPp): CloneWorkspace(Ip, OutputWorkspace="PCalpha") CropWorkspace(InputWorkspace="PCalpha", OutputWorkspace="PCalpha", StartWorkspaceIndex="0", EndWorkspaceIndex="0") - _PCalpha = (mtd['PCalpha'] * 0.0) + 1.0 - _alpha = mtd['PCalpha'] # a1=alpha.readY(0) # for i in range(0,len(a1)): # alpha.dataY(0)[i]=0.0 @@ -451,7 +448,6 @@ def nrPNRCorrection(Wksp, crho, calpha, cAp, cPp): CloneWorkspace("PCalpha", OutputWorkspace="PCAp") CloneWorkspace("PCalpha", OutputWorkspace="PCPp") rho = mtd['PCrho'] - _Ap = mtd['PCAp'] Pp = mtd['PCPp'] # for i in range(0,len(a1)): # x=(alpha.dataX(0)[i]+alpha.dataX(0)[i])/2.0 @@ -516,7 +512,6 @@ def nrPACorrection(Wksp, crho, calpha, cAp, cPp): # UpUpWksp,UpDownWksp,DownUpW CloneWorkspace(Ipp, OutputWorkspace="PCalpha") CropWorkspace(InputWorkspace="PCalpha", OutputWorkspace="PCalpha", StartWorkspaceIndex=0, EndWorkspaceIndex=0) - _PCalpha = (mtd['PCalpha'] * 0.0) + 1.0 alpha = mtd['PCalpha'] CloneWorkspace("PCalpha", OutputWorkspace="PCrho") CloneWorkspace("PCalpha", OutputWorkspace="PCAp") @@ -643,9 +638,9 @@ def _testQuick(): [_w1lam, _w1q, _th] = quick(94511, theta=0.25, trans='94504') [_w2lam, _w2q, _th] = quick(94512, theta=0.65, trans='94504') [_w3lam, _w3q, _th] = quick(94513, theta=1.5, trans='94504') - _g1 = plotSpectrum("94511_IvsQ", 0) - _g2 = plotSpectrum("94512_IvsQ", 0) - _g3 = plotSpectrum("94513_IvsQ", 0) + plotSpectrum("94511_IvsQ", 0) + plotSpectrum("94512_IvsQ", 0) + plotSpectrum("94513_IvsQ", 0) return True diff --git a/scripts/Reflectometry/isis_reflectometry/saveModule.py b/scripts/Reflectometry/isis_reflectometry/saveModule.py index 81121d515cd617e557d525149d5df074108ddc89..4910e22b3a8b9e807b848dde85231647958ffb98 100644 --- a/scripts/Reflectometry/isis_reflectometry/saveModule.py +++ b/scripts/Reflectometry/isis_reflectometry/saveModule.py @@ -6,7 +6,8 @@ import numpy as n try: _fromUtf8 = QtCore.QString.fromUtf8 except AttributeError: - _fromUtf8 = lambda s: s + def _fromUtf8(s): + return s def saveCustom(idx,fname,sep = ' ',logs = [],title = False,error = False): @@ -45,7 +46,6 @@ def saveANSTO(idx,fname): fname+='.txt' print "FILENAME: ", fname a1=mtd[str(idx.text())] - titl='#'+a1.getTitle()+'\n' x1=a1.readX(0) X1=n.zeros((len(x1)-1)) for i in range(0,len(x1)-1): @@ -67,7 +67,6 @@ def saveMFT(idx,fname,logs): fname+='.mft' print "FILENAME: ", fname a1=mtd[str(idx.text())] - titl=a1.getTitle()+'\n' x1=a1.readX(0) X1=n.zeros((len(x1)-1)) for i in range(0,len(x1)-1): diff --git a/scripts/Reflectometry/isis_reflectometry/settings.py b/scripts/Reflectometry/isis_reflectometry/settings.py index 1879628fea6f481eea6aa62760da313a15074e6f..04a749429c9304988d2c461f790dd9904cd6c9fe 100644 --- a/scripts/Reflectometry/isis_reflectometry/settings.py +++ b/scripts/Reflectometry/isis_reflectometry/settings.py @@ -1,6 +1,5 @@ import xml.etree.ElementTree as XML import os.path -from mantid.simpleapi import * class MissingSettings(Exception): diff --git a/scripts/SANS/ISISCommandInterface.py b/scripts/SANS/ISISCommandInterface.py index 1eeeaab9e1eab7134dedd78e20f8b955621c58cd..07d9163db62469f9afd7f1a9dd5f5daf2f244930 100644 --- a/scripts/SANS/ISISCommandInterface.py +++ b/scripts/SANS/ISISCommandInterface.py @@ -6,9 +6,6 @@ import isis_instrument from reducer_singleton import ReductionSingleton from mantid.kernel import Logger - -sanslog = Logger("SANS") - import isis_reduction_steps import isis_reducer from centre_finder import * @@ -21,6 +18,8 @@ import SANSUtility as su from SANSUtility import deprecated import SANSUserFileParser as UserFileParser +sanslog = Logger("SANS") + # disable plotting if running outside Mantidplot try: import mantidplot @@ -44,7 +43,8 @@ LAST_SAMPLE = None def SetVerboseMode(state): # TODO: this needs to be on the reducer - _VERBOSE_ = state + # _VERBOSE_ = state # FIXME this does nothing + pass # Print a message and log it if the @@ -411,7 +411,7 @@ def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_su else: combineDet = 'rear' - if not full_trans_wav is None: + if full_trans_wav is not None: ReductionSingleton().full_trans_wav = full_trans_wav ReductionSingleton().to_wavelen.set_range(wav_start, wav_end) @@ -964,7 +964,7 @@ def PlotResult(workspace, canvas=None): else: graph = mantidplot.importMatrixWorkspace(workspace.getName()).plotGraph2D() - if not canvas is None: + if canvas is not None: # we were given a handle to an existing graph, use it mantidplot.mergePlots(canvas, graph) graph = canvas @@ -1526,7 +1526,7 @@ def set_q_resolution_use(use): ''' if use: ReductionSingleton().to_Q.set_use_q_resolution(True) - elif use == False: + elif not use: ReductionSingleton().to_Q.set_use_q_resolution(False) else: sanslog.warning('Warning: Could could not set useage of QResolution') diff --git a/scripts/SANS/SANSBatchMode.py b/scripts/SANS/SANSBatchMode.py index 520ad347032dd268d84f97d37ba1dabe1fbdec3e..7d6f643ac973fc3c21a3ce398051416e04cfc81e 100644 --- a/scripts/SANS/SANSBatchMode.py +++ b/scripts/SANS/SANSBatchMode.py @@ -35,12 +35,12 @@ import SANSUtility as su from mantid.simpleapi import * from mantid.api import WorkspaceGroup from mantid.kernel import Logger -sanslog = Logger("SANS") import copy import sys import re from reduction_settings import REDUCTION_SETTINGS_OBJ_NAME from isis_reduction_steps import UserFile +sanslog = Logger("SANS") ################################################################################ # Avoid a bug with deepcopy in python 2.6, details and workaround here: # http://bugs.python.org/issue1515 @@ -135,7 +135,8 @@ def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'}, @param filename: the CSV file with the list of runs to analyse @param format: type of file to load, nxs for Nexus, etc. @param plotresults: if true and this function is run from Mantidplot a graph will be created for the results of each reduction - @param saveAlgs: this named algorithm will be passed the name of the results workspace and filename (default = 'SaveRKH'). Pass a tuple of strings to save to multiple file formats + @param saveAlgs: this named algorithm will be passed the name of the results workspace and filename (default = 'SaveRKH'). + Pass a tuple of strings to save to multiple file formats @param verbose: set to true to write more information to the log (default=False) @param centreit: do centre finding (default=False) @param reducer: if to use the command line (default) or GUI reducer object @@ -210,7 +211,9 @@ def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'}, if verbose == 1: FindBeamCentre(50.,170.,12) - # WavRangeReduction runs the reduction for the specified wavelength range where the final argument can either be DefaultTrans or CalcTrans: + # WavRangeReduction runs the reduction for the specified + # wavelength range where the final argument can either be + # DefaultTrans or CalcTrans: reduced = WavRangeReduction(combineDet=combineDet, out_fit_settings=scale_shift) except SkipEntry, reason: diff --git a/scripts/SANS/SANSUtility.py b/scripts/SANS/SANSUtility.py index baca6361fcb1479711a2990589cfa44a8dee779e..85e1d15871189c3e0bd5cc8cf2cd1f34eb354111 100644 --- a/scripts/SANS/SANSUtility.py +++ b/scripts/SANS/SANSUtility.py @@ -635,7 +635,7 @@ def extract_child_ws_for_added_eventdata(ws_group, appendix): if len(ws_handles) != 2: raise RuntimeError("Expected two child workspaces when loading added event data." "Please make sure that you have loaded added event data which was generated by the Add tab of the SANS Gui." - ) + ) # Now ungroup the group UnGroupWorkspace(ws_group) @@ -826,8 +826,7 @@ def is_valid_ws_for_removing_zero_errors(input_workspace_name): if not isValid: message = ("Workspace does not seem valid for zero error removal." - "It must have been reduced with Q1D or Qxy." - ) + "It must have been reduced with Q1D or Qxy.") return message, isValid @@ -900,7 +899,6 @@ class PlusWorkspaces(object): @param output_workspace :: the output workspace @param time_shift :: unused parameter """ - dummy_shift = time_shift lhs_ws = self._get_workspace(LHS_workspace) rhs_ws = self._get_workspace(RHS_workspace) @@ -1117,7 +1115,8 @@ class CummulativeTimeSeriesPropertyAdder(object): log_name_start_time = "start_time" if (run_lhs.hasProperty(log_name_start_time) and run_rhs.hasProperty(log_name_start_time)): - convert_to_date = lambda val: DateAndTime(val) if isinstance(val, str) else val + def convert_to_date(val): + return DateAndTime(val) if isinstance(val, str) else val self._start_time_lhs = convert_to_date(run_lhs.getProperty(log_name_start_time).value) self._start_time_rhs = convert_to_date(run_rhs.getProperty(log_name_start_time).value) @@ -1324,7 +1323,7 @@ def is_convertible_to_int(input_value): @param input_value :: a general input ''' try: - dummy_converted = int(input_value) + int(input_value) except ValueError: return False return True @@ -1341,7 +1340,7 @@ def is_convertible_to_float(input_value): is_convertible = False else: try: - dummy_converted = float(input_value) + float(input_value) is_convertible = True except ValueError: is_convertible = False @@ -1543,7 +1542,6 @@ def correct_q_resolution_for_can(original_workspace, can_workspace, subtracted_w @param can_workspace: the can workspace @param subtracted_workspace: the subtracted workspace ''' - dummy1 = can_workspace if original_workspace.getNumberHistograms() == 1 and original_workspace.hasDx(0): subtracted_workspace.setDx(0, original_workspace.dataDx(0)) @@ -1656,7 +1654,7 @@ class MeasurementTimeFromNexusFileExtractor(object): sanslog.warning("Failed to retrieve the measurement time for " + str(filename_full)) finally: nxs_file.close() - except ValueError, NeXusError: + except ValueError: sanslog.warning("Failed to open the file: " + str(filename_full)) return measurement_time @@ -1752,7 +1750,6 @@ def is_valid_user_file_extension(user_file): filename, file_extension = os.path.splitext(user_file) file_extension = file_extension.upper() - dummy_file = filename is_allowed = False if file_extension in allowed_values or re.match(pattern, file_extension): is_allowed = True @@ -1961,7 +1958,8 @@ def SetupTransmissionWorkspace(inputWS, spec_list, backmon_start, backmon_end, w if loqremovebins: RemoveBins(InputWorkspace=tmpWS,OutputWorkspace=tmpWS,XMin= 19900,XMax= 20500, Interpolation='Linear') if backmon_start is not None and backmon_end is not None: - CalculateFlatBackground(InputWorkspace=tmpWS,OutputWorkspace= tmpWS, StartX = backmon_start, EndX = backmon_end, WorkspaceIndexList = spec_list, Mode='Mean') + CalculateFlatBackground(InputWorkspace=tmpWS, OutputWorkspace=tmpWS, + StartX=backmon_start, EndX=backmon_end, WorkspaceIndexList=spec_list, Mode='Mean') # Convert and rebin ConvertUnits(InputWorkspace=tmpWS,OutputWorkspace=tmpWS,Target="Wavelength") diff --git a/scripts/SANS/SANSadd2.py b/scripts/SANS/SANSadd2.py index 12c7c8d1aca95fb6ecff430df7a40158da09d53e..9244af582f57ab58554ed5a3fc3bf923dd2c4ee6 100644 --- a/scripts/SANS/SANSadd2.py +++ b/scripts/SANS/SANSadd2.py @@ -3,13 +3,14 @@ import os from mantid.simpleapi import * from mantid.kernel import Logger from SANSUtility import (bundle_added_event_data_as_group, AddOperation, transfer_special_sample_logs) -sanslog = Logger("SANS") from shutil import copyfile +sanslog = Logger("SANS") _NO_INDIVIDUAL_PERIODS = -1 -def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, binning='Monitors', saveAsEvent=False, isOverlay = False, time_shifts = []): +def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, + binning='Monitors', saveAsEvent=False, isOverlay = False, time_shifts = []): if inst.upper() == "SANS2DTUBES": inst = "SANS2D" #check if there is at least one file in the list @@ -102,7 +103,7 @@ def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add' return "" # in case of event file force it into a histogram workspace - if isFirstDataSetEvent and saveAsEvent == False: + if isFirstDataSetEvent and not saveAsEvent: wsInMonitor = mtd['AddFilesSumTempory_monitors'] if binning == 'Monitors': monX = wsInMonitor.dataX(0) @@ -219,9 +220,9 @@ def _makeFilename(entry, ext, inst) : If entry not already a valid filename make it into one """ try : - runNum = int(entry) #the user entered something that translates to a run number, convert it to a file + runNum = int(entry) #the user entered something that translates to a run number, convert it to a file filename=inst+_padZero(runNum, inst)+ext - except ValueError : #we don't have a run number, assume it's a valid filename + except ValueError: #we don't have a run number, assume it's a valid filename filename = entry dummy, ext = os.path.splitext(filename) @@ -318,7 +319,7 @@ def _copyLog(lastPath, logFile, pathout): copyfile(logFile, os.path.join(pathout, os.path.basename(logFile))) else: logger.notice("Could not find log file %s" % logFile) - except Exception, reason: + except Exception: error = 'Error copying log file ' + logFile + ' to directory ' + pathout+'\n' print error logger.notice(error) diff --git a/scripts/SANS/centre_finder.py b/scripts/SANS/centre_finder.py index 38194236520fcee5334daa42c9e7560b6fc829d7..c22bb431d8d6a019fb732e1ac35c731a127c26cf 100644 --- a/scripts/SANS/centre_finder.py +++ b/scripts/SANS/centre_finder.py @@ -233,7 +233,6 @@ class CentreFinder(object): return residueX, residueY def _residual_calculation_for_single_direction(self, yvalsA, yvalsB, qvalsA, qvalsB, qrange, nvals, id1, id2): - dummy_1 = qrange residue = 0 indexB = 0 for indexA in range(0, nvals): @@ -271,7 +270,7 @@ class CentrePositioner(object): Handles the positions and increments for beam finding. ''' - def __init__(self, reducer, position_type, coord1_start, coord2_start,coord1_step,coord2_step, tolerance): #pylint: disable=too-many-arguments + def __init__(self, reducer, position_type, coord1_start, coord2_start,coord1_step,coord2_step, tolerance): ''' Set the CentrePositioner. It requires: @param reducer:: The reducer @@ -401,10 +400,6 @@ class BeamCentrePositionUpdater(object): #pylint: disable=R0903 super(BeamCentrePositionUpdater, self).__init__() def increment_position(self, coord1_old, coord2_old, coord1_increment, coord2_increment): - dummy_1 = coord1_old - dummy_2 = coord2_old - dummy_3 = coord1_increment - dummy_4 = coord2_increment raise RuntimeError("BeamCentrePositionUpdater is not implemented") @@ -444,7 +439,6 @@ class BeamCentrePositionUpdaterUpDown(BeamCentrePositionUpdater): @param coord2_increment: the increment for the second coordinate @returns the incremented position ''' - dummy_1 = coord1_increment return coord1_old, coord2_old + coord2_increment @@ -465,7 +459,6 @@ class BeamCentrePositionUpdaterLeftRight(BeamCentrePositionUpdater): @param coord2_increment: the increment for the second coordinate @returns the incremented position ''' - dummy_1 = coord2_increment return coord1_old + coord1_increment, coord2_old def produce_final_position(self, x_new, x_initial, y_new, y_initial): @@ -477,8 +470,6 @@ class BeamCentrePositionUpdaterLeftRight(BeamCentrePositionUpdater): @param coord2_initial: the second initial coordinate @returns the final position ''' - dummy_1 = y_new - dummy_2 = x_initial return x_new, y_initial @@ -576,21 +567,14 @@ class PositionProviderFactory(object): class PositionProvider(object): def __init__(self, increment_coord1, increment_coord2, tolerance): super(PositionProvider,self).__init__() - dummy_1 = increment_coord1 - dummy_2 = increment_coord2 - dummy_3 = tolerance def get_coord1_for_input_with_correct_scaling(self, coord1): - dummy_coord1 = coord1 RuntimeError("The PositionProvider interface is not implemented") def get_coord1_for_output_with_correct_scaling_and_offset(self, coord1): - dummy_coord1 = coord1 RuntimeError("The PositionProvider interface is not implemented") def produce_initial_position(self, coord1, coord2): - dummy_coord1 = coord1 - dummy_coord2 = coord2 RuntimeError("The PositionProvider interface is not implemented") def half_and_reverse_increment_coord1(self): @@ -702,7 +686,7 @@ class PositionProviderAngleY(PositionProvider): and the second is a cartesian coordinate ''' - def __init__(self, increment_coord1, increment_coord2, tolerance, tolerance_angle, coord1_offset, coord1_scale_factor): #pylint: disable=too-many-arguments + def __init__(self, increment_coord1, increment_coord2, tolerance, tolerance_angle, coord1_offset, coord1_scale_factor): super(PositionProviderAngleY,self).__init__(increment_coord1, increment_coord2, tolerance) self.increment_angle = increment_coord1 self.increment_y = increment_coord2 diff --git a/scripts/SANS/isis_instrument.py b/scripts/SANS/isis_instrument.py index 3f5444eea0d5469e0e4e90196978fb3fed4d1a88..0af2527313a771a7470b512e6676b42b700a71a4 100644 --- a/scripts/SANS/isis_instrument.py +++ b/scripts/SANS/isis_instrument.py @@ -248,7 +248,7 @@ class DetectorBank(object): self._side_corr = None def get_y_corr(self): - if not self._y_corr is None: + if self._y_corr is not None: return self._y_corr else: raise NotImplementedError('y correction is not used for this detector') @@ -258,11 +258,11 @@ class DetectorBank(object): Only set the value if it isn't disabled @param value: set y_corr to this value, unless it's disabled """ - if not self._y_corr is None: + if self._y_corr is not None: self._y_corr = value def get_rot_corr(self): - if not self._rot_corr is None: + if self._rot_corr is not None: return self._rot_corr else: raise NotImplementedError('rot correction is not used for this detector') @@ -272,12 +272,12 @@ class DetectorBank(object): Only set the value if it isn't disabled @param value: set rot_corr to this value, unless it's disabled """ - if not self._rot_corr is None: + if self._rot_corr is not None: self._rot_corr = value # 22/3/12 RKH added two new variables radius_corr, side_corr def get_radius_corr(self): - if not self._radius_corr is None: + if self._radius_corr is not None: return self._radius_corr else: raise NotImplementedError('radius correction is not used for this detector') @@ -287,11 +287,11 @@ class DetectorBank(object): Only set the value if it isn't disabled @param value: set radius_corr to this value, unless it's disabled """ - if not self._rot_corr is None: + if self._rot_corr is not None: self._radius_corr = value def get_side_corr(self): - if not self._side_corr is None: + if self._side_corr is not None: return self._side_corr else: raise NotImplementedError('side correction is not used for this detector') @@ -301,7 +301,7 @@ class DetectorBank(object): Only set the value if it isn't disabled @param value: set side_corr to this value, unless it's disabled """ - if not self._side_corr is None: + if self._side_corr is not None: self._side_corr = value y_corr = property(get_y_corr, set_y_corr, None, None) @@ -390,7 +390,7 @@ class DetectorBank(object): is given by an orientation string and this function throws if the string is not recognised @param orien: the orienation string must be a string contained in the dictionary _ORIENTED """ - dummy = self._ORIENTED[orien] + self._ORIENTED[orien] self._orientation = orien def crop_to_detector(self, input_name, output_name=None): @@ -753,13 +753,6 @@ class ISISInstrument(BaseInstrument): @param coord2_scale_factor: scale factor for the second coordinate @param relative_displacement: If the the displacement is to be relative (it normally should be) """ - dummy_1 = workspace - dummy_2 = component_name - dummy_3 = coord1 - dummy_3 = coord2 - dummy_4 = relative_displacement - dummy_5 = coord1_scale_factor - dummy_6 = coord2_scale_factor raise RuntimeError("Not Implemented") def cur_detector_position(self, ws_name): @@ -768,7 +761,6 @@ class ISISInstrument(BaseInstrument): @param ws_name: the input workspace name @raise RuntimeError: Not implemented ''' - dummy_1 = ws_name raise RuntimeError("Not Implemented") def on_load_sample(self, ws_name, beamcentre, isSample): @@ -1629,9 +1621,9 @@ class LARMOR(ISISInstrument): MoveInstrumentComponent(ws, ComponentName=detBench.name(), X=xshift, Y=yshift, Z=zshift) # Deal with the angle value - _total_x_shift = self._rotate_around_y_axis(workspace=ws, component_name=detBench.name(), - x_beam=xbeam, x_scale_factor=XSF, - bench_rotation=BENCH_ROT) + self._rotate_around_y_axis(workspace=ws, component_name=detBench.name(), + x_beam=xbeam, x_scale_factor=XSF, + bench_rotation=BENCH_ROT) # Set the beam centre position afte the move self.beam_centre_pos1_after_move = xbeam # Need to provide the angle in 1000th of a degree @@ -1654,7 +1646,6 @@ class LARMOR(ISISInstrument): @param coord2_scale_factor: scale factor for the second coordinate @param relative_displacement: If the the displacement is to be relative (it normally should be) """ - dummy_coord2_scale_factor = coord2_scale_factor # Shift the component in the y direction MoveInstrumentComponent(Workspace=workspace, ComponentName=component_name, diff --git a/scripts/SANS/isis_reducer.py b/scripts/SANS/isis_reducer.py index c68fe092ef4b21c5f219bf60ce26c0cca49feff2..6358ed5f73c864887ef12924ae5b3b51e9f62b64 100644 --- a/scripts/SANS/isis_reducer.py +++ b/scripts/SANS/isis_reducer.py @@ -845,19 +845,11 @@ class ISISReducer(Reducer): ''' was_event = False if self.is_can(): - sample = self.get_can() - try: - dummy_ws = mtd[can.loader.wksp_name + "_monitors"] + can = self.get_can() + if can.loader.wksp_name + "_monitors" in mtd.getObjectNames(): was_event = True - # pylint: disable=bare-except - except: - was_event = False else: sample = self.get_sample() - try: - dummy_ws = mtd[sample.loader.wksp_name + "_monitors"] + if sample.loader.wksp_name + "_monitors" in mtd.getObjectNames(): was_event = True - # pylint: disable=bare-except - except: - was_event = False return was_event diff --git a/scripts/SANS/isis_reduction_steps.py b/scripts/SANS/isis_reduction_steps.py index c637aa3906967cb05ffd86c9925017b066ae279c..0a71a96c5f40ccc051003da319da7713ebf9350e 100644 --- a/scripts/SANS/isis_reduction_steps.py +++ b/scripts/SANS/isis_reduction_steps.py @@ -155,8 +155,6 @@ class LoadRun(object): """ if extra_options is None: extra_options = dict() - _inst = inst - _is_can = is_can if self._period != self.UNSET_PERIOD: workspace = self._get_workspace_name(self._period) if not can_load_as_event_workspace(self._data_file): @@ -256,7 +254,6 @@ class LoadRun(object): If reload is True, it will try to get all the information necessary to reload this workspace from the data file. """ - _reducer = reducer assert isinstance(self._data_file, Workspace) ws_pointer = self._data_file @@ -395,7 +392,7 @@ class LoadRun(object): return numPeriods def _getHistory(self, wk_name): - _ws = getWorkspaceReference(wk_name) + getWorkspaceReference(wk_name) if isinstance(wk_name, Workspace): ws_h = wk_name.getHistory() @@ -463,7 +460,6 @@ class LoadTransmissions(object): self._period_d = period def execute(self, reducer, workspace): - _workspace = workspace if self._trans_name not in [None, '']: self.trans = LoadRun(self._trans_name, trans=True, reload=self._reload, entry=self._period_t) self.trans._assignHelper(reducer) @@ -519,7 +515,7 @@ class CanSubtraction(ReductionStep): # clean up the workspaces ready users to see them if required if reducer.to_Q.output_type == '1D': - _rem_nans = StripEndNans() + StripEndNans() self._keep_partial_results(tmp_smp, tmp_can) @@ -565,7 +561,6 @@ class Mask_ISIS(ReductionStep): def __init__(self, timemask='', timemask_r='', timemask_f='', specmask='', specmask_r='', specmask_f=''): - _specmask = specmask self._xml = [] # these spectra will be masked by the algorithm MaskDetectors @@ -630,10 +625,6 @@ class Mask_ISIS(ReductionStep): @param complement: mask in the direction of the normal or away @return the xml string """ - if complement: - _addition = '#' - else: - _addition = '' return '<infinite-plane id="' + str(id) + '">' + \ '<point-in-plane x="' + str(plane_pt[0]) + '" y="' + str(plane_pt[1]) + '" z="' + \ str(plane_pt[2]) + '" />' + \ @@ -1762,15 +1753,18 @@ class DarkRunSubtraction(object): run_number.append(setting.run_number) # Get the indices with settings which correspond to the individual settings - get_indices = lambda time_flag, mon_flag : [i for i, val in enumerate(use_time) - if use_time[i] == time_flag and use_mon[i] == mon_flag] + def get_indices(time_flag, mon_flag): + return [i for i, use_time_i in enumerate(use_time) if use_time_i == time_flag and use_mon[i] == mon_flag] + indices_time_detector = get_indices(True, False) indices_time_monitor = get_indices(True, True) indices_uamp_detector = get_indices(False, False) indices_uamp_monitor = get_indices(False, True) # Check that for each of these settings we only have one run number specified, else raise an error - has_max_one_run_number = lambda indices : len(set([run_number[index] for index in indices])) < 2 + def has_max_one_run_number(indices): + return len(set([run_number[index] for index in indices])) < 2 + if not has_max_one_run_number(indices_time_detector) or \ not has_max_one_run_number(indices_time_monitor) or \ not has_max_one_run_number(indices_uamp_detector) or \ @@ -1852,9 +1846,8 @@ class DarkRunSubtraction(object): monitor_mon_numbers.append(mon_numbers[index]) # Check if the mean value is identical for all entries - are_all_same = lambda a_list : all([a_list[0] == a_list[i] for i in range(0, len(a_list))]) if len(monitor_mean) > 0: - if not are_all_same(monitor_mean): + if len(set(monitor_mean)) != 1: raise RuntimeError("DarkRunSubtraction: If several monitors are specified for a certain type " "of subtraction, it is required to use either all MEAN or all TOF.") @@ -1996,7 +1989,6 @@ class TransmissionCalc(ReductionStep): YUNITLABEL_TRANSMISSION_RATIO = "Transmission" def __init__(self, loader=None): - _loader = loader super(TransmissionCalc, self).__init__() # set these variables to None, which means they haven't been set and defaults will be set further down self.fit_props = ['lambda_min', 'lambda_max', 'fit_method', 'order'] @@ -2227,7 +2219,6 @@ class TransmissionCalc(ReductionStep): or estimates the proportion of neutrons that are transmitted through the sample """ - _workspace = workspace self.output_wksp = None # look for run files that contain transmission data @@ -2876,7 +2867,6 @@ class ConvertToQISIS(ReductionStep): ''' # Here we need to check if the binning has changed, ie if the # existing - _dummy_ws = det_bank_workspace raise RuntimeError("The QResolution optimization has not been implemented yet") def set_q_resolution_moderator(self, file_name): @@ -3035,7 +3025,6 @@ class UnitsConvert(ReductionStep): @param workspace: the name of the workspace to convert @param workspace: the name of the workspace to convert """ - _reducer = reducer ConvertUnits(InputWorkspace=workspace, OutputWorkspace=workspace, Target=self._units) low_wav = self.wav_low @@ -3167,8 +3156,6 @@ class BaseBeamFinder(ReductionStep): return [self._beam_center_x, self._beam_center_y] def execute(self, reducer, workspace=None): - _reducer = reducer - _workspace = workspace return "Beam Center set at: %s %s" % (str(self._beam_center_x), str(self._beam_center_y)) def update_beam_center(self, beam_center_x, beam_center_y): @@ -3221,7 +3208,6 @@ class UserFile(ReductionStep): return fresh def execute(self, reducer, workspace=None): - _workspace = workspace if self.filename is None: raise AttributeError('The user file must be set, use the function MaskFile') user_file = self.filename @@ -4009,7 +3995,6 @@ class GetOutputName(ReductionStep): @param reducer the reducer object that called this step @param workspace un-used """ - _workspace = workspace reducer.output_wksp = reducer.get_out_ws_name() @@ -4019,7 +4004,6 @@ class ReplaceErrors(ReductionStep): self.name = None def execute(self, reducer, workspace): - _reducer = reducer ReplaceSpecialValues(InputWorkspace=workspace, OutputWorkspace=workspace, NaNValue="0", InfinityValue="0") @@ -4069,7 +4053,6 @@ class StripEndNans(ReductionStep): @param reducer: unused @param workspace: the workspace to convert """ - _reducer = reducer result_ws = mtd[workspace] if result_ws.getNumberHistograms() != 1: # Strip zeros is only possible on 1D workspaces @@ -4231,7 +4214,6 @@ class GetSampleGeom(ReductionStep): Reads the geometry information stored in the workspace but doesn't replace values that have been previously set """ - _reducer = reducer wksp = mtd[workspace] if isinstance(wksp, WorkspaceGroup): wksp = wksp[0] diff --git a/scripts/SCD_Reduction/ReduceSCD_OneRun.py b/scripts/SCD_Reduction/ReduceSCD_OneRun.py index fece0e2ddee58f2ce902837be7ca2b7f8ef5119b..2d715a0b325d1ea3d858a25072010ffedd4add33 100644 --- a/scripts/SCD_Reduction/ReduceSCD_OneRun.py +++ b/scripts/SCD_Reduction/ReduceSCD_OneRun.py @@ -39,7 +39,7 @@ import os import sys import time import ReduceDictionary -sys.path.append("/opt/mantidnightly/bin") +sys.path.append("/opt/mantidnightly/bin") # noqa #sys.path.append("/opt/Mantid/bin") from mantid.simpleapi import * @@ -326,8 +326,7 @@ elif use_cylindrical_integration: Cylinder='1', CylinderLength = cylinder_length, PercentBackground = '20', ProfileFunction = 'NoFit', ProfilesFile = profiles_filename, - PeaksWorkspace=peaks_ws, - ) + PeaksWorkspace=peaks_ws) # # Save the final integrated peaks, using the Niggli reduced cell. @@ -342,14 +341,14 @@ else: # Print warning if user is trying to integrate using the cylindrical method and transorm the cell if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): + if (cell_type is not None) or (centering is not None): print "WARNING: Cylindrical profiles are NOT transformed!!!" # # If requested, also switch to the specified conventional cell and save the # corresponding matrix and integrate file # else: - if (not cell_type is None) and (not centering is None) : + if (cell_type is not None) and (centering is not None) : run_conventional_matrix_file = output_directory + "/" + run + "_" + \ cell_type + "_" + centering + ".mat" if output_nexus: diff --git a/scripts/SCD_Reduction/ReduceSCD_Parallel.py b/scripts/SCD_Reduction/ReduceSCD_Parallel.py index ae48269b7deb377779d52cfafa33d828e98af772..1e3001a958ee6a58d663e3bf62419edd2d7bcbf5 100644 --- a/scripts/SCD_Reduction/ReduceSCD_Parallel.py +++ b/scripts/SCD_Reduction/ReduceSCD_Parallel.py @@ -40,7 +40,7 @@ import threading import time import ReduceDictionary -sys.path.append("/opt/mantidnightly/bin") +sys.path.append("/opt/mantidnightly/bin") # noqa #sys.path.append("/opt/Mantid/bin") from mantid.simpleapi import * @@ -264,7 +264,7 @@ if not use_cylindrical_integration: # corresponding matrix and integrate file # if not use_cylindrical_integration: - if (not cell_type is None) and (not centering is None) : + if (cell_type is not None) and (centering is not None) : conv_name = output_directory + "/" + exp_name + "_" + cell_type + "_" + centering if output_nexus: conventional_integrate_file = conv_name + ".nxs" @@ -281,7 +281,7 @@ if not use_cylindrical_integration: SaveIsawUB( InputWorkspace=peaks_ws, Filename=conventional_matrix_file ) if use_cylindrical_integration: - if (not cell_type is None) or (not centering is None): + if (cell_type is not None) or (centering is not None): print "WARNING: Cylindrical profiles are NOT transformed!!!" # Combine *.profiles files filename = output_directory + '/' + exp_name + '.profiles' diff --git a/scripts/SCD_Reduction/SCDCalibratePanelsResults.py b/scripts/SCD_Reduction/SCDCalibratePanelsResults.py index ec292683733f762549d8844bdd793dea4fa0475c..6fa02b04079dd941228e5d0e0b289a8701385cec 100755 --- a/scripts/SCD_Reduction/SCDCalibratePanelsResults.py +++ b/scripts/SCD_Reduction/SCDCalibratePanelsResults.py @@ -9,7 +9,7 @@ import os import math import sys import numpy as np -sys.path.append("/opt/mantidnightly/bin") +sys.path.append("/opt/mantidnightly/bin") # noqa from mantid.simpleapi import * # Make a ./plots subdirectory for the plot files. diff --git a/scripts/TofConverter/convertUnits.py b/scripts/TofConverter/convertUnits.py index cbe8f2cb0ece87a28bb3c0cc00412b5af54b2785..89c14fcc0ff828eb431d13e4987f36ca0ad87cd8 100644 --- a/scripts/TofConverter/convertUnits.py +++ b/scripts/TofConverter/convertUnits.py @@ -15,7 +15,7 @@ def input2energy(inputval, inOption, theta, flightpath): e2lam = 81.787 #using lambda=h/p p: momentum, h: planck's const, lambda: wavelength e2nu = 4.139 # using h/(m*lambda^2) m: mass of neutron e2v = 0.0000052276 # using v = h/(m*lambda) - e2k = 2.717 #using k = 2*pi/(lambda) k:momentum + e2k = 2.0717 #using k = 2*pi/(lambda) k:momentum e2t = 0.086165 #using t = (m*v^2)/(2kb) kb: Boltzmann const e2cm = 0.123975 #cm = 8.06554465*E E:energy iv2 = inputval ** 2 @@ -70,7 +70,7 @@ def energy2output(Energy, outOption, theta, flightpath): e2lam = 81.787 #using lambda=h/p p: momentum, h: planck's const, lambda: wavelength e2nu = 4.139 # using h/(m*lambda^2) m: mass of neutron e2v = 0.0000052276 # using v = h/(m*lambda) - e2k = 2.717 #using k = 2*pi/(lambda) k:momentum + e2k = 2.0717 #using k = 2*pi/(lambda) k:momentum e2t = 0.086165 #using t = (m*v^2)/(2kb) kb: Boltzmann const e2cm = 0.123975 #cm = 8.06554465*E E:energy diff --git a/scripts/TofConverter/converterGUI.py b/scripts/TofConverter/converterGUI.py index 40b57c9af5d24e4d4016abe83ea07c301a261103..1d3d19f21905064565e80c4a70fe762605893694 100644 --- a/scripts/TofConverter/converterGUI.py +++ b/scripts/TofConverter/converterGUI.py @@ -13,12 +13,12 @@ class MainWindow(QtGui.QMainWindow): def thetaEnable (self, enabled): self.ui.scatteringAngleInput.setEnabled(enabled) - if enabled == False: + if not enabled: self.ui.scatteringAngleInput.clear() def flightPathEnable (self, enabled): self.ui.totalFlightPathInput.setEnabled(enabled) - if enabled == False: + if not enabled: self.ui.totalFlightPathInput.clear() def setInstrumentInputs (self): diff --git a/scripts/reduction/instruments/reflectometer/wks_utility.py b/scripts/reduction/instruments/reflectometer/wks_utility.py index bc7499d64033e3441ac35ee05d56dbb3a36a4726..630617631c38f81cd77ace0e81c47834a6d888f3 100644 --- a/scripts/reduction/instruments/reflectometer/wks_utility.py +++ b/scripts/reduction/instruments/reflectometer/wks_utility.py @@ -240,7 +240,6 @@ def findQaxisMinMax(q_axis): #find now the index of those min and max in each row _q_axis_min_max_index = zeros((nbr_row, 2)) for i in arange(nbr_row): - _q_axis = q_axis[i] for j in arange(nbr_col - 1): _q = q_axis[i, j] _q_next = q_axis[i, j + 1] @@ -269,7 +268,6 @@ def cleanup_data(InputWorkspace=None, _y = mti.readY(px)[tof] if _y != 0: _e = mti.readE(px)[tof] - _y2 = _y * _y # if _y < _e: if _y < 0 or _y < _e: _y = 0. @@ -300,8 +298,6 @@ def createIntegratedWorkspace(mt1, """ _tof_axis = mt1.readX(0)[:] - nbr_tof = len(_tof_axis) - _t_range = arange(nbr_tof-1) _fromXpixel = min([fromXpixel, toXpixel]) _toXpixel = max([fromXpixel, toXpixel]) @@ -574,10 +570,7 @@ def convertToRvsQWithCorrection(mt, dMD= -1, theta= -1.0, tof=None, yrange=None, # m = 1.675e-27 #kg sample = mt.getInstrument().getSample() - source = mt.getInstrument().getSource() - dSM = sample.getDistance(source) - _maxX = 304 maxY = 256 dPS_array = zeros(maxY) @@ -585,8 +578,6 @@ def convertToRvsQWithCorrection(mt, dMD= -1, theta= -1.0, tof=None, yrange=None, detector = mt.getDetector(y) dPS_array[y] = sample.getDistance(detector) - #array of distances pixel->source - _dMP_array = dPS_array + dSM #distance sample->center of detector dSD = dPS_array[maxY / 2] @@ -1063,7 +1054,6 @@ def integrateOverLowResRange(mt1, print '--> integrated over low res range of ', type _tof_axis = mt1.readX(0)[:].copy() - _nbr_tof = len(_tof_axis) # t_range = arange(nbr_tof-1) # -1 to work with index directly @@ -1072,10 +1062,8 @@ def integrateOverLowResRange(mt1, if is_nexus_detector_rotated_flag: sz_y_axis = 304 - _sz_x_axis = 256 else: sz_y_axis = 256 - _sz_x_axis = 304 _y_axis = zeros((sz_y_axis, len(_tof_axis) - 1)) _y_error_axis = zeros((sz_y_axis, len(_tof_axis) - 1)) @@ -1133,11 +1121,6 @@ def substractBackground(tof_axis, y_axis, y_error_axis, szPeak = peakMax - peakMin + 1 # init arrays - _minBack = [] - _minBackError = [] - _maxBack = [] - _maxBackError = [] - final_y_axis = zeros((szPeak, nbrTof)) final_y_error_axis = zeros((szPeak, nbrTof)) @@ -1325,7 +1308,6 @@ def sumWithError(value, error): def integratedOverPixelDim(data_y_axis, data_y_error_axis): size = data_y_axis.shape - _nbr_pixel = size[0] nbr_tof = size[1] final_data = zeros(nbr_tof) @@ -1340,7 +1322,6 @@ def integratedOverPixelDim(data_y_axis, data_y_error_axis): def fullSumWithError(data_y_axis, data_y_error_axis): size = data_y_axis.shape - _nbr_pixel = size[0] nbr_tof = size[1] final_data = zeros(nbr_tof) @@ -1695,8 +1676,6 @@ def getDistances(ws_event_data): detector = ws_event_data.getDetector(_index) dPS_array[y, x] = sample.getDistance(detector) - # Array of distances pixel->source - _dMP_array = dPS_array + dSM # Distance sample->center of detector dSD = dPS_array[256./2.,304./2.] # Distance source->center of detector @@ -1810,7 +1789,6 @@ def convertToQ(tof_axis, _tmp_q_axis = _q_axis[_y_index] _q_axis = _tmp_q_axis[::-1] #reverse the axis (now in increasing order) - _tmp_peak_pixel = y_range[_y_index] _y_axis_tmp = y_axis[_y_index,:] _y_error_axis_tmp = y_error_axis[_y_index,:] @@ -1893,7 +1871,6 @@ def getQaxis(dMD, dSD, theta, _const = float(4) * math.pi * m * dMD / h sz_tof = len(tof_axis) - _tmp_q_axis = zeros(sz_tof) q_array = zeros((len(y_range), sz_tof)) index_y = range(len(y_range)) @@ -1975,7 +1952,6 @@ def createQworkspace(q_axis, y_axis, y_error_axis): sz = q_axis.shape nbr_pixel = sz[0] - _nbr_tof = sz[1] q_axis_1d = q_axis.flatten() y_axis_1d = y_axis.flatten() diff --git a/scripts/reduction/instruments/sans/sans_reduction_steps.py b/scripts/reduction/instruments/sans/sans_reduction_steps.py index e4c3e02415402fceec5e664eb645ea2aa7d46a11..c4a28117080744cb5d9ff4a9c711720142a38938 100644 --- a/scripts/reduction/instruments/sans/sans_reduction_steps.py +++ b/scripts/reduction/instruments/sans/sans_reduction_steps.py @@ -223,10 +223,6 @@ class Mask(ReductionStep): @param complement: mask in the direction of the normal or away @return the xml string """ - if complement: - addition = '#' - else: - addition = '' return '<infinite-plane id="' + str(id) + '">' + \ '<point-in-plane x="' + str(plane_pt[0]) + '" y="' + str(plane_pt[1]) + '" z="' + str(plane_pt[2]) + \ '" />' + '<normal-to-plane x="' + str(normal_pt[0]) + '" y="' + str(normal_pt[1]) + '" z="' + \ @@ -707,7 +703,7 @@ class GetSampleGeom(ReductionStep): self._use_wksp_height = False # For a cylinder and sphere the height=width=radius - if (not self._shape is None) and (self._shape.startswith('cylinder')): + if (self._shape is not None) and (self._shape.startswith('cylinder')): self._width = self._height self._use_wksp_widtht = False diff --git a/scripts/reduction_workflow/instruments/sans/sns_instrument.py b/scripts/reduction_workflow/instruments/sans/sns_instrument.py index 14277d31ca4b9e5f501dda85766517b0fd61c309..b658f21c846855e924fd5e25cc0473d9ace99716 100644 --- a/scripts/reduction_workflow/instruments/sans/sns_instrument.py +++ b/scripts/reduction_workflow/instruments/sans/sns_instrument.py @@ -71,22 +71,6 @@ def get_masked_pixels(nx_low, nx_high, ny_low, ny_high, workspace): return masked_pts -def _get_pixel_info(workspace): - """ - Get the pixel size and number of pixels from the workspace - @param workspace: workspace to extract the pixel information from - """ - ## Number of detector pixels in X - nx_pixels = int(workspace.getInstrument().getNumberParameter("number-of-x-pixels")[0]) - ## Number of detector pixels in Y - ny_pixels = int(workspace.getInstrument().getNumberParameter("number-of-y-pixels")[0]) - ## Pixel size in mm - pixel_size_x = workspace.getInstrument().getNumberParameter("x-pixel-size")[0] - pixel_size_y = workspace.getInstrument().getNumberParameter("y-pixel-size")[0] - - return nx_pixels, ny_pixels, pixel_size_x, pixel_size_y - - def get_detector_from_pixel(pixel_list, workspace): """ Returns a list of detector IDs from a list of [x,y] pixels, diff --git a/tools/PeriodicTable/generate_atom_code.py b/tools/PeriodicTable/generate_atom_code.py index 855a70f8140d580d2c5b0e8294f9583ce21c186d..8b748b12436ea13ea1b38136531512060665dddb 100755 --- a/tools/PeriodicTable/generate_atom_code.py +++ b/tools/PeriodicTable/generate_atom_code.py @@ -1,9 +1,8 @@ #pylint: disable=invalid-name #!/usr/bin/env python -VERSION = "1.0" - import optparse +import sys try: import periodictable if not periodictable.__version__.startswith("1.3."): @@ -12,7 +11,8 @@ try: except ImportError, e: print "*****To use this you must 'easy_install periodictable'" sys.exit(-1) -import sys + +VERSION = "1.0" # elements not to put in the output file BANNED = ['n', 'Bk', 'Cf', 'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg', diff --git a/tools/Pylint/run_pylint.py b/tools/Pylint/run_pylint.py index 35573536c06d1690d5a739e62e9aa2df5d25fac2..f65189e81b0d620e7cae2382997201467cc798ed 100644 --- a/tools/Pylint/run_pylint.py +++ b/tools/Pylint/run_pylint.py @@ -248,7 +248,7 @@ def check_module_imports(): msg = "" #pylint: disable=unused-variable try: - import mantid + import mantid # noqa except ImportError, exc: msg = "Unable to import mantid module: '%s'\n"\ "Try passing the -m option along with the path to the module"\ @@ -353,7 +353,6 @@ def get_proc_results(processes, wait=False): (Updated processes, results) """ results = Results() - nprocs = len(processes) running = [] for index, proc_info in enumerate(processes): if wait: diff --git a/tools/reports/facility-code-changes.py b/tools/reports/facility-code-changes.py index 847db92595840b657ccfb455c1c211a6514e0749..b29ba55d91b5bb720551031e9697cc2f9f33430e 100644 --- a/tools/reports/facility-code-changes.py +++ b/tools/reports/facility-code-changes.py @@ -1,8 +1,6 @@ #pylint: disable=invalid-name from __future__ import (absolute_import, division, print_function, unicode_literals) -__author__ = 'Stuart Campbell' - import datetime import subprocess import csv @@ -10,6 +8,8 @@ import argparse import os import time +__author__ = 'Stuart Campbell' + def generate_file_changes_data(year_start, year_end): @@ -31,7 +31,7 @@ def generate_file_changes_data(year_start, year_end): f = open('facility-file-changes-{0}.stdout'.format(date_key),'w',buffering=0) arg_changes = ['git', 'log', '--pretty=format:"%aE"', '--shortstat', since, until] - sub = subprocess.Popen(arg_changes, stdout=f, stderr=subprocess.PIPE, cwd=repolocation) + subprocess.Popen(arg_changes, stdout=f, stderr=subprocess.PIPE, cwd=repolocation) f.flush() os.fsync(f.fileno()) f.close() @@ -58,7 +58,7 @@ def generate_commit_data(year_start, year_end): f = open('facility-commits-{0}.stdout'.format(date_key),'w',buffering=0) args_commits = ['git', 'log', '--pretty=format:"%aE"', since, until] - sub = subprocess.Popen(args_commits, stdout=f, stderr=subprocess.PIPE, cwd=repolocation) + subprocess.Popen(args_commits, stdout=f, stderr=subprocess.PIPE, cwd=repolocation) f.flush() os.fsync(f.fileno()) f.close() @@ -131,8 +131,7 @@ if __name__ == '__main__': 'granrothge@users.noreply.github.com': 'ORNL', 'tom.g.r.brooks@gmail.com': 'STFC', 'ross.whitfield@gmail.com': 'ORNL', - 'MikeHart85@users.noreply.github.com': 'STFC' - } + 'MikeHart85@users.noreply.github.com': 'STFC'} days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] diff --git a/tools/reports/release-list.py b/tools/reports/release-list.py index a77d6a7f84974a9d3271cd79b28a8dfe8274dbd8..890ba8ac1fa67319c39c6fceffbddb9fef53c049 100644 --- a/tools/reports/release-list.py +++ b/tools/reports/release-list.py @@ -1,9 +1,7 @@ #pylint: disable=invalid-name from __future__ import (absolute_import, division, print_function, unicode_literals) -import csv import datetime -import json import os import requests import subprocess diff --git a/tools/scripts/ConvertBadAlgmLinks.py b/tools/scripts/ConvertBadAlgmLinks.py index ec36764d225b94e13db98859baad1b04588a53c3..848d84b431acac0d717c6cedf251032c72d6607c 100644 --- a/tools/scripts/ConvertBadAlgmLinks.py +++ b/tools/scripts/ConvertBadAlgmLinks.py @@ -21,7 +21,6 @@ def grep(patt,lines): #get alg names algs = AlgorithmFactory.getRegisteredAlgorithms(True) -#algs = ['Abragam','BackToBackExponential','BivariateNormal','BSpline','Chebyshev','ChudleyElliot','CompositeFunction','Convolution','CubicSpline','DiffRotDiscreteCircle','DiffSphere','DSFInterp1DFit','ExpDecay','ExpDecayMuon','ExpDecayOsc','FickDiffusion','FlatBackground','GausDecay','GausOsc','Gaussian','HallRoss','IkedaCarpenterPV','LatticeErrors','LinearBackground','LogNormal','Lorentzian','MuonFInteraction','NeutronBk2BkExpConvPVoigt','PeakHKLErrors','ProductFunction','ProductLinearExp','ProductQuadraticExp','Quadratic','SCDPanelErrors','StaticKuboToyabe','StaticKuboToyabeTimesExpDecay','StaticKuboToyabeTimesGausDecay','StretchedExpFT','StretchExp','StretchExpMuon','TeixeiraWater','ThermalNeutronBk2BkExpConvPVoigt','UserFunction','Voigt'] regexs= {} for alg in algs: regexs[alg] = re.compile(r'`%s\s+<[\w\:\/\.]+\/%s>`_' % (alg,alg)) diff --git a/tools/scripts/CorrectConceptLinksinAlgPages.py b/tools/scripts/CorrectConceptLinksinAlgPages.py index de091b574842480209195c0cb5cfd4b6e37f5012..3591e2349db0880aeb05cfcbaf99d76fe1b3031c 100644 --- a/tools/scripts/CorrectConceptLinksinAlgPages.py +++ b/tools/scripts/CorrectConceptLinksinAlgPages.py @@ -1,7 +1,6 @@ #pylint: disable=invalid-name import os import re -import urllib2 concepts = ['Algorithm', 'Analysis_Data_Service', @@ -74,5 +73,5 @@ for alg in algs: with open (filename, "w") as algRst: algRst.write(algText) - if fileFound==False: + if not fileFound: outputError(alg, algVersion, "File not found") diff --git a/tools/scripts/FindIncompleteAlgRSTPages.py b/tools/scripts/FindIncompleteAlgRSTPages.py index 197d5cf5386ae760f3bb5ff914586b8ffd7cd686..5e2e00d21e7cea952b2ca776b35cf2f744bd7a82 100644 --- a/tools/scripts/FindIncompleteAlgRSTPages.py +++ b/tools/scripts/FindIncompleteAlgRSTPages.py @@ -35,7 +35,8 @@ for ticket in ticketList: ticketHash[ticket] = readWebPage( r"http://trac.mantidproject.org/mantid/ticket/" + str(ticket)) usagePattern = re.compile('Usage', re.IGNORECASE) -excusesPattern = re.compile('(rarely called directly|designed to work with other algorithms|only used for testing|deprecated)', re.IGNORECASE) +excusesPattern = re.compile('(rarely called directly|designed to work with other algorithms|only used for testing|deprecated)', + re.IGNORECASE) algs = AlgorithmFactory.getRegisteredAlgorithms(True) @@ -51,5 +52,5 @@ for alg in algs: #check if already in a ticket usageTicket = ticketExists(alg,ticketHash) outputError(alg, algVersion, "No usage section", usageTicket) - if fileFound==False: + if not fileFound: outputError(alg, algVersion, "File not found") diff --git a/tools/scripts/extractAuthorNamesFromGit.py b/tools/scripts/extractAuthorNamesFromGit.py index 6f0a5019b56ff332aee5949865eb4559cccbe3c4..6d211ff2d85007fdd92cd0399c8a3de3ada250c1 100644 --- a/tools/scripts/extractAuthorNamesFromGit.py +++ b/tools/scripts/extractAuthorNamesFromGit.py @@ -6,9 +6,7 @@ # was original used in connection with creating usage examples for algorithms # and creating an algorithm list for each developer to have a go at -import string import os -import re import subprocess