diff --git a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h index 9191b13619941a544f8dec5bcfa50ad6c2183b9e..7bcde9b23863f237fa13299422bde7cf00cb29bd 100644 --- a/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h +++ b/Framework/API/inc/MantidAPI/MatrixWorkspaceMDIterator.h @@ -127,8 +127,8 @@ private: /// The Y (vertical, e.g. spectra) dimension Mantid::Geometry::IMDDimension_const_sptr m_dimY; - /// Blocksize of workspace - size_t m_blockSize; + /// vector of starting index of the unraveled data array + std::vector<size_t> m_startIndices; /// Workspace index at which the iterator begins size_t m_beginWI; diff --git a/Framework/API/inc/MantidAPI/WorkspaceGroup.h b/Framework/API/inc/MantidAPI/WorkspaceGroup.h index 71b10329ff1e3045e31298ef79dcd3ba8a1c0e04..a3ab7f468295acfbb1d088c60a5971a547ed5b93 100644 --- a/Framework/API/inc/MantidAPI/WorkspaceGroup.h +++ b/Framework/API/inc/MantidAPI/WorkspaceGroup.h @@ -9,6 +9,7 @@ #include "MantidAPI/AnalysisDataService.h" #include <Poco/NObserver.h> +#include <iterator> #include <mutex> namespace Mantid { @@ -88,6 +89,19 @@ public: /// Prints the group to the screen using the logger at debug void print() const; + /// Returns a non-const iterator pointing at the first element in the + /// workspace group + std::vector<Workspace_sptr>::iterator begin(); + /// Returns a non-const iterator pointing at the last element in the workspace + /// group + std::vector<Workspace_sptr>::iterator end(); + /// Returns a const iterator pointing at the first element in the workspace + /// group + std::vector<Workspace_sptr>::const_iterator begin() const; + /// Returns a const iterator pointing at the last element in the workspace + /// group + std::vector<Workspace_sptr>::const_iterator end() const; + /// @name Wrapped ADS calls //@{ @@ -114,7 +128,6 @@ public: /// returns a copy as the internal vector can mutate while the vector is being /// iterated over. std::vector<std::string> getNames() const; - //@} WorkspaceGroup(const WorkspaceGroup &ref) = delete; diff --git a/Framework/API/src/ExperimentInfo.cpp b/Framework/API/src/ExperimentInfo.cpp index 156460e959a58de6fde3e9fa38065adc7d3d3af1..6906795293c2bd558bf2c2e2f64d52e0444a377d 100644 --- a/Framework/API/src/ExperimentInfo.cpp +++ b/Framework/API/src/ExperimentInfo.cpp @@ -1010,7 +1010,7 @@ ExperimentInfo::getInstrumentFilename(const std::string &instrumentName, if (!filePath.isFile()) continue; - std::string l_filenamePart = filePath.getFileName(); + const std::string &l_filenamePart = filePath.getFileName(); if (regex_match(l_filenamePart, regex)) { const auto &pathName = filePath.toString(); g_log.debug() << "Found file: '" << pathName << "'\n"; diff --git a/Framework/API/src/LogManager.cpp b/Framework/API/src/LogManager.cpp index 5178ff3e66b05aa7a6a81ab6cd7e99f44f383d33..dc611be94cec2b5b30584652357c9796df64a04b 100644 --- a/Framework/API/src/LogManager.cpp +++ b/Framework/API/src/LogManager.cpp @@ -463,7 +463,7 @@ void LogManager::clearOutdatedTimeSeriesLogValues() { */ void LogManager::saveNexus(::NeXus::File *file, const std::string &group, bool keepOpen) const { - file->makeGroup(group, "NXgroup", 1); + file->makeGroup(group, "NXgroup", true); file->putAttr("version", 1); // Save all the properties as NXlog diff --git a/Framework/API/src/MatrixWorkspace.cpp b/Framework/API/src/MatrixWorkspace.cpp index 0343dc8a37103d5eba8ebd55ad35a979607a03cd..ee0ee4c105fbbbfed9f58ed60ce35cb2b8dda6a1 100644 --- a/Framework/API/src/MatrixWorkspace.cpp +++ b/Framework/API/src/MatrixWorkspace.cpp @@ -171,12 +171,13 @@ const std::string MatrixWorkspace::toString() const { std::ostringstream os; os << id() << "\n" << "Title: " << getTitle() << "\n" - << "Histograms: " << getNumberHistograms() << "\n"; + << "Histograms: " << getNumberHistograms() << "\n" + << "Bins: "; try { - os << "Bins: " << blocksize() << "\n"; + os << blocksize() << "\n"; } catch (std::length_error &) { - os << "Bins: variable\n"; // TODO shouldn't use try/catch + os << "variable\n"; // TODO shouldn't use try/catch } if (isHistogramData()) diff --git a/Framework/API/src/MatrixWorkspaceMDIterator.cpp b/Framework/API/src/MatrixWorkspaceMDIterator.cpp index a50a0164233f3888baac601a5f1146975b949cc4..7fd7e4291a4abda9b9a3acfa7001974d9027006e 100644 --- a/Framework/API/src/MatrixWorkspaceMDIterator.cpp +++ b/Framework/API/src/MatrixWorkspaceMDIterator.cpp @@ -33,7 +33,6 @@ MatrixWorkspaceMDIterator::MatrixWorkspaceMDIterator( m_center = VMD(2); m_isBinnedData = m_ws->isHistogramData(); m_dimY = m_ws->getDimension(1); - m_blockSize = m_ws->blocksize(); m_beginWI = beginWI; if (m_beginWI >= m_ws->getNumberHistograms()) @@ -48,7 +47,14 @@ MatrixWorkspaceMDIterator::MatrixWorkspaceMDIterator( throw std::runtime_error( "MatrixWorkspaceMDIterator: End point is before the start point."); - m_max = (m_endWI - m_beginWI) * m_blockSize; + // calculate the indices and the largest index we accept + m_max = 0; + m_startIndices.reserve(m_endWI - m_beginWI); + for (size_t i = m_beginWI; i < m_endWI; ++i) { + m_startIndices.push_back(m_max); + m_max += m_ws->readY(i).size(); + } + m_xIndex = 0; // Trigger the calculation for the first index m_workspaceIndex = size_t(-1); // This makes sure calcWorkspacePos() updates @@ -66,9 +72,11 @@ size_t MatrixWorkspaceMDIterator::getDataSize() const { return size_t(m_max); } * @param index :: point to jump to. Must be 0 <= index < getDataSize(). */ void MatrixWorkspaceMDIterator::jumpTo(size_t index) { - m_pos = uint64_t(index); - m_xIndex = m_pos % m_blockSize; - size_t newWI = m_beginWI + (m_pos / m_blockSize); + m_pos = static_cast<uint64_t>(index); // index into the unraveled workspace + const auto lower = + std::lower_bound(m_startIndices.begin(), m_startIndices.end(), index); + m_xIndex = m_pos - (*lower); // index into the Y[] array of the spectrum + size_t newWI = m_beginWI + std::distance(m_startIndices.begin(), lower); calcWorkspacePos(newWI); } @@ -120,7 +128,7 @@ bool MatrixWorkspaceMDIterator::next() { do { m_pos++; m_xIndex++; - if (m_xIndex >= m_blockSize) { + if (m_xIndex >= m_Y.size()) { m_xIndex = 0; this->calcWorkspacePos(m_workspaceIndex + 1); } @@ -133,7 +141,7 @@ bool MatrixWorkspaceMDIterator::next() { // Go through every point; m_pos++; m_xIndex++; - if (m_xIndex >= m_blockSize) { + if (m_xIndex >= m_Y.size()) { m_xIndex = 0; this->calcWorkspacePos(m_workspaceIndex + 1); } diff --git a/Framework/API/src/Run.cpp b/Framework/API/src/Run.cpp index 4197729d4cbbeb8f397e9619d2cf47b839528e71..4458726d4258374d42d21210936002e471861496 100644 --- a/Framework/API/src/Run.cpp +++ b/Framework/API/src/Run.cpp @@ -348,7 +348,7 @@ void Run::saveNexus(::NeXus::File *file, const std::string &group, // write the histogram bins, if there are any if (!m_histoBins.empty()) { - file->makeGroup(HISTO_BINS_LOG_NAME, "NXdata", 1); + file->makeGroup(HISTO_BINS_LOG_NAME, "NXdata", true); file->writeData("value", m_histoBins); file->closeGroup(); } @@ -356,12 +356,12 @@ void Run::saveNexus(::NeXus::File *file, const std::string &group, const std::vector<double> &values = this->getPropertyValueAsType<std::vector<double>>("PeakRadius"); - file->makeGroup(PEAK_RADIUS_GROUP, "NXdata", 1); + file->makeGroup(PEAK_RADIUS_GROUP, "NXdata", true); file->writeData("value", values); file->closeGroup(); } if (this->hasProperty("BackgroundInnerRadius")) { - file->makeGroup(INNER_BKG_RADIUS_GROUP, "NXdata", 1); + file->makeGroup(INNER_BKG_RADIUS_GROUP, "NXdata", true); const std::vector<double> &values = this->getPropertyValueAsType<std::vector<double>>( "BackgroundInnerRadius"); @@ -369,7 +369,7 @@ void Run::saveNexus(::NeXus::File *file, const std::string &group, file->closeGroup(); } if (this->hasProperty("BackgroundOuterRadius")) { - file->makeGroup(OUTER_BKG_RADIUS_GROUP, "NXdata", 1); + file->makeGroup(OUTER_BKG_RADIUS_GROUP, "NXdata", true); const std::vector<double> &values = this->getPropertyValueAsType<std::vector<double>>( "BackgroundOuterRadius"); diff --git a/Framework/API/src/Sample.cpp b/Framework/API/src/Sample.cpp index ab57c3f541fd66ba8fd4c1a7c5fa607f83ec2413..4578f18482a805f761419fb651fa7254387b78d2 100644 --- a/Framework/API/src/Sample.cpp +++ b/Framework/API/src/Sample.cpp @@ -288,7 +288,7 @@ void Sample::addSample(boost::shared_ptr<Sample> childSample) { * @param group :: name of the group to create */ void Sample::saveNexus(::NeXus::File *file, const std::string &group) const { - file->makeGroup(group, "NXsample", 1); + file->makeGroup(group, "NXsample", true); file->putAttr("name", m_name); file->putAttr("version", 1); file->putAttr("shape_xml", m_shape.getShapeXML()); diff --git a/Framework/API/src/WorkspaceGroup.cpp b/Framework/API/src/WorkspaceGroup.cpp index 8d333b9041116226271c6a4d2c40d1f1f78f2f53..1fe9323e23858b64485d49e2279951071149dde6 100644 --- a/Framework/API/src/WorkspaceGroup.cpp +++ b/Framework/API/src/WorkspaceGroup.cpp @@ -224,9 +224,48 @@ void WorkspaceGroup::print() const { } } +/** + * Returns an iterator pointing to the first element in the group. + * + * @return A non-const iterator pointing to the first workspace in this + * workspace group. + */ +std::vector<Workspace_sptr>::iterator WorkspaceGroup::begin() { + return m_workspaces.begin(); +} + +/** + * Returns a const iterator pointing to the first element in the group. + * + * @return A const iterator pointing to the first workspace in this + * workspace group. + */ +std::vector<Workspace_sptr>::const_iterator WorkspaceGroup::begin() const { + return m_workspaces.begin(); +} + +/** + * Returns an iterator pointing to the past-the-end element in the group. + * + * @return A non-const iterator pointing to the last workspace in this + * workspace group. + */ +std::vector<Workspace_sptr>::iterator WorkspaceGroup::end() { + return m_workspaces.end(); +} + +/** Returns a const iterator pointing to the past-the-end element in the group. + * + * @return A const iterator pointing to the last workspace in this + * workspace group. + */ +std::vector<Workspace_sptr>::const_iterator WorkspaceGroup::end() const { + return m_workspaces.end(); +} + /** * Remove a workspace pointed to by an index. The workspace remains in the ADS - *if it was there + * if it was there * * @param index :: Index of a workspace to delete. */ diff --git a/Framework/API/test/ExperimentInfoTest.h b/Framework/API/test/ExperimentInfoTest.h index 0d8a85a0b40dd9c68dce778a3c621ef27d4d0a84..8390c21937a516b9ff785ee40ddcd3426a648738 100644 --- a/Framework/API/test/ExperimentInfoTest.h +++ b/Framework/API/test/ExperimentInfoTest.h @@ -879,37 +879,6 @@ public: compInfo.detectorsInSubtree(compInfo.indexOf(sourceId)).size(), 0); } - void test_component_info_stripped_of_invalid_detectors() { - using namespace Mantid::Geometry; - - auto instrument = boost::make_shared<Mantid::Geometry::Instrument>(); - int id = 1; - Detector *det1 = - new Detector("pixel1", id /*detector id*/, instrument.get()); - Detector *det2 = - new Detector("pixel2", id /*same detector id*/, instrument.get()); - // Add detector to the instrument - instrument->add(det1); - // Add other detector to the instrument - instrument->add(det2); - instrument->markAsDetector(det1); - // The following should fail. Same id is reused! - instrument->markAsDetector(det2); - - // A source - ObjComponent *source = new ObjComponent("source"); - instrument->add(source); - instrument->markAsSource(source); - - // A sample - ObjComponent *sample = new ObjComponent("some-surface-holder"); - instrument->add(sample); - instrument->markAsSamplePos(sample); - - ExperimentInfo expInfo; - TS_ASSERT_THROWS_NOTHING(expInfo.setInstrument(instrument)); - } - void test_component_info_source_sample_l1() { auto inst = ComponentCreationHelper::createMinimalInstrument( diff --git a/Framework/API/test/MatrixWorkspaceMDIteratorTest.h b/Framework/API/test/MatrixWorkspaceMDIteratorTest.h index dd67ce57540ed3081d0df9cf809038df1205bf2b..5d1f3979ffd901762e948ea5a47ca148c73f9883 100644 --- a/Framework/API/test/MatrixWorkspaceMDIteratorTest.h +++ b/Framework/API/test/MatrixWorkspaceMDIteratorTest.h @@ -13,6 +13,7 @@ using namespace Mantid; using namespace Mantid::API; using namespace Mantid::Kernel; using namespace Mantid::Geometry; +using namespace Mantid::HistogramData; class MatrixWorkspaceMDIteratorTest : public CxxTest::TestSuite { public: @@ -23,12 +24,12 @@ public: ws->initialize(4, 6, 5); NumericAxis *ax1 = new NumericAxis(4); for (size_t wi = 0; wi < 4; wi++) { - ax1->setValue(wi, double(wi) * 2.0); + ax1->setValue(wi, static_cast<double>(wi) * 2.0); for (size_t x = 0; x < 6; x++) { - ws->dataX(wi)[x] = double(x) * 2.0; + ws->dataX(wi)[x] = static_cast<double>(x) * 2.0; if (x < 5) { - ws->dataY(wi)[x] = double(wi * 10 + x); - ws->dataE(wi)[x] = double((wi * 10 + x) * 2); + ws->dataY(wi)[x] = static_cast<double>(wi * 10 + x); + ws->dataE(wi)[x] = static_cast<double>((wi * 10 + x) * 2); } } } @@ -100,16 +101,17 @@ public: for (size_t i = 0; i < iterators.size(); i++) { IMDIterator *it = iterators[i]; + const double i_d = static_cast<double>(i); // Only 5 elements per each iterator TS_ASSERT_EQUALS(it->getDataSize(), 5); - TS_ASSERT_DELTA(it->getSignal(), double(i) * 10 + 0.0, 1e-5); + TS_ASSERT_DELTA(it->getSignal(), i_d * 10 + 0.0, 1e-5); it->next(); - TS_ASSERT_DELTA(it->getSignal(), double(i) * 10 + 1.0, 1e-5); - TS_ASSERT_DELTA(it->getError(), double(i) * 20 + 2.0, 1e-5); + TS_ASSERT_DELTA(it->getSignal(), i_d * 10 + 1.0, 1e-5); + TS_ASSERT_DELTA(it->getError(), i_d * 20 + 2.0, 1e-5); // Coordinates at X index = 1 TS_ASSERT_DELTA(it->getCenter()[0], 3.0, 1e-5); // And this coordinate is the spectrum number - TS_ASSERT_DELTA(it->getCenter()[1], double(i * 2), 1e-5); + TS_ASSERT_DELTA(it->getCenter()[1], i_d * 2, 1e-5); TS_ASSERT(it->next()); TS_ASSERT(it->next()); TS_ASSERT(it->next()); @@ -128,6 +130,53 @@ public: } delete it; } + + void testUnequalBins() { + boost::shared_ptr<MatrixWorkspace> ws = makeFakeWS(); + // set the first spectrum to be different + ws->setHistogram(0, BinEdges({0, 1, 2}), Counts({10, 20})); + + // quick checks to make sure things are returning the expected values + TS_ASSERT(!(ws->isCommonBins())); + TS_ASSERT_THROWS(ws->blocksize(), std::logic_error); + TS_ASSERT_EQUALS(ws->size(), 17); + // Split in 4 iterators + std::vector<IMDIterator *> iterators = ws->createIterators(4, nullptr); + TS_ASSERT_EQUALS(iterators.size(), 4); + + for (size_t i = 0; i < iterators.size(); i++) { + IMDIterator *it = iterators[i]; + const double i_d = static_cast<double>(i); + if (i == 0) { + // Only 5 elements per each iterator + TS_ASSERT_EQUALS(it->getDataSize(), 2); + TS_ASSERT_DELTA(it->getSignal(), 10.0, 1e-5); + it->next(); + TS_ASSERT_DELTA(it->getSignal(), 20., 1e-5); + TS_ASSERT_DELTA(it->getError(), std::sqrt(20), 1e-5); + // Coordinates at X index = 1 + TS_ASSERT_DELTA(it->getCenter()[0], 1.5, 1e-5); + // And this coordinate is the spectrum number + TS_ASSERT_DELTA(it->getCenter()[1], 0.0, 1e-5); + } else { + // Only 5 elements per each iterator + TS_ASSERT_EQUALS(it->getDataSize(), 5); + TS_ASSERT_DELTA(it->getSignal(), i_d * 10 + 0.0, 1e-5); + it->next(); + TS_ASSERT_DELTA(it->getSignal(), i_d * 10 + 1.0, 1e-5); + TS_ASSERT_DELTA(it->getError(), i_d * 20 + 2.0, 1e-5); + // Coordinates at X index = 1 + TS_ASSERT_DELTA(it->getCenter()[0], 3.0, 1e-5); + // And this coordinate is the spectrum number + TS_ASSERT_DELTA(it->getCenter()[1], i_d * 2, 1e-5); + TS_ASSERT(it->next()); // more elements in i != 0 + TS_ASSERT(it->next()); + TS_ASSERT(it->next()); + } + TS_ASSERT(!it->next()); + delete it; + } + } }; #endif /* MANTID_API_MATRIXWORKSPACEMDITERATORTEST_H_ */ diff --git a/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h b/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h index d4182cf5a948e4d6cc70cd9bb59007d919482e6c..d47ca50770df2ce0664f44d5d00f3a376ef35a3c 100644 --- a/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h +++ b/Framework/Algorithms/inc/MantidAlgorithms/PhaseQuadMuon.h @@ -68,4 +68,4 @@ private: } // namespace Algorithms } // namespace Mantid -#endif /*MANTID_ALGORITHM_PHASEQUAD_H_*/ \ No newline at end of file +#endif /*MANTID_ALGORITHM_PHASEQUAD_H_*/ diff --git a/Framework/Algorithms/src/Bin2DPowderDiffraction.cpp b/Framework/Algorithms/src/Bin2DPowderDiffraction.cpp index 70a5cb7e10228130315df9970411f31f49f8a84d..a8b02431bc853fae552f03dec2a07b9d6d50bb90 100644 --- a/Framework/Algorithms/src/Bin2DPowderDiffraction.cpp +++ b/Framework/Algorithms/src/Bin2DPowderDiffraction.cpp @@ -183,7 +183,7 @@ MatrixWorkspace_sptr Bin2DPowderDiffraction::createOutputWorkspace() { << std::endl; size_t idx = 0; - for (const auto Xbins : fileXbins) { + for (const auto &Xbins : fileXbins) { g_log.debug() << "Xbins size: " << Xbins.size() << std::endl; BinEdges binEdges(Xbins); outputWS->setBinEdges(idx, binEdges); @@ -360,7 +360,7 @@ size_t Bin2DPowderDiffraction::UnifyXBins( void Bin2DPowderDiffraction::normalizeToBinArea(MatrixWorkspace_sptr outWS) { NumericAxis *verticalAxis = dynamic_cast<NumericAxis *>(outWS->getAxis(1)); - const std::vector<double> yValues = verticalAxis->getValues(); + const std::vector<double> &yValues = verticalAxis->getValues(); auto nhist = outWS->getNumberHistograms(); g_log.debug() << "Number of hists: " << nhist << " Length of YAxis: " << verticalAxis->length() << std::endl; diff --git a/Framework/Algorithms/src/CalMuonDetectorPhases.cpp b/Framework/Algorithms/src/CalMuonDetectorPhases.cpp index ddc555d2f17ca4d445bf818d8d0adc39337f2878..15ebefc35d35a6753a0ab72c74ce8ef603e64efa 100644 --- a/Framework/Algorithms/src/CalMuonDetectorPhases.cpp +++ b/Framework/Algorithms/src/CalMuonDetectorPhases.cpp @@ -202,22 +202,22 @@ void CalMuonDetectorPhases::extractDetectorInfo( double asym = paramTab->Double(0, 1); double phase = paramTab->Double(2, 1); // If asym<0, take the absolute value and add \pi to phase - // f(x) = A * sin( w * x + p) = -A * sin( w * x + p + PI) + // f(x) = A * cos( w * x + p) = -A * cos( w * x + p - PI) if (asym < 0) { asym = -asym; - phase = phase + M_PI; + phase = phase - M_PI; } // Now convert phases to interval [0, 2PI) - int factor = static_cast<int>(floor(phase / 2 / M_PI)); + int factor = static_cast<int>(floor(phase / (2. * M_PI))); if (factor) { - phase = phase - factor * 2 * M_PI; + phase = phase - factor * 2. * M_PI; } // Copy parameters to new row in results table API::TableRow row = resultsTab->appendRow(); row << static_cast<int>(spectrumNumber) << asym << phase; } -/** Creates the fitting function f(x) = A * sin( w*x + p) + B as string +/** Creates the fitting function f(x) = A * cos( w*x + p) + B as string * Two modes: * 1) Fixed frequency, no background - for main sequential fit * 2) Varying frequency, flat background - for finding frequency from asymmetry @@ -234,10 +234,10 @@ std::string CalMuonDetectorPhases::createFittingFunction(double freq, ss << "name=UserFunction,"; if (fixFreq) { // no background - ss << "Formula=A*sin(w*x+p),"; + ss << "Formula=A*cos(w*x+p),"; } else { // flat background - ss << "Formula=A*sin(w*x+p)+B,"; + ss << "Formula=A*cos(w*x+p)+B,"; ss << "B=0.5,"; } ss << "A=0.5,"; diff --git a/Framework/Algorithms/src/ClearCache.cpp b/Framework/Algorithms/src/ClearCache.cpp index 0cdf7ba229b312c4ccafbdc44bedb7052e1610a8..ca2702cd3eb2adbe225dcd732bbef7e0a987f6d1 100644 --- a/Framework/Algorithms/src/ClearCache.cpp +++ b/Framework/Algorithms/src/ClearCache.cpp @@ -136,7 +136,7 @@ int ClearCache::deleteFiles(const std::string &path, std::set<std::string> files; Poco::Glob::glob(pathPattern, files, Poco::Glob::GLOB_CASELESS); - for (auto filepath : files) { + for (const auto &filepath : files) { Poco::File file(filepath); g_log.debug("Deleting file " + filepath); try { diff --git a/Framework/Algorithms/src/ConvertAxisByFormula.cpp b/Framework/Algorithms/src/ConvertAxisByFormula.cpp index de1ab2350a84783216df15414e77d9a00103c55e..05a165a5428779056fccfb01acc6b0cdf4d75dc5 100644 --- a/Framework/Algorithms/src/ConvertAxisByFormula.cpp +++ b/Framework/Algorithms/src/ConvertAxisByFormula.cpp @@ -150,7 +150,7 @@ void ConvertAxisByFormula::exec() { mu::Parser p; try { // set parameter lookups for the axis value - for (auto variable : variables) { + for (const auto &variable : variables) { p.DefineVar(variable->name, &(variable->value)); } // set some constants @@ -262,7 +262,7 @@ void ConvertAxisByFormula::exec() { void ConvertAxisByFormula::setAxisValue(const double &value, std::vector<Variable_ptr> &variables) { - for (auto variable : variables) { + for (const auto &variable : variables) { if (!variable->isGeometric) { variable->value = value; } @@ -281,7 +281,7 @@ void ConvertAxisByFormula::calculateValues( void ConvertAxisByFormula::setGeometryValues( const API::SpectrumInfo &specInfo, const size_t index, std::vector<Variable_ptr> &variables) { - for (auto variable : variables) { + for (const auto &variable : variables) { if (variable->isGeometric) { if (variable->name == "twotheta") { variable->value = specInfo.twoTheta(index); diff --git a/Framework/Algorithms/src/CopyLogs.cpp b/Framework/Algorithms/src/CopyLogs.cpp index c1f3071e12b34de5313dc31d08a781ade3333634..e2f6b26df259a1fdeff40bb26490086b6d641a1f 100644 --- a/Framework/Algorithms/src/CopyLogs.cpp +++ b/Framework/Algorithms/src/CopyLogs.cpp @@ -56,7 +56,7 @@ void CopyLogs::exec() { // get logs from input workspace Run &inputRun = inputWs->mutableRun(); - auto inputLogs = inputRun.getLogData(); + const auto &inputLogs = inputRun.getLogData(); // get run from output workspace Run &outputRun = outputWs->mutableRun(); diff --git a/Framework/Algorithms/src/FilterEvents.cpp b/Framework/Algorithms/src/FilterEvents.cpp index ee310f2a8f1535282774addf9e8e4a5f39db76d0..936759f7cd0cd4699be40d6da404bf941cc301b1 100644 --- a/Framework/Algorithms/src/FilterEvents.cpp +++ b/Framework/Algorithms/src/FilterEvents.cpp @@ -1505,7 +1505,7 @@ void FilterEvents::setupCustomizedTOFCorrection() { // If there are more than 1 spectrum, it is very likely to have problem // with correction factor const DataObjects::EventList events = m_eventWS->getSpectrum(i); - auto detids = events.getDetectorIDs(); + const auto &detids = events.getDetectorIDs(); if (detids.size() != 1) { // Check whether there are more than 1 detector per spectra. stringstream errss; @@ -1894,7 +1894,7 @@ std::vector<std::string> FilterEvents::getTimeSeriesLogNames() { // append to vector if it is either double TimeSeries or int TimeSeries if (dbltimeprop || inttimeprop || booltimeprop) { - std::string pname = ip->name(); + const std::string &pname = ip->name(); lognames.push_back(pname); } } diff --git a/Framework/Algorithms/src/MagFormFactorCorrection.cpp b/Framework/Algorithms/src/MagFormFactorCorrection.cpp index 555d715fad57836bbaf7fe28bd5825fe51b46637..ed5942f120738cef99b2c1a83917f8dda51feda5 100644 --- a/Framework/Algorithms/src/MagFormFactorCorrection.cpp +++ b/Framework/Algorithms/src/MagFormFactorCorrection.cpp @@ -80,7 +80,7 @@ void MagFormFactorCorrection::exec() { } // Parses the ion name and get handle to MagneticIon object - const MagneticIon ion = getMagneticIon(ionNameStr); + const MagneticIon &ion = getMagneticIon(ionNameStr); // Gets the vector of form factor values std::vector<double> FF; FF.reserve(Qvals.size()); diff --git a/Framework/Algorithms/src/NormaliseByDetector.cpp b/Framework/Algorithms/src/NormaliseByDetector.cpp index beaf7b7dee014632ba1c07b5faf15ecb31f7dd8e..35d8b68ea84bd92dbeae797270a49ef2f2bc8c42 100644 --- a/Framework/Algorithms/src/NormaliseByDetector.cpp +++ b/Framework/Algorithms/src/NormaliseByDetector.cpp @@ -105,7 +105,7 @@ void NormaliseByDetector::processHistogram(size_t wsIndex, const Geometry::FitParameter &foundFittingParam = tryParseFunctionParameter(foundParam, det); - std::string fitFunctionName = foundFittingParam.getFunction(); + const std::string &fitFunctionName = foundFittingParam.getFunction(); IFunction_sptr function = FunctionFactory::Instance().createFunction(fitFunctionName); typedef std::vector<std::string> ParamNames; @@ -122,7 +122,7 @@ void NormaliseByDetector::processHistogram(size_t wsIndex, throw std::runtime_error( "A Forumla has not been provided for a fit function"); } else { - std::string resultUnitStr = fitParam.getResultUnit(); + const std::string &resultUnitStr = fitParam.getResultUnit(); if (!resultUnitStr.empty() && resultUnitStr != "Wavelength") { throw std::runtime_error( "Units for function parameters must be in Wavelength"); diff --git a/Framework/Algorithms/src/PDCalibration.cpp b/Framework/Algorithms/src/PDCalibration.cpp index 8a25e38b017d9c299055058b2275121955c91caf..8eef86258d9912d33f53cb208642b3f845220d66 100644 --- a/Framework/Algorithms/src/PDCalibration.cpp +++ b/Framework/Algorithms/src/PDCalibration.cpp @@ -61,7 +61,7 @@ public: // convert workspace index into detector id const auto &spectrum = wksp->getSpectrum(wkspIndex); - const auto detIds = spectrum.getDetectorIDs(); + const auto &detIds = spectrum.getDetectorIDs(); if (detIds.size() != 1) { throw std::runtime_error("Summed pixels is not currently supported"); } diff --git a/Framework/Algorithms/src/PhaseQuadMuon.cpp b/Framework/Algorithms/src/PhaseQuadMuon.cpp index b87f0d41f675e3c572ac21761e609784499a87fc..b05cb4fbb93ad9564bf585a6aea9c94ade1eff5c 100644 --- a/Framework/Algorithms/src/PhaseQuadMuon.cpp +++ b/Framework/Algorithms/src/PhaseQuadMuon.cpp @@ -6,6 +6,29 @@ #include "MantidKernel/PhysicalConstants.h" #include "MantidKernel/Unit.h" +namespace { +const std::array<std::string, 2> phaseNames = {{"phase", "phi"}}; +const std::array<std::string, 3> asymmNames = {{"asymmetry", "asymm", "asym"}}; + +template <typename T1, typename T2> +int findName(const T1 &patterns, const T2 &names) { + for (const std::string &pattern : patterns) { + auto it = std::find_if(names.begin(), names.end(), + [pattern](const std::string &s) { + if (s == pattern) { + return true; + } else { + return false; + } + }); + if (it != names.end()) { + return static_cast<int>(std::distance(names.begin(), it)); + } + } + return -1; +} +} + namespace Mantid { namespace Algorithms { @@ -92,7 +115,38 @@ std::map<std::string, std::string> PhaseQuadMuon::validateInputs() { if (tabWS->columnCount() != 3) { result["PhaseTable"] = "PhaseTable must have three columns"; } - + auto names = tabWS->getColumnNames(); + for (auto &name : names) { + std::transform(name.begin(), name.end(), name.begin(), ::tolower); + } + int phaseCount = 0; + int asymmetryCount = 0; + for (const std::string &name : names) { + for (const std::string &goodName : phaseNames) { + if (name == goodName) { + phaseCount += 1; + } + } + for (const std::string &goodName : asymmNames) { + if (name == goodName) { + asymmetryCount += 1; + } + } + } + if (phaseCount == 0) { + result["PhaseTable"] = "PhaseTable needs phases column"; + } + if (asymmetryCount == 0) { + result["PhaseTable"] = "PhaseTable needs a asymmetry/asymm/asym column"; + } + if (phaseCount > 1) { + result["PhaseTable"] = + "PhaseTable has " + std::to_string(phaseCount) + " phase columns"; + } + if (asymmetryCount > 1) { + result["PhaseTable"] = "PhaseTable has " + std::to_string(asymmetryCount) + + " asymmetry/asymm/asym columns"; + } // Check units, should be microseconds Unit_const_sptr unit = inputWS->getAxis(0)->unit(); if ((unit->caption() != "Time") || (unit->label().ascii() != "microsecond")) { @@ -101,6 +155,7 @@ std::map<std::string, std::string> PhaseQuadMuon::validateInputs() { return result; } + //---------------------------------------------------------------------------------------------- /** Calculates the normalization constant for the exponential decay * @param ws :: [input] Workspace containing the spectra to remove exponential @@ -168,11 +223,18 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, throw std::invalid_argument("Invalid normalization constants"); } + auto names = phase->getColumnNames(); + for (auto &name : names) { + std::transform(name.begin(), name.end(), name.begin(), ::tolower); + } + auto phaseIndex = findName(phaseNames, names); + auto asymmetryIndex = findName(asymmNames, names); + // Get the maximum asymmetry double maxAsym = 0.; for (size_t h = 0; h < nspec; h++) { - if (phase->Double(h, 1) > maxAsym) { - maxAsym = phase->Double(h, 1); + if (phase->Double(h, asymmetryIndex) > maxAsym) { + maxAsym = phase->Double(h, asymmetryIndex); } } if (maxAsym == 0.0) { @@ -188,8 +250,8 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, double sxy = 0.; for (size_t h = 0; h < nspec; h++) { - const double asym = phase->Double(h, 1) / maxAsym; - const double phi = phase->Double(h, 2); + const double asym = phase->Double(h, asymmetryIndex) / maxAsym; + const double phi = phase->Double(h, phaseIndex); const double X = n0[h] * asym * cos(phi); const double Y = n0[h] * asym * sin(phi); sxx += X * X; @@ -202,8 +264,8 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, const double lam2 = 2 * sxy / (sxy * sxy - sxx * syy); const double mu2 = 2 * sxx / (sxx * syy - sxy * sxy); for (size_t h = 0; h < nspec; h++) { - const double asym = phase->Double(h, 1) / maxAsym; - const double phi = phase->Double(h, 2); + const double asym = phase->Double(h, asymmetryIndex) / maxAsym; + const double phi = phase->Double(h, phaseIndex); const double X = n0[h] * asym * cos(phi); const double Y = n0[h] * asym * sin(phi); aj.push_back((lam1 * X + mu1 * Y) * 0.5); @@ -226,7 +288,7 @@ PhaseQuadMuon::squash(const API::MatrixWorkspace_sptr &ws, auto &realE = ows->mutableE(0); auto &imagE = ows->mutableE(1); - const auto &xPointData = ws->histogram(0).points(); + const auto xPointData = ws->histogram(0).points(); // First X value const double X0 = xPointData.front(); diff --git a/Framework/Algorithms/src/ReflectometryReductionOne2.cpp b/Framework/Algorithms/src/ReflectometryReductionOne2.cpp index 880d2ae3c1f26536bc471934742d601b707b3898..ccc851035de87393c7fb8acd8be051aeaef3685f 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOne2.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOne2.cpp @@ -94,7 +94,7 @@ void translateAdd(const std::string &instructions, std::vector<size_t> outSpectra; outSpectra.reserve(spectra.count()); - for (auto spectrum : spectra) { + for (const auto &spectrum : spectra) { // add this spectrum to the group we're about to add outSpectra.push_back(boost::lexical_cast<size_t>(spectrum)); } diff --git a/Framework/Algorithms/src/ReflectometryReductionOneAuto2.cpp b/Framework/Algorithms/src/ReflectometryReductionOneAuto2.cpp index 0e9b1399870d7869635d59178852ea12a68aecf9..170e36f77af977e02e5d4d067a7003040d92b110 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOneAuto2.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOneAuto2.cpp @@ -346,7 +346,7 @@ std::vector<std::string> ReflectometryReductionOneAuto2::getDetectorNames( std::vector<std::string> detectors; try { - for (const auto wsIndex : wsIndices) { + for (const auto &wsIndex : wsIndices) { size_t index = boost::lexical_cast<size_t>(wsIndex); diff --git a/Framework/Algorithms/src/RunCombinationHelpers/SampleLogsBehaviour.cpp b/Framework/Algorithms/src/RunCombinationHelpers/SampleLogsBehaviour.cpp index a734e22ceaf9dfd46064d21d921d77b5d11ed78a..8d7f330f2986b9c4c1eff9aaf2514950f00a1a7f 100644 --- a/Framework/Algorithms/src/RunCombinationHelpers/SampleLogsBehaviour.cpp +++ b/Framework/Algorithms/src/RunCombinationHelpers/SampleLogsBehaviour.cpp @@ -676,7 +676,7 @@ void SampleLogsBehaviour::removeSampleLogsFromWorkspace( * @param addeeWS the workspace being merged */ void SampleLogsBehaviour::readdSampleLogToWorkspace(MatrixWorkspace &addeeWS) { - for (auto item : m_addeeLogMap) { + for (const auto &item : m_addeeLogMap) { auto property = std::unique_ptr<Kernel::Property>(item->clone()); addeeWS.mutableRun().addProperty(std::move(property)); } diff --git a/Framework/Algorithms/test/CalMuonDetectorPhasesTest.h b/Framework/Algorithms/test/CalMuonDetectorPhasesTest.h index 90a8ee919699685c0cd922d7ac20eb005aa54df7..f1e01df541aa22ae0d668f90fb17ffb91c58772c 100644 --- a/Framework/Algorithms/test/CalMuonDetectorPhasesTest.h +++ b/Framework/Algorithms/test/CalMuonDetectorPhasesTest.h @@ -211,10 +211,10 @@ private: TS_ASSERT_DELTA(tab->Double(2, 1), 0.100, 0.001); TS_ASSERT_DELTA(tab->Double(3, 1), 0.100, 0.001); // Test phases - TS_ASSERT_DELTA(tab->Double(0, 2), 6.278, 0.001); - TS_ASSERT_DELTA(tab->Double(1, 2), 0.781, 0.001); - TS_ASSERT_DELTA(tab->Double(2, 2), 1.566, 0.001); - TS_ASSERT_DELTA(tab->Double(3, 2), 2.350, 0.001); + TS_ASSERT_DELTA(tab->Double(0, 2), 4.707, 0.001); + TS_ASSERT_DELTA(tab->Double(1, 2), 5.494, 0.001); + TS_ASSERT_DELTA(tab->Double(2, 2), 6.278, 0.001); + TS_ASSERT_DELTA(tab->Double(3, 2), 0.779, 0.001); } }; diff --git a/Framework/Algorithms/test/PhaseQuadMuonTest.h b/Framework/Algorithms/test/PhaseQuadMuonTest.h index 005d3b233609841b102baf6a82b1fa822371295c..4348b5f253f818cc6eb97e6d3c380c229e133450 100644 --- a/Framework/Algorithms/test/PhaseQuadMuonTest.h +++ b/Framework/Algorithms/test/PhaseQuadMuonTest.h @@ -1,6 +1,8 @@ #ifndef MANTID_ALGORITHMS_PHASEQUADMUONTEST_H_ #define MANTID_ALGORITHMS_PHASEQUADMUONTEST_H_ +#include <math.h> + #include <cxxtest/TestSuite.h> #include "MantidAPI/AlgorithmManager.h" #include "MantidAPI/AnalysisDataService.h" @@ -13,34 +15,58 @@ 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"); + +void populatePhaseTable(ITableWorkspace_sptr phaseTable, + std::vector<std::string> names, bool swap = false) { + phaseTable->addColumn("int", names[0]); + phaseTable->addColumn("double", names[1]); + phaseTable->addColumn("double", names[2]); + double asym(1.), phase(2.); + if (swap) { + std::swap(asym, phase); + } for (int i = 0; i < 16; i++) { TableRow phaseRow1 = phaseTable->appendRow(); - phaseRow1 << i << 1. << 0.; + phaseRow1 << i << asym << phase; TableRow phaseRow2 = phaseTable->appendRow(); - phaseRow2 << i << 1. << 1.57; + phaseRow2 << i << asym << phase; } } +void populatePhaseTable(ITableWorkspace_sptr phaseTable) { + populatePhaseTable(phaseTable, {"DetectorID", "Asymmetry", "Phase"}); +} -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); - +IAlgorithm_sptr setupAlg(MatrixWorkspace_sptr m_loadedData, bool isChildAlg, + ITableWorkspace_sptr phaseTable) { // Set up PhaseQuad IAlgorithm_sptr phaseQuad = AlgorithmManager::Instance().create("PhaseQuad"); phaseQuad->setChild(isChildAlg); phaseQuad->initialize(); - phaseQuad->setProperty("InputWorkspace", inputWs); + phaseQuad->setProperty("InputWorkspace", m_loadedData); phaseQuad->setProperty("PhaseTable", phaseTable); phaseQuad->setPropertyValue("OutputWorkspace", "outputWs"); return phaseQuad; } +IAlgorithm_sptr setupAlg(MatrixWorkspace_sptr m_loadedData, bool isChildAlg) { + // Create and populate a detector table + boost::shared_ptr<ITableWorkspace> phaseTable( + new Mantid::DataObjects::TableWorkspace); + populatePhaseTable(phaseTable); + + return setupAlg(m_loadedData, isChildAlg, phaseTable); +} + +IAlgorithm_sptr setupAlg(MatrixWorkspace_sptr m_loadedData, bool isChildAlg, + std::vector<std::string> names, bool swap = false) { + // Create and populate a detector table + boost::shared_ptr<ITableWorkspace> phaseTable( + new Mantid::DataObjects::TableWorkspace); + populatePhaseTable(phaseTable, names, swap); + + return setupAlg(m_loadedData, isChildAlg, phaseTable); +} + MatrixWorkspace_sptr loadMuonDataset() { IAlgorithm_sptr loader = AlgorithmManager::Instance().create("Load"); loader->setChild(true); @@ -49,14 +75,26 @@ MatrixWorkspace_sptr loadMuonDataset() { loader->setPropertyValue("OutputWorkspace", "outputWs"); loader->execute(); Workspace_sptr temp = loader->getProperty("OutputWorkspace"); - MatrixWorkspace_sptr inputWs = + MatrixWorkspace_sptr m_loadedData = boost::dynamic_pointer_cast<MatrixWorkspace>(temp); - return inputWs; + return m_loadedData; } } class PhaseQuadMuonTest : 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 PhaseQuadMuonTest *createSuite() { return new PhaseQuadMuonTest(); } + + static void destroySuite(PhaseQuadMuonTest *suite) { delete suite; } + + void setUp() override { + if (!m_loadedData) { + m_loadedData = loadMuonDataset(); + } + } + void testTheBasics() { IAlgorithm_sptr phaseQuad = AlgorithmManager::Instance().create("PhaseQuad"); @@ -67,8 +105,65 @@ public: } void testExecPhaseTable() { - MatrixWorkspace_sptr inputWs = loadMuonDataset(); - IAlgorithm_sptr phaseQuad = setupAlg(inputWs, true); + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true); + TS_ASSERT_THROWS_NOTHING(phaseQuad->execute()); + TS_ASSERT(phaseQuad->isExecuted()); + + // Get the output ws + MatrixWorkspace_sptr outputWs = phaseQuad->getProperty("OutputWorkspace"); + + TS_ASSERT_EQUALS(outputWs->getNumberHistograms(), 2); + TS_ASSERT_EQUALS( + outputWs->getSpectrum(0).readX(), + m_loadedData->getSpectrum(0).readX()); // Check outputWs X values + TS_ASSERT_EQUALS(outputWs->getSpectrum(1).readX(), + m_loadedData->getSpectrum(1).readX()); + + 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], 2.1969, 0.0001); + TS_ASSERT_DELTA(specReY[20], 0.0510, 0.0001); + TS_ASSERT_DELTA(specReY[50], -0.0525, 0.0001); + // Check real E values + TS_ASSERT_DELTA(specReE[0], 0.0024, 0.0001); + TS_ASSERT_DELTA(specReE[20], 0.0041, 0.0001); + TS_ASSERT_DELTA(specReE[50], 0.0047, 0.0001); + // Check imaginary Y values + TS_ASSERT_DELTA(specImY[0], -0.1035, 0.0001); + TS_ASSERT_DELTA(specImY[20], -0.0006, 0.0001); + TS_ASSERT_DELTA(specImY[50], 0.0047, 0.0001); + // Check imaginary E values + TS_ASSERT_DELTA(specImE[0], 0.0002, 0.0001); + TS_ASSERT_DELTA(specImE[20], 0.0004, 0.0001); + TS_ASSERT_DELTA(specImE[50], 0.0005, 0.0001); + } + void testNoPhase() { + std::vector<std::string> names = {"ID", "Asym", "dummy"}; + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true, names); + TS_ASSERT_THROWS(phaseQuad->execute(), std::runtime_error); + } + void testNoAsymm() { + std::vector<std::string> names = {"ID", "AsYMg", "phase"}; + MatrixWorkspace_sptr m_loadedData = loadMuonDataset(); + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true, names); + TS_ASSERT_THROWS(phaseQuad->execute(), std::runtime_error); + } + void testTwoPhases() { + std::vector<std::string> names = {"ID", "Phase", "phi"}; + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true, names); + TS_ASSERT_THROWS(phaseQuad->execute(), std::runtime_error); + } + void testTwoAsymm() { + std::vector<std::string> names = {"ID", "Asym", "Asymm"}; + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true, names); + TS_ASSERT_THROWS(phaseQuad->execute(), std::runtime_error); + } + void testSwapOrder() { + std::vector<std::string> names = {"ID", "phase", "Asymm"}; + IAlgorithm_sptr phaseQuad = setupAlg(m_loadedData, true, names, true); TS_ASSERT_THROWS_NOTHING(phaseQuad->execute()); TS_ASSERT(phaseQuad->isExecuted()); @@ -78,31 +173,35 @@ public: TS_ASSERT_EQUALS(outputWs->getNumberHistograms(), 2); TS_ASSERT_EQUALS( outputWs->getSpectrum(0).readX(), - inputWs->getSpectrum(0).readX()); // Check outputWs X values + m_loadedData->getSpectrum(0).readX()); // Check outputWs X values TS_ASSERT_EQUALS(outputWs->getSpectrum(1).readX(), - inputWs->getSpectrum(1).readX()); + m_loadedData->getSpectrum(1).readX()); 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], -1.0019, 0.0001); - TS_ASSERT_DELTA(specReY[20], -0.0289, 0.0001); - TS_ASSERT_DELTA(specReY[50], 0.0227, 0.0001); + TS_ASSERT_DELTA(specReY[0], 2.1969, 0.0001); + TS_ASSERT_DELTA(specReY[20], 0.0510, 0.0001); + TS_ASSERT_DELTA(specReY[50], -0.0525, 0.0001); // Check real E values - TS_ASSERT_DELTA(specReE[0], 0.0010, 0.0001); - TS_ASSERT_DELTA(specReE[20], 0.0021, 0.0001); - TS_ASSERT_DELTA(specReE[50], 0.0024, 0.0001); + TS_ASSERT_DELTA(specReE[0], 0.0024, 0.0001); + TS_ASSERT_DELTA(specReE[20], 0.0041, 0.0001); + TS_ASSERT_DELTA(specReE[50], 0.0047, 0.0001); // Check imaginary Y values - TS_ASSERT_DELTA(specImY[0], -1.0011, 0.0001); - TS_ASSERT_DELTA(specImY[20], 0.0079, 0.0001); - TS_ASSERT_DELTA(specImY[50], 0.0280, 0.0001); + TS_ASSERT_DELTA(specImY[0], -0.1035, 0.0001); + TS_ASSERT_DELTA(specImY[20], -0.0006, 0.0001); + TS_ASSERT_DELTA(specImY[50], 0.0047, 0.0001); // Check imaginary E values - TS_ASSERT_DELTA(specImE[0], 0.0029, 0.0001); - TS_ASSERT_DELTA(specImE[20], 0.0031, 0.0001); - TS_ASSERT_DELTA(specImE[50], 0.0035, 0.0001); + TS_ASSERT_DELTA(specImE[0], 0.0002, 0.0001); + TS_ASSERT_DELTA(specImE[20], 0.0004, 0.0001); + TS_ASSERT_DELTA(specImE[50], 0.0005, 0.0001); } + // add test for different order + +private: + MatrixWorkspace_sptr m_loadedData; }; class PhaseQuadMuonTestPerformance : public CxxTest::TestSuite { @@ -119,8 +218,8 @@ public: } void setUp() override { - inputWs = loadMuonDataset(); - phaseQuad = setupAlg(inputWs, false); + m_loadedData = loadMuonDataset(); + phaseQuad = setupAlg(m_loadedData, false); } void tearDown() override { @@ -130,7 +229,7 @@ public: void testPerformanceWs() { phaseQuad->execute(); } private: - MatrixWorkspace_sptr inputWs; + MatrixWorkspace_sptr m_loadedData; IAlgorithm_sptr phaseQuad; }; diff --git a/Framework/Crystal/src/AnvredCorrection.cpp b/Framework/Crystal/src/AnvredCorrection.cpp index 8f275c0324e1ae0fd563398d221d84581348ed75..23da65b6c574d5f767f5ab2c940d612af6a2e0a6 100644 --- a/Framework/Crystal/src/AnvredCorrection.cpp +++ b/Framework/Crystal/src/AnvredCorrection.cpp @@ -237,7 +237,7 @@ void AnvredCorrection::exec() { API::Run &run = correctionFactors->mutableRun(); run.addProperty<double>("Radius", m_radius, true); if (!m_onlySphericalAbsorption && !m_returnTransmissionOnly) - run.addProperty<bool>("LorentzCorrection", 1, true); + run.addProperty<bool>("LorentzCorrection", true, true); setProperty("OutputWorkspace", correctionFactors); } @@ -330,7 +330,7 @@ void AnvredCorrection::execEvent() { API::Run &run = correctionFactors->mutableRun(); run.addProperty<double>("Radius", m_radius, true); if (!m_onlySphericalAbsorption && !m_returnTransmissionOnly) - run.addProperty<bool>("LorentzCorrection", 1, true); + run.addProperty<bool>("LorentzCorrection", true, true); setProperty("OutputWorkspace", std::move(correctionFactors)); // Now do some cleaning-up since destructor may not be called immediately diff --git a/Framework/DataHandling/src/LoadEventNexus.cpp b/Framework/DataHandling/src/LoadEventNexus.cpp index b646c22ee35c49e60e31f2d2c4a4ffc1df435b80..3bca9459782a663cf12be3db1b4a2e383a509152 100644 --- a/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Framework/DataHandling/src/LoadEventNexus.cpp @@ -635,7 +635,7 @@ LoadEventNexus::LoadEventNexus() filter_tof_max(0), m_specList(), m_specMin(0), m_specMax(0), filter_time_start(), filter_time_stop(), chunk(0), totalChunks(0), firstChunkForBank(0), eventsPerChunk(0), m_tofMutex(), longest_tof(0), - shortest_tof(0), bad_tofs(0), discarded_events(0), precount(0), + shortest_tof(0), bad_tofs(0), discarded_events(0), precount(false), compressTolerance(0), eventVectors(), m_eventVectorMutex(), eventid_max(0), pixelID_to_wi_vector(), pixelID_to_wi_offset(), m_bankPulseTimes(), m_allBanksPulseTimes(), m_top_entry_name(), diff --git a/Framework/DataHandling/src/LoadMappingTable.cpp b/Framework/DataHandling/src/LoadMappingTable.cpp index 5a567cb2f5c647c9bd718aac6124bc1d1717b9a0..f9207fe1c43911d3399f9a027774227edbddba63 100644 --- a/Framework/DataHandling/src/LoadMappingTable.cpp +++ b/Framework/DataHandling/src/LoadMappingTable.cpp @@ -35,7 +35,7 @@ void LoadMappingTable::exec() { /// ISISRAW class instance which does raw file reading. auto iraw = Kernel::make_unique<ISISRAW2>(); - if (iraw->readFromFile(m_filename.c_str(), 0) != + if (iraw->readFromFile(m_filename.c_str(), false) != 0) // ReadFrom File with no data { g_log.error("Unable to open file " + m_filename); diff --git a/Framework/DataHandling/src/LoadNexusProcessed.cpp b/Framework/DataHandling/src/LoadNexusProcessed.cpp index 58c7f6db2579c3ea42ac9fec9e1aae2113bcea13..b21f81db28578b859531fbeba0fbfd4507a078fb 100644 --- a/Framework/DataHandling/src/LoadNexusProcessed.cpp +++ b/Framework/DataHandling/src/LoadNexusProcessed.cpp @@ -874,7 +874,7 @@ API::Workspace_sptr LoadNexusProcessed::loadTableEntry(NXEntry &entry) { columnNumber++; - } while (1); + } while (true); return boost::static_pointer_cast<API::Workspace>(workspace); } @@ -996,7 +996,7 @@ API::Workspace_sptr LoadNexusProcessed::loadPeaksEntry(NXEntry &entry) { columnNumber++; - } while (1); + } while (true); // Get information from all but data group std::string parameterStr; @@ -1584,19 +1584,21 @@ API::Workspace_sptr LoadNexusProcessed::loadEntry(NXRoot &root, local_workspace->loadExperimentInfoNexus( getPropertyValue("Filename"), m_cppFile, parameterStr); // REQUIRED PER PERIOD + + // Parameter map parsing only if instrument loaded OK. + progress(progressStart + 0.11 * progressRange, + "Reading the parameter maps..."); + local_workspace->readParameterMap(parameterStr); } catch (std::exception &e) { - g_log.information("Error loading Instrument section of nxs file"); - g_log.information(e.what()); + g_log.warning("Error loading Instrument section of nxs file"); + g_log.warning(e.what()); + g_log.warning("Try running LoadInstrument Algorithm on the Workspace to " + "update the geometry"); } // Now assign the spectra-detector map readInstrumentGroup(mtd_entry, local_workspace); - // Parameter map parsing - progress(progressStart + 0.11 * progressRange, - "Reading the parameter maps..."); - local_workspace->readParameterMap(parameterStr); - if (!local_workspace->getAxis(1) ->isSpectra()) { // If not a spectra axis, load the axis data into // the workspace. (MW 25/11/10) diff --git a/Framework/DataHandling/src/SaveNexusProcessed.cpp b/Framework/DataHandling/src/SaveNexusProcessed.cpp index df1889a141851d5b943d63b6db8f45053c87fac4..7cceb2f31bb182dd05dd4a538888746533cd5e71 100644 --- a/Framework/DataHandling/src/SaveNexusProcessed.cpp +++ b/Framework/DataHandling/src/SaveNexusProcessed.cpp @@ -547,7 +547,7 @@ void SaveNexusProcessed::saveSpectraMapNexus( } // Start the detector group - file->makeGroup("detector", "NXdetector", 1); + file->makeGroup("detector", "NXdetector", true); file->putAttr("version", 1); int numberSpec = int(spec.size()); diff --git a/Framework/Geometry/inc/MantidGeometry/Instrument/InstrumentVisitor.h b/Framework/Geometry/inc/MantidGeometry/Instrument/InstrumentVisitor.h index 05d5c406de04ef6856613d9ae9b7489388f3de79..d44302c5ba18422fc5a9a3326876fc280ad3bdb7 100644 --- a/Framework/Geometry/inc/MantidGeometry/Instrument/InstrumentVisitor.h +++ b/Framework/Geometry/inc/MantidGeometry/Instrument/InstrumentVisitor.h @@ -86,9 +86,6 @@ private: boost::shared_ptr<std::unordered_map<Mantid::Geometry::IComponent *, size_t>> m_componentIdToIndexMap; - /// Counter for dropped detectors - size_t m_droppedDetectors = 0; - /// Detector ID -> index mappings boost::shared_ptr<const std::unordered_map<detid_t, size_t>> m_detectorIdToIndexMap; diff --git a/Framework/Geometry/src/Crystal/OrientedLattice.cpp b/Framework/Geometry/src/Crystal/OrientedLattice.cpp index 50b52c1df2f9d58a31b8c9c1c5169e50cf3ab2ed..51b61d5e6a9fc1f7fafa59b4bd1ec60b089fa42e 100644 --- a/Framework/Geometry/src/Crystal/OrientedLattice.cpp +++ b/Framework/Geometry/src/Crystal/OrientedLattice.cpp @@ -220,7 +220,7 @@ const DblMatrix &OrientedLattice::setUFromVectors(const V3D &u, const V3D &v) { */ void OrientedLattice::saveNexus(::NeXus::File *file, const std::string &group) const { - file->makeGroup(group, "NXcrystal", 1); + file->makeGroup(group, "NXcrystal", true); file->writeData("unit_cell_a", this->a()); file->writeData("unit_cell_b", this->b()); file->writeData("unit_cell_c", this->c()); diff --git a/Framework/Geometry/src/Instrument.cpp b/Framework/Geometry/src/Instrument.cpp index cffba155f0f79a234c0f06010f63c6a6e71ad73d..ec1060f42d711d0b2ff6220f91f9f267a04010a4 100644 --- a/Framework/Geometry/src/Instrument.cpp +++ b/Framework/Geometry/src/Instrument.cpp @@ -28,6 +28,13 @@ namespace Geometry { namespace { Kernel::Logger g_log("Instrument"); + +void raiseDuplicateDetectorError(const size_t detectorId) { + std::stringstream sstream; + sstream << "Instrument Definition corrupt. Detector with ID " << detectorId + << " already exists."; + throw std::runtime_error(sstream.str()); +} } /// Default constructor @@ -709,12 +716,12 @@ void Instrument::markAsDetector(const IDetector *det) { // Create a (non-deleting) shared pointer to it IDetector_const_sptr det_sptr = IDetector_const_sptr(det, NoDeleting()); auto it = lower_bound(m_detectorCache, det->getID()); - // Silently ignore detector IDs that are already marked as detectors, even if - // the actual detector is different. - if ((it == m_detectorCache.end()) || (std::get<0>(*it) != det->getID())) { - bool isMonitor = false; - m_detectorCache.emplace(it, det->getID(), det_sptr, isMonitor); + // Duplicate detector ids are forbidden + if ((it != m_detectorCache.end()) && (std::get<0>(*it) == det->getID())) { + raiseDuplicateDetectorError(det->getID()); } + bool isMonitor = false; + m_detectorCache.emplace(it, det->getID(), det_sptr, isMonitor); } /// As markAsDetector but without the required sorting. Must call @@ -733,20 +740,21 @@ void Instrument::markAsDetectorIncomplete(const IDetector *det) { /// Sorts the detector cache. Called after all detectors have been marked via /// markAsDetectorIncomplete. void Instrument::markAsDetectorFinalize() { - // markAsDetector silently ignores detector IDs that are already marked as - // detectors, even if the actual detector is different. We mimic this behavior - // in this final sort by using stable_sort and removing duplicates. This will - // effectively favor the first detector with a certain ID that was added. - std::stable_sort(m_detectorCache.begin(), m_detectorCache.end(), - [](const std::tuple<detid_t, IDetector_const_sptr, bool> &a, - const std::tuple<detid_t, IDetector_const_sptr, bool> &b) - -> bool { return std::get<0>(a) < std::get<0>(b); }); - m_detectorCache.erase( - std::unique(m_detectorCache.begin(), m_detectorCache.end(), - [](const std::tuple<detid_t, IDetector_const_sptr, bool> &a, - const std::tuple<detid_t, IDetector_const_sptr, bool> &b) - -> bool { return std::get<0>(a) == std::get<0>(b); }), - m_detectorCache.end()); + // Detectors (even when different objects) are NOT allowed to have duplicate + // ids. This method establishes the presence of duplicates. + std::sort(m_detectorCache.begin(), m_detectorCache.end(), + [](const std::tuple<detid_t, IDetector_const_sptr, bool> &a, + const std::tuple<detid_t, IDetector_const_sptr, bool> &b) + -> bool { return std::get<0>(a) < std::get<0>(b); }); + + auto resultIt = std::adjacent_find( + m_detectorCache.begin(), m_detectorCache.end(), + [](const std::tuple<detid_t, IDetector_const_sptr, bool> &a, + const std::tuple<detid_t, IDetector_const_sptr, bool> &b) + -> bool { return std::get<0>(a) == std::get<0>(b); }); + if (resultIt != m_detectorCache.end()) { + raiseDuplicateDetectorError(std::get<0>(*resultIt)); + } } /** Mark a Component which has already been added to the Instrument class @@ -991,7 +999,7 @@ const std::string &Instrument::getXmlText() const { */ void Instrument::saveNexus(::NeXus::File *file, const std::string &group) const { - file->makeGroup(group, "NXinstrument", 1); + file->makeGroup(group, "NXinstrument", true); file->putAttr("version", 1); file->writeData("name", getName()); diff --git a/Framework/Geometry/src/Instrument/Goniometer.cpp b/Framework/Geometry/src/Instrument/Goniometer.cpp index 5e3362994e1fd06372ca491cadf1b896b4a50c73..3bae3f88603880e33666d42fce6e9d27970da9c9 100644 --- a/Framework/Geometry/src/Instrument/Goniometer.cpp +++ b/Framework/Geometry/src/Instrument/Goniometer.cpp @@ -248,7 +248,7 @@ void Goniometer::recalculateR() { */ void Goniometer::saveNexus(::NeXus::File *file, const std::string &group) const { - file->makeGroup(group, "NXpositioner", 1); + file->makeGroup(group, "NXpositioner", true); file->putAttr("version", 1); // Because the order of the axes is very important, they have to be written // and read out in the same order diff --git a/Framework/Geometry/src/Instrument/InstrumentVisitor.cpp b/Framework/Geometry/src/Instrument/InstrumentVisitor.cpp index e6aba051909095cafc96f1e689de3c288406d99c..13adc7e538800b24e92c5da9b3489683ff17ad1a 100644 --- a/Framework/Geometry/src/Instrument/InstrumentVisitor.cpp +++ b/Framework/Geometry/src/Instrument/InstrumentVisitor.cpp @@ -50,9 +50,8 @@ void clearLegacyParameters(ParameterMap *pmap, const IComponent &comp) { } /** - * @brief InstrumentVisitor::registerComponentAssembly + * Constructor * @param instrument : Instrument being visited - * @return Component index of this component */ InstrumentVisitor::InstrumentVisitor( boost::shared_ptr<const Instrument> instrument) @@ -239,43 +238,31 @@ void InstrumentVisitor::markAsSourceOrSample(ComponentID componentId, */ size_t InstrumentVisitor::registerDetector(const IDetector &detector) { - size_t detectorIndex = 0; - try { - detectorIndex = m_detectorIdToIndexMap->at(detector.getID()); - } catch (std::out_of_range &) { - /* - Do not register a detector with an invalid id. if we can't determine - the index, we cannot register it in the right place! - */ - ++m_droppedDetectors; - return detectorIndex; - } - if (m_componentIds->at(detectorIndex) == nullptr) { - - /* Already allocated we just need to index into the inital front-detector - * part of the collection. - * 1. Guarantee on grouping detectors by type such that the first n - * components - * are detectors. - * 2. Guarantee on ordering such that the - * detectorIndex == componentIndex for all detectors. - */ - // Record the ID -> component index mapping - (*m_componentIdToIndexMap)[detector.getComponentID()] = detectorIndex; - (*m_componentIds)[detectorIndex] = detector.getComponentID(); - m_assemblySortedDetectorIndices->push_back(detectorIndex); - (*m_detectorPositions)[detectorIndex] = - Kernel::toVector3d(detector.getPos()); - (*m_detectorRotations)[detectorIndex] = - Kernel::toQuaterniond(detector.getRotation()); - (*m_shapes)[detectorIndex] = detector.shape(); - (*m_scaleFactors)[detectorIndex] = - Kernel::toVector3d(detector.getScaleFactor()); - if (m_instrument->isMonitorViaIndex(detectorIndex)) { - m_monitorIndices->push_back(detectorIndex); - } - clearLegacyParameters(m_pmap, detector); + auto detectorIndex = m_detectorIdToIndexMap->at(detector.getID()); + + /* Already allocated we just need to index into the inital front-detector + * part of the collection. + * 1. Guarantee on grouping detectors by type such that the first n + * components + * are detectors. + * 2. Guarantee on ordering such that the + * detectorIndex == componentIndex for all detectors. + */ + // Record the ID -> component index mapping + (*m_componentIdToIndexMap)[detector.getComponentID()] = detectorIndex; + (*m_componentIds)[detectorIndex] = detector.getComponentID(); + m_assemblySortedDetectorIndices->push_back(detectorIndex); + (*m_detectorPositions)[detectorIndex] = Kernel::toVector3d(detector.getPos()); + (*m_detectorRotations)[detectorIndex] = + Kernel::toQuaterniond(detector.getRotation()); + (*m_shapes)[detectorIndex] = detector.shape(); + (*m_scaleFactors)[detectorIndex] = + Kernel::toVector3d(detector.getScaleFactor()); + if (m_instrument->isMonitorViaIndex(detectorIndex)) { + m_monitorIndices->push_back(detectorIndex); } + clearLegacyParameters(m_pmap, detector); + /* Note that positions and rotations for detectors are currently NOT stored! These go into DetectorInfo at present. push_back works for other Component types because Detectors are always come first in the resultant @@ -306,9 +293,7 @@ InstrumentVisitor::componentIds() const { * @return The total size of the components visited. * This will be the same as the number of IDs. */ -size_t InstrumentVisitor::size() const { - return m_componentIds->size() - m_droppedDetectors; -} +size_t InstrumentVisitor::size() const { return m_componentIds->size(); } bool InstrumentVisitor::isEmpty() const { return size() == 0; } @@ -371,6 +356,5 @@ InstrumentVisitor::makeWrappers(const Instrument &instrument, visitor.walkInstrument(); return visitor.makeWrappers(); } - } // namespace Geometry } // namespace Mantid diff --git a/Framework/Geometry/test/InstrumentTest.h b/Framework/Geometry/test/InstrumentTest.h index 49dd076d708a06720e3f192d8a3a6f7013abd215..ab3c53d9288fe4df41c1628ebd4d05dd0f4c5eba 100644 --- a/Framework/Geometry/test/InstrumentTest.h +++ b/Framework/Geometry/test/InstrumentTest.h @@ -668,6 +668,40 @@ public: TS_ASSERT(!instrument.isEmptyInstrument()); } + void test_duplicate_detectors_throw_via_mark_as_detector() { + + // Create a very basic instrument to visit + auto instrument = ComponentCreationHelper::createMinimalInstrument( + V3D(0, 0, 0) /*source pos*/, V3D(10, 0, 0) /*sample pos*/ + , + V3D(11, 0, 0) /*detector position*/); + + // Create an add a duplicate detector + Detector *det = + new Detector("invalid_detector", 1 /*DUPLICATE detector id*/, nullptr); + instrument->add(det); + TSM_ASSERT_THROWS("Duplicate ID, should throw", + instrument->markAsDetector(det), std::runtime_error &); + } + + void test_duplicate_detectors_throw_via_mark_as_detector_finalize() { + + // Create a very basic instrument to visit + auto instrument = ComponentCreationHelper::createMinimalInstrument( + V3D(0, 0, 0) /*source pos*/, V3D(10, 0, 0) /*sample pos*/ + , + V3D(11, 0, 0) /*detector position*/); + + // Create an add a duplicate detector + Detector *det = + new Detector("invalid_detector", 1 /*DUPLICATE detector id*/, nullptr); + instrument->add(det); + instrument->markAsDetectorIncomplete(det); + TSM_ASSERT_THROWS("Duplicate ID, should throw", + instrument->markAsDetectorFinalize(), + std::runtime_error &); + } + private: Instrument_sptr createInstrumentWithSource() { using Mantid::Kernel::V3D; diff --git a/Framework/Geometry/test/InstrumentVisitorTest.h b/Framework/Geometry/test/InstrumentVisitorTest.h index 4d4b525ba33203a5063b6338b91382ade5b47a46..352c57dbd6658b452a226317ce047ef7adbb32c6 100644 --- a/Framework/Geometry/test/InstrumentVisitorTest.h +++ b/Framework/Geometry/test/InstrumentVisitorTest.h @@ -291,40 +291,6 @@ public: TS_ASSERT_EQUALS(visitor.detectorIds()->at(0), 1); // index 0 is ID 1 } - void test_visitor_drops_detectors_without_id() { - /* - We have to go via DetectorInfo::indexOf to get the index of a detector. - if this throws because the detector has an invalid id, we are forced to - drop it. - Some IDFs i.e. SNAP have montiors with detector ids < 0. - */ - - // Create a very basic instrument to visit - auto visitee = createMinimalInstrument(V3D(0, 0, 0) /*source pos*/, - V3D(10, 0, 0) /*sample pos*/ - , - V3D(11, 0, 0) /*detector position*/); - - // Create an add a duplicate detector - Detector *det = - new Detector("invalid_detector", 1 /*DUPLICATE detector id*/, nullptr); - visitee->add(det); - visitee->markAsDetector(det); - - InstrumentVisitor visitor(visitee); - - // Visit everything - visitor.walkInstrument(); - - size_t expectedSize = 0; - ++expectedSize; // only detector - ++expectedSize; // source - ++expectedSize; // sample - ++expectedSize; // instrument - // Note no second detector counted - TS_ASSERT_EQUALS(visitor.size(), expectedSize); - } - void test_visitation_of_rectangular_detector() { // Need confidence that this works properly for RectangularDetectors diff --git a/Framework/Geometry/test/ParInstrumentTest.h b/Framework/Geometry/test/ParInstrumentTest.h index 86a41d036278bee5d35e832af5c54ec4d2059376..9943b08a6ada384b844ede39a13c800d2642f888 100644 --- a/Framework/Geometry/test/ParInstrumentTest.h +++ b/Framework/Geometry/test/ParInstrumentTest.h @@ -37,7 +37,6 @@ public: instrument->markAsDetector(det2); det3 = new Detector("det3", 11, nullptr); instrument->add(det3); - instrument->markAsDetector(det3); instrument->markAsMonitor(det3); pmap.reset(new ParameterMap); diff --git a/Framework/Kernel/inc/MantidKernel/System.h b/Framework/Kernel/inc/MantidKernel/System.h index 9fd4783776846db9976b1a2a6a5b9046e564fd4d..d7f94e97893a5d34115e5d01754e24648ff8598a 100644 --- a/Framework/Kernel/inc/MantidKernel/System.h +++ b/Framework/Kernel/inc/MantidKernel/System.h @@ -81,7 +81,7 @@ /** * A Macro to mark a function as deprecated. */ -#ifdef __GNUC__ +#if (defined(__GNUC__) || defined(__clang__)) #define DEPRECATED(func) func __attribute__((deprecated)) #elif defined(_MSC_VER) #define DEPRECATED(func) __declspec(deprecated) func diff --git a/Framework/Kernel/src/CompositeValidator.cpp b/Framework/Kernel/src/CompositeValidator.cpp index a3727f3d382777495f8f3ce4320a936dc5549933..b6af12842ca5fc78aa4ae7aa0c9b491464a04183 100644 --- a/Framework/Kernel/src/CompositeValidator.cpp +++ b/Framework/Kernel/src/CompositeValidator.cpp @@ -82,7 +82,7 @@ std::string CompositeValidator::check(const boost::any &value) const { } std::string CompositeValidator::checkAll(const boost::any &value) const { - for (const auto validator : m_children) { + for (const auto &validator : m_children) { const auto error = validator->check(value); // exit on the first error, to avoid passing doing more tests on invalid // objects that could fail diff --git a/Framework/Kernel/src/Material.cpp b/Framework/Kernel/src/Material.cpp index 8cfe58313dd97489151696d82b073dd6ff074bfc..6ac3951c57ab06caa382a1cb011b40f1d02abf4c 100644 --- a/Framework/Kernel/src/Material.cpp +++ b/Framework/Kernel/src/Material.cpp @@ -384,7 +384,7 @@ double Material::totalScatterLengthSqrd(const double lambda) const { * @param group :: name of the group to create */ void Material::saveNexus(::NeXus::File *file, const std::string &group) const { - file->makeGroup(group, "NXdata", 1); + file->makeGroup(group, "NXdata", true); file->putAttr("version", 2); file->putAttr("name", m_name); diff --git a/Framework/Kernel/src/TimeSeriesProperty.cpp b/Framework/Kernel/src/TimeSeriesProperty.cpp index c7a24fc95ab27f9fb0d876d525badad72b8b003a..8fca4287759f35ef9c4d55e319767226f035707c 100644 --- a/Framework/Kernel/src/TimeSeriesProperty.cpp +++ b/Framework/Kernel/src/TimeSeriesProperty.cpp @@ -2237,7 +2237,7 @@ void TimeSeriesProperty<std::string>::saveProperty(::NeXus::File *file) { std::vector<std::string> values = this->valuesAsVector(); if (values.empty()) return; - file->makeGroup(this->name(), "NXlog", 1); + file->makeGroup(this->name(), "NXlog", true); // Find the max length of any string auto max_it = @@ -2275,7 +2275,7 @@ template <> void TimeSeriesProperty<bool>::saveProperty(::NeXus::File *file) { if (value.empty()) return; std::vector<uint8_t> asUint(value.begin(), value.end()); - file->makeGroup(this->name(), "NXlog", 1); + file->makeGroup(this->name(), "NXlog", true); file->writeData("value", asUint); file->putAttr("boolean", "1"); saveTimeVector(file); diff --git a/Framework/LiveData/src/ISIS/DAE/isisds_command.cpp b/Framework/LiveData/src/ISIS/DAE/isisds_command.cpp index 53c6321bda2c627f032645387ae5cfde633c4d95..9cd10abdd3cca214200d14ec18ccf04c6e52c7da 100644 --- a/Framework/LiveData/src/ISIS/DAE/isisds_command.cpp +++ b/Framework/LiveData/src/ISIS/DAE/isisds_command.cpp @@ -343,9 +343,11 @@ int isisds_recv_command(SOCKET s, char *command, int *len_command, void *data, istat = isisds_recv_command_helper(s, &command_temp, &data, type, dims_array, ndims, 0); } - strncpy(command, command_temp, *len_command); - *len_command = static_cast<int>(strlen(command_temp)); - free(command_temp); + if (command_temp) { + strncpy(command, command_temp, *len_command); + *len_command = static_cast<int>(strlen(command_temp)); + free(command_temp); + } return istat; } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp index 21f061e5da20c83f282868550ccd5e0f9ea4fa95..28de6020d119dc58eeeaab4c1702e483153aecce 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp @@ -40,7 +40,7 @@ getChildrenAsList(boost::shared_ptr<AlgorithmHistory> self) { */ boost::python::object getPropertiesAsList(AlgorithmHistory &self) { boost::python::list names; - const auto histories = self.getProperties(); + const auto &histories = self.getProperties(); for (const auto &historie : histories) { names.append(historie); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp b/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp index 3595b9e7ef30dc80bfce390d2b4fa4fd58337fbe..0acc3ee16b7296a5cac205637e2b72281cd9abe6 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/BinaryOperations.cpp @@ -156,7 +156,7 @@ ResultType performBinaryOpWithDouble(const LHSType inputWS, const double value, const std::string &op, const std::string &name, bool inplace, bool reverse) { - std::string algoName = op; + const std::string &algoName = op; // Create the single valued workspace first so that it is run as a top-level // algorithm diff --git a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp index 7329e9ee30cbcb8c4f38f8bd35dce11769236226..0e5d66f5aecd35c357e7b65427d253690153d8d1 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceGroup.cpp @@ -4,7 +4,9 @@ #include "MantidPythonInterface/kernel/Registry/RegisterWorkspacePtrToPython.h" #include <boost/python/class.hpp> +#include <boost/python/copy_non_const_reference.hpp> #include <boost/python/return_value_policy.hpp> +#include <boost/python/iterator.hpp> using namespace Mantid::API; using namespace Mantid::PythonInterface; @@ -12,6 +14,28 @@ using namespace boost::python; GET_POINTER_SPECIALIZATION(WorkspaceGroup) +/** + * Returns an iterator pointing to the first element in the group. + * + * @param self :: handle to the workspace group. + * @return A non-const iterator pointing at start of workspace group, + * for use in python. + */ +std::vector<Workspace_sptr>::iterator group_begin(WorkspaceGroup &self) { + return self.begin(); +} + +/** + * Returns an iterator pointing to the past-the-end element in the group. + * + * @param self :: handle to the workspace group. + * @return A non-const iterator pointing at end of workspace group, + * for use in python. + */ +std::vector<Workspace_sptr>::iterator group_end(WorkspaceGroup &self) { + return self.end(); +} + void export_WorkspaceGroup() { class_<WorkspaceGroup, bases<Workspace>, boost::noncopyable>("WorkspaceGroup", no_init) @@ -51,7 +75,9 @@ void export_WorkspaceGroup() { (Workspace_sptr (WorkspaceGroup::*)(const size_t) const) & WorkspaceGroup::getItem, (arg("self"), arg("index")), - return_value_policy<Policies::ToWeakPtr>()); + return_value_policy<Policies::ToWeakPtr>()) + .def("__iter__", range<return_value_policy<copy_non_const_reference>>( + &group_begin, &group_end)); Registry::RegisterWorkspacePtrToPython<WorkspaceGroup>(); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp index 9d53db73f7a7d20823d31d63b96621c49365bc6b..ada4060c095776b0647cd27beb0ba3dedf97541b 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp @@ -25,7 +25,7 @@ GET_POINTER_SPECIALIZATION(WorkspaceHistory) */ boost::python::object getHistoriesAsList(WorkspaceHistory &self) { boost::python::list names; - const auto histories = self.getAlgorithmHistories(); + const auto &histories = self.getAlgorithmHistories(); for (const auto &historie : histories) { names.append(historie); } diff --git a/Framework/PythonInterface/mantid/api/src/FitFunctions/IFunctionAdapter.cpp b/Framework/PythonInterface/mantid/api/src/FitFunctions/IFunctionAdapter.cpp index cab183753b65b9c3b40c63897e2695a9ce30777b..8f1398c9ae6a725bd58ab783109e5aad1a9ab5b5 100644 --- a/Framework/PythonInterface/mantid/api/src/FitFunctions/IFunctionAdapter.cpp +++ b/Framework/PythonInterface/mantid/api/src/FitFunctions/IFunctionAdapter.cpp @@ -183,7 +183,7 @@ boost::python::object IFunctionAdapter::createPythonEquivalentFunctions(IFunction &self) { auto functions = self.createEquivalentFunctions(); boost::python::list list; - for (auto fun : functions) { + for (const auto &fun : functions) { list.append(fun); } return list; diff --git a/Framework/PythonInterface/mantid/fitfunctions.py b/Framework/PythonInterface/mantid/fitfunctions.py index 6044211b36e084f99b72b75e76cf84d0a2095cda..f059d01ad3f09375745e287cc33fd64b85f7d991 100644 --- a/Framework/PythonInterface/mantid/fitfunctions.py +++ b/Framework/PythonInterface/mantid/fitfunctions.py @@ -150,6 +150,88 @@ class FunctionWrapper(object): return output_array else: return output_array[0] + + def plot(self, **kwargs): + """ Plot the function + + :param workspace=ws: workspace upon whose x values + the function is plotted. + """ + from mantid import mtd + try: + from mantidplot import plot + except: + raise RuntimeError("mantidplot must be importable to plot functions.") + from mantid.simpleapi import CreateWorkspace + import numpy as np + + isWorkspace = False + extractSpectrum = False + workspaceIndex = 0 + haveXValues = False + haveStartX = False + haveEndX = False + nSteps = 20 + plotName = self.name + + def inRange(x): + return x >= xMin and x <= xMax + + for key in kwargs: + if key == "workspace": + isWorkspace = True + ws = kwargs[key] + if type(ws) == type('string'): + ws = mtd[ws] + if key == "workspaceIndex": + workspaceIndex = kwargs[key] + if workspaceIndex > 0: + extractSpectrum = True + if key == "xValues": + xvals = kwargs[key] + haveXValues = True + if key == "startX": + xMin = kwargs[key] + haveStartX = True + if key == "endX": + xMax = kwargs[key] + haveEndX = True + if key == "nSteps": + nSteps = kwargs[key] + if nSteps < 1: + raise RuntimeError("nSteps must be at least 1") + if key == "name": + plotName = kwargs[key] + + if haveStartX and haveEndX: + if xMin >= xMax: + raise RuntimeError("startX must be less than EndX") + + if haveXValues: + spectrumWs = self._execute_algorithm('CreateWorkspace', DataX=xvals, DataY=xvals) + elif isWorkspace: + xvals = ws.readX(workspaceIndex) + if haveStartX and haveEndX: + xvals = filter(inRange, xvals) + if extractSpectrum or (haveStartX and haveEndX): + spectrumWs = self._execute_algorithm('CreateWorkspace', DataX=xvals, DataY=xvals) + else: + spectrumWs = ws + elif haveStartX and haveEndX: + xvals = np.linspace(start=xMin, stop=xMax, num=nSteps) + spectrumWs = self._execute_algorithm('CreateWorkspace', DataX=xvals, DataY=xvals) + else: + if not haveStartX: + raise RuntimeError("startX must be defined if no workspace or xValues are defined.") + if not haveEndX: + raise RuntimeError("endX must be defined if no workspace or xValues are defined.") + else: + raise RuntimeError("insufficient plotting arguments") # Should not occur. + + outWs = self(spectrumWs) + vals = outWs.readY(1) + function = CreateWorkspace( DataX=xvals, DataY=vals, OutputWorkspace=plotName) + plot(plotName,0) def tie (self, *args, **kwargs): """ Add ties. diff --git a/Framework/PythonInterface/mantid/kernel/plugins.py b/Framework/PythonInterface/mantid/kernel/plugins.py index 27309f1d6d5c17923025fce5c39b9db2a1cf72b2..27c7b0d4b5b23655d7f6afe26f85cefd82a8fc0d 100644 --- a/Framework/PythonInterface/mantid/kernel/plugins.py +++ b/Framework/PythonInterface/mantid/kernel/plugins.py @@ -242,7 +242,8 @@ def contains_algorithm(filename): #endif alg_found = True try: - with open(filename,'r') as plugin_file: + from io import open + with open(filename,'r', encoding='UTF-8') as plugin_file: for line in readlines_reversed(plugin_file): if 'AlgorithmFactory.subscribe' in line: alg_found = True diff --git a/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp b/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp index 8216be7524b3199054dd98536f9338b84a7172d5..6f3e76a80835f67e7e7312eabc382d5a09456afb 100644 --- a/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp +++ b/Framework/PythonInterface/mantid/kernel/src/Exports/UnitLabel.cpp @@ -42,7 +42,7 @@ createLabel(const object &ascii, const object &utf8, const object &latex) { * @return A new Python unicode string with the contents of the utf8 label */ PyObject *utf8ToUnicode(UnitLabel &self) { - const auto label = self.utf8(); + const auto &label = self.utf8(); return PyUnicode_FromWideChar(label.c_str(), label.size()); } } diff --git a/Framework/PythonInterface/mantid/simpleapi.py b/Framework/PythonInterface/mantid/simpleapi.py index ec85223fa24a57c84b0cb93fc90e99117d2329e7..670e5b0484b5707255a8a7ae39368b2fff25c1fe 100644 --- a/Framework/PythonInterface/mantid/simpleapi.py +++ b/Framework/PythonInterface/mantid/simpleapi.py @@ -253,23 +253,30 @@ def StartLiveData(*args, **kwargs): """ instrument, = _get_mandatory_args('StartLiveData', ["Instrument"], *args, **kwargs) - # Create and execute + # Create algorithm (_startProgress, _endProgress, kwargs) = extract_progress_kwargs(kwargs) algm = _create_algorithm_object('StartLiveData', startProgress=_startProgress, endProgress=_endProgress) _set_logging_option(algm, kwargs) - try: - algm.setProperty('Instrument', instrument) # Must be set first - except ValueError as ve: - raise ValueError('Problem when setting Instrument. This is the detailed error ' - 'description: ' + str(ve)) - # Remove from keywords so it is not set twice - try: - del kwargs['Instrument'] - except KeyError: - pass + # Some properties have side effects and must be set separately + def handleSpecialProperty(name, value=None): + try: + if value is None: + value = kwargs[name] + algm.setProperty(name, value) + kwargs.pop(name, None) + except ValueError as ve: + raise ValueError('Problem when setting %s. This is the detailed error ' + 'description: %s' % (name, str(ve))) + except KeyError: + pass # ignore if kwargs[name] doesn't exist + + # Listener properties depend on these values, so they must be set first + handleSpecialProperty('Instrument', instrument) + handleSpecialProperty('Connection') + handleSpecialProperty('Listener') # LHS Handling currently unsupported for StartLiveData lhs = _kernel.funcinspect.lhs_info() diff --git a/Framework/PythonInterface/plugins/algorithms/Mean.py b/Framework/PythonInterface/plugins/algorithms/Mean.py index dccc362edab00a40a49578b1cefdeaecfceb94ba..081a5f1e9d4236dba03632446807563ad49b0127 100644 --- a/Framework/PythonInterface/plugins/algorithms/Mean.py +++ b/Framework/PythonInterface/plugins/algorithms/Mean.py @@ -1,5 +1,8 @@ #pylint: disable=no-init,invalid-name from __future__ import (absolute_import, division, print_function) + +import numpy + from mantid.simpleapi import * from mantid.api import * from mantid.kernel import * @@ -26,6 +29,25 @@ class Mean(PythonAlgorithm): self.declareProperty(MatrixWorkspaceProperty("OutputWorkspace", "", Direction.Output), doc="Output mean workspace") + def validateInputs(self): + issues = dict() + workspaces = self.getProperty("Workspaces").value.split(',') + name = workspaces[0].strip() + ws1 = mtd[name] + nSpectra = ws1.getNumberHistograms() + + for index in range(1, len(workspaces)): + name = workspaces[index].strip() + ws2 = mtd[name] + if not self._are_workspaces_compatible(ws1, ws2): + issues["workspaces"]="Input Workspaces are not the same shape." + # cannot run the next test if this fails + return issues + for spectra in range(0,nSpectra): + if numpy.allclose(ws1.readX(spectra) ,ws2.readX(spectra)) ==False: + issues["Workspaces"] = "The data should have the same order for x values. Sort your data first" + return issues + def _are_workspaces_compatible(self, ws_a, ws_b): sizeA = ws_a.blocksize() * ws_a.getNumberHistograms() sizeB = ws_b.blocksize() * ws_b.getNumberHistograms() @@ -38,8 +60,6 @@ class Mean(PythonAlgorithm): for index in range(1, len(workspaces)): name = workspaces[index].strip() workspace = mtd[name] - if not self._are_workspaces_compatible(out_ws, workspace): - raise RuntimeError("Input Workspaces are not the same shape.") out_ws += workspace out_ws /= len(workspaces) self.setProperty("OutputWorkspace", out_ws) diff --git a/Framework/PythonInterface/plugins/algorithms/VesuvioCorrections.py b/Framework/PythonInterface/plugins/algorithms/VesuvioCorrections.py index fe527138fce502a2d0542a18842ad90a44cb7d37..1786cc074762d246911ad05e0692c75b93840ddd 100644 --- a/Framework/PythonInterface/plugins/algorithms/VesuvioCorrections.py +++ b/Framework/PythonInterface/plugins/algorithms/VesuvioCorrections.py @@ -637,7 +637,7 @@ class VesuvioCorrections(VesuvioBase): constraint = constraints[symbol].value material = material_builder.setFormula(symbol).build() cross_section = material.totalScatterXSection() - cross_section_ratio = cross_section / hydrogen_cross_section + cross_section_ratio = hydrogen_cross_section / cross_section weight = constraint.get('weight', default_weight).value factor = constraint.get('factor', 1).value hydrogen_intensity += cross_section_ratio * factor * weight * constraint['intensity'].value diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/AddSampleLogMultiple.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/AddSampleLogMultiple.py index 3627a2f48fafd5b40f46d4efef70d9023e45c9a1..d523aabcc4c379cef205751e5e1c556cda5f5018 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/AddSampleLogMultiple.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/AddSampleLogMultiple.py @@ -31,7 +31,7 @@ class AddSampleLogMultiple(PythonAlgorithm): doc='Determine the value type by parsing the string') def PyExec(self): - workspace = self.getPropertyValue('Workspace') + workspace = self.getProperty('Workspace').value log_names = self.getProperty('LogNames').value log_values = self.getProperty('LogValues').value log_units = self.getProperty('LogUnits').value diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorption.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorption.py new file mode 100644 index 0000000000000000000000000000000000000000..17ec442290c0e408c568bac93f262462893ac9f3 --- /dev/null +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorption.py @@ -0,0 +1,792 @@ +from __future__ import (absolute_import, division, print_function) + +from mantid.api import (DataProcessorAlgorithm, AlgorithmFactory, PropertyMode, WorkspaceGroupProperty, + Progress, mtd, SpectraAxis, WorkspaceGroup, WorkspaceProperty) +from mantid.kernel import (VisibleWhenProperty, PropertyCriterion, StringListValidator, IntBoundedValidator, + FloatBoundedValidator, Direction, logger, LogicOperator, config) + +import math +import numpy as np +import os.path + + +class CalculateMonteCarloAbsorption(DataProcessorAlgorithm): + # General variables + _emode = None + _efixed = None + _general_kwargs = None + _shape = None + _height = None + + # Sample variables + _sample_angle = None + _sample_center = None + _sample_chemical_formula = None + _sample_density = None + _sample_density_type = None + _sample_inner_radius = None + _sample_outer_radius = None + _sample_radius = None + _sample_thickness = None + _sample_unit = None + _sample_width = None + _sample_ws = None + + # Container variables + _container_angle = None + _container_center = None + _container_chemical_formula = None + _container_density = None + _container_density_type = None + _container_inner_radius = None + _container_outer_radius = None + _container_thickness = None + _container_width = None + + # Output workspaces + _ass_ws = None + _acc_ws = None + _output_ws = None + + def category(self): + return "Workflow\\Inelastic;CorrectionFunctions\\AbsorptionCorrections;Workflow\\MIDAS" + + def summary(self): + return "Calculates indirect absorption corrections for a given sample shape, using a MonteCarlo simulation." + + def checkGroups(self): + return False + + def PyInit(self): + # Sample options + self.declareProperty(WorkspaceProperty('SampleWorkspace', '', direction=Direction.Input), + doc='Sample Workspace') + self.declareProperty(name='SampleChemicalFormula', defaultValue='', + doc='Chemical formula for the sample material') + self.declareProperty(name='SampleDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Sample density type') + self.declareProperty(name='SampleDensity', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Sample density') + + self.setPropertyGroup('SampleWorkspace', 'Sample Options') + self.setPropertyGroup('SampleChemicalFormula', 'Sample Options') + self.setPropertyGroup('SampleDensityType', 'Sample Options') + self.setPropertyGroup('SampleDensity', 'Sample Options') + + # Beam Options + self.declareProperty(name='BeamHeight', defaultValue=1.0, + validator=FloatBoundedValidator(0.0), + doc='Height of the beam (cm)') + self.declareProperty(name='BeamWidth', defaultValue=1.0, + validator=FloatBoundedValidator(0.0), + doc='Width of the beam (cm)') + + self.setPropertyGroup('BeamHeight', 'Beam Options') + self.setPropertyGroup('BeamWidth', 'Beam Options') + + # Monte Carlo options + self.declareProperty(name='NumberOfWavelengthPoints', defaultValue=10, + validator=IntBoundedValidator(1), + doc='Number of wavelengths for calculation') + self.declareProperty(name='EventsPerPoint', defaultValue=1000, + validator=IntBoundedValidator(0), + doc='Number of neutron events') + self.declareProperty(name='Interpolation', defaultValue='Linear', + validator=StringListValidator( + ['Linear', 'CSpline']), + doc='Type of interpolation') + + self.setPropertyGroup('NumberOfWavelengthPoints', 'Monte Carlo Options') + self.setPropertyGroup('EventsPerPoint', 'Monte Carlo Options') + self.setPropertyGroup('Interpolation', 'Monte Carlo Options') + + # Container options + self.declareProperty(WorkspaceProperty('ContainerWorkspace', '', direction=Direction.Input, + optional=PropertyMode.Optional), + doc='Container Workspace') + + container_condition = VisibleWhenProperty('ContainerWorkspace', PropertyCriterion.IsNotDefault) + + self.declareProperty(name='ContainerChemicalFormula', defaultValue='', + doc='Chemical formula for the container material') + self.declareProperty(name='ContainerDensityType', defaultValue='Mass Density', + validator=StringListValidator(['Mass Density', 'Number Density']), + doc='Container density type') + self.declareProperty(name='ContainerDensity', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Container density') + + self.setPropertyGroup('ContainerWorkspace', 'Container Options') + self.setPropertyGroup('ContainerChemicalFormula', 'Container Options') + self.setPropertyGroup('ContainerDensityType', 'Container Options') + self.setPropertyGroup('ContainerDensity', 'Container Options') + + self.setPropertySettings('ContainerChemicalFormula', container_condition) + self.setPropertySettings('ContainerDensityType', container_condition) + self.setPropertySettings('ContainerDensity', container_condition) + + # Shape options + self.declareProperty(name='Shape', defaultValue='FlatPlate', + validator=StringListValidator(['FlatPlate', 'Cylinder', 'Annulus']), + doc='Geometric shape of the sample environment') + + flat_plate_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'FlatPlate') + cylinder_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Cylinder') + annulus_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Annulus') + + # height is common to all, and should be the same for sample and container + self.declareProperty('Height', defaultValue=0.0, validator=FloatBoundedValidator(0.0), + doc='Height of the sample environment (cm)') + + self.setPropertyGroup('Shape', 'Shape Options') + self.setPropertyGroup('Height', 'Shape Options') + + # ---------------------------Sample--------------------------- + # Flat Plate + self.declareProperty(name='SampleWidth', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Width of the sample environment (cm)') + self.declareProperty(name='SampleThickness', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Thickness of the sample environment (cm)') + self.declareProperty(name='SampleCenter', defaultValue=0.0, + doc='Center of the sample environment') + self.declareProperty(name='SampleAngle', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Angle of the sample environment with respect to the beam (degrees)') + + self.setPropertySettings('SampleWidth', flat_plate_condition) + self.setPropertySettings('SampleThickness', flat_plate_condition) + self.setPropertySettings('SampleCenter', flat_plate_condition) + self.setPropertySettings('SampleAngle', flat_plate_condition) + + self.setPropertyGroup('SampleWidth', 'Sample Shape Options') + self.setPropertyGroup('SampleThickness', 'Sample Shape Options') + self.setPropertyGroup('SampleCenter', 'Sample Shape Options') + self.setPropertyGroup('SampleAngle', 'Sample Shape Options') + + # Cylinder + self.declareProperty(name='SampleRadius', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Radius of the sample environment (cm)') + + self.setPropertySettings('SampleRadius', cylinder_condition) + self.setPropertyGroup('SampleRadius', 'Sample Shape Options') + + # Annulus + self.declareProperty(name='SampleInnerRadius', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Inner radius of the sample environment (cm)') + self.declareProperty(name='SampleOuterRadius', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Outer radius of the sample environment (cm)') + + self.setPropertySettings('SampleInnerRadius', annulus_condition) + self.setPropertySettings('SampleOuterRadius', annulus_condition) + + self.setPropertyGroup('SampleInnerRadius', 'Sample Shape Options') + self.setPropertyGroup('SampleOuterRadius', 'Sample Shape Options') + + # ---------------------------Container--------------------------- + # Flat Plate + self.declareProperty(name='ContainerFrontThickness', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Front thickness of the container environment (cm)') + self.declareProperty(name='ContainerBackThickness', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Back thickness of the container environment (cm)') + + container_flat_plate_condition = VisibleWhenProperty(container_condition, flat_plate_condition, + LogicOperator.And) + + self.setPropertySettings('ContainerFrontThickness', container_flat_plate_condition) + self.setPropertySettings('ContainerBackThickness', container_flat_plate_condition) + + self.setPropertyGroup('ContainerFrontThickness', 'Container Shape Options') + self.setPropertyGroup('ContainerBackThickness', 'Container Shape Options') + + # Both cylinder and annulus have an annulus container + + not_flat_plate_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsNotEqualTo, 'FlatPlate') + + container_n_f_p_condition = VisibleWhenProperty(container_condition, not_flat_plate_condition, + LogicOperator.And) + + self.declareProperty(name='ContainerInnerRadius', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Inner radius of the container environment (cm)') + self.declareProperty(name='ContainerOuterRadius', defaultValue=0.0, + validator=FloatBoundedValidator(0.0), + doc='Outer radius of the container environment (cm)') + + self.setPropertySettings('ContainerInnerRadius', container_n_f_p_condition) + self.setPropertySettings('ContainerOuterRadius', container_n_f_p_condition) + + self.setPropertyGroup('ContainerInnerRadius', 'Container Shape Options') + self.setPropertyGroup('ContainerOuterRadius', 'Container Shape Options') + + # output + self.declareProperty(WorkspaceGroupProperty(name='CorrectionsWorkspace', + defaultValue='corrections', + direction=Direction.Output, + optional=PropertyMode.Optional), + doc='Name of the workspace group to save correction factors') + self.setPropertyGroup('CorrectionsWorkspace', 'Output Options') + + def PyExec(self): + + # set up progress reporting + prog = Progress(self, 0, 1, 10) + + prog.report('Converting to wavelength') + sample_wave_ws = self._convert_to_wavelength(self._sample_ws) + + prog.report('Calculating sample absorption factors') + + sample_kwargs = dict() + sample_kwargs.update(self._general_kwargs) + sample_kwargs['ChemicalFormula'] = self._sample_chemical_formula + sample_kwargs['DensityType'] = self._sample_density_type + sample_kwargs['Density'] = self._sample_density + sample_kwargs['Height'] = self._height + sample_kwargs['Shape'] = self._shape + + if self._shape == 'FlatPlate': + sample_kwargs['Width'] = self._sample_width + sample_kwargs['Thickness'] = self._sample_thickness + sample_kwargs['Angle'] = self._sample_angle + sample_kwargs['Center'] = self._sample_center + + if self._shape == 'Cylinder': + sample_kwargs['Radius'] = self._sample_radius + + if self._shape == 'Annulus': + sample_kwargs['InnerRadius'] = self._sample_inner_radius + sample_kwargs['OuterRadius'] = self._sample_outer_radius + + ss_monte_carlo_alg = self.createChildAlgorithm("SimpleShapeMonteCarloAbsorption", enableLogging=True) + ss_monte_carlo_alg.setProperty("InputWorkspace", sample_wave_ws) + self._set_algorithm_properties(ss_monte_carlo_alg, sample_kwargs) + ss_monte_carlo_alg.execute() + ass_ws = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + sample_log_names = [] + sample_log_values = [] + + for log_name, log_value in sample_kwargs.items(): + sample_log_names.append("sample_" + log_name.lower()) + sample_log_values.append(log_value) + + ass_ws = self._convert_from_wavelength(ass_ws) + self._add_sample_log_multiple(ass_ws, sample_log_names, sample_log_values) + + if not self.isChild(): + mtd.addOrReplace(self._ass_ws_name, ass_ws) + + if self._container_ws: + prog.report('Calculating container absorption factors') + + container_wave_1 = self._convert_to_wavelength(self._container_ws) + container_wave_2 = self._clone_ws(container_wave_1) + + container_kwargs = dict() + container_kwargs.update(self._general_kwargs) + container_kwargs['ChemicalFormula'] = self._container_chemical_formula + container_kwargs['DensityType'] = self._container_density_type + container_kwargs['Density'] = self._container_density + container_kwargs['Height'] = self._height + container_kwargs['Shape'] = self._shape + self._set_algorithm_properties(ss_monte_carlo_alg, container_kwargs) + + if self._shape == 'FlatPlate': + offset_front = 0.5 * (self._container_front_thickness + self._sample_thickness) + ss_monte_carlo_alg.setProperty("InputWorkspace", container_wave_1) + ss_monte_carlo_alg.setProperty("Width", self._sample_width) + ss_monte_carlo_alg.setProperty("Angle", self._sample_angle) + ss_monte_carlo_alg.setProperty("Thickness", self._container_front_thickness) + ss_monte_carlo_alg.setProperty("Center", -offset_front) + ss_monte_carlo_alg.execute() + acc_1 = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + offset_back = 0.5 * (self._container_back_thickness + self._sample_thickness) + ss_monte_carlo_alg.setProperty("InputWorkspace", container_wave_2) + ss_monte_carlo_alg.setProperty("Thickness", self._container_back_thickness) + ss_monte_carlo_alg.setProperty("Center", offset_back) + ss_monte_carlo_alg.execute() + acc_2 = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + acc_ws = self._multiply(acc_1, acc_2) + + elif self._shape == 'Cylinder': + ss_monte_carlo_alg.setProperty("InputWorkspace", container_wave_1) + ss_monte_carlo_alg.setProperty("InnerRadius", self._container_inner_radius) + ss_monte_carlo_alg.setProperty("OuterRadius", self._container_outer_radius) + ss_monte_carlo_alg.setProperty("Shape", "Annulus") + ss_monte_carlo_alg.execute() + acc_ws = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + elif self._shape == 'Annulus': + ss_monte_carlo_alg.setProperty("InputWorkspace", container_wave_1) + ss_monte_carlo_alg.setProperty("InnerRadius", self._container_inner_radius) + ss_monte_carlo_alg.setProperty("OuterRadius", self._container_outer_radius) + ss_monte_carlo_alg.execute() + acc_1 = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + ss_monte_carlo_alg.setProperty("InputWorkspace", container_wave_2) + ss_monte_carlo_alg.execute() + acc_2 = ss_monte_carlo_alg.getProperty("OutputWorkspace").value + + acc_ws = self._multiply(acc_1, acc_2) + + for log_name, log_value in container_kwargs.items(): + sample_log_names.append("container_" + log_name.lower()) + sample_log_values.append(log_value) + + acc_ws = self._convert_from_wavelength(acc_ws) + + self._add_sample_log_multiple(acc_ws, sample_log_names, sample_log_values) + + if not self.isChild(): + mtd.addOrReplace(self._acc_ws_name, acc_ws) + + self._output_ws = self._group_ws([ass_ws, acc_ws]) + else: + self._output_ws = self._group_ws([ass_ws]) + + self.setProperty('CorrectionsWorkspace', self._output_ws) + + def _setup(self): + + # The beam properties and monte carlo properties are simply passed straight on to the + # SimpleShapeMonteCarloAbsorptionCorrection algorithm so they are being put into + # a dictionary for simplicity + self._sample_ws = self.getProperty("SampleWorkspace").value + self._container_ws = self.getProperty("ContainerWorkspace").value + sample_is_group = isinstance(self._sample_ws, WorkspaceGroup) + container_is_group = isinstance(self._container_ws, WorkspaceGroup) + + # Currently we cannot support workspace groups because the output of the child + # algorithm is a workspace group. This causes a crash in the ADS when this + # algorithm attempts to put a workspace group into another workspace group + if sample_is_group or container_is_group: + raise RuntimeError("CalculateMonteCarloAbsorption does not currently support" + " WorkspaceGroups") + + self._general_kwargs = {'BeamHeight': self.getProperty('BeamHeight').value, + 'BeamWidth': self.getProperty('BeamWidth').value, + 'NumberOfWavelengthPoints': self.getProperty('NumberOfWavelengthPoints').value, + 'EventsPerPoint': self.getProperty('EventsPerPoint').value, + 'Interpolation': self.getProperty('Interpolation').value} + + self._shape = self.getProperty('Shape').value + self._height = self.getProperty('Height').value + + self._sample_unit = self._sample_ws.getAxis(0).getUnit().unitID() + logger.information('Input X-unit is {}'.format(self._sample_unit)) + if self._sample_unit == 'dSpacing': + self._emode = 'Elastic' + else: + self._emode = str(self._sample_ws.getEMode()) + if self._emode == 'Indirect' or 'Direct': + self._efixed = self._get_efixed() + + self._sample_chemical_formula = self.getPropertyValue('SampleChemicalFormula') + self._sample_density_type = self.getPropertyValue('SampleDensityType') + self._sample_density = self.getProperty('SampleDensity').value + + if self._container_ws: + self._container_chemical_formula = self.getPropertyValue('ContainerChemicalFormula') + self._container_density_type = self.getPropertyValue('ContainerDensityType') + self._container_density = self.getProperty('ContainerDensity').value + + if self._shape == 'FlatPlate': + self._sample_width = self.getProperty('SampleWidth').value + self._sample_thickness = self.getProperty('SampleThickness').value + self._sample_angle = self.getProperty('SampleAngle').value + self._sample_center = self.getProperty('SampleCenter').value + + if self._shape == 'Cylinder': + self._sample_radius = self.getProperty('SampleRadius').value + + if self._shape == 'Annulus': + self._sample_inner_radius = self.getProperty('SampleInnerRadius').value + self._sample_outer_radius = self.getProperty('SampleOuterRadius').value + + if self._container_ws: + if self._shape == 'FlatPlate': + self._container_front_thickness = self.getProperty('ContainerFrontThickness').value + self._container_back_thickness = self.getProperty('ContainerBackThickness').value + + else: + self._container_inner_radius = self.getProperty('ContainerInnerRadius').value + self._container_outer_radius = self.getProperty('ContainerOuterRadius').value + + self._output_ws = self.getProperty('CorrectionsWorkspace').value + output_ws_name = self.getPropertyValue('CorrectionsWorkspace') + self._ass_ws_name = output_ws_name + "_ass" + self._acc_ws_name = output_ws_name + "_acc" + self._transposed = False + self._indirect_elastic = False + + def validateInputs(self): + issues = dict() + + try: + self._setup() + except Exception as err: + issues['SampleWorkspace'] = str(err) + + if self._shape == 'Annulus': + if self._sample_inner_radius >= self._sample_outer_radius: + issues['SampleOuterRadius'] = 'Must be greater than SampleInnerRadius (' \ + + str(self._sample_inner_radius) + "). Current value " \ + + str(self._sample_outer_radius) + + if self._container_ws: + container_unit = self._container_ws.getAxis(0).getUnit().unitID() + if container_unit != self._sample_unit: + raise ValueError('Sample and Container units must be the same!') + + if self._shape == 'Cylinder': + if self._container_inner_radius <= self._sample_radius: + issues['ContainerInnerRadius'] = 'Must be greater than SampleRadius' + if self._container_outer_radius <= self._container_inner_radius: + issues['ContainerOuterRadius'] = 'Must be greater than ContainerInnerRadius' + + if self._shape == 'Annulus': + if self._container_inner_radius >= self._sample_inner_radius: + issues['ContainerInnerRadius'] = 'Must be less than SampleInnerRadius' + if self._container_outer_radius <= self._sample_outer_radius: + issues['ContainerOuterRadius'] = 'Must be greater than SampleOuterRadius' + + return issues + + def _get_efixed(self): + """ + Returns the efixed value relating to the specified workspace + """ + inst = self._sample_ws.getInstrument() + + if inst.hasParameter('Efixed'): + return inst.getNumberParameter('Efixed')[0] + + if inst.hasParameter('analyser'): + analyser_comp = inst.getComponentByName(inst.getStringParameter('analyser')[0]) + + if analyser_comp is not None and analyser_comp.hasParameter('Efixed'): + return analyser_comp.getNumberParameter('EFixed')[0] + + raise ValueError('No Efixed parameter found') + + # ------------------------------- Converting to/from wavelength ------------------------------- + + def _convert_to_wavelength(self, workspace): + """ + Converts the specified workspace to units of wavelength. + + :param workspace: The workspace to convert. + :return: + """ + + x_unit = workspace.getAxis(0).getUnit().unitID() + y_unit = workspace.getAxis(1).getUnit().unitID() + + # ----- Quick Conversions (Wavelength and DeltaE) ----- + + if x_unit == 'Wavelength': + return self._clone_ws(workspace) + elif y_unit == 'Wavelength': + self._transposed = True + return self._tranpose_ws(workspace) + elif x_unit == 'DeltaE': + return self._convert_units(workspace, "Wavelength", self._emode, self._efixed) + elif y_unit == 'DeltaE': + self._transposed = True + workspace = self._tranpose_ws(workspace) + return self._convert_units(workspace, "Wavelength", self._emode, self._efixed) + + # ----- Indirect Elastic Conversions ----- + + if self._emode == "Indirect": + + if x_unit == 'MomentumTransfer': + self._transposed = True + return self._create_waves_indirect_elastic(self._tranpose_ws(workspace)) + else: + return self._create_waves_indirect_elastic(self._clone_ws(workspace)) + + # ----- Direct Conversions ----- + + return self._convert_units(workspace, "Wavelength", self._emode) + + def _convert_from_wavelength(self, workspace): + """ + Converts the specified workspace into units of wavelength. + + :param workspace: The workspace whose units to convert. + :return: A workspace with units of wavelength, created from + converting the specified workspace. + """ + + if self._transposed: + workspace = self._tranpose_ws(workspace) + + if self._indirect_elastic: + return self._convert_units(workspace, "MomentumTransfer", self._emode, self._efixed) + elif self._emode == "Indirect": + return self._convert_units(workspace, self._sample_unit, self._emode, self._efixed) + elif self._sample_unit != 'Wavelength': + return self._convert_units(workspace, self._sample_unit, self._emode) + else: + return workspace + + # ------------------------------- Converting IndirectElastic to wavelength ------------------------------ + + def _create_waves_indirect_elastic(self, workspace): + """ + Creates a wavelength workspace, from the workspace with the specified input workspace + name, using an Elastic instrument definition file. E-Mode must be Indirect and the y-axis + of the input workspace must be in units of Q. + + :param workspace: The input workspace. + :return: The output wavelength workspace. + """ + self._indirect_elastic = True + self._q_values = workspace.getAxis(1).extractValues() + instrument_name = workspace.getInstrument().getName() + isis_instrument = instrument_name == "IRIS" or instrument_name == "OSIRIS" + + # ---------- Load Elastic Instrument Definition File ---------- + + if isis_instrument: + idf_name = instrument_name + '_elastic_Definition.xml' + + idf_path = os.path.join(config.getInstrumentDirectory(), idf_name) + logger.information('IDF = %s' % idf_path) + + load_alg = self.createChildAlgorithm("LoadInstrument", enableLogging=True) + load_alg.setProperty("Workspace", workspace) + load_alg.setProperty("Filename", idf_path) + load_alg.setProperty("RewriteSpectraMap", True) + load_alg.execute() + + # ---------- Create Spectra Axis ----------- + + # Replace y-axis with spectra axis + workspace.replaceAxis(1, SpectraAxis.create(workspace)) + e_fixed = float(self._efixed) + logger.information('Efixed = %f' % e_fixed) + + # ---------- Set Instrument Parameters ---------- + + sip_alg = self.createChildAlgorithm("SetInstrumentParameter", enableLogging=False) + sip_alg.setProperty("Workspace", workspace) + sip_alg.setProperty("ParameterName", 'EFixed') + sip_alg.setProperty("ParameterType", 'Number') + sip_alg.setProperty("Value", str(e_fixed)) + sip_alg.execute() + + # ---------- Calculate Wavelength ---------- + + wave = math.sqrt(81.787 / e_fixed) + logger.information('Wavelength = %f' % wave) + workspace.getAxis(0).setUnit('Wavelength') + + # ---------- Format Input Workspace --------- + + convert_alg = self.createChildAlgorithm("ConvertToHistogram", enableLogging=False) + convert_alg.setProperty("InputWorkspace", workspace) + convert_alg.execute() + + workspace = self._crop_ws(convert_alg.getProperty("OutputWorkspace").value) + + # --------- Set wavelengths as X-values in Output Workspace ---------- + + waves = (0.01 * np.arange(-1, workspace.blocksize())) + wave + logger.information('Waves : ' + str(waves)) + nhist = workspace.getNumberHistograms() + for idx in range(nhist): + workspace.setX(idx, waves) + + if isis_instrument: + self._update_instrument_angles(workspace, self._q_values, wave) + + return workspace + + def _update_instrument_angles(self, workspace, q_values, wave): + """ + Updates the instrument angles in the specified workspace, using the specified wavelength + and the specified Q-Values. This is required when calculating absorption corrections for + indirect elastic. + + :param workspace: The workspace whose instrument angles to update. + :param q_values: The extracted Q-Values (MomentumTransfer) + :param wave: The wavelength + """ + work_dir = config['defaultsave.directory'] + k0 = 4.0 * math.pi / wave + theta = 2.0 * np.degrees(np.arcsin(q_values / k0)) # convert to angle + + filename = 'Elastic_angles.txt' + path = os.path.join(work_dir, filename) + logger.information('Creating angles file : ' + path) + handle = open(path, 'w') + head = 'spectrum,theta' + handle.write(head + " \n") + for n in range(0, len(theta)): + handle.write(str(n + 1) + ' ' + str(theta[n]) + "\n") + handle.close() + + update_alg = self.createChildAlgorithm("UpdateInstrumentFromFile", enableLogging=False) + update_alg.setProperty("Workspace", workspace) + update_alg.setProperty("Filename", path) + update_alg.setProperty("MoveMonitors", False) + update_alg.setProperty("IgnorePhi", True) + update_alg.setProperty("AsciiHeader", head) + update_alg.setProperty("SkipFirstNLines", 1) + + def _crop_ws(self, workspace): + """ + Crops the specified workspace to the XMin and XMax values specified in + it's first and last X-Values. + + :param workspace: The workspace to crop. + :return: The cropped workspace. + """ + x = workspace.dataX(0) + xmin = x[0] + xmax = x[1] + crop_alg = self.createChildAlgorithm("CropWorkspace", enableLogging=False) + crop_alg.setProperty("InputWorkspace", workspace) + crop_alg.setProperty("XMin", xmin) + crop_alg.setProperty("XMax", xmax) + crop_alg.execute() + return crop_alg.getProperty("OutputWorkspace").value + + # ------------------------------- Child algorithms ------------------------------- + + def _clone_ws(self, input_ws): + """ + Clones the specified input workspace. + + :param input_ws: The workspace to clone. + :return: A clone of the specified workspace. + """ + clone_alg = self.createChildAlgorithm("CloneWorkspace", enableLogging=False) + clone_alg.setProperty("InputWorkspace", input_ws) + clone_alg.execute() + return clone_alg.getProperty("OutputWorkspace").value + + def _multiply(self, lhs_ws, rhs_ws): + """ + Multiplies the specified workspaces together. + + :param lhs_ws: The left hand workspace multiplicand. + :param rhs_ws: The right hand workspace multiplicand. + :return: The product of the specified workspaces. + """ + multiply_alg = self.createChildAlgorithm("Multiply", enableLogging=False) + multiply_alg.setProperty("LHSWorkspace", lhs_ws) + multiply_alg.setProperty("RHSWorkspace", rhs_ws) + multiply_alg.execute() + return multiply_alg.getProperty('OutputWorkspace').value + + def _group_ws(self, workspaces): + """ + Groups the specified input workspaces. + + :param input_ws: A list of the workspaces to group together. + :return: A WorkspaceGroup containing the specified workspaces. + """ + group_alg = self.createChildAlgorithm("GroupWorkspaces", enableLogging=False) + group_alg.setProperty("InputWorkspaces", workspaces) + group_alg.execute() + return group_alg.getProperty("OutputWorkspace").value + + def _add_sample_log_multiple(self, input_ws, log_names, log_values): + """ + Adds sample logs to the specified input workspace using the specified + log names and values. + + :param input_ws: The workspace to add sample logs to. + :param log_names: The names of each sample log to add (ordered). + :param log_values: The values of each sample log to add (ordered). + """ + sample_log_mult_alg = self.createChildAlgorithm("AddSampleLogMultiple", enableLogging=False) + sample_log_mult_alg.setProperty("Workspace", input_ws) + sample_log_mult_alg.setProperty("LogNames", log_names) + sample_log_mult_alg.setProperty("LogValues", log_values) + sample_log_mult_alg.execute() + + def _convert_units(self, workspace, target_unit, emode, efixed=None): + """ + Converts the units of the specified workspace to the target unit, given + the specified EMode, and potentially EFixed value. + + :param workspace: The workspace whose units to convert. + :param target_unit: The unit to convert to. + :param emode: The EMode to use in conversion. + :param efixed: The EFixed value to use in conversion. + :return: A workspace created from converting the units of the + specified workspace to the specified target unit. + """ + convert_units_alg = self.createChildAlgorithm("ConvertUnits", enableLogging=False) + convert_units_alg.setProperty("InputWorkspace", workspace) + convert_units_alg.setProperty("Target", target_unit) + convert_units_alg.setProperty("EMode", emode) + # Check if EFixed was defined + if efixed is not None: + convert_units_alg.setProperty("EFixed", efixed) + convert_units_alg.execute() + return convert_units_alg.getProperty("OutputWorkspace").value + + def _convert_spectra_axis(self, workspace, target, emode, efixed): + """ + Convert the units of the spectra axis of the specified workspace to the + specified target unit, given the specified EMode and EFixed value. + + :param workspace: The workspace whose spectra axis to convert. + :param target: The target unit to convert to. + :param emode: The EMode to use in conversion. + :param efixed: The EFixed value to use in conversion. + :return: A workspace created from converting the units of the + spectra axis of the specified workspace to the specified + target unit. + """ + convert_axis_alg = self.createChildAlgorithm("ConvertSpectraAxis", enableLogging=False) + convert_axis_alg.setProperty("InputWorkspace", workspace) + convert_axis_alg.setProperty("EMode", emode) + convert_axis_alg.setProperty("Target", target) + convert_axis_alg.setProperty("EFixed", efixed) + convert_axis_alg.execute() + return convert_axis_alg.getProperty("OutputWorkspace").value + + def _tranpose_ws(self, workspace): + """ + Tranposes the specified workspace. + + :param workspace: The workspace to transpose. + :return: The transpose of the specified workspace. + """ + transpose_alg = self.createChildAlgorithm("Transpose", enableLogging=False) + transpose_alg.setProperty("InputWorkspace", workspace) + transpose_alg.execute() + return transpose_alg.getProperty("OutputWorkspace").value + + # ------------------------------- Utility algorithms ------------------------------- + def _set_algorithm_properties(self, algorithm, properties): + """ + Sets the specified algorithm's properties using the given properties. + + :param algorithm: The algorithm whose properties to set. + :param properties: The dictionary of properties to set. + """ + + for key, value in properties.items(): + algorithm.setProperty(key, value) + + +# Register algorithm with Mantid +AlgorithmFactory.subscribe(CalculateMonteCarloAbsorption) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py index ed43c0914ff6ca57cb2cbf26fa7d0fed2d684320..341cfc023723feace923469d5530e72f8491c005 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/HFIRSANSReduction.py @@ -95,7 +95,7 @@ class HFIRSANSReduction(PythonAlgorithm): self.default_output_dir = head return output_str - def PyExec(self): + def PyExec(self): # noqa: C901 filename = self.getProperty("Filename").value output_ws = self.getPropertyValue("OutputWorkspace") #output_ws = '__'+output_ws+'_reduced' diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py index 004a3881328b716048b6cddb53e2aa21692fc316..a8ddf10abd57d56257bb68e6937f0df8c2df48d1 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReduction.py @@ -1,6 +1,7 @@ from __future__ import (absolute_import, division, print_function) import itertools +from six import iteritems from IndirectReductionCommon import load_files @@ -159,6 +160,13 @@ class DRangeToWorkspaceMap(object): """ return d_range in self._map + def __str__(self): + str_output = "{\n" + + for d_range, workspaces in self._map.items(): + str_output += str(d_range) + ": " + str(workspaces) + "\n" + return str_output + "}" + def average_ws_list(ws_list): """ @@ -169,31 +177,54 @@ def average_ws_list(ws_list): :return: The name of the workspace containing the average. """ # Assert we have some ws in the list, and if there is only one then return it. - if len(ws_list) == 0: + num_workspaces = len(ws_list) + + if num_workspaces == 0: raise RuntimeError("getAverageWs: Trying to take an average of nothing") - if len(ws_list) == 1: + if num_workspaces == 1: return ws_list[0] - return sum(ws_list) / len(ws_list) - - -def find_intersection_of_ranges(rangeA, rangeB): - if rangeA[0] >= rangeA[1] or rangeB[0] >= rangeB[1]: + def do_binary_op(name, operands): + alg = AlgorithmManager.createUnmanaged(name) + alg.initialize() + alg.setChild(True) + for prop_name, value in iteritems(operands): + alg.setProperty(prop_name, value) + alg.setProperty("OutputWorkspace", "__unused__") + alg.execute() + return alg.getProperty('OutputWorkspace').value + + def local_sum(operand_list): + total = operand_list[0] + for j in range(1, num_workspaces): + operands = {"LHSWorkspace": total, + "RHSWorkspace": operand_list[j]} + total = do_binary_op("Plus", operands) + return total + + inputs = {"InputWorkspace": local_sum(ws_list), + "Factor": 1. / float(num_workspaces), + "Operation": "Multiply"} + return do_binary_op("Scale", inputs) + + +def find_intersection_of_ranges(range_a, range_b): + if range_a[0] >= range_a[1] or range_b[0] >= range_b[1]: raise RuntimeError("Malformed range") - if rangeA[0] <= rangeA[1] <= rangeB[0] <= rangeB[1]: + if range_a[0] <= range_a[1] <= range_b[0] <= range_b[1]: return - if rangeB[0] <= rangeB[1] <= rangeA[0] <= rangeA[1]: + if range_b[0] <= range_b[1] <= range_a[0] <= range_a[1]: return - if rangeA[0] <= rangeB[0] <= rangeB[1] <= rangeA[1]: - return rangeB - if rangeB[0] <= rangeA[0] <= rangeA[1] <= rangeB[1]: - return rangeA - if rangeA[0] <= rangeB[0] <= rangeA[1] <= rangeB[1]: - return [rangeB[0], rangeA[1]] - if rangeB[0] <= rangeA[0] <= rangeB[1] <= rangeA[1]: - return [rangeA[0], rangeB[1]] + if range_a[0] <= range_b[0] <= range_b[1] <= range_a[1]: + return range_b + if range_b[0] <= range_a[0] <= range_a[1] <= range_b[1]: + return range_a + if range_a[0] <= range_b[0] <= range_a[1] <= range_b[1]: + return [range_b[0], range_a[1]] + if range_b[0] <= range_a[0] <= range_b[1] <= range_a[1]: + return [range_a[0], range_b[1]] # Should never reach here raise RuntimeError() @@ -379,18 +410,26 @@ class OSIRISDiffractionReduction(PythonAlgorithm): self._man_d_range = None if not self.getProperty("DetectDRange").value: - self._man_d_range = self.getProperty("DRange").value + self._man_d_range = self._parse_string_array(self.getProperty("DRange").value) + self._man_d_range = [x - 1 for x in self._man_d_range] + num_ranges = len(self._man_d_range) + num_runs = len(self._sample_runs) + + if num_runs % num_ranges == 0: + self._man_d_range = list(self._man_d_range * int(num_runs / num_ranges)) + elif num_runs != num_ranges: + raise ValueError("Less D-Ranges supplied than Sample Runs. Expected " + str(num_runs) + + ", Received " + str(num_ranges) + ".") def validateInputs(self): - self._get_properties() issues = dict() - if self._man_d_range is not None: - try: - self._man_d_range = self._parse_string_array(self._man_d_range) - self._man_d_range = [x - 1 for x in self._man_d_range] - except BaseException as exc: - issues['DRange'] = str(exc) + try: + self._get_properties() + except ValueError as exc: + issues['DRange'] = str(exc) + except RuntimeError as exc: + issues['Sample'] = str(exc) num_samples = len(self._sample_runs) num_vanadium = len(self._vanadium_runs) @@ -584,7 +623,6 @@ class OSIRISDiffractionReduction(PythonAlgorithm): mtd.addOrReplace(sample_ws_name, sample_ws) if len(divided) > 1: - # Merge the sample files into one. merge_runs_alg = self.createChildAlgorithm("MergeRuns", enableLogging=False) merge_runs_alg.setProperty("InputWorkspaces", sample_ws_names) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py index d726339dcfe501f8b53b6a3e106ecb37ba7642dd..f62feba05cd0a8175c4f28095fa6fd02c5d07ddc 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSBeamSpreaderTransmission.py @@ -60,8 +60,7 @@ class SANSBeamSpreaderTransmission(PythonAlgorithm): self.declareProperty("OutputMessage", "", direction=Direction.Output, doc = "Output message") - #pylint: disable=too-many-locals,too-many-branches - def PyExec(self): + def PyExec(self): # noqa: C901 # Get the reduction property manager property_manager_name = self.getProperty("ReductionProperties").value property_manager = PropertyManagerDataService.retrieve(property_manager_name) diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py index 80c8320c6ccbb51fb33a6d3400e5f98e030bfdb6..7a3be835da5a124d52af8b218ddb1520dd26512c 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SANSReduction.py @@ -85,8 +85,7 @@ class SANSReduction(PythonAlgorithm): output_str += self._load_data(data_file, workspace, property_manager, property_manager_name) return output_str - #pylint: disable=too-many-locals,too-many-branches - def _py_exec(self): + def _py_exec(self): # noqa: C901 filename = self.getProperty("Filename").value output_ws = self.getPropertyValue("OutputWorkspace") property_manager_name = self.getProperty("ReductionProperties").value diff --git a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SimpleShapeMonteCarloAbsorption.py b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SimpleShapeMonteCarloAbsorption.py index 2a312eb68a8004e6b34fab3f249f75e0418ab81a..2abf5198c05ebaaffd583e336188bd9ac85d5d28 100644 --- a/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SimpleShapeMonteCarloAbsorption.py +++ b/Framework/PythonInterface/plugins/algorithms/WorkflowAlgorithms/SimpleShapeMonteCarloAbsorption.py @@ -1,7 +1,6 @@ from __future__ import (absolute_import, division, print_function) -from mantid.simpleapi import SetBeam, SetSample, MonteCarloAbsorption -from mantid.api import DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, Progress +from mantid.api import (DataProcessorAlgorithm, AlgorithmFactory, MatrixWorkspaceProperty, Progress) from mantid.kernel import (VisibleWhenProperty, EnabledWhenProperty, PropertyCriterion, StringListValidator, IntBoundedValidator, FloatBoundedValidator, Direction) @@ -52,20 +51,20 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): self.declareProperty(name='MaterialAlreadyDefined', defaultValue=False, doc='Select this option if the material has already been defined') - materialDefinedProp = EnabledWhenProperty('MaterialAlreadyDefined', PropertyCriterion.IsDefault) + material_defined_prop = EnabledWhenProperty('MaterialAlreadyDefined', PropertyCriterion.IsDefault) self.declareProperty(name='ChemicalFormula', defaultValue='', doc='Chemical formula of sample') - self.setPropertySettings('ChemicalFormula', materialDefinedProp) + self.setPropertySettings('ChemicalFormula', material_defined_prop) self.declareProperty(name='DensityType', defaultValue='Mass Density', validator=StringListValidator(['Mass Density', 'Number Density']), doc='Use of Mass density or Number density') - self.setPropertySettings('DensityType', materialDefinedProp) + self.setPropertySettings('DensityType', material_defined_prop) self.declareProperty(name='Density', defaultValue=0.1, doc='Mass density (g/cm^3) or Number density (atoms/Angstrom^3)') - self.setPropertySettings('Density', materialDefinedProp) + self.setPropertySettings('Density', material_defined_prop) # ------------------------------------------------------------------------------------------- @@ -101,9 +100,9 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): validator=StringListValidator(['FlatPlate', 'Cylinder', 'Annulus']), doc='Geometry of sample environment. Options are: FlatPlate, Cylinder, Annulus') - flatPlateCondition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'FlatPlate') - cylinderCondition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Cylinder') - annulusCondition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Annulus') + flat_plate_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'FlatPlate') + cylinder_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Cylinder') + annulus_condition = VisibleWhenProperty('Shape', PropertyCriterion.IsEqualTo, 'Annulus') # height is common to all options @@ -116,40 +115,40 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): self.declareProperty(name='Width', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Width of the FlatPlate sample environment (cm)') - self.setPropertySettings('Width', flatPlateCondition) + self.setPropertySettings('Width', flat_plate_condition) self.declareProperty(name='Thickness', defaultValue=0.0, validator=FloatBoundedValidator(), doc='Thickness of the FlatPlate sample environment (cm)') - self.setPropertySettings('Thickness', flatPlateCondition) + self.setPropertySettings('Thickness', flat_plate_condition) self.declareProperty(name='Center', defaultValue=0.0, doc='Center of the FlatPlate sample environment') - self.setPropertySettings('Center', flatPlateCondition) + self.setPropertySettings('Center', flat_plate_condition) self.declareProperty(name='Angle', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Angle of the FlatPlate sample environment with respect to the beam (degrees)') - self.setPropertySettings('Angle', flatPlateCondition) + self.setPropertySettings('Angle', flat_plate_condition) # cylinder options self.declareProperty(name='Radius', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Radius of the Cylinder sample environment (cm)') - self.setPropertySettings('Radius', cylinderCondition) + self.setPropertySettings('Radius', cylinder_condition) # annulus options self.declareProperty(name='OuterRadius', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Outer radius of the Annulus sample environment (cm)') - self.setPropertySettings('OuterRadius', annulusCondition) + self.setPropertySettings('OuterRadius', annulus_condition) self.declareProperty(name='InnerRadius', defaultValue=0.0, validator=FloatBoundedValidator(0.0), doc='Inner radius of the Annulus sample environment (cm)') - self.setPropertySettings('InnerRadius', annulusCondition) + self.setPropertySettings('InnerRadius', annulus_condition) # ------------------------------------------------------------------------------------------- @@ -164,10 +163,12 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): prog.report('Setting up sample environment') # set the beam shape - SetBeam(self._input_ws_name, - Geometry={'Shape': 'Slit', - 'Width': self._beam_width, - 'Height': self._beam_height}) + set_beam_alg = self.createChildAlgorithm("SetBeam", enableLogging=False) + set_beam_alg.setProperty("InputWorkspace", self._input_ws) + set_beam_alg.setProperty("Geometry", {'Shape': 'Slit', + 'Width': self._beam_width, + 'Height': self._beam_height}) + set_beam_alg.execute() # set the sample geometry sample_geometry = dict() @@ -192,11 +193,14 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): sample_geometry['Center'] = [0.0, 0.0, 0.0] sample_geometry['Axis'] = 1 + set_sample_alg = self.createChildAlgorithm("SetSample", enableLogging=False) + set_sample_alg.setProperty("InputWorkspace", self._input_ws) + set_sample_alg.setProperty("Geometry", sample_geometry) + # set sample if self._material_defined: # set sample without sample material - SetSample(InputWorkspace=self._input_ws_name, - Geometry=sample_geometry) + set_sample_alg.execute() else: # set the sample material @@ -208,17 +212,24 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): if self._density_type == 'Number Density': sample_material['SampleNumberDensity'] = self._density - SetSample(InputWorkspace=self._input_ws_name, - Geometry=sample_geometry, - Material=sample_material) + set_sample_alg.setProperty("Material", sample_material) + + try: + set_sample_alg.execute() + except RuntimeError as exc: + raise RuntimeError("Supplied chemical formula was invalid: \n" + str(exc)) prog.report('Calculating sample corrections') - MonteCarloAbsorption(InputWorkspace=self._input_ws_name, - OutputWorkspace=self._output_ws, - EventsPerPoint=self._events, - NumberOfWavelengthPoints=self._number_wavelengths, - Interpolation=self._interpolation) + monte_carlo_alg = self.createChildAlgorithm("MonteCarloAbsorption", enableLogging=True) + monte_carlo_alg.setProperty("InputWorkspace", self._input_ws) + monte_carlo_alg.setProperty("OutputWorkspace", self._output_ws) + monte_carlo_alg.setProperty("EventsPerPoint", self._events) + monte_carlo_alg.setProperty("NumberOfWavelengthPoints", self._number_wavelengths) + monte_carlo_alg.setProperty("Interpolation", self._interpolation) + monte_carlo_alg.execute() + + output_ws = monte_carlo_alg.getProperty("OutputWorkspace").value prog.report('Recording Sample Logs') @@ -231,17 +242,17 @@ class SimpleShapeMonteCarloAbsorption(DataProcessorAlgorithm): log_values.append(value) add_sample_log_alg = self.createChildAlgorithm('AddSampleLogMultiple', enableLogging=False) - add_sample_log_alg.setProperty('Workspace', self._output_ws) + add_sample_log_alg.setProperty('Workspace', output_ws) add_sample_log_alg.setProperty('LogNames', log_names) add_sample_log_alg.setProperty('LogValues', log_values) add_sample_log_alg.execute() - self.setProperty('OutputWorkspace', self._output_ws) + self.setProperty('OutputWorkspace', output_ws) def _setup(self): # basic options - self._input_ws_name = self.getPropertyValue('InputWorkspace') + self._input_ws = self.getProperty('InputWorkspace').value self._material_defined = self.getProperty('MaterialAlreadyDefined').value self._chemical_formula = self.getPropertyValue('ChemicalFormula') self._density_type = self.getPropertyValue('DensityType') diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py index 6b9d195f20e3ff36a2e402ebbd472e60348b8804..11267638bb83ead093777797735e8867d65aae08 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/MeanTest.py @@ -10,9 +10,10 @@ class MeanTest(unittest.TestCase): a = CreateWorkspace(DataX=[1,2,3],DataY=[1,2,3],DataE=[1,1,1],UnitX='TOF') try: c = Mean(Workspaces='a,b') # 'b' does not exist. - self.fail("Should not have got here. Should throw without both workspace names indexing real workspaces in IDF.") except RuntimeError: pass + else: + self.fail("Should not have got here. Should throw without both workspace names indexing real workspaces in IDF.") finally: DeleteWorkspace(a) @@ -21,9 +22,10 @@ class MeanTest(unittest.TestCase): b = CreateWorkspace(DataX=[1,2,3,4],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF') try: c = Mean(Workspaces='a,b') # 'a' and 'b' are different sizes. - self.fail("Should not have got here. Should throw as axis0 is unequal in size between a and b.") except RuntimeError: pass + else: + self.fail("Should not have got here. Should throw as axis0 is unequal in size between a and b.") finally: DeleteWorkspace(a) DeleteWorkspace(b) @@ -33,9 +35,23 @@ class MeanTest(unittest.TestCase): b = CreateWorkspace(DataX=[1,2,3,4],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF',NSpec=2) try: c = Mean(Workspaces='a,b') # 'a' and 'b' are different sizes. + except RuntimeError: + pass + else: self.fail("Should not have got here. Should throw as axis1 is unequal in size between a and b.") + finally: + DeleteWorkspace(a) + DeleteWorkspace(b) + + def test_throws_if_workspace_unorded(self): + a = CreateWorkspace(DataX=[1,2,1,2],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF',NSpec=2) + b = CreateWorkspace(DataX=[1,2,2,1],DataY=[1,2,3,4],DataE=[1,1,1,1],UnitX='TOF',NSpec=2) + try: + c = Mean(Workspaces='a,b') # 'a' and 'b' have different x data. except RuntimeError: pass + else: + self.fail("Should not have got here. Should throw as the x data is unsorted") finally: DeleteWorkspace(a) DeleteWorkspace(b) diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CMakeLists.txt b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CMakeLists.txt index 99e0747dda996a610c3db8d7841f80bef0700118..6dba3a3729f4c6e0a70bd3338b25a950506b6f8b 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CMakeLists.txt +++ b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CMakeLists.txt @@ -7,6 +7,7 @@ set ( TEST_PY_FILES ApplyPaalmanPingsCorrectionTest.py BayesQuasiTest.py BayesStretchTest.py + CalculateMonteCarloAbsorptionTest.py DetectorFloodWeightingTest.py DirectILLApplySelfShieldingTest.py DirectILLCollectDataTest.py diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorptionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorptionTest.py new file mode 100644 index 0000000000000000000000000000000000000000..94dec43d4ec3f2ffd3feb253c9cd6daafc094e7f --- /dev/null +++ b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/CalculateMonteCarloAbsorptionTest.py @@ -0,0 +1,143 @@ +from mantid.kernel import * +from mantid.api import * +from mantid.simpleapi import (Load, DeleteWorkspace, CalculateMonteCarloAbsorption) + +import unittest + +class CalculateMonteCarloAbsorptionTest(unittest.TestCase): + + _red_ws = None + _container_ws = None + _indirect_elastic_ws = None + + def setUp(self): + red_ws = Load('irs26176_graphite002_red.nxs') + container_ws = Load('irs26173_graphite002_red.nxs') + indirect_elastic_ws = Load('osi104367_elf.nxs') + self._red_ws = red_ws + self._container_ws = container_ws + self._indirect_elastic_ws = indirect_elastic_ws + self._expected_unit = self._red_ws.getAxis(0).getUnit().unitID() + self._expected_hist = 10 + self._expected_blocksize = 1905 + + self._arguments = {'SampleChemicalFormula': 'H2-O', + 'SampleDensityType': 'Mass Density', + 'SampleDensity': 1.0, + 'EventsPerPoint': 200, + 'BeamHeight': 3.5, + 'BeamWidth': 4.0, + 'Height': 2.0 } + + self._container_args = {'ContainerWorkspace':self._container_ws, + 'ContainerChemicalFormula':'Al', + 'ContainerDensityType':'Mass Density', + 'ContainerDensity':1.0 } + self._test_arguments = dict() + + def tearDown(self): + DeleteWorkspace(self._red_ws) + + if self._container_ws is not None: + DeleteWorkspace(self._container_ws) + if self._indirect_elastic_ws is not None: + DeleteWorkspace(self._indirect_elastic_ws) + + def _setup_flat_plate_container(self): + self._test_arguments['ContainerFrontThickness'] = 1.5 + self._test_arguments['ContainerBackThickness'] = 1.5 + + def _setup_annulus_container(self): + self._test_arguments['ContainerInnerRadius'] = 1.0 + self._test_arguments['ContainerOuterRadius'] = 2.0 + + def _test_corrections_workspace(self, corr_ws): + x_unit = corr_ws.getAxis(0).getUnit().unitID() + self.assertEquals(x_unit, self._expected_unit) + + y_unit = corr_ws.YUnitLabel() + self.assertEquals(y_unit, 'Attenuation factor') + + num_hists = corr_ws.getNumberHistograms() + self.assertEquals(num_hists, self._expected_hist) + + blocksize = corr_ws.blocksize() + self.assertEquals(blocksize, self._expected_blocksize) + + def _test_corrections_workspaces(self, workspaces): + self.assertNotEquals(workspaces, None) + + for workspace in workspaces: + self._test_corrections_workspace(workspace) + + def _run_correction_and_test(self, shape, sample_ws=None): + + if sample_ws is None: + sample_ws = self._red_ws + + arguments = self._arguments.copy() + arguments.update(self._test_arguments) + corrected = CalculateMonteCarloAbsorption(SampleWorkspace=sample_ws, + Shape=shape, + **arguments) + self._test_corrections_workspaces(corrected) + + def _run_correction_with_container_test(self, shape): + self._test_arguments.update(self._container_args) + + if shape == 'FlatPlate': + self._setup_flat_plate_container() + else: + self._setup_annulus_container() + + self._run_correction_and_test(shape) + + def _run_indirect_elastic_test(self, shape): + self._expected_unit = "MomentumTransfer" + self._expected_hist = 17 + self._expected_blocksize = 1 + self._run_correction_and_test(shape, self._indirect_elastic_ws) + + def _flat_plate_test(self, test_func): + self._test_arguments['SampleWidth'] = 2.0 + self._test_arguments['SampleThickness'] = 2.0 + test_func('FlatPlate') + + def _annulus_test(self, test_func): + self._test_arguments['SampleInnerRadius'] = 1.2 + self._test_arguments['SampleOuterRadius'] = 1.8 + test_func('Annulus') + + def _cylinder_test(self, test_func): + self._test_arguments['SampleRadius'] = 0.5 + test_func('Cylinder') + + def test_flat_plate_no_container(self): + self._flat_plate_test(self._run_correction_and_test) + + def test_cylinder_no_container(self): + self._cylinder_test(self._run_correction_and_test) + + def test_annulus_no_container(self): + self._annulus_test(self._run_correction_and_test) + + def test_flat_plate_with_container(self): + self._flat_plate_test(self._run_correction_with_container_test) + + def test_cylinder_with_container(self): + self._cylinder_test(self._run_correction_with_container_test) + + def test_annulus_with_container(self): + self._annulus_test(self._run_correction_with_container_test) + + def test_flat_plate_indirect_elastic(self): + self._flat_plate_test(self._run_indirect_elastic_test) + + def test_cylinder_indirect_elastic(self): + self._cylinder_test(self._run_indirect_elastic_test) + + def test_annulus_indirect_elastic(self): + self._annulus_test(self._run_indirect_elastic_test) + +if __name__ == "__main__": + unittest.main() diff --git a/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReductionTest.py b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReductionTest.py index 058d2376df2ef7dc1c9c5cad4dc5498c49724429..e09ee0b7b1b9e29db8f9ce6b5b148c1c5873473b 100644 --- a/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReductionTest.py +++ b/Framework/PythonInterface/test/python/plugins/algorithms/WorkflowAlgorithms/OSIRISDiffractionReductionTest.py @@ -22,9 +22,9 @@ class OSIRISDiffractionReductionTest(unittest.TestCase): self.assertEqual(wks.getAxis(0).getUnit().unitID(), 'dSpacing') self.assertEqual(wks.getNumberHistograms(), 1) - def test_reduction_with_manual_drange_completes(self): + def test_reduction_with_single_manual_drange_completes(self): """ - Test to ensure reduction with manual dRange selection completes. + Test to ensure reduction with single manual dRange selection completes. The run here is for dRange 3. """ diff --git a/Framework/SINQ/src/PoldiFitPeaks1D2.cpp b/Framework/SINQ/src/PoldiFitPeaks1D2.cpp index 3ec195ea9c419cf29b95e1d0e817ab54ead13c4d..8ca44f3a4e1728bfd70a49bd4ccd03af987f9882 100644 --- a/Framework/SINQ/src/PoldiFitPeaks1D2.cpp +++ b/Framework/SINQ/src/PoldiFitPeaks1D2.cpp @@ -283,7 +283,7 @@ PoldiFitPeaks1D2::fitPeaks(const PoldiPeakCollection_sptr &peaks) { Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace"); m_fitplots->removeAll(); - for (auto currentRange : reducedRanges) { + for (const auto ¤tRange : reducedRanges) { int nMin = getBestChebyshevPolynomialDegree(dataWorkspace, currentRange); if (nMin > -1) { diff --git a/Framework/TestHelpers/inc/MantidTestHelpers/FakeObjects.h b/Framework/TestHelpers/inc/MantidTestHelpers/FakeObjects.h index 9914b17433470dd26e38cdc6ebfe4daaf31ac957..63c03bb8d4cc5bb8f622e44143a11822fbb40804 100644 --- a/Framework/TestHelpers/inc/MantidTestHelpers/FakeObjects.h +++ b/Framework/TestHelpers/inc/MantidTestHelpers/FakeObjects.h @@ -111,8 +111,24 @@ public: // Empty overrides of virtual methods size_t getNumberHistograms() const override { return m_spec; } const std::string id() const override { return "AxeslessWorkspaceTester"; } - size_t size() const override { return m_vec.size() * blocksize(); } + size_t size() const override { + size_t total_size = 0; + for (const auto &it : m_vec) { + total_size += it.dataY().size(); + } + return total_size; + } size_t blocksize() const override { + if (m_vec.empty()) { + return 0; + } else { + size_t numY = m_vec[0].dataY().size(); + for (const auto &it : m_vec) { + if (it.dataY().size() != numY) + throw std::logic_error("non-constant number of bins"); + } + return numY; + } return m_vec.empty() ? 0 : m_vec[0].dataY().size(); } ISpectrum &getSpectrum(const size_t index) override { diff --git a/Framework/TestHelpers/src/NexusTestHelper.cpp b/Framework/TestHelpers/src/NexusTestHelper.cpp index 9fb8bf16a84b3c4c0ab64905c03ee9aad134781c..0a4fbbb68cb65985b30de91dbc38548b6bd91820 100644 --- a/Framework/TestHelpers/src/NexusTestHelper.cpp +++ b/Framework/TestHelpers/src/NexusTestHelper.cpp @@ -40,7 +40,7 @@ void NexusTestHelper::createFile(std::string barefilename) { if (Poco::File(filename).exists()) Poco::File(filename).remove(); file = new ::NeXus::File(filename, NXACC_CREATE5); - file->makeGroup("test_entry", "NXentry", 1); + file->makeGroup("test_entry", "NXentry", true); } //---------------------------------------------------------------------------------------------- diff --git a/Framework/TestHelpers/src/SANSInstrumentCreationHelper.cpp b/Framework/TestHelpers/src/SANSInstrumentCreationHelper.cpp index 2b21baaad231881de33a6b945b33b4f9df22de65..1bdc34d3ef0a4ca0e9b61bb7df20980cd6c53266 100644 --- a/Framework/TestHelpers/src/SANSInstrumentCreationHelper.cpp +++ b/Framework/TestHelpers/src/SANSInstrumentCreationHelper.cpp @@ -42,7 +42,7 @@ Workspace2D_sptr SANSInstrumentCreationHelper::createSANSInstrumentWorkspace( // Create a test workspace with test data with a well defined peak // The test instrument has two monitor channels Workspace2D_sptr ws = WorkspaceCreationHelper::create2DWorkspace123( - nBins * nBins + nMonitors, 1, 1); + nBins * nBins + nMonitors, 1, true); AnalysisDataService::Instance().addOrReplace(workspace, ws); ws->getAxis(0)->unit() = Mantid::Kernel::UnitFactory::Instance().create("Wavelength"); diff --git a/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp b/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp index 26ce6ac239b47ffe58d1d0fffd78b10f0f76904c..80c585043d454be55138c6059aa00b9b00fc25b0 100644 --- a/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp +++ b/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp @@ -247,7 +247,7 @@ void ConvolutionFitSequential::exec() { deleteProgress.report("Deleting PlotPeak Output"); const auto paramTableName = outputWsName + "_Parameters"; - AnalysisDataService::Instance().add(paramTableName, outputWs); + AnalysisDataService::Instance().addOrReplace(paramTableName, outputWs); // Construct output workspace const auto resultWsName = outputWsName + "_Result"; diff --git a/MantidPlot/src/ApplicationWindow.cpp b/MantidPlot/src/ApplicationWindow.cpp index 0ab856296e3a6023f00b72af9b9bb6c25143f8b7..a8db3a39f7faa42e6cc6006e856b4a644d53aa15 100644 --- a/MantidPlot/src/ApplicationWindow.cpp +++ b/MantidPlot/src/ApplicationWindow.cpp @@ -6566,7 +6566,7 @@ void ApplicationWindow::exportASCII(const QString &tableName, if (!fname.isEmpty()) { QFileInfo fi(fname); QString baseName = fi.fileName(); - if (baseName.contains(".") == 0) + if (!baseName.contains(".")) fname.append(selectedFilter.remove("*")); asciiDirPath = fi.absolutePath(); @@ -8305,7 +8305,7 @@ void ApplicationWindow::drawArrow() { Graph *g = dynamic_cast<Graph *>(plot->activeGraph()); if (g) { - g->drawLine(true, 1); + g->drawLine(true, true); emit modified(); } } diff --git a/MantidPlot/src/ConfigDialog.cpp b/MantidPlot/src/ConfigDialog.cpp index f1d554c8653a04edf0804c09433a47de395ad178..7013816d4f750861e70906c94a98053f8f5c0e6a 100644 --- a/MantidPlot/src/ConfigDialog.cpp +++ b/MantidPlot/src/ConfigDialog.cpp @@ -716,7 +716,7 @@ void ConfigDialog::initMantidPage() { // Populate boxes auto faclist = cfgSvc.getFacilityNames(); - for (auto it : faclist) { + for (const auto &it : faclist) { facility->addItem(QString::fromStdString(it)); } @@ -1197,7 +1197,7 @@ void ConfigDialog::populateProgramTree() { void ConfigDialog::updateProgramTree() { // Store into a map ready to go into config service when apply is clicked - for (const auto itr : m_sendToSettings) { + for (const auto &itr : m_sendToSettings) { // creating the map of kvps needs to happen first as createing the item // requires them. std::map<std::string, std::string> programKeysAndDetails = itr.second; @@ -1223,7 +1223,7 @@ void ConfigDialog::updateChildren( QTreeWidgetItem *program) { program->takeChildren(); // get the current program's (itr) keys and values (pItr) - for (const auto pItr : programKeysAndDetails) { + for (const auto &pItr : programKeysAndDetails) { QTreeWidgetItem *item = new QTreeWidgetItem(program); QString itemText = QString(" ") .append(QString::fromStdString(pItr.first)) @@ -1242,7 +1242,7 @@ void ConfigDialog::updateSendToTab() { std::vector<std::string> programNames = cfgSvc.getKeys("workspace.sendto.name"); - for (const auto itr : m_sendToSettings) { + for (const auto &itr : m_sendToSettings) { for (size_t i = 0; i < programNames.size(); ++i) { if (programNames[i] == itr.first) { // The selected program hasn't been deleted so set to blank string (all @@ -1255,7 +1255,7 @@ void ConfigDialog::updateSendToTab() { std::map<std::string, std::string> programKeysAndDetails = itr.second; - for (const auto pItr : programKeysAndDetails) { + for (const auto &pItr : programKeysAndDetails) { if (pItr.second != "") cfgSvc.setString("workspace.sendto." + itr.first + "." + pItr.first, pItr.second); @@ -1289,7 +1289,7 @@ void ConfigDialog::refreshTreeCategories() { widgetMap categories; // Keeps track of categories added to the tree // Loop over all categories loaded into Mantid - for (const auto i : categoryMap) { + for (const auto &i : categoryMap) { QString catNames = QString::fromStdString(i.first); // Start recursion down building tree from names @@ -2465,7 +2465,7 @@ void ConfigDialog::apply() { sep.replace(tr("SPACE"), " "); sep.replace("\\s", " "); - if (sep.contains(QRegExp("[0-9.eE+-]")) != 0) { + if (sep.contains(QRegExp("[0-9.eE+-]"))) { QMessageBox::warning(nullptr, tr("MantidPlot - Import options error"), tr("The separator must not contain the following " "characters: 0-9eE.+-")); @@ -2872,7 +2872,7 @@ QStringList ConfigDialog::buildHiddenCategoryString(QTreeWidgetItem *parent) { } QStringList childResults = buildHiddenCategoryString(item); - for (const auto it : childResults) { + for (const auto &it : childResults) { results.append(item->text(0) + "\\" + it); } } diff --git a/MantidPlot/src/Folder.cpp b/MantidPlot/src/Folder.cpp index 2cb1f2ab11aa4419bfbc8040d13322c0e4697276..a2abde0fe6361820e33b89d28949ae78e1985872 100644 --- a/MantidPlot/src/Folder.cpp +++ b/MantidPlot/src/Folder.cpp @@ -143,7 +143,7 @@ MdiSubWindow *Folder::findWindow(const QString &s, bool windowNames, else if (caseSensitive && name == s) return w; else { - QString text = s; + const QString &text = s; if (name == text.toLower()) return w; } @@ -156,7 +156,7 @@ MdiSubWindow *Folder::findWindow(const QString &s, bool windowNames, else if (caseSensitive && label == s) return w; else { - QString text = s; + const QString &text = s; if (label == text.toLower()) return w; } diff --git a/MantidPlot/src/Graph.cpp b/MantidPlot/src/Graph.cpp index afaef73f4af2c83d5df5d98c38171580536411a2..387e491227cde16614c833e8305c1e2933abff6e 100644 --- a/MantidPlot/src/Graph.cpp +++ b/MantidPlot/src/Graph.cpp @@ -1006,7 +1006,7 @@ void Graph::initScaleLimits() { // We call this function the first time we add continue; const QwtPlotCurve *c = dynamic_cast<const QwtPlotCurve *>(item); - const QwtSymbol s = c->symbol(); + const QwtSymbol &s = c->symbol(); if (s.style() != QwtSymbol::NoSymbol && s.size().width() >= maxSymbolSize) maxSymbolSize = s.size().width(); @@ -1845,7 +1845,7 @@ void Graph::updateCurvesData(Table *w, const QString &yColName) { QColor Graph::canvasFrameColor() { QwtPlotCanvas *canvas = (QwtPlotCanvas *)d_plot->canvas(); - QPalette pal = canvas->palette(); + const QPalette &pal = canvas->palette(); return pal.color(QPalette::Active, QPalette::Foreground); } @@ -1988,7 +1988,7 @@ QString Graph::saveCurveLayout(int index) { s += QString::number(c->pen().style() - 1) + "\t"; s += QString::number(c->pen().widthF()) + "\t"; - const QwtSymbol symbol = c->symbol(); + const QwtSymbol &symbol = c->symbol(); s += QString::number(symbol.size().width()) + "\t"; s += QString::number(SymbolBox::symbolIndex(symbol.style())) + "\t"; s += QString::number(ColorBox::colorIndex(symbol.pen().color())) + "\t"; @@ -2754,7 +2754,7 @@ PlotCurve *Graph::insertCurve(Table *w, const QString &xColName, if (!xval.isEmpty() && !yval.isEmpty()) { bool valid_data = true; if (xColType == Table::Text) { - if (xLabels.contains(xval) == 0) + if (!xLabels.contains(xval)) xLabels << xval; X[size] = (double)(xLabels.indexOf(xval) + 1); } else if (xColType == Table::Time) { @@ -4619,7 +4619,7 @@ void Graph::guessUniqueCurveLayout(int &colorIndex, int &symbolIndex) { if (c) { colorIndex = std::max(ColorBox::colorIndex(c->pen().color()), colorIndex); - QwtSymbol symb = c->symbol(); + const QwtSymbol &symb = c->symbol(); symbolIndex = std::max(SymbolBox::symbolIndex(symb.style()), symbolIndex); } } diff --git a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp index da8945a4ef0e4f9fdff4f441fa9a412c1df84cd8..507fefc92ad5fe09cd351c2b25da849bddc95df6 100644 --- a/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp +++ b/MantidPlot/src/Mantid/AlgorithmHistoryWindow.cpp @@ -45,7 +45,7 @@ AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QString title, QWidget *w) m_execDurationEdit = new QLineEdit("", this); if (m_execDurationEdit) - m_execDurationEdit->setReadOnly(1); + m_execDurationEdit->setReadOnly(true); m_execDurationlabel = new QLabel("Duration:", this); if (m_execDurationlabel) m_execDurationlabel->setBuddy(m_execDurationEdit); @@ -53,7 +53,7 @@ AlgExecSummaryGrpBox::AlgExecSummaryGrpBox(QString title, QWidget *w) QDateTime datetime(QDate(0, 0, 0), QTime(0, 0, 0), Qt::LocalTime); m_execDateTimeEdit = new QLineEdit("", this); if (m_execDateTimeEdit) - m_execDateTimeEdit->setReadOnly(1); + m_execDateTimeEdit->setReadOnly(true); m_Datelabel = new QLabel("Date:", this); if (m_Datelabel) m_Datelabel->setBuddy(m_execDateTimeEdit); @@ -124,7 +124,7 @@ AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QString title, QWidget *w) // OS Name Label & Edit Box m_osNameEdit = new QLineEdit("", this); if (m_osNameEdit) { - m_osNameEdit->setReadOnly(1); + m_osNameEdit->setReadOnly(true); } m_osNameLabel = new QLabel("OS Name:", this); if (m_osNameLabel) @@ -133,7 +133,7 @@ AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QString title, QWidget *w) // OS Version Label & Edit Box m_osVersionEdit = new QLineEdit("", this); if (m_osVersionEdit) { - m_osVersionEdit->setReadOnly(1); + m_osVersionEdit->setReadOnly(true); m_osVersionLabel = new QLabel("OS Version:", this); } if (m_osVersionLabel) @@ -142,7 +142,7 @@ AlgEnvHistoryGrpBox::AlgEnvHistoryGrpBox(QString title, QWidget *w) // Mantid Framework Version Label & Edit Box m_frmwkVersnEdit = new QLineEdit("", this); if (m_frmwkVersnEdit) - m_frmwkVersnEdit->setReadOnly(1); + m_frmwkVersnEdit->setReadOnly(true); m_frmworkVersionLabel = new QLabel("Framework Version:", this); if (m_frmworkVersionLabel) m_frmworkVersionLabel->setBuddy(m_frmwkVersnEdit); diff --git a/MantidPlot/src/Mantid/InputHistory.cpp b/MantidPlot/src/Mantid/InputHistory.cpp index f3b0b438979cf22992c965e5ee187e3c13e9bca0..265243309408f68ad163101665fa4fdc4ebf1850 100644 --- a/MantidPlot/src/Mantid/InputHistory.cpp +++ b/MantidPlot/src/Mantid/InputHistory.cpp @@ -132,7 +132,7 @@ QString InputHistoryImpl::getDirectoryFromFilePath(const QString &filePath) { } QString InputHistoryImpl::getNameOnlyFromFilePath(const QString &filePath) { - QString s = filePath; + const QString &s = filePath; int i = s.lastIndexOf('\\'); if (i < 0) i = s.lastIndexOf('/'); diff --git a/MantidPlot/src/Mantid/MantidMatrix.cpp b/MantidPlot/src/Mantid/MantidMatrix.cpp index 76e6000af7f7504b7b7600b6042c64f21b34510e..7f70a5f3b103dcad1f6c4790754e9aaeacb418e8 100644 --- a/MantidPlot/src/Mantid/MantidMatrix.cpp +++ b/MantidPlot/src/Mantid/MantidMatrix.cpp @@ -226,7 +226,16 @@ void MantidMatrix::setup(Mantid::API::MatrixWorkspace_const_sptr ws, int start, ? m_workspaceTotalHist - 1 : end; m_rows = m_endRow - m_startRow + 1; - m_cols = static_cast<int>(ws->blocksize()); + try { + // let the workspace do its thing + m_cols = static_cast<int>(ws->blocksize()); + } catch (std::length_error &) { + // otherwise get the maximum + m_cols = static_cast<int>(ws->y(0).size()); + for (int i = 0; i < m_workspaceTotalHist; ++i) { + m_cols = std::max(m_cols, static_cast<int>(ws->y(i).size())); + } + } if (ws->isHistogramData()) m_histogram = true; connect(this, SIGNAL(needsUpdating()), this, SLOT(repaintAll())); @@ -530,35 +539,39 @@ void MantidMatrix::goToColumn(int col) { } double MantidMatrix::dataX(int row, int col) const { + if (!m_workspace || row >= numRows() || col >= numCols()) + return 0.; const auto &x = m_workspace->x(row + m_startRow); - if (!m_workspace || row >= numRows() || col >= static_cast<int>(x.size())) + if (col >= static_cast<int>(x.size())) return 0.; - double res = x[col]; - return res; + return x[col]; } double MantidMatrix::dataY(int row, int col) const { - const auto &y = m_workspace->y(row + m_startRow); if (!m_workspace || row >= numRows() || col >= numCols()) return 0.; - double res = y[col]; - return res; + const auto &y = m_workspace->y(row + m_startRow); + if (col >= static_cast<int>(y.size())) + return 0.; + return y[col]; } double MantidMatrix::dataE(int row, int col) const { - const auto &e = m_workspace->e(row + m_startRow); if (!m_workspace || row >= numRows() || col >= numCols()) return 0.; - double res = e[col]; - return res; + const auto &e = m_workspace->e(row + m_startRow); + if (col >= static_cast<int>(e.size())) + return 0.; + return e[col]; } double MantidMatrix::dataDx(int row, int col) const { - const auto &dx = m_workspace->dx(row + m_startRow); if (!m_workspace || row >= numRows() || col >= numCols()) return 0.; - double res = dx[col]; - return res; + const auto &dx = m_workspace->dx(row + m_startRow); + if (col >= static_cast<int>(dx.size())) + return 0.; + return dx[col]; } QString MantidMatrix::workspaceName() const { @@ -587,10 +600,11 @@ QwtDoubleRect MantidMatrix::boundingRect() { while (x_start == x_end && i0 <= m_endRow) { const auto &X = m_workspace->x(i0); x_start = X[0]; - if (X.size() != m_workspace->y(i0).size()) - x_end = X[m_workspace->blocksize()]; + const size_t y_size = m_workspace->y(i0).size(); + if (X.size() != y_size) + x_end = X[y_size]; else - x_end = X[m_workspace->blocksize() - 1]; + x_end = X[y_size - 1]; if (!std::isfinite(x_start) || !std::isfinite(x_end)) { x_start = x_end = 0; } @@ -971,8 +985,8 @@ void MantidMatrix::afterReplaceHandle( } void MantidMatrix::changeWorkspace(Mantid::API::MatrixWorkspace_sptr ws) { - if (m_cols != static_cast<int>(ws->blocksize()) || - m_workspaceTotalHist != static_cast<int>(ws->getNumberHistograms())) { + if (m_workspaceTotalHist != static_cast<int>(ws->getNumberHistograms()) || + m_cols != static_cast<int>(ws->blocksize())) { closeDependants(); } diff --git a/MantidPlot/src/Mantid/MantidMatrixModel.cpp b/MantidPlot/src/Mantid/MantidMatrixModel.cpp index 88cbd1d8a65ee5e35de5ab168e5e8aaa34c131d1..d71773369472c3b66f86701c5c049345e6877957 100644 --- a/MantidPlot/src/Mantid/MantidMatrixModel.cpp +++ b/MantidPlot/src/Mantid/MantidMatrixModel.cpp @@ -44,28 +44,41 @@ void MantidMatrixModel::setup(const Mantid::API::MatrixWorkspace *ws, int rows, m_mask_color = QApplication::palette().color(QPalette::Disabled, QPalette::Background); - if (ws->blocksize() != 0) - m_colNumCorr = ws->isHistogramData() ? 1 : 0; - else - m_colNumCorr = 0; + m_colNumCorr = 0; + const size_t numHist = ws->getNumberHistograms(); + for (size_t i = 0; i < numHist; ++i) { + // anything being non-empty means check it + // checking x-means EventWorkspaces aren't + // histogramed as part of the check + if (!ws->x(i).empty()) { + m_colNumCorr = ws->isHistogramData() ? 1 : 0; + break; + } + } } double MantidMatrixModel::data(int row, int col) const { Mantid::Kernel::ReadLock _lock(*m_workspace); - double val; + const size_t workspaceIndex = static_cast<size_t>(row + m_startRow); + + double val = 0.; // default value switch (m_type) { case X: - val = m_workspace->x(row + m_startRow)[col]; + if (col < static_cast<int>(m_workspace->x(workspaceIndex).size())) + val = m_workspace->x(workspaceIndex)[col]; break; case Y: - val = m_workspace->y(row + m_startRow)[col]; + if (col < static_cast<int>(m_workspace->y(workspaceIndex).size())) + val = m_workspace->y(workspaceIndex)[col]; break; case E: - val = m_workspace->e(row + m_startRow)[col]; + if (col < static_cast<int>(m_workspace->e(workspaceIndex).size())) + val = m_workspace->e(workspaceIndex)[col]; break; default: - val = m_workspace->dx(row + m_startRow)[col]; + if (col < static_cast<int>(m_workspace->dx(workspaceIndex).size())) + val = m_workspace->dx(workspaceIndex)[col]; break; } return val; @@ -174,7 +187,7 @@ QVariant MantidMatrixModel::headerData(int section, Qt::Orientation orientation, Mantid::API::BinEdgeAxis *binEdgeAxis = dynamic_cast<Mantid::API::BinEdgeAxis *>(axis); if (binEdgeAxis && axisIndex == 1) { - const Mantid::MantidVec axisBinEdges = binEdgeAxis->getValues(); + const Mantid::MantidVec &axisBinEdges = binEdgeAxis->getValues(); double binCentreValue = (axisBinEdges[section] + axisBinEdges[section + 1]) / 2.0; diff --git a/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp b/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp index c662154697e334a78ef8a36c25a78f14177bef58..f39a3f0b4051d5aca2a94ca9e5c7d505f514ad76 100644 --- a/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp +++ b/MantidPlot/src/Mantid/MantidSampleLogDialog.cpp @@ -72,7 +72,7 @@ MantidSampleLogDialog::MantidSampleLogDialog(const QString &wsname, for (size_t i = 0; i < NUM_STATS; i++) { statLabels[i] = new QLabel(stats[i].c_str()); statValues[i] = new QLineEdit(""); - statValues[i]->setReadOnly(1); + statValues[i]->setReadOnly(true); statsBoxLayout->addRow(statLabels[i], statValues[i]); } statsBox->setLayout(statsBoxLayout); diff --git a/MantidPlot/src/Mantid/MantidTable.cpp b/MantidPlot/src/Mantid/MantidTable.cpp index f33665d4b88f79c60d58ca6659cd449dd27720f7..295b08302052dd65f515ce48747fac56e5484fdd 100644 --- a/MantidPlot/src/Mantid/MantidTable.cpp +++ b/MantidPlot/src/Mantid/MantidTable.cpp @@ -1,3 +1,6 @@ +#include <iomanip> +#include <limits> + #include "MantidTable.h" #include "../ApplicationWindow.h" #include "../Mantid/MantidUI.h" @@ -312,7 +315,8 @@ void MantidTable::cellEdited(int row, int col) { // Put it back in the stream and let the column deduce the correct // type of the number. std::stringstream textStream; - textStream << number; + textStream << std::setprecision(std::numeric_limits<long double>::digits10 + + 1) << number; std::istringstream stream(textStream.str()); c->read(index, stream); } diff --git a/MantidPlot/src/Mantid/MantidUI.cpp b/MantidPlot/src/Mantid/MantidUI.cpp index 8318b70393aa78dddceea19820ea7ebe21b1cb19..b3c50e44212a3051078d2e2a0452edbe0e3a9adb 100644 --- a/MantidPlot/src/Mantid/MantidUI.cpp +++ b/MantidPlot/src/Mantid/MantidUI.cpp @@ -1,5 +1,6 @@ // Python header must go first #include "MantidQtWidgets/Common/PythonThreading.h" +#include "MantidQtWidgets/Common/DropEventHelper.h" #include "AlgorithmDockWidget.h" #include "AlgorithmHistoryWindow.h" @@ -734,7 +735,7 @@ MantidUI::plotMDList(const QStringList &wsNames, const int plotAxis, const bool showErrors, MultiLayer *plotWindow, bool clearWindow) { ScopedOverrideCursor waitCursor; - auto firstName = wsNames.at(0); + const auto &firstName = wsNames.at(0); bool isGraphNew = false; MultiLayer *ml = appWindow()->prepareMultiLayer(isGraphNew, plotWindow, @@ -744,7 +745,7 @@ MantidUI::plotMDList(const QStringList &wsNames, const int plotAxis, try { for (int i = 0; i < wsNames.size(); ++i) { // Create the curve with defaults - auto wsName = wsNames.at(i); + const auto &wsName = wsNames.at(i); MantidMDCurve *curve = new MantidMDCurve(wsName, g, showErrors); MantidQwtIMDWorkspaceData *data = curve->mantidData(); @@ -1563,8 +1564,8 @@ bool MantidUI::drop(QDropEvent *e) { foreach (const auto &wsName, wsNames) { importWorkspace(wsName, false); } return true; } else if (e->mimeData()->hasUrls()) { - QStringList pyFiles = extractPyFiles(e->mimeData()->urls()); - if (pyFiles.size() > 0) { + const auto pyFiles = DropEventHelper::extractPythonFiles(e); + if (!pyFiles.empty()) { try { MantidQt::API::ProjectSerialiser serialiser(m_appWindow); serialiser.openScriptWindow(pyFiles); @@ -1598,22 +1599,6 @@ bool MantidUI::drop(QDropEvent *e) { return false; } -/// extracts the files from a mimedata object that have a .py extension -QStringList MantidUI::extractPyFiles(const QList<QUrl> &urlList) const { - QStringList filenames; - for (int i = 0; i < urlList.size(); ++i) { - QString fName = urlList[i].toLocalFile(); - if (fName.size() > 0) { - QFileInfo fi(fName); - - if (fi.suffix().toUpper() == "PY") { - filenames.append(fName); - } - } - } - return filenames; -} - /** Executes the Save Nexus dialogue from the right click context menu. diff --git a/MantidPlot/src/Mantid/MantidUI.h b/MantidPlot/src/Mantid/MantidUI.h index c0b5400f2849791350fa0312d07bca65f81c414b..dc50a4ad94075492cd06cf1ed7be522b38b286fd 100644 --- a/MantidPlot/src/Mantid/MantidUI.h +++ b/MantidPlot/src/Mantid/MantidUI.h @@ -620,9 +620,6 @@ private: bool useAbsoluteDate, Mantid::Types::Core::DateAndTime start); - /// extracts the files from a mimedata object that have a .py extension - QStringList extractPyFiles(const QList<QUrl> &urlList) const; - // Whether new plots shoul re-use the same plot instance (for every // different // type of plot). diff --git a/MantidPlot/src/Mantid/PeakPickerTool.cpp b/MantidPlot/src/Mantid/PeakPickerTool.cpp index f7bedc80dc1ea786f4b075b69efaf2b915c6f9ac..718608590cff6e8e22c5cb4de2912f005ac74dd9 100644 --- a/MantidPlot/src/Mantid/PeakPickerTool.cpp +++ b/MantidPlot/src/Mantid/PeakPickerTool.cpp @@ -1033,7 +1033,7 @@ bool PeakPickerTool::initializeFromCurve(PlotCurve *curve) { */ void PeakPickerTool::addExistingFitsAndGuess(const QStringList &curvesList) { bool hasGuess = false; - for (const auto curveName : curvesList) { + for (const auto &curveName : curvesList) { if (curveName.contains(QRegExp("Workspace-[Calc|Diff]"))) { // fit m_curveNames.append(curveName); } else if (curveName == "CompositeFunction") { // guess diff --git a/MantidPlot/src/Plot.cpp b/MantidPlot/src/Plot.cpp index 56846dad2031935f2218836a0264149b1d395879..c82c7f9de0a9b0f76dd2e9163feb2223b145c631 100644 --- a/MantidPlot/src/Plot.cpp +++ b/MantidPlot/src/Plot.cpp @@ -263,19 +263,19 @@ void Plot::drawInwardTicks(QPainter *painter, const QRect &rect, int y2 = rect.bottom(); QPalette pal = axisWidget(axis)->palette(); - QColor color = pal.color(QPalette::Active, QPalette::Foreground); + const QColor &color = pal.color(QPalette::Active, QPalette::Foreground); painter->save(); painter->setPen(QPen(color, axesLinewidth(), Qt::SolidLine)); const QwtScaleDiv *scDiv = (const QwtScaleDiv *)axisScaleDiv(axis); - const QwtValueList minTickList = scDiv->ticks(QwtScaleDiv::MinorTick); + const QwtValueList &minTickList = scDiv->ticks(QwtScaleDiv::MinorTick); int minTicks = (int)minTickList.count(); - const QwtValueList medTickList = scDiv->ticks(QwtScaleDiv::MediumTick); + const QwtValueList &medTickList = scDiv->ticks(QwtScaleDiv::MediumTick); int medTicks = (int)medTickList.count(); - const QwtValueList majTickList = scDiv->ticks(QwtScaleDiv::MajorTick); + const QwtValueList &majTickList = scDiv->ticks(QwtScaleDiv::MajorTick); int majTicks = (int)majTickList.count(); int j, x, y, low, high; diff --git a/MantidPlot/src/ProjectSaveView.cpp b/MantidPlot/src/ProjectSaveView.cpp index 5550bdc9cc9a40a42d5e46a56de11ec7fda6939c..2e661c1ca0c62933a29fee488a3858e38fbadeab 100644 --- a/MantidPlot/src/ProjectSaveView.cpp +++ b/MantidPlot/src/ProjectSaveView.cpp @@ -91,7 +91,7 @@ void ProjectSaveView::setProjectPath(const QString &path) { void ProjectSaveView::updateWorkspacesList( const std::vector<WorkspaceInfo> &workspaces) { m_ui.workspaceList->clear(); - for (auto info : workspaces) { + for (const auto &info : workspaces) { addWorkspaceItem(info); } // pad the header for longish workspace names @@ -108,7 +108,7 @@ void ProjectSaveView::updateWorkspacesList( void ProjectSaveView::updateIncludedWindowsList( const std::vector<WindowInfo> &windows) { m_ui.includedWindows->clear(); - for (auto info : windows) { + for (const auto &info : windows) { addWindowItem(m_ui.includedWindows, info); } @@ -125,7 +125,7 @@ void ProjectSaveView::updateIncludedWindowsList( void ProjectSaveView::updateExcludedWindowsList( const std::vector<WindowInfo> &windows) { m_ui.excludedWindows->clear(); - for (auto info : windows) { + for (const auto &info : windows) { addWindowItem(m_ui.excludedWindows, info); } @@ -138,7 +138,7 @@ void ProjectSaveView::updateExcludedWindowsList( */ void ProjectSaveView::removeFromIncludedWindowsList( const std::vector<std::string> &windows) { - for (auto name : windows) { + for (const auto &name : windows) { removeItem(m_ui.includedWindows, name); } } @@ -149,7 +149,7 @@ void ProjectSaveView::removeFromIncludedWindowsList( */ void ProjectSaveView::removeFromExcludedWindowsList( const std::vector<std::string> &windows) { - for (auto name : windows) { + for (const auto &name : windows) { removeItem(m_ui.excludedWindows, name); } } @@ -312,7 +312,7 @@ void ProjectSaveView::addWindowItem(QTreeWidget *widget, void ProjectSaveView::addWorkspaceItem(const WorkspaceInfo &info) { auto item = makeWorkspaceItem(info); - for (auto subInfo : info.subWorkspaces) { + for (const auto &subInfo : info.subWorkspaces) { auto subItem = makeWorkspaceItem(subInfo); item->addChild(subItem); } diff --git a/MantidPlot/src/PythonScripting.cpp b/MantidPlot/src/PythonScripting.cpp index eda2aa21c199aa5bfbd50a3ce215d1322789f7b3..f9787b465764f72664bfe9f04c5d5a9497622f72 100644 --- a/MantidPlot/src/PythonScripting.cpp +++ b/MantidPlot/src/PythonScripting.cpp @@ -291,7 +291,7 @@ PyObject *PythonScripting::toPyList(const QStringList &items) { Py_ssize_t length = static_cast<Py_ssize_t>(items.length()); PyObject *pylist = PyList_New((length)); for (Py_ssize_t i = 0; i < length; ++i) { - QString item = items.at(static_cast<int>(i)); + const QString &item = items.at(static_cast<int>(i)); PyList_SetItem(pylist, i, FROM_CSTRING(item.toAscii())); } return pylist; diff --git a/MantidPlot/src/ScaleDetails.cpp b/MantidPlot/src/ScaleDetails.cpp index 544ce7f9c70a891f458087de653ea58cc477422b..e7d3f9472876c5dd63474389b940d02733b42365 100644 --- a/MantidPlot/src/ScaleDetails.cpp +++ b/MantidPlot/src/ScaleDetails.cpp @@ -378,7 +378,7 @@ void ScaleDetails::initWidgets() { m_grpAxesBreaks->setEnabled(false); } - QwtValueList lst = scDiv->ticks(QwtScaleDiv::MajorTick); + const QwtValueList &lst = scDiv->ticks(QwtScaleDiv::MajorTick); m_spnMajorValue->setValue(lst.count()); checkstep(); diff --git a/MantidPlot/src/ScaleDraw.cpp b/MantidPlot/src/ScaleDraw.cpp index 430de554ed0b3f693c0d9abb5430d0f42e309b88..19b81c0a5b2afd685d8ec60700c09da7dae8b603 100644 --- a/MantidPlot/src/ScaleDraw.cpp +++ b/MantidPlot/src/ScaleDraw.cpp @@ -370,15 +370,15 @@ ScaleEngine *sc_engine =dynamic_cast< ScaleEngine*>(qwtsc_engine); } //} QwtScaleDiv scDiv = scaleDiv(); - QwtValueList majTicks = scDiv.ticks(QwtScaleDiv::MajorTick); + const QwtValueList &majTicks = scDiv.ticks(QwtScaleDiv::MajorTick); if (majTicks.contains(value) && (d_majTicks == In || d_majTicks == None)) return; - QwtValueList medTicks = scDiv.ticks(QwtScaleDiv::MediumTick); + const QwtValueList &medTicks = scDiv.ticks(QwtScaleDiv::MediumTick); if (medTicks.contains(value) && (d_minTicks == In || d_minTicks == None)) return; - QwtValueList minTicks = scDiv.ticks(QwtScaleDiv::MinorTick); + const QwtValueList &minTicks = scDiv.ticks(QwtScaleDiv::MinorTick); if (minTicks.contains(value) && (d_minTicks == In || d_minTicks == None)) return; diff --git a/MantidPlot/src/ScriptingWindow.cpp b/MantidPlot/src/ScriptingWindow.cpp index dac8874cd5c790bf5da7aaa62847af29ec7e89f8..367aa69276c857267ea3e95b997ad0367b7166a3 100644 --- a/MantidPlot/src/ScriptingWindow.cpp +++ b/MantidPlot/src/ScriptingWindow.cpp @@ -4,6 +4,7 @@ #include "ScriptingWindow.h" #include "ApplicationWindow.h" #include "MantidQtWidgets/Common/TSVSerialiser.h" +#include "MantidQtWidgets/Common/DropEventHelper.h" #include "MultiTabScriptInterpreter.h" #include "ScriptFileInterpreter.h" #include "ScriptingEnv.h" @@ -37,6 +38,7 @@ using namespace Mantid; using namespace MantidQt::API; +namespace DropEventHelper = MantidQt::MantidWidgets::DropEventHelper; namespace { /// static logger @@ -516,7 +518,8 @@ void ScriptingWindow::customEvent(QEvent *event) { void ScriptingWindow::dragEnterEvent(QDragEnterEvent *de) { const QMimeData *mimeData = de->mimeData(); if (mimeData->hasUrls()) { - if (extractPyFiles(mimeData->urls()).size() > 0) { + const auto pythonFilenames = DropEventHelper::extractPythonFiles(de); + if (!pythonFilenames.empty()) { de->acceptProposedAction(); } } @@ -529,7 +532,8 @@ void ScriptingWindow::dragEnterEvent(QDragEnterEvent *de) { void ScriptingWindow::dragMoveEvent(QDragMoveEvent *de) { const QMimeData *mimeData = de->mimeData(); if (mimeData->hasUrls()) { - if (extractPyFiles(mimeData->urls()).size() > 0) { + const auto pythonFilenames = DropEventHelper::extractPythonFiles(de); + if (!pythonFilenames.empty()) { de->accept(); } } @@ -542,11 +546,11 @@ void ScriptingWindow::dragMoveEvent(QDragMoveEvent *de) { void ScriptingWindow::dropEvent(QDropEvent *de) { const QMimeData *mimeData = de->mimeData(); if (mimeData->hasUrls()) { - QStringList filenames = extractPyFiles(mimeData->urls()); + const auto filenames = DropEventHelper::extractPythonFiles(de); de->acceptProposedAction(); - for (int i = 0; i < filenames.size(); ++i) { - m_manager->openInNewTab(filenames[i]); + for (const auto &name : filenames) { + m_manager->openInNewTab(name); } } } @@ -894,18 +898,3 @@ Script::ExecutionMode ScriptingWindow::getExecutionMode() const { else return Script::Serialised; } - -QStringList ScriptingWindow::extractPyFiles(const QList<QUrl> &urlList) const { - QStringList filenames; - for (int i = 0; i < urlList.size(); ++i) { - QString fName = urlList[i].toLocalFile(); - if (fName.size() > 0) { - QFileInfo fi(fName); - - if (fi.suffix().toUpper() == "PY") { - filenames.append(fName); - } - } - } - return filenames; -} diff --git a/MantidPlot/src/ScriptingWindow.h b/MantidPlot/src/ScriptingWindow.h index 3e7852897d9244fb845ff7de31ffb51933d15d03..09c9cb306881ed64e6b8a19ccf2a9cde4c2f5820 100644 --- a/MantidPlot/src/ScriptingWindow.h +++ b/MantidPlot/src/ScriptingWindow.h @@ -145,9 +145,6 @@ private: /// Returns the current execution mode Script::ExecutionMode getExecutionMode() const; - /// Extract py files from urllist - QStringList extractPyFiles(const QList<QUrl> &urlList) const; - private: /// The script editors' manager MultiTabScriptInterpreter *m_manager; diff --git a/MantidPlot/src/Spectrogram.cpp b/MantidPlot/src/Spectrogram.cpp index 09905880b925032282b7491964d056b37d2410f4..33266dd1249004bb9195d32d48f05835c60f82f6 100644 --- a/MantidPlot/src/Spectrogram.cpp +++ b/MantidPlot/src/Spectrogram.cpp @@ -39,6 +39,7 @@ #include "Mantid/MantidMatrix.h" #include "Mantid/MantidMatrixFunction.h" #include "MantidAPI/IMDIterator.h" +#include "MantidAPI/MatrixWorkspace.h" #include "MantidKernel/Strings.h" #include "MantidKernel/make_unique.h" #include "MantidQtWidgets/Common/PlotAxis.h" @@ -212,6 +213,34 @@ void Spectrogram::updateData( postDataUpdate(); } +/** + * Check all histograms in a matrix workspace to make sure that minX and maxX + * cover all x -values. + * @param workspace :: A workspace being plotted. + * @param minX :: The minimum value on the Spectrogram's x axis. Updated if + * workspace is ragged. + * @param maxX :: The maximum value on the Spectrogram's x axis. Updated if + * workspace is ragged. + */ +void Spectrogram::checkRaggedMatrixWorkspace( + const Mantid::API::Workspace *workspace, Mantid::coord_t &minX, + Mantid::coord_t &maxX) { + auto matrixWorkspace = + dynamic_cast<const Mantid::API::MatrixWorkspace *>(workspace); + if (matrixWorkspace) { + for (size_t iHisto = 0; iHisto < matrixWorkspace->getNumberHistograms(); + ++iHisto) { + const auto &x = matrixWorkspace->x(iHisto); + if (x.front() < minX) { + minX = static_cast<Mantid::coord_t>(x.front()); + } + if (x.back() > maxX) { + maxX = static_cast<Mantid::coord_t>(x.back()); + } + } + } +} + /** * Extracts data from workspace * @param workspace :: [input] Pointer to workspace @@ -230,6 +259,7 @@ MantidQt::API::QwtRasterDataMD *Spectrogram::dataFromWorkspace( // colour range QwtDoubleInterval fullRange = MantidQt::API::SignalRange(*workspace).interval(); + if (range) { wsData->setRange(*range); } else { @@ -240,6 +270,11 @@ MantidQt::API::QwtRasterDataMD *Spectrogram::dataFromWorkspace( auto dim1 = workspace->getDimension(1); Mantid::coord_t minX(dim0->getMinimum()), maxX(dim0->getMaximum()), minY(dim1->getMinimum()), maxY(dim1->getMaximum()); + + // A MatrixWorkspace can be ragged. Make sure the x axis covers all + // histograms. + checkRaggedMatrixWorkspace(workspace.get(), minX, maxX); + Mantid::coord_t dx(dim0->getBinWidth()), dy(dim1->getBinWidth()); const Mantid::coord_t width = (maxX - minX) + dx; const Mantid::coord_t height = (maxY - minY) + dy; diff --git a/MantidPlot/src/Spectrogram.h b/MantidPlot/src/Spectrogram.h index 96a58055aec1f5354f9a6e340126de8436284b22..d76b365914fc2aaebaa0e5a9412d2a060805f788 100644 --- a/MantidPlot/src/Spectrogram.h +++ b/MantidPlot/src/Spectrogram.h @@ -190,6 +190,8 @@ protected: const QwtScaleMap &yMap, const QwtRasterData::ContourLines &lines) const; void createLabels(); + void checkRaggedMatrixWorkspace(const Mantid::API::Workspace *workspace, + Mantid::coord_t &minX, Mantid::coord_t &maxX); //! Pointer to the source data matrix Matrix *d_matrix; diff --git a/MantidPlot/src/importOPJ.cpp b/MantidPlot/src/importOPJ.cpp index f32a11fcfeaf4c4548be1d89fe4216f8f94f6000..a041ae55b1d52d7ad6f7ea0d2f68337b570bf99c 100644 --- a/MantidPlot/src/importOPJ.cpp +++ b/MantidPlot/src/importOPJ.cpp @@ -1045,8 +1045,8 @@ bool ImportOPJ::importGraphs(const OPJFile &opj) { translateOrigin2QtiplotLineStyle(grids[3].style)))); grid->setAxis(2, 0); - grid->enableZeroLineX(0); - grid->enableZeroLineY(0); + grid->enableZeroLineX(false); + grid->enableZeroLineY(false); vector<graphAxisFormat> formats = opj.layerAxisFormat(g, l); vector<graphAxisTick> ticks = opj.layerAxisTickLabels(g, l); diff --git a/MantidPlot/src/origin/OPJFile.cpp b/MantidPlot/src/origin/OPJFile.cpp index 04a87560bb03df4c5522fb9cc4e818304acd5929..909798721d267f15432dc33a87139a9e2810988a 100644 --- a/MantidPlot/src/origin/OPJFile.cpp +++ b/MantidPlot/src/origin/OPJFile.cpp @@ -1260,7 +1260,7 @@ int OPJFile::ParseFormatNew() { //////////////////////// OBJECT INFOS ////////////////////////////////////// POS += 0xB; CHECKED_FSEEK(debug, f, POS, SEEK_SET); - while (1) { + while (true) { fprintf(debug, " reading Header\n"); fflush(debug); @@ -1311,7 +1311,7 @@ int OPJFile::ParseFormatNew() { CHECKED_FREAD(debug, &c, 1, 1, f); } CHECKED_FSEEK(debug, f, 1 + 5, SEEK_CUR); - while (1) { + while (true) { // fseek(f,5+0x40+1,SEEK_CUR); int size; CHECKED_FREAD(debug, &size, 4, 1, f); @@ -1444,7 +1444,7 @@ void OPJFile::readSpreadInfo(FILE *f, int file_size, FILE *debug) { // possible sections: column formulas, __WIPR, __WIOTN, __LayerInfoStorage // etc // section name(column name in formula case) starts with 0x46 position - while (1) { + while (true) { int sec_size; // section_header_size=0x6F(4 bytes) + '\n' LAYER += 0x5; @@ -1523,7 +1523,7 @@ void OPJFile::readSpreadInfo(FILE *f, int file_size, FILE *debug) { fprintf(debug, " Spreadsheet has %zu columns\n", SPREADSHEET[spread].column.size()); - while (1) { + while (true) { LAYER += 0x5; CHECKED_FSEEK(debug, f, LAYER + 0x12, SEEK_SET); CHECKED_FREAD(debug, &name, 12, 1, f); @@ -1683,7 +1683,7 @@ void OPJFile::readExcelInfo(FILE *f, int file_size, FILE *debug) { LAYER += headersize + 0x1; int sec_size; int isheet = 0; - while (1) // multisheet loop + while (true) // multisheet loop { // LAYER section LAYER += 0x5 /* length of block = 0x12D + '\n'*/ + 0x12D + 0x1; @@ -1694,7 +1694,7 @@ void OPJFile::readExcelInfo(FILE *f, int file_size, FILE *debug) { // possible sections: column formulas, __WIPR, __WIOTN, __LayerInfoStorage // etc // section name(column name in formula case) starts with 0x46 position - while (1) { + while (true) { // section_header_size=0x6F(4 bytes) + '\n' LAYER += 0x5; @@ -1769,7 +1769,7 @@ void OPJFile::readExcelInfo(FILE *f, int file_size, FILE *debug) { fprintf(debug, " Excel sheet %d has %zu columns\n", isheet, EXCEL[iexcel].sheet[isheet].column.size()); - while (1) { + while (true) { LAYER += 0x5; CHECKED_FSEEK(debug, f, LAYER + 0x12, SEEK_SET); CHECKED_FREAD(debug, &name, 12, 1, f); @@ -1990,7 +1990,7 @@ void OPJFile::readMatrixInfo(FILE *f, int file_size, FILE *debug) { // section_body_2 + '\n' // possible sections: column formulas, __WIPR, __WIOTN, __LayerInfoStorage // section name(column name in formula case) starts with 0x46 position - while (1) { + while (true) { // section_header_size=0x6F(4 bytes) + '\n' LAYER += 0x5; @@ -2053,7 +2053,7 @@ void OPJFile::readMatrixInfo(FILE *f, int file_size, FILE *debug) { } LAYER += 0x5; - while (1) { + while (true) { LAYER += 0x5; short width = 0; @@ -2140,7 +2140,7 @@ void OPJFile::readGraphInfo(FILE *f, int file_size, FILE *debug) { int LAYER = POS; LAYER += headersize + 0x1; int sec_size; - while (1) // multilayer loop + while (true) // multilayer loop { GRAPH.back().layer.push_back(graphLayer()); // LAYER section @@ -2206,7 +2206,7 @@ void OPJFile::readGraphInfo(FILE *f, int file_size, FILE *debug) { // possible sections: axes, legend, __BC02, _202, _231, _232, // __LayerInfoStorage etc // section name starts with 0x46 position - while (1) { + while (true) { // section_header_size=0x6F(4 bytes) + '\n' LAYER += 0x5; @@ -2505,7 +2505,7 @@ void OPJFile::readGraphInfo(FILE *f, int file_size, FILE *debug) { SwapBytes(sec_size); if (sec_size == 0x1E7) // check layer is not empty { - while (1) { + while (true) { LAYER += 0x5; graphCurve curve; @@ -2784,7 +2784,7 @@ void OPJFile::readGraphInfo(FILE *f, int file_size, FILE *debug) { LAYER += 0x5; // read axis breaks - while (1) { + while (true) { CHECKED_FSEEK(debug, f, LAYER, SEEK_SET); CHECKED_FREAD(debug, &sec_size, 4, 1, f); if (IsBigEndian()) @@ -2902,7 +2902,7 @@ void OPJFile::skipObjectInfo(FILE *f, FILE *fdebug) { int LAYER = POS; LAYER += headersize + 0x1; int sec_size; - while (1) // multilayer loop + while (true) // multilayer loop { // LAYER section LAYER += 0x5 /* length of block = 0x12D + '\n'*/ + 0x12D + 0x1; @@ -2912,7 +2912,7 @@ void OPJFile::skipObjectInfo(FILE *f, FILE *fdebug) { // section_body_2 + '\n' // possible sections: column formulas, __WIPR, __WIOTN, __LayerInfoStorage // section name(column name in formula case) starts with 0x46 position - while (1) { + while (true) { // section_header_size=0x6F(4 bytes) + '\n' LAYER += 0x5; @@ -2962,7 +2962,7 @@ void OPJFile::skipObjectInfo(FILE *f, FILE *fdebug) { } LAYER += 0x5; - while (1) { + while (true) { LAYER += 0x5; LAYER += 0x1E7 + 0x1; diff --git a/Testing/Data/UnitTest/IRIS_Definition_elastic.xml.md5 b/Testing/Data/UnitTest/IRIS_Definition_elastic.xml.md5 new file mode 100644 index 0000000000000000000000000000000000000000..4d01ea9c6e1543960a32b7f3b088c0ceb7d18a33 --- /dev/null +++ b/Testing/Data/UnitTest/IRIS_Definition_elastic.xml.md5 @@ -0,0 +1 @@ +10c94998a8bfd30573fe909dc29f4149 diff --git a/Testing/Data/UnitTest/OSIRIS_Definition_elastic.xml.md5 b/Testing/Data/UnitTest/OSIRIS_Definition_elastic.xml.md5 new file mode 100644 index 0000000000000000000000000000000000000000..2446af87367b60ab64fd7de599b9237d6b7503a9 --- /dev/null +++ b/Testing/Data/UnitTest/OSIRIS_Definition_elastic.xml.md5 @@ -0,0 +1 @@ +7f2b341bf3c39b9e891f3091675aa093 diff --git a/Testing/Data/UnitTest/QENSWorkspaceGroup.nxs.md5 b/Testing/Data/UnitTest/QENSWorkspaceGroup.nxs.md5 new file mode 100644 index 0000000000000000000000000000000000000000..16238b072fd3c0cc2229c6d8453610a8ceb59c7a --- /dev/null +++ b/Testing/Data/UnitTest/QENSWorkspaceGroup.nxs.md5 @@ -0,0 +1 @@ +c9aba3e8ef1f0e40c68f729f33a001c7 diff --git a/Testing/Data/UnitTest/osi104367_elf.nxs.md5 b/Testing/Data/UnitTest/osi104367_elf.nxs.md5 new file mode 100644 index 0000000000000000000000000000000000000000..2f375249098221f6e49f93ae1e8650afcc77daed --- /dev/null +++ b/Testing/Data/UnitTest/osi104367_elf.nxs.md5 @@ -0,0 +1 @@ +7b74bc1023e999dd29ea3ba26d09c3e7 diff --git a/Testing/SystemTests/tests/analysis/MuonFFTTest.py b/Testing/SystemTests/tests/analysis/MuonFFTTest.py index 69d791fbba997bce0f1ae26f01799be51cf30bc7..a32e4c0c8c4853c5218a6e821b040a1d6dbb229c 100644 --- a/Testing/SystemTests/tests/analysis/MuonFFTTest.py +++ b/Testing/SystemTests/tests/analysis/MuonFFTTest.py @@ -14,8 +14,8 @@ class MuonFFTTest(stresstesting.MantidStressTest): # create a PhaseTable with detector information tab = CreateEmptyTableWorkspace() tab.addColumn('int', 'DetID') - tab.addColumn('double', 'Phase') tab.addColumn('double', 'Asym') + tab.addColumn('double', 'Phase') for i in range(0,32): phi = 2*pi*i/32. tab.addRow([i + 1, 0.2, phi]) diff --git a/Testing/SystemTests/tests/analysis/VesuvioCorrectionsTest.py b/Testing/SystemTests/tests/analysis/VesuvioCorrectionsTest.py index 4e63718f9552f22677b9c392d41d257c34c98e27..a91e3fcfa216bc4efc236abf825bb7d0bc5c2314 100644 --- a/Testing/SystemTests/tests/analysis/VesuvioCorrectionsTest.py +++ b/Testing/SystemTests/tests/analysis/VesuvioCorrectionsTest.py @@ -483,16 +483,16 @@ class TestCorrectionsInBackScatteringSpectra(stresstesting.MantidStressTest): corrections_wsg = self._algorithm.getProperty("CorrectionWorkspaces").value _validate_group_structure(self, corrections_wsg, 3) corrections_ts_peak = 0.131359579675 - corrections_ms_peak = 0.00117365595751 + # corrections_ms_peak = 0.00117365595751 corrections_ts_bin = 701 - corrections_ms_bin = 690 - if _is_old_boost_version(): - corrections_ms_bin = 691 + # corrections_ms_bin = 690 + # if _is_old_boost_version(): + # corrections_ms_bin = 691 _validate_matrix_peak_height(self, corrections_wsg.getItem(1), corrections_ts_peak, corrections_ts_bin, tolerance=0.2, bin_tolerance=5) - _validate_matrix_peak_height(self, corrections_wsg.getItem(2), corrections_ms_peak, corrections_ms_bin, - tolerance=0.2, bin_tolerance=5) + # _validate_matrix_peak_height(self, corrections_wsg.getItem(2), corrections_ms_peak, corrections_ms_bin, + # tolerance=0.2, bin_tolerance=5) # Test Corrected Workspaces corrected_wsg = self._algorithm.getProperty("CorrectedWorkspaces").value diff --git a/buildconfig/CMake/VersionNumber.cmake b/buildconfig/CMake/VersionNumber.cmake index b1644ad3dcc209afe78ac6ec794a81965ec28329..6f9b49bbd6d76813989b9d2c57eadb03c7702829 100644 --- a/buildconfig/CMake/VersionNumber.cmake +++ b/buildconfig/CMake/VersionNumber.cmake @@ -1,7 +1,7 @@ # Set the version number here for MantidVersion and the package filenames set ( VERSION_MAJOR 3 ) -set ( VERSION_MINOR 10 ) +set ( VERSION_MINOR 11 ) # UNCOMMENT the next 'set' line to 'force' the patch version number to # a value (instead of using the count coming out of 'git describe') diff --git a/docs/source/algorithms/Abins-v1.rst b/docs/source/algorithms/Abins-v1.rst index c3bdecc5ced813ac41796b9e2e8e987b7ad8427e..afdba918ec56bd69ab5d63724c754082a71db4a5 100644 --- a/docs/source/algorithms/Abins-v1.rst +++ b/docs/source/algorithms/Abins-v1.rst @@ -53,7 +53,7 @@ Usage for name in benzene_wrk.getNames(): - print name + print(name) Output: @@ -71,7 +71,7 @@ Output: wrk=Abins(DFTProgram="CRYSTAL", PhononFile="b3lyp.out", QuantumOrderEventsNumber="1") for name in wrk.getNames(): - print name + print(name) Output: @@ -97,7 +97,7 @@ Output: QuantumOrderEventsNumber="1", ScaleByCrossSection="Incoherent") for name in wrk_verbose.getNames(): - print name + print(name) Output: diff --git a/docs/source/algorithms/AbsorptionCorrection-v1.rst b/docs/source/algorithms/AbsorptionCorrection-v1.rst index 8a79dfef66b416f82e30cc1a3fd39f3b31f784fe..a82143c2e74f5493e381568a5bb62cb8d8cab653 100644 --- a/docs/source/algorithms/AbsorptionCorrection-v1.rst +++ b/docs/source/algorithms/AbsorptionCorrection-v1.rst @@ -95,9 +95,9 @@ Usage wsOut = AbsorptionCorrection(ws, NumberOfWavelengthPoints=5, ElementSize=3) wsCorrected = ws / wsOut - print "The created workspace has one entry for each spectra: %i" % wsOut.getNumberHistograms() - print "Original y values: ", ws.readY(0) - print "Corrected y values: ", wsCorrected.readY(0) + print("The created workspace has one entry for each spectra: {}".format(wsOut.getNumberHistograms())) + print("Original y values: {}".format(ws.readY(0))) + print("Corrected y values: {}".format(wsCorrected.readY(0))) Output: diff --git a/docs/source/algorithms/AccumulateMD-v1.rst b/docs/source/algorithms/AccumulateMD-v1.rst index 90f931204ead23cb689f30053a06ed0d206b36ad..fdd1a6c4f81dbfbc87dc80a12205d3269f04aaf4 100644 --- a/docs/source/algorithms/AccumulateMD-v1.rst +++ b/docs/source/algorithms/AccumulateMD-v1.rst @@ -55,8 +55,8 @@ Usage acc_ws = AccumulateMD(md_ws, 'sample_data_1,sample_data_2,sample_data_3', Alatt=[1.4165, 1.4165, 1.4165], Angdeg=[90, 90, 90], u=[1, 0, 0,], v=[0,1,0]) # acc_ws should have double the number of events that md_ws has - print "There are {kwarg} events in each of the two data workspaces.".format(kwarg=md_ws.getNEvents()) - print "The accumulated data workspace contains {kwarg} events.".format(kwarg=acc_ws.getNEvents()) + print("There are {} events in each of the two data workspaces.".format(md_ws.getNEvents())) + print("The accumulated data workspace contains {} events.".format(acc_ws.getNEvents())) Output: diff --git a/docs/source/algorithms/AddLogDerivative-v1.rst b/docs/source/algorithms/AddLogDerivative-v1.rst index 1caeaa771d9d9e3e4b2b397702779803466b7638..c2880f978ff91702268d2ad8bbe7b11ec5f2cee0 100644 --- a/docs/source/algorithms/AddLogDerivative-v1.rst +++ b/docs/source/algorithms/AddLogDerivative-v1.rst @@ -41,8 +41,8 @@ Usage AddLogDerivative(ws,"MyLog",derivative=3,NewLogName="Derivative3") for logName in ["MyLog","Derivative1","Derivative2","Derivative3"]: - print "Log: " + logName - print ws.getRun().getProperty(logName).valueAsString() + print("Log: {}".format(logName)) + print(ws.getRun().getProperty(logName).valueAsString()) Output: diff --git a/docs/source/algorithms/AddNote-v1.rst b/docs/source/algorithms/AddNote-v1.rst index e3c4d0f9651553f3a05263ce39e26ab2cc56b5d0..1bf77157e838f85d068b29436956efe70d8b2246 100644 --- a/docs/source/algorithms/AddNote-v1.rst +++ b/docs/source/algorithms/AddNote-v1.rst @@ -30,17 +30,17 @@ Usage AddNote(ws, Name="my_log", Time="2014-01-01T00:50:00", Value="Final") log = ws.getRun().getLogData("my_log") - print "my_log has %i entries" % log.size() + print("my_log has {} entries".format(log.size())) for i in range(log.size()): - print "\t%s\t%s" %(log.times[i], log.value[i]) + print("\t{}\t{}".format(log.times[i], log.value[i])) AddNote(ws, Name="my_log", Time="2014-01-01T00:00:00", Value="New Initial", DeleteExisting=True) AddNote(ws, Name="my_log", Time="2014-01-01T00:30:00", Value="New Final") log = ws.getRun().getLogData("my_log") - print "my_log now has %i entries" %log.size() + print("my_log now has {} entries".format(log.size())) for i in range(log.size()): - print "\t%s\t%s" % (log.times[i], log.value[i]) + print("\t{}\t{}".format(log.times[i], log.value[i])) Output: diff --git a/docs/source/algorithms/AddPeak-v1.rst b/docs/source/algorithms/AddPeak-v1.rst index eed591b6ec01918afa5b11185c17fa9c8c683394..6dae159033cc423eb3875cc317cf424c8d2e07c2 100644 --- a/docs/source/algorithms/AddPeak-v1.rst +++ b/docs/source/algorithms/AddPeak-v1.rst @@ -22,11 +22,11 @@ Usage # Find the peaks in a 2D workspace. peaks_ws = FindSXPeaks(ws) - print "The number of peaks before adding a peak is: " + str(peaks_ws.getNumberPeaks()) + print("The number of peaks before adding a peak is: {}".format(peaks_ws.getNumberPeaks())) # Add a peak to the peaks workspace. AddPeak(PeaksWorkspace=peaks_ws,RunWorkspace=ws,DetectorID=101,TOF=3819,Height=10.3,BinCount=2) - print "The number of peaks after adding a peak is: " + str(peaks_ws.getNumberPeaks()) + print("The number of peaks after adding a peak is: {}".format(peaks_ws.getNumberPeaks())) Output: diff --git a/docs/source/algorithms/AddPeakHKL-v1.rst b/docs/source/algorithms/AddPeakHKL-v1.rst index 1f2cf615d04c638454ccb2eea3cddc4f7dcb46de..1a300f7f9218d0237554a125a69ce249b4a9fa22 100644 --- a/docs/source/algorithms/AddPeakHKL-v1.rst +++ b/docs/source/algorithms/AddPeakHKL-v1.rst @@ -44,10 +44,10 @@ Usage # Get info on newly added peak peak = peak_ws.getPeak(0) - print 'Peak wavelength', round(peak.getWavelength(), 4) - print 'Peak detector id', peak.getDetectorID() - print 'Peak run number', peak.getRunNumber() - print 'Peak HKL', peak.getHKL() + print('Peak wavelength {}'.format(round(peak.getWavelength(), 4))) + print('Peak detector id {}'.format(peak.getDetectorID())) + print('Peak run number {}'.format(peak.getRunNumber())) + print('Peak HKL {}'.format(peak.getHKL())) Output: diff --git a/docs/source/algorithms/AddSampleLog-v1.rst b/docs/source/algorithms/AddSampleLog-v1.rst index 91132333946dbc057e88a8e1ee006db108b71951..6cad3c0127071bca753c8aebee4939366f1a0ebb 100644 --- a/docs/source/algorithms/AddSampleLog-v1.rst +++ b/docs/source/algorithms/AddSampleLog-v1.rst @@ -53,9 +53,9 @@ Usage log_z = run.getLogData('z') # Print the log values - print log_x.value - print log_y.value - print log_z.value + print(log_x.value) + print(log_y.value) + print(log_z.value) Output: diff --git a/docs/source/algorithms/AddSampleLogMultiple-v1.rst b/docs/source/algorithms/AddSampleLogMultiple-v1.rst index 782f8f47f150a485ec161c92499e1005f041f896..0f445b1e1f7e083c475c900b4308af25470d19d6 100644 --- a/docs/source/algorithms/AddSampleLogMultiple-v1.rst +++ b/docs/source/algorithms/AddSampleLogMultiple-v1.rst @@ -34,9 +34,9 @@ Usage # Print the log values run = demo_ws.getRun() - print run.getLogData('x').value - print run.getLogData('y').value - print run.getLogData('z').value + print(run.getLogData('x').value) + print(run.getLogData('y').value) + print(run.getLogData('z').value) Output: diff --git a/docs/source/algorithms/AddTimeSeriesLog-v1.rst b/docs/source/algorithms/AddTimeSeriesLog-v1.rst index 571f064da895c4c22737d5aa4c965e276ef32cee..e96fdea285ed0db289f5277d5b4003f4c1975775 100644 --- a/docs/source/algorithms/AddTimeSeriesLog-v1.rst +++ b/docs/source/algorithms/AddTimeSeriesLog-v1.rst @@ -33,17 +33,17 @@ Usage AddTimeSeriesLog(ws, Name="my_log", Time="2010-01-01T00:50:00", Value=100.2) log = ws.getRun().getLogData("my_log") - print "my_log has %i entries" % log.size() + print("my_log has {} entries".format(log.size())) for i in range(log.size()): - print "\t%s\t%f" % (log.times[i], log.value[i]) + print("\t{}\t{:.6f}".format(log.times[i], log.value[i])) AddTimeSeriesLog(ws, Name="my_log", Time="2010-01-01T00:00:00", Value=12, Type="int", DeleteExisting=True) AddTimeSeriesLog(ws, Name="my_log", Time="2010-01-01T00:50:00", Value=34, Type="int") log = ws.getRun().getLogData("my_log") - print "my_log now has %i entries" % log.size() + print("my_log now has {} entries".format(log.size())) for i in range(log.size()): - print "\t%s\t%i" % (log.times[i], log.value[i]) + print("\t{}\t{}".format(log.times[i], log.value[i])) Output: diff --git a/docs/source/algorithms/AlignComponents-v1.rst b/docs/source/algorithms/AlignComponents-v1.rst index 86b823e1908db0dc6df25516888a6f79951b473d..cc15126ce789e3628d743a7b946873df455f0baa 100644 --- a/docs/source/algorithms/AlignComponents-v1.rst +++ b/docs/source/algorithms/AlignComponents-v1.rst @@ -70,7 +70,7 @@ Usage MakeMaskWorkspace=True, WorkspaceName="PG3") component="bank26" - print "Start position is",ws.getInstrument().getComponentByName(component).getPos() + print("Start position is {}".format(ws.getInstrument().getComponentByName(component).getPos())) AlignComponents(CalibrationTable="PG3_cal", Workspace=ws, MaskWorkspace="PG3_mask", @@ -78,7 +78,7 @@ Usage ComponentList=component) ws=mtd['ws'] final_pos = ws.getInstrument().getComponentByName(component).getPos() - print "Final position is [{:.2f}.{:.2f},{:.2f}]".format(final_pos[0],final_pos[1],final_pos[2]) + print("Final position is [{:.2f}.{:.2f},{:.2f}]".format(final_pos[0],final_pos[1],final_pos[2])) Output: @@ -101,8 +101,8 @@ Output: components="bank25,bank46" bank25Rot = ws.getInstrument().getComponentByName("bank25").getRotation().getEulerAngles() bank46Rot = ws.getInstrument().getComponentByName("bank46").getRotation().getEulerAngles() - print "Start bank25 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank25Rot[0], bank25Rot[1], bank25Rot[2]) - print "Start bank46 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank46Rot[0], bank46Rot[1], bank46Rot[2]) + print("Start bank25 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank25Rot[0], bank25Rot[1], bank25Rot[2])) + print("Start bank46 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank46Rot[0], bank46Rot[1], bank46Rot[2])) AlignComponents(CalibrationTable="PG3_cal", Workspace=ws, MaskWorkspace="PG3_mask", @@ -112,8 +112,8 @@ Output: ws=mtd['ws'] bank25Rot = ws.getInstrument().getComponentByName("bank25").getRotation().getEulerAngles() bank46Rot = ws.getInstrument().getComponentByName("bank46").getRotation().getEulerAngles() - print "Final bank25 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank25Rot[0], bank25Rot[1], bank25Rot[2]) - print "Final bank46 rotation is [{:.2f}.{:.3f},{:.3f}]".format(bank46Rot[0], bank46Rot[1], bank46Rot[2]) + print("Final bank25 rotation is [{:.3f}.{:.3f},{:.3f}]".format(bank25Rot[0], bank25Rot[1], bank25Rot[2])) + print("Final bank46 rotation is [{:.2f}.{:.3f},{:.3f}]".format(bank46Rot[0], bank46Rot[1], bank46Rot[2])) Output: @@ -138,13 +138,13 @@ Output: # Mask banks that don't have calibration data MaskBTP(Workspace='PG3_mask', Instrument='POWGEN', Bank='22-25,42-45,62-66,82-86,102-105,123,124,143,144,164,184,204') - print "Start sample position is",ws.getInstrument().getSample().getPos().getZ() + print("Start sample position is {}".format(ws.getInstrument().getSample().getPos().getZ())) AlignComponents(CalibrationTable="PG3_cal", Workspace=ws, MaskWorkspace="PG3_mask", FitSamplePosition=True, Zposition=True) - print "Final sample position is {:.3f}".format(mtd['ws'].getInstrument().getSample().getPos().getZ()) + print("Final sample position is {:.3f}".format(mtd['ws'].getInstrument().getSample().getPos().getZ())) Output: diff --git a/docs/source/algorithms/AlignDetectors-v1.rst b/docs/source/algorithms/AlignDetectors-v1.rst index 0321de98c6705fe4245cf8d70811f2212a5c16c5..74b8560ef5d0952a6952ace13da3bb837c452868 100644 --- a/docs/source/algorithms/AlignDetectors-v1.rst +++ b/docs/source/algorithms/AlignDetectors-v1.rst @@ -71,8 +71,8 @@ Usage offset = GetDetectorOffsets(InputWorkspace='wsD', DReference=2.5, XMin=2, XMax=3) wsA = AlignDetectors(InputWorkspace='ws', OutputWorkspace='wsA', OffsetsWorkspace='offset') maxA = Max(wsA) - print "Peak in dSpace", maxD.readX(0)[0] - print "Peak from calibration", maxA.readX(0)[0] + print("Peak in dSpace {:.11f}".format(maxD.readX(0)[0])) + print("Peak from calibration {:.10f}".format(maxA.readX(0)[0])) Output: diff --git a/docs/source/algorithms/AlphaCalc-v1.rst b/docs/source/algorithms/AlphaCalc-v1.rst index 91e3ecd78ed5398100a7694e7255a90fc23af9d5..10bea530d19f43f4cc8a4918ad82c9b07c5649bd 100644 --- a/docs/source/algorithms/AlphaCalc-v1.rst +++ b/docs/source/algorithms/AlphaCalc-v1.rst @@ -31,7 +31,7 @@ Usage alpha = AlphaCalc(input) - print 'Alpha value: {0:.3f}'.format(alpha) + print('Alpha value: {0:.3f}'.format(alpha)) Output: @@ -51,7 +51,7 @@ Output: ForwardSpectra=[2], BackwardSpectra=[1]) - print 'Alpha value: {0:.3f}'.format(alpha) + print('Alpha value: {0:.3f}'.format(alpha)) Output: diff --git a/docs/source/algorithms/AnnularRingAbsorption-v1.rst b/docs/source/algorithms/AnnularRingAbsorption-v1.rst index 6654ca05813362a363f701ad81c8af69687bd61d..6fcc2deab208f817866d3d8bc3a0a262eaed9def 100644 --- a/docs/source/algorithms/AnnularRingAbsorption-v1.rst +++ b/docs/source/algorithms/AnnularRingAbsorption-v1.rst @@ -38,8 +38,8 @@ Usage SampleChemicalFormula="Li2-Ir-O3",SampleNumberDensity=0.004813, EventsPerPoint=300) - print "The created workspace has one entry for each spectra: %i" % factors.getNumberHistograms() - print "Just divide your data by the correction to correct for absorption." + print("The created workspace has one entry for each spectra: {}".format(factors.getNumberHistograms())) + print("Just divide your data by the correction to correct for absorption.") Output: diff --git a/docs/source/algorithms/AppendSpectra-v1.rst b/docs/source/algorithms/AppendSpectra-v1.rst index 1b99faa99dfd2c5820c15dda43c6cc6190e94ca5..9a7151955ee62523befb1eecabf52a4de944c38d 100644 --- a/docs/source/algorithms/AppendSpectra-v1.rst +++ b/docs/source/algorithms/AppendSpectra-v1.rst @@ -58,9 +58,9 @@ Usage ws = CreateSampleWorkspace(BankPixelWidth=1) ws2 = CreateSampleWorkspace(BankPixelWidth=2) for wsLoop in [ws,ws2]: - print "Workspace '%s' has %i spectra beforehand" % (wsLoop, wsLoop.getNumberHistograms()) + print("Workspace '{}' has {} spectra beforehand".format(wsLoop, wsLoop.getNumberHistograms())) wsOut = AppendSpectra(ws, ws2) - print "Workspace '%s' has %i spectra after AppendSpectra" % (wsOut, wsOut.getNumberHistograms()) + print("Workspace '{}' has {} spectra after AppendSpectra".format(wsOut, wsOut.getNumberHistograms())) Output: @@ -78,9 +78,9 @@ Output: ws = CreateSampleWorkspace(BankPixelWidth=1) ws2 = CreateSampleWorkspace(BankPixelWidth=1) for wsLoop in [ws,ws2]: - print "Workspace '%s' has %i spectra beforehand" % (wsLoop, wsLoop.getNumberHistograms()) + print("Workspace '{}' has {} spectra beforehand".format(wsLoop, wsLoop.getNumberHistograms())) wsOut = AppendSpectra(ws, ws2, Number=4) - print "Workspace '%s' has %i spectra after AppendSpectra" % (wsOut, wsOut.getNumberHistograms()) + print("Workspace '{}' has {} spectra after AppendSpectra".format(wsOut, wsOut.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/ApplyCalibration-v1.rst b/docs/source/algorithms/ApplyCalibration-v1.rst index 6a3693e36ece70ff89cdef65b6e39f6b5dd7baeb..44f4c7933996d02212a769c755923e6fde13b11e 100644 --- a/docs/source/algorithms/ApplyCalibration-v1.rst +++ b/docs/source/algorithms/ApplyCalibration-v1.rst @@ -37,8 +37,8 @@ Usage # Show positions before calibration for i in spectra: det = ws.getDetector(i) - print "Position of Detector ID=%i before ApplyCalibration: %.0f,%.0f,%.0f" % (det.getID(), - det.getPos().X(), det.getPos().Y(), det.getPos().Z()) + print("Position of Detector ID=%i before ApplyCalibration: %.0f,%.0f,%.0f" % (det.getID(), + det.getPos().X(), det.getPos().Y(), det.getPos().Z())) # Create PositionTable - This would be done by the calibration functions @@ -60,8 +60,8 @@ Usage # Show positions after calibration for i in spectra: det = ws.getDetector(i) - print "Position of Detector ID=%i after ApplyCalibration: %.0f,%.0f,%.0f" % (det.getID(), - det.getPos().X(), det.getPos().Y(), det.getPos().Z()) + print("Position of Detector ID=%i after ApplyCalibration: %.0f,%.0f,%.0f" % (det.getID(), + det.getPos().X(), det.getPos().Y(), det.getPos().Z())) Output: diff --git a/docs/source/algorithms/ApplyDeadTimeCorr-v1.rst b/docs/source/algorithms/ApplyDeadTimeCorr-v1.rst index 38936b5701a20f8fd26d1bffe6178a1f50e272c6..3234aa9f0e9bf83feaae370eb4a85f61ae8434b1 100644 --- a/docs/source/algorithms/ApplyDeadTimeCorr-v1.rst +++ b/docs/source/algorithms/ApplyDeadTimeCorr-v1.rst @@ -66,7 +66,7 @@ Usage format_str = 'Spectrum: {0:d}; original: {1:.3f}; corrected: {2:.3f}' for s in [0,32,63]: - print format_str.format(s, original.readY(s)[0], corrected.readY(s)[0]) + print(format_str.format(s, original.readY(s)[0], corrected.readY(s)[0])) Output: @@ -95,7 +95,7 @@ Output: format_str = 'Spectrum: {0:d}; original: {1:.3f}; corrected: {2:.3f}' for s in [0,32,63]: - print format_str.format(s, original.readY(s)[0], corrected.readY(s)[0]) + print(format_str.format(s, original.readY(s)[0], corrected.readY(s)[0])) Output: diff --git a/docs/source/algorithms/ApplyDetailedBalance-v1.rst b/docs/source/algorithms/ApplyDetailedBalance-v1.rst index 0c7cc314d93d6a230d4effe5f995a3496ee5951d..2b9603ffc68e68aae14b499b5210ef8b26619a0a 100644 --- a/docs/source/algorithms/ApplyDetailedBalance-v1.rst +++ b/docs/source/algorithms/ApplyDetailedBalance-v1.rst @@ -37,9 +37,9 @@ Usage ws = CreateWorkspace(DataX='-5,-4,-3,-2,-1,0,1,2,3,4,5',DataY='2,2,2,2,2,2,2,2,2,2',DataE='1,1,1,1,1,1,1,1,1,1',UnitX='DeltaE') ows = ApplyDetailedBalance(InputWorkspace='ws',OutputWorkspace='ows',Temperature='100', OutputUnits='Frequency') - print "The Y values in the Output Workspace are" - print str(ows.readY(0)[0:5]) - print str(ows.readY(0)[5:10]) + print("The Y values in the Output Workspace are") + print(ows.readY(0)[0:5]) + print(ows.readY(0)[5:10]) Output: diff --git a/docs/source/algorithms/ApplyPaalmanPingsCorrection-v1.rst b/docs/source/algorithms/ApplyPaalmanPingsCorrection-v1.rst index 9628594dc0fe64b6e6b41b18a4f4ee851d5dca1c..19cf71884ad6c95476c66e269013ad0a782ba698 100644 --- a/docs/source/algorithms/ApplyPaalmanPingsCorrection-v1.rst +++ b/docs/source/algorithms/ApplyPaalmanPingsCorrection-v1.rst @@ -136,11 +136,9 @@ Usage CorrectionsWorkspace=corrections_ws, CanWorkspace=can_ws) - print 'Corrected workspace has %d spectra over %d bins' % ( - corr.getNumberHistograms(), corr.blocksize()) + print('Corrected workspace has {} spectra over {} bins'.format(corr.getNumberHistograms(), corr.blocksize())) - print 'Type of correction applied: %s' % ( - corr.getRun()['corrections_type'].value) + print('Type of correction applied: {}'.format(corr.getRun()['corrections_type'].value)) Output: diff --git a/docs/source/algorithms/AsymmetryCalc-v1.rst b/docs/source/algorithms/AsymmetryCalc-v1.rst index c7dc8224585f24458fe239868109a0998644543b..311e2821e3cc7c8ec61f024f076cfc9997dd3ae2 100644 --- a/docs/source/algorithms/AsymmetryCalc-v1.rst +++ b/docs/source/algorithms/AsymmetryCalc-v1.rst @@ -46,8 +46,8 @@ Usage asymmetry = AsymmetryCalc(input, Alpha=0.5) - print 'Asymmetry:', asymmetry.readY(0) - print 'Errors:', asymmetry.readE(0) + print('Asymmetry: {}'.format(asymmetry.readY(0))) + print('Errors: {}'.format(asymmetry.readE(0))) Output: diff --git a/docs/source/algorithms/AverageLogData-v1.rst b/docs/source/algorithms/AverageLogData-v1.rst index 336134c890fbd444dec47c5f0a58f90cd95df79a..a987825908e6aad802ff5ff565c38c1aa7764603 100644 --- a/docs/source/algorithms/AverageLogData-v1.rst +++ b/docs/source/algorithms/AverageLogData-v1.rst @@ -32,7 +32,7 @@ Usage value,error=AverageLogData(ws,LogName="ChopperStatus5") #print the values - print "ChopperStatus5 : %1.3f +/- %1.3f"%(value,error) + print("ChopperStatus5 : %1.3f +/- %1.3f"%(value,error)) .. testcleanup:: AverageLogData diff --git a/docs/source/algorithms/Bin2DPowderDiffraction-v1.rst b/docs/source/algorithms/Bin2DPowderDiffraction-v1.rst index 5bfa3e41cab53c0cb23d090d829a80970c174d4a..32317820bc9db3d987805174dfe864834bc2dcf5 100644 --- a/docs/source/algorithms/Bin2DPowderDiffraction-v1.rst +++ b/docs/source/algorithms/Bin2DPowderDiffraction-v1.rst @@ -100,10 +100,10 @@ Usage wsOutNorm = Bin2DPowderDiffraction(wsIn, dSpaceBinning="2,2,6", dPerpendicularBinning="1,2,5", NormalizeByBinArea=True) # Print the result - print "Y values without normalization:" - print wsOut.extractY() - print "Y values with normalization by bin area:" - print wsOutNorm.extractY() + print("Y values without normalization:") + print(wsOut.extractY()) + print("Y values with normalization by bin area:") + print(wsOutNorm.extractY()) Output: diff --git a/docs/source/algorithms/BinMD-v1.rst b/docs/source/algorithms/BinMD-v1.rst index b012a7ee483eb2031a83a7d26992bb1a565fcadf..d55794cbcd476111f9d4678bf0d26b62ed428e7f 100644 --- a/docs/source/algorithms/BinMD-v1.rst +++ b/docs/source/algorithms/BinMD-v1.rst @@ -116,7 +116,7 @@ Usage mdws = CreateMDWorkspace(Dimensions=3, Extents='-10,10,-10,10,-10,10', Names='A,B,C', Units='U,U,U') FakeMDEventData(InputWorkspace=mdws, PeakParams='500000,0,0,0,3') binned_ws = BinMD(InputWorkspace=mdws, AlignedDim0='A,0,10,100', AlignedDim1='B,-10,10,100', AlignedDim2='C,-10,10,100') - print "Number of events =", binned_ws.getNEvents() + print("Number of events = {}".format(binned_ws.getNEvents())) Output: @@ -139,7 +139,7 @@ The output looks like the following in the `SliceViewer <http://www.mantidprojec FakeMDEventData(InputWorkspace=mdws, PeakParams='100000,0,0,0,1') FakeMDEventData(InputWorkspace=mdws, PeakParams='100000,5,5,0,1') binned_ws = BinMD(InputWorkspace=mdws, AxisAligned=False, BasisVector0='a,unit,1,1,0',BasisVector1='b,unit,-1,1,0',BasisVector2='c,unit,0,0,1',NormalizeBasisVectors=True,Translation=[-10,-10,0], OutputExtents=[0,math.sqrt(2*20*20),-2,2,-10,10], OutputBins=[100, 100, 1] ) - print "Number of events =", binned_ws.getNEvents() + print("Number of events = {}".format(binned_ws.getNEvents())) Output: @@ -161,7 +161,7 @@ The output looks like the following in the `SliceViewer <http://www.mantidprojec mdws = CreateMDWorkspace(Dimensions=2, Extents='-10,10,-10,10', Names='A,B', Units='U,U') FakeMDEventData(InputWorkspace=mdws, PeakParams='500000,'+str(x)+',0,3') binned_ws = BinMD(InputWorkspace=mdws, AlignedDim0='A,-10,10,100', AlignedDim1='B,-10,10,100', TemporaryDataWorkspace=binned_ws) - print "Number of events =", binned_ws.getNEvents() + print("Number of events = {}".format(binned_ws.getNEvents())) Output: diff --git a/docs/source/algorithms/BinWidthAtX-v1.rst b/docs/source/algorithms/BinWidthAtX-v1.rst index f7753cee2003a3fb03753be3e627c45a9abb420f..9d65bc04234a63f50605ce9a74ffa879634c32ec 100644 --- a/docs/source/algorithms/BinWidthAtX-v1.rst +++ b/docs/source/algorithms/BinWidthAtX-v1.rst @@ -50,9 +50,9 @@ Usage return (first, last) first, last = firstAndLastBinWidths(ws) - print('Bin widths before rebinning, first: {0}, last: {1}'.format(first, last)) + print('Bin widths before rebinning, first: {0:.4f}, last: {1:.4f}'.format(first, last)) first, last = firstAndLastBinWidths(rebinned) - print('Bin widths after rebinning, first: {0}, last: {1}'.format(first, last)) + print('Bin widths after rebinning, first: {0:.2f}, last: {1:.2f}'.format(first, last)) Output: diff --git a/docs/source/algorithms/BinaryOperateMasks-v1.rst b/docs/source/algorithms/BinaryOperateMasks-v1.rst index 80dc0851fb4cd3e0a5652304ecbe0e438bf297d3..c8b284618f9d717db99792b08265fc710c132f4c 100644 --- a/docs/source/algorithms/BinaryOperateMasks-v1.rst +++ b/docs/source/algorithms/BinaryOperateMasks-v1.rst @@ -48,9 +48,9 @@ Usage # Run using XOR _xor = BinaryOperateMasks(a, b, OperationType='XOR') - print _and.readY(0) - print _or.readY(0) - print _xor.readY(0) + print(_and.readY(0)) + print(_or.readY(0)) + print(_xor.readY(0)) Output: diff --git a/docs/source/algorithms/CalMuonDeadTime-v1.rst b/docs/source/algorithms/CalMuonDeadTime-v1.rst index 0c52d11f0e6e3909881271e66e0febb236c3f6e5..25e721cd2a81a3c2b5edc454728566b926723fcb 100644 --- a/docs/source/algorithms/CalMuonDeadTime-v1.rst +++ b/docs/source/algorithms/CalMuonDeadTime-v1.rst @@ -46,9 +46,9 @@ Usage #CalMuonDeadTime outputs two workspaces so catch them both (wsOut,wsFitted) = CalMuonDeadTime('ws_1') - print ("First five dead times:") + print("First five dead times:") for i in range(5): - print (" Spectrum %i -> %.4f" % (wsOut.column(0)[i],wsOut.column(1)[i])) + print(" Spectrum {} -> {:.4f}".format(wsOut.column(0)[i], wsOut.column(1)[i])) Output: diff --git a/docs/source/algorithms/CalMuonDetectorPhases-v1.rst b/docs/source/algorithms/CalMuonDetectorPhases-v1.rst index 71621b133169b96e57c859112c27e784d2999082..756d448a06212dcfb9432e031d1f806fbf154420 100644 --- a/docs/source/algorithms/CalMuonDetectorPhases-v1.rst +++ b/docs/source/algorithms/CalMuonDetectorPhases-v1.rst @@ -13,7 +13,7 @@ Description Calculates detector asymmetries and phases from a reference dataset. The algorithm fits each of the spectra in the input workspace to: -.. math:: f_i(t) = A_i \sin\left(\omega t + \phi_i\right) +.. math:: f_i(t) = A_i \cos\left(\omega t + \phi_i\right) where :math:`\omega` is shared across spectra and :math:`A_i` and :math:`\phi_i` are detector-dependent. @@ -58,16 +58,16 @@ Usage # Print the result for i in range(0,4): - print "Detector %i has phase %f and amplitude %f" % (detectorTable.cell(i,0), detectorTable.cell(i,2), detectorTable.cell(i,1)) + print("Detector {} has phase {:.6f} and amplitude {:.6f}".format(detectorTable.cell(i,0), detectorTable.cell(i,2), detectorTable.cell(i,1))) Output: .. testoutput:: CalMuonDetectorPhasesExample - Detector 1 has phase 0.620299 and amplitude 0.133113 - Detector 2 has phase 0.399003 and amplitude 0.134679 - Detector 3 has phase 0.214079 and amplitude 0.149431 - Detector 4 has phase 0.086315 and amplitude 0.152870 + Detector 1 has phase 5.332568 and amplitude 0.133112 + Detector 2 has phase 5.111274 and amplitude 0.134679 + Detector 3 has phase 4.926346 and amplitude 0.149430 + Detector 4 has phase 4.798584 and amplitude 0.152869 .. categories:: diff --git a/docs/source/algorithms/CalculateChiSquared-v1.rst b/docs/source/algorithms/CalculateChiSquared-v1.rst index 922343f84c3d269504815376d5d5460c94f316bc..03ba5e7f4a095c957738d4b764a31cdccd7614c1 100644 --- a/docs/source/algorithms/CalculateChiSquared-v1.rst +++ b/docs/source/algorithms/CalculateChiSquared-v1.rst @@ -82,13 +82,12 @@ Usage # Calculate the chi squared chi2,chi2dof,chi2ndata,chi2W,chi2Wdof,chi2Wndata = CalculateChiSquared(func,ws) - print 'Chi squared is %s' % chi2 - print 'Chi squared / DOF is %s' % chi2dof - print 'Chi squared / NDATA is %s' % chi2ndata - print 'Chi squared weighted is %s' % chi2W - print 'Chi squared weighted / DOF is %s' % chi2Wdof - print 'Chi squared weighted / NDATA is %s' % chi2Wndata - print + print('Chi squared is {:.13f}'.format(chi2)) + print('Chi squared / DOF is {:.14f}'.format(chi2dof)) + print('Chi squared / NDATA is {:.14f}'.format(chi2ndata)) + print('Chi squared weighted is {:.11f}'.format(chi2W)) + print('Chi squared weighted / DOF is {:.14f}'.format(chi2Wdof)) + print('Chi squared weighted / NDATA is {:.12f}'.format(chi2Wndata)) # Define a function that models the data exactly func = 'name=LinearBackground,A0=1.0,A1=2.0' @@ -96,12 +95,12 @@ Usage # Calculate the chi squared chi2,chi2dof,chi2ndata,chi2W,chi2Wdof,chi2Wndata = CalculateChiSquared(func,ws) - print 'Chi squared is %s' % chi2 - print 'Chi squared / DOF is %s' % chi2dof - print 'Chi squared / NDATA is %s' % chi2ndata - print 'Chi squared weighted is %s' % chi2W - print 'Chi squared weighted / DOF is %s' % chi2Wdof - print 'Chi squared weighted / NDATA is %s' % chi2Wndata + print('Chi squared is {:.1f}'.format(chi2)) + print('Chi squared / DOF is {:.1f}'.format(chi2dof)) + print('Chi squared / NDATA is {:.1f}'.format(chi2ndata)) + print('Chi squared weighted is {:.1f}'.format(chi2W)) + print('Chi squared weighted / DOF is {:.1f}'.format(chi2Wdof)) + print('Chi squared weighted / NDATA is {:.1f}'.format(chi2Wndata)) Output: @@ -110,10 +109,9 @@ Output: Chi squared is 0.0351851851852 Chi squared / DOF is 0.00439814814815 Chi squared / NDATA is 0.00351851851852 - Chi squared weighted is 0.0266028783977 + Chi squared weighted is 0.02660287840 Chi squared weighted / DOF is 0.00332535979971 - Chi squared weighted / NDATA is 0.00266028783977 - + Chi squared weighted / NDATA is 0.002660287840 Chi squared is 0.0 Chi squared / DOF is 0.0 Chi squared / NDATA is 0.0 diff --git a/docs/source/algorithms/CalculateCostFunction-v1.rst b/docs/source/algorithms/CalculateCostFunction-v1.rst index f39c80d5a0d0f21ba7015e31f565e4a8f9ffaef3..5bd9729208ffae7a40ed0b370b07cec32e5d58ae 100644 --- a/docs/source/algorithms/CalculateCostFunction-v1.rst +++ b/docs/source/algorithms/CalculateCostFunction-v1.rst @@ -32,11 +32,11 @@ Usage # Calculate the chi squared by default value = CalculateCostFunction(func, ws) - print 'Value of least squares is %s' % value + print('Value of least squares is {:.13f}'.format(value)) # Calculate the unweighted least squares value = CalculateCostFunction(func, ws, CostFunction='Unweighted least squares') - print 'Value of unweighted least squares is %s' % value + print('Value of unweighted least squares is {:.13f}'.format(value)) Output: diff --git a/docs/source/algorithms/CalculateCountRate-v1.rst b/docs/source/algorithms/CalculateCountRate-v1.rst index aa2594fd123fab05c02be9c22cf98472e142a981..acdaee775c530e1c45455cf0ab4a4c6e2cb0a6d5 100644 --- a/docs/source/algorithms/CalculateCountRate-v1.rst +++ b/docs/source/algorithms/CalculateCountRate-v1.rst @@ -57,20 +57,20 @@ Usage # no rate log found: rez = CheckForSampleLogs(LogTest,log_name) - print ("Initially, {0}".format(rez)) + print("Initially, {0}".format(rez)) # calculate number of events in the workspace CalculateCountRate(LogTest,CountRateLogName= log_name) rez = CheckForSampleLogs(LogTest,log_name) if len(rez)==0: - print ("The Algorithm produced log: {0}".format(log_name)) + print("The Algorithm produced log: {0}".format(log_name)) log = LogTest.run().getLogData(log_name) - print ("log {0} contains {1} entries".format(log_name,log.size())) - print ("log starts at {0} and records value: {1}".format(log.firstTime(),log.firstValue())) - print ("log ends at {0} and records value: {1}".format(log.lastTime(),log.lastValue())) + print("log {0} contains {1} entries".format(log_name, log.size())) + print("log starts at {0} and records value: {1}".format(log.firstTime(), log.firstValue())) + print("log ends at {0} and records value: {1}".format(log.lastTime(), log.lastValue())) else: - print ("{0}".format(rez)) + print("{0}".format(rez)) .. testoutput:: ExCalcCountRate diff --git a/docs/source/algorithms/CalculateCoverageDGS-v1.rst b/docs/source/algorithms/CalculateCoverageDGS-v1.rst index 49d9acb5dd5027bc584204ee0dfdf116e348587a..bc56890b804b2696b7e249c0c58e9ffb128279e9 100644 --- a/docs/source/algorithms/CalculateCoverageDGS-v1.rst +++ b/docs/source/algorithms/CalculateCoverageDGS-v1.rst @@ -48,7 +48,7 @@ Usage Dimension4Min=0, Dimension4Max=3, Dimension4Step=0.1) # Print the result - print "You cover %i MD bins out of %i" %(coverage.getSignalArray().sum(),coverage.getSignalArray().size) + print("You cover {:.0f} MD bins out of {}".format(coverage.getSignalArray().sum(),coverage.getSignalArray().size)) Output: diff --git a/docs/source/algorithms/CalculateDIFC-v1.rst b/docs/source/algorithms/CalculateDIFC-v1.rst index abf9420e861b7302a687a7036a567560d1505a79..fa6df9c66a9ae2bd6b56e550e0d54c83fa70833c 100644 --- a/docs/source/algorithms/CalculateDIFC-v1.rst +++ b/docs/source/algorithms/CalculateDIFC-v1.rst @@ -36,8 +36,8 @@ Usage ws = CalculateDIFC(ws, OutputWorkspace="ws") # Print the result - print "The output workspace has %i spectra" % ws.getNumberHistograms() - print "DIFC of pixel %i is %1.f" % (100, ws.readY(100)[0]) + print("The output workspace has {} spectra".format(ws.getNumberHistograms())) + print("DIFC of pixel {} is {:.0f}".format(100, ws.readY(100)[0])) Output: diff --git a/docs/source/algorithms/CalculateFlatBackground-v1.rst b/docs/source/algorithms/CalculateFlatBackground-v1.rst index a947c75fa0e0f36a7a2cb0037fbe324920877fed..10195afcb26a7ef69f092ce3a47ac917002ddd32 100644 --- a/docs/source/algorithms/CalculateFlatBackground-v1.rst +++ b/docs/source/algorithms/CalculateFlatBackground-v1.rst @@ -42,7 +42,7 @@ Usage Mode='Linear Fit', OutputMode='Subtract Background') - print 'Values with subtracted background:', np.around(output.readY(0)) + print('Values with subtracted background: {}'.format(np.around(output.readY(0)))) Output: @@ -70,9 +70,9 @@ Output: # 3 (even negative!). By default, NullifyNegativeValues will be set # to true, and subtracting the output from the input workspace will # set these bins to zero. - print 'Calculated Mean background:', np.around(output.readY(0)) + print('Calculated Mean background: {}'.format(np.around(output.readY(0)))) subtracted = input - output - print 'Background subtracted:', np.around(subtracted.readY(0)) + print('Background subtracted: {}'.format(np.around(subtracted.readY(0)))) Output: diff --git a/docs/source/algorithms/CalculateMonteCarloAbsorption-v1.rst b/docs/source/algorithms/CalculateMonteCarloAbsorption-v1.rst new file mode 100644 index 0000000000000000000000000000000000000000..5a5e85e049c3d461fc0e73c8a55fa55aef8cbdb1 --- /dev/null +++ b/docs/source/algorithms/CalculateMonteCarloAbsorption-v1.rst @@ -0,0 +1,99 @@ +.. algorithm:: + +.. summary:: + +.. alias:: + +.. properties:: + + +Description +----------- + +This algorithm calculates the absorption factors, required for the Paalman Pings method of absorption corrections, using a Monte Carlo procedure. Currently only the acc and ass factors are calculated. + +CalculateMonteCarloAbsorption subsequently calls the :ref:`algm-SimpleShapeMonteCarloAbsorption` algorithm for the calculation of each absorption factor. + +There are three existing Shape Options: *Flat Plate*, *Annulus* and *Cylinder*. Each shape is defined by a different set of geometric parameters. + +Flat Plate parameters: *SampleThickness* and *SampleWidth* for the Sample, *ContainerFrontThickness* and *ContainerBackThickness* for the container. +Annulus parameters: *SampleInnerRadius* and *SampleOuterRadius* for the Sample, *ContainerInnerRadius* and *ContainerOuterRadius* for the container. +Cylinder parameters: *SampleRadius* for the sample, *ContainerInnerRadius* and *ContainerOuterRadius* for the container. + +The location and orientation of the sample can be defined with *SampleCenter* and *SampleAngle*. + + +Workflow +-------- + +.. diagram:: CalculateMonteCarloAbsorption-v1_wkflw.dot + + +Usage +----- + +**Example - CalculateMonteCarloAbsorption** + +.. testcode:: QENSCalculateShapeMonteCarloAbsorption + + sample_ws = CreateSampleWorkspace(Function="Quasielastic", + XUnit="Wavelength", + XMin=-0.5, + XMax=0.5, + BinWidth=0.01) + # Efixed is generally defined as part of the IDF for real data. + # Fake it here + inst_name = sample_ws.getInstrument().getName() + SetInstrumentParameter(sample_ws, ComponentName=inst_name, + ParameterName='Efixed', ParameterType='Number', Value='4.1') + + container_ws = CreateSampleWorkspace(Function="Quasielastic", + XUnit="Wavelength", + XMin=-0.5, + XMax=0.5, + BinWidth=0.01) + SetInstrumentParameter(container_ws, ComponentName=inst_name, + ParameterName='Efixed', ParameterType='Number', Value='4.1') + + corrections = CalculateMonteCarloAbsorption(SampleWorkspace = sample_ws, + SampleChemicalFormula = 'H2-O', + SampleDensityType = 'Mass Density', + SampleDensity = 1.0, + ContainerWorkspace = container_ws, + ContainerChemicalFormula = 'Al', + ContainerDensityType = 'Mass Density', + ContainerDensity = 1.0, + EventsPerPoint = 200, + BeamHeight = 3.5, + BeamWidth = 4.0, + Height = 2.0, + Shape = 'FlatPlate', + SampleWidth = 1.4, + SampleThickness = 2.1, + ContainerFrontThickness = 1.2, + ContainerBackThickness = 1.1) + + ass_ws = corrections[0] + acc_ws = corrections[1] + + print("Workspaces: " + str(ass_ws.getName()) + ", " + str(acc_ws.getName())) + print("Y-Unit Label of " + str(ass_ws.getName()) + ": " + str(ass_ws.YUnitLabel())) + print("Y-Unit Label of " + str(acc_ws.getName()) + ": " + str(acc_ws.YUnitLabel())) + +.. testcleanup:: QENSCalculateShapeMonteCarloAbsorption + + DeleteWorkspace(sample_ws) + DeleteWorkspace(container_ws) + DeleteWorkspace(corrections) + +**Output:** + +.. testoutput:: QENSCalculateShapeMonteCarloAbsorption + + Workspaces: corrections_ass, corrections_acc + Y-Unit Label of corrections_ass: Attenuation factor + Y-Unit Label of corrections_acc: Attenuation factor + +.. categories:: + +.. sourcelink:: diff --git a/docs/source/algorithms/CalculateMuonAsymmetry-v1.rst b/docs/source/algorithms/CalculateMuonAsymmetry-v1.rst index 2189d3347a832451f08e43594baaaa6937f09ece..af7fda4820886fddfe633f98695355ea5ee77d50 100644 --- a/docs/source/algorithms/CalculateMuonAsymmetry-v1.rst +++ b/docs/source/algorithms/CalculateMuonAsymmetry-v1.rst @@ -49,8 +49,8 @@ This example is for calculating the Asymmetry from counts. run = input.getRun() run.addProperty("goodfrm","10","None",True) output,norm=CalculateMuonAsymmetry (InputWorkspace=input,spectra=0,StartX=1,EndX=5,FittingFunction= "name = GausOsc, A = 10.0, Sigma = 0.2, Frequency = 1.0, Phi = 0.0",InputDataType="counts",Minimizer="Levenberg-MarquardtMD",MaxIterations=500 ) - print "Asymmetry: ",['{0:.2f}'.format(value) for value in output.readY(0)] - print "Normalization constant: {0:.2f}".format(norm[0]) + print("Asymmetry: {}".format(['{0:.2f}'.format(value) for value in output.readY(0)])) + print("Normalization constant: {0:.2f}".format(norm[0])) Output: @@ -76,8 +76,8 @@ This example is for calculating the Asymmetry from an estimate of the asymmetry. run.addProperty("goodfrm","10","None",True) estAsymm,estNorm=CalculateMuonAsymmetry(InputWorkspace=input,spectra=0,StartX=1,EndX=5) output,norm=CalculateMuonAsymmetry(InputWorkspace=estAsymm,spectra=0,StartX=1,EndX=5,FittingFunction= "name = GausOsc, A = 10.0, Sigma = 0.2, Frequency = 1.0, Phi = 0.0",InputDataType="asymmetry",Minimizer="Levenberg-MarquardtMD",MaxIterations=500,PreviousNormalizationConstant=estNorm ) - print "Asymmetry: ",['{0:.2f}'.format(value) for value in output.readY(0)] - print "Normalization constant: {0:.2f}".format(norm[0]) + print("Asymmetry: {}".format(['{0:.2f}'.format(value) for value in output.readY(0)])) + print("Normalization constant: {0:.2f}".format(norm[0])) Output: diff --git a/docs/source/algorithms/CalculatePeaksHKL-v1.rst b/docs/source/algorithms/CalculatePeaksHKL-v1.rst index 017696e9c5a2cbfcde5835ac565b3ac4d43fcd3e..7c0b6d328d79d70081c01ee1d3bfaf3e7f3f8318 100644 --- a/docs/source/algorithms/CalculatePeaksHKL-v1.rst +++ b/docs/source/algorithms/CalculatePeaksHKL-v1.rst @@ -36,7 +36,7 @@ Usage # Run the algorithm indexed = CalculatePeaksHKL(PeaksWorkspace=peaks, OverWrite=True) - print "Number of Indexed Peaks: ", indexed + print("Number of Indexed Peaks: {}".format(indexed)) Output: diff --git a/docs/source/algorithms/CalculateSampleTransmission-v1.rst b/docs/source/algorithms/CalculateSampleTransmission-v1.rst index 9e763805c5b03e22ca145078e2c15e0a4d0bf2cf..f062723d18ea07c642e1db87734d387198ef9108 100644 --- a/docs/source/algorithms/CalculateSampleTransmission-v1.rst +++ b/docs/source/algorithms/CalculateSampleTransmission-v1.rst @@ -29,8 +29,8 @@ Usage ws = CalculateSampleTransmission(WavelengthRange='2.0, 0.1, 10.0', ChemicalFormula='H2-O') - print 'Transmission: %f, %f, %f ...' % tuple(ws.readY(0)[:3]) - print 'Scattering: %f, %f, %f ...' % tuple(ws.readY(1)[:3]) + print('Transmission: {:.6f}, {:.6f}, {:.6f} ...'.format(*ws.readY(0)[:3])) + print('Scattering: {:.6f}, {:.6f}, {:.6f} ...'.format(*ws.readY(1)[:3])) Output: @@ -51,8 +51,8 @@ Output: Density=0.2, Thickness=0.58) - print 'Transmission: %f, %f, %f ...' % tuple(ws.readY(0)[:3]) - print 'Scattering: %f, %f, %f ...' % tuple(ws.readY(1)[:3]) + print('Transmission: {:.6f}, {:.6f}, {:.6f} ...'.format(*ws.readY(0)[:3])) + print('Scattering: {:.6f}, {:.6f}, {:.6f} ...'.format(*ws.readY(1)[:3])) Output: diff --git a/docs/source/algorithms/CalculateSlits-v1.rst b/docs/source/algorithms/CalculateSlits-v1.rst index b3fbee1dc7c6f4acffd74e2c3254247db269ab20..cca529d82fff7bdcfac3c3ae43cf9699ea8f889f 100644 --- a/docs/source/algorithms/CalculateSlits-v1.rst +++ b/docs/source/algorithms/CalculateSlits-v1.rst @@ -36,8 +36,8 @@ Usage .. testcode:: s1, s2 = CalculateSlits(Slit1Slit2=1940.5, Slit2SA=364, Angle=0.7, Footprint=50, Resolution=0.03) - print("Slit 1: %.3f mm" % s1) - print("Slit 2: %.3f mm" % s2) + print("Slit 1: {:.3f} mm".format(s1)) + print("Slit 2: {:.3f} mm".format(s2)) .. testoutput:: diff --git a/docs/source/algorithms/CalculateZscore-v1.rst b/docs/source/algorithms/CalculateZscore-v1.rst index 1e9c0639ad221002e2a3221716ada9f3016bdf14..d444025b3f1aea28b0d79242cf92d3f9a6cb1a92 100644 --- a/docs/source/algorithms/CalculateZscore-v1.rst +++ b/docs/source/algorithms/CalculateZscore-v1.rst @@ -36,7 +36,7 @@ Usage # rebin from min to max with size bin = 2 ws2 = CalculateZscore(InputWorkspace=ws) - print "The Z-scores are: " + str(ws2.readY(0)) + print("The Z-scores are: {}".format(ws2.readY(0))) .. testcleanup:: ExHistSimple diff --git a/docs/source/algorithms/CatalogGetDataFiles-v1.rst b/docs/source/algorithms/CatalogGetDataFiles-v1.rst index 3d2babf5ab716418cf28d0a8887bb8fc17204978..3688e18d63a69d74fb72e98c973385d3882ba03b 100644 --- a/docs/source/algorithms/CatalogGetDataFiles-v1.rst +++ b/docs/source/algorithms/CatalogGetDataFiles-v1.rst @@ -23,11 +23,11 @@ Usage datafiles = CatalogGetDataFiles(InvestigationId = '1390028', Session = session.getPropertyValue("Session")) # Verify that we have any datafiles in the returned workspace. - print "The number of datafiles in this investigation is: " + str(len(datafiles)) + print("The number of datafiles in this investigation is: {}".format(len(datafiles))) # Output the ID of the datafiles related to the given investigation. for row in datafiles: - print "A datafile with id '" + row['Id'] + "' exists." + print("A datafile with id '{}' exists.".format(row['Id'])) Output: diff --git a/docs/source/algorithms/CatalogGetDataSets-v1.rst b/docs/source/algorithms/CatalogGetDataSets-v1.rst index cc07f8a6091f97d0c859ca9a9ff52941c39fd373..6727e74f9f2c5cc7dad5291ccad1cb2291037557 100644 --- a/docs/source/algorithms/CatalogGetDataSets-v1.rst +++ b/docs/source/algorithms/CatalogGetDataSets-v1.rst @@ -23,7 +23,7 @@ Usage datasets = CatalogGetDataSets(InvestigationId = '1193002', Session = session.getPropertyValue("Session")) # Verify that we have any datafiles in the returned workspace. - print "The number of datasets for this investigation is: " + str(len(datasets)) + print("The number of datasets for this investigation is: {}".format(len(datasets))) Output: diff --git a/docs/source/algorithms/CatalogListInstruments-v1.rst b/docs/source/algorithms/CatalogListInstruments-v1.rst index 41a417a0462e1b8ed491efcd3684154c6a15602f..5fe41febc6db3d8b60eb6321d69be68dc6e6adde 100644 --- a/docs/source/algorithms/CatalogListInstruments-v1.rst +++ b/docs/source/algorithms/CatalogListInstruments-v1.rst @@ -22,14 +22,14 @@ Usage instruments = CatalogListInstruments() # How many instruments are at ISIS? - print "The number of instruments at ISIS is:" + str(len(instruments)) + print("The number of instruments at ISIS is: {}".format(len(instruments))) for instrument in instruments: - print "Instrument name is: " + instrument + print("Instrument name is: {}".format(instrument)) # Verify that the instrument belongs to ISIS. instrument = instruments[0] - print "The facility of instrument " + instrument + " is: " + str(ConfigService.getInstrument(instrument).facility()) + print("The facility of instrument {} is: {}".format(instrument, ConfigService.getInstrument(instrument).facility())) Output: diff --git a/docs/source/algorithms/CatalogListInvestigationTypes-v1.rst b/docs/source/algorithms/CatalogListInvestigationTypes-v1.rst index 55a220ba9c22e33719a0a2a94e81dbfe186cae25..9a265490df931d35d9fe95305af74613d75f588d 100644 --- a/docs/source/algorithms/CatalogListInvestigationTypes-v1.rst +++ b/docs/source/algorithms/CatalogListInvestigationTypes-v1.rst @@ -22,11 +22,11 @@ Usage investigation_types = CatalogListInvestigations() # How many different types of investigations are at ISIS? - print "The number of investigation types are: " + str(len(investigation_types)) + print("The number of investigation types are: {}".format(len(investigation_types))) # Print and view the investigation types for investigation in investigation_types: - print "Investigation type is: " + investigation + print("Investigation type is: {}".format(investigation)) Output: diff --git a/docs/source/algorithms/CatalogLogin-v1.rst b/docs/source/algorithms/CatalogLogin-v1.rst index de9f88d30a6ee1f360d03c1e3c36a7240cd1e219..34693f8be889e9e89fc82f025b24ebf3500445a3 100644 --- a/docs/source/algorithms/CatalogLogin-v1.rst +++ b/docs/source/algorithms/CatalogLogin-v1.rst @@ -24,7 +24,7 @@ Usage session = CatalogLogin(username='SECRET',password='SECRET',Facility="ISIS") # View the session ID for this catalog session. - print "The session ID is: " + session.getPropertyValue("Session") + print("The session ID is: {}".format(session.getPropertyValue("Session"))) Output: diff --git a/docs/source/algorithms/CatalogMyDataSearch-v1.rst b/docs/source/algorithms/CatalogMyDataSearch-v1.rst index f530ebda9153adea71225a254e4b96bd5ef7093c..54a479042e5a1cb3e9b6aaee87cf295b98beefd9 100644 --- a/docs/source/algorithms/CatalogMyDataSearch-v1.rst +++ b/docs/source/algorithms/CatalogMyDataSearch-v1.rst @@ -22,11 +22,11 @@ Usage my_data = CatalogMyDataSearch() # Verify that we have any investigations in 'My Data' - print "The number of investigations in 'My data' is: " + str(len(my_data)) + print("The number of investigations in 'My data' is: {}".format(len(my_data))) # Output the title of each investigation in 'My data' for row in my_data: - print "The title of the investigation is: " + row['Title'] + print("The title of the investigation is: {}".format(row['Title'])) Output: diff --git a/docs/source/algorithms/CatalogSearch-v1.rst b/docs/source/algorithms/CatalogSearch-v1.rst index ac4cdab9431366b8956b4ed5bbc6c040415e3ba2..a57ff5abfc875f9a55df432366b60277e827598f 100644 --- a/docs/source/algorithms/CatalogSearch-v1.rst +++ b/docs/source/algorithms/CatalogSearch-v1.rst @@ -25,11 +25,11 @@ Usage # A tuple is returned from CatalogSearch(). The first item is the search results. investigations = search_results[0] - print "The number of investigations returned was: " + str(len(investigations)) + print("The number of investigations returned was: {}".format(len(investigations))) # Print the title of all returned investigations. for investigation in investigations: - print "The title of the investigation is: " + investigation['Title'] + print("The title of the investigation is: {}".format(investigation['Title'])) # Log out of the catalog, otherwise results are appended to the workspace (search_results). CatalogLogout() @@ -53,7 +53,7 @@ Output: # If CountOnly is not provided, then ALL results are returned. This can be extremely slow. search_results = CatalogSearch(Instrument="ALF",CountOnly=True,StartDate="03/06/2012", EndDate="03/06/2014") - print "The number of search results returned was: " + str(search_results[1]) + print("The number of search results returned was: {}".format(search_results[1])) CatalogLogout() @@ -67,4 +67,4 @@ Output: .. sourcelink:: :h: Framework/ICat/inc/MantidICat/CatalogSearch.h - :cpp: Framework/ICat/src/CatalogSearch.cpp \ No newline at end of file + :cpp: Framework/ICat/src/CatalogSearch.cpp diff --git a/docs/source/algorithms/CentroidPeaks-v1.rst b/docs/source/algorithms/CentroidPeaks-v1.rst index be3b2e2468a66681ca5045f3242ebc6a8d838f68..da3aadceb906bc4932d54d551a8c73f68ae34296 100644 --- a/docs/source/algorithms/CentroidPeaks-v1.rst +++ b/docs/source/algorithms/CentroidPeaks-v1.rst @@ -27,10 +27,10 @@ Usage FindUBUsingFFT(PeaksWorkspace='peaks', MinD=2, MaxD=16) IndexPeaks(PeaksWorkspace='peaks', NumIndexed=100, AverageError=0.013759860303255647) peak = peaks.getPeak(0) - print peak.getBinCount() + print(peak.getBinCount()) peaks = CentroidPeaks(InPeaksWorkspace='peaks', InputWorkspace='TOPAZ_3132_nxs') peak = peaks.getPeak(0) - print peak.getBinCount() + print(peak.getBinCount()) .. categories:: diff --git a/docs/source/algorithms/CentroidPeaksMD-v2.rst b/docs/source/algorithms/CentroidPeaksMD-v2.rst index a41e51de139f38e8806dc6f9ec09b6dbc7436984..3cd2d75fb71edd585457d71c2f57c9b49cf7a3d6 100644 --- a/docs/source/algorithms/CentroidPeaksMD-v2.rst +++ b/docs/source/algorithms/CentroidPeaksMD-v2.rst @@ -45,16 +45,16 @@ FindPeaksMD algorithm. for name in tab_names: if name in common : - print "| {0:>10} ".format(name), + print("| {0:>10} ".format(name)) else: if name in long: - print "|FindPeaksMD found (old):{0:>7} |IntegrEllipsoids (new): {0:>7} ".format(name), + print("|FindPeaksMD found (old):{0:>7} |IntegrEllipsoids (new): {0:>7} ".format(name)) else: ntp = name; if len(ntp )>6: ntp = ntp[0:6] - print "| old {0:>6} | new {0:>6} ".format(ntp), - print "|\n", + print("| old {0:>6} | new {0:>6} ".format(ntp)) + print("|\n" ) for i in xrange(0,nRows): for name in tab_names: @@ -63,14 +63,14 @@ FindPeaksMD algorithm. col2 = pTWS2.column(name); data2_toPr=col2[i] if name in common : - print "| {0:>10} ".format(data1_toPr), + print("| {0:>10} ".format(data1_toPr)) else: if name in long: - print "| {0:>30} | {1:>30} ".format(data1_toPr,data2_toPr), + print("| {0:>30} | {1:>30} ".format(data1_toPr,data2_toPr)) else: - print "| {0:>10.2f} | {1:>10.2f} ".format(data1_toPr,data2_toPr), + print("| {0:>10.2f} | {1:>10.2f} ".format(data1_toPr,data2_toPr)) - print "|\n", + print("|\n ") # load test workspace diff --git a/docs/source/algorithms/ChangeBinOffset-v1.rst b/docs/source/algorithms/ChangeBinOffset-v1.rst index 96f4c884cf842aa6b2d67e08d9668e23e54343cc..69738abb70a6e1865d9d49209ba111e42b5c7a9e 100644 --- a/docs/source/algorithms/ChangeBinOffset-v1.rst +++ b/docs/source/algorithms/ChangeBinOffset-v1.rst @@ -37,11 +37,11 @@ Usage x1 = ws.readX(0) x2 = wsOffset.readX(0) # Test that all elements of arrays x2 and x1 differ by 1.0 - print np.all( x2 - x1 == 1.0 ) + print(np.all( x2 - x1 == 1.0 )) y1 = ws.readY(0) y2 = wsOffset.readY(0) # Test that arrays y2 and y1 are equal - print np.all( y2 == y1 ) + print(np.all( y2 == y1 )) .. testoutput:: ExOffset diff --git a/docs/source/algorithms/ChangeLogTime-v1.rst b/docs/source/algorithms/ChangeLogTime-v1.rst index f225a29aa74974e2a73079fe007973146572a190..e1e6567aff68da99da75e4dded2c59360ac0cfb6 100644 --- a/docs/source/algorithms/ChangeLogTime-v1.rst +++ b/docs/source/algorithms/ChangeLogTime-v1.rst @@ -28,8 +28,8 @@ Usage #get the log times for a particular variable, after change modified=w.getRun()['Speed5'].times #print times - print "OriginalTimes: ", original - print "ModifiedTimes: ", modified + print("OriginalTimes: {}".format(original)) + print("ModifiedTimes: {}".format(modified)) .. testcleanup:: ChangeLogTime diff --git a/docs/source/algorithms/ChangeQConvention-v1.rst b/docs/source/algorithms/ChangeQConvention-v1.rst index 19ec3fbf4898cdba1f5446e7ce94140f1b731038..c76f26b1497a570b278a75c06317a1c9a3217643 100644 --- a/docs/source/algorithms/ChangeQConvention-v1.rst +++ b/docs/source/algorithms/ChangeQConvention-v1.rst @@ -23,11 +23,11 @@ Usage mdws = LoadMD('MAPS_MDEW.nxs') dim = mdws.getXDimension() - print "X range of Q ",dim.getX(0),dim.getX(1) + print("X range of Q {} {}".format(dim.getX(0), dim.getX(1))) ChangeQConvention(mdws) mdws = mtd['mdws'] dim = mdws.getXDimension() - print "X range of Q after ChangeQConvention ",dim.getX(0),dim.getX(1) + print("X range of Q after ChangeQConvention {} {}".format(dim.getX(0), dim.getX(1))) Output: diff --git a/docs/source/algorithms/ChangeTimeZero-v1.rst b/docs/source/algorithms/ChangeTimeZero-v1.rst index 23e6e6f02ab09303362ead4c16fcf9af1b2b9363..79804c894305842be556d2ad2016a1cb90fe5bc3 100644 --- a/docs/source/algorithms/ChangeTimeZero-v1.rst +++ b/docs/source/algorithms/ChangeTimeZero-v1.rst @@ -45,11 +45,11 @@ Usage original_pulse_times = original_ws.getSpectrum(7).getPulseTimes() shifted_pulse_times = shifted_ws.getSpectrum(7).getPulseTimes() - print "Original proton_charge time: ", original_proton_charge.nthTime(0), ", ", original_proton_charge.nthTime(1), ", ..." - print "Shifted proton_charge time: ", shifted_proton_charge.nthTime(0), ", ", shifted_proton_charge.nthTime(1), ", ..." + print("Original proton_charge time: {} , {} , ...".format(original_proton_charge.nthTime(0), original_proton_charge.nthTime(1))) + print("Shifted proton_charge time: {} , {} , ...".format(shifted_proton_charge.nthTime(0), shifted_proton_charge.nthTime(1))) - print "Original pulse times: ", original_pulse_times[0], ", ", original_pulse_times[1], ", ..." - print "Shifted pulse times: ", shifted_pulse_times[0], ", ", shifted_pulse_times[1], ", ..." + print("Original pulse times: {} , {} , ...".format(original_pulse_times[0], original_pulse_times[1])) + print("Shifted pulse times: {} , {} , ...".format(shifted_pulse_times[0], shifted_pulse_times[1])) .. testcleanup:: ExRelativeChangeTimeZero @@ -86,11 +86,11 @@ Output: original_pulse_times = original_ws.getSpectrum(7).getPulseTimes() shifted_pulse_times = shifted_ws.getSpectrum(7).getPulseTimes() - print "Original proton_charge time: ", original_proton_charge.nthTime(0), ", ", original_proton_charge.nthTime(1), ", ..." - print "Shifted proton_charge time: ", shifted_proton_charge.nthTime(0), ", ", shifted_proton_charge.nthTime(1), ", ..." + print("Original proton_charge time: {} , {} , ...".format(original_proton_charge.nthTime(0), original_proton_charge.nthTime(1))) + print("Shifted proton_charge time: {} , {} , ...".format(shifted_proton_charge.nthTime(0), shifted_proton_charge.nthTime(1))) - print "Original pulse times: ", original_pulse_times[0], ", ", original_pulse_times[1], ", ..." - print "Shifted pulse times: ", shifted_pulse_times[0], ", ", shifted_pulse_times[1], ", ..." + print("Original pulse times: {} , {} , ...".format(original_pulse_times[0], original_pulse_times[1])) + print("Shifted pulse times: {} , {} , ...".format(shifted_pulse_times[0], shifted_pulse_times[1])) .. testcleanup:: ExAbsoluteChangeTimeZero diff --git a/docs/source/algorithms/CheckForSampleLogs-v1.rst b/docs/source/algorithms/CheckForSampleLogs-v1.rst index 96bb43f5ef7331626b5bc77a3578c803c092eef2..d97dbd87a671dd6b61752a34935a841edfaf6db8 100644 --- a/docs/source/algorithms/CheckForSampleLogs-v1.rst +++ b/docs/source/algorithms/CheckForSampleLogs-v1.rst @@ -25,10 +25,10 @@ Usage sampleLogs="Phase1,Phase3" result=CheckForSampleLogs(ws,sampleLogs) if len(result)==0: - print "We found logs for "+sampleLogs + print("We found logs for {}".format(sampleLogs)) sampleLogs="DJIA" result=CheckForSampleLogs(ws,sampleLogs) - print result.strip() + print(result.strip()) .. testcleanup:: CheckForSampleLogs diff --git a/docs/source/algorithms/CheckMantidVersion-v1.rst b/docs/source/algorithms/CheckMantidVersion-v1.rst index f1631e9ed9c0f4d34eeb23cdc3009d847d87f046..bfb5768748c0848e3770a18df662ded253427d8e 100644 --- a/docs/source/algorithms/CheckMantidVersion-v1.rst +++ b/docs/source/algorithms/CheckMantidVersion-v1.rst @@ -29,9 +29,9 @@ Usage .. code:: (current_version, most_recent_version, is_new_version_available)=CheckMantidVersion() - print "Current Version: " + current_version - print "Most Recent Version: " + most_recent_version - print "Is a newer version available? " + str(is_new_version_available) + print("Current Version: {}".format(current_version)) + print("Most Recent Version: {}".format(most_recent_version)) + print("Is a newer version available? {}".format(is_new_version_available)) Output: diff --git a/docs/source/algorithms/CheckWorkspacesMatch-v1.rst b/docs/source/algorithms/CheckWorkspacesMatch-v1.rst index ba874f343c2f41ed7987ba85b46ed39c95be5c51..ce78cc7d3c43aee7545b734914393f7f9fc5458f 100644 --- a/docs/source/algorithms/CheckWorkspacesMatch-v1.rst +++ b/docs/source/algorithms/CheckWorkspacesMatch-v1.rst @@ -37,7 +37,7 @@ Usage #create a copy of the workspace ws2 = CloneWorkspace(ws1) - print CheckWorkspacesMatch(ws1, ws2) + print(CheckWorkspacesMatch(ws1, ws2)) Output: @@ -61,8 +61,8 @@ Output: dataY2 = np.sin(dataX) + 0.1*np.random.random_sample(len(dataX)) ws2 = CreateWorkspace(dataX, dataY2) - print CheckWorkspacesMatch(ws1, ws2) #fails, they're not the same - print CheckWorkspacesMatch(ws1, ws2, Tolerance=0.1) #passes, they're close enough + print(CheckWorkspacesMatch(ws1, ws2)) #fails, they're not the same + print(CheckWorkspacesMatch(ws1, ws2, Tolerance=0.1)) #passes, they're close enough Output: diff --git a/docs/source/algorithms/ChopData-v1.rst b/docs/source/algorithms/ChopData-v1.rst index 5af47a23488e86ba259d7cb5bb5b10d60c25be19..90ad0f9452199c6af8c14b126096b088619a3d81 100644 --- a/docs/source/algorithms/ChopData-v1.rst +++ b/docs/source/algorithms/ChopData-v1.rst @@ -62,10 +62,10 @@ Usage # Chop the workspace roughly in two. result = ChopData(ws, NChops=2, Step=time_diff/2) - print "The time range of the original workspace was %i." % time_diff - print "The number of bins in the orginal workspace was %i." % ws.blocksize() - print "The number of bins in the 1st chop is %i." % result[0][0].blocksize() - print "The number of bins in the 2nd chop is %i." % result[0][1].blocksize() + print("The time range of the original workspace was {:.0f}.".format(time_diff)) + print("The number of bins in the orginal workspace was {}.".format(ws.blocksize())) + print("The number of bins in the 1st chop is {}.".format(result[0][0].blocksize())) + print("The number of bins in the 2nd chop is {}.".format(result[0][1].blocksize())) Output: diff --git a/docs/source/algorithms/ClearCache-v1.rst b/docs/source/algorithms/ClearCache-v1.rst index 1b5af88f74c49fb2bf015f6e413689b34b820103..d630d350ad907c0717edf3f5aaddf66b32a30d19 100644 --- a/docs/source/algorithms/ClearCache-v1.rst +++ b/docs/source/algorithms/ClearCache-v1.rst @@ -25,7 +25,7 @@ Usage filesRemoved = ClearCache(DownloadedInstrumentFileCache=True) # Print the result - print "%i files were removed" % filesRemoved + print("{} files were removed".format(filesRemoved)) # This will repopulate the cache you have just cleared DownloadInstrument() diff --git a/docs/source/algorithms/ClearUB-v1.rst b/docs/source/algorithms/ClearUB-v1.rst index edf4a3b14df5024990fde3eb29f7abbf55900fed..e37593140ff7952e17240fcb02f2a842d680aac1 100644 --- a/docs/source/algorithms/ClearUB-v1.rst +++ b/docs/source/algorithms/ClearUB-v1.rst @@ -27,15 +27,15 @@ Usage #check that we do have a UB matrix from numpy import * mat=array(ws.sample().getOrientedLattice().getUB()) - print "UB matrix size", mat.size + print("UB matrix size {}".format(mat.size )) ClearUB(ws) #check that it removed UB matrix & orientated lattice if( ws.sample().hasOrientedLattice() ): - print "ClearUB has not removed the orientated lattice." + print("ClearUB has not removed the orientated lattice.") else: - print "ClearUB has removed the oriented lattice." + print("ClearUB has removed the oriented lattice.") Output: diff --git a/docs/source/algorithms/CollectHB3AExperimentInfo-v1.rst b/docs/source/algorithms/CollectHB3AExperimentInfo-v1.rst index eb89bb31aec3a30e2a014477692817967ed9a0d7..512ddf52f0604bf5bbc573ef69f34e011185bc79 100644 --- a/docs/source/algorithms/CollectHB3AExperimentInfo-v1.rst +++ b/docs/source/algorithms/CollectHB3AExperimentInfo-v1.rst @@ -65,9 +65,9 @@ Usage expinfows = mtd['ExpInfoTable'] virtualdetws = mtd['VirtualInstrumentTable'] - print 'Number of input files = %d' % (expinfows.rowCount()) - print 'Number of detectors in virtual instrument = %d'%(virtualdetws.rowCount()) - print 'Virtual detectors are from ID = %d to ID = %d'%(virtualdetws.cell(0,0), virtualdetws.cell(131072-1,0)) + print('Number of input files = {}'.format(expinfows.rowCount())) + print('Number of detectors in virtual instrument = {}'.format(virtualdetws.rowCount())) + print('Virtual detectors are from ID = {} to ID = {}'.format(virtualdetws.cell(0,0), virtualdetws.cell(131072-1,0))) .. testcleanup:: ExCollect355Info diff --git a/docs/source/algorithms/Comment-v1.rst b/docs/source/algorithms/Comment-v1.rst index ee89fdfac9ccd503f9848abd8c739451f5c135d0..aa250230abdf5da9e33eaf2036cb7bb06ab427ab 100644 --- a/docs/source/algorithms/Comment-v1.rst +++ b/docs/source/algorithms/Comment-v1.rst @@ -29,7 +29,7 @@ Usage Comment(ws,"The next algorithm is doing 1/ws") # Print the result - print ws.getHistory().lastAlgorithm().getPropertyValue("Text") + print(ws.getHistory().lastAlgorithm().getPropertyValue("Text")) Output: diff --git a/docs/source/algorithms/CompareMDWorkspaces-v1.rst b/docs/source/algorithms/CompareMDWorkspaces-v1.rst index 4b25627e07715220bbb642b3a5324a12492dd87a..f9c5e19a6cfa0e5795ef35b2e65905eef21a7018 100644 --- a/docs/source/algorithms/CompareMDWorkspaces-v1.rst +++ b/docs/source/algorithms/CompareMDWorkspaces-v1.rst @@ -43,8 +43,8 @@ Usage comp_rez2=CompareMDWorkspaces(mdWs1,mdWs2) # print comparison results - print "Workspaces mdWs1 and mdWs1a are equal? : {0} : Comparison result: {1}".format(comp_rez1[0],comp_rez1[1]) - print "Workspaces mdWs1 and mdWs2 are equal? : {0} : Comparison result: {1}".format(comp_rez2[0],comp_rez2[1]) + print("Workspaces mdWs1 and mdWs1a are equal? : {0} : Comparison result: {1}".format(comp_rez1[0], comp_rez1[1])) + print("Workspaces mdWs1 and mdWs2 are equal? : {0} : Comparison result: {1}".format(comp_rez2[0], comp_rez2[1])) diff --git a/docs/source/algorithms/CompareSampleLogs-v1.rst b/docs/source/algorithms/CompareSampleLogs-v1.rst index 3e6e08820848e649ec0bd8dd0ded51eabf055844..ce743b9a15440924fd4cb0df944b141f345b4181 100644 --- a/docs/source/algorithms/CompareSampleLogs-v1.rst +++ b/docs/source/algorithms/CompareSampleLogs-v1.rst @@ -34,7 +34,7 @@ Usage # compare sample logs result = CompareSampleLogs('ws1,ws2', 'omega,wavelength,polarisation,flipper' , 0.01) if result == '': - print "All sample logs match!" + print("All sample logs match!") .. testcleanup:: ExCompareSampleLogs @@ -64,13 +64,13 @@ Output: # compare sample logs result = CompareSampleLogs('ws1,ws2', lognames , 0.01) - print "Following sample logs do not match: ", result + print("Following sample logs do not match: {}".format(result)) # create a table table = CreateLogPropertyTable('ws1,ws2', result, GroupPolicy='All') - print "Column names are: ", table.getColumnNames() - print "The omega values are:", table.column(1) - print "The flipper values are:", table.column(2) + print("Column names are: {}".format(table.getColumnNames())) + print("The omega values are: {}".format(table.column(1))) + print("The flipper values are: {}".format(table.column(2))) .. testcleanup:: ExCompareSampleLogs2 diff --git a/docs/source/algorithms/CompareWorkspaces-v1.rst b/docs/source/algorithms/CompareWorkspaces-v1.rst index 39195df1882265d010ee034d45f6d0eef9441f15..1efc31e907fde0dd5ab3854bc7c4e87e152f9758 100644 --- a/docs/source/algorithms/CompareWorkspaces-v1.rst +++ b/docs/source/algorithms/CompareWorkspaces-v1.rst @@ -47,8 +47,8 @@ Usage (result, messages) = CompareWorkspaces(ws1, ws2) - print "Result:", result - print messages.rowCount() + print("Result: {}".format(result)) + print(messages.rowCount()) Output: @@ -75,14 +75,14 @@ Output: ws2 = CreateWorkspace(dataX, dataY2) (result, messages) = CompareWorkspaces(ws1, ws2) # Fails, they're not the same - print "Result:", result - print "Displaying", messages.rowCount(), "messages:" - for row in messages: print row + print("Result: {}".format(result)) + print("Displaying {} messages:".format(messages.rowCount())) + for row in messages: print(row) (result, messages) = CompareWorkspaces(ws1, ws2, Tolerance=0.1) # Passes, they're close enough - print "Result:", result - print "Displaying", messages.rowCount(), "messages:" - for row in messages: print row + print("Result: {}".format(result)) + print("Displaying {} messages:".format(messages.rowCount())) + for row in messages: print(row) Output: diff --git a/docs/source/algorithms/CompressEvents-v1.rst b/docs/source/algorithms/CompressEvents-v1.rst index d716a23eec6765f0a1d4ab356025cc8388146eb0..53abcbbde0d147b98e003dddff57b6cc5bfb4142 100644 --- a/docs/source/algorithms/CompressEvents-v1.rst +++ b/docs/source/algorithms/CompressEvents-v1.rst @@ -41,12 +41,12 @@ Usage ws = CreateSampleWorkspace("Event",BankPixelWidth=1) - print "The unfiltered workspace %s has %i events and a peak value of %.2f" % (ws, ws.getNumberEvents(),ws.readY(0)[50]) + print("The unfiltered workspace {} has {} events and a peak value of {:.2f}".format(ws, ws.getNumberEvents(), ws.readY(0)[50])) ws = CompressEvents(ws) - print "The compressed workspace %s still has %i events and a peak value of %.2f" % (ws, ws.getNumberEvents(),ws.readY(0)[50]) - print "However it now takes up less memory." + print("The compressed workspace {} still has {} events and a peak value of {:.2f}".format(ws, ws.getNumberEvents(), ws.readY(0)[50])) + print("However it now takes up less memory.") Output: diff --git a/docs/source/algorithms/ComputeCalibrationCoefVan-v1.rst b/docs/source/algorithms/ComputeCalibrationCoefVan-v1.rst index 56cefac33618e3ef6096978da36f33855733c16c..48e59b72e4bc468c1f1749bc7f8158cd272da4fd 100644 --- a/docs/source/algorithms/ComputeCalibrationCoefVan-v1.rst +++ b/docs/source/algorithms/ComputeCalibrationCoefVan-v1.rst @@ -73,12 +73,12 @@ Usage epptable = FindEPP(wsVana) # calculate correction coefficients wsCoefs = ComputeCalibrationCoefVan(wsVana, epptable) - print 'Spectrum 4 of the output workspace is filled with: ', round(wsCoefs.readY(999)[0]) + print('Spectrum 4 of the output workspace is filled with: {}'.format(round(wsCoefs.readY(999)[0]))) # wsCoefs can be used as rhs with Divide algorithm to apply correction to the data wsCorr = wsVana/wsCoefs - print 'Spectrum 4 of the input workspace is filled with: ', round(wsVana.readY(999)[0], 1) - print 'Spectrum 4 of the corrected workspace is filled with: ', round(wsCorr.readY(999)[0], 5) + print('Spectrum 4 of the input workspace is filled with: {}'.format(round(wsVana.readY(999)[0], 1))) + print('Spectrum 4 of the corrected workspace is filled with: {}'.format(round(wsCorr.readY(999)[0], 5))) Output: diff --git a/docs/source/algorithms/ConjoinFiles-v1.rst b/docs/source/algorithms/ConjoinFiles-v1.rst index fe9ff5b0622735c19ee3b9e92aa8c5887686be22..eb087a5e9ffba3fc4a65f52d574b6bf096dc5cc4 100644 --- a/docs/source/algorithms/ConjoinFiles-v1.rst +++ b/docs/source/algorithms/ConjoinFiles-v1.rst @@ -33,15 +33,15 @@ Usage ws2Path = os.path.join(savePath, ConfigService.getInstrument().shortName() + "_4567.gsa") ws1 = CreateSampleWorkspace(WorkspaceType="Histogram", NumBanks=2, BankPixelWidth=1, BinWidth=10, Xmax=50) - print "Number of spectra in first workspace", ws1.getNumberHistograms() + print("Number of spectra in first workspace {}".format(ws1.getNumberHistograms())) SaveGSS(ws1, ws1Path, SplitFiles=False, Append=False) ws2 = CreateSampleWorkspace(WorkspaceType="Histogram", NumBanks=3, BankPixelWidth=1, BinWidth=10, Xmax=50) - print "Number of spectra in second workspace", ws2.getNumberHistograms() + print("Number of spectra in second workspace {}".format(ws2.getNumberHistograms())) SaveGSS(ws2,ws2Path, SplitFiles=False, Append=False) wsOutput = ConjoinFiles(RunNumbers=[1234,4567], Directory= savePath) - print "Number of spectra after ConjoinWorkspaces", wsOutput.getNumberHistograms() + print("Number of spectra after ConjoinWorkspaces {}".format(wsOutput.getNumberHistograms())) os.remove(ws1Path) os.remove(ws2Path) diff --git a/docs/source/algorithms/ConjoinSpectra-v1.rst b/docs/source/algorithms/ConjoinSpectra-v1.rst index f2772eeea2699e9563fc4b99d50a70403b605d20..5d12ae848478f90b9869dab522fc1d958633ee58 100644 --- a/docs/source/algorithms/ConjoinSpectra-v1.rst +++ b/docs/source/algorithms/ConjoinSpectra-v1.rst @@ -39,8 +39,8 @@ Usage ws3 = CreateSampleWorkspace("Histogram",BankPixelWidth=1) wsOut = ConjoinSpectra("ws,ws2,ws3",WorkspaceIndex=1) - print ("Creates a workspace with %i spectra labelled as" % wsOut.getNumberHistograms()) - print wsOut.getAxis(1).extractValues() + print("Creates a workspace with {} spectra labelled as".format(wsOut.getNumberHistograms())) + print(wsOut.getAxis(1).extractValues()) Output: @@ -66,14 +66,14 @@ Output: AddTimeSeriesLog(w, Name="myLog", Time=time_string, Value=(wsIndex*100)+minute) wsOut = ConjoinSpectra("ws,ws2,ws3",WorkspaceIndex=0,LabelUsing="myLog",LabelValue="Mean") - print ("Creates a workspace with %i spectra labelled using the Mean of myLog." % wsOut.getNumberHistograms()) - print wsOut.getAxis(1).extractValues() + print("Creates a workspace with {} spectra labelled using the Mean of myLog.".format(wsOut.getNumberHistograms())) + print(wsOut.getAxis(1).extractValues()) otherLabelValueOptions = ["First Value","Median", "Maximum", "Minimum"] for labelValueOption in otherLabelValueOptions: wsOut = ConjoinSpectra("ws,ws2,ws3",WorkspaceIndex=0,LabelUsing="myLog", LabelValue=labelValueOption) - print ("Creates a workspace with %i spectra labelled using the %s of myLog." % (wsOut.getNumberHistograms(), labelValueOption)) - print wsOut.getAxis(1).extractValues() + print("Creates a workspace with {} spectra labelled using the {} of myLog.".format(wsOut.getNumberHistograms(), labelValueOption)) + print(wsOut.getAxis(1).extractValues()) Output: diff --git a/docs/source/algorithms/ConjoinWorkspaces-v1.rst b/docs/source/algorithms/ConjoinWorkspaces-v1.rst index e30e93c85156b7964d25db9f8c78258dfbc63902..ab027b06f819905a8b7b1df5e9c098faf4923ba3 100644 --- a/docs/source/algorithms/ConjoinWorkspaces-v1.rst +++ b/docs/source/algorithms/ConjoinWorkspaces-v1.rst @@ -81,14 +81,14 @@ Usage .. testcode:: ConjoinWorkspacesEx ws1 = CreateSampleWorkspace(WorkspaceType="Histogram", NumBanks=2, BankPixelWidth=1, BinWidth=10, Xmax=50) - print("Number of spectra in first workspace = " + str(ws1.getNumberHistograms())) + print("Number of spectra in first workspace = {}".format(ws1.getNumberHistograms())) ws2 = CreateSampleWorkspace(WorkspaceType="Histogram", NumBanks=3, BankPixelWidth=1, BinWidth=10, Xmax=50) - print("Number of spectra in second workspace = " + str(ws2.getNumberHistograms())) + print("Number of spectra in second workspace = {}".format(ws2.getNumberHistograms())) ConjoinWorkspaces(InputWorkspace1=ws1, InputWorkspace2=ws2, CheckOverlapping=False, YAxisUnit="New unit", YAxisLabel="New label") ws = mtd['ws1'] # Have to update workspace from ADS, as it is an in-out parameter - print("Number of spectra after ConjoinWorkspaces = " + str(ws.getNumberHistograms())) - print("Y unit is " + ws.YUnit()) - print("Y label " + ws.YUnitLabel()) + print("Number of spectra after ConjoinWorkspaces = {}".format(ws.getNumberHistograms())) + print("Y unit is {}".format(ws.YUnit())) + print("Y label {}".format(ws.YUnitLabel())) Output: diff --git a/docs/source/algorithms/ConvertAxesToRealSpace-v1.rst b/docs/source/algorithms/ConvertAxesToRealSpace-v1.rst index 11f850a241c451df78bf29916dc4a9eb2d234f37..fe11f4e7b475e4cc31670e6d5510261a5d076d5b 100644 --- a/docs/source/algorithms/ConvertAxesToRealSpace-v1.rst +++ b/docs/source/algorithms/ConvertAxesToRealSpace-v1.rst @@ -68,8 +68,8 @@ Usage wsOut = ConvertAxesToRealSpace(ws,"y","2theta",20,20) # Print the result - print "The output workspace has axes of %s with %i bins" % (wsOut.getAxis(1).getUnit().caption(), wsOut.getNumberHistograms()) - print "and %s with %i bins." % (wsOut.getAxis(0).getUnit().caption(), wsOut.blocksize()) + print("The output workspace has axes of {} with {} bins".format(wsOut.getAxis(1).getUnit().caption(), wsOut.getNumberHistograms())) + print("and {} with {} bins.".format(wsOut.getAxis(0).getUnit().caption(), wsOut.blocksize())) .. figure:: /images/ConvertAxesToRealSpace_Example.png :alt: ConvertAxesToRealSpace_Example.png diff --git a/docs/source/algorithms/ConvertAxisByFormula-v1.rst b/docs/source/algorithms/ConvertAxisByFormula-v1.rst index 257c02734ce36581b1f6014765149914b54af1f8..60d703e14b4f3d7b46953e690475d648f7b5a745 100644 --- a/docs/source/algorithms/ConvertAxisByFormula-v1.rst +++ b/docs/source/algorithms/ConvertAxisByFormula-v1.rst @@ -86,9 +86,9 @@ Usage AxisTitle="Squared X", AxisUnits="x^2") - print "New X values:", output.getAxis(0).extractValues() - print "New X units:", output.getAxis(0).getUnit().symbol() - print "New X title:", output.getAxis(0).getUnit().caption() + print("New X values: {}".format(output.getAxis(0).extractValues())) + print("New X units: {}".format(output.getAxis(0).getUnit().symbol())) + print("New X title: {}".format(output.getAxis(0).getUnit().caption())) Output: @@ -124,9 +124,9 @@ Output: AxisTitle="Doubled Y", AxisUnits="y*2") - print "New Y values:", output.getAxis(1).extractValues() - print "New Y units:", output.getAxis(1).getUnit().symbol() - print "New Y title:", output.getAxis(1).getUnit().caption() + print("New Y values: {}".format(output.getAxis(1).extractValues())) + print("New Y units: {}".format(output.getAxis(1).getUnit().symbol())) + print("New Y title: {}".format(output.getAxis(1).getUnit().caption())) Output: @@ -150,7 +150,7 @@ Output: #check they are the same isMatched, messageTable = CompareWorkspaces(wsMTbyFormula,wsMTbyConvertUnits,0.00001,checkAxes=True, CheckType=True) if isMatched: - print "Both methods create matching workspaces." + print("Both methods create matching workspaces.") Output: diff --git a/docs/source/algorithms/ConvertCWPDMDToSpectra-v1.rst b/docs/source/algorithms/ConvertCWPDMDToSpectra-v1.rst index f58d3cff9cdebcd91cbe2c86d37469b1d05c5016..a68b94e474bcce4b0d551ea976b2ba561fdf0c9a 100644 --- a/docs/source/algorithms/ConvertCWPDMDToSpectra-v1.rst +++ b/docs/source/algorithms/ConvertCWPDMDToSpectra-v1.rst @@ -198,7 +198,7 @@ Usage vece = ws.readE(0) for i in [100, 100, 1101, 1228]: - print "2theta = %-5f, Y = %-5f, E = %-5f" % (vecx[i], vecy[i], vece[i]) + print("2theta = {:.6f}, Y = {:.6f}, E = {:.6f}".format(vecx[i], vecy[i], vece[i])) .. testcleanup:: ExReduceHB2AToFullprof diff --git a/docs/source/algorithms/ConvertCWSDExpToMomentum-v1.rst b/docs/source/algorithms/ConvertCWSDExpToMomentum-v1.rst index 319715c4f232bc17fa8536e8c146b430311c2124..f73282142aa6664a7fd9c12671ba551e60d2db06 100644 --- a/docs/source/algorithms/ConvertCWSDExpToMomentum-v1.rst +++ b/docs/source/algorithms/ConvertCWSDExpToMomentum-v1.rst @@ -169,13 +169,13 @@ Usage # Examine mdws = mtd['QSampleMD'] - print 'Output MDEventWorkspace has %d events.'%(mdws.getNEvents()) + print('Output MDEventWorkspace has {} events.'.format(mdws.getNEvents())) peakws = mtd['PeakTable'] - print 'There are %d peaks found in output MDWorkspace'%(peakws.getNumberPeaks()) + print('There are {} peaks found in output MDWorkspace'.format(peakws.getNumberPeaks())) peak = peakws.getPeak(0) qsample = peak.getQSampleFrame() - print 'In Q-sample frame, center of peak 0 is at (%.5f, %.5f, %.5f) at detector with ID %d'%( - qsample.X(), qsample.Y(), qsample.Z(), peak.getDetectorID()) + print('In Q-sample frame, center of peak 0 is at ({:.5f}, {:.5f}, {:.5f}) at detector with ID {}'. + format(qsample.X(), qsample.Y(), qsample.Z(), peak.getDetectorID())) .. testcleanup:: ExConvertHB3AToMDVirtualInstrument @@ -213,13 +213,13 @@ Output: # Examine mdws = mtd['QSampleMD'] - print 'Output MDEventWorkspace has %d events.'%(mdws.getNEvents()) + print('Output MDEventWorkspace has {} events.'.format(mdws.getNEvents())) peakws = mtd['PeakTable'] - print 'There are %d peaks found in output MDWorkspace'%(peakws.getNumberPeaks()) + print('There are {} peaks found in output MDWorkspace'.format(peakws.getNumberPeaks())) peak = peakws.getPeak(0) qsample = peak.getQSampleFrame() - print 'In Q-sample frame, center of peak 0 is at (%.5f, %.5f, %.5f) at detector with ID %d'%( - qsample.X(), qsample.Y(), qsample.Z(), peak.getDetectorID()) + print('In Q-sample frame, center of peak 0 is at ({:.5f}, {:.5f}, {:.5f}) at detector with ID {}'. + format(qsample.X(), qsample.Y(), qsample.Z(), peak.getDetectorID())) .. testcleanup:: ExConvertHB3AToMDCopyInstrument diff --git a/docs/source/algorithms/ConvertCWSDMDtoHKL-v1.rst b/docs/source/algorithms/ConvertCWSDMDtoHKL-v1.rst index 68f44b314a3617cd0899c5a6a354270e5b45741d..678e46d31aa9666e9e49ffc683f4d95af519981b 100644 --- a/docs/source/algorithms/ConvertCWSDMDtoHKL-v1.rst +++ b/docs/source/algorithms/ConvertCWSDMDtoHKL-v1.rst @@ -79,13 +79,13 @@ Usage # Examine mdws = mtd['QSampleMD'] hklws = mtd['HKLMD'] - print 'Output QSample and HKL workspaces have %d and %d events.'%(mdws.getNEvents(), hklws.getNEvents()) + print('Output QSample and HKL workspaces have %d and %d events.'%(mdws.getNEvents(), hklws.getNEvents())) BinMD(InputWorkspace='HKLMD', AlignedDim0='H,-0.3,0.3,60', AlignedDim1='K,-0.4,0.5,90', AlignedDim2='L,4,8,10', OutputWorkspace='BinndHKL') histws = mtd['BinndHKL'] events_array = histws.getNumEventsArray() - print 'events[22, 53, 5] = %.1f' % events_array[22, 53, 5] - print 'events[30, 40, 5] = %.1f' % events_array[30, 40, 5] + print('events[22, 53, 5] = {:.1f}'.format(events_array[22, 53, 5])) + print('events[30, 40, 5] = {:.1f}'.format(events_array[30, 40, 5])) .. testcleanup:: ExConvertHB3AToHKL diff --git a/docs/source/algorithms/ConvertFromDistribution-v1.rst b/docs/source/algorithms/ConvertFromDistribution-v1.rst index ac1b22ff62284bc7752bd4b55aa19f8bf5f055fe..d4254dcd47e71bb53410978083bc3ae9dbc094a3 100644 --- a/docs/source/algorithms/ConvertFromDistribution-v1.rst +++ b/docs/source/algorithms/ConvertFromDistribution-v1.rst @@ -31,12 +31,12 @@ Usage # If your data is already distributed then this is not required. ConvertToDistribution(ws_multi) - print "Is the workspace a distribution? " + str(ws_multi.isDistribution()) + print("Is the workspace a distribution? {}".format(ws_multi.isDistribution())) # Convert back to the initial workspace state. ConvertFromDistribution(ws_multi) - print "Is the workspace a distribution? " + str(ws_multi.isDistribution()) + print("Is the workspace a distribution? {}".format(ws_multi.isDistribution())) Output: diff --git a/docs/source/algorithms/ConvertMDHistoToMatrixWorkspace-v1.rst b/docs/source/algorithms/ConvertMDHistoToMatrixWorkspace-v1.rst index 15652a49f96807ca6833e0f431221f6e32e4c06f..f43815f52678824ea801fdf1ae5fd7674bea2004 100644 --- a/docs/source/algorithms/ConvertMDHistoToMatrixWorkspace-v1.rst +++ b/docs/source/algorithms/ConvertMDHistoToMatrixWorkspace-v1.rst @@ -23,11 +23,11 @@ Usage ErrorInput='1,1,1,1,1,1,1,1,1', Dimensionality='2', Extents='-1,1,-1,1', NumberOfBins='3,3', Names='A,B', Units='U,T') - print "%s is a %s" % (ws, ws.id()) + print("{} is a {}".format(ws, ws.id())) wsOut=ConvertMDHistoToMatrixWorkspace(ws) - print "%s is a %s with %i histograms and %i bins" % (wsOut, wsOut.id(), wsOut.getNumberHistograms(), wsOut.blocksize()) + print("{} is a {} with {} histograms and {} bins".format(wsOut, wsOut.id(), wsOut.getNumberHistograms(), wsOut.blocksize())) Output: @@ -45,11 +45,11 @@ Output: ErrorInput='1,1,1', Dimensionality='2', Extents='-1,1,-1,1', NumberOfBins='1,3', Names='A,B', Units='U,T') - print "%s is a %s" % (ws, ws.id()) + print("{} is a {}".format(ws, ws.id())) wsOut=ConvertMDHistoToMatrixWorkspace(ws) - print "%s is a %s with %i histograms and %i bins" % (wsOut, wsOut.id(), wsOut.getNumberHistograms(), wsOut.blocksize()) + print("{} is a {} with {} histograms and {} bins".format(wsOut, wsOut.id(), wsOut.getNumberHistograms(), wsOut.blocksize())) Output: diff --git a/docs/source/algorithms/ConvertMultipleRunsToSingleCrystalMD-v1.rst b/docs/source/algorithms/ConvertMultipleRunsToSingleCrystalMD-v1.rst index a11ea41251044a6265102650a6f2ae68548e4a81..d5aeb6030065763e8cc1578bd2a6cd130dbb6612 100644 --- a/docs/source/algorithms/ConvertMultipleRunsToSingleCrystalMD-v1.rst +++ b/docs/source/algorithms/ConvertMultipleRunsToSingleCrystalMD-v1.rst @@ -53,10 +53,10 @@ Usage SetGoniometer=True, Axis0="huber,0,1,0,1") ws=mtd['output'] - print "The workspace is in", ws.getSpecialCoordinateSystem() - print "There are", ws.getNumExperimentInfo(), "experiment runs in the workspace" - print "Number of Events =", ws.getNEvents() - print "There are",ws.getNumDims(),"dimensions with names:",ws.getDimension(0).name,ws.getDimension(1).name,ws.getDimension(2).name + print("The workspace is in {}".format(ws.getSpecialCoordinateSystem())) + print("There are {} experiment runs in the workspace".format(ws.getNumExperimentInfo())) + print("Number of Events = {}".format(ws.getNEvents())) + print("There are {} dimensions with names: {} {} {}".format(ws.getNumDims(), ws.getDimension(0).name, ws.getDimension(1).name, ws.getDimension(2).name)) Output: @@ -78,10 +78,10 @@ Output: SetGoniometer=True, Axis0="BL9:Mot:Sample:Axis1,0,1,0,1") ws=mtd['output'] - print "The workspace is in", ws.getSpecialCoordinateSystem() - print "There are", ws.getNumExperimentInfo(), "experiment runs in the workspace" - print "Number of Events =", ws.getNEvents() - print "There are",ws.getNumDims(),"dimensions with names:",ws.getDimension(0).name,ws.getDimension(1).name,ws.getDimension(2).name + print("The workspace is in {}".format(ws.getSpecialCoordinateSystem())) + print("There are {} experiment runs in the workspace".format(ws.getNumExperimentInfo())) + print("Number of Events = {}".format(ws.getNEvents())) + print("There are {} dimensions with names: {} {} {}".format(ws.getNumDims(), ws.getDimension(0).name, ws.getDimension(1).name, ws.getDimension(2).name)) Output: @@ -115,10 +115,10 @@ Output: Axis0="huber,0,1,0,1", UBMatrix=UBfilename) ws=mtd['output'] - print "The workspace is in", ws.getSpecialCoordinateSystem() - print "There are", ws.getNumExperimentInfo(), "experiment runs in the workspace" - print "Number of Events =", ws.getNEvents() - print "There are",ws.getNumDims(),"dimensions with names:",ws.getDimension(0).name,ws.getDimension(1).name,ws.getDimension(2).name + print("The workspace is in {}".format(ws.getSpecialCoordinateSystem())) + print("There are {} experiment runs in the workspace".format(ws.getNumExperimentInfo())) + print("Number of Events = {}".format(ws.getNEvents())) + print("There are {} dimensions with names: {} {} {}".format(ws.getNumDims(), ws.getDimension(0).name, ws.getDimension(1).name, ws.getDimension(2).name)) Output: @@ -141,10 +141,10 @@ Output: Axis0="BL9:Mot:Sample:Axis1,0,1,0,1", UBMatrix="/SNS/CORELLI/IPTS-15526/shared/benzil_Hexagonal.mat") ws=mtd['output'] - print "The workspace is in", ws.getSpecialCoordinateSystem() - print "There are", ws.getNumExperimentInfo(), "experiment runs in the workspace" - print "Number of Events =", ws.getNEvents() - print "There are",ws.getNumDims(),"dimensions with names:",ws.getDimension(0).name,ws.getDimension(1).name,ws.getDimension(2).name + print("The workspace is in {}".format(ws.getSpecialCoordinateSystem())) + print("There are {} experiment runs in the workspace".format(ws.getNumExperimentInfo())) + print("Number of Events = {}".format(ws.getNEvents())) + print("There are {} dimensions with names: {} {} {}".format(ws.getNumDims(), ws.getDimension(0).name, ws.getDimension(1).name, ws.getDimension(2).name)) Output: diff --git a/docs/source/algorithms/ConvertSnsRoiFileToMask-v1.rst b/docs/source/algorithms/ConvertSnsRoiFileToMask-v1.rst index 6607db9e665bf7c7549cc8fcd1ec2c6022cffee9..e3315aae1c95d42c0708877555351f2be0ad91e0 100644 --- a/docs/source/algorithms/ConvertSnsRoiFileToMask-v1.rst +++ b/docs/source/algorithms/ConvertSnsRoiFileToMask-v1.rst @@ -38,9 +38,9 @@ Usage MaskDetectors(ws, MaskedWorkspace=mask) # Check to see that only first 2 pixels are not masked - print "Is detector 0 masked:", ws.getDetector(0).isMasked() - print "Is detector 1 masked:", ws.getDetector(1).isMasked() - print "Is detector 2 masked:", ws.getDetector(2).isMasked() + print("Is detector 0 masked: {}".format(ws.getDetector(0).isMasked())) + print("Is detector 1 masked: {}".format(ws.getDetector(1).isMasked())) + print("Is detector 2 masked: {}".format(ws.getDetector(2).isMasked())) Output: diff --git a/docs/source/algorithms/ConvertSpectrumAxis-v1.rst b/docs/source/algorithms/ConvertSpectrumAxis-v1.rst index 9172723007ca8fb8ac484ffc63b90aa53a56e482..84599ff4a6562757005ead4435f4463d8534b51e 100644 --- a/docs/source/algorithms/ConvertSpectrumAxis-v1.rst +++ b/docs/source/algorithms/ConvertSpectrumAxis-v1.rst @@ -36,8 +36,8 @@ Usage theta = ConvertSpectrumAxis(dataws, Target="theta", Version=1) vertical_axis = theta.getAxis(1) - print "There are %d axis values" % vertical_axis.length() - print "Final theta value: %f (degrees)" % vertical_axis.getValue(vertical_axis.length() - 1) + print("There are {} axis values".format(vertical_axis.length())) + print("Final theta value: {:.6f} (degrees)".format(vertical_axis.getValue(vertical_axis.length() - 1))) .. testoutput:: diff --git a/docs/source/algorithms/ConvertSpectrumAxis-v2.rst b/docs/source/algorithms/ConvertSpectrumAxis-v2.rst index 8abcaadec53aae43ff3bf0ee9997675cbe302610..1e79f4ab6e544f016b237721a1cbec0baff85cb2 100644 --- a/docs/source/algorithms/ConvertSpectrumAxis-v2.rst +++ b/docs/source/algorithms/ConvertSpectrumAxis-v2.rst @@ -33,8 +33,8 @@ Usage theta = ConvertSpectrumAxis(dataws, Target="Theta") vertical_axis = theta.getAxis(1) - print "There are %d axis values" % vertical_axis.length() - print "Final theta value: %f (degrees)" % vertical_axis.getValue(vertical_axis.length() - 1) + print("There are {} axis values".format(vertical_axis.length())) + print("Final theta value: {:.6f} (degrees)".format(vertical_axis.getValue(vertical_axis.length() - 1))) .. testoutput:: @@ -51,8 +51,8 @@ Usage qws = ConvertSpectrumAxis(dataws, Target="ElasticQ", EFixed=15., EMode="Direct") vertical_axis = qws.getAxis(1) - print "There are %d axis values" % vertical_axis.length() - print "Final Q value: %f (A^-1)" % vertical_axis.getValue(vertical_axis.length() - 1) + print("There are {} axis values".format(vertical_axis.length())) + print("Final Q value: {:.6f} (A^-1)".format(vertical_axis.getValue(vertical_axis.length() - 1))) .. testoutput:: diff --git a/docs/source/algorithms/ConvertSpiceDataToRealSpace-v1.rst b/docs/source/algorithms/ConvertSpiceDataToRealSpace-v1.rst index a8dd3a8f6e40ebe480482a80a5bc4f8f5001277c..ab02f5f03b42a72e0a3738023501bf3349d9e511 100644 --- a/docs/source/algorithms/ConvertSpiceDataToRealSpace-v1.rst +++ b/docs/source/algorithms/ConvertSpiceDataToRealSpace-v1.rst @@ -191,7 +191,7 @@ Usage # output datamdws = mtd["Exp0231DataMD"] - print "Number of events = %d" % (datamdws.getNEvents()) + print("Number of events = {}".format(datamdws.getNEvents())) .. testcleanup:: ExLoadHB2ADataToMD diff --git a/docs/source/algorithms/ConvertTableToMatrixWorkspace-v1.rst b/docs/source/algorithms/ConvertTableToMatrixWorkspace-v1.rst index 549f6a604a753b56dd1a21bc0f6eec078491edee..8d86b1c18b62f8fe3f238db0898e7405941c1977 100644 --- a/docs/source/algorithms/ConvertTableToMatrixWorkspace-v1.rst +++ b/docs/source/algorithms/ConvertTableToMatrixWorkspace-v1.rst @@ -34,8 +34,8 @@ Usage ws=ConvertTableToMatrixWorkspace(t,"A","B","BError") - print "%s is a %s and the Y values are:" % (ws,ws.id()) - print ws.readY(0) + print("{} is a {} and the Y values are:".format(ws,ws.id())) + print(ws.readY(0)) Output: diff --git a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v1.rst b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v1.rst index 9b7ee8edddd17516181c89e141fdfb7acfe245a1..b524c3855fcdb5be7a4f60b7270352ce2ab8872d 100644 --- a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v1.rst +++ b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v1.rst @@ -99,8 +99,8 @@ Usage md = ConvertToDiffractionMDWorkspace(InputWorkspace=events, OutputWorkspace='md', OneEventPerBin=False, LorentzCorrection=True, SplitThreshold=150, Version=1) # A way to look at these results as a text: - print "Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims()) - print "Workspace Type is: ",md.id() + print("Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims())) + print("Workspace Type is: {}".format(md.id())) **Output:** diff --git a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst index c5fce3fa469226950e289fd1d8424854b580d1b0..8fc87deec53ad234c80fd8e972bfbe65e4ab76d3 100644 --- a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst +++ b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v2.rst @@ -75,8 +75,8 @@ Usage md = ConvertToDiffractionMDWorkspace(InputWorkspace=events, OutputWorkspace='md', OneEventPerBin=False, LorentzCorrection=True, SplitThreshold=150, Version=2) # A way to look at these results as a text: - print "Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims()) - print "Workspace Type is: ",md.id() + print("Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims())) + print("Workspace Type is: {}".format(md.id())) **Output:** diff --git a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v3.rst b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v3.rst index 73a16a001c7e00d8fe154cf1e6d29c5fd66a49af..baadcca1e3357a6459969f128730a2c219616ef4 100644 --- a/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v3.rst +++ b/docs/source/algorithms/ConvertToDiffractionMDWorkspace-v3.rst @@ -65,8 +65,8 @@ Usage md = ConvertToDiffractionMDWorkspace(InputWorkspace=events, OutputWorkspace='md', OneEventPerBin=False, LorentzCorrection=True, SplitThreshold=150) # A way to look at these results as a text: - print "Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims()) - print "Workspace Type is: ",md.id() + print("Resulting MD workspace has {0} events and {1} dimensions".format(md.getNEvents(),md.getNumDims())) + print("Workspace Type is: {}".format(md.id())) **Output:** diff --git a/docs/source/algorithms/ConvertToDistribution-v1.rst b/docs/source/algorithms/ConvertToDistribution-v1.rst index fc6885753f777e12b7b8ea6d85f628e340b5ac31..d753ba8c5d557e33b1f3d346e94823bbc6390431 100644 --- a/docs/source/algorithms/ConvertToDistribution-v1.rst +++ b/docs/source/algorithms/ConvertToDistribution-v1.rst @@ -27,15 +27,15 @@ Usage ws_multi = CreateSampleWorkspace("Histogram", "Multiple Peaks") - print "Is the workspace a distribution? " + str(ws_multi.isDistribution()) - print "The workspace has a level background of " + str(ws_multi.readY(0)[0]) + " counts." - print "The largest of which is " + str(ws_multi.readY(0)[60]) + " counts." + "\n" + print("Is the workspace a distribution? {}".format(ws_multi.isDistribution())) + print("The workspace has a level background of {} counts.".format(ws_multi.readY(0)[0])) + print("The largest of which is {} counts.\n".format(ws_multi.readY(0)[60])) ConvertToDistribution(ws_multi) - print "Is the workspace a distribution? " + str(ws_multi.isDistribution()) - print "The workspace has a level background of " + str(ws_multi.readY(0)[0]) + " counts." - print "The largest of which is " + str(ws_multi.readY(0)[60]) + " counts." + print("Is the workspace a distribution? {}".format(ws_multi.isDistribution())) + print("The workspace has a level background of {} counts.".format(ws_multi.readY(0)[0])) + print("The largest of which is {} counts.".format(ws_multi.readY(0)[60])) Output: diff --git a/docs/source/algorithms/ConvertToMD-v1.rst b/docs/source/algorithms/ConvertToMD-v1.rst index e5ab9cc69528567933751ceb41b11d677de8bfc3..e822302682555ca0c97a5d72bf355a8e0497ea79 100644 --- a/docs/source/algorithms/ConvertToMD-v1.rst +++ b/docs/source/algorithms/ConvertToMD-v1.rst @@ -108,9 +108,8 @@ Mantid for different testing tasks. # Look at sample results: # A way to look at these results as a text: - print "Resulting MD workspace has {0} events and {1} dimensions".format(ws.getNEvents(),ws.getNumDims()) - #print "MD workspace ID is:\n",ws.id - print "--------------------------------------------" + print("Resulting MD workspace has {0} events and {1} dimensions".format(ws.getNEvents(),ws.getNumDims())) + print("--------------------------------------------") .. testcleanup:: ExConvertToMDNoQ @@ -158,12 +157,12 @@ obtained in an experiment and stored in nxspe files are provided to it. pars['OverwriteExisting']=0 # Change this to false, if the files should/can be added in memory # #---> Start loop over contributing files - for n in xrange(0,5,1): + for n in range(0,5,1): source_file = 'MER19566_22.0meV_one2one125.nxspe'; # redefine source files list as function of loop number target = 'MDMAP_T1'+str(n)+'.nxs'; # check if the file already been converted to MD and is there if not(os.path.exists(target )): - print 'Converting ',source_file + print('Converting {}'.format(source_file)) #current_ws=LoadNXSPE(Filename=source) #### For the sample script, simulate load operation above current_ws = CreateSimulationWorkspace(Instrument='MAR',BinParams=[-3,1,3],UnitX='DeltaE',OutputWorkspace=source_file) @@ -198,9 +197,8 @@ obtained in an experiment and stored in nxspe files are provided to it. # plot results using sliceviewer #plotSlice(md_ws) # produce some test output - print "Resulting MD workspace contains {0} events and {1} dimensions".format(md_ws.getNEvents(),md_ws.getNumDims()) - #print "MD workspace ID is:\n",md_ws.id - print "--------------------------------------------" + print("Resulting MD workspace contains {0} events and {1} dimensions".format(md_ws.getNEvents(),md_ws.getNumDims())) + print("--------------------------------------------") .. testcleanup:: ExConvertToMDQ3D @@ -232,7 +230,7 @@ This example produces 3-dimensional dataset, with a temperature axis. try: DeleteWorkspace(RezWS) except ValueError: - print "Target ws ",RezWS," not found in analysis data service\n" + print("Target ws {} not found in analysis data service\n".format(RezWS)) # define convert to MD parameters pars = dict(); @@ -249,7 +247,7 @@ This example produces 3-dimensional dataset, with a temperature axis. # let's assume this is the temperature range obtained in experiments and # each data file is obtained for particular temperature. T = [1.0,2.0,3.0,3.5,4.0,5.0,6.0,7.0,8.0,9.0,9.5,10.0] - for i in xrange(0,len(T),1): + for i in range(0,len(T),1): # source = sorurce_file_name[i]; #current_ws=LoadNXSPE(Filename=source) # EMULATE LOAD OF DIFFERENT results obtained for different temperatures. ------> @@ -267,11 +265,8 @@ This example produces 3-dimensional dataset, with a temperature axis. DeleteWorkspace(current_ws) # end loop - #plotSlice(RezWS) # produce some test output - print "Resulting MD workspace contains {0} events and {1} dimensions".format(md_ws.getNEvents(),md_ws.getNumDims()) - #print "MD workspace ID is:\n",md_ws.id - print "--------------------------------------------" + print("Resulting MD workspace contains {0} events and {1} dimensions".format(md_ws.getNEvents(),md_ws.getNumDims())) .. testcleanup:: ExConvertToMD|Q|T @@ -285,7 +280,6 @@ This example produces 3-dimensional dataset, with a temperature axis. Target ws WS_3D not found in analysis data service Resulting MD workspace contains 605880 events and 3 dimensions - -------------------------------------------- .. categories:: diff --git a/docs/source/algorithms/ConvertToMDMinMaxGlobal-v1.rst b/docs/source/algorithms/ConvertToMDMinMaxGlobal-v1.rst index f61b6e7430f752a6ff2e0858d9490d6dd123a601..974b11cc4ef5eeaaccf0c7c4e0d4260473b4881a 100644 --- a/docs/source/algorithms/ConvertToMDMinMaxGlobal-v1.rst +++ b/docs/source/algorithms/ConvertToMDMinMaxGlobal-v1.rst @@ -60,9 +60,9 @@ Usage # evaluate |Q| transformation limits minn,maxx = ConvertToMDMinMaxGlobal(InputWorkspace=detWS,QDimensions='|Q|',dEAnalysisMode='Direct') # Look at sample results: - print 'MD workspace limits:' - print '|Q|_min: {0:10f}, dE_min: {1:10f}'.format(minn[0],minn[1]) - print '|Q|_max: {0:10f}, dE_max: {1:10f}'.format(maxx[0],maxx[1]) + print('MD workspace limits:') + print('|Q|_min: {0:10f}, dE_min: {1:10f}'.format(minn[0], minn[1])) + print('|Q|_max: {0:10f}, dE_max: {1:10f}'.format(maxx[0],maxx[1])) .. testcleanup:: ExConvertToMDMinMaxGlobalQ @@ -87,8 +87,8 @@ Usage # evaluate Q3D transformation limits, which includes converting units minn,maxx = ConvertToMDMinMaxGlobal(InputWorkspace=detWS,QDimensions='Q3D',dEAnalysisMode='Direct') - print 'Min values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(minn[0],minn[1],minn[2],minn[3]); - print 'Max values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(maxx[0],maxx[1],maxx[2],maxx[3]); + print('Min values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(minn[0],minn[1],minn[2],minn[3])) + print('Max values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(maxx[0],maxx[1],maxx[2],maxx[3])) .. testcleanup:: ExConvertToMDMinMaxGlobalQ3D @@ -111,9 +111,9 @@ Usage AddSampleLog(detWS,LogName='Ei',LogText='52.',LogType='Number'); minn,maxx = ConvertToMDMinMaxGlobal(InputWorkspace=detWS,QDimensions='CopyToMD',dEAnalysisMode='Direct',OtherDimensions='Ei') # Look at sample results: - print 'MD workspace limits:' - print 'TOF_min: {0:10f}, Ei_min: {1:10f}'.format(minn[0],minn[1]) - print 'TOF_max: {0:10f}, Ei_max: {1:10f}'.format(maxx[0],maxx[1]) + print('MD workspace limits:') + print('TOF_min: {0:10f}, Ei_min: {1:10f}'.format(minn[0],minn[1])) + print('TOF_max: {0:10f}, Ei_max: {1:10f}'.format(maxx[0],maxx[1])) .. testcleanup:: ExConvertToMDMinMaxGlobalCopyToMD diff --git a/docs/source/algorithms/ConvertToMDMinMaxLocal-v1.rst b/docs/source/algorithms/ConvertToMDMinMaxLocal-v1.rst index 5483d625eb8c2a3df87cd62d4f196da3fc2b284c..8974a0e5da4e7dde0a11ee90a0b79b018407e319 100644 --- a/docs/source/algorithms/ConvertToMDMinMaxLocal-v1.rst +++ b/docs/source/algorithms/ConvertToMDMinMaxLocal-v1.rst @@ -49,9 +49,9 @@ Usage # evaluate |Q| transformation limits minn,maxx = ConvertToMDMinMaxLocal(InputWorkspace=detWS,QDimensions='|Q|',dEAnalysisMode='Direct') # Look at sample results: - print 'MD workspace limits:' - print '|Q|_min: {0:10f}, dE_min: {1:10f}'.format(minn[0],minn[1]) - print '|Q|_max: {0:10f}, dE_max: {1:10f}'.format(maxx[0],maxx[1]) + print('MD workspace limits:') + print('|Q|_min: {0:10f}, dE_min: {1:10f}'.format(minn[0],minn[1])) + print('|Q|_max: {0:10f}, dE_max: {1:10f}'.format(maxx[0],maxx[1])) .. testcleanup:: ExConvertToMDMinMaxLocalQ @@ -76,8 +76,8 @@ Usage # evaluate Q3D transformation limits, which includes converting units minn,maxx = ConvertToMDMinMaxLocal(InputWorkspace=detWS,QDimensions='Q3D',dEAnalysisMode='Direct') - print 'Min values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(minn[0],minn[1],minn[2],minn[3]); - print 'Max values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(maxx[0],maxx[1],maxx[2],maxx[3]); + print('Min values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(minn[0],minn[1],minn[2],minn[3])) + print('Max values:: Qx: {0:10f}, Qy: {1:10f}, Qz: {2:10f}, dE:{3:10f}'.format(maxx[0],maxx[1],maxx[2],maxx[3])) .. testcleanup:: ExConvertToMDMinMaxLocalQ3D @@ -100,9 +100,9 @@ Usage AddSampleLog(detWS,LogName='Ei',LogText='52.',LogType='Number'); minn,maxx = ConvertToMDMinMaxLocal(InputWorkspace=detWS,QDimensions='CopyToMD',dEAnalysisMode='Direct',OtherDimensions='Ei') # Look at sample results: - print 'MD workspace limits:' - print 'TOF_min: {0:10f}, Ei_min: {1:10f}'.format(minn[0],minn[1]) - print 'TOF_max: {0:10f}, Ei_max: {1:10f}'.format(maxx[0],maxx[1]) + print('MD workspace limits:') + print('TOF_min: {0:10f}, Ei_min: {1:10f}'.format(minn[0],minn[1])) + print('TOF_max: {0:10f}, Ei_max: {1:10f}'.format(maxx[0],maxx[1])) .. testcleanup:: ExConvertToMDMinMaxLocalCopyToMD diff --git a/docs/source/algorithms/ConvertToMatrixWorkspace-v1.rst b/docs/source/algorithms/ConvertToMatrixWorkspace-v1.rst index 72b35b5bc5c5e32938cf61614d6ab2254dd2bfd0..3aecaa2f8d8b5f6d63e3077adadbd8b9c64a3cd7 100644 --- a/docs/source/algorithms/ConvertToMatrixWorkspace-v1.rst +++ b/docs/source/algorithms/ConvertToMatrixWorkspace-v1.rst @@ -25,8 +25,8 @@ Usage # Run the conversion algorithm histo_ws = ConvertToMatrixWorkspace(event_ws) # Check that the original workspace and the converted workspace have the same shape - print event_ws.getNumberHistograms(), event_ws.blocksize() - print histo_ws.getNumberHistograms(), histo_ws.blocksize() + print("{} {}".format(event_ws.getNumberHistograms(), event_ws.blocksize())) + print("{} {}".format(histo_ws.getNumberHistograms(), histo_ws.blocksize())) .. testoutput:: ConvertToMatrixWorkspaceSimpleExample @@ -43,8 +43,8 @@ Usage # Run the conversion algorithm histo_ws_rebinned = ConvertToMatrixWorkspace(event_ws_rebinned) # Check that the original workspace and the converted workspace have the same shape - print event_ws_rebinned.getNumberHistograms(), event_ws_rebinned.blocksize() - print histo_ws_rebinned.getNumberHistograms(), histo_ws_rebinned.blocksize() + print("{} {}".format(event_ws_rebinned.getNumberHistograms(), event_ws_rebinned.blocksize())) + print("{} {}".format(histo_ws_rebinned.getNumberHistograms(), histo_ws_rebinned.blocksize())) Output: diff --git a/docs/source/algorithms/ConvertToReflectometryQ-v1.rst b/docs/source/algorithms/ConvertToReflectometryQ-v1.rst index c355a7f8bfaeccc16db59096fd69f8dda3e09f06..f97a14c55836cbb10bdbfb905bd96bda572637aa 100644 --- a/docs/source/algorithms/ConvertToReflectometryQ-v1.rst +++ b/docs/source/algorithms/ConvertToReflectometryQ-v1.rst @@ -122,9 +122,9 @@ Normalised Polygon Transformation pipf, vertexes_pipf = ConvertToReflectometryQ(InputWorkspace='SignedTheta_vs_Wavelength', OutputDimensions='P (lab frame)', Extents='0,0.1,-0.02,0.15', OutputAsMDWorkspace=False,Method='NormalisedPolygon') - print qxqy.getDimension(0).name, qxqy.getDimension(1).name - print kikf.getDimension(0).name, kikf.getDimension(1).name - print pipf.getDimension(0).name, pipf.getDimension(1).name + print("{} {}".format(qxqy.getDimension(0).name, qxqy.getDimension(1).name)) + print("{} {}".format(kikf.getDimension(0).name, kikf.getDimension(1).name)) + print("{} {}".format(pipf.getDimension(0).name, pipf.getDimension(1).name)) Output: diff --git a/docs/source/algorithms/ConvertToYSpace-v1.rst b/docs/source/algorithms/ConvertToYSpace-v1.rst index 765cbb88cc22cc80eb5061dafa250c36b48a30b5..b1cc08cc506cab3c4c983239658cca78869ae515 100644 --- a/docs/source/algorithms/ConvertToYSpace-v1.rst +++ b/docs/source/algorithms/ConvertToYSpace-v1.rst @@ -50,8 +50,8 @@ Usage wsY=ConvertToYSpace(InputWorkspace='tof_ws',Mass='30') # # Look at sample results: - print 'part of the converted workspace:' - for i in xrange(0,10): print wsY.readX(0)[i],wsY.readY(0)[i],wsY.readE(0)[i] + print('part of the converted workspace:') + for i in range(0,10): print("{:.9f} {:.11f} {}".format(wsY.readX(0)[i], wsY.readY(0)[i], wsY.readE(0)[i])) @@ -69,12 +69,12 @@ Usage 217.970903402 4.44292943299 0.0 217.763039952 4.43608530232 0.0 217.555655487 4.42925581439 0.0 - 217.34874818 4.42244092015 0.0 + 217.348748180 4.42244092015 0.0 217.142316213 4.41564057078 0.0 - 216.936357776 4.4088547177 0.0 + 216.936357776 4.40885471770 0.0 216.730871069 4.40208331255 0.0 216.525854298 4.39532630718 0.0 - 216.32130568 4.38858365367 0.0 + 216.321305680 4.38858365367 0.0 .. categories:: diff --git a/docs/source/algorithms/ConvertUnits-v1.rst b/docs/source/algorithms/ConvertUnits-v1.rst index ffac24bfda385548ff62a67f5ee9a71327dcdb1b..c755f197ba76df381c66d7f5e4a17233b0df78df 100644 --- a/docs/source/algorithms/ConvertUnits-v1.rst +++ b/docs/source/algorithms/ConvertUnits-v1.rst @@ -62,8 +62,8 @@ Usage ws = CreateSampleWorkspace("Histogram",NumBanks=1,BankPixelWidth=1) wsOut = ConvertUnits(ws,Target="Wavelength") - print "Input", ws.readX(0)[ws.blocksize()-1] - print "Output", wsOut.readX(0)[wsOut.blocksize()-1] + print("Input {}".format(ws.readX(0)[ws.blocksize()-1])) + print("Output {:.11f}".format(wsOut.readX(0)[wsOut.blocksize()-1])) Output: diff --git a/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst b/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst index 988f8a3ceb33cca0a500d06703abed5d1d523dd3..fc6e37b0c5370e561651e04b50337d62001ae349 100644 --- a/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst +++ b/docs/source/algorithms/ConvertUnitsUsingDetectorTable-v1.rst @@ -54,8 +54,8 @@ Usage wsOut = ConvertUnitsUsingDetectorTable(ws,Target="Wavelength",DetectorParameters=detpars) - print "Input", ws.readX(0)[ws.blocksize()-1] - print "Output", wsOut.readX(0)[wsOut.blocksize()-1] + print("Input {}".format(ws.readX(0)[ws.blocksize()-1])) + print("Output {:.11f}".format(wsOut.readX(0)[wsOut.blocksize()-1])) Output: diff --git a/docs/source/algorithms/ConvolveWorkspaces-v1.rst b/docs/source/algorithms/ConvolveWorkspaces-v1.rst index 33294c03bfed87ff42f1516074a2d66673f4bf85..fd67dcf082c47e52312259bbd36bf501aa01ab73 100644 --- a/docs/source/algorithms/ConvolveWorkspaces-v1.rst +++ b/docs/source/algorithms/ConvolveWorkspaces-v1.rst @@ -27,7 +27,7 @@ Usage #restrict the number of wavelength points to speed up the example wsOut = ConvolveWorkspaces(ws,ws) - print "Output: ", wsOut.readY(0) + print("Output: {}".format(wsOut.readY(0))) Output: diff --git a/docs/source/algorithms/CopyDetectorMapping-v1.rst b/docs/source/algorithms/CopyDetectorMapping-v1.rst index aee81e88a5e111cbc29df6d9df5dadea7354587e..d03fe81b0830c1d62f01dd790b2a8629a1e93b94 100644 --- a/docs/source/algorithms/CopyDetectorMapping-v1.rst +++ b/docs/source/algorithms/CopyDetectorMapping-v1.rst @@ -39,14 +39,14 @@ Usage: to_match = GroupDetectors(InputWorkspace=to_match, PreserveEvents=False, CopyGroupingFromWorkspace='grouping_ws') - print 'Spectrum 0 detectors before copy: ' + str(to_remap.getSpectrum(0).getDetectorIDs()) + print('Spectrum 0 detectors before copy: {}'.format(to_remap.getSpectrum(0).getDetectorIDs())) # Copy the grouping to another workspace CopyDetectorMapping(WorkspaceToMatch='to_match', WorkspaceToRemap='to_remap', IndexBySpectrumNumber=True) - print 'Spectrum 0 detectors after copy: ' + str(to_remap.getSpectrum(0).getDetectorIDs()) + print('Spectrum 0 detectors after copy: {}'.format(to_remap.getSpectrum(0).getDetectorIDs())) Output: diff --git a/docs/source/algorithms/CopyInstrumentParameters-v1.rst b/docs/source/algorithms/CopyInstrumentParameters-v1.rst index b3b0f53b92d3a34bf19fa27b497c23450b13c807..434ea4a7f72753798383b815d21b518af0a6d017 100644 --- a/docs/source/algorithms/CopyInstrumentParameters-v1.rst +++ b/docs/source/algorithms/CopyInstrumentParameters-v1.rst @@ -42,14 +42,14 @@ Usage # Show positions in 1st workspace for i in spectra: det = ws1.getDetector(i) - print "Position of Detector ID=%i in 1st workspace: %.0f,%.0f,%.0f" % (det.getID(), - det.getPos().X(), det.getPos().Y(), det.getPos().Z()) + print("Position of Detector ID={} in 1st workspace: {:.0f},{:.0f},{:.0f}". + format(det.getID(), det.getPos().X(), det.getPos().Y(), det.getPos().Z())) # Show positions in 2nd workspace before CopyInstrumrentParameters for i in spectra: det = ws2.getDetector(i) - print "Position of Detector ID=%i in 2nd workspace before CopyInstrumentParameters: %.0f,%.0f,%.0f" % (det.getID(), - det.getPos().X(), det.getPos().Y(), det.getPos().Z()) + print("Position of Detector ID=%i in 2nd workspace before CopyInstrumentParameters: %.0f,%.0f,%.0f" % (det.getID(), + det.getPos().X(), det.getPos().Y(), det.getPos().Z())) # Copy paremeters from 1st workspace to 2nd workspace @@ -59,8 +59,8 @@ Usage # Show positions in 2nd workspace after CopyInstrumrentParameters for i in spectra: det = ws2.getDetector(i) - print "Position of Detector ID=%i in 2nd workspace after CopyInstrumentParameters: %.0f,%.0f,%.0f" % (det.getID(), - det.getPos().X(), det.getPos().Y(), det.getPos().Z()) + print("Position of Detector ID={} in 2nd workspace after CopyInstrumentParameters: {:.0f},{:.0f},{:.0f}". + format(det.getID(), det.getPos().X(), det.getPos().Y(), det.getPos().Z())) Output: diff --git a/docs/source/algorithms/CopyLogs-v1.rst b/docs/source/algorithms/CopyLogs-v1.rst index 1a4ff51ae67055357d2ae6d665740daa74a33846..a9cb195add6e4379c7e242eae5ebcdf34ccd625b 100644 --- a/docs/source/algorithms/CopyLogs-v1.rst +++ b/docs/source/algorithms/CopyLogs-v1.rst @@ -54,9 +54,9 @@ Usage log_w = run2.getLogData('w') # Print the log values - print "Before CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", w =", log_w.value + print("Before CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , w = {}".format(log_x2.value, log_w.value )) # Copy logs of 1st workspace to 2nd workspace CopyLogs( demo_ws1, demo_ws2) @@ -73,9 +73,9 @@ Usage log_z2 = run2.getLogData('z') # Print the log values - print "After CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", w =", log_w.value,", y =", log_y2.value,", z =", log_z2.value + print("After CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , w = {} , y = {} , z = {}".format(log_x2.value, log_w.value, log_y2.value, log_z2.value)) Output: @@ -116,9 +116,9 @@ Output: log_w = run2.getLogData('w') # Print the log values - print "Before CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", w =", log_w.value + print("Before CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , w = {}".format(log_x2.value, log_w.value)) # Copy logs of 1st workspace to 2nd workspace CopyLogs( demo_ws1, demo_ws2, MergeStrategy='MergeKeepExisting') @@ -135,9 +135,9 @@ Output: log_z2 = run2.getLogData('z') # Print the log values - print "After CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", w =", log_w.value,", y =", log_y2.value,", z =", log_z2.value + print("After CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , w = {} , y = {} , z = {}".format(log_x2.value, log_w.value, log_y2.value, log_z2.value)) Output: @@ -178,9 +178,9 @@ Output: log_w = run2.getLogData('w') # Print the log values - print "Before CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", w =", log_w.value + print("Before CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , w = {}".format(log_x2.value, log_w.value)) # Copy logs of 1st workspace to 2nd workspace CopyLogs( demo_ws1, demo_ws2, MergeStrategy='WipeExisting') @@ -196,9 +196,9 @@ Output: log_z2 = run2.getLogData('z') # Print the log values - print "After CopyLog" - print "1st workspace log values x =",log_x1.value,", y =", log_y.value,", z =", log_z.value - print "2nd workspace log values x =",log_x2.value,", y =", log_y2.value,", z =", log_z2.value + print("After CopyLog") + print("1st workspace log values x = {} , y = {} , z = {}".format(log_x1.value, log_y.value, log_z.value)) + print("2nd workspace log values x = {} , y = {} , z = {}".format(log_x2.value, log_y2.value, log_z2.value)) Output: diff --git a/docs/source/algorithms/CopySample-v1.rst b/docs/source/algorithms/CopySample-v1.rst index 6aa09357be42d23bf2a4c37130265c19ed9e906b..aea9496426035111c42e98570a56222c0ad046ec 100644 --- a/docs/source/algorithms/CopySample-v1.rst +++ b/docs/source/algorithms/CopySample-v1.rst @@ -46,7 +46,8 @@ Usage #do a quick check ol=data.sample().getOrientedLattice() - print "Data lattice parameters are:",ol.a(),ol.b(),ol.c(),ol.alpha(),ol.beta(),ol.gamma() + print("Data lattice parameters are: {} {} {} {} {} {}".format( + ol.a(), ol.b(), ol.c(), ol.alpha(), ol.beta(), ol.gamma())) .. testcleanup:: CopySample diff --git a/docs/source/algorithms/CorelliCrossCorrelate-v1.rst b/docs/source/algorithms/CorelliCrossCorrelate-v1.rst index 941fe44e23d0da36bb90f66c220c8d378ea300cc..daec61b383639a1c2dca468418dcee019f805c3e 100644 --- a/docs/source/algorithms/CorelliCrossCorrelate-v1.rst +++ b/docs/source/algorithms/CorelliCrossCorrelate-v1.rst @@ -36,9 +36,9 @@ Usage # Run the cross-correlation. This is using a TDC timing offset of 56000ns. wsOut = CorelliCrossCorrelate(ws, 56000) - print 'The detector 172305 has ' + str(ws.getSpectrum(172305).getNumberEvents()) + ' events.' - print 'The event weights before cross-correlation are ' + str(ws.getSpectrum(172305).getWeights()) - print 'The event weights after cross-correlation are ' + str(wsOut.getSpectrum(172305).getWeights()) + print('The detector 172305 has {} events.'.format(ws.getSpectrum(172305).getNumberEvents())) + print('The event weights before cross-correlation are {}'.format(ws.getSpectrum(172305).getWeights())) + print('The event weights after cross-correlation are {}'.format(wsOut.getSpectrum(172305).getWeights())) Output: diff --git a/docs/source/algorithms/CorrectKiKf-v1.rst b/docs/source/algorithms/CorrectKiKf-v1.rst index 26641b9fc1788a5a62279af5be55d4e0bee54bc0..ec0daa197c7b7fb55e51b59a81a1c331cf1f55d0 100644 --- a/docs/source/algorithms/CorrectKiKf-v1.rst +++ b/docs/source/algorithms/CorrectKiKf-v1.rst @@ -32,8 +32,8 @@ Usage wsOut = CorrectKiKf(ws, EMode="Direct", EFixed=7.5) - print ("First five bins:") - print ("index orig corrected") + print("First five bins:") + print("index orig corrected") for i in range(5): print(" %i %.2f %.2f" % (i,ws.readY(0)[i],wsOut.readY(0)[i])) diff --git a/docs/source/algorithms/CorrectLogTimes-v1.rst b/docs/source/algorithms/CorrectLogTimes-v1.rst index a17c2a34a1fcfc85ca1d1bb0a7d24cff59157002..846e2ab5d825b1e0426314ed49caf6811f1dc3b0 100644 --- a/docs/source/algorithms/CorrectLogTimes-v1.rst +++ b/docs/source/algorithms/CorrectLogTimes-v1.rst @@ -25,12 +25,12 @@ Usage .. testcode:: CorrectLogTimes w=Load('CNCS_7860') - print "Original start time for 'proton_charge':", str(w.getRun()['proton_charge'].times[0]).strip() - print "Original start time for 'Speed5':", str(w.getRun()['Speed5'].times[0]).strip() + print("Original start time for 'proton_charge': {}".format(w.getRun()['proton_charge'].times[0]).strip()) + print("Original start time for 'Speed5': {}".format(w.getRun()['Speed5'].times[0]).strip()) #Change the log times CorrectLogTimes(w) #there should be almost 10 seconds different than before - print "Corrected start time for 'Speed5':", str(w.getRun()['Speed5'].times[0]).strip() + print("Corrected start time for 'Speed5': {}".format(w.getRun()['Speed5'].times[0]).strip()) .. testcleanup:: CorrectLogTimes diff --git a/docs/source/algorithms/CorrectTOF-v1.rst b/docs/source/algorithms/CorrectTOF-v1.rst index 313931f344b1a7db6a57b2697307a491550b0cff..9fe776bc90b585a1b305be7ce25ad30ccb1f442f 100644 --- a/docs/source/algorithms/CorrectTOF-v1.rst +++ b/docs/source/algorithms/CorrectTOF-v1.rst @@ -63,9 +63,9 @@ Usage # apply correction wscorr = CorrectTOF(ws, table) - print "Correction term dt = t_el - t_table = ", round(8190.02 - 8128.59, 2) + print("Correction term dt = t_el - t_table = {:.2f}".format(8190.02 - 8128.59, 2)) difference = wscorr.readX(0) - ws.readX(0) - print "Difference between input and corrected workspaces: ", round(difference[10],2) + print("Difference between input and corrected workspaces: {}".format(round(difference[10],2))) Output: @@ -94,9 +94,9 @@ Output: ws_dE = ConvertUnits(ws_tof_corr, Target='DeltaE', EMode='Direct', EFixed=2.27) ConvertToDistribution(ws_dE) - print "5 X values of raw data: ", numpy.round(ws_tof.readX(200)[580:585],2) - print "5 X values corrected data: ", numpy.round(ws_tof_corr.readX(200)[580:585],2) - print "5 X values after units conversion: ", numpy.round(ws_dE.readX(200)[580:585], 2) + print("5 X values of raw data: {}".format(numpy.round(ws_tof.readX(200)[580:585],2))) + print("5 X values corrected data: {}".format(numpy.round(ws_tof_corr.readX(200)[580:585],2))) + print("5 X values after units conversion: {}".format(numpy.round(ws_dE.readX(200)[580:585], 2))) Output: diff --git a/docs/source/algorithms/CountReflections-v1.rst b/docs/source/algorithms/CountReflections-v1.rst index a7134d5a017762d76bdfbeefe6eef3c7d7b127d5..5d404ab75c48be0b50faf0b9c57177744d127593 100644 --- a/docs/source/algorithms/CountReflections-v1.rst +++ b/docs/source/algorithms/CountReflections-v1.rst @@ -62,12 +62,12 @@ data, because some intensities in the input file are 0, so these reflections are LatticeCentering='Robv', MinDSpacing=0.205, MaxDSpacing=2.08, MissingReflectionsWorkspace='') - print 'Data set statistics:' - print ' Peaks: {0}'.format(peaks.getNumberPeaks()) - print ' Unique: {0}'.format(unique) - print ' Completeness: {0}%'.format(round(completeness * 100, 2)) - print ' Redundancy: {0}'.format(round(redundancy, 2)) - print ' Multiply observed: {0}%'.format(round(multiple*100, 2)) + print('Data set statistics:') + print(' Peaks: {0}'.format(peaks.getNumberPeaks())) + print(' Unique: {0}'.format(unique)) + print(' Completeness: {0}%'.format(round(completeness * 100, 2))) + print(' Redundancy: {0}'.format(round(redundancy, 2))) + print(' Multiply observed: {0}%'.format(round(multiple*100, 2))) Output: diff --git a/docs/source/algorithms/CreateCalFileByNames-v1.rst b/docs/source/algorithms/CreateCalFileByNames-v1.rst index 5ad877b4afe10314597841805625c4f5e425364e..35952daf80fc12cdbb4ce8f2bcc6a82ecb28dbd6 100644 --- a/docs/source/algorithms/CreateCalFileByNames-v1.rst +++ b/docs/source/algorithms/CreateCalFileByNames-v1.rst @@ -53,7 +53,7 @@ Usage # Check the output file - print "File Exists:", os.path.exists(newFile) + print("File Exists: {}".format(os.path.exists(newFile))) Output: diff --git a/docs/source/algorithms/CreateChunkingFromInstrument-v1.rst b/docs/source/algorithms/CreateChunkingFromInstrument-v1.rst index 456c573450c18e6eef29cc3687751bb5ab1d495d..3486c253d892a28e6318ad8992a3de44bcc1f093 100644 --- a/docs/source/algorithms/CreateChunkingFromInstrument-v1.rst +++ b/docs/source/algorithms/CreateChunkingFromInstrument-v1.rst @@ -28,7 +28,7 @@ Usage pg3 = LoadEmptyInstrument(Filename="POWGEN_Definition_2015-08-01.xml") ws = CreateChunkingFromInstrument(InputWorkspace=pg3, ChunkBy="Group") - print "Created %i Chunks" % ws.rowCount() + print("Created {} Chunks".format(ws.rowCount())) Output: @@ -41,7 +41,7 @@ Output: .. testcode:: ExSnap ws = CreateChunkingFromInstrument(InstrumentName="snap", ChunkNames="East,West", MaxBankNumber=20) - print "Created %i Chunks" % ws.rowCount() + print("Created {} Chunks".format(ws.rowCount())) Output: diff --git a/docs/source/algorithms/CreateDummyCalFile-v1.rst b/docs/source/algorithms/CreateDummyCalFile-v1.rst index f42aef4dbd3aa98a15f7ecd36497887b636fadad..385ce99d981219c76c4115157081d56b550ba7dd 100644 --- a/docs/source/algorithms/CreateDummyCalFile-v1.rst +++ b/docs/source/algorithms/CreateDummyCalFile-v1.rst @@ -45,7 +45,7 @@ Usage CreateDummyCalFile(ws_1,newFile) # Check the output file - print "File Exists:", os.path.exists(newFile) + print("File Exists: {}".format(os.path.exists(newFile))) f = open( newFile, 'r' ) file = f.read().split('\n') @@ -54,7 +54,7 @@ Usage for line in file[0:6]: # print the line truncating before system dependent line break can take effect # also stripping off any trailing spaces - print line[0:89].rstrip() + print(line[0:89].rstrip()) Output: diff --git a/docs/source/algorithms/CreateEPP-v1.rst b/docs/source/algorithms/CreateEPP-v1.rst index 456fbe2b2af9ba4ff047f9929fc5f45c48177bed..43a4b5f9bb2e8e0b26cfb30fceebf229b5dc1c0a 100644 --- a/docs/source/algorithms/CreateEPP-v1.rst +++ b/docs/source/algorithms/CreateEPP-v1.rst @@ -77,9 +77,9 @@ Usage findEPPWS = FindEPP(InputWorkspace='exWS') epp1 = createEPPWS.cell('PeakCentre', 0) - print('CreateEPP gives {0} as the first elastic peak position.'.format(epp1)) + print('CreateEPP gives {0:.8f} as the first elastic peak position.'.format(epp1)) epp2 = findEPPWS.cell('PeakCentre', 0) - print('FindEPP gives {0}.'.format(epp2)) + print('FindEPP gives {0:.8f}.'.format(epp2)) Output: diff --git a/docs/source/algorithms/CreateEmptyTableWorkspace-v1.rst b/docs/source/algorithms/CreateEmptyTableWorkspace-v1.rst index 6191c24c98fc72d21a3c32c54979e0ad3cdf3d82..73e10d17ab6b47705d6c977af2f33b57bcb4b9a7 100644 --- a/docs/source/algorithms/CreateEmptyTableWorkspace-v1.rst +++ b/docs/source/algorithms/CreateEmptyTableWorkspace-v1.rst @@ -35,10 +35,10 @@ Usage my_table.addRow(["IRIS", 8465]) my_table.addRow(["SANS2D", 20462]) - print "The run number for IRIS is " + str(my_table.cell("Run Number", 1)) + "." - print "The number of rows is " + str(my_table.rowCount()) + "." - print "The title of the table is " + my_table.getTitle() + "." - print "Remember, the table is a workspace. It's name is \"" + my_table.name() + "\"." + print("The run number for IRIS is {}.".format(my_table.cell("Run Number", 1))) + print("The number of rows is {}.".format(my_table.rowCount())) + print("The title of the table is {}.".format(my_table.getTitle())) + print("Remember, the table is a workspace. It's name is \"{}\".".format(my_table.name())) Output: diff --git a/docs/source/algorithms/CreateFlatEventWorkspace-v1.rst b/docs/source/algorithms/CreateFlatEventWorkspace-v1.rst index 4f92d24c4e00f8588a18dbab9f64e235b18bf180..6dc23cbb88b83863486f52c5e14ac90ca19dafc5 100644 --- a/docs/source/algorithms/CreateFlatEventWorkspace-v1.rst +++ b/docs/source/algorithms/CreateFlatEventWorkspace-v1.rst @@ -26,10 +26,10 @@ Usage #to compare we need to match the bins wsOut=RebinToWorkspace(wsOut,ws,PreserveEvents=True) - print "The values for every 10th bin." - print "bin\tws\twsOut" + print("The values for every 10th bin.") + print("bin\tws\twsOut") for i in range (0,ws.blocksize(),10): - print "%i\t%.2f\t%.2f" % (i,ws.readY(0)[i],wsOut.readY(0)[i]) + print("{}\t{:.2f}\t{:.2f}".format(i,ws.readY(0)[i],wsOut.readY(0)[i])) Output: diff --git a/docs/source/algorithms/CreateGroupingWorkspace-v1.rst b/docs/source/algorithms/CreateGroupingWorkspace-v1.rst index 96c7607422e589c2c6e5e8a358fd8c38dd43a6e9..c472673786b026cfb187f4bdfbb430348ee0ace0 100644 --- a/docs/source/algorithms/CreateGroupingWorkspace-v1.rst +++ b/docs/source/algorithms/CreateGroupingWorkspace-v1.rst @@ -49,7 +49,7 @@ Usage grouping = result[0] inst1 = grouping.getInstrument() comp1 = inst1.getComponentByName("MUSR") - print "Instrument name =", comp1.getName() + print("Instrument name = {}".format(comp1.getName())) Output: @@ -73,7 +73,7 @@ Output: grouping = result[0] inst1 = grouping.getInstrument() comp1 = inst1.getComponentByName("MUSR") - print "Instrument name =", comp1.getName() + print("Instrument name = {}".format(comp1.getName())) Output: @@ -92,7 +92,7 @@ Output: grouping = result[0] inst1 = grouping.getInstrument() comp1 = inst1.getComponentByName("GEM") - print "Instrument name =", comp1.getName() + print("Instrument name = {}".format(comp1.getName())) Output: @@ -106,8 +106,8 @@ Output: grouping_ws, spectra_count, group_count = CreateGroupingWorkspace(InstrumentName='IRIS', ComponentName='graphite', FixedGroupCount=5) - print "Number of grouped spectra:",spectra_count - print "Number of groups:",group_count + print("Number of grouped spectra: {}".format(spectra_count)) + print("Number of groups: {}".format(group_count)) Output: diff --git a/docs/source/algorithms/CreateLeBailFitInput-v1.rst b/docs/source/algorithms/CreateLeBailFitInput-v1.rst index 69835244f9da3370525f9e282864b9749b4ec6d7..c39b0896524ecd098e98e0e7787df18e103df2ea 100644 --- a/docs/source/algorithms/CreateLeBailFitInput-v1.rst +++ b/docs/source/algorithms/CreateLeBailFitInput-v1.rst @@ -60,7 +60,7 @@ Usage # Examine partablews = mtd["PG3_Bank3_ParTable"] braggtablews = mtd["LaB6_HKL_Table"] - print "Number Bragg peaks from .hkl file is %d. Number of peak profile parameters is %d." % (braggtablews.rowCount(), partablews.rowCount()) + print("Number Bragg peaks from .hkl file is {}. Number of peak profile parameters is {}.".format(braggtablews.rowCount(), partablews.rowCount())) .. testcleanup:: ExCreateLBInputs diff --git a/docs/source/algorithms/CreateLogPropertyTable-v1.rst b/docs/source/algorithms/CreateLogPropertyTable-v1.rst index dde3cf8515849385252372f4f5ae90d63eac3d64..ec6bb4ceac7f54525652827e02acfcb62e0f5f17 100644 --- a/docs/source/algorithms/CreateLogPropertyTable-v1.rst +++ b/docs/source/algorithms/CreateLogPropertyTable-v1.rst @@ -76,8 +76,8 @@ Usage tab=CreateLogPropertyTable(InputWorkspaces='a,b,c',LogPropertyNames='run_title,ImportantParameter') #do some tests - print "Column names are: ",tab.getColumnNames() - print "The values of the ImportantParameter are:",tab.column(1) + print("Column names are: {}".format(tab.getColumnNames())) + print("The values of the ImportantParameter are: {}".format(tab.column(1))) .. testcleanup:: CreateLogPropertyTable diff --git a/docs/source/algorithms/CreateLogTimeCorrection-v1.rst b/docs/source/algorithms/CreateLogTimeCorrection-v1.rst index ee168a6b951866278aa263a879e09f9045736f2a..1208abebe3d129655b0829ca4685ffeef1b25179 100644 --- a/docs/source/algorithms/CreateLogTimeCorrection-v1.rst +++ b/docs/source/algorithms/CreateLogTimeCorrection-v1.rst @@ -33,24 +33,24 @@ Usage cfile.close() # Print out partial result - print "From output TableWorkspace:" - print "detector (ID: %d) correction = %-.6f" % (corrws.cell(0, 0), corrws.cell(0, 1)) - print "detector (ID: %d) correction = %-.6f" % (corrws.cell(10, 0), corrws.cell(10, 1)) - print "detector (ID: %d) correction = %-.6f" % (corrws.cell(100, 0), corrws.cell(100, 1)) - print "detector (ID: %d) correction = %-.6f" % (corrws.cell(1000, 0), corrws.cell(1000, 1)) - print "detector (ID: %d) correction = %-.6f" % (corrws.cell(10000, 0), corrws.cell(1000, 1)) - - print "\nFrom output file:" + print("From output TableWorkspace:") + print("detector (ID: {}) correction = {:.6f}".format(corrws.cell(0, 0), corrws.cell(0, 1))) + print("detector (ID: {}) correction = {:.6f}".format(corrws.cell(10, 0), corrws.cell(10, 1))) + print("detector (ID: {}) correction = {:.6f}".format(corrws.cell(100, 0), corrws.cell(100, 1))) + print("detector (ID: {}) correction = {:.6f}".format(corrws.cell(1000, 0), corrws.cell(1000, 1))) + print("detector (ID: {}) correction = {:.6f}".format(corrws.cell(10000, 0), corrws.cell(1000, 1))) + + print("\nFrom output file:") terms = lines[0].split() - print "detector (ID: %s) correction = %s" % (terms[0], terms[1]) + print("detector (ID: {}) correction = {}".format(terms[0], terms[1])) terms = lines[10].split() - print "detector (ID: %s) correction = %s" % (terms[0], terms[1]) + print("detector (ID: {}) correction = {}".format(terms[0], terms[1])) terms = lines[100].split() - print "detector (ID: %s) correction = %s" % (terms[0], terms[1]) + print("detector (ID: {}) correction = {}".format(terms[0], terms[1])) terms = lines[1000].split() - print "detector (ID: %s) correction = %s" % (terms[0], terms[1]) + print("detector (ID: {}) correction = {}".format(terms[0], terms[1])) terms = lines[10000].split() - print "detector (ID: %s) correction = %s" % (terms[0], terms[1]) + print("detector (ID: {}) correction = {}".format(terms[0], terms[1])) .. testcleanup:: ExHistSimple diff --git a/docs/source/algorithms/CreateMD-v1.rst b/docs/source/algorithms/CreateMD-v1.rst index 2b1afe98324446de90452172e355b3d84d178b8d..6dbf4667c57ea593e6dcee44339fc31e892ebdcf 100644 --- a/docs/source/algorithms/CreateMD-v1.rst +++ b/docs/source/algorithms/CreateMD-v1.rst @@ -80,7 +80,7 @@ Workflow ndims = new_mdew.getNumDims() for i in range(ndims): dim = new_mdew.getDimension(i) - print dim.getName() + print(dim.getName()) Output ^^^^^^ @@ -116,7 +116,7 @@ Output ndims = new_merged.getNumDims() for i in range(ndims): dim = new_merged.getDimension(i) - print dim.getName() + print(dim.getName()) Output ^^^^^^ @@ -152,7 +152,7 @@ Output ndims = new_merged.getNumDims() for i in range(ndims): dim = new_merged.getDimension(i) - print dim.getName() + print(dim.getName()) Output ^^^^^^ diff --git a/docs/source/algorithms/CreateMDHistoWorkspace-v1.rst b/docs/source/algorithms/CreateMDHistoWorkspace-v1.rst index 1d3b7a79855f4b5083b8f5a3914fa1b9e082dc79..f7d5b533368f7c5d10eb60aa2d8a2e187fca716f 100644 --- a/docs/source/algorithms/CreateMDHistoWorkspace-v1.rst +++ b/docs/source/algorithms/CreateMDHistoWorkspace-v1.rst @@ -51,14 +51,15 @@ Usage NumberOfBins='10,10',Names='Dim1,Dim2',Units='MomentumTransfer,EnergyTransfer') # check it looks like the one we wanted - print 'created workspace is of type: {0}\n'.format(ws.id()), - print 'and has {0} dimensions with {1} points and {2} events'.format(ws.getNumDims(),ws.getNPoints(),ws.getNEvents()); + print('created workspace is of type: {0}'.format(ws.id())) + print('and has {0} dimensions with {1} points and {2} events'. + format(ws.getNumDims(),ws.getNPoints(),ws.getNEvents())) d1=ws.getDimension(0) - print 'dimension 0 has ID: {0}; nBins={1}; min: {2}; max: {3} in units of: {4}\n'.format(d1.getDimensionId(),d1.getNBins(),\ - d1.getMinimum(),d1.getMaximum(),d1.getUnits()), + print('dimension 0 has ID: {0}; nBins={1}; min: {2}; max: {3} in units of: {4}'. + format(d1.getDimensionId(), d1.getNBins(), d1.getMinimum(), d1.getMaximum(),d1.getUnits())) d1=ws.getDimension(1) - print 'dimension 1 has ID: {0}; nBins={1}; min: {2}; max: {3} in units of: {4}\n'.format(d1.getDimensionId(),d1.getNBins(),\ - d1.getMinimum(),d1.getMaximum(),d1.getUnits()), + print('dimension 1 has ID: {0}; nBins={1}; min: {2}; max: {3} in units of: {4}'. + format(d1.getDimensionId(), d1.getNBins(), d1.getMinimum(), d1.getMaximum(), d1.getUnits())) **Output:** diff --git a/docs/source/algorithms/CreateMDWorkspace-v1.rst b/docs/source/algorithms/CreateMDWorkspace-v1.rst index c7e342fa340506424e041296870dca2ca0fd6da6..01682818c6820c79086ffe8902b6a2f5bfd1f574 100644 --- a/docs/source/algorithms/CreateMDWorkspace-v1.rst +++ b/docs/source/algorithms/CreateMDWorkspace-v1.rst @@ -35,10 +35,10 @@ Usage mdws = CreateMDWorkspace(Dimensions=3, Extents='-10,10,-10,10,-10,10', Names='A,B,C', Units='U,U,U') - print "mdws is a " + mdws.id() - print "with {0} dimensions:".format(mdws.getNumDims()) + print("mdws is a " + mdws.id()) + print("with {0} dimensions:".format(mdws.getNumDims())) for i in range (mdws.getNumDims()): - print mdws.getDimension(i).name + print(mdws.getDimension(i).name) Output: diff --git a/docs/source/algorithms/CreatePSDBleedMask-v1.rst b/docs/source/algorithms/CreatePSDBleedMask-v1.rst index 65b36dc5f7d3610439d564bbe24cad3c6dd075ff..632ba9484bdf2159af3bc6ac269aab318bd2110f 100644 --- a/docs/source/algorithms/CreatePSDBleedMask-v1.rst +++ b/docs/source/algorithms/CreatePSDBleedMask-v1.rst @@ -72,7 +72,7 @@ Usage ws.setY(50,noisyY) (wsOut, numFailures) = CreatePSDBleedMask(ws,MaxTubeFramerate=10, NIgnoredCentralPixels=2) - print "%i spectra have been masked in wsOut" % numFailures + print("{} spectra have been masked in wsOut".format(numFailures)) Output: diff --git a/docs/source/algorithms/CreatePeaksWorkspace-v1.rst b/docs/source/algorithms/CreatePeaksWorkspace-v1.rst index e9e54e0a58e0b28d0af60bff428e941789ba27b1..7538196ffafb22be8a937f64597a68167ef47d94 100644 --- a/docs/source/algorithms/CreatePeaksWorkspace-v1.rst +++ b/docs/source/algorithms/CreatePeaksWorkspace-v1.rst @@ -25,7 +25,7 @@ Usage .. testcode:: ExEmptyTable ws = CreatePeaksWorkspace() - print "Created a %s with %i rows" % (ws.id(), ws.rowCount()) + print("Created a {} with {} rows".format(ws.id(), ws.rowCount())) Output: @@ -39,7 +39,7 @@ Output: sampleWs = CreateSampleWorkspace() ws = CreatePeaksWorkspace(InstrumentWorkspace=sampleWs,NumberOfPeaks=3) - print "Created a %s with %i rows" % (ws.id(), ws.rowCount()) + print("Created a {} with {} rows".format(ws.id(), ws.rowCount())) Output: diff --git a/docs/source/algorithms/CreateSampleWorkspace-v1.rst b/docs/source/algorithms/CreateSampleWorkspace-v1.rst index 633e93a8579651bd2529f8fb2b6a46ac43a1ed6f..3fd42ca473a1bf7148f76410acbdf24853e43cb0 100644 --- a/docs/source/algorithms/CreateSampleWorkspace-v1.rst +++ b/docs/source/algorithms/CreateSampleWorkspace-v1.rst @@ -73,10 +73,9 @@ Usage # create histogram workspace ws = CreateSampleWorkspace() - print "Number of spectra: " + str(ws.getNumberHistograms()) - print "Number of bins: " + str(ws.blocksize()) - print "Each spectra has a level backgound of " + str(ws.readY(0)[0]) + \ - " counts and a peak in the centre of " + str(ws.readY(0)[50]) + " counts." + print("Number of spectra: {}".format(ws.getNumberHistograms())) + print("Number of bins: {}".format(ws.blocksize())) + print("Each spectra has a level backgound of {} counts and a peak in the centre of {} counts.".format(ws.readY(0)[0], ws.readY(0)[50])) Output: @@ -93,13 +92,12 @@ Output: # create event workspace ws = CreateSampleWorkspace("Event") - print "Number of spectra: " + str(ws.getNumberHistograms()) - print "Number of bins: " + str(ws.blocksize()) - print "Number of events: " + str(ws.getNumberEvents()) - print "Event Workspaces come with bins set by default to a bin width of " + str(ws.readX(0)[1]-ws.readX(0)[0]) + print("Number of spectra: {}".format(ws.getNumberHistograms())) + print("Number of bins: {}".format(ws.blocksize())) + print("Number of events: {}".format(ws.getNumberEvents())) + print("Event Workspaces come with bins set by default to a bin width of {}".format(ws.readX(0)[1]-ws.readX(0)[0])) #The data itensity of an EventWorkspce is scaled by the number of events used, so the values differ from the histogram above. - print "Each spectra has a level backgound of " + str(ws.readY(0)[0]) + \ - " counts and a peak in the centre of " + str(ws.readY(0)[50]) + " counts." + print("Each spectra has a level backgound of {} counts and a peak in the centre of {} counts.".format(ws.readY(0)[0], ws.readY(0)[50])) Output: @@ -117,16 +115,16 @@ Output: # create a workspace with Flat Background wsFlat = CreateSampleWorkspace("Histogram","Flat background") - print "Flat background has a constant value of " + str(wsFlat.readY(0)[0]) + " counts." + print("Flat background has a constant value of {} counts.".format(wsFlat.readY(0)[0])) # create a workspace with multiple peaks wsMulti = CreateSampleWorkspace("Histogram","Multiple Peaks") - print "Multiple Peaks has a level backgound of " + str(wsMulti.readY(0)[0]), - print "counts and two gaussian peaks, the largest of which is " + str(wsMulti.readY(0)[60]) + " counts." + print("Multiple Peaks has a level backgound of {} counts and two gaussian peaks, the largest of which is {} counts.". + format(wsMulti.readY(0)[0], wsMulti.readY(0)[60])) # create a workspace with Exponential Decay wsExp = CreateSampleWorkspace("Histogram","Exp Decay") - print ("Exp Decay starts high and drops rapidly to %.2f counts at 8,000 us (with the default binning)." % wsExp.readY(0)[40]) + print("Exp Decay starts high and drops rapidly to {:.2f} counts at 8,000 us (with the default binning).".format(wsExp.readY(0)[40])) Output: @@ -145,9 +143,9 @@ Output: ws = CreateSampleWorkspace("Histogram","User Defined",myFunc) - print "My function defined a background of "+ str(ws.readY(0)[0]) + " counts." - print "With a peak reaching "+ str(ws.readY(0)[5]) + " counts at 1,000 us," - print "and another reaching "+ str(ws.readY(0)[50]) + " counts at 10,000 us." + print("My function defined a background of {} counts.".format(ws.readY(0)[0])) + print("With a peak reaching {} counts at 1,000 us,".format(ws.readY(0)[5])) + print("and another reaching {} counts at 10,000 us.".format(ws.readY(0)[50])) Output: @@ -167,8 +165,8 @@ Output: XMax=0.5, BinWidth=0.01) - print "Number of spectra: " + str(ws.getNumberHistograms()) - print "Number of bins: " + str(ws.blocksize()) + print("Number of spectra: {}".format(ws.getNumberHistograms())) + print("Number of bins: {}".format(ws.blocksize())) Output: @@ -184,8 +182,8 @@ Output: #Random adds a little random noise to the data function ws=CreateSampleWorkspace(WorkspaceType="Event",Function="One Peak",NumBanks=4,NumMonitors=3,BankPixelWidth=5,NumEvents=500,Random=True,XUnit="tof",XMin=0, XMax=8000, BinWidth=100) - print "Number of spectra: " + str(ws.getNumberHistograms()) - print "Number of bins: " + str(ws.blocksize()) + print("Number of spectra: {}".format(ws.getNumberHistograms())) + print("Number of bins: {}".format(ws.blocksize())) Output: diff --git a/docs/source/algorithms/CreateSingleValuedWorkspace-v1.rst b/docs/source/algorithms/CreateSingleValuedWorkspace-v1.rst index 4aeed835db5affd02b4961f3a21819ea66a0418b..cdab8c58d7191b9ea4c70eeccc8b691d941ce7fc 100644 --- a/docs/source/algorithms/CreateSingleValuedWorkspace-v1.rst +++ b/docs/source/algorithms/CreateSingleValuedWorkspace-v1.rst @@ -27,13 +27,13 @@ Usage five = CreateSingleValuedWorkspace(5) - print "Number of histograms:",five.getNumberHistograms() - print "Length of y array:",len(five.readY(0)) - print "Length of e array:",len(five.readE(0)) - print "Length of x array:",len(five.readX(0)) + print("Number of histograms: {}".format(five.getNumberHistograms())) + print("Length of y array: {}".format(len(five.readY(0)))) + print("Length of e array: {}".format(len(five.readE(0)))) + print("Length of x array: {}".format(len(five.readX(0)))) - print "y value:",five.readY(0) - print "e value:",five.readE(0) + print("y value: {}".format(five.readY(0))) + print("e value: {}".format(five.readE(0))) Output: @@ -52,13 +52,13 @@ Output: five = CreateSingleValuedWorkspace(5, 0.1) - print "Number of histograms:",five.getNumberHistograms() - print "Length of y array:",len(five.readY(0)) - print "Length of e array:",len(five.readE(0)) - print "Length of x array:",len(five.readX(0)) + print("Number of histograms: {}".format(five.getNumberHistograms())) + print("Length of y array: {}".format(len(five.readY(0)))) + print("Length of e array: {}".format(len(five.readE(0)))) + print("Length of x array: {}".format(len(five.readX(0)))) - print "y value:",five.readY(0) - print "e value:",five.readE(0) + print("y value: {}".format(five.readY(0))) + print("e value: {}".format(five.readE(0))) Output: diff --git a/docs/source/algorithms/CreateTransmissionWorkspace-v1.rst b/docs/source/algorithms/CreateTransmissionWorkspace-v1.rst index 912da132323649e6518303ee8635aa5688eab345..d4a051e996461cfab9a62d525fa024b75d47d0b1 100644 --- a/docs/source/algorithms/CreateTransmissionWorkspace-v1.rst +++ b/docs/source/algorithms/CreateTransmissionWorkspace-v1.rst @@ -53,9 +53,9 @@ Usage MonitorIntegrationWavelengthMax = 10, Version=1) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: @@ -89,9 +89,9 @@ Output: MonitorIntegrationWavelengthMax = 10, Version=1) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: diff --git a/docs/source/algorithms/CreateTransmissionWorkspace-v2.rst b/docs/source/algorithms/CreateTransmissionWorkspace-v2.rst index e9c958a7038e18da4874721d82fbb631ec62ba2e..395469e382fa7b6396de8e487b21ebaffe39ef15 100644 --- a/docs/source/algorithms/CreateTransmissionWorkspace-v2.rst +++ b/docs/source/algorithms/CreateTransmissionWorkspace-v2.rst @@ -71,9 +71,9 @@ Usage MonitorIntegrationWavelengthMin = 4, MonitorIntegrationWavelengthMax = 10) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: @@ -105,9 +105,9 @@ Output: MonitorIntegrationWavelengthMin = 4, MonitorIntegrationWavelengthMax = 10) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: diff --git a/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v1.rst b/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v1.rst index e966ee66cfac272b9956c3f9e9cea593b6dfa874..57ac9a3c13c05db89ff50dc2fa306a8e4fe84744 100644 --- a/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v1.rst +++ b/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v1.rst @@ -33,9 +33,9 @@ Usage # Reduction overriding the default values for MonitorBackgroundWavelengthMin and MonitorBackgroundWavelengthMax which would otherwise be retirieved from the workspace transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans, Version=1) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: @@ -57,9 +57,9 @@ Output: # Reduction overriding the default values for MonitorBackgroundWavelengthMin and MonitorBackgroundWavelengthMax which would otherwise be retirieved from the workspace transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans, MonitorBackgroundWavelengthMin=0.0, MonitorBackgroundWavelengthMax=1.0, Version=1) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: @@ -81,9 +81,9 @@ Output: # Reduction overriding the default values for MonitorBackgroundWavelengthMin and MonitorBackgroundWavelengthMax which would otherwise be retirieved from the workspace transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, SecondTransmissionRun=trans2, Params=[1.5,0.02,17], StartOverlap=10.0, EndOverlap=12.0, Version=1) - print "The first four transWS Y values are:" + print("The first four transWS Y values are:") for i in range (4): - print "%.4f" % transWS.readY(0)[i] + print("{:.4f}".format(transWS.readY(0)[i])) Output: diff --git a/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v2.rst b/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v2.rst index e21cb9b79c186a9ad126e864aec2c94d2a6f338a..b599275fa98342e6a31ab4d8369a3640976d947e 100644 --- a/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v2.rst +++ b/docs/source/algorithms/CreateTransmissionWorkspaceAuto-v2.rst @@ -49,10 +49,10 @@ Usage trans = Load(Filename='INTER00013463.nxs') transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans) - print "%.4f" % (transWS.readY(0)[26]) - print "%.4f" % (transWS.readY(0)[27]) - print "%.4f" % (transWS.readY(0)[28]) - print "%.4f" % (transWS.readY(0)[29]) + print("{:.4f}".format(transWS.readY(0)[26])) + print("{:.4f}".format(transWS.readY(0)[27])) + print("{:.4f}".format(transWS.readY(0)[28])) + print("{:.4f}".format(transWS.readY(0)[29])) Output: @@ -72,10 +72,10 @@ Output: trans = Load(Filename='INTER00013463.nxs') transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans, MonitorBackgroundWavelengthMin=0.0, MonitorBackgroundWavelengthMax=1.0) - print "%.3f" % (transWS.readY(0)[26]) - print "%.3f" % (transWS.readY(0)[27]) - print "%.3f" % (transWS.readY(0)[28]) - print "%.3f" % (transWS.readY(0)[29]) + print("{:.3f}".format(transWS.readY(0)[26])) + print("{:.3f}".format(transWS.readY(0)[27])) + print("{:.3f}".format(transWS.readY(0)[28])) + print("{:.3f}".format(transWS.readY(0)[29])) Output: @@ -95,10 +95,10 @@ Output: trans2 = Load(Filename='INTER00013464.nxs') transWS = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, SecondTransmissionRun=trans2, Params=[1.5,0.02,17], StartOverlap=10.0, EndOverlap=12.0) - print "%.4f" % (transWS.readY(0)[26]) - print "%.4f" % (transWS.readY(0)[27]) - print "%.4f" % (transWS.readY(0)[28]) - print "%.4f" % (transWS.readY(0)[29]) + print("{:.4f}".format(transWS.readY(0)[26])) + print("{:.4f}".format(transWS.readY(0)[27])) + print("{:.4f}".format(transWS.readY(0)[28])) + print("{:.4f}".format(transWS.readY(0)[29])) Output: diff --git a/docs/source/algorithms/CreateUserDefinedBackground-v1.rst b/docs/source/algorithms/CreateUserDefinedBackground-v1.rst index a197aaa35958c7898fcee3910d3f4fc3d0a7ccd9..3e9ee3da1275e95400169c0d3701699df946bf69 100644 --- a/docs/source/algorithms/CreateUserDefinedBackground-v1.rst +++ b/docs/source/algorithms/CreateUserDefinedBackground-v1.rst @@ -58,7 +58,7 @@ Usage # Check that workspace matches expected peak expected = CreateWorkspace(dataX, peak) result, messages = CompareWorkspaces(peakWS, expected) - print "Workspaces match:", result + print("Workspaces match: {}".format(result)) Output: diff --git a/docs/source/algorithms/CropWorkspace-v1.rst b/docs/source/algorithms/CropWorkspace-v1.rst index 0257d69e956dd04e0dd827eadb24ff957893a34c..7723bed4a499edeb4fcb81e1da4f29f78b73ec75 100644 --- a/docs/source/algorithms/CropWorkspace-v1.rst +++ b/docs/source/algorithms/CropWorkspace-v1.rst @@ -39,8 +39,8 @@ Usage OutputWorkspace = CropWorkspace(InputWorkspace=ws,XMin=10.0,XMax=40.0) # Show workspaces - print "TOF Before CropWorkspace",ws.readX(0) - print "TOF After CropWorkspace",OutputWorkspace.readX(0) + print("TOF Before CropWorkspace {}".format(ws.readX(0))) + print("TOF After CropWorkspace {}".format(OutputWorkspace.readX(0))) Output: diff --git a/docs/source/algorithms/CrossCorrelate-v1.rst b/docs/source/algorithms/CrossCorrelate-v1.rst index c906e32f125cf955f92c6a9f7279a5701a0fa3f8..cfd7452b8dc7aa1830ab09ee8817daa96d7b23eb 100644 --- a/docs/source/algorithms/CrossCorrelate-v1.rst +++ b/docs/source/algorithms/CrossCorrelate-v1.rst @@ -35,8 +35,8 @@ Usage OutputWorkspace = CrossCorrelate(InputWorkspace='ws', WorkspaceIndexMax=1, XMin=2, XMax=4) # Show workspaces - print "AutoCorrelation",OutputWorkspace.readY(0) - print "CrossCorrelation",OutputWorkspace.readY(1) + print("AutoCorrelation {}".format(OutputWorkspace.readY(0))) + print("CrossCorrelation {}".format(OutputWorkspace.readY(1))) .. testoutput:: ExCrossCorrelate diff --git a/docs/source/algorithms/CrystalFieldEnergies-v1.rst b/docs/source/algorithms/CrystalFieldEnergies-v1.rst index d72c6ca1fc3baf713bdc040a6348f6b851c5d442..cf102a0f030c99b473faf6398231c0a3658f7337 100644 --- a/docs/source/algorithms/CrystalFieldEnergies-v1.rst +++ b/docs/source/algorithms/CrystalFieldEnergies-v1.rst @@ -21,11 +21,11 @@ The algorithm calculates the crystal field energies and wave functions. The exam en, wf, ham = energies(1, B20=0.37737, B22=3.9770, B40=-0.031787, B42=-0.11611, B44=-0.12544) # a list of crystal field energies - print 'energies:\n', en + print('energies:\n{}'.format(en)) # a complex-valued matrix with wave functions - print 'wave functions:\n', wf + print('wave functions:\n{}'.format(wf)) # a complex-valued matrix with the Hamiltonian - print 'Hamiltonian:\n', ham + print('Hamiltonian:\n{}'.format(ham)) .. testoutput:: diff --git a/docs/source/algorithms/CuboidGaugeVolumeAbsorption-v1.rst b/docs/source/algorithms/CuboidGaugeVolumeAbsorption-v1.rst index a5d91184e46a4493f8d207e3dc622d8dba08966d..8b5b26683731a737ad4f26c1d4a02ada33cd63f2 100644 --- a/docs/source/algorithms/CuboidGaugeVolumeAbsorption-v1.rst +++ b/docs/source/algorithms/CuboidGaugeVolumeAbsorption-v1.rst @@ -65,7 +65,7 @@ Usage wsOut = CuboidGaugeVolumeAbsorption(ws, NumberOfWavelengthPoints=5, ElementSize=3, SampleHeight=1,SampleWidth=2,SampleThickness=3) - print "The created workspace has one entry for each spectra: %i" % wsOut.getNumberHistograms() + print("The created workspace has one entry for each spectra: {}".format(wsOut.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/CutMD-v1.rst b/docs/source/algorithms/CutMD-v1.rst index 6da38bdbf8aedb594ddc2a8c487bd41550b7eefa..7c77511cbc1199e97c023231229cbcc71867c1f1 100644 --- a/docs/source/algorithms/CutMD-v1.rst +++ b/docs/source/algorithms/CutMD-v1.rst @@ -157,11 +157,11 @@ _`Usage` #Another way we can call CutMD: #[out1, out2, out3] = CutMD([to_cut, "some_other_file.nxs", "some_workspace_name"], ...) - print 'number of dimensions', out_md.getNumDims() - print 'number of dimensions not integrated', len(out_md.getNonIntegratedDimensions()) + print('number of dimensions {}'.format(out_md.getNumDims())) + print('number of dimensions not integrated {}'.format(len(out_md.getNonIntegratedDimensions()))) dim_dE = out_md.getDimension(3) - print 'min dE', dim_dE.getMaximum() - print 'max dE', dim_dE.getMinimum() + print('min dE {}'.format(dim_dE.getMaximum())) + print('max dE {}'.format(dim_dE.getMinimum())) Output: @@ -184,15 +184,15 @@ Output: # Cut the MDHistoWorkspace to give a single bin containing half the data cut= CutMD(InputWorkspace=histo_ws, PBins=[[-10, 10], [-5, 5]]) - print 'Total signal in input = %0.2f' % sum(signal) - print 'Half the volume should give half the signal = %0.2f' % cut.getSignalArray() + print('Total signal in input = {}'.format(sum(signal))) + print('Half the volume should give half the signal = {}'.format(cut.getSignalArray()[0][0])) Output: .. testoutput:: ExampleMDHisto - Total signal in input = 100.00 - Half the volume should give half the signal = 50.00 + Total signal in input = 100.0 + Half the volume should give half the signal = 50.0 .. categories:: diff --git a/docs/source/algorithms/CylinderPaalmanPingsCorrection-v2.rst b/docs/source/algorithms/CylinderPaalmanPingsCorrection-v2.rst index fa3ff1f0b80ded918b8f8d45d20d6037213e009e..fdc45aeb0b045aa0fcb88dc27766ebdb26a1a7c5 100644 --- a/docs/source/algorithms/CylinderPaalmanPingsCorrection-v2.rst +++ b/docs/source/algorithms/CylinderPaalmanPingsCorrection-v2.rst @@ -74,7 +74,7 @@ Usage Emode='Indirect', Efixed=1.845) - print 'Correction workspaces: %s' % (', '.join(corr.getNames())) + print('Correction workspaces: {}'.format((', '.join(corr.getNames())))) Output: diff --git a/docs/source/algorithms/DNSComputeDetEffCorrCoefs-v1.rst b/docs/source/algorithms/DNSComputeDetEffCorrCoefs-v1.rst index 3b7b0c7c738147187b9a11a7b03992325debed7f..531751a4edb624bd15171d245527f48db72f4ad0 100644 --- a/docs/source/algorithms/DNSComputeDetEffCorrCoefs-v1.rst +++ b/docs/source/algorithms/DNSComputeDetEffCorrCoefs-v1.rst @@ -81,23 +81,25 @@ Usage # Calculate correction coefficients coefs = DNSComputeDetEffCorrCoefs([vana_sf, vana_nsf], [bkgr_sf, bkgr_nsf]) - print "First 3 correction coefficients: " + print("First 3 correction coefficients: ") for i in range(3): - print round(coefs.readY(i),2) + print(round(coefs.readY(i),2)) - print "Is first detector masked?", coefs.getInstrument().getDetector(1).isMasked() + print("Is first detector masked? {}".format(coefs.getInstrument().getDetector(1).isMasked())) # load sample data rawdata = LoadDNSLegacy('oi196012pbi.d_dat', Normalization='duration', CoilCurrentsTable=curtable) # apply correction corrected_data = rawdata/coefs - print "First 3 corrected data points" + print("First 3 corrected data points") for i in range(3): - print round(corrected_data.readY(i),2) + print(round(corrected_data.readY(i),2)) Output: +.. code-block:: python + First 3 correction coefficients: 0.0 diff --git a/docs/source/algorithms/DNSFlippingRatioCorr-v1.rst b/docs/source/algorithms/DNSFlippingRatioCorr-v1.rst index 6e02d9065c02b8d0619b1870e9b2da3ca720c257..438f785749e0f19ba84182699065993067f9a08f 100644 --- a/docs/source/algorithms/DNSFlippingRatioCorr-v1.rst +++ b/docs/source/algorithms/DNSFlippingRatioCorr-v1.rst @@ -110,7 +110,7 @@ Usage vana_ratio = sf_corrected/nsf_corrected # ratio must be around 2, print first 5 points of the data array - print np.around(vana_ratio.extractY()[:5]) + print(np.around(vana_ratio.extractY()[:5])) Output: diff --git a/docs/source/algorithms/DNSMergeRuns-v1.rst b/docs/source/algorithms/DNSMergeRuns-v1.rst index 1749f53b570ab7f6f7438b2044b35cf1f420c417..5221c1f2fea61f1e424f3a5868bec6ea6c1cf5b5 100644 --- a/docs/source/algorithms/DNSMergeRuns-v1.rst +++ b/docs/source/algorithms/DNSMergeRuns-v1.rst @@ -81,10 +81,10 @@ Usage for f in datafiles: try: wname = splitext(f)[0] - #print "Processing ", wname # uncomment if needed + #print("Processing {}".format(wname)) # uncomment if needed LoadDNSLegacy(Filename=join(mypath, f), OutputWorkspace=wname, CoilCurrentsTable=coilcurrents, Normalization='duration') except RuntimeError as err: - print err + print(err) else: wslist.append(wname) @@ -95,19 +95,19 @@ Usage # print selected values from merged workspaces two_theta = merged.extractX()[0] - print "First 5 2Theta values: ", two_theta[:5] + print("First 5 2Theta values: {}".format(two_theta[:5])) q = mergedQ.extractX()[0] - print "First 5 |Q| values: ", np.round(q[:5], 3) + print("First 5 |Q| values: {}".format(np.round(q[:5], 3))) d = mergedD.extractX()[0] - print "First 5 d values: ", np.round(d[:5], 3) + print("First 5 d values: {}".format(np.round(d[:5], 3))) Output: - First 5 2Theta values: [ 7.5 8. 8.5 9. 9.5] + First 5 2Theta values: [ 7.5 8. 8.5 9. 9.5] - First 5 Q values: [ 0.249 0.266 0.282 0.299 0.315] + First 5 Q values: [ 0.249 0.266 0.282 0.299 0.315] - First 5 d values: [ 1.844 1.848 1.852 1.856 1.86 ] + First 5 d values: [ 1.844 1.848 1.852 1.856 1.86 ] .. categories:: diff --git a/docs/source/algorithms/ElasticWindow-v1.rst b/docs/source/algorithms/ElasticWindow-v1.rst index 456c66d677c6caf292e9ec8ca7835e28da36e2d5..636cfe3af37ff318cd386db8c360e96bec01723e 100644 --- a/docs/source/algorithms/ElasticWindow-v1.rst +++ b/docs/source/algorithms/ElasticWindow-v1.rst @@ -47,8 +47,8 @@ Usage # Run the algorithm q, q2 = ElasticWindow(ws, -0.1, 0.1) - print q.getAxis(0).getUnit().caption() - print q2.getAxis(0).getUnit().caption() + print(q.getAxis(0).getUnit().caption()) + print(q2.getAxis(0).getUnit().caption()) .. testoutput:: exElasticWindowSimple diff --git a/docs/source/algorithms/ElasticWindowMultiple-v1.rst b/docs/source/algorithms/ElasticWindowMultiple-v1.rst index 1f31d76899ae0925d44204c256dc055bb10eff7c..a953d30b052b9e5ad24f6c70de145f781e1cf8a4 100644 --- a/docs/source/algorithms/ElasticWindowMultiple-v1.rst +++ b/docs/source/algorithms/ElasticWindowMultiple-v1.rst @@ -72,9 +72,9 @@ Usage # Run the algorithm q, q2, elf = ElasticWindowMultiple(input, -0.1, 0.1) - print 'ELF X axis: %s' % elf.getAxis(0).getUnit().caption() - print 'ELF spectra count: %d' % elf.getNumberHistograms() - print 'ELF bin count: %d' % elf.blocksize() + print('ELF X axis: %s' % elf.getAxis(0).getUnit().caption()) + print('ELF spectra count: %d' % elf.getNumberHistograms()) + print('ELF bin count: %d' % elf.blocksize()) # Reset the facility to the original setting config['default.facility'] = facility diff --git a/docs/source/algorithms/EnggCalibrate-v1.rst b/docs/source/algorithms/EnggCalibrate-v1.rst index f44353c7dfc95ff4ee11f12fd77ba797f9ba7ab4..0375eb44e530f5f8bd9b0391cdb4a4ca40bbb7aa 100644 --- a/docs/source/algorithms/EnggCalibrate-v1.rst +++ b/docs/source/algorithms/EnggCalibrate-v1.rst @@ -88,23 +88,23 @@ Usage difc=[difc1, difc2], tzero=[tzero1, tzero2]) import math - print "DIFA1: {0}".format(difa1) + print("DIFA1: {0}".format(difa1)) delta = 2 approx_difc1 = 18267 difc1_ok = abs(difc1 - approx_difc1) <= delta - print "DIFC1 is approximately (+/- {0}) {1}: {2}".format(delta, approx_difc1, difc1_ok) + print("DIFC1 is approximately (+/- {0}) {1}: {2}".format(delta, approx_difc1, difc1_ok)) approx_tzero1 = 277 tzero1_ok = abs(tzero1 - approx_tzero1) <= delta - print "TZERO1 is approximately (+/- {0}) {1}: {2}".format(delta, approx_tzero1, tzero1_ok) + print("TZERO1 is approximately (+/- {0}) {1}: {2}".format(delta, approx_tzero1, tzero1_ok)) tbl = mtd[out_tbl_name] tbl_values_ok = (abs(tbl.cell(0,1) - approx_difc1) <= delta) and (abs(tbl.cell(0,2) - approx_tzero1) <= delta) - print "The output table has {0} row(s) and its values are as expected: {1}".format(tbl.rowCount(), - tbl_values_ok) + print("The output table has {0} row(s) and its values are as expected: {1}".format(tbl.rowCount(), + tbl_values_ok)) import os - print "Output GSAS iparam file was written? {0}".format(os.path.exists(GSAS_iparm_fname)) - print "Number of lines of the GSAS iparam file: {0}".format(sum(1 for line in open(GSAS_iparm_fname))) + print("Output GSAS iparam file was written? {0}".format(os.path.exists(GSAS_iparm_fname))) + print("Number of lines of the GSAS iparam file: {0}".format(sum(1 for line in open(GSAS_iparm_fname)))) .. testcleanup:: ExampleCalib diff --git a/docs/source/algorithms/EnggCalibrateFull-v1.rst b/docs/source/algorithms/EnggCalibrateFull-v1.rst index ad21cfd3ddb7ac8a7f9116aee6036faf39f1bc97..5cac4656139d49d652d774abe2bda0d914e327c9 100644 --- a/docs/source/algorithms/EnggCalibrateFull-v1.rst +++ b/docs/source/algorithms/EnggCalibrateFull-v1.rst @@ -96,11 +96,11 @@ Usage det_id = pos_table.column(0)[0] cal_pos = pos_table.column(2)[0] - print "Det ID:", det_id - print "Calibrated position: (%.3f,%.3f,%.3f)" % (cal_pos.getX(), cal_pos.getY(), cal_pos.getZ()) + print("Det ID: {}".format(det_id)) + print("Calibrated position: (%.3f,%.3f,%.3f)" % (cal_pos.getX(), cal_pos.getY(), cal_pos.getZ())) ws = mtd[ws_name] posInWSInst = ws.getInstrument().getDetector(det_id).getPos() - print "Is the detector position calibrated now in the original workspace instrument?", (cal_pos == posInWSInst) + print("Is the detector position calibrated now in the original workspace instrument? {}".format(cal_pos == posInWSInst)) .. testcleanup:: ExCalFull @@ -140,13 +140,13 @@ Output: det_id = pos_table.column(0)[0] pos = pos_table.column(2)[0] - print "Det ID:", det_id - print "Calibrated position: ({0:.3f},{1:.3f},{2:.3f})".format(pos.getX(),pos.getY(),pos.getZ()) - print "Got details on the peaks fitted for {0:d} detector(s)".format(peaks_info.rowCount()) - print "Was the file created?", os.path.exists(pos_filename) + print("Det ID: {}".format(det_id)) + print("Calibrated position: ({0:.3f},{1:.3f},{2:.3f})".format(pos.getX(),pos.getY(),pos.getZ())) + print("Got details on the peaks fitted for {0:d} detector(s)".format(peaks_info.rowCount())) + print("Was the file created? {}".format(os.path.exists(pos_filename))) with open(pos_filename) as csvf: reader = csv.reader(csvf, dialect='excel') - reader.next() + next(reader) calibOK = True for i,row in enumerate(reader): cal_pos = pos_table.column(2)[i] @@ -154,7 +154,7 @@ Output: (abs(float(row[5]) - cal_pos.getY()) < 1e-6) and\ (abs(float(row[6]) - cal_pos.getZ()) < 1e-6) if not calibOK: break - print "Does the calibration file have the expected values?", calibOK + print("Does the calibration file have the expected values? {}".format(calibOK)) .. testcleanup:: ExCalFullWithOutputFile diff --git a/docs/source/algorithms/EnggFitDIFCFromPeaks-v1.rst b/docs/source/algorithms/EnggFitDIFCFromPeaks-v1.rst index 7a414997151cfe546ccb3af7fffadf143353b7d0..7a3f1c2a8f31cf96d68054c8d44202f3a0f64c46 100644 --- a/docs/source/algorithms/EnggFitDIFCFromPeaks-v1.rst +++ b/docs/source/algorithms/EnggFitDIFCFromPeaks-v1.rst @@ -76,17 +76,17 @@ Usage difa, difc, tzero = EnggFitDIFCFromPeaks(FittedPeaks=peaks_tbl, OutParametersTable=out_tbl_name) # Print the results - print "DIFA: %.1f" % difa - print "DIFC: %.0f" % round(difc,-1) - print "TZERO: %.0f" %round(tzero,-1) + print("DIFA: %.1f" % difa) + print("DIFC: %.0f" % round(difc,-1)) + print("TZERO: %.0f" %round(tzero,-1)) tbl = mtd[out_tbl_name] - print "The output table has %d row(s)" % tbl.rowCount() - print "Parameters from the table, DIFA: %.1f, DIFC: %.0f, TZERO: %.0f" % (tbl.cell(0,0), round(tbl.cell(0,1),-1), round(tbl.cell(0,2),-1)) - print "Number of peaks fitted: {0}".format(peaks_tbl.rowCount()) - print "First peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[0]) - print "First fitted peak center (ToF): {0:.1f}".format(peaks_tbl.column('X0')[0]) - print "Second peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[1]) - print "Second fitted peak center (ToF): {0:.0f}".format(round(peaks_tbl.column('X0')[1],-1)) + print("The output table has %d row(s)" % tbl.rowCount()) + print("Parameters from the table, DIFA: %.1f, DIFC: %.0f, TZERO: %.0f" % (tbl.cell(0,0), round(tbl.cell(0,1),-1), round(tbl.cell(0,2),-1))) + print("Number of peaks fitted: {0}".format(peaks_tbl.rowCount())) + print("First peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[0])) + print("First fitted peak center (ToF): {0:.1f}".format(peaks_tbl.column('X0')[0])) + print("Second peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[1])) + print("Second fitted peak center (ToF): {0:.0f}".format(round(peaks_tbl.column('X0')[1],-1))) Output: diff --git a/docs/source/algorithms/EnggFitPeaks-v1.rst b/docs/source/algorithms/EnggFitPeaks-v1.rst index 524a02295fe3428800af69eeb014c8c3e4577231..54680ed1ea0d1397ea97a85a56294a57310c89bc 100644 --- a/docs/source/algorithms/EnggFitPeaks-v1.rst +++ b/docs/source/algorithms/EnggFitPeaks-v1.rst @@ -80,11 +80,11 @@ Usage # Print the results - print "Number of peaks fitted: {0}".format(peaks_tbl.rowCount()) - print "First peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[0]) - print "First fitted peak center (ToF): {0:.1f}".format(peaks_tbl.column('X0')[0]) - print "Second peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[1]) - print "Second fitted peak center (ToF): {0:.0f}".format(round(peaks_tbl.column('X0')[1],-1)) + print("Number of peaks fitted: {0}".format(peaks_tbl.rowCount())) + print("First peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[0])) + print("First fitted peak center (ToF): {0:.1f}".format(peaks_tbl.column('X0')[0])) + print("Second peak expected (dSpacing): {0}".format(peaks_tbl.column('dSpacing')[1])) + print("Second fitted peak center (ToF): {0:.0f}".format(round(peaks_tbl.column('X0')[1],-1))) Output: diff --git a/docs/source/algorithms/EnggFocus-v1.rst b/docs/source/algorithms/EnggFocus-v1.rst index d76860e58e4531cadf5e6a397ba2e0174015a615..12f2f1dd1206e2e076c91ed875e15d60ac8a0483 100644 --- a/docs/source/algorithms/EnggFocus-v1.rst +++ b/docs/source/algorithms/EnggFocus-v1.rst @@ -65,12 +65,12 @@ Usage Bank='1') # Should have one spectrum only - print "No. of spectra:", focussed_ws.getNumberHistograms() + print("No. of spectra: {}".format(focussed_ws.getNumberHistograms())) # Print a few arbitrary bins where higher intensities are expected fmt = "For TOF of {0:.3f} normalized intensity is {1:.3f}" for bin in [3169, 6037, 7124]: - print fmt.format(focussed_ws.readX(0)[bin], focussed_ws.readY(0)[bin]) + print(fmt.format(focussed_ws.readX(0)[bin], focussed_ws.readY(0)[bin])) .. testcleanup:: ExSimpleFocussing diff --git a/docs/source/algorithms/EnggVanadiumCorrections-v1.rst b/docs/source/algorithms/EnggVanadiumCorrections-v1.rst index 9fba4a28399719564d8e4525e8632c5b8e954d95..f980ed5fb93fc602d76cec4cd7ca88e8b92555e8 100644 --- a/docs/source/algorithms/EnggVanadiumCorrections-v1.rst +++ b/docs/source/algorithms/EnggVanadiumCorrections-v1.rst @@ -111,7 +111,7 @@ Usage CurvesWorkspace = curves_ws) # Should have one spectrum only - print "No. of spectra:", sample_ws.getNumberHistograms() + print("No. of spectra: {}".format(sample_ws.getNumberHistograms())) # Print a few arbitrary integrated spectra ws_idx = 400 @@ -120,7 +120,7 @@ Usage EndWorkspaceIndex=ws_idx+idx_count) fmt = "For workspace index {0:d} the spectrum integration is {1:.3f}" for i in range(idx_count): - print fmt.format(ws_idx+i, integ_ws.readY(i)[0]) + print(fmt.format(ws_idx+i, integ_ws.readY(i)[0])) .. testcleanup:: ExVanadiumCorr diff --git a/docs/source/algorithms/EstimateMuonAsymmetryFromCounts-v1.rst b/docs/source/algorithms/EstimateMuonAsymmetryFromCounts-v1.rst index 9c2f64f50ab51b8e7f5a748efbc0c0e7f5bb96d3..7480c94af69078cd8d7908d3ef92249fa22d393e 100644 --- a/docs/source/algorithms/EstimateMuonAsymmetryFromCounts-v1.rst +++ b/docs/source/algorithms/EstimateMuonAsymmetryFromCounts-v1.rst @@ -41,8 +41,8 @@ Usage run = input.getRun() run.addProperty("goodfrm","10","None",True) output,norm=EstimateMuonAsymmetryFromCounts(InputWorkspace=input,spectra=0,StartX=1,EndX=5) - print "Asymmetry: ",['{0:.2f}'.format(value) for value in output.readY(0)] - print "Normalization constant: {0:.2f}".format(norm[0]) + print("Asymmetry: {}".format(['{0:.2f}'.format(value) for value in output.readY(0)])) + print("Normalization constant: {0:.2f}".format(norm[0])) Output: @@ -63,8 +63,8 @@ Output: run = input.getRun() run.addProperty("goodfrm","10","None",True) output,norm=EstimateMuonAsymmetryFromCounts(InputWorkspace=input,spectra=0,StartX=1,EndX=5,NormalizationIn=20.0) - print "Asymmetry: ",['{0:.2f}'.format(value) for value in output.readY(0)] - print "Normalization constant: {0:.2f}".format(norm[0]) + print("Asymmetry: {}".format(['{0:.2f}'.format(value) for value in output.readY(0)])) + print("Normalization constant: {0:.2f}".format(norm[0])) Output: diff --git a/docs/source/algorithms/EstimateResolutionDiffraction-v1.rst b/docs/source/algorithms/EstimateResolutionDiffraction-v1.rst index 0e0e63f0b766cc81055c4c93910660fc710336ec..8f568c5f514c346aabba51f948618a892f246d3c 100644 --- a/docs/source/algorithms/EstimateResolutionDiffraction-v1.rst +++ b/docs/source/algorithms/EstimateResolutionDiffraction-v1.rst @@ -68,10 +68,10 @@ Usage EstimateResolutionDiffraction(InputWorkspace="PG3_2538", DeltaTOF=40.0, OutputWorkspace="PG3_Resolution") resws = mtd["PG3_Resolution"] - print "Size of workspace 'PG3_Resolution' = ", resws.getNumberHistograms() - print "Estimated resolution of detector of spectrum 0 = ", resws.readY(0)[0] - print "Estimated resolution of detector of spectrum 100 = ", resws.readY(100)[0] - print "Estimated resolution of detector of spectrum 999 = ", resws.readY(999)[0] + print("Size of workspace 'PG3_Resolution' = {}".format(resws.getNumberHistograms())) + print("Estimated resolution of detector of spectrum 0 = {:.14f}".format(resws.readY(0)[0])) + print("Estimated resolution of detector of spectrum 100 = {:.14f}".format(resws.readY(100)[0])) + print("Estimated resolution of detector of spectrum 999 = {:.14f}".format(resws.readY(999)[0])) .. testcleanup:: ExHistSimple diff --git a/docs/source/algorithms/EvaluateMDFunction-v1.rst b/docs/source/algorithms/EvaluateMDFunction-v1.rst index 56b5bd917617d5a36fce6b15b12acd31af4db6a1..91f8acc66df3cb1d45a660e0486936a87771518f 100644 --- a/docs/source/algorithms/EvaluateMDFunction-v1.rst +++ b/docs/source/algorithms/EvaluateMDFunction-v1.rst @@ -37,10 +37,10 @@ Usage out = EvaluateMDFunction(ws,function) # Check the result workspace - print out.getNumDims() - print out.getXDimension().name - print out.getYDimension().name - print out.getZDimension().name + print(out.getNumDims()) + print(out.getXDimension().name) + print(out.getYDimension().name) + print(out.getZDimension().name) Output diff --git a/docs/source/algorithms/ExaminePowderDiffProfile-v1.rst b/docs/source/algorithms/ExaminePowderDiffProfile-v1.rst index 190f1c0d662e64bc21912609233d7c669835f125..431f6369d1d361c47c7acbe5a7851bf742aa1b4b 100644 --- a/docs/source/algorithms/ExaminePowderDiffProfile-v1.rst +++ b/docs/source/algorithms/ExaminePowderDiffProfile-v1.rst @@ -48,7 +48,7 @@ Usage # Output result ws = mtd['PG3_15035B3_Cal'] - print 'Output workspace has %d spectra' % (ws.getNumberHistograms()) + print('Output workspace has %d spectra' % (ws.getNumberHistograms())) .. testcleanup:: ExExaminePG3Profile diff --git a/docs/source/algorithms/ExampleSaveAscii-v1.rst b/docs/source/algorithms/ExampleSaveAscii-v1.rst index 471640b81046ca9d3b590596158ea15ed8fed5eb..6f061321b8261b5104ba7bf3ca29a51143508816 100644 --- a/docs/source/algorithms/ExampleSaveAscii-v1.rst +++ b/docs/source/algorithms/ExampleSaveAscii-v1.rst @@ -40,9 +40,9 @@ Usage # Read and print first 3 lines from file with open(filepath, 'r') as f: - print f.readline()[:-1] - print f.readline()[:-1] - print f.readline()[:-1] + print(f.readline()[:-1]) + print(f.readline()[:-1]) + print(f.readline()[:-1]) # Delete the test file os.remove(filepath) diff --git a/docs/source/algorithms/Exponential-v1.rst b/docs/source/algorithms/Exponential-v1.rst index bd59e56c4b4886912ac0086b693c931ac3fdb53c..a08913dde2c45e787ff609f3842336a866672cf6 100644 --- a/docs/source/algorithms/Exponential-v1.rst +++ b/docs/source/algorithms/Exponential-v1.rst @@ -37,7 +37,7 @@ Usage # Use numpy array calculation to apply an exponential to all elements of array y yexp = np.exp(y) # Use numpy to check that all elements in two arrays are equal - print np.all( yexp == yres ) + print(np.all( yexp == yres )) Output ###### diff --git a/docs/source/algorithms/ExponentialCorrection-v1.rst b/docs/source/algorithms/ExponentialCorrection-v1.rst index dc5d025c76d70be56c82a25d76108bc1fa191cfc..369f24d942c622bb0e75c2faedf55bed283146e8 100644 --- a/docs/source/algorithms/ExponentialCorrection-v1.rst +++ b/docs/source/algorithms/ExponentialCorrection-v1.rst @@ -26,15 +26,15 @@ Usage ws = CreateSampleWorkspace() - print "The first Y value before correction is: " + str(ws.dataY(0)[1]) + print("The first Y value before correction is: {}".format((ws.dataY(0)[1]))) # By default, the Divide operation is used to correct the data. # The result is saved into another workspace, which can also be itself. ws_divide = ExponentialCorrection(InputWorkspace=ws,C0=2.0,C1=1.0,Operation="Divide") ws_multiply = ExponentialCorrection(InputWorkspace=ws,C0=2.0,C1=1.0,Operation="Multiply") - print "The first Y value after divide correction is: " + str(ws_divide.dataY(0)[1]) - print "The first Y value after multiply correction is: " + str(ws_multiply.dataY(0)[1]) + print("The first Y value after divide correction is: {:.11e}".format(ws_divide.dataY(0)[1])) + print("The first Y value after multiply correction is: {:.11e}".format(ws_multiply.dataY(0)[1])) Output: diff --git a/docs/source/algorithms/ExportExperimentLog-v1.rst b/docs/source/algorithms/ExportExperimentLog-v1.rst index 29662f0fb2cbac9053b1cf8fc011291bcb74dd08..25967655bf6a061dfae2a0dd00b2164fdf93478a 100644 --- a/docs/source/algorithms/ExportExperimentLog-v1.rst +++ b/docs/source/algorithms/ExportExperimentLog-v1.rst @@ -114,14 +114,14 @@ Usage FileFormat = "tab", TimeZone = "America/New_York") - print "File is created = ", os.path.exists(savefile) + print("File is created = {}".format(os.path.exists(savefile))) # Get lines of file sfile = open(savefile, 'r') slines = sfile.readlines() sfile.close() - print "Number of lines in File =", len(slines) + print("Number of lines in File = {}".format(len(slines))) .. testcleanup:: ExExportExpLogs diff --git a/docs/source/algorithms/ExportGeometry-v1.rst b/docs/source/algorithms/ExportGeometry-v1.rst index 6678c67a61cbe224696c7001f06c8fb7c62db886..53878c8d80451e9faf099d99d59f4f39441a3d10 100644 --- a/docs/source/algorithms/ExportGeometry-v1.rst +++ b/docs/source/algorithms/ExportGeometry-v1.rst @@ -30,7 +30,7 @@ Usage Filename=filename) import os if os.path.isfile(filename): - print "File created: True" + print("File created: True") .. testcleanup:: ExportGeometry diff --git a/docs/source/algorithms/ExportSampleLogsToCSVFile-v1.rst b/docs/source/algorithms/ExportSampleLogsToCSVFile-v1.rst index 9d125f2cbe87e54576d924525613a98dab75f5a3..51d77cd96ff035ec9e82455dfb20da82cc152221 100644 --- a/docs/source/algorithms/ExportSampleLogsToCSVFile-v1.rst +++ b/docs/source/algorithms/ExportSampleLogsToCSVFile-v1.rst @@ -100,8 +100,8 @@ Usage headerfilename = os.path.join(defaultdir, "testphase4_header.txt") - print "File is created = ", os.path.exists(savefile) - print "Header file is created = ", os.path.exists(headerfilename) + print("File is created = {}".format(os.path.exists(savefile))) + print("Header file is created = {}".format(os.path.exists(headerfilename))) # Get the lines of both files sfile = open(savefile, 'r') @@ -111,8 +111,8 @@ Usage hlines = hfile.readlines() hfile.close() - print "Number of lines in File =", len(slines) - print "Number of lines in Header file =", len(hlines) + print("Number of lines in File = {}".format(len(slines))) + print("Number of lines in Header file = {}".format(len(hlines))) .. testcleanup:: ExExportSampleToTSV diff --git a/docs/source/algorithms/ExportTimeSeriesLog-v1.rst b/docs/source/algorithms/ExportTimeSeriesLog-v1.rst index 6757a08f7aec8664915c8cb509bda856a8c5a445..e1816edca98b4257ef685124c5b22c67f4742636 100644 --- a/docs/source/algorithms/ExportTimeSeriesLog-v1.rst +++ b/docs/source/algorithms/ExportTimeSeriesLog-v1.rst @@ -51,9 +51,9 @@ Usage import mantid.kernel as mk testprop = mk.FloatTimeSeriesProperty("Temp") - import random + from numpy import random random.seed(10) - for i in xrange(60): + for i in range(60): randsec = random.randint(0, 59) randval = random.random()*100. timetemp = mk.DateAndTime("2012-01-01T00:%d:%d"%(i, randsec)) @@ -64,10 +64,10 @@ Usage propws = ExportTimeSeriesLog(InputWorkspace=dataws, LogName="Temp", IsEventWorkspace=False) # Check - print "Length of X = %d, Length of Y = %d." % (len(propws.readX(0)), len(propws.readY(0))) - print "X[0] = %.1f, Y[0] = %.5f" % (propws.readX(0)[0], propws.readY(0)[0]) - print "X[20] = %.1f, Y[20] = %.5f" % (propws.readX(0)[20], propws.readY(0)[20]) - print "X[40] = %.1f, Y[40] = %.5f" % (propws.readX(0)[40], propws.readY(0)[40]) + print("Length of X = %d, Length of Y = %d." % (len(propws.readX(0)), len(propws.readY(0)))) + print("X[0] = {:.1f}, Y[0] = {:.5f}".format(propws.readX(0)[0], propws.readY(0)[0])) + print("X[20] = {:.1f}, Y[20] = {:.5f}".format(propws.readX(0)[20], propws.readY(0)[20])) + print("X[40] = {:.1f}, Y[40] = {:.5f}".format(propws.readX(0)[40], propws.readY(0)[40])) .. testcleanup:: ExExpTempWS2D @@ -79,10 +79,9 @@ Output: .. testoutput:: ExExpTempWS2D Length of X = 60, Length of Y = 60. - X[0] = 26089826.0, Y[0] = 42.88891 - X[20] = 26091001.0, Y[20] = 22.42990 - X[40] = 26092226.0, Y[40] = 39.05869 - + X[0] = 26089801.0, Y[0] = 29.87612 + X[20] = 26091048.0, Y[20] = 61.19433 + X[40] = 26092225.0, Y[40] = 63.79516 **Example - export a float series to a EventWorkspace:** @@ -95,9 +94,9 @@ Output: # Create a new log testprop = mk.FloatTimeSeriesProperty("Temp") - import random + from numpy import random random.seed(10) - for i in xrange(60): + for i in range(60): randsec = random.randint(0, 59) randval = random.random()*100. timetemp = mk.DateAndTime("2012-01-01T00:%d:%d"%(i, randsec)) @@ -108,9 +107,9 @@ Output: propws = ExportTimeSeriesLog(InputWorkspace=dataws, LogName="Temp", NumberEntriesExport=40, IsEventWorkspace=True) # Check - print "Length of X = %d, Length of Y = %d." % (len(propws.readX(0)), len(propws.readY(0))) - print "X[0] = %.1f, Y[0] = %.5f" % (propws.readX(0)[0], propws.readY(0)[0]) - print "Number of events = %d" % (propws.getNumberEvents()) + print("Length of X = {}, Length of Y = {}.".format(len(propws.readX(0)), len(propws.readY(0)))) + print("X[0] = {:.1f}, Y[0] = {:.5f}".format(propws.readX(0)[0], propws.readY(0)[0])) + print("Number of events = {}".format(propws.getNumberEvents())) .. testcleanup:: ExExpTempEvent @@ -122,7 +121,7 @@ Output: .. testoutput:: ExExpTempEvent Length of X = 2, Length of Y = 1. - X[0] = 26089826000000.0, Y[0] = 1702.58055 + X[0] = 26089801000000.0, Y[0] = 1958.93574 Number of events = 40 .. categories:: diff --git a/docs/source/algorithms/ExtractMask-v1.rst b/docs/source/algorithms/ExtractMask-v1.rst index c5daf4c305987c8492c38c97c90e93f7d073ec0a..2a9dfa07dfac906df5e3650e46669658598dd59d 100644 --- a/docs/source/algorithms/ExtractMask-v1.rst +++ b/docs/source/algorithms/ExtractMask-v1.rst @@ -39,10 +39,10 @@ Usage ws2 = CreateSampleWorkspace(NumBanks=1,BankPixelWidth=bankPixelWidth) MaskDetectors(ws2,MaskedWorkspace="wsMask") - print "Masked Detectors" - print "n ws ws2" + print("Masked Detectors") + print("n ws ws2") for i in range (ws.getNumberHistograms()): - print "%i %-5s %s" % (i, ws.getDetector(i).isMasked(), ws2.getDetector(i).isMasked()) + print("%i %-5s %s" % (i, ws.getDetector(i).isMasked(), ws2.getDetector(i).isMasked())) Output: diff --git a/docs/source/algorithms/ExtractMaskToTable-v1.rst b/docs/source/algorithms/ExtractMaskToTable-v1.rst index 64b17356e2b10f5252a8e6571858c647332274d1..35251f1b572874413e799e90af46c554a7b6a83e 100644 --- a/docs/source/algorithms/ExtractMaskToTable-v1.rst +++ b/docs/source/algorithms/ExtractMaskToTable-v1.rst @@ -43,15 +43,15 @@ Usage dataws = LoadNexusProcessed(Filename="PG3_2538_2k.nxs") # mask some detectors - for i in xrange(100): + for i in range(100): dataws.maskDetectors(100+i) # Run algorithm outmaskws = ExtractMaskToTable(InputWorkspace=dataws, Xmin = 12300., Xmax = 24500.) # Output - print "Number of rows: ", outmaskws.rowCount() - print "Row 0: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(0, 0), outmaskws.cell(0, 1), outmaskws.cell(0, 2)) + print("Number of rows: {}".format(outmaskws.rowCount())) + print("Row 0: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(0, 0), outmaskws.cell(0, 1), outmaskws.cell(0, 2))) .. testcleanup:: ExHistSimple @@ -73,7 +73,7 @@ Output: dataws = LoadNexusProcessed(Filename="PG3_2538_2k.nxs") # mask some detectors - for i in xrange(100): + for i in range(100): dataws.maskDetectors(100+i) # create a mask table workspacetws = @@ -88,10 +88,10 @@ Output: outmaskws = ExtractMaskToTable(InputWorkspace=dataws, MaskTableWorkspace=tws, Xmin = 12300., Xmax = 24500.) # Write some result - print "Number of rows: ", outmaskws.rowCount() - print "Row 0: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(0, 0), outmaskws.cell(0, 1), outmaskws.cell(0, 2)) - print "Row 1: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(1, 0), outmaskws.cell(1, 1), outmaskws.cell(1, 2)) - print "Row 2: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(2, 0), outmaskws.cell(2, 1), outmaskws.cell(2, 2)) + print("Number of rows: {}".format(outmaskws.rowCount())) + print("Row 0: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(0, 0), outmaskws.cell(0, 1), outmaskws.cell(0, 2))) + print("Row 1: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(1, 0), outmaskws.cell(1, 1), outmaskws.cell(1, 2))) + print("Row 2: Xmin = %.5f, Xmax = %.5f, DetectorIDsList = %s." % (outmaskws.cell(2, 0), outmaskws.cell(2, 1), outmaskws.cell(2, 2))) .. testcleanup:: ExOptTable diff --git a/docs/source/algorithms/ExtractMonitors-v1.rst b/docs/source/algorithms/ExtractMonitors-v1.rst index 731114c9090ab4f2f0ddc4c92c127d7a4da5defd..6b758461ae92904339b815e67ce7c3b9cb3d398e 100644 --- a/docs/source/algorithms/ExtractMonitors-v1.rst +++ b/docs/source/algorithms/ExtractMonitors-v1.rst @@ -33,17 +33,17 @@ Usage monitor_ws = mtd['Monitors'] # Detector histograms - print("Number of spectra in input workspace: {0}").format(ws.getNumberHistograms()) + print("Number of spectra in input workspace: {0}".format(ws.getNumberHistograms())) # Detector histograms (spectra missing detectors generate warnings) - print("Number of spectra in detector workspace: {0}").format(detector_ws.getNumberHistograms()) + print("Number of spectra in detector workspace: {0}".format(detector_ws.getNumberHistograms())) # Monitor histograms - print("Number of spectra in monitor workspace: {0}").format(monitor_ws.getNumberHistograms()) + print("Number of spectra in monitor workspace: {0}".format(monitor_ws.getNumberHistograms())) # Check if the first spectrum in the detector workspace is a monitor - print("Detector workspace isMonitor for spectrum 0: {0}").format(detector_ws.getDetector(0).isMonitor()) + print("Detector workspace isMonitor for spectrum 0: {0}".format(detector_ws.getDetector(0).isMonitor())) # Check if the first spectrum in the monitor workspace is a monitor - print("Monitor workspace isMonitor for spectrum 0: {0}").format(monitor_ws.getDetector(0).isMonitor()) + print("Monitor workspace isMonitor for spectrum 0: {0}".format(monitor_ws.getDetector(0).isMonitor())) # See the monitor workspace is set - print("Name of monitor workspace: {0}").format(detector_ws.getMonitorWorkspace().name()) + print("Name of monitor workspace: {0}".format(detector_ws.getMonitorWorkspace().name())) Output: diff --git a/docs/source/algorithms/ExtractSingleSpectrum-v1.rst b/docs/source/algorithms/ExtractSingleSpectrum-v1.rst index d53f48d9b63b3aa251875c0c95b4d5cf8a9f4bc4..624dd7889b1ec0eb6a587521b328d5cf40778567 100644 --- a/docs/source/algorithms/ExtractSingleSpectrum-v1.rst +++ b/docs/source/algorithms/ExtractSingleSpectrum-v1.rst @@ -20,16 +20,16 @@ Usage .. testcode:: ExExtractSingleSpectrum ws = CreateSampleWorkspace() - print "Workspace %s contains %i spectra" % (ws, ws.getNumberHistograms()) - print "Counts for every 10th bin for workspace index 5" - print ws.readY(5)[0:100:10] + print("Workspace %s contains %i spectra" % (ws, ws.getNumberHistograms())) + print("Counts for every 10th bin for workspace index 5") + print(", ".join(["{:.1f}".format(y) for y in ws.readY(5)[0:100:10]])) wsOut = ExtractSingleSpectrum(ws,WorkspaceIndex=5) - print "After extracting one spectra at workspace index 5" + print("After extracting one spectra at workspace index 5") - print "Workspace %s contains %i spectra" % (wsOut, wsOut.getNumberHistograms()) - print "Counts for every 10th bin for workspace index 0 (now it's 0 as wsOut only contains 1 spectra)" - print wsOut.readY(0)[0:100:10] + print("Workspace %s contains %i spectra" % (wsOut, wsOut.getNumberHistograms())) + print("Counts for every 10th bin for workspace index 0 (now it's 0 as wsOut only contains 1 spectra)") + print(", ".join(["{:.1f}".format(y) for y in wsOut.readY(0)[0:100:10]])) Output: @@ -38,11 +38,11 @@ Output: Workspace ws contains 200 spectra Counts for every 10th bin for workspace index 5 - [ 0.3 0.3 0.3 0.3 0.3 10.3 0.3 0.3 0.3 0.3] + 0.3, 0.3, 0.3, 0.3, 0.3, 10.3, 0.3, 0.3, 0.3, 0.3 After extracting one spectra at workspace index 5 Workspace wsOut contains 1 spectra Counts for every 10th bin for workspace index 0 (now it's 0 as wsOut only contains 1 spectra) - [ 0.3 0.3 0.3 0.3 0.3 10.3 0.3 0.3 0.3 0.3] + 0.3, 0.3, 0.3, 0.3, 0.3, 10.3, 0.3, 0.3, 0.3, 0.3 .. categories:: diff --git a/docs/source/algorithms/ExtractSpectra-v1.rst b/docs/source/algorithms/ExtractSpectra-v1.rst index 17d925e805944a17493a1ede314bacf59b9610a4..094704b06f804cbef7d0deb2064261ef2d1dfbc4 100644 --- a/docs/source/algorithms/ExtractSpectra-v1.rst +++ b/docs/source/algorithms/ExtractSpectra-v1.rst @@ -24,13 +24,13 @@ Usage # Create an input workspace ws = CreateSampleWorkspace() - print 'Input workspace has %s bins' % ws.blocksize() - print 'Input workspace has %s spectra' % ws.getNumberHistograms() + print('Input workspace has %s bins' % ws.blocksize()) + print('Input workspace has %s spectra' % ws.getNumberHistograms()) # Extract spectra 1,3 and 5 and crop the x-vector to interval 200 <= x <= 1300 cropped = ExtractSpectra(ws,200,1300,WorkspaceIndexList=[1,3,5]) - print 'Output workspace has %s bins' % cropped.blocksize() - print 'Output workspace has %s spectra' % cropped.getNumberHistograms() + print('Output workspace has %s bins' % cropped.blocksize()) + print('Output workspace has %s spectra' % cropped.getNumberHistograms()) Output: diff --git a/docs/source/algorithms/ExtractUnmaskedSpectra-v1.rst b/docs/source/algorithms/ExtractUnmaskedSpectra-v1.rst index b104502bc0020e1070a744bfc124927c9047519a..3d3a3ca9fc00f457a62d89d611c36f860fc92e05 100644 --- a/docs/source/algorithms/ExtractUnmaskedSpectra-v1.rst +++ b/docs/source/algorithms/ExtractUnmaskedSpectra-v1.rst @@ -31,8 +31,8 @@ Usage ows = ExtractUnmaskedSpectra(ws) # Compare workspace sizes - print 'Number of spectra in original workspace', ws.getNumberHistograms() - print 'Number of spectra in cropped workspace', ows.getNumberHistograms() + print('Number of spectra in original workspace {}'.format(ws.getNumberHistograms())) + print('Number of spectra in cropped workspace {}'.format(ows.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/FFT-v1.rst b/docs/source/algorithms/FFT-v1.rst index e34efd1c58fb9dec606fa99a803ea9b7b06a0b9e..23d8d392f4b37f2c901b3baa7ef116ef2dc1ba47 100644 --- a/docs/source/algorithms/FFT-v1.rst +++ b/docs/source/algorithms/FFT-v1.rst @@ -208,11 +208,10 @@ Usage #apply the FFT algorithm - note output is point data outworkspace = FFT(InputWorkspace = ws, Transform = 'Backward') - #print statements - print "DataX(0)[1] equals DataX(0)[99]? : " + str((round(abs(outworkspace.dataX(0)[1]), 3)) == (round(outworkspace.dataX(0)[99], 3))) - print "DataX(0)[10] equals DataX(0)[90]? : " + str((round(abs(outworkspace.dataX(0)[10]), 3)) == (round(outworkspace.dataX(0)[90], 3))) - print "DataX((0)[50] equals 0? : " + str((round(abs(outworkspace.dataX(0)[50]), 3)) == 0) - print "DataY(0)[40] equals DataY(0)[60]? : " + str((round(abs(outworkspace.dataY(0)[40]), 5)) == (round(outworkspace.dataY(0)[60], 5))) + print("DataX(0)[1] equals DataX(0)[99]? : " + str((round(abs(outworkspace.dataX(0)[1]), 3)) == (round(outworkspace.dataX(0)[99], 3)))) + print("DataX(0)[10] equals DataX(0)[90]? : " + str((round(abs(outworkspace.dataX(0)[10]), 3)) == (round(outworkspace.dataX(0)[90], 3)))) + print("DataX((0)[50] equals 0? : " + str((round(abs(outworkspace.dataX(0)[50]), 3)) == 0)) + print("DataY(0)[40] equals DataY(0)[60]? : " + str((round(abs(outworkspace.dataY(0)[40]), 5)) == (round(outworkspace.dataY(0)[60], 5)))) Output: diff --git a/docs/source/algorithms/FFTDerivative-v1.rst b/docs/source/algorithms/FFTDerivative-v1.rst index dea3e63929d1011aac94fdcdc08d05a856ae6162..fd926b6bbf5d8d5dacc2ff393c9e0c04d83ac61b 100644 --- a/docs/source/algorithms/FFTDerivative-v1.rst +++ b/docs/source/algorithms/FFTDerivative-v1.rst @@ -23,9 +23,9 @@ Usage wsOrder2 = FFTDerivative(wsOriginal,Order=2) wsOrder3 = FFTDerivative(wsOriginal,Order=3) - print "bin Orig 1st 2nd 3rd" + print("bin Orig 1st 2nd 3rd") for i in range (41,67,5): - print "%i %.2f %.2f %.2f %.2f" % (i, wsOriginal.readY(0)[i], wsOrder1.readY(0)[i], wsOrder2.readY(0)[i], wsOrder3.readY(0)[i]) + print("{} {:.2f} {:.2f} {:.2f} {:.2f}".format(i, wsOriginal.readY(0)[i], wsOrder1.readY(0)[i], wsOrder2.readY(0)[i], wsOrder3.readY(0)[i])) .. figure:: /images/FFTDerivativeExample.png :align: right @@ -54,8 +54,8 @@ Output: wsOrder2Test = FFTDerivative(wsOrder1,Order=1) - print "The direct 2nd order derivative and the derivative of a derivative should match" - print CompareWorkspaces(wsOrder2,wsOrder2Test,CheckAllData=True,Tolerance=1e10)[0] + print("The direct 2nd order derivative and the derivative of a derivative should match") + print(CompareWorkspaces(wsOrder2,wsOrder2Test,CheckAllData=True,Tolerance=1e10)[0]) Output: diff --git a/docs/source/algorithms/FFTSmooth-v1.rst b/docs/source/algorithms/FFTSmooth-v1.rst index b27eed6daf80497c24103281ad5676baea4118ea..244a668c3db3d2311931b7e808e09ddbed4db73b 100644 --- a/docs/source/algorithms/FFTSmooth-v1.rst +++ b/docs/source/algorithms/FFTSmooth-v1.rst @@ -46,9 +46,9 @@ Usage wsSmooth = FFTSmooth(ws, Params='2', Version=1) - print "bin Orig Smoothed" + print("bin Orig Smoothed") for i in range (0,100,10): - print "%i %.2f %.2f" % (i, ws.readY(0)[i], wsSmooth.readY(0)[i]) + print("{} {:.2f} {:.2f}".format(i, ws.readY(0)[i], wsSmooth.readY(0)[i])) .. figure:: /images/FFTSmoothZeroing.png diff --git a/docs/source/algorithms/FFTSmooth-v2.rst b/docs/source/algorithms/FFTSmooth-v2.rst index a1d132f711315cdebba329bf70f637f5a065c3e9..1bef23441fa9d1c2c1f63958f524f23b54dbade3 100644 --- a/docs/source/algorithms/FFTSmooth-v2.rst +++ b/docs/source/algorithms/FFTSmooth-v2.rst @@ -67,9 +67,9 @@ Usage wsSmooth = FFTSmooth(ws, Params='2') - print "bin Orig Smoothed" + print("bin Orig Smoothed") for i in range (0,100,10): - print "%i %.2f %.2f" % (i, ws.readY(0)[i], wsSmooth.readY(0)[i]) + print("{} {:.2f} {:.2f}".format(i, ws.readY(0)[i], wsSmooth.readY(0)[i])) .. figure:: /images/FFTSmoothZeroing.png @@ -114,9 +114,9 @@ Output: wsButter5_2 = FFTSmooth(ws, Filter="Butterworth", Params='5,2', AllSpectra=True) wsButter20_2 = FFTSmooth(ws, Filter="Butterworth", Params='20,2', AllSpectra=True) - print "bin Orig 2_2 5_2 20_2" + print("bin Orig 2_2 5_2 20_2") for i in range (0,100,10): - print "%i %.2f %.2f %.2f %.2f" % (i, ws.readY(0)[i], wsButter2_2.readY(0)[i], wsButter5_2.readY(0)[i], wsButter20_2.readY(0)[i]) + print("{} {:.2f} {:.2f} {:.2f} {:.2f}".format(i, ws.readY(0)[i], wsButter2_2.readY(0)[i], wsButter5_2.readY(0)[i], wsButter20_2.readY(0)[i])) .. figure:: /images/FFTSmoothZeroingButter.png diff --git a/docs/source/algorithms/FakeISISEventDAE-v1.rst b/docs/source/algorithms/FakeISISEventDAE-v1.rst index 8c5eb452bcfe87e07d0fa45e4f2b9a5beeca9945..dd8ccf50f955d24ba2ed4df6e515f024f5588696 100644 --- a/docs/source/algorithms/FakeISISEventDAE-v1.rst +++ b/docs/source/algorithms/FakeISISEventDAE-v1.rst @@ -67,8 +67,8 @@ Usage try: captureLive() - except Exception, exc: - print "Error occurred starting live data" + except: + print("Error occurred starting live data") finally: thread.join() # this must get hit @@ -77,7 +77,7 @@ Usage #get the ouput workspace wsOut = mtd["wsOut"] - print "The workspace contains %i events" % wsOut.getNumberEvents() + print("The workspace contains %i events" % wsOut.getNumberEvents()) Output: diff --git a/docs/source/algorithms/FakeISISHistoDAE-v1.rst b/docs/source/algorithms/FakeISISHistoDAE-v1.rst index 3b61adf99d78c9f9584481388dcbf28bcb58c6ba..64be954cbced56b98848eb8a87ce33e02bcb82c4 100644 --- a/docs/source/algorithms/FakeISISHistoDAE-v1.rst +++ b/docs/source/algorithms/FakeISISHistoDAE-v1.rst @@ -61,8 +61,8 @@ Usage try: captureLive() - except Exception, exc: - print "Error occurred starting live data" + except: + print("Error occurred starting live data") finally: thread.join() # this must get hit @@ -71,7 +71,7 @@ Usage #get the ouput workspace wsOut = mtd["wsOut"] - print "The workspace contains %i histograms" % wsOut.getNumberHistograms() + print("The workspace contains %i histograms" % wsOut.getNumberHistograms()) Output: diff --git a/docs/source/algorithms/FakeMDEventData-v1.rst b/docs/source/algorithms/FakeMDEventData-v1.rst index f1ce1a4be7c5c4ed1d3b144653d98a92ab6c677d..2566749755edc5d75e9b5844c2ccfde93edaceb5 100644 --- a/docs/source/algorithms/FakeMDEventData-v1.rst +++ b/docs/source/algorithms/FakeMDEventData-v1.rst @@ -28,7 +28,7 @@ using :ref:`CreateMDWorkspace <algm-CreateMDWorkspace>`. ws = CreateMDWorkspace(Dimensions='2', EventType='MDEvent', Extents='-10,10,-10,10', Names='Q_lab_x,Q_lab_y', Units='A,B') FakeMDEventData(ws, UniformParams="1000000") - print "Number of events =", ws.getNEvents() + print("Number of events = {}".format(ws.getNEvents())) Output: @@ -54,7 +54,7 @@ Creates 3 peaks in (H,K,L) at (0,0,0), (1,1,0) and (1,1,1). FakeMDEventData(ws, PeakParams='10000,1,1,1,0.1', RandomSeed='63759', RandomizeSignal='1') FakeMDEventData(ws, PeakParams='100000,0,0,0,0.1', RandomSeed='63759', RandomizeSignal='1') FakeMDEventData(ws, PeakParams='40000,1,1,0,0.1', RandomSeed='63759', RandomizeSignal='1') - print "Number of events =", ws.getNEvents() + print("Number of events = {}".format(ws.getNEvents())) Output: @@ -85,7 +85,7 @@ Creates a peak at (H,K,L) of (0,0,0) around T=5K. ws = CreateMDWorkspace(Dimensions='4', Extents='-1,1,-1,1,-1,1,0,10', Names='H,K,L,T', Units='rlu,rlu,rlu,K', SplitInto='2', SplitThreshold='50') FakeMDEventData(ws, PeakParams='1e+06,0,0,0,5,0.2', RandomSeed='3873875') - print "Number of events =", ws.getNEvents() + print("Number of events = {}".format(ws.getNEvents())) Output: diff --git a/docs/source/algorithms/FilterBadPulses-v1.rst b/docs/source/algorithms/FilterBadPulses-v1.rst index c46cd5a239e90cf9541e0ca4f4d8a8aa55c3c7ef..d90b34fa8d438906d3e10522207b9a0263198d43 100644 --- a/docs/source/algorithms/FilterBadPulses-v1.rst +++ b/docs/source/algorithms/FilterBadPulses-v1.rst @@ -33,8 +33,8 @@ Usage AddSampleLog(ws,"gd_prtn_chrg", "1e6", "Number") wsFiltered = FilterBadPulses(ws) - print ("The number of events that remain: %i" % wsFiltered.getNumberEvents()) - print ("compared to the number in the unfiltered workspace: %i" % ws.getNumberEvents()) + print("The number of events that remain: %i" % wsFiltered.getNumberEvents()) + print("compared to the number in the unfiltered workspace: %i" % ws.getNumberEvents()) Output: diff --git a/docs/source/algorithms/FilterByLogValue-v1.rst b/docs/source/algorithms/FilterByLogValue-v1.rst index 5d19b7291c7ac986c34dacc599a261f291ba3728..757d3077511bcb83499f5f4d800867303b258a91 100644 --- a/docs/source/algorithms/FilterByLogValue-v1.rst +++ b/docs/source/algorithms/FilterByLogValue-v1.rst @@ -97,11 +97,11 @@ Usage AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:40:00", Value=15) AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:50:00", Value=100) - print "The unfiltered workspace %s has %i events and a peak value of %.2f" % (ws, ws.getNumberEvents(),ws.readY(0)[50]) + print("The unfiltered workspace {} has {} events and a peak value of {:.2f}".format(ws, ws.getNumberEvents(),ws.readY(0)[50])) wsOut = FilterByLogValue(ws,"proton_charge",MinimumValue=75, MaximumValue=150) - print "The filtered workspace %s has %i events and a peak value of %.2f" % (wsOut, wsOut.getNumberEvents(),wsOut.readY(0)[50]) + print("The filtered workspace {} has {} events and a peak value of {:.2f}".format(wsOut, wsOut.getNumberEvents(),wsOut.readY(0)[50])) Output: diff --git a/docs/source/algorithms/FilterByTime-v1.rst b/docs/source/algorithms/FilterByTime-v1.rst index 18afeb60bcf58568e5285a4035738ff2263b25fe..075d9cd6d4ce2e367808a47ee1f900a669ce9949 100644 --- a/docs/source/algorithms/FilterByTime-v1.rst +++ b/docs/source/algorithms/FilterByTime-v1.rst @@ -53,9 +53,9 @@ Usage AbsoluteStartTime="2010-01-01T00:10:00", AbsoluteStopTime="2010-01-01T00:20:00") - print ("The number of events within the relative Filter: %i" % wsFiltered.getNumberEvents()) - print ("The number of events within the Aboslute Filter: %i" % wsFilteredAbs.getNumberEvents()) - print ("Compared to the number in the unfiltered workspace: %i" % ws.getNumberEvents()) + print("The number of events within the relative Filter: %i" % wsFiltered.getNumberEvents()) + print("The number of events within the Aboslute Filter: %i" % wsFilteredAbs.getNumberEvents()) + print("Compared to the number in the unfiltered workspace: %i" % ws.getNumberEvents()) Output: diff --git a/docs/source/algorithms/FilterByXValue-v1.rst b/docs/source/algorithms/FilterByXValue-v1.rst index 0870c0cbf37ceab576e58cc352ce6012a1e15107..120a8e3626f171b84ddb5bc0c03d463722563edb 100644 --- a/docs/source/algorithms/FilterByXValue-v1.rst +++ b/docs/source/algorithms/FilterByXValue-v1.rst @@ -26,9 +26,9 @@ Usage .. testcode:: ExFilterTofByMax ws = CreateSampleWorkspace("Event",BankPixelWidth=1) - print "%i events before filtering" % ws.getNumberEvents() + print("%i events before filtering" % ws.getNumberEvents()) wsOut = FilterByXValue(ws,XMax=15000) - print "%i events after filtering" % wsOut.getNumberEvents() + print("%i events after filtering" % wsOut.getNumberEvents()) Output: @@ -44,9 +44,9 @@ Output: ws = CreateSampleWorkspace("Event",BankPixelWidth=1) ws = ConvertUnits(ws,"Wavelength") - print "%i events before filtering" % ws.getNumberEvents() + print("%i events before filtering" % ws.getNumberEvents()) wsOut = FilterByXValue(ws,XMin=1,XMax=3) - print "%i events after filtering" % wsOut.getNumberEvents() + print("%i events after filtering" % wsOut.getNumberEvents()) Output: diff --git a/docs/source/algorithms/FilterEvents-v1.rst b/docs/source/algorithms/FilterEvents-v1.rst index ba45cb8d2ec015d1d6b4a94b5e0d310424303e63..9d78efc93deb4bf219b98c8c16dbc0d9e7ded91a 100644 --- a/docs/source/algorithms/FilterEvents-v1.rst +++ b/docs/source/algorithms/FilterEvents-v1.rst @@ -162,7 +162,7 @@ Usage wsnames = wsgroup.getNames() for name in sorted(wsnames): tmpws = mtd[name] - print "workspace %s has %d events" % (name, tmpws.getNumberEvents()) + print("workspace %s has %d events" % (name, tmpws.getNumberEvents())) Output: @@ -207,9 +207,9 @@ Output: wsnames = wsgroup.getNames() for name in sorted(wsnames): tmpws = mtd[name] - print "workspace %s has %d events" % (name, tmpws.getNumberEvents()) + print("workspace %s has %d events" % (name, tmpws.getNumberEvents())) split_log = tmpws.run().getProperty('splitter') - print 'event splitter log: entry 0 and entry 1 are {0} and {1}.'.format(split_log.times[0], split_log.times[1]) + print('event splitter log: entry 0 and entry 1 are {0} and {1}.'.format(split_log.times[0], split_log.times[1])) Output: @@ -251,7 +251,7 @@ Output: wsnames = wsgroup.getNames() for name in sorted(wsnames): tmpws = mtd[name] - print "workspace %s has %d events" % (name, tmpws.getNumberEvents()) + print("workspace %s has %d events" % (name, tmpws.getNumberEvents())) Output: @@ -290,7 +290,7 @@ Output: wsnames = wsgroup.getNames() for name in sorted(wsnames): tmpws = mtd[name] - print "workspace %s has %d events" % (name, tmpws.getNumberEvents()) + print("workspace %s has %d events" % (name, tmpws.getNumberEvents())) Output: diff --git a/docs/source/algorithms/FilterLogByTime-v1.rst b/docs/source/algorithms/FilterLogByTime-v1.rst index b44bd6fee1ba0f262f267632767913462a6a663a..3a59a1ecd3255866ba099938b67ccfe01ece06b2 100644 --- a/docs/source/algorithms/FilterLogByTime-v1.rst +++ b/docs/source/algorithms/FilterLogByTime-v1.rst @@ -40,26 +40,26 @@ Usage AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:40:00", Value=15) AddTimeSeriesLog(ws, Name="proton_charge", Time="2010-01-01T00:50:00", Value=100) - print ("Without a StartTime or EndTime all of the values are included") + print("Without a StartTime or EndTime all of the values are included") (filtered_result,stat_result) = FilterLogByTime(ws,LogName="proton_charge") - print ("The default statistic is mean: %i" % stat_result) - print ("The filtered result is") - print (filtered_result) + print("The default statistic is mean: %i" % stat_result) + print("The filtered result is") + print(filtered_result) (filtered_result,stat_result) = FilterLogByTime(ws,LogName="proton_charge", Method="max") - print ("The max is: %i" % stat_result) + print("The max is: %i" % stat_result) (filtered_result,stat_result) = FilterLogByTime(ws,LogName="proton_charge", Method="min") - print ("The min is: %i" % stat_result) + print("The min is: %i" % stat_result) (filtered_result,stat_result) = FilterLogByTime(ws,LogName="proton_charge", Method="median") - print ("The median is: %i" % stat_result) - print + print("The median is: %i" % stat_result) + print("") print("Adding a start time and optionally an end time allows you to filter the values") (filtered_result,stat_result) = FilterLogByTime(ws,LogName="proton_charge", StartTime=580,EndTime = 1800) - print ("The filtered mean is: %i" % stat_result) - print ("The filtered result is") - print (filtered_result) + print("The filtered mean is: %i" % stat_result) + print("The filtered result is") + print(filtered_result) Output: diff --git a/docs/source/algorithms/FindDeadDetectors-v1.rst b/docs/source/algorithms/FindDeadDetectors-v1.rst index b7f410db0688cb9720866081733d07beddf37610..9b2e143ec19b91b48ffa75831c27e5123b134215 100644 --- a/docs/source/algorithms/FindDeadDetectors-v1.rst +++ b/docs/source/algorithms/FindDeadDetectors-v1.rst @@ -43,17 +43,17 @@ Usage str_data=[0.4,5.0,0.001,0.0,0.0,0.0,0.0,0.0,1.0,1.0] ws.setY(20,np.array(str_data)) - print "With no range will find very dead" + print("With no range will find very dead") (wsOut,detList) = FindDeadDetectors(ws) - print str(detList) + print(detList) - print "\nwith a lower range will find very dead and drop off" + print("\nwith a lower range will find very dead and drop off") (wsOut,detList) = FindDeadDetectors(ws,RangeLower=8e3) - print str(detList) + print(detList) - print "\nwith a lower range and upper range will find all three" + print("\nwith a lower range and upper range will find all three") (wsOut,detList) = FindDeadDetectors(ws,RangeLower=8e3, rangeUpper=1.6e4) - print str(detList) + print(detList) Output: diff --git a/docs/source/algorithms/FindDetectorsInShape-v1.rst b/docs/source/algorithms/FindDetectorsInShape-v1.rst index 38b803444cb0a9984e17777fcc3da58f1103eb6c..396988effb94fd4de0137525dea4c93b7dcee0d9 100644 --- a/docs/source/algorithms/FindDetectorsInShape-v1.rst +++ b/docs/source/algorithms/FindDetectorsInShape-v1.rst @@ -53,8 +53,8 @@ Usage no_detectors = FindDetectorsInShape(musr_inst_ws, narrow_cylinder) all_detectors = FindDetectorsInShape(musr_inst_ws, wide_cylinder) - print "The narrow cylinder contains %i of the detectors." % len(no_detectors) - print "The wide cylinder contains %i of the detectors." % len(all_detectors) + print("The narrow cylinder contains %i of the detectors." % len(no_detectors)) + print("The wide cylinder contains %i of the detectors." % len(all_detectors)) Output: diff --git a/docs/source/algorithms/FindDetectorsOutsideLimits-v1.rst b/docs/source/algorithms/FindDetectorsOutsideLimits-v1.rst index 126443985114aa9efd1370b1034df482f7648bec..1533d25ddaa87184d675276c7e50a26a80bfea0f 100644 --- a/docs/source/algorithms/FindDetectorsOutsideLimits-v1.rst +++ b/docs/source/algorithms/FindDetectorsOutsideLimits-v1.rst @@ -41,15 +41,15 @@ Usage ws.setY(i,np.array(deadDetArray)) ws.setY(i+1,np.array(noisyDetArray)) - print "With just the default LowThreshold of 0" + print("With just the default LowThreshold of 0") (wsOut,NumberOfFailures)=FindDetectorsOutsideLimits(ws) - print "%i spectra were outside the limits." % NumberOfFailures - print + print("{} spectra were outside the limits.".format(NumberOfFailures)) + print("") - print "With a High and LowThreshold, as well as restricting the XRange to consider" + print("With a High and LowThreshold, as well as restricting the range to consider") (wsOut2,NumberOfFailures)=FindDetectorsOutsideLimits(ws, HighThreshold=1000, LowThreshold=0, RangeLower=200, RangeUpper=10000) - print "%i spectra were outside the limits." % NumberOfFailures + print("{} spectra were outside the limits.".format(NumberOfFailures)) mtd.clear() @@ -61,7 +61,7 @@ Output: With just the default LowThreshold of 0 20 spectra were outside the limits. - With a High and LowThreshold, as well as restricting the XRange to consider + With a High and LowThreshold, as well as restricting the range to consider 40 spectra were outside the limits. **Example:** @@ -70,7 +70,7 @@ Output: ws = CreateSimulationWorkspace('MARI','0,1,10') nh = ws.getNumberHistograms() - for ind in xrange(nh): + for ind in range(nh): y = ws.dataY(ind) if ind>=100 and ind < 300: y.fill(100) @@ -80,15 +80,15 @@ Output: mws1,nMasked1 = FindDetectorsOutsideLimits(ws,100) mws2,nMasked2 = FindDetectorsOutsideLimits(ws,100,startWorkspaceIndex = 200) - print "****************************************" - print "full mask ws has {0} masked detectors".format(nMasked1) - print "part mask ws has {0} masked detectors".format(nMasked2) - print "****************************************" + print("****************************************") + print("full mask ws has {0} masked detectors".format(nMasked1)) + print("part mask ws has {0} masked detectors".format(nMasked2)) + print("****************************************") selected_spec = [99,100,199,200,299,300] for spec in selected_spec: - print "full mask ws Spec N{0} is masked: {1}".format(spec,mws1.readY(spec)[0]>0.5) - print "part mask ws Spec N{0} is masked: {1}".format(spec,mws2.readY(spec)[0]>0.5) - print "****************************************" + print("full mask ws Spec N{0} is masked: {1}".format(spec,mws1.readY(spec)[0]>0.5)) + print("part mask ws Spec N{0} is masked: {1}".format(spec,mws2.readY(spec)[0]>0.5) ) + print("****************************************") Output: diff --git a/docs/source/algorithms/FindDetectorsPar-v1.rst b/docs/source/algorithms/FindDetectorsPar-v1.rst index bb6fa2e89a61ed04e9c46bb65101be7e8431e05b..4ba2c875bdd5863d42d4eda7583d62568de4e826 100644 --- a/docs/source/algorithms/FindDetectorsPar-v1.rst +++ b/docs/source/algorithms/FindDetectorsPar-v1.rst @@ -81,9 +81,9 @@ Usage # Output workspace is None if OutputParTable is not used) pars = FindDetectorsPar(ws, OutputParTable="pars") # pars is a TableWorkspace - print "Workspace type =", pars.id() + print("Workspace type = {}".format(pars.id())) # Show width column headers - print "Width headers = (", pars.getColumnNames()[3], ",", pars.getColumnNames()[4], ")" + print("Width headers = ( {} , {} )".format(pars.getColumnNames()[3], pars.getColumnNames()[4])) Output: @@ -100,9 +100,9 @@ Output: # Output workspace is None if OutputParTable is not used) pars = FindDetectorsPar(ws, ReturnLinearRanges=True, OutputParTable="pars") # pars is a TableWorkspace - print "Workspace type =", pars.id() + print("Workspace type = {}".format(pars.id())) # Show width column headers - print "Width headers = (", pars.getColumnNames()[3], ",", pars.getColumnNames()[4], ")" + print("Width headers = ( {} , {} )".format(pars.getColumnNames()[3], pars.getColumnNames()[4])) Output: diff --git a/docs/source/algorithms/FindEPP-v1.rst b/docs/source/algorithms/FindEPP-v1.rst index ffa00dab2f4d08f7e3b338a51b5c1626edb44c3c..e3e3334e8964df233a9422a44d2b2ce58bfaa89a 100644 --- a/docs/source/algorithms/FindEPP-v1.rst +++ b/docs/source/algorithms/FindEPP-v1.rst @@ -31,9 +31,9 @@ Usage table = FindEPP(ws, Version=1) # print some results - print "The fit status is", table.row(0)['FitStatus'] - print "The peak centre is at", round(table.row(0)['PeakCentre'], 2), "microseconds" - print "The peak height is", round(table.row(0)['Height'],2) + print("The fit status is {}".format(table.row(0)['FitStatus'])) + print("The peak centre is at {} microseconds".format(round(table.row(0)['PeakCentre'], 2))) + print("The peak height is {}".format(round(table.row(0)['Height'],2))) Output: diff --git a/docs/source/algorithms/FindEPP-v2.rst b/docs/source/algorithms/FindEPP-v2.rst index 398731f00d3bee715e46adfbc2fcd68c93b4f5bd..5d21c8caf27c5c1e12403f093a1c978c26dfca50 100644 --- a/docs/source/algorithms/FindEPP-v2.rst +++ b/docs/source/algorithms/FindEPP-v2.rst @@ -40,9 +40,9 @@ Usage table = FindEPP(ws) # print some results - print "The fit status is", table.row(0)['FitStatus'] - print "The peak centre is at", round(table.row(0)['PeakCentre'], 2), "microseconds" - print "The peak height is", round(table.row(0)['Height'],2) + print("The fit status is {}".format(table.row(0)['FitStatus'])) + print("The peak centre is at {} microseconds".format(round(table.row(0)['PeakCentre'], 2))) + print("The peak height is {}".format(round(table.row(0)['Height'],2))) Output: diff --git a/docs/source/algorithms/FindPeaks-v1.rst b/docs/source/algorithms/FindPeaks-v1.rst index 93fdb6e0fd1c0a65a56f573f7a53f77731cbb994..7dec298b87ee0460735beac301dbcf644b931ec6 100644 --- a/docs/source/algorithms/FindPeaks-v1.rst +++ b/docs/source/algorithms/FindPeaks-v1.rst @@ -100,8 +100,7 @@ Usage row = table.row(0) - #print row - print "Peak 1 {Centre: %.3f, width: %.3f, height: %.3f }" % ( row["centre"], row["width"], row["height"]) + print("Peak 1 {Centre: %.3f, width: %.3f, height: %.3f }" % ( row["centre"], row["width"], row["height"])) Output: diff --git a/docs/source/algorithms/FindPeaksMD-v1.rst b/docs/source/algorithms/FindPeaksMD-v1.rst index 91ee79d2e486a5e49e550f1b385a6c1644160710..7b1a29af7a50ac9936fed2e23fa3fd5db5d20994 100644 --- a/docs/source/algorithms/FindPeaksMD-v1.rst +++ b/docs/source/algorithms/FindPeaksMD-v1.rst @@ -76,18 +76,18 @@ file is availible in `Mantid system tests repository <https://github.com/mantidp for name in tab_names: if len(name)>8: name= name[0:8]; - print "| {0:8} ".format(name), - print "|\n", + print("| {0:8} ".format(name)) + print("|\n") for i in xrange(0,nRows): for name in tab_names: col = pTWS.column(name); data2pr=col[i] if type(data2pr) is float: - print "| {0:>8.2f} ".format(data2pr), + print("| {0:>8.2f} ".format(data2pr)) else: - print "| {0:>8} ".format(data2pr), - print "|\n", + print("| {0:>8} ".format(data2pr)) + print("|\n") # load test workspace diff --git a/docs/source/algorithms/FindReflectometryLines-v1.rst b/docs/source/algorithms/FindReflectometryLines-v1.rst index 600b75086d78b2a9c275f1752be96f0be15cf63b..8658801e013f42af57adff0cd8459122cc7a49d6 100644 --- a/docs/source/algorithms/FindReflectometryLines-v1.rst +++ b/docs/source/algorithms/FindReflectometryLines-v1.rst @@ -36,7 +36,7 @@ Usage wsOut = FindReflectometryLines(ws) for i in range(wsOut.columnCount()): - print wsOut.getColumnNames()[i], wsOut.column(i)[0] + print("{} {}".format(wsOut.getColumnNames()[i], wsOut.column(i)[0])) Output: diff --git a/docs/source/algorithms/FindSXPeaks-v1.rst b/docs/source/algorithms/FindSXPeaks-v1.rst index 811893a826ff689fd819ac4216ffb18d0a41a908..aa8708b8c041754ab5a29309c296dff1040e164d 100644 --- a/docs/source/algorithms/FindSXPeaks-v1.rst +++ b/docs/source/algorithms/FindSXPeaks-v1.rst @@ -73,7 +73,7 @@ Usage wsPeaks = FindSXPeaks(ws) - print "Peaks found: " + str(wsPeaks.getNumberPeaks()) + print("Peaks found: {}".format(wsPeaks.getNumberPeaks())) Output: diff --git a/docs/source/algorithms/FindUBUsingFFT-v1.rst b/docs/source/algorithms/FindUBUsingFFT-v1.rst index dc20e3e9c9ef43c6d6120168f7e299693bf06079..e6da90fce3d0e014456297c2f9c725880f9a2c28 100644 --- a/docs/source/algorithms/FindUBUsingFFT-v1.rst +++ b/docs/source/algorithms/FindUBUsingFFT-v1.rst @@ -46,12 +46,12 @@ Usage .. testcode:: ExFindUBUsingFFT ws=LoadIsawPeaks("TOPAZ_3007.peaks") - print "After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) FindUBUsingFFT(ws,MinD=8.0,MaxD=13.0) - print "After FindUBUsingFFT does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After FindUBUsingFFT does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) - print ws.sample().getOrientedLattice().getUB() + print(ws.sample().getOrientedLattice().getUB()) Output: diff --git a/docs/source/algorithms/FindUBUsingIndexedPeaks-v1.rst b/docs/source/algorithms/FindUBUsingIndexedPeaks-v1.rst index 14c934b71399f50fa3f5e3e88a6cfcb87f684057..9f012d1c6451e94c05427362863a96687e142dca 100644 --- a/docs/source/algorithms/FindUBUsingIndexedPeaks-v1.rst +++ b/docs/source/algorithms/FindUBUsingIndexedPeaks-v1.rst @@ -27,12 +27,12 @@ Usage .. testcode:: ExFindUBUsingIndexedPeaks ws=LoadIsawPeaks("TOPAZ_3007.peaks") - print "After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) FindUBUsingIndexedPeaks(ws) - print "After FindUBUsingIndexedPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After FindUBUsingIndexedPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) - print ws.sample().getOrientedLattice().getUB() + print(ws.sample().getOrientedLattice().getUB()) Output: diff --git a/docs/source/algorithms/FindUBUsingLatticeParameters-v1.rst b/docs/source/algorithms/FindUBUsingLatticeParameters-v1.rst index f67ed4fdad26ab510e308279a81eb767d24ca3bf..d31f8cfc3ed504b1e6dad0dab990143ebb1f0b2f 100644 --- a/docs/source/algorithms/FindUBUsingLatticeParameters-v1.rst +++ b/docs/source/algorithms/FindUBUsingLatticeParameters-v1.rst @@ -49,12 +49,12 @@ Usage .. testcode:: ExFindUBUsingLatticeParameters ws=LoadIsawPeaks("TOPAZ_3007.peaks") - print "After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After LoadIsawPeaks does the workspace have an orientedLattice: {}".format(ws.sample().hasOrientedLattice())) FindUBUsingLatticeParameters(ws,a=14.131,b=19.247,c=8.606,alpha=90.0,beta=105.071,gamma=90.0,NumInitial=15) - print "After FindUBUsingLatticeParameters does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After FindUBUsingLatticeParameters does the workspace have an orientedLattice: {}".format(ws.sample().hasOrientedLattice())) - print ws.sample().getOrientedLattice().getUB() + print(ws.sample().getOrientedLattice().getUB()) Output: diff --git a/docs/source/algorithms/FindUBUsingMinMaxD-v1.rst b/docs/source/algorithms/FindUBUsingMinMaxD-v1.rst index f8377400779c982ac8690c31fa6a54b8db20dfeb..27be73a329442b37211b1d0ca04275c85d9fdf03 100644 --- a/docs/source/algorithms/FindUBUsingMinMaxD-v1.rst +++ b/docs/source/algorithms/FindUBUsingMinMaxD-v1.rst @@ -34,12 +34,12 @@ Usage .. testcode:: ExFindUBUsingMinMaxD ws=LoadIsawPeaks("TOPAZ_3007.peaks") - print "After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After LoadIsawPeaks does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) FindUBUsingMinMaxD(ws,MinD=8.0,MaxD=13.0) - print "After FindUBUsingMinMaxD does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice() + print("After FindUBUsingMinMaxD does the workspace have an orientedLattice: %s" % ws.sample().hasOrientedLattice()) - print ws.sample().getOrientedLattice().getUB() + print(ws.sample().getOrientedLattice().getUB()) Output: diff --git a/docs/source/algorithms/Fit-v1.rst b/docs/source/algorithms/Fit-v1.rst index 66b4087f5ff396379b573862756a243aa86f9cbe..035b0430a80232ed73337d74293b2f047bc5ea8f 100644 --- a/docs/source/algorithms/Fit-v1.rst +++ b/docs/source/algorithms/Fit-v1.rst @@ -382,7 +382,6 @@ Usage .. testcode:: ExFitPeak - from __future__ import print_function # create a workspace with a gaussian peak sitting on top of a linear (here flat) background ws = CreateSampleWorkspace(Function="User Defined", UserDefinedFunction="name=LinearBackground, \ A0=0.3;name=Gaussian, PeakCentre=5, Height=10, Sigma=0.7", NumBanks=1, BankPixelWidth=1, XMin=0, XMax=10, BinWidth=0.1) @@ -406,14 +405,14 @@ Usage paramTable = fit_output.OutputParameters # table containing the optimal fit parameters fitWorkspace = fit_output.OutputWorkspace - print("The fit was: " + fit_output.OutputStatus) - print("chi-squared of fit is: %.2f" % fit_output.OutputChi2overDoF) - print("Fitted Height value is: %.2f" % paramTable.column(1)[0]) - print("Fitted centre value is: %.2f" % paramTable.column(1)[1]) - print("Fitted sigma value is: %.2f" % paramTable.column(1)[2]) + print("The fit was: {}".format(fit_output.OutputStatus)) + print("chi-squared of fit is: {:.2f}".format(fit_output.OutputChi2overDoF)) + print("Fitted Height value is: {:.2f}".format(paramTable.column(1)[0])) + print("Fitted centre value is: {:.2f}".format(paramTable.column(1)[1])) + print("Fitted sigma value is: {:.2f}".format(paramTable.column(1)[2])) # fitWorkspace contains the data, the calculated and the difference patterns - print("Number of spectra in fitWorkspace is: " + str(fitWorkspace.getNumberHistograms())) - print("The 20th y-value of the calculated pattern: %.4f" % fitWorkspace.readY(1)[19]) + print("Number of spectra in fitWorkspace is: {}".format(fitWorkspace.getNumberHistograms())) + print("The 20th y-value of the calculated pattern: {:.4f}".format(fitWorkspace.readY(1)[19])) Output: @@ -431,7 +430,6 @@ Output: .. testcode:: simFit - from __future__ import print_function import math import numpy as np @@ -470,7 +468,6 @@ Output: .. testcode:: shareFit - from __future__ import print_function import math import numpy as np @@ -508,7 +505,6 @@ Output: .. testcode:: shareFit2 - from __future__ import print_function import math import numpy as np @@ -554,4 +550,4 @@ Output: .. sourcelink:: :h: Framework/CurveFitting/inc/MantidCurveFitting/Algorithms/Fit.h - :cpp: Framework/CurveFitting/src/Algorithms/Fit.cpp \ No newline at end of file + :cpp: Framework/CurveFitting/src/Algorithms/Fit.cpp diff --git a/docs/source/algorithms/FitGaussian-v1.rst b/docs/source/algorithms/FitGaussian-v1.rst index ad8970cb5ed1e550a1be3f6fae7a228c0b3b10ed..779dd6ba6da4a9b2722b8665f41849e7fad85a1d 100644 --- a/docs/source/algorithms/FitGaussian-v1.rst +++ b/docs/source/algorithms/FitGaussian-v1.rst @@ -45,9 +45,9 @@ Usage # attempt the fit fitResult = FitGaussian(wspace,0) if (0.0,0.0) == fitResult: - print "the fit was not successful" + print("the fit was not successful") else: - print "the fitted peak: centre=%.2f, sigma=%.2f" % fitResult + print("the fitted peak: centre={:.2f}, sigma={:.2f}".format(fitResult[0], fitResult[1])) .. testcleanup:: ExFitPeak diff --git a/docs/source/algorithms/FitPeak-v1.rst b/docs/source/algorithms/FitPeak-v1.rst index f0313b90704c98ede1dfc41a03589d47d3b98e2d..0149c2ebf09b15df50917f656e824f3b5454131e 100644 --- a/docs/source/algorithms/FitPeak-v1.rst +++ b/docs/source/algorithms/FitPeak-v1.rst @@ -147,7 +147,7 @@ Usage peakheight = tbws.cell(2, 1) peakcentre = tbws.cell(3, 1) sigma = tbws.cell(4, 1) - print "Chi-square = %.5f: Peak centre = %.5f, Height = %.2f, Sigma = %.5f" % (chi2, peakcentre, peakheight, sigma) + print("Chi-square = {:.5f}: Peak centre = {:.5f}, Height = {:.2f}, Sigma = {:.5f}".format(chi2, peakcentre, peakheight, sigma)) .. testcleanup:: ExFitPeak diff --git a/docs/source/algorithms/FitPowderDiffPeaks-v1.rst b/docs/source/algorithms/FitPowderDiffPeaks-v1.rst index f33f53b52adc31d64fda8d284f429e9cc3d7d4ac..04796e007eb77eb7145ee504c60c915852133e7b 100644 --- a/docs/source/algorithms/FitPowderDiffPeaks-v1.rst +++ b/docs/source/algorithms/FitPowderDiffPeaks-v1.rst @@ -139,9 +139,9 @@ Usage # Print result resultws = mtd["BraggPeakParameterTable2_P"] - for i in xrange(10): - print "Peak @ d = %.5f, TOF_0 = %.5f, A = %.5f, B = %.5f, Sigma = %.5f" % (resultws.readX(0)[i], - resultws.readY(0)[i], resultws.readY(1)[i], resultws.readY(2)[i], resultws.readY(3)[i]) + for i in range(10): + print("Peak @ d = {:.5f}, TOF_0 = {:.5f}, A = {:.5f}, B = {:.5f}, Sigma = {:.5f}". + format(resultws.readX(0)[i], resultws.readY(0)[i], resultws.readY(1)[i], resultws.readY(2)[i], resultws.readY(3)[i])) .. testcleanup:: ExFitSingleDiffPeaks diff --git a/docs/source/algorithms/FixGSASInstrumentFile-v1.rst b/docs/source/algorithms/FixGSASInstrumentFile-v1.rst index 1080a5e13052d9537e58c56ad62393a0fea6537b..fe76a35484bf0a99a8867c5ccd939d4079039eb1 100644 --- a/docs/source/algorithms/FixGSASInstrumentFile-v1.rst +++ b/docs/source/algorithms/FixGSASInstrumentFile-v1.rst @@ -41,7 +41,7 @@ Usage numlinefewer80b += 1 # Print out result - print "Corrected File: Number of lines that are not equal to 80 characters = ", numlinefewer80b + print("Corrected File: Number of lines that are not equal to 80 characters = {}".format(numlinefewer80b)) .. testcleanup:: ExHistSimple diff --git a/docs/source/algorithms/FlatPlateAbsorption-v1.rst b/docs/source/algorithms/FlatPlateAbsorption-v1.rst index 22219abe2ef404f7dfa1494f32494a433a7a131c..1ef508555216b7e32a86d944769184d155394b61 100644 --- a/docs/source/algorithms/FlatPlateAbsorption-v1.rst +++ b/docs/source/algorithms/FlatPlateAbsorption-v1.rst @@ -44,7 +44,7 @@ Usage wsOut = FlatPlateAbsorption(ws, SampleHeight=1, SampleWidth=0.5, SampleThickness=0.5) - print "The created workspace has one entry for each spectra: %i" % wsOut.getNumberHistograms() + print("The created workspace has one entry for each spectra: %i" % wsOut.getNumberHistograms()) Output: diff --git a/docs/source/algorithms/FlatPlatePaalmanPingsCorrection-v1.rst b/docs/source/algorithms/FlatPlatePaalmanPingsCorrection-v1.rst index 81b4ccfd3af12c4acb37ba89555a672752a5e85b..1cf5a9118b4df6a334ef118db7892e2ae66674cc 100644 --- a/docs/source/algorithms/FlatPlatePaalmanPingsCorrection-v1.rst +++ b/docs/source/algorithms/FlatPlatePaalmanPingsCorrection-v1.rst @@ -68,7 +68,7 @@ Usage Emode='Indirect', Efixed=1.845) - print 'Correction workspaces: %s' % (', '.join(corr.getNames())) + print('Correction workspaces: %s' % (', '.join(corr.getNames()))) Output: diff --git a/docs/source/algorithms/IntegrateByComponent-v1.rst b/docs/source/algorithms/IntegrateByComponent-v1.rst index 0d6a3d0cbea98afd78ae2c13c7d21ebe431852f0..d961ed53eeecc636349676ecb0fdac4272342dfd 100644 --- a/docs/source/algorithms/IntegrateByComponent-v1.rst +++ b/docs/source/algorithms/IntegrateByComponent-v1.rst @@ -35,24 +35,24 @@ Usage ws1=IntegrateByComponent(ws,LevelsUp=1) ws2=IntegrateByComponent(ws,LevelsUp=2) ws0=IntegrateByComponent(ws,LevelsUp=4) - + #Check some values - print "For LevelsUp=1 we found that:" - print " - two pixels in the same tube have the same value ", ws1.dataY(1)[0]==ws1.dataY(100)[0] - print " - two pixels in different tubes have the same value ", ws1.dataY(1)[0]==ws1.dataY(200)[0] - print " - two pixels in different bankss have the same value ", ws1.dataY(1)[0]==ws1.dataY(2000)[0] - - print "For LevelsUp=2 we found that:" - print " - two pixels in the same tube have the same value ", ws2.dataY(1)[0]==ws2.dataY(100)[0] - print " - two pixels in different tubes have the same value ", ws2.dataY(1)[0]==ws2.dataY(200)[0] - print " - two pixels in different bankss have the same value ", ws2.dataY(1)[0]==ws2.dataY(2000)[0] - - print "For LevelsUp=4 we found that:" - print " - two pixels in the same tube have the same value ", ws0.dataY(1)[0]==ws0.dataY(100)[0] - print " - two pixels in different tubes have the same value ", ws0.dataY(1)[0]==ws0.dataY(200)[0] - print " - two pixels in different bankss have the same value ", ws0.dataY(1)[0]==ws0.dataY(2000)[0] - - + print("For LevelsUp=1 we found that:") + print(" - two pixels in the same tube have the same value {}".format(ws1.dataY(1)[0]==ws1.dataY(100)[0])) + print(" - two pixels in different tubes have the same value {}".format(ws1.dataY(1)[0]==ws1.dataY(200)[0])) + print(" - two pixels in different banks have the same value {}".format(ws1.dataY(1)[0]==ws1.dataY(2000)[0])) + + print("For LevelsUp=2 we found that:") + print(" - two pixels in the same tube have the same value {}".format(ws2.dataY(1)[0]==ws2.dataY(100)[0])) + print(" - two pixels in different tubes have the same value {}".format(ws2.dataY(1)[0]==ws2.dataY(200)[0])) + print(" - two pixels in different banks have the same value {}".format(ws2.dataY(1)[0]==ws2.dataY(2000)[0])) + + print("For LevelsUp=4 we found that:") + print(" - two pixels in the same tube have the same value {}".format(ws0.dataY(1)[0]==ws0.dataY(100)[0])) + print(" - two pixels in different tubes have the same value {}".format(ws0.dataY(1)[0]==ws0.dataY(200)[0])) + print(" - two pixels in different banks have the same value {}".format(ws0.dataY(1)[0]==ws0.dataY(2000)[0])) + + .. testcleanup:: IntegrateByComponent DeleteWorkspace('ws') @@ -62,17 +62,17 @@ Output: .. testoutput:: IntegrateByComponent For LevelsUp=1 we found that: - - two pixels in the same tube have the same value True - - two pixels in different tubes have the same value False - - two pixels in different bankss have the same value False + - two pixels in the same tube have the same value True + - two pixels in different tubes have the same value False + - two pixels in different banks have the same value False For LevelsUp=2 we found that: - - two pixels in the same tube have the same value True - - two pixels in different tubes have the same value True - - two pixels in different bankss have the same value False + - two pixels in the same tube have the same value True + - two pixels in different tubes have the same value True + - two pixels in different banks have the same value False For LevelsUp=4 we found that: - - two pixels in the same tube have the same value True - - two pixels in different tubes have the same value True - - two pixels in different bankss have the same value True + - two pixels in the same tube have the same value True + - two pixels in different tubes have the same value True + - two pixels in different banks have the same value True .. categories:: diff --git a/docs/source/algorithms/IntegrateEPP-v1.rst b/docs/source/algorithms/IntegrateEPP-v1.rst index ec821f4b43c482a0d386f6e19dc1bef21a6170c9..fdcbce9792eebddb012875c61286676ebea8d04e 100644 --- a/docs/source/algorithms/IntegrateEPP-v1.rst +++ b/docs/source/algorithms/IntegrateEPP-v1.rst @@ -33,7 +33,7 @@ Usage xs = integrated.readX(0) ys = integrated.readY(0) - print('Integral from {} to {} yields {:.5}'.format(xs[0], xs[1], ys[0])) + print('Integral from {:.6} to {:.6} yields {:.5}'.format(xs[0], xs[1], ys[0])) Output: diff --git a/docs/source/algorithms/IntegrateEllipsoids-v1.rst b/docs/source/algorithms/IntegrateEllipsoids-v1.rst index 056941241ffbd00ce3a6f7f320fac5e34d60a275..df15eda12f8359d81daa1357c9d38b3b4cfea94e 100644 --- a/docs/source/algorithms/IntegrateEllipsoids-v1.rst +++ b/docs/source/algorithms/IntegrateEllipsoids-v1.rst @@ -218,72 +218,72 @@ Usage **Example - IntegrateEllipsoids:** -The code itself works but disabled from doc tests as takes too long to complete. User should provide its own -event nexus file instead of **TOPAZ_3132_event.nxs** used within this example. The original **TOPAZ_3132_event.nxs** +User should provide their own event nexus file instead of **TOPAZ_3132_event.nxs** used within this example. The original **TOPAZ_3132_event.nxs** file is availible in `Mantid system tests repository <https://github.com/mantidproject/systemtests/tree/master/Data/TOPAZ_3132_event.nxs>`_. +.. .. testcode:: exIntegrateEllipsoids +.. The code itself works but disabled from doc tests as takes too long to complete. + .. code-block:: python :linenos: - #.. testcode:: exIntegrateEllipsoids def print_tableWS(pTWS,nRows): ''' Method to print part of the table workspace ''' - tab_names=pTWS.keys(); - + tab_names=pTWS.keys() + row = "" for name in tab_names: if len(name)>8: - name= name[0:8]; - print "| {0:8} ".format(name), - print "|\n", + name= name[:8] + row += "| {:8} ".format(name) + print(row + "|") - for i in xrange(0,nRows): + for i in range(nRows): + row = "" for name in tab_names: col = pTWS.column(name); data2pr=col[i] if type(data2pr) is float: - print "| {0:8.3f} ".format(data2pr), + row += "| {:8.1f} ".format(data2pr) else: - print "| {0:8} ".format(data2pr), - print "|\n", - - + row += "| {:8} ".format(str(data2pr)) + print(row + "|") + # load test workspace Load(Filename=r'TOPAZ_3132_event.nxs',OutputWorkspace='TOPAZ_3132_event',LoadMonitors='1') - + # build peak workspace necessary for IntegrateEllipsoids algorithm to work ConvertToMD(InputWorkspace='TOPAZ_3132_event',QDimensions='Q3D',dEAnalysisMode='Elastic',Q3DFrames='Q_sample',LorentzCorrection='1',OutputWorkspace='TOPAZ_3132_md',\ MinValues='-25,-25,-25',MaxValues='25,25,25',SplitInto='2',SplitThreshold='50',MaxRecursionDepth='13',MinRecursionDepth='7') FindPeaksMD(InputWorkspace='TOPAZ_3132_md',PeakDistanceThreshold='0.3768',MaxPeaks='50',DensityThresholdFactor='100',OutputWorkspace='TOPAZ_3132_peaks') FindUBUsingFFT(PeaksWorkspace='TOPAZ_3132_peaks',MinD='3',MaxD='15',Tolerance='0.12') IndexPeaks(PeaksWorkspace='TOPAZ_3132_peaks',Tolerance='0.12') - + # integrate Ellipsoids result=IntegrateEllipsoids(InputWorkspace='TOPAZ_3132_event',PeaksWorkspace='TOPAZ_3132_peaks',\ RegionRadius='0.25',PeakSize='0.2',BackgroundInnerSize='0.2',BackgroundOuterSize='0.25',OutputWorkspace='TOPAZ_3132_peaks') - + # print 10 rows of resulting table workspace print_tableWS(result,10) **Output:** +.. .. testoutput:: exIntegrateEllipsoids + .. code-block:: python :linenos: - #.. testoutput:: exIntegrateEllipsoids - - | RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | - | 3132 | 1124984 | -2.000 | -1.000 | 2.000 | 3.104 | 8.491 | 14482.289 | 2.025 | 119890.000 | 372.000 | 1668.000 | bank17 | 120.000 | 42.000 | [1.57771,1.21779,2.37854] | [2.99396,0.815958,0.00317344] | - | 3132 | 1156753 | -3.000 | -2.000 | 3.000 | 2.085 | 18.822 | 9725.739 | 1.298 | 148721.000 | 391.069 | 1060.000 | bank17 | 145.000 | 166.000 | [2.48964,1.45725,3.88666] | [4.52618,1.71025,0.129461] | - | 3132 | 1141777 | -4.000 | -2.000 | 3.000 | 1.707 | 28.090 | 7963.171 | 1.050 | 8703.000 | 105.570 | 96.000 | bank17 | 17.000 | 108.000 | [2.60836,2.31423,4.86391] | [5.69122,1.79492,-0.452799] | - | 3132 | 1125241 | -4.000 | -2.000 | 4.000 | 1.554 | 33.860 | 7252.155 | 1.014 | 19715.000 | 145.805 | 83.000 | bank17 | 121.000 | 43.000 | [3.15504,2.42573,4.75121] | [5.97829,1.63473,0.0118744] | - | 3132 | 1170598 | -4.000 | -3.000 | 4.000 | 1.548 | 34.124 | 7224.587 | 0.950 | 15860.000 | 131.111 | 73.000 | bank17 | 166.000 | 220.000 | [3.43363,1.70178,5.39301] | [6.07726,2.59962,0.281759] | - | 3132 | 1214951 | -2.000 | -1.000 | 4.000 | 1.894 | 22.795 | 8839.546 | 1.677 | 121613.000 | 352.155 | 719.000 | bank18 | 231.000 | 137.000 | [2.73683,1.43808,2.11574] | [3.5786,0.470838,1.00329] | - | 3132 | 1207827 | -3.000 | -1.000 | 4.000 | 1.713 | 27.890 | 7991.697 | 1.319 | 64063.000 | 257.175 | 447.000 | bank18 | 19.000 | 110.000 | [2.80324,2.29519,3.09134] | [4.71517,0.554412,0.37714] | - | 3132 | 1232949 | -4.000 | -2.000 | 6.000 | 1.239 | 53.277 | 5782.138 | 0.934 | 18185.000 | 139.072 | 45.000 | bank18 | 53.000 | 208.000 | [4.29033,2.63319,4.46168] | [6.52658,1.27985,1.00646] | - | 3132 | 1189484 | -4.000 | -1.000 | 6.000 | 1.136 | 63.418 | 5299.275 | 0.964 | 13470.000 | 120.607 | 31.000 | bank18 | 108.000 | 38.000 | [4.02414,3.39659,3.83664] | [6.4679,0.298896,0.726133] | - | 3132 | 1218337 | -5.000 | -2.000 | 7.000 | 1.012 | 79.807 | 4724.051 | 0.773 | 7405.000 | 88.210 | 15.000 | bank18 | 33.000 | 151.000 | [4.96622,3.61607,5.32554] | [7.99244,1.19363,0.892655] | - + | RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | + | 3132 | 1124984 | -2.0 | -1.0 | 2.0 | 3.1 | 8.5 | 14482.3 | 2.0 | 120486.0 | 375.8 | 1668.0 | bank17 | 120.0 | 42.0 | [1.57771,1.21779,2.37854] | [2.99396,0.815958,0.00317344] | + | 3132 | 1156753 | -3.0 | -2.0 | 3.0 | 2.1 | 18.8 | 9725.7 | 1.3 | 149543.0 | 393.0 | 1060.0 | bank17 | 145.0 | 166.0 | [2.48964,1.45725,3.88666] | [4.52618,1.71025,0.129461] | + | 3132 | 1141777 | -4.0 | -2.0 | 3.0 | 1.7 | 28.1 | 7963.2 | 1.0 | 8744.0 | 106.3 | 96.0 | bank17 | 17.0 | 108.0 | [2.60836,2.31423,4.86391] | [5.69122,1.79492,-0.452799] | + | 3132 | 1125241 | -4.0 | -2.0 | 4.0 | 1.6 | 33.9 | 7252.2 | 1.0 | 19740.0 | 146.2 | 83.0 | bank17 | 121.0 | 43.0 | [3.15504,2.42573,4.75121] | [5.97829,1.63473,0.0118744] | + | 3132 | 1170598 | -4.0 | -3.0 | 4.0 | 1.5 | 34.1 | 7224.6 | 0.9 | 15914.0 | 131.4 | 73.0 | bank17 | 166.0 | 220.0 | [3.43363,1.70178,5.39301] | [6.07726,2.59962,0.281759] | + | 3132 | 1214951 | -2.0 | -1.0 | 4.0 | 1.9 | 22.8 | 8839.5 | 1.7 | 121852.0 | 352.9 | 719.0 | bank18 | 231.0 | 137.0 | [2.73683,1.43808,2.11574] | [3.5786,0.470838,1.00329] | + | 3132 | 1207827 | -3.0 | -1.0 | 4.0 | 1.7 | 27.9 | 7991.7 | 1.3 | 64593.0 | 257.7 | 447.0 | bank18 | 19.0 | 110.0 | [2.80324,2.29519,3.09134] | [4.71517,0.554412,0.37714] | + | 3132 | 1232949 | -4.0 | -2.0 | 6.0 | 1.2 | 53.3 | 5782.1 | 0.9 | 18247.0 | 139.3 | 45.0 | bank18 | 53.0 | 208.0 | [4.29033,2.63319,4.46168] | [6.52658,1.27985,1.00646] | + | 3132 | 1189484 | -4.0 | -1.0 | 6.0 | 1.1 | 63.4 | 5299.3 | 1.0 | 13512.0 | 120.7 | 31.0 | bank18 | 108.0 | 38.0 | [4.02414,3.39659,3.83664] | [6.4679,0.298896,0.726133] | + | 3132 | 1218337 | -5.0 | -2.0 | 7.0 | 1.0 | 79.8 | 4724.1 | 0.8 | 7411.0 | 88.3 | 15.0 | bank18 | 33.0 | 151.0 | [4.96622,3.61607,5.32554] | [7.99244,1.19363,0.892655] | .. categories:: diff --git a/docs/source/algorithms/IntegrateEllipsoidsTwoStep-v1.rst b/docs/source/algorithms/IntegrateEllipsoidsTwoStep-v1.rst index 097c34db94cbe1efd7cb244523e4e3c5fa01dd3a..45b4b26dde8b2dc05eb7315b00f80eac20b6e687 100644 --- a/docs/source/algorithms/IntegrateEllipsoidsTwoStep-v1.rst +++ b/docs/source/algorithms/IntegrateEllipsoidsTwoStep-v1.rst @@ -257,38 +257,40 @@ Usage **Example - IntegrateEllipsoids:** -The code itself works but disabled from doc tests as takes too long to complete. -User should provide its own event nexus file instead of **TOPAZ_3132_event.nxs** + +User should provide their own event nexus file instead of **TOPAZ_3132_event.nxs** used within this example. The original **TOPAZ_3132_event.nxs** file is availible in `Mantid system tests repository <https://github.com/mantidproject/systemtests/tree/master/Data/TOPAZ_3132_event.nxs>`_. +.. .. testcode:: exIntegrateEllipsoidsTwoStep +.. The code itself works but disabled from doc tests as they take too long to complete. + .. code-block:: python :linenos: - #.. testcode:: exIntegrateEllipsoids - def print_tableWS(pTWS,nRows): ''' Method to print part of the table workspace ''' - tab_names=pTWS.keys(); - + tab_names=pTWS.keys() + row = "" for name in tab_names: if len(name)>8: - name= name[0:8]; - print "| {0:8} ".format(name), - print "|\n", + name= name[:8] + row += "| {:8} ".format(name) + print(row + "|") - for i in xrange(0,nRows): + for i in range(nRows): + row = "" for name in tab_names: col = pTWS.column(name); data2pr=col[i] if type(data2pr) is float: - print "| {0:8.3f} ".format(data2pr), + row += "| {:8.1f} ".format(data2pr) else: - print "| {0:8} ".format(data2pr), - print "|\n", - - + row += "| {:8} ".format(str(data2pr)) + print(row + "|") + + # load test workspace Load(Filename=r'TOPAZ_3132_event.nxs',OutputWorkspace='TOPAZ_3132_event',LoadMonitors='1') @@ -308,23 +310,22 @@ availible in `Mantid system tests repository **Output:** +.. .. testoutput:: exIntegrateEllipsoidsTwoStep + .. code-block:: python :linenos: - #.. testoutput:: exIntegrateEllipsoids - -| RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | -| 3132 | 1124984 | 2.000 | 1.000 | 2.000 | 3.104 | 8.491 | 14482.289 | 2.025 | 120486.000 | 375.814 | 1668.000 | bank17 | 120.000 | 42.000 | [1.57771,1.21779,2.37854] | [2.99396,0.815958,0.00317344] | -| 3132 | 1156753 | 3.000 | 2.000 | 3.000 | 2.085 | 18.822 | 9725.739 | 1.298 | 149543.000 | 393.038 | 1060.000 | bank17 | 145.000 | 166.000 | [2.48964,1.45725,3.88666] | [4.52618,1.71025,0.129461] | -| 3132 | 1141777 | 4.000 | 2.000 | 3.000 | 1.707 | 28.090 | 7963.171 | 1.050 | 8744.000 | 106.311 | 96.000 | bank17 | 17.000 | 108.000 | [2.60836,2.31423,4.86391] | [5.69122,1.79492,-0.452799] | -| 3132 | 1125241 | 4.000 | 2.000 | 4.000 | 1.554 | 33.860 | 7252.155 | 1.014 | 19740.000 | 146.164 | 83.000 | bank17 | 121.000 | 43.000 | [3.15504,2.42573,4.75121] | [5.97829,1.63473,0.0118744] | -| 3132 | 1170598 | 4.000 | 3.000 | 4.000 | 1.548 | 34.124 | 7224.587 | 0.950 | 15914.000 | 131.385 | 73.000 | bank17 | 166.000 | 220.000 | [3.43363,1.70178,5.39301] | [6.07726,2.59962,0.281759] | -| 3132 | 1214951 | 2.000 | 1.000 | 4.000 | 1.894 | 22.795 | 8839.546 | 1.677 | 121852.000 | 352.919 | 719.000 | bank18 | 231.000 | 137.000 | [2.73683,1.43808,2.11574] | [3.5786,0.470838,1.00329] | -| 3132 | 1207827 | 3.000 | 1.000 | 4.000 | 1.713 | 27.890 | 7991.697 | 1.319 | 64593.000 | 257.707 | 447.000 | bank18 | 19.000 | 110.000 | [2.80324,2.29519,3.09134] | [4.71517,0.554412,0.37714] | -| 3132 | 1232949 | 4.000 | 2.000 | 6.000 | 1.239 | 53.277 | 5782.138 | 0.934 | 18247.000 | 139.302 | 45.000 | bank18 | 53.000 | 208.000 | [4.29033,2.63319,4.46168] | [6.52658,1.27985,1.00646] | -| 3132 | 1189484 | 4.000 | 1.000 | 6.000 | 1.136 | 63.418 | 5299.275 | 0.964 | 13512.000 | 120.748 | 31.000 | bank18 | 108.000 | 38.000 | [4.02414,3.39659,3.83664] | [6.4679,0.298896,0.726133] | -| 3132 | 1218337 | 5.000 | 2.000 | 7.000 | 1.012 | 79.807 | 4724.051 | 0.773 | 7411.000 | 88.289 | 15.000 | bank18 | 33.000 | 151.000 | [4.96622,3.61607,5.32554] | [7.99244,1.19363,0.892655] | - + | RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | + | 3132 | 1124984 | -2.0 | -1.0 | 2.0 | 3.1 | 8.5 | 14482.3 | 2.0 | 120486.0 | 375.8 | 1668.0 | bank17 | 120.0 | 42.0 | [1.57771,1.21779,2.37854] | [2.99396,0.815958,0.00317344] | + | 3132 | 1156753 | -3.0 | -2.0 | 3.0 | 2.1 | 18.8 | 9725.7 | 1.3 | 149543.0 | 393.0 | 1060.0 | bank17 | 145.0 | 166.0 | [2.48964,1.45725,3.88666] | [4.52618,1.71025,0.129461] | + | 3132 | 1141777 | -4.0 | -2.0 | 3.0 | 1.7 | 28.1 | 7963.2 | 1.0 | 8744.0 | 106.3 | 96.0 | bank17 | 17.0 | 108.0 | [2.60836,2.31423,4.86391] | [5.69122,1.79492,-0.452799] | + | 3132 | 1125241 | -4.0 | -2.0 | 4.0 | 1.6 | 33.9 | 7252.2 | 1.0 | 19740.0 | 146.2 | 83.0 | bank17 | 121.0 | 43.0 | [3.15504,2.42573,4.75121] | [5.97829,1.63473,0.0118744] | + | 3132 | 1170598 | -4.0 | -3.0 | 4.0 | 1.5 | 34.1 | 7224.6 | 0.9 | 15914.0 | 131.4 | 73.0 | bank17 | 166.0 | 220.0 | [3.43363,1.70178,5.39301] | [6.07726,2.59962,0.281759] | + | 3132 | 1214951 | -2.0 | -1.0 | 4.0 | 1.9 | 22.8 | 8839.5 | 1.7 | 121852.0 | 352.9 | 719.0 | bank18 | 231.0 | 137.0 | [2.73683,1.43808,2.11574] | [3.5786,0.470838,1.00329] | + | 3132 | 1207827 | -3.0 | -1.0 | 4.0 | 1.7 | 27.9 | 7991.7 | 1.3 | 64593.0 | 257.7 | 447.0 | bank18 | 19.0 | 110.0 | [2.80324,2.29519,3.09134] | [4.71517,0.554412,0.37714] | + | 3132 | 1232949 | -4.0 | -2.0 | 6.0 | 1.2 | 53.3 | 5782.1 | 0.9 | 18247.0 | 139.3 | 45.0 | bank18 | 53.0 | 208.0 | [4.29033,2.63319,4.46168] | [6.52658,1.27985,1.00646] | + | 3132 | 1189484 | -4.0 | -1.0 | 6.0 | 1.1 | 63.4 | 5299.3 | 1.0 | 13512.0 | 120.7 | 31.0 | bank18 | 108.0 | 38.0 | [4.02414,3.39659,3.83664] | [6.4679,0.298896,0.726133] | + | 3132 | 1218337 | -5.0 | -2.0 | 7.0 | 1.0 | 79.8 | 4724.1 | 0.8 | 7411.0 | 88.3 | 15.0 | bank18 | 33.0 | 151.0 | [4.96622,3.61607,5.32554] | [7.99244,1.19363,0.892655] | .. categories:: diff --git a/docs/source/algorithms/IntegrateFlux-v1.rst b/docs/source/algorithms/IntegrateFlux-v1.rst index 9266edd18e894d8df96512db7766b000fc4c6600..04161a2ddd77d2ee7622a0abc4aa61d7e49569b8 100644 --- a/docs/source/algorithms/IntegrateFlux-v1.rst +++ b/docs/source/algorithms/IntegrateFlux-v1.rst @@ -29,8 +29,8 @@ Usage wsOut = IntegrateFlux( ws ) # Print the result - print "The input workspace has %i spectra" % ws.getNumberHistograms() - print "The output workspace has %i spectra" % wsOut.getNumberHistograms() + print("The input workspace has {} spectra".format(ws.getNumberHistograms())) + print("The output workspace has {} spectra".format(wsOut.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst b/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst index edf8a87057768aa354ce2774b1b02251437d9ee3..0f27858c11c22d17176c407784559a28771e0f04 100644 --- a/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst +++ b/docs/source/algorithms/IntegrateMDHistoWorkspace-v1.rst @@ -54,10 +54,10 @@ Usage low_d_cut =IntegrateMDHistoWorkspace(InputWorkspace=high_d_cut, P1Bin=[], P2Bin=[-2,2], P3Bin=[-5,5]) non_integrated_dims = low_d_cut.getNonIntegratedDimensions() - print 'Number of non integrated dimensions after integration are %i' % len(non_integrated_dims) + print('Number of non integrated dimensions after integration are {}'.format(len(non_integrated_dims))) for dim in non_integrated_dims: - print 'Non integrated dimension is %s' % dim.name - print 'Limits are from %0.2f to %0.2f' % (dim.getMinimum(), dim.getMaximum()) + print('Non integrated dimension is {}'.format(dim.name)) + print('Limits are from {:.2f} to {:.2f}'.format(dim.getMinimum(), dim.getMaximum())) Output: @@ -86,14 +86,14 @@ maximum and minimum limits may need to be adjusted to ensure no partial binning low_d_cut=IntegrateMDHistoWorkspace(InputWorkspace=high_d_cut,P1Bin=[-9.48,copy_key,9.01], P2Bin=[-2,2], P3Bin=[-5,5]) dim = high_d_cut.getDimension(0) - print 'Input bin width is %0.2f' % float((dim.getMaximum() - dim.getMinimum())/dim.getNBins()) + print('Input bin width is {:.2f}'.format(float((dim.getMaximum() - dim.getMinimum())/dim.getNBins()))) non_integrated_dims = low_d_cut.getNonIntegratedDimensions() - print 'Number of non integrated dimensions after integration are %i' % len(non_integrated_dims) + print('Number of non integrated dimensions after integration are {}'.format(len(non_integrated_dims))) for dim in non_integrated_dims: - print 'Non integrated dimension is %s' % dim.name - print 'Limits are from %0.2f to %0.2f' % (dim.getMinimum(), dim.getMaximum()) - print 'Output bin width is %0.2f' % float((dim.getMaximum() - dim.getMinimum() )/dim.getNBins()) + print('Non integrated dimension is {}'.format(dim.name)) + print('Limits are from {:.2f} to {:.2f}'.format(dim.getMinimum(), dim.getMaximum())) + print('Output bin width is {:.2f}'.format(float((dim.getMaximum() - dim.getMinimum() )/dim.getNBins()))) Output: diff --git a/docs/source/algorithms/IntegratePeakTimeSlices-v1.rst b/docs/source/algorithms/IntegratePeakTimeSlices-v1.rst index 6d54a0efafc380b13e939586e47dd64ef225baf2..7c95e0d49fd254afc3d78c176f74644e114a0f97 100644 --- a/docs/source/algorithms/IntegratePeakTimeSlices-v1.rst +++ b/docs/source/algorithms/IntegratePeakTimeSlices-v1.rst @@ -59,7 +59,7 @@ Usage # Run the Integration algorithm and print results peak0,int,sig = IntegratePeakTimeSlices(InputWorkspace='TOPAZ_3132_nxs', Peaks='peaks', Intensity=4580.8587719746683, SigmaIntensity=190.21154129339735) - print "Intensity and SigmaIntensity of peak 0 = ",int,sig + print("Intensity and SigmaIntensity of peak 0 = {} {}".format(int, sig)) .. categories:: diff --git a/docs/source/algorithms/IntegratePeaksMD-v2.rst b/docs/source/algorithms/IntegratePeaksMD-v2.rst index 9fa3748a68f470e0a0d7e8cc027158fc3a4439ae..9e159ed56c3bcc660a1742df507526975c2b0ba0 100644 --- a/docs/source/algorithms/IntegratePeaksMD-v2.rst +++ b/docs/source/algorithms/IntegratePeaksMD-v2.rst @@ -183,43 +183,42 @@ Usage **Example - IntegratePeaks:** -The code itself works but disabled from doc tests as takes too long to complete. User should provide its own +User should provide its own event nexus file instead of **TOPAZ_3132_event.nxs** used within this example. The original **TOPAZ_3132_event.nxs** file is availible in `Mantid system tests repository <https://github.com/mantidproject/systemtests/tree/master/Data/TOPAZ_3132_event.nxs>`_. +.. The code itself works but disabled from doc tests as takes too long to complete. +.. .. testcode:: exIntegratePeaksMD .. code-block:: python :linenos: - #.. testcode:: exIntegratePeaksMD - - def print_tableWS(pTWS,nRows): ''' Method to print part of the table workspace ''' - tab_names=pTWS.keys(); - + tab_names=pTWS.keys() + row = "" for name in tab_names: if len(name)>8: - name= name[0:8]; - print "| {0:8} ".format(name), - print "|\n", + name= name[:8] + row += "| {:8} ".format(name) + print(row + "|") - for i in xrange(0,nRows): + for i in range(nRows): + row = "" for name in tab_names: col = pTWS.column(name); data2pr=col[i] if type(data2pr) is float: - print "| {0:8.3f} ".format(data2pr), + row += "| {:8.1f} ".format(data2pr) else: - print "| {0:8} ".format(data2pr), - print "|\n", - + row += "| {:8} ".format(str(data2pr)) + print(row + "|") # Load a SCD data set and find the peaks LoadEventNexus(Filename=r'TOPAZ_3132_event.nxs',OutputWorkspace='TOPAZ_3132_nxs') ConvertToDiffractionMDWorkspace(InputWorkspace='TOPAZ_3132_nxs',OutputWorkspace='TOPAZ_3132_md',LorentzCorrection='1') FindPeaksMD(InputWorkspace='TOPAZ_3132_md',PeakDistanceThreshold='0.15',MaxPeaks='100',OutputWorkspace='peaks') - FindUBUsingFFT(PeaksWorkspace='peaks',MinD='2',MaxD='16') + FindUBUsingFFT(PeaksWorkspace='peaks',MinD='2',MaxD='16') # Perform the peak integration, in-place in the 'peaks' workspace. peaks= IntegratePeaksMD(InputWorkspace='TOPAZ_3132_md', PeaksWorkspace='peaks',\ @@ -231,22 +230,23 @@ file is availible in `Mantid system tests repository <https://github.com/mantidp **Output:** +.. .. testoutput:: exIntegratePeaksMD + .. code-block:: python :linenos: - #.. testoutput:: exIntegratePeaksMD - - | RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | - | 3132 | 1168976 | 0.000 | 0.000 | 0.000 | 1.106 | 66.853 | 5161.495 | 0.664 | 2161.555 | 32.493 | 1042.000 | bank17 | 80.000 | 214.000 | [4.42299,2.80447,7.87903] | [8.7569,3.57474,-0.211883] | - | 3132 | 1156499 | 0.000 | 0.000 | 0.000 | 2.081 | 18.887 | 9708.954 | 1.297 | 5137.547 | 13.432 | 828.000 | bank17 | 147.000 | 165.000 | [2.49809,1.45732,3.88559] | [4.53003,1.70942,0.137013] | - | 3132 | 1156756 | 0.000 | 0.000 | 0.000 | 1.040 | 75.677 | 4850.409 | 0.648 | 1597.017 | 30.643 | 577.000 | bank17 | 148.000 | 166.000 | [5.00569,2.90696,7.77943] | [9.06543,3.43008,0.281929] | - | 3132 | 1141779 | 0.000 | 0.000 | 0.000 | 1.704 | 28.167 | 7952.321 | 1.049 | 648.434 | 7.481 | 379.000 | bank17 | 19.000 | 108.000 | [2.61862,2.31234,4.86545] | [5.69642,1.79732,-0.443944] | - | 3132 | 1124982 | 0.000 | 0.000 | 0.000 | 1.555 | 33.819 | 7256.594 | 1.014 | 1990.427 | 14.457 | 330.000 | bank17 | 118.000 | 42.000 | [3.14235,2.43685,4.75299] | [5.97935,1.62817,-0.00373607] | - | 3132 | 1170597 | 0.000 | 0.000 | 0.000 | 1.551 | 34.005 | 7237.138 | 0.951 | 1825.812 | 14.812 | 327.000 | bank17 | 165.000 | 220.000 | [3.42477,1.70221,5.38678] | [6.06909,2.59493,0.276379] | - | 3132 | 1124982 | 0.000 | 0.000 | 0.000 | 3.111 | 8.454 | 14514.017 | 2.028 | 749.742 | 2.242 | 268.000 | bank17 | 118.000 | 42.000 | [1.57108,1.21836,2.37636] | [2.9895,0.814038,-0.00186793] | - | 3132 | 1232181 | 0.000 | 0.000 | 0.000 | 1.238 | 53.388 | 5776.071 | 0.934 | 3460.775 | 25.974 | 1229.000 | bank18 | 53.000 | 205.000 | [4.28486,2.64933,4.45466] | [6.52915,1.2635,0.998372] | - | 3132 | 1200023 | 0.000 | 0.000 | 0.000 | 1.433 | 39.816 | 6687.166 | 1.232 | 963.069 | 9.208 | 990.000 | bank18 | 151.000 | 79.000 | [3.37972,2.40572,2.9675] | [5.01065,0.386939,0.871633] | - | 3132 | 1218594 | 0.000 | 0.000 | 0.000 | 1.016 | 79.240 | 4740.921 | 0.776 | 2999.159 | 35.467 | 901.000 | bank18 | 34.000 | 152.000 | [4.9551,3.59367,5.30453] | [7.96049,1.19466,0.899379] | + + | RunNumbe | DetID | h | k | l | Waveleng | Energy | TOF | DSpacing | Intens | SigInt | BinCount | BankName | Row | Col | QLab | QSample | + | 3132 | 1168209 | 0.0 | 0.0 | 0.0 | 1.1 | 66.9 | 5158.0 | 0.7 | 2160.9 | 32.3 | 1326.0 | bank17 | 81.0 | 211.0 | [4.42961,2.81707,7.86314] | [8.75838,3.55459,-0.205083] | + | 3132 | 1124983 | 0.0 | 0.0 | 0.0 | 1.6 | 33.9 | 7250.6 | 1.0 | 1990.0 | 14.4 | 1060.0 | bank17 | 119.0 | 42.0 | [3.14813,2.43563,4.75389] | [5.9822,1.62965,0.00130101] | + | 3132 | 1141521 | 0.0 | 0.0 | 0.0 | 1.7 | 28.1 | 7959.1 | 1.0 | 644.6 | 7.3 | 1034.0 | bank17 | 17.0 | 107.0 | [2.60893,2.31831,4.86248] | [5.69311,1.79103,-0.453311] | + | 3132 | 1125238 | 0.0 | 0.0 | 0.0 | 3.1 | 8.4 | 14518.9 | 2.0 | 750.5 | 2.2 | 880.0 | bank17 | 118.0 | 43.0 | [1.57116,1.21649,2.37775] | [2.98926,0.816337,-0.00161709] | + | 3132 | 1170852 | 0.0 | 0.0 | 0.0 | 1.6 | 34.0 | 7235.3 | 1.0 | 1826.4 | 14.7 | 762.0 | bank17 | 164.0 | 221.0 | [3.4229,1.70246,5.39532] | [6.0734,2.6008,0.271523] | + | 3132 | 1156497 | 0.0 | 0.0 | 0.0 | 2.1 | 18.9 | 9718.2 | 1.3 | 5137.6 | 13.4 | 518.0 | bank17 | 145.0 | 165.0 | [2.49117,1.46093,3.88649] | [4.5291,1.70753,0.129446] | + | 3132 | 1207828 | 0.0 | 0.0 | 0.0 | 1.7 | 27.9 | 7989.1 | 1.3 | 3233.6 | 12.7 | 1024.0 | bank18 | 20.0 | 110.0 | [2.80538,2.29342,3.08833] | [4.71342,0.553533,0.380727] | + | 3132 | 1218593 | 0.0 | 0.0 | 0.0 | 1.0 | 79.6 | 4729.3 | 0.8 | 3018.1 | 35.4 | 756.0 | bank18 | 33.0 | 152.0 | [4.96533,3.60693,5.32436] | [7.98578,1.19927,0.895763] | + | 3132 | 1232694 | 0.0 | 0.0 | 0.0 | 1.2 | 53.4 | 5772.9 | 0.9 | 3464.5 | 25.9 | 631.0 | bank18 | 54.0 | 207.0 | [4.29539,2.63813,4.45945] | [6.53086,1.27477,1.00974] | + | 3132 | 1200023 | 0.0 | 0.0 | 0.0 | 0.7 | 159.1 | 3345.1 | 0.6 | 3796.1 | 71.1 | 509.0 | bank18 | 151.0 | 79.0 | [6.75629,4.8092,5.93224] | [10.0166,0.773518,1.74245] | .. categories:: diff --git a/docs/source/algorithms/IntegratePeaksMDHKL-v1.rst b/docs/source/algorithms/IntegratePeaksMDHKL-v1.rst index c84013696263215a8bd37284d75df8ad84791b24..4d72ed12cd13e9cfcd075cfe4232b4e1dba9155c 100644 --- a/docs/source/algorithms/IntegratePeaksMDHKL-v1.rst +++ b/docs/source/algorithms/IntegratePeaksMDHKL-v1.rst @@ -80,13 +80,13 @@ Usage pws =IntegratePeaksMDHKL(InputWorkspace=mdws,PeaksWorkspace=pws,DeltaHKL=1.5,GridPoints=21) for i in range(3): p = pws.getPeak(i) - print p.getIntensity(),p.getSigmaIntensity() + print('{:.7f} {:.9f}'.format(p.getIntensity(),p.getSigmaIntensity())) #Test with MDHistoWorkspace mdws = BinMD(InputWorkspace=mdws,AlignedDim0="[H,0,0],-10,10,101",AlignedDim1="[0,K,0],-10,10,101",AlignedDim2="[0,0,L],-10,10,101") pws =IntegratePeaksMDHKL(InputWorkspace=mdws,PeaksWorkspace=pws,DeltaHKL=1.5,GridPoints=21) for i in range(3): p = pws.getPeak(i) - print p.getIntensity(),p.getSigmaIntensity() + print('{:.7f} {:.9f}'.format(p.getIntensity(),p.getSigmaIntensity())) Output: diff --git a/docs/source/algorithms/InterpolatingRebin-v1.rst b/docs/source/algorithms/InterpolatingRebin-v1.rst index 7eca9e7ed712bba32e85c69a815bb5f4273509e8..6749b30292b8033bd4e5faee80b62f16731f308b 100644 --- a/docs/source/algorithms/InterpolatingRebin-v1.rst +++ b/docs/source/algorithms/InterpolatingRebin-v1.rst @@ -60,8 +60,8 @@ Usage # rebin from min to max with size bin = 0.5 ws = InterpolatingRebin(ws, 0.5) - print "First 5 rebinned X values are:", ws.readX(0)[0:5] - print "First 5 rebinned Y values are:", ws.readY(0)[0:5] + print("First 5 rebinned X values are: {}".format(ws.readX(0)[0:5])) + print("First 5 rebinned Y values are: {}".format(ws.readY(0)[0:5])) Output: diff --git a/docs/source/algorithms/InvertMDDim-v1.rst b/docs/source/algorithms/InvertMDDim-v1.rst index ffeadd6f34720858d9b86f64069ad2d933e90d83..eeb1dc83f562cc364d722b526a881032100e5c07 100644 --- a/docs/source/algorithms/InvertMDDim-v1.rst +++ b/docs/source/algorithms/InvertMDDim-v1.rst @@ -23,11 +23,11 @@ Usage def outputMDDimensions(ws): num_dims = ws.getNumDims() - print "Name Bins Min Max" + print("Name Bins Min Max") for dim_index in range(num_dims): dim = ws.getDimension(dim_index) - print "%s %i %.2f %.2f" % (dim.name, - dim.getNBins(), dim.getMinimum(), dim.getMaximum()) + print("{} {} {:.2f} {:.2f}".format( + dim.name, dim.getNBins(), dim.getMinimum(), dim.getMaximum())) #create a test MD event workspace mdew = CreateMDWorkspace(Dimensions=3, Extents=[-1,1,-5,5,-9,10], @@ -39,12 +39,12 @@ Usage AlignedDim1='B,-5,5,5', AlignedDim2='C,-9,10,9') - print "The original workspace" + print("The original workspace") outputMDDimensions(wsHisto) wsInverted = InvertMDDim(wsHisto) - print "\nInvertMDDim reverses the order of the dimensions" + print("\nInvertMDDim reverses the order of the dimensions") outputMDDimensions(wsInverted) .. testoutput:: InvertMDExample diff --git a/docs/source/algorithms/InvertMask-v1.rst b/docs/source/algorithms/InvertMask-v1.rst index cfee688e528af53035c69502d33e1bf565c0f3c1..15441ddfb17d42d5cb83001dd66387941cc16a7b 100644 --- a/docs/source/algorithms/InvertMask-v1.rst +++ b/docs/source/algorithms/InvertMask-v1.rst @@ -32,7 +32,7 @@ Usage # Check source mask workspace nummasked = 0 - for i in xrange(maskws.getNumberHistograms()): + for i in range(maskws.getNumberHistograms()): if maskws.readY(i)[0] > 0.5: nummasked += 1 @@ -41,14 +41,14 @@ Usage # Check target mask workspace nummasked2 = 0 - for i in xrange(invmaskws.getNumberHistograms()): + for i in range(invmaskws.getNumberHistograms()): if invmaskws.readY(i)[0] > 0.5: nummasked2 += 1 # Print out - print "Number of histogram: ", maskws.getNumberHistograms() - print "Source Mask workspace # Detectors masked = ", nummasked - print "Source Mask workspace # Detectors masked = ", nummasked2 + print("Number of histogram: {}".format(maskws.getNumberHistograms())) + print("Source Mask workspace # Detectors masked = {}".format(nummasked)) + print("Source Mask workspace # Detectors masked = {}".format(nummasked2)) Output: diff --git a/docs/source/algorithms/LineProfile-v1.rst b/docs/source/algorithms/LineProfile-v1.rst index 963da14b0f8ec83551dd86e80e650d7f3072f672..7e6b73a9aca1ad2ccff13147ba3c6b6b319feb92 100644 --- a/docs/source/algorithms/LineProfile-v1.rst +++ b/docs/source/algorithms/LineProfile-v1.rst @@ -144,17 +144,17 @@ Output: sumCutWS = LineProfile(wsInTheta, centre, width, Mode='Sum') # When no NaNs are present both modes give the same result. - iElastic = sumCutWS.blocksize() / 2 + iElastic = sumCutWS.blocksize() // 2 y = sumCutWS.readY(0)[iElastic] e = sumCutWS.readE(0)[iElastic] - print('Sum profile at elastic peak: {} +/- {}'.format(y, e)) + print('Sum profile at elastic peak: {:.8f} +/- {:.10f}'.format(y, e)) # The weighting is apparent when the profile crosses some # special values. - iEdge = sumCutWS.blocksize() / 6 + iEdge = sumCutWS.blocksize() // 6 y = sumCutWS.readY(0)[iEdge] e = sumCutWS.readE(0)[iEdge] - print('Sum profile near NaNs: {} +/- {}'.format(y, e)) + print('Sum profile near NaNs: {:.11f} +/- {:.11f}'.format(y, e)) .. testoutput:: SumMode diff --git a/docs/source/algorithms/Load-v1.rst b/docs/source/algorithms/Load-v1.rst index fea562a196d1eaf13689cc0d6c2c199b04267018..02ca814359891da88cf0cfa6ab549c8a83671d64 100644 --- a/docs/source/algorithms/Load-v1.rst +++ b/docs/source/algorithms/Load-v1.rst @@ -65,7 +65,7 @@ Usage # Load ISIS LOQ histogram dataset ws = Load('LOQ49886.nxs') - print "The 1st x-value of the first spectrum is: " + str(ws.readX(0)[0]) + print("The 1st x-value of the first spectrum is: {}".format(ws.readX(0)[0])) Output: @@ -81,7 +81,7 @@ Output: # Load SNS HYS event dataset ws = Load('HYS_11092_event.nxs') - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: @@ -97,7 +97,7 @@ Output: # Load ISIS multiperiod muon MUSR dataset ws = Load('MUSR00015189.nxs') - print "The number of periods (entries) is: " + str(ws[0].getNumberOfEntries()) + print("The number of periods (entries) is: {}".format(ws[0].getNumberOfEntries())) Output: @@ -113,7 +113,7 @@ Output: # Load Mantid processed GEM data file ws = Load('focussed.nxs') - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadAscii-v2.rst b/docs/source/algorithms/LoadAscii-v2.rst index 2f851cefad9d7a37c7da47013946639291d70c02..7060d3037ee685d90e7ea1bee8d866eac8ffe85f 100644 --- a/docs/source/algorithms/LoadAscii-v2.rst +++ b/docs/source/algorithms/LoadAscii-v2.rst @@ -67,7 +67,7 @@ Usage #Load it again - Load would work just as well as LoadAscii wsOutput = LoadAscii(savefile,Unit="Label") - print CompareWorkspaces(ws1,wsOutput)[0] + print(CompareWorkspaces(ws1,wsOutput)[0]) #clean up the file I saved os.remove(savefile) diff --git a/docs/source/algorithms/LoadBBY-v1.rst b/docs/source/algorithms/LoadBBY-v1.rst index ab81113c1339fe0c77221366809ac92caad09d54..09d00219fd584d34075b6446fec96d185d76f8a0 100644 --- a/docs/source/algorithms/LoadBBY-v1.rst +++ b/docs/source/algorithms/LoadBBY-v1.rst @@ -26,7 +26,7 @@ Usage ws = LoadBBY('BBY0000014.tar'); - print "Number of spectra:", ws.getNumberHistograms() + print("Number of spectra: {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadCIF-v1.rst b/docs/source/algorithms/LoadCIF-v1.rst index 765ad8aa65bbc0a44d5b2b17ce9f861995dfc258..13c7a125836fe471715ed5833506361c14e3b480 100644 --- a/docs/source/algorithms/LoadCIF-v1.rst +++ b/docs/source/algorithms/LoadCIF-v1.rst @@ -73,7 +73,7 @@ The following script loads a CIF-file and prints the space group of the crystal # Get the space group from the crystal structure that was loaded crystal_structure = sample_ws.sample().getCrystalStructure() - print 'Space group:', crystal_structure.getSpaceGroup().getHMSymbol() + print('Space group: {}'.format(crystal_structure.getSpaceGroup().getHMSymbol())) The output is: diff --git a/docs/source/algorithms/LoadCalFile-v1.rst b/docs/source/algorithms/LoadCalFile-v1.rst index 06edd070ca0e8742f8f56daf1b93dde2ada069cd..66e8c0a0fad29d143fe48114afff5ba62cec1167 100644 --- a/docs/source/algorithms/LoadCalFile-v1.rst +++ b/docs/source/algorithms/LoadCalFile-v1.rst @@ -33,11 +33,11 @@ create the necessary workspaces. # WorkspaceName parameter is required inspite of docs not saying so. ws = LoadCalFile(InstrumentName="GEM", CalFilename="offsets_2006_cycle064.cal", WorkspaceName="ws") - print "Total number of workspaces =", len(ws) - print "Workspace 1 type =", ws[0].id() - print "Workspace 2 type =", ws[1].id() - print "Workspace 3 type =", ws[2].id() - print "Workspace 4 type =", ws[3].id() + print("Total number of workspaces = {}".format(len(ws))) + print("Workspace 1 type = {}".format(ws[0].id())) + print("Workspace 2 type = {}".format(ws[1].id())) + print("Workspace 3 type = {}".format(ws[2].id())) + print("Workspace 4 type = {}".format(ws[3].id())) Output: diff --git a/docs/source/algorithms/LoadCanSAS1D-v1.rst b/docs/source/algorithms/LoadCanSAS1D-v1.rst index 10f1666845005f2d0e502c2c479f1296fc8e3c20..67c40d640db338f87a223f57ffd4bab200b581f1 100644 --- a/docs/source/algorithms/LoadCanSAS1D-v1.rst +++ b/docs/source/algorithms/LoadCanSAS1D-v1.rst @@ -40,7 +40,7 @@ Usage SaveCanSAS1D(out_ws, file_path, Version=1) in_ws = LoadCanSAS1D(file_path, Version=1) - print "Contents of the file = " + str(in_ws.readY(0)) + "." + print("Contents of the file = {}.".format(in_ws.readY(0))) .. testcleanup:: ExSimpleSavingRoundtrip diff --git a/docs/source/algorithms/LoadCanSAS1D-v2.rst b/docs/source/algorithms/LoadCanSAS1D-v2.rst index 2dfaee2e69e62d1be0c00de597c4608db21b8067..70e703c0341f1da497db8359bebed3d484083ebd 100644 --- a/docs/source/algorithms/LoadCanSAS1D-v2.rst +++ b/docs/source/algorithms/LoadCanSAS1D-v2.rst @@ -39,7 +39,7 @@ Usage SaveCanSAS1D(out_ws, file_path) in_ws = LoadCanSAS1D(file_path) - print "Contents of the file = " + str(in_ws.readY(0)) + "." + print("Contents of the file = {}.".format(in_ws.readY(0))) .. testcleanup:: ExSimpleSavingRoundtrip diff --git a/docs/source/algorithms/LoadDNSLegacy-v1.rst b/docs/source/algorithms/LoadDNSLegacy-v1.rst index ebe85d2b41d2bab38e634cc1d4694c7fd83347c1..4d55aa05bff60a1f7597cf004d8b957efd5b2d80 100644 --- a/docs/source/algorithms/LoadDNSLegacy-v1.rst +++ b/docs/source/algorithms/LoadDNSLegacy-v1.rst @@ -67,7 +67,7 @@ Usage # Load dataset ws = LoadDNSLegacy(datafile, Normalization='monitor') - print "This workspace has", ws.getNumDims(), "dimensions and has", ws.getNumberHistograms(), "histograms." + print("This workspace has {} dimensions and has {} histograms.".format(ws.getNumDims(), ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadDetectorInfo-v1.rst b/docs/source/algorithms/LoadDetectorInfo-v1.rst index c2a8fde97e9ed2424e5563546b44799056621409..7a3545e0dbc3692d839cd81f8fd1301b50b39d0e 100644 --- a/docs/source/algorithms/LoadDetectorInfo-v1.rst +++ b/docs/source/algorithms/LoadDetectorInfo-v1.rst @@ -283,11 +283,11 @@ that the first three detectors (monitors) were not touched and the next three we def write_detectors(instr_type,instr,ndet): ''' print first ndet detectors from given instrument ''' - print "{0} {1} instrument".format(instr_type, instr.getName()) - print 'det ID | monitor? | polar angle| position X | position Y | position Z | Pressure | Wall thick |' + print("{0} {1} instrument".format(instr_type, instr.getName())) + print('det ID | monitor? | polar angle| position X | position Y | position Z | Pressure | Wall thick |') # get first nder detectors using detector ID - for i in xrange(0,ndet): + for i in range(0,ndet): if i<3: detBase = 1 else: @@ -297,9 +297,9 @@ that the first three detectors (monitors) were not touched and the next three we pos = det1.getPos(); pressure = det1.getNumberParameter('TubePressure'); thickness = det1.getNumberParameter('TubeThickness'); - print ' {0:5} | {1:8} | {2:10.3f} | {3:>10.3f} | {4:>10.3f} | {5:>10.3f} | {6:10} | {7:10} |\n'.format(\ - detID,det1.isMonitor(),(det1.getPhi()*(180/math.pi)),pos.X(),pos.Y(),pos.Z(),pressure[0],thickness[0]), - print '*********************************************************************************' + print(' {0:5} | {1:8} | {2:10.3f} | {3:>10.3f} | {4:>10.3f} | {5:>10.3f} | {6:10} | {7:10} |'.format(\ + detID,det1.isMonitor(),(det1.getPhi()*(180/math.pi)),pos.X(),pos.Y(),pos.Z(),pressure[0],thickness[0])) + print('*********************************************************************************') # def prepare_test_detector(ind): """ prepare modified detector with random test values """ @@ -347,7 +347,7 @@ that the first three detectors (monitors) were not touched and the next three we f.write("{0} 14\n".format(ndet)) f.write("det no. offset l2 code theta phi w_x w_y w_z f_x f_y f_z a_x a_y a_z det_1 det_2 det_3 det4\n"); - for i in xrange(0,ndet): + for i in range(0,ndet): detBase,offset,l2,code,theta,phi,w_xyz,f_xyz,a_xyz,det1,det2,det3,det4=prepare_test_detector(i); detID = detBase+i f.write("{0:>9} {1:>7} {2: >8f} {3:>5} {4:>11f} {5:>11f} {6:>11f} {7:>11f} {8:>11f} {9:>11f} {10:>11f} {11:>11f} {12:>11f} {13:>11f} {14:>11f} {15:>11f} {16:>11f} {17:>11f} {18:>11f} {19:>11f}\n".format(\ diff --git a/docs/source/algorithms/LoadDetectorsGroupingFile-v1.rst b/docs/source/algorithms/LoadDetectorsGroupingFile-v1.rst index e3ef270deab55d238c4981000211f8dd160cf55b..8481ea8e301a8bd25d541ecc25cd6d0d8c1360a2 100644 --- a/docs/source/algorithms/LoadDetectorsGroupingFile-v1.rst +++ b/docs/source/algorithms/LoadDetectorsGroupingFile-v1.rst @@ -162,19 +162,18 @@ Usage ws=LoadDetectorsGroupingFile("test.xml") #check some values + format_string = "Detector {}, with ID {}, in spectrum {} belongs to group {:.0f}" + sid=0 - print "Detector "+ws.getDetector(sid).getName()+", with ID "+\ - str(ws.getDetector(sid).getID())+ ", in spectrum "+str(sid)+\ - " belongs to group "+str(int(ws.dataY(sid)[0])) + print(format_string.format(ws.getDetector(sid).getName(), ws.getDetector(sid).getID(), + sid, ws.dataY(sid)[0])) sid=2500 - print "Detector "+ws.getDetector(sid).getName()+", with ID "+\ - str(ws.getDetector(sid).getID())+ ", in spectrum "+str(sid)+\ - " belongs to group "+str(int(ws.dataY(sid)[0])) + print(format_string.format(ws.getDetector(sid).getName(), ws.getDetector(sid).getID(), + sid, ws.dataY(sid)[0])) sid=5000 - print "Detector "+ws.getDetector(sid).getName()+", with ID "+\ - str(ws.getDetector(sid).getID())+ ", in spectrum "+str(sid)+\ - " belongs to group "+str(int(ws.dataY(sid)[0])) - + print(format_string.format(ws.getDetector(sid).getName(), ws.getDetector(sid).getID(), + sid, ws.dataY(sid)[0])) + .. testcleanup:: LoadDetectorsGroupingFile DeleteWorkspace(ws) @@ -214,9 +213,9 @@ Output: ws=LoadDetectorsGroupingFile("test.map") #check some values - print "Spectrum 0 belongs to group", ws.readY(0)[0] - print "Spectrum 65 belongs to group", ws.readY(65)[0] - print "Spectrum 125 belongs to group", ws.readY(125)[0] + print("Spectrum 0 belongs to group {}".format(ws.readY(0)[0])) + print("Spectrum 65 belongs to group {}".format(ws.readY(65)[0])) + print("Spectrum 125 belongs to group {}".format(ws.readY(125)[0])) .. testcleanup:: LoadDetectorsGroupingFileMap diff --git a/docs/source/algorithms/LoadDspacemap-v1.rst b/docs/source/algorithms/LoadDspacemap-v1.rst index 84d42a5d39cae793e1f1c45ba7727ca5f8d66da3..e92564e49306d7c18ce070a75b8c46419a5dcd8d 100644 --- a/docs/source/algorithms/LoadDspacemap-v1.rst +++ b/docs/source/algorithms/LoadDspacemap-v1.rst @@ -26,7 +26,7 @@ This algorithm is SNS specific in its use. ws = LoadDspacemap(InstrumentName="VULCAN", Filename="pid_offset_vulcan_new.dat", FileType="VULCAN-ASCII") - print "Workspace type =", ws.id() + print("Workspace type = {}".format(ws.id())) Output: diff --git a/docs/source/algorithms/LoadEmptyInstrument-v1.rst b/docs/source/algorithms/LoadEmptyInstrument-v1.rst index 1e5f559136bdcfdbc60d473065f31eff2fd9a538..16d294756665094af1b521aa5c898372dbf25dd4 100644 --- a/docs/source/algorithms/LoadEmptyInstrument-v1.rst +++ b/docs/source/algorithms/LoadEmptyInstrument-v1.rst @@ -30,7 +30,7 @@ Usage wsOut = LoadEmptyInstrument(inesPath) - print "The workspace contains %i spectra" % wsOut.getNumberHistograms() + print("The workspace contains {} spectra".format(wsOut.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadEmptyVesuvio-v1.rst b/docs/source/algorithms/LoadEmptyVesuvio-v1.rst index 164799f06880d8f23cd49ff385c65971e4c989ff..4b8909997c656e4f6edb6d2b687cda35d1792e4d 100644 --- a/docs/source/algorithms/LoadEmptyVesuvio-v1.rst +++ b/docs/source/algorithms/LoadEmptyVesuvio-v1.rst @@ -32,7 +32,7 @@ Usage b_det_1_l1 = sample.getPos().distance(b_det_1.getPos()) - print "First backscattering detector L1 = %.5fm" % (b_det_1_l1) + print("First backscattering detector L1 = {:.5f}m".format(b_det_1_l1)) Output: @@ -53,7 +53,7 @@ Output: b_det_1_l1 = sample.getPos().distance(b_det_1.getPos()) - print "First backscattering detector L1 = %.5fm" % (b_det_1_l1) + print("First backscattering detector L1 = {:.5f}m".format(b_det_1_l1)) Output: diff --git a/docs/source/algorithms/LoadEventAndCompress-v1.rst b/docs/source/algorithms/LoadEventAndCompress-v1.rst index c43e8355556bf3ee1329d4c7b83bc2794941cd4e..7af29968e94db749312f7569e3f4fd1e49982942 100644 --- a/docs/source/algorithms/LoadEventAndCompress-v1.rst +++ b/docs/source/algorithms/LoadEventAndCompress-v1.rst @@ -60,7 +60,7 @@ Create a python driver script called test_mpi.py mpiSize = 1 # simplify if clauses wksp = LoadEventAndCompress(Filename="PG3_2538_event.nxs") - print "Rank = ", mpiRank, "Number of Events = ", wksp.getNumberEvents() + print("Rank = {} Number of Events = {}".format(mpiRank, wksp.getNumberEvents())) if mpiRank == 0: reduce = AlignAndFocusPowder(InputWorkspace=wksp, CalFileName='PG3_calibrate_d2538_2014_05_13.cal', Params='0.5,0.01,2') SaveNexus(reduce,Filename=str(mpiSize)+"tasks.nxs") diff --git a/docs/source/algorithms/LoadEventNexus-v1.rst b/docs/source/algorithms/LoadEventNexus-v1.rst index 1ecc3ef7f8eda88dd0b0add1d867c156747e5924..06ac964a6a818309ed40b669963214946d75cc88 100644 --- a/docs/source/algorithms/LoadEventNexus-v1.rst +++ b/docs/source/algorithms/LoadEventNexus-v1.rst @@ -131,7 +131,7 @@ Usage # Load SNS HYS event dataset ws = LoadEventNexus('HYS_11092_event.nxs') - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: @@ -146,7 +146,7 @@ Output: # Load SNS CNCS event dataset between 10 and 20 minutes ws = LoadEventNexus('CNCS_7860_event.nxs', FilterByTimeStart=600, FilterByTimeStop=1200) - print "The number of events: " + str(ws.getNumberEvents()) + print("The number of events: {}".format(ws.getNumberEvents())) Output: diff --git a/docs/source/algorithms/LoadFITS-v1.rst b/docs/source/algorithms/LoadFITS-v1.rst index 10faa2e600e9ef3c46fa8b019513ea7be5973d9e..fc1b672d2f38c163dcf33fe41a9a8bad84725117 100644 --- a/docs/source/algorithms/LoadFITS-v1.rst +++ b/docs/source/algorithms/LoadFITS-v1.rst @@ -89,19 +89,19 @@ Example 1: loading one spectrum per image row bpp_log = 'BITPIX' try: log = ws.getRun().getLogData(bpp_log).value - print "Bits per pixel: %s" % int(log) + print("Bits per pixel: {}".format(log)) except RuntimeError: - print "Could not find the keyword '%s' in this FITS file" % bpp_log + print("Could not find the keyword '{}' in this FITS file".format(bpp_log)) axis1_log = 'NAXIS1' axis2_log = 'NAXIS2' try: log1 = ws.getRun().getLogData(axis1_log).value log2 = ws.getRun().getLogData(axis2_log).value - print "FITS image size: %s x %s pixels" % (int(log1), int(log2)) - print "Number of spectra in the output workspace: %d" % ws.getNumberHistograms() + print("FITS image size: {} x {} pixels".format(log1, log2)) + print("Number of spectra in the output workspace: {}".format(ws.getNumberHistograms())) except RuntimeError: - print "Could not find the keywords '%s' and '%s' in this FITS file" % (axis1_log, axis2_log) + print("Could not find the keywords '{}' and '{}' in this FITS file".format(axis1_log, axis2_log)) .. testcleanup:: LoadFITS1SpectrumPerRow @@ -128,19 +128,19 @@ Example 2: loading one spectrum per pixel bpp_log = 'BITPIX' try: log = ws.getRun().getLogData(bpp_log).value - print "Bits per pixel: %s" % int(log) + print("Bits per pixel: {}".format(int(log))) except RuntimeError: - print "Could not find the keyword '%s' in this FITS file" % bpp_log + print("Could not find the keyword '{}' in this FITS file".format(bpp_log)) axis1_log = 'NAXIS1' axis2_log = 'NAXIS2' try: log1 = ws.getRun().getLogData(axis1_log).value log2 = ws.getRun().getLogData(axis2_log).value - print "FITS image size: %s x %s pixels" % (int(log1), int(log2)) - print "Number of spectra in the output workspace: %d" % ws.getNumberHistograms() + print("FITS image size: {} x {} pixels".format(log1, log2)) + print("Number of spectra in the output workspace: {}".format(ws.getNumberHistograms())) except RuntimeError: - print "Could not find the keywords '%s' and '%s' in this FITS file" % (axis1_log, axis2_log) + print("Could not find the keywords '{}' and '{}' in this FITS file".format(axis1_log, axis2_log)) .. testcleanup:: LoadFITSManySpectra diff --git a/docs/source/algorithms/LoadFlexiNexus-v1.rst b/docs/source/algorithms/LoadFlexiNexus-v1.rst index 4685187a4cc8296c37a672125a976dbf95bf868f..4dede92da8dc8fb4c687f0d5cbf9e7d82251e76a 100644 --- a/docs/source/algorithms/LoadFlexiNexus-v1.rst +++ b/docs/source/algorithms/LoadFlexiNexus-v1.rst @@ -69,12 +69,12 @@ Usage Dictionary=os.path.join(dictionary_path, 'amor.dic')) num_dims = wsOut.getNumDims() - print "This has loaded a MD Workspace with %i dimensions" % num_dims - print "Name Bins Min Max" + print("This has loaded a MD Workspace with {} dimensions".format(num_dims)) + print("Name Bins Min Max") for dim_index in range(num_dims): dim = wsOut.getDimension(dim_index) - print "%s %i %.2f %.2f" % (dim.name, - dim.getNBins(), dim.getMinimum(), dim.getMaximum()) + print("{} {} {:.2f} {:.2f}".format(dim.name, + dim.getNBins(), dim.getMinimum(), dim.getMaximum())) Output: diff --git a/docs/source/algorithms/LoadFullprofFile-v1.rst b/docs/source/algorithms/LoadFullprofFile-v1.rst index 0ebb92e5017ef8560e26218b9a8fa273477a5bce..5de9c8a277bef0822cafd520a33a2416f8c363a1 100644 --- a/docs/source/algorithms/LoadFullprofFile-v1.rst +++ b/docs/source/algorithms/LoadFullprofFile-v1.rst @@ -58,10 +58,10 @@ Usage infotablews = mtd["LaB6_InfoTable"] dataws = mtd["PG3_LaB6_Bank3"] - print "LaB6: A = B = C = %.5f, Alpha = Beta = Gamma = %.5f" % (infotablews.cell(0, 1), infotablews.cell(5, 1)) + print("LaB6: A = B = C = {:.5f}, Alpha = Beta = Gamma = {:.5f}".format(infotablews.cell(0, 1), infotablews.cell(5, 1))) maxy = max(dataws.readY(1)) - print "Maximum peak value (calculated) = %.5f" % (maxy) + print("Maximum peak value (calculated) = {:.5f}".format(maxy)) .. testcleanup:: ExLoadPrf @@ -89,15 +89,15 @@ Output: fakedataws = mtd["Fake"] reftablews = mtd["LaB6_Ref_Table"] - print "Reflection table imported %d peaks. Faked data workspace contains %d data points." % ( - reftablews.rowCount(), len(fakedataws.readX(0))) + print("Reflection table imported {} peaks. Faked data workspace contains {} data points.".format( + reftablews.rowCount(), len(fakedataws.readX(0)))) index = 0 - print "Peak %d of (%d, %d, %d): Alpha = %.5f, Beta = %.5f, FWHM = %.5f" % (index, reftablews.cell(index, 0), - reftablews.cell(index, 1), reftablews.cell(index, 2), reftablews.cell(index, 3), reftablews.cell(index, 4), reftablews.cell(index, 7)) + print("Peak {} of ({}, {}, {}): Alpha = {:.5f}, Beta = {:.5f}, FWHM = {:.5f}".format(index, reftablews.cell(index, 0), + reftablews.cell(index, 1), reftablews.cell(index, 2), reftablews.cell(index, 3), reftablews.cell(index, 4), reftablews.cell(index, 7))) index = 75 - print "Peak %d of (%d, %d, %d): Alpha = %.5f, Beta = %.5f, FWHM = %.5f" % (index, reftablews.cell(index, 0), - reftablews.cell(index, 1), reftablews.cell(index, 2), reftablews.cell(index, 3), reftablews.cell(index, 4), reftablews.cell(index, 7)) + print("Peak {} of ({}, {}, {}): Alpha = {:.5f}, Beta = {:.5f}, FWHM = {:.5f}".format(index, reftablews.cell(index, 0), + reftablews.cell(index, 1), reftablews.cell(index, 2), reftablews.cell(index, 3), reftablews.cell(index, 4), reftablews.cell(index, 7))) .. testcleanup:: ExLoadIrf diff --git a/docs/source/algorithms/LoadFullprofResolution-v1.rst b/docs/source/algorithms/LoadFullprofResolution-v1.rst index 13ed7d7e49376e4258a017c241958b3e4fcec7e6..36fbfebb1853808425f5859f02e208ede61d5170 100644 --- a/docs/source/algorithms/LoadFullprofResolution-v1.rst +++ b/docs/source/algorithms/LoadFullprofResolution-v1.rst @@ -43,19 +43,19 @@ Usage tws = LoadFullprofResolution("MUSR_01.irf",Banks="3,5", Workspace="ws") #Print first four rows of output table workspace - print "First 4 rows of OutputTableWorkspace" + print("First 4 rows of OutputTableWorkspace") for i in [0,1,2,3]: row = tws.row(i) - print "{'Name': '%s', 'Value_3': %.2f, 'Value_5': %.2f}" % ( row["Name"], row["Value_3"], row["Value_5"] ) + print("{{'Name': '{}', 'Value_3': {:.2f}, 'Value_5': {:.2f}}}".format(row["Name"], row["Value_3"], row["Value_5"])) # Get the instrument with the parameters inst = ws[0][0].getInstrument() # demonstrate that the type of parameters saved are fitting parameters - print "Type of 3 parameters got from instrument in workspace" - print "Alpha0 type =", inst.getParameterType('Alpha0') - print "Beta0 type =", inst.getParameterType('Beta0') - print "SigmaSquared type =", inst.getParameterType('SigmaSquared') + print("Type of 3 parameters got from instrument in workspace") + print("Alpha0 type = {}".format(inst.getParameterType('Alpha0'))) + print("Beta0 type = {}".format(inst.getParameterType('Beta0'))) + print("SigmaSquared type = {}".format(inst.getParameterType('SigmaSquared'))) # As of the time of writing, # fitting instrument parameters cannot be diff --git a/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst b/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst index 36758f817987eb816de4250f3674acf745f2f528..6d26c479f30c8664791c93c56d44fd37c80496e5 100644 --- a/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst +++ b/docs/source/algorithms/LoadGSASInstrumentFile-v1.rst @@ -30,7 +30,7 @@ Usage #Print first four rows for i in [0,1,2,3]: row = tws.row(i) - print "{'Name': '%s','Value_1': %.2f, 'Value_2': %.2f}" % ( row["Name"], row["Value_1"], row["Value_2"] ) + print("{{'Name': '{}','Value_1': {:.2f}, 'Value_2': {:.2f}}}".format(row["Name"], row["Value_1"], row["Value_2"] )) Output: @@ -56,19 +56,19 @@ Output: # ...and check they do not exist instrument = groupWs.getItem(0).getInstrument() - print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") - print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") - print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + print("Alpha0 parameter exists: {}".format(instrument.hasParameter("Alpha0"))) + print("Beta0 parameter exists: {}".format(instrument.hasParameter("Beta0"))) + print("SigmaSquared parameter exists: {}".format(instrument.hasParameter("SigmaSquared"))) # Now we load a GSAS Instrument file with 2 Banks into the workspace... - print "\nLoading parameters from GSAS\n" + print("\nLoading parameters from GSAS\n") tws = LoadGSASInstrumentFile(Filename="GSAS_2bank.prm",UseBankIDsInFile=True,Workspace=groupWs,Banks=[1,2]) # ...and check parameters are there again instrument = groupWs.getItem(0).getInstrument() - print "Alpha0 parameter exists: ", instrument.hasParameter("Alpha0") - print "Beta0 parameter exists: ", instrument.hasParameter("Beta0") - print "SigmaSquared parameter exists: " , instrument.hasParameter("SigmaSquared") + print("Alpha0 parameter exists: {}".format(instrument.hasParameter("Alpha0"))) + print("Beta0 parameter exists: {}".format(instrument.hasParameter("Beta0"))) + print("SigmaSquared parameter exists: {}".format(instrument.hasParameter("SigmaSquared"))) Output: diff --git a/docs/source/algorithms/LoadIDFFromNexus-v1.rst b/docs/source/algorithms/LoadIDFFromNexus-v1.rst index c34bccb57d62675bfaa59f44948821382d2e5ef8..09fdf94e69b07be1128a2e8ba76fd97d3509ee8a 100644 --- a/docs/source/algorithms/LoadIDFFromNexus-v1.rst +++ b/docs/source/algorithms/LoadIDFFromNexus-v1.rst @@ -52,12 +52,12 @@ Usage # This workspace had the IDF loaded into it, so getting component renamed to "the rings". inst1 = ws_1.getInstrument() comp1 = inst1.getComponentByName("the rings") - print "Modified component name =", comp1.getName() + print("Modified component name = {}".format(comp1.getName())) # This workspace had no IDF loaded into it, so still has component named to "both rings". inst2 = ws_2.getInstrument() comp2 = inst2.getComponentByName("both rings") - print "Unmodified component name =", comp2.getName() + print("Unmodified component name = {}".format(comp2.getName())) Output: diff --git a/docs/source/algorithms/LoadILLReflectometry-v1.rst b/docs/source/algorithms/LoadILLReflectometry-v1.rst index 89cf9d7722069fa65e23c1c93f2f11ac34022f05..d7957b329cff15ef165042b3502bb3bd9da27bc5 100644 --- a/docs/source/algorithms/LoadILLReflectometry-v1.rst +++ b/docs/source/algorithms/LoadILLReflectometry-v1.rst @@ -158,7 +158,7 @@ Usage # Load ILL D17 data file (TOF mode) into a workspace 2D using default input options: ws1 = Load('ILL/D17/317370.nxs') - print("Workspace {} has {} dimensions and {} histograms.").format(ws1.name(), ws1.getNumDims(), ws1.getNumberHistograms()) + print("Workspace {} has {} dimensions and {} histograms.".format(ws1.name(), ws1.getNumDims(), ws1.getNumberHistograms())) Output: @@ -185,7 +185,7 @@ Output: # The Sample Log entry stheta will be the user defined angle of 30 degrees: angleBragg = ws2.getRun().getProperty("stheta").value * 180. / numpy.pi - print("The detector of workspace {} was rotated to {} degrees.").format(ws2.name(), 2. * angleBragg) + print("The detector of workspace {} was rotated to {:.1f} degrees.".format(ws2.name(), 2. * angleBragg)) print("The nominal angle in the NeXus file was {:.2} degrees.".format(angleOrig)) Output: diff --git a/docs/source/algorithms/LoadILLSANS-v1.rst b/docs/source/algorithms/LoadILLSANS-v1.rst index 0f6f937e30bdf94e776374cf4fbe5ceb29978e3b..c0accafcb7fa7cb8de2799bf68ff36679f085f02 100644 --- a/docs/source/algorithms/LoadILLSANS-v1.rst +++ b/docs/source/algorithms/LoadILLSANS-v1.rst @@ -25,7 +25,7 @@ Usage # Load ILL D33 data file into a workspace 2D. ws = Load('ILLD33_sample_001425.nxs') - print "This workspace has", ws.getNumDims(), "dimensions and has", ws.getNumberHistograms(), "histograms." + print("This workspace has {} dimensions and has {} histograms.".format(ws.getNumDims(), ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadISISNexus-v2.rst b/docs/source/algorithms/LoadISISNexus-v2.rst index 5fe7a9968e4eca79d5349f30b26ce96293fec5cf..92d8cbe22f7651c15394ab25b85512fc50c4bc1a 100644 --- a/docs/source/algorithms/LoadISISNexus-v2.rst +++ b/docs/source/algorithms/LoadISISNexus-v2.rst @@ -152,7 +152,7 @@ Usage # Load LOQ histogram dataset ws = LoadISISNexus('LOQ49886.nxs') - print "The 1st x-value of the first spectrum is: " + str(ws.readX(0)[0]) + print("The 1st x-value of the first spectrum is: {}".format(ws.readX(0)[0])) Output: @@ -167,7 +167,7 @@ Output: # Load from LOQ data file spectrum 2 to 3. ws = LoadISISNexus('LOQ49886.nxs',SpectrumMin=2,SpectrumMax=3) - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: @@ -182,7 +182,7 @@ Output: # Load first period of multiperiod POLREF data file ws = LoadISISNexus('POLREF00004699.nxs', EntryNumber=1) - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadInstrument-v1.rst b/docs/source/algorithms/LoadInstrument-v1.rst index 5050b5f50d3d1f064234a1d0d91e0a6be92aa927..9bb17050731bffe22d3823c82e5c9024e3575b4b 100644 --- a/docs/source/algorithms/LoadInstrument-v1.rst +++ b/docs/source/algorithms/LoadInstrument-v1.rst @@ -37,14 +37,14 @@ Usage ws=CreateSampleWorkspace(); inst0=ws.getInstrument(); - print "Default workspace has instrument: {0} with {1} parameters".format(inst0.getName(),len(inst0.getParameterNames())); + print("Default workspace has instrument: {0} with {1} parameters".format(inst0.getName(),len(inst0.getParameterNames()))) # load MARI det=LoadInstrument(ws,InstrumentName='MARI', RewriteSpectraMap=True) inst1=ws.getInstrument(); - print "Modified workspace has instrument: {0} with {1} parameters".format(inst1.getName(),len(inst1.getParameterNames())); - print "Instrument {0} has the following detectors: ".format(inst1.getName()),det + print("Modified workspace has instrument: {0} with {1} parameters".format(inst1.getName(),len(inst1.getParameterNames()))) + print("Instrument {0} has the following detectors: {1}".format(inst1.getName(), det)) **Output:** diff --git a/docs/source/algorithms/LoadInstrumentFromNexus-v1.rst b/docs/source/algorithms/LoadInstrumentFromNexus-v1.rst index 476675cffe35e2499bfb0813946bccf444affe7f..c7d47ac3c0dfad7a7fc63af18f044e41c373329c 100644 --- a/docs/source/algorithms/LoadInstrumentFromNexus-v1.rst +++ b/docs/source/algorithms/LoadInstrumentFromNexus-v1.rst @@ -31,15 +31,15 @@ Usage inst = ws.getInstrument() source = inst.getSource() - print "The name of the instrument is \"%s\"." % inst.getName().strip() - print ("The source postion is at: %s." % str(source.getPos()) ) + print("The name of the instrument is '{}'.".format(inst.getName().strip())) + print("The source postion is at: {}.".format(source.getPos())) Output: .. testoutput:: ExLoadMUSR - The name of the instrument is "MUSR". + The name of the instrument is 'MUSR'. The source postion is at: [0,-10,0]. .. categories:: diff --git a/docs/source/algorithms/LoadInstrumentFromRaw-v1.rst b/docs/source/algorithms/LoadInstrumentFromRaw-v1.rst index 83402d78258ab4aad7f63bbce67537792e33ae9d..8468aa33fd589d28daaec47a12c6dcc1bbddc35f 100644 --- a/docs/source/algorithms/LoadInstrumentFromRaw-v1.rst +++ b/docs/source/algorithms/LoadInstrumentFromRaw-v1.rst @@ -34,17 +34,17 @@ Usage inst = ws.getInstrument() - print "The name of the instrument is \"%s\"." % inst.getName().strip() - print "The position of the source is %s." % str(inst.getSource().getPos()) - print "The position of detector 5 is %s." % str(inst.getDetector(5).getPos()) - print "Is detector 1 a monitor? " + str(inst.getDetector(1).isMonitor()) - print "Is detector 8 a monitor? " + str(inst.getDetector(8).isMonitor()) + print("The name of the instrument is '{}'.".format(inst.getName().strip())) + print("The position of the source is {}.".format(inst.getSource().getPos())) + print("The position of detector 5 is {}.".format(inst.getDetector(5).getPos())) + print("Is detector 1 a monitor? {}".format(inst.getDetector(1).isMonitor())) + print("Is detector 8 a monitor? {}".format(inst.getDetector(8).isMonitor())) Output: .. testoutput:: Ex - The name of the instrument is "LOQ". + The name of the instrument is 'LOQ'. The position of the source is [0,0,-11]. The position of detector 5 is [0,0,-11.15]. Is detector 1 a monitor? True diff --git a/docs/source/algorithms/LoadIsawDetCal-v1.rst b/docs/source/algorithms/LoadIsawDetCal-v1.rst index b6a8d6f23f03123bb27052f03574f08db4c6953e..39dc33620d67e532766bb20401c05af859199c7f 100644 --- a/docs/source/algorithms/LoadIsawDetCal-v1.rst +++ b/docs/source/algorithms/LoadIsawDetCal-v1.rst @@ -27,7 +27,7 @@ Usage iw = LoadEmptyInstrument(Filename="IDFs_for_UNIT_TESTING/MINITOPAZ_Definition.xml",) LoadIsawDetCal(InputWorkspace=iw,FileName=filename) bank = iw.getInstrument().getComponentByName("bank1") - print "Position after LoadDetCal :",bank.getPos() + print("Position after LoadDetCal : {}".format(bank.getPos())) .. testcleanup:: LoadIsawDetCal diff --git a/docs/source/algorithms/LoadIsawPeaks-v1.rst b/docs/source/algorithms/LoadIsawPeaks-v1.rst index 6a92e732406551e93f1057e3258a343428b6c45c..8a27cedbe85a0aa9257a6b05d58e1670467c1992 100644 --- a/docs/source/algorithms/LoadIsawPeaks-v1.rst +++ b/docs/source/algorithms/LoadIsawPeaks-v1.rst @@ -27,7 +27,7 @@ Usage .. testcode:: LoadIsawPeaksEx peaks = LoadIsawPeaks('TOPAZ_1204.peaks') - print "Number of peaks entries", peaks.getNumberPeaks() + print("Number of peaks entries {}".format(peaks.getNumberPeaks())) Output: diff --git a/docs/source/algorithms/LoadIsawSpectrum-v1.rst b/docs/source/algorithms/LoadIsawSpectrum-v1.rst index 15697d18bfe71e8a1c62024c38e7b23332f3a65e..aa2b05caee8d5307bff2fc9701e262512aee2a0e 100644 --- a/docs/source/algorithms/LoadIsawSpectrum-v1.rst +++ b/docs/source/algorithms/LoadIsawSpectrum-v1.rst @@ -43,8 +43,8 @@ Usage ow = LoadIsawSpectrum(SpectraFile=filename,InstrumentName="TOPAZ") #check the results - print "x=",ow.readX(0) - print "y=",ow.readY(0) + print("x= {}".format(ow.readX(0))) + print("y= {}".format(ow.readY(0))) .. testcleanup:: LoadIsawSpectrum diff --git a/docs/source/algorithms/LoadIsawUB-v1.rst b/docs/source/algorithms/LoadIsawUB-v1.rst index 1f8aac4809976b959614f0cabba0a7e806f80d86..3f2f5f3adf37f6e2c64fe95c95b5ab88374379e9 100644 --- a/docs/source/algorithms/LoadIsawUB-v1.rst +++ b/docs/source/algorithms/LoadIsawUB-v1.rst @@ -47,13 +47,13 @@ Usage #check the results ol=w.sample().getOrientedLattice() - print "a=",ol.a() - print "b=",ol.b() - print "c=",ol.c() - print "alpha=",ol.alpha() - print "beta=",ol.beta() - print "gamma=",ol.gamma() - print "The following vectors are in the horizontal plane: ", ol.getuVector(),ol.getvVector() + print("a= {}".format(ol.a())) + print("b= {}".format(ol.b())) + print("c= {}".format(ol.c())) + print("alpha= {}".format(ol.alpha())) + print("beta= {}".format(ol.beta())) + print("gamma= {}".format(ol.gamma() )) + print("The following vectors are in the horizontal plane: {} {}".format(ol.getuVector(), ol.getvVector())) .. testcleanup:: LoadIsawUB diff --git a/docs/source/algorithms/LoadLLB-v1.rst b/docs/source/algorithms/LoadLLB-v1.rst index f82fff1d47556e23316ea957d57d2a9711ecb746..7fb60a344b96d74bc585631d9eae6779460b1d68 100644 --- a/docs/source/algorithms/LoadLLB-v1.rst +++ b/docs/source/algorithms/LoadLLB-v1.rst @@ -27,7 +27,7 @@ Usage # Load the MIBEMOL dataset into a workspace2D. ws = Load('LLB_d22418.nxs') - print "This workspace has", ws.getNumDims(), "dimensions and its title is:", ws.getTitle() + print("This workspace has {} dimensions and its title is: ".format(ws.getNumDims(), ws.getTitle())) Output: diff --git a/docs/source/algorithms/LoadLog-v1.rst b/docs/source/algorithms/LoadLog-v1.rst index 68300da4ed1a5f8bdba6e66dd43afd84e5ed072b..79315d77c3eb6517e3f4a67bb0b9fa209f35585d 100644 --- a/docs/source/algorithms/LoadLog-v1.rst +++ b/docs/source/algorithms/LoadLog-v1.rst @@ -60,18 +60,18 @@ Usage #get the log data out of the Workspace's run object run = ws.getRun() logs= run.getLogData() - print "Logs before adding:" + print("Logs before adding:") for i in range(0,len(logs)): - print logs[i].name + print(logs[i].name) #ExampleForLog.log is taken from a NIMROD run LoadLog(ws,"ExampleForLog.log") - print "" + print("") run = ws.getRun() logs= run.getLogData() - print "Logs after adding:" + print("Logs after adding:") for i in range(0,len(logs)): - print logs[i].name + print(logs[i].name) Output: diff --git a/docs/source/algorithms/LoadLogPropertyTable-v1.rst b/docs/source/algorithms/LoadLogPropertyTable-v1.rst index e359f22ff0826b58d89b1e2781ddbd3dcdf4a974..11c227f673f9c4b77ff35d149fe79c646a7a1779 100644 --- a/docs/source/algorithms/LoadLogPropertyTable-v1.rst +++ b/docs/source/algorithms/LoadLogPropertyTable-v1.rst @@ -41,23 +41,21 @@ Usage .. testcode:: Exlogtable def print_table_workspace(wsOut): - for i in range(wsOut.columnCount()): - print wsOut.getColumnNames()[i], - print + print(" ".join(wsOut.getColumnNames()[i] + for i in range(wsOut.columnCount()))) for rowIndex in range(wsOut.columnCount()): - for i in range(wsOut.columnCount()): - print wsOut.column(i)[rowIndex], - print + print(" ".join(str(wsOut.column(i)[rowIndex]) + for i in range(wsOut.columnCount()))) wsComment = LoadLogPropertyTable(FirstFile = "MUSR00015189.nxs", LastFile = "MUSR00015193.nxs", LogNames="comment") - print "The comments of all the files" + print("The comments of all the files") print_table_workspace(wsComment) wsMultiple = LoadLogPropertyTable(FirstFile = "MUSR00015189.nxs", LastFile = "MUSR00015193.nxs", LogNames="Temp_Sample,dur") - print "\nThe Temp_Sample and dur logs" + print("\nThe Temp_Sample and dur logs") print_table_workspace(wsMultiple) diff --git a/docs/source/algorithms/LoadMD-v1.rst b/docs/source/algorithms/LoadMD-v1.rst index 24f28172c64aacaf0b4920d1096abc2ef8903566..add4525edef8561436c64d27e127cd32af6ef1e6 100644 --- a/docs/source/algorithms/LoadMD-v1.rst +++ b/docs/source/algorithms/LoadMD-v1.rst @@ -40,8 +40,8 @@ Usage mdws = LoadMD('MAPS_MDEW.nxs'); # Check results - print "Workspace type is:",mdws.id() - print "Workspace has:{0:2} dimensions and contains: {1:4} MD events".format(mdws.getNumDims(),mdws.getNEvents()) + print("Workspace type is: {}".format(mdws.id())) + print("Workspace has:{0:2} dimensions and contains: {1:4} MD events".format(mdws.getNumDims(),mdws.getNEvents())) Output: diff --git a/docs/source/algorithms/LoadMLZ-v1.rst b/docs/source/algorithms/LoadMLZ-v1.rst index 3ef1ceba554ff35d51d6d86297940c8aeffc24d2..fcbb25c2efcf5ba4317a293a98555b0d2ccdfc9e 100644 --- a/docs/source/algorithms/LoadMLZ-v1.rst +++ b/docs/source/algorithms/LoadMLZ-v1.rst @@ -29,8 +29,8 @@ Usage ws = LoadMLZ(Filename='TOFTOFTestdata.nxs') - print "Name of the instrument: ", ws.getInstrument().getName() - print "Number of spectra: ", ws.getNumberHistograms() + print("Name of the instrument: {}".format(ws.getInstrument().getName())) + print("Number of spectra: {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadMask-v1.rst b/docs/source/algorithms/LoadMask-v1.rst index 9564f97bead77bc79fc38a295b4fd12dd5a8f35e..223fcea04d39d5eedc140a1ffab1cc96a1680b56 100644 --- a/docs/source/algorithms/LoadMask-v1.rst +++ b/docs/source/algorithms/LoadMask-v1.rst @@ -89,11 +89,11 @@ Usage # ws.maskDetectors(MaskedWorkspace=mask) # Check some pixels - print "Is detector 0 masked:", ws.getDetector(0).isMasked() - print "Is detector 6245 masked:", ws.getDetector(6245).isMasked() - print "Is detector 11464 masked:", ws.getDetector(11464).isMasked() - print "Is detector 17578 masked:", ws.getDetector(17578).isMasked() - print "Is detector 20475 masked:", ws.getDetector(20475).isMasked() + print("Is detector 0 masked: {}".format(ws.getDetector(0).isMasked())) + print("Is detector 6245 masked: {}".format(ws.getDetector(6245).isMasked())) + print("Is detector 11464 masked: {}".format(ws.getDetector(11464).isMasked())) + print("Is detector 17578 masked: {}".format(ws.getDetector(17578).isMasked())) + print("Is detector 20475 masked: {}".format(ws.getDetector(20475).isMasked())) Output: @@ -142,7 +142,7 @@ Output: MaskedDet1to1= [] MaskedSp_R = [] MaskedDet_R= [] - for ind in xrange(0,nhist): + for ind in range(0,nhist): try: det = rws.getDetector(ind) if det.isMasked(): @@ -160,25 +160,25 @@ Output: MaskedDet_R.append(det.getID()) except: pass - print "*** ************************************ **********************************************" - print ("*** Masked Spec. Id(s): {0}".format(masked_list)) - print "*** Initial workspace masking parameters **********************************************" - print "Masked Spectra Numbers: ",Sig0Masked - print "Masked Detector IDs : ",Det0Masked - print "*** One to one mask workspace has masked the same spectra numbers but different detectors" - print "ws 1to1 Masked spectra: ",MaskedSp1to1 - print "ws 1to1 Masked DedIDs : ",MaskedDet1to1 - print "*** Real spectra-det-map workspace has masked different spectra numbers but the same detectors" - print "ws RSDM Masked spectra: ",MaskedSp_R - print "ws RSDM Masked DedIDs : ",MaskedDet_R - print "*** indeed the same:" + print("*** ************************************ **********************************************") + print("*** Masked Spec. Id(s): {0}".format(masked_list)) + print( "*** Initial workspace masking parameters **********************************************") + print("Masked Spectra Numbers: {}".format(Sig0Masked)) + print("Masked Detector IDs : {}".format(Det0Masked)) + print("*** One to one mask workspace has masked the same spectra numbers but different detectors") + print("ws 1to1 Masked spectra: {}".format(MaskedSp1to1)) + print("ws 1to1 Masked DedIDs : {}".format(MaskedDet1to1)) + print("*** Real spectra-det-map workspace has masked different spectra numbers but the same detectors") + print("ws RSDM Masked spectra: {}".format(MaskedSp_R)) + print("ws RSDM Masked DedIDs : {}".format(MaskedDet_R)) + print("*** indeed the same:") Det0Masked.sort() MaskedDet_R.sort() - print "sorted initial DetIDs : ",Det0Masked - print "sorted RSDM DedIDs : ",MaskedDet_R - print "*** ************************************ **********************************************" - print "*** note spectra with id 4 is a monitor, not present in the masking workspaces" - print "*** ************************************ **********************************************" + print("sorted initial DetIDs : {}".format(Det0Masked)) + print("sorted RSDM DedIDs : {}".format(MaskedDet_R)) + print("*** ************************************ **********************************************") + print("*** note spectra with id 4 is a monitor, not present in the masking workspaces") + print("*** ************************************ **********************************************") Output: diff --git a/docs/source/algorithms/LoadMcStas-v1.rst b/docs/source/algorithms/LoadMcStas-v1.rst index a720bb626c26b540198195bfa76f613e3e51a4a1..1586411c449de85e739d51a07b69c6dabccdec6f 100644 --- a/docs/source/algorithms/LoadMcStas-v1.rst +++ b/docs/source/algorithms/LoadMcStas-v1.rst @@ -98,15 +98,15 @@ Usage # workspace group is first entry in tuple group = ws[0] - print "Number of entries in group: " + str(group.getNumberOfEntries()) + print("Number of entries in group: {}".format(group.getNumberOfEntries())) eventData = ws[1] - print "Number of histograms in event data: " + str(eventData.getNumberHistograms()) - print "Name of event data: " + str(eventData.getName()) + print("Number of histograms in event data: {}".format(eventData.getNumberHistograms())) + print("Name of event data: {}".format(eventData.getName())) someHistogramData = ws[2] - print "Number of histograms in hist data: " + str(someHistogramData.getNumberHistograms()) - print "Name of hist data: " + str(someHistogramData.getName()) + print("Number of histograms in hist data: {}".format(someHistogramData.getNumberHistograms())) + print("Name of hist data: {}".format(someHistogramData.getName())) Output: diff --git a/docs/source/algorithms/LoadMultipleGSS-v1.rst b/docs/source/algorithms/LoadMultipleGSS-v1.rst index 71e518feb69d48a270a332a2b1747263e65bf79f..7aab060dd3dba7da955429ccface9c08c2aaebdb 100644 --- a/docs/source/algorithms/LoadMultipleGSS-v1.rst +++ b/docs/source/algorithms/LoadMultipleGSS-v1.rst @@ -22,10 +22,10 @@ Usage LoadMultipleGSS(FilePrefix="PG3",RunNumbers="11485,11486",Directory="") #quick test: - print "Found workspace PG3_11485",mtd.doesExist("PG3_11485") - print "It has",mtd["PG3_11485"].getNumberHistograms(),"histogram, with",mtd["PG3_11485"].blocksize(),"bins" - print "Found workspace PG3_11486",mtd.doesExist("PG3_11486") - print "It has",mtd["PG3_11486"].getNumberHistograms(),"histogram, with",mtd["PG3_11486"].blocksize(),"bins" + print("Found workspace PG3_11485 {}".format(mtd.doesExist("PG3_11485"))) + print("It has {} histogram, with {} bins".format(mtd["PG3_11485"].getNumberHistograms(), mtd["PG3_11485"].blocksize())) + print("Found workspace PG3_11486 {}".format(mtd.doesExist("PG3_11486"))) + print("It has {} histogram, with {} bins".format(mtd["PG3_11486"].getNumberHistograms(), mtd["PG3_11486"].blocksize())) .. testcleanup:: LoadMultipleGSS diff --git a/docs/source/algorithms/LoadMuonLog-v1.rst b/docs/source/algorithms/LoadMuonLog-v1.rst index 7b8e4c2a4ec5d272c62c64036e6b2d860a795795..e089716be96ffee53040448a177733541157da79 100644 --- a/docs/source/algorithms/LoadMuonLog-v1.rst +++ b/docs/source/algorithms/LoadMuonLog-v1.rst @@ -48,8 +48,8 @@ Usage # Extract a property from the log. time_series_prop = fake_musr_ws.run().getLogData("BEAMLOG_FREQ") - print "BEAMLOG_FREQ is a TimeSeriesProperty with %i entries." % time_series_prop.size() - print "The first entry is %f." % time_series_prop.firstValue() + print("BEAMLOG_FREQ is a TimeSeriesProperty with {} entries.".format(time_series_prop.size())) + print("The first entry is {:.6f}.".format(time_series_prop.firstValue())) Output: diff --git a/docs/source/algorithms/LoadMuonNexus-v2.rst b/docs/source/algorithms/LoadMuonNexus-v2.rst index cbcadd632a231f5f82537c332e54b40ed8f1e422..a36ba6e4689a095cc188658eb058fb731396bce5 100644 --- a/docs/source/algorithms/LoadMuonNexus-v2.rst +++ b/docs/source/algorithms/LoadMuonNexus-v2.rst @@ -173,7 +173,7 @@ Usage # Load MUSR dataset ws = LoadMuonNexus(Filename="MUSR00015189.nxs",EntryNumber=1) - print "Workspace has ", ws[0].getNumberHistograms(), " spectra" + print("Workspace has {} spectra".format(ws[0].getNumberHistograms())) Output: @@ -187,7 +187,7 @@ Output: # Load some spectra ws = LoadMuonNexus(Filename="MUSR00015189.nxs",SpectrumMin=5,SpectrumMax=10,EntryNumber=1) - print "Workspace has ", ws[0].getNumberHistograms(), " spectra" + print("Workspace has {} spectra".format(ws[0].getNumberHistograms())) Output: @@ -203,18 +203,18 @@ Output: ws = LoadMuonNexus(Filename="emu00006473.nxs",SpectrumMin=5,SpectrumMax=10,DeadTimeTable="deadTimeTable") tab = mtd['deadTimeTable'] for i in range(0,tab.rowCount()): - print tab.cell(i,0), tab.cell(i,1) + print("{} {:.12f}".format(tab.cell(i,0), tab.cell(i,1))) Output: .. testoutput:: ExLoadDeadTimeTable - 5 0.00161112251226 - 6 0.00215016817674 - 7 0.0102171599865 - 8 0.00431686220691 - 9 0.00743605662137 - 10 0.00421147653833 + 5 0.001611122512 + 6 0.002150168177 + 7 0.010217159986 + 8 0.004316862207 + 9 0.007436056621 + 10 0.004211476538 **Example - Load detector grouping into table:** @@ -224,7 +224,7 @@ Output: ws = LoadMuonNexus(Filename="emu00006473.nxs",SpectrumList="1,16,17,32",DetectorGroupingTable="detectorTable") tab = mtd['detectorTable'] for i in range(0,tab.rowCount()): - print tab.cell(i,0) + print(tab.cell(i,0)) Output: diff --git a/docs/source/algorithms/LoadNMoldyn3Ascii-v1.rst b/docs/source/algorithms/LoadNMoldyn3Ascii-v1.rst index 6e0aca39fff33dcc414e7c857e94d67803ef95a0..8d06bedd116cf74939206059b3e3517497eb5657 100644 --- a/docs/source/algorithms/LoadNMoldyn3Ascii-v1.rst +++ b/docs/source/algorithms/LoadNMoldyn3Ascii-v1.rst @@ -30,7 +30,7 @@ Usage Functions=['Fqt-total', 'Sqw-total']) for ws_name in out_ws_group.getNames(): - print ws_name + print(ws_name) Output: diff --git a/docs/source/algorithms/LoadNMoldyn4Ascii-v1.rst b/docs/source/algorithms/LoadNMoldyn4Ascii-v1.rst index 8f7bb7a8828ee13b0ce86e3f2ae6e2eb30cc2415..72179b710986f3f4db9baace501499f93733ecf7 100644 --- a/docs/source/algorithms/LoadNMoldyn4Ascii-v1.rst +++ b/docs/source/algorithms/LoadNMoldyn4Ascii-v1.rst @@ -53,7 +53,7 @@ Usage Functions=['sqf_total', 'iqt_total']) for ws in data: - print ws.name() + print(ws.name()) Output: diff --git a/docs/source/algorithms/LoadNMoldyn4Ascii1D-v1.rst b/docs/source/algorithms/LoadNMoldyn4Ascii1D-v1.rst index 2e358ae7bfed80d5a81f057aa04e51d5475fd659..033966b156f5afd856c0c3829a500b2f01b9f59c 100644 --- a/docs/source/algorithms/LoadNMoldyn4Ascii1D-v1.rst +++ b/docs/source/algorithms/LoadNMoldyn4Ascii1D-v1.rst @@ -60,7 +60,7 @@ resolution convolution** Functions=['dos_total', 'vacf_total']) for ws in data: - print ws.name() + print(ws.name()) Output: diff --git a/docs/source/algorithms/LoadNexus-v1.rst b/docs/source/algorithms/LoadNexus-v1.rst index bffccbd6e03e25838c179c06dcc693d59fceb7f4..5ab2681bb8c65331654d6a3d28a718cc3a151de3 100644 --- a/docs/source/algorithms/LoadNexus-v1.rst +++ b/docs/source/algorithms/LoadNexus-v1.rst @@ -53,7 +53,7 @@ Usage # Load LOQ histogram dataset ws = LoadNexus('LOQ49886.nxs') - print "The 1st x-value of the first spectrum is: " + str(ws.readX(0)[0]) + print("The 1st x-value of the first spectrum is: {}".format(ws.readX(0)[0])) Output: @@ -69,7 +69,7 @@ Output: # Load ISIS multiperiod muon MUSR dataset ws = LoadNexus('MUSR00015189.nxs') - print "The number of periods (entries) is: " + str(ws[0].getNumberOfEntries()) + print("The number of periods (entries) is: {}".format(ws[0].getNumberOfEntries())) Output: @@ -85,7 +85,7 @@ Output: # Load Mantid processed GEM data file ws = LoadNexus('focussed.nxs') - print "The number of histograms (spectra) is: " + str(ws.getNumberHistograms()) + print("The number of histograms (spectra) is: {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadNexusLogs-v1.rst b/docs/source/algorithms/LoadNexusLogs-v1.rst index a598f17748066e6344e366a9613b1ccfd1f9c45a..fd20fc6c67360449fa595f7da27ab8d18cc681bf 100644 --- a/docs/source/algorithms/LoadNexusLogs-v1.rst +++ b/docs/source/algorithms/LoadNexusLogs-v1.rst @@ -78,21 +78,21 @@ the logs. ws = LoadEventPreNexus("CNCS_7860_neutron_event.dat") # Five logs are already present - print "Number of original logs =", len(ws.getRun().keys()) + print("Number of original logs = {}".format(len(ws.getRun().keys()))) phase_log = "Phase1" # Try to get a log that doesn't exist yet try: log = ws.getRun().getLogData(phase_log) except RuntimeError: - print phase_log, "log does not exist!" + print("{} log does not exist!".format(phase_log)) LoadNexusLogs(ws, "CNCS_7860_event.nxs") - print "Number of final logs =", len(ws.getRun().keys()) + print("Number of final logs = {}".format(len(ws.getRun().keys()))) # Try getting the log again try: log = ws.getRun().getLogData(phase_log) - print phase_log, "log size =", log.size() + print("{} log size = {}".format(phase_log, log.size())) except RuntimeError: - print phase_log, "log does not exist!" + print("{} log does not exist!".format(phase_log)) Output: diff --git a/docs/source/algorithms/LoadNexusMonitors-v1.rst b/docs/source/algorithms/LoadNexusMonitors-v1.rst index 7e9f0ee88517c8f8d4bf9b9afd6c1cbb08207057..8e8a3f6dfa259103c2e7516ede37a0e2a6c45bed 100644 --- a/docs/source/algorithms/LoadNexusMonitors-v1.rst +++ b/docs/source/algorithms/LoadNexusMonitors-v1.rst @@ -33,7 +33,7 @@ Usage ws = LoadNexusMonitors("CNCS_7860_event.nxs") # CNCS has 3 monitors - print "Number of monitors =", ws.getNumberHistograms() + print("Number of monitors = {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadNexusMonitors-v2.rst b/docs/source/algorithms/LoadNexusMonitors-v2.rst index fc5a63140681f987b124a554a3ebac0982abfa5a..9a6fda08a2f8e8c5dd5d487a349f14f59217d8b3 100644 --- a/docs/source/algorithms/LoadNexusMonitors-v2.rst +++ b/docs/source/algorithms/LoadNexusMonitors-v2.rst @@ -71,7 +71,7 @@ Usage ws = LoadNexusMonitors("CNCS_7860_event.nxs") # CNCS has 3 monitors - print "Number of monitors =", ws.getNumberHistograms() + print("Number of monitors = {}".format(ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadNexusProcessed-v1.rst b/docs/source/algorithms/LoadNexusProcessed-v1.rst index 5dbce6170e3d1ade12c93eacaefba0b95a6c9b29..d807be0ba03ed7892201de228c000218dd96036f 100644 --- a/docs/source/algorithms/LoadNexusProcessed-v1.rst +++ b/docs/source/algorithms/LoadNexusProcessed-v1.rst @@ -68,7 +68,7 @@ Usage wsOutput = LoadNexusProcessed(wsPath) - print CompareWorkspaces(ws,wsOutput, CheckInstrument=False)[0] + print(CompareWorkspaces(ws,wsOutput, CheckInstrument=False)[0]) os.remove(wsPath) diff --git a/docs/source/algorithms/LoadPreNexusMonitors-v1.rst b/docs/source/algorithms/LoadPreNexusMonitors-v1.rst index b39bb795ee197bba43b8902167f715d71f46a50c..4f45a04ca08fb7602824e37b7c0c3c8f18d78632 100644 --- a/docs/source/algorithms/LoadPreNexusMonitors-v1.rst +++ b/docs/source/algorithms/LoadPreNexusMonitors-v1.rst @@ -24,7 +24,7 @@ Usage # CNCS_7860_runinfo.xml references 3 beam monitor files. monitor_ws = LoadPreNexusMonitors("CNCS_7860_runinfo.xml") - print "The resulting workspace contains %i spectra -- one for each monitor." % monitor_ws.getNumberHistograms() + print("The resulting workspace contains {} spectra -- one for each monitor.".format(monitor_ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadRKH-v1.rst b/docs/source/algorithms/LoadRKH-v1.rst index 6e38d1600146be2ee494d3242adb44d6b342cb2a..08d8e4c84aeff3b2965044686cbefbf823d575cf 100644 --- a/docs/source/algorithms/LoadRKH-v1.rst +++ b/docs/source/algorithms/LoadRKH-v1.rst @@ -38,7 +38,7 @@ Usage SaveRKH(out_ws, file_path) in_ws = LoadRKH(file_path) - print "Contents of the file = " + str(in_ws.readY(0)) + print("Contents of the file = {}".format(in_ws.readY(0))) .. testcleanup:: ExSimpleSavingRoundtrip diff --git a/docs/source/algorithms/LoadRaw-v3.rst b/docs/source/algorithms/LoadRaw-v3.rst index 2ed1b9feb55c9624aa6b0250d7a7826f6b0aa4a5..4a67346b1de281decacb0786fc5ed0f551872be6 100644 --- a/docs/source/algorithms/LoadRaw-v3.rst +++ b/docs/source/algorithms/LoadRaw-v3.rst @@ -82,15 +82,15 @@ Example 1: using defaults # Load a RAW file using all defaults ws = Load('HRP39180.RAW') - print 'Workspace has',ws.getNumberHistograms(),'spectra' + print('Workspace has {} spectra'.format(ws.getNumberHistograms())) # Get a detector in histogram 1024 of the workspace detid = ws.getSpectrum(1024).getDetectorIDs()[0] - print 'Is detector',detid,'a monitor?',ws.getInstrument().getDetector(detid).isMonitor() + print('Is detector {} a monitor? {}'.format(detid, ws.getInstrument().getDetector(detid).isMonitor())) # Get the Run object run = ws.run() - print 'Workspace contains',len(run.keys()),'logs' - print 'Workspace has property INT1:',run.hasProperty('INT1') + print('Workspace contains {} logs'.format(len(run.keys()))) + print('Workspace has property INT1: {}'.format(run.hasProperty('INT1'))) Output ^^^^^^ @@ -110,15 +110,15 @@ Example 2: load without the logs # Load a RAW file without the logs ws = Load('HRP39180.RAW',LoadLogFiles=False) - print 'Workspace has',ws.getNumberHistograms(),'spectra' + print('Workspace has {} spectra'.format(ws.getNumberHistograms())) # Get a detector in histogram 1024 of the workspace detid = ws.getSpectrum(1024).getDetectorIDs()[0] - print 'Is detector',detid,'a monitor?',ws.getInstrument().getDetector(detid).isMonitor() + print('Is detector {} a monitor? {}'.format(detid, ws.getInstrument().getDetector(detid).isMonitor())) # Get the Run object run = ws.run() - print 'Workspace contains',len(run.keys()),'logs' - print 'Workspace has property INT1:',run.hasProperty('INT1') + print('Workspace contains {} logs'.format(len(run.keys()))) + print('Workspace has property INT1: {}'.format(run.hasProperty('INT1'))) Output ^^^^^^ @@ -137,15 +137,15 @@ Example 3: exclude monitors # Load a RAW file without the monitors ws = Load('HRP39180.RAW',LoadMonitors='Exclude') - print 'Workspace has',ws.getNumberHistograms(),'spectra' + print('Workspace has {} spectra'.format(ws.getNumberHistograms())) # Get a detector in histogram 1024 of the workspace detid = ws.getSpectrum(1024).getDetectorIDs()[0] - print 'Is detector',detid,'a monitor?',ws.getInstrument().getDetector(detid).isMonitor() + print('Is detector {} a monitor? {}'.format(detid, ws.getInstrument().getDetector(detid).isMonitor())) # Get the Run object run = ws.run() - print 'Workspace contains',len(run.keys()),'logs' - print 'Workspace has property INT1:',run.hasProperty('INT1') + print('Workspace contains {} logs'.format(len(run.keys()))) + print('Workspace has property INT1: {}'.format(run.hasProperty('INT1'))) Output ^^^^^^ @@ -164,16 +164,16 @@ Example 4: load monitors separately # Load a RAW file, load the monitors into a separate workspace dataws,monitorws = Load('HRP39180.RAW',LoadMonitors='Separate') - print 'Data workspace has',dataws.getNumberHistograms(),'spectra' + print('Data workspace has {} spectra'.format(dataws.getNumberHistograms())) - print 'Monitor workspace has',monitorws.getNumberHistograms(),'spectra' + print('Monitor workspace has {} spectra'.format(monitorws.getNumberHistograms())) # Check that the detector in the first histogram of the monitor workspace is a monitor detid = monitorws.getSpectrum(0).getDetectorIDs()[0] - print 'Is detector',detid,'a monitor?',monitorws.getInstrument().getDetector(detid).isMonitor() + print('Is detector {} a monitor? {}'.format(detid, monitorws.getInstrument().getDetector(detid).isMonitor())) # Check that the detector in the second histogram of the monitor workspace is a monitor detid = monitorws.getSpectrum(1).getDetectorIDs()[0] - print 'Is detector',detid,'a monitor?',monitorws.getInstrument().getDetector(detid).isMonitor() + print('Is detector {} a monitor? {}'.format(detid, monitorws.getInstrument().getDetector(detid).isMonitor())) Output ^^^^^^ diff --git a/docs/source/algorithms/LoadRawBin0-v1.rst b/docs/source/algorithms/LoadRawBin0-v1.rst index 9b1a7f32593467b643caeb656f18a2e6fbb49b96..ac383e40ef00c66c35b8823e828f89a16dfad398 100644 --- a/docs/source/algorithms/LoadRawBin0-v1.rst +++ b/docs/source/algorithms/LoadRawBin0-v1.rst @@ -25,7 +25,7 @@ Usage bin_zeroes = LoadRawBin0("IRS21360.raw") total = SumSpectra(bin_zeroes) - print "Bin0 contained %i counts." % total.readY(0)[0] + print("Bin0 contained {:.0f} counts.".format(total.readY(0)[0])) Output: diff --git a/docs/source/algorithms/LoadRawSpectrum0-v1.rst b/docs/source/algorithms/LoadRawSpectrum0-v1.rst index 1d964fe7e5869909d83a311f5e10df4b024c5680..93003f14ec466cb65b08e21e83bcf88578677809 100644 --- a/docs/source/algorithms/LoadRawSpectrum0-v1.rst +++ b/docs/source/algorithms/LoadRawSpectrum0-v1.rst @@ -25,7 +25,7 @@ Usage wsOut = LoadRawSpectrum0('HRP39180.RAW') wsIntegral = Integration(wsOut) - print ("Spectrum0 contained %i counts" % wsIntegral.readY(0)[0]) + print("Spectrum0 contained {:.0f} counts".format(wsIntegral.readY(0)[0])) Output: diff --git a/docs/source/algorithms/LoadSESANS-v1.rst b/docs/source/algorithms/LoadSESANS-v1.rst index 757143e7bd64a1f02271bb3af2b7da27c9713b5c..eb1ca8b16b0d595cb68cf676ce1680efb65c63a5 100644 --- a/docs/source/algorithms/LoadSESANS-v1.rst +++ b/docs/source/algorithms/LoadSESANS-v1.rst @@ -40,7 +40,7 @@ Usage # Retrieve loaded workspace from ADS in_ws = mtd["in_ws"] - print("Y values of loaded workspace = " + str(in_ws.readY(0))) + print("Y values of loaded workspace = {}".format(in_ws.readY(0))) .. testcleanup:: LoadSESANSRoundTrip diff --git a/docs/source/algorithms/LoadSINQ-v1.rst b/docs/source/algorithms/LoadSINQ-v1.rst index 6a8e12a3799ab928dd70c1ef2425f36b150e4ec0..87fbda9bf56c58e87b599f04210077a0f7efb957 100644 --- a/docs/source/algorithms/LoadSINQ-v1.rst +++ b/docs/source/algorithms/LoadSINQ-v1.rst @@ -27,7 +27,7 @@ The following usage example loads a POLDI data file using the instrument name, y poldi_data = LoadSINQ(Instrument = "POLDI", Year = 2013, Numor = 6904) - print "Poldi sample 6904 has", poldi_data.getNumberHistograms(), "histograms." + print("Poldi sample 6904 has {} histograms.".format(poldi_data.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadSINQFile-v1.rst b/docs/source/algorithms/LoadSINQFile-v1.rst index b7a6bf7f0d6b7156bf148e5d6ec8ee8e5668b8c7..44fce4dd38fbdacdcfb7f0fac8b2823cc4c07e1e 100644 --- a/docs/source/algorithms/LoadSINQFile-v1.rst +++ b/docs/source/algorithms/LoadSINQFile-v1.rst @@ -24,7 +24,7 @@ Usage poldi_data = LoadSINQFile(Filename = "poldi2013n006904.hdf", Instrument = "POLDI") - print "Poldi sample 6904 has", poldi_data.getNumberHistograms(), "histograms." + print("Poldi sample 6904 has {} histograms.".format(poldi_data.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadSINQFocus-v1.rst b/docs/source/algorithms/LoadSINQFocus-v1.rst index 993beba527742e6b5a46da3c79c2aeb7f315bf9b..c9693e0b067244a31d2accb9686b9da2b0de0884 100644 --- a/docs/source/algorithms/LoadSINQFocus-v1.rst +++ b/docs/source/algorithms/LoadSINQFocus-v1.rst @@ -28,8 +28,8 @@ The following example script loads a data file obtained at the FOCUS instrument focus_2906 = LoadSINQFocus('focus2014n002906.hdf') # Print out some information - print "Sample title:", focus_2906.getTitle() - print "Number of spectra:", focus_2906.getNumberHistograms() + print("Sample title: {}".format(focus_2906.getTitle())) + print("Number of spectra: {}".format(focus_2906.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/LoadSPE-v1.rst b/docs/source/algorithms/LoadSPE-v1.rst index 941084c966c6fcadbba28dce7d9a6d354cc9f646..cd8acb3fcbab83a6c1bb001a62ba8273797dc860 100644 --- a/docs/source/algorithms/LoadSPE-v1.rst +++ b/docs/source/algorithms/LoadSPE-v1.rst @@ -27,8 +27,8 @@ Usage #If it's in your managed user directories there's no need for an absolute path ws1 = LoadSPE("Example.spe") - print "Number of Spectra:", ws1.getNumberHistograms() - print "Number of Bins:", ws1.blocksize() + print("Number of Spectra: {}".format(ws1.getNumberHistograms())) + print("Number of Bins: {}".format(ws1.blocksize())) Output: diff --git a/docs/source/algorithms/LoadSQW-v1.rst b/docs/source/algorithms/LoadSQW-v1.rst index 4f2f63dd6ff6ed47e657ddbc1230c37d1cfac4fb..2420f3498c19dd5bb0266a521e15edffdcd112b6 100644 --- a/docs/source/algorithms/LoadSQW-v1.rst +++ b/docs/source/algorithms/LoadSQW-v1.rst @@ -180,8 +180,8 @@ Usage mdws = LoadSQW('test_horace_reader.sqw'); # Check results - print "Workspace type is: ",mdws.id() - print "Workspace has:{0:2} dimensions and contains: {1:4} MD events".format(mdws.getNumDims(),mdws.getNEvents()) + print("Workspace type is: {}".format(mdws.id())) + print("Workspace has:{0:2} dimensions and contains: {1:4} MD events".format(mdws.getNumDims(),mdws.getNEvents())) Output: diff --git a/docs/source/algorithms/LoadSampleDetailsFromRaw-v1.rst b/docs/source/algorithms/LoadSampleDetailsFromRaw-v1.rst index 8d394327da15ed05092da0816047099c27e30b93..2b92c0b7005dbc1ab7b671e7c6e7e30d30cacf65 100644 --- a/docs/source/algorithms/LoadSampleDetailsFromRaw-v1.rst +++ b/docs/source/algorithms/LoadSampleDetailsFromRaw-v1.rst @@ -39,8 +39,8 @@ Usage LoadSampleDetailsFromRaw(ws,filename) s = ws.sample() - print "Geometry flag %.0f" % s.getGeometryFlag() - print "Dimensions H,W,D %.0f,%.0f,%.0f" % (s.getHeight(),s.getWidth(),s.getThickness()) + print("Geometry flag {:.0f}".format(s.getGeometryFlag())) + print("Dimensions H,W,D {:.0f},{:.0f},{:.0f}".format(s.getHeight(),s.getWidth(),s.getThickness())) Output: diff --git a/docs/source/algorithms/LoadSassena-v1.rst b/docs/source/algorithms/LoadSassena-v1.rst index f9b56522b7fd52eca4df662822e5cd674dfe4e59..0680ea202de148432432798afba5d5e5048cc9e5 100644 --- a/docs/source/algorithms/LoadSassena-v1.rst +++ b/docs/source/algorithms/LoadSassena-v1.rst @@ -56,7 +56,7 @@ Usage from __future__ import print_function ws = LoadSassena("loadSassenaExample.h5", TimeUnit=1.0) - print('workspaces instantiated: ', ', '.join(ws.getNames())) + print('workspaces instantiated: {}'.format(', '.join(ws.getNames()))) fqtReal = ws[1] # Real part of F(Q,t) # Let's fit it to a Gaussian. We start with an initial guess intensity = 0.5 @@ -71,13 +71,13 @@ Usage paramTable = fit_output.OutputParameters # table containing the optimal fit parameters fitWorkspace = fit_output.OutputWorkspace - print("The fit was: " + fit_output.OutputStatus) - print("Fitted Height value is: %.2f" % paramTable.column(1)[0]) - print("Fitted centre value is: %.2f" % abs(paramTable.column(1)[1])) - print("Fitted sigma value is: %.1f" % paramTable.column(1)[2]) + print("The fit was: {}".format(fit_output.OutputStatus)) + print("Fitted Height value is: {:.2f}".format(paramTable.column(1)[0])) + print("Fitted centre value is: {:.2f}".format(abs(paramTable.column(1)[1]))) + print("Fitted sigma value is: {:.1f}".format(paramTable.column(1)[2])) # fitWorkspace contains the data, the calculated and the difference patterns - print("Number of spectra in fitWorkspace is: " + str(fitWorkspace.getNumberHistograms())) - print("The 989th y-value of the fitted curve: %.3f" % fitWorkspace.readY(1)[989]) + print("Number of spectra in fitWorkspace is: {}".format(fitWorkspace.getNumberHistograms())) + print("The 989th y-value of the fitted curve: {:.3f}".format(fitWorkspace.readY(1)[989])) Output: diff --git a/docs/source/algorithms/LoadSpiceAscii-v1.rst b/docs/source/algorithms/LoadSpiceAscii-v1.rst index 589da7a30c83875e02442fb6078dc7e3bb40f440..93662c3b27203045c4e341728568139c4f079539 100644 --- a/docs/source/algorithms/LoadSpiceAscii-v1.rst +++ b/docs/source/algorithms/LoadSpiceAscii-v1.rst @@ -53,15 +53,16 @@ Usage datatbws = mtd['HB2A_0231_0001_Data'] infows = mtd['HB2A_0231_Info'] - print "Number of measuring points = %d" % (datatbws.rowCount()) - print "Number of columns in data workspace = %d" % (datatbws.columnCount()) + print("Number of measuring points = {}".format(datatbws.rowCount())) + print("Number of columns in data workspace = {}".format(datatbws.columnCount())) propertylist = infows.getRun().getProperties() - print "Number of run information = %d" % (len(propertylist)) - for i in xrange(len(propertylist)): - print "Property %d: Name = %-20s." % (i, propertylist[i].name) - print "Sum of Counts = %d" % (infows.getRun().getProperty("Sum of Counts").value) - print "Center of Mass = %.5f +/- %.5f" % (infows.getRun().getProperty("Center of Mass").value, - infows.getRun().getProperty("Center of Mass.error").value) + print("Number of run information = {}".format(len(propertylist))) + for i in range(len(propertylist)): + print("Property {}: Name = {}".format(i, propertylist[i].name)) + print("Sum of Counts = {}".format(infows.getRun().getProperty("Sum of Counts").value)) + print("Center of Mass = {:.5f} +/- {:.5f}".format( + infows.getRun().getProperty("Center of Mass").value, + infows.getRun().getProperty("Center of Mass.error").value)) .. testcleanup:: ExLoadHB2AData @@ -75,41 +76,41 @@ Output: Number of measuring points = 61 Number of columns in data workspace = 70 Number of run information = 35 - Property 0: Name = Center of Mass . - Property 1: Name = Center of Mass.error. - Property 2: Name = Full Width Half-Maximum. - Property 3: Name = Full Width Half-Maximum.error. - Property 4: Name = Sum of Counts . - Property 5: Name = analyzer . - Property 6: Name = builtin_command . - Property 7: Name = col_headers . - Property 8: Name = collimation . - Property 9: Name = command . - Property 10: Name = date . - Property 11: Name = def_x . - Property 12: Name = def_y . - Property 13: Name = experiment . - Property 14: Name = experiment_number . - Property 15: Name = latticeconstants . - Property 16: Name = local_contact . - Property 17: Name = mode . - Property 18: Name = monochromator . - Property 19: Name = preset_channel . - Property 20: Name = preset_type . - Property 21: Name = preset_value . - Property 22: Name = proposal . - Property 23: Name = runend . - Property 24: Name = samplemosaic . - Property 25: Name = samplename . - Property 26: Name = sampletype . - Property 27: Name = scan . - Property 28: Name = scan_title . - Property 29: Name = sense . - Property 30: Name = time . - Property 31: Name = ubconf . - Property 32: Name = ubmatrix . - Property 33: Name = users . - Property 34: Name = run_start . + Property 0: Name = Center of Mass + Property 1: Name = Center of Mass.error + Property 2: Name = Full Width Half-Maximum + Property 3: Name = Full Width Half-Maximum.error + Property 4: Name = Sum of Counts + Property 5: Name = analyzer + Property 6: Name = builtin_command + Property 7: Name = col_headers + Property 8: Name = collimation + Property 9: Name = command + Property 10: Name = date + Property 11: Name = def_x + Property 12: Name = def_y + Property 13: Name = experiment + Property 14: Name = experiment_number + Property 15: Name = latticeconstants + Property 16: Name = local_contact + Property 17: Name = mode + Property 18: Name = monochromator + Property 19: Name = preset_channel + Property 20: Name = preset_type + Property 21: Name = preset_value + Property 22: Name = proposal + Property 23: Name = runend + Property 24: Name = samplemosaic + Property 25: Name = samplename + Property 26: Name = sampletype + Property 27: Name = scan + Property 28: Name = scan_title + Property 29: Name = sense + Property 30: Name = time + Property 31: Name = ubconf + Property 32: Name = ubmatrix + Property 33: Name = users + Property 34: Name = run_start Sum of Counts = 1944923 Center of Mass = 9.00076 +/- 0.00921 diff --git a/docs/source/algorithms/LoadSpiceXML2DDet-v1.rst b/docs/source/algorithms/LoadSpiceXML2DDet-v1.rst index 68f8a43df094ee532d8290deee27eedd4a2b3e7a..05c83f510107ec310106c991f10128ae8dc6cc08 100644 --- a/docs/source/algorithms/LoadSpiceXML2DDet-v1.rst +++ b/docs/source/algorithms/LoadSpiceXML2DDet-v1.rst @@ -100,9 +100,9 @@ Usage # Access output workspace and print out some result ws = mtd["s0001_0522"] - print "Number of spectrum = %d." % (ws.getNumberHistograms()) + print("Number of spectrum = {}.".format(ws.getNumberHistograms())) for i, j in [(0, 0), (255, 255), (136, 140), (143, 140)]: - print "Y[%-3d, %-3d] = %.5f" % (i, j, ws.readY(i)[j]) + print("Y[{:<3}, {:<3}] = {:.5f}".format(i, j, ws.readY(i)[j])) .. testcleanup:: ExLoadHB3AXMLData diff --git a/docs/source/algorithms/LoadVesuvio-v1.rst b/docs/source/algorithms/LoadVesuvio-v1.rst index d10e75aa46ab1a816572c925e8f4595b5e0f7814..9adc889a649ba374b84f8c904aaee834e0774cd0 100644 --- a/docs/source/algorithms/LoadVesuvio-v1.rst +++ b/docs/source/algorithms/LoadVesuvio-v1.rst @@ -103,7 +103,7 @@ Usage tof = LoadVesuvio("14188",SpectrumList=135) - print "Number of spectra:", tof.getNumberHistograms() + print("Number of spectra: {}".format(tof.getNumberHistograms())) Output:: @@ -115,7 +115,7 @@ Output:: tof = LoadVesuvio("14188-14193",SpectrumList=135) - print "Number of spectra:", tof.getNumberHistograms() + print("Number of spectra: {}".format(tof.getNumberHistograms())) Output:: @@ -127,7 +127,7 @@ Output:: tof = LoadVesuvio("14188-14193",SpectrumList="135-142") - print "Number of spectra:", tof.getNumberHistograms() + print("Number of spectra: {}".format(tof.getNumberHistograms())) Output:: @@ -139,7 +139,7 @@ Output:: tof = LoadVesuvio("14188-14193",SpectrumList="135-142", SumSpectra=True) - print "Number of spectra:", tof.getNumberHistograms() + print("Number of spectra: {}".format(tof.getNumberHistograms())) Output:: @@ -152,7 +152,7 @@ Output:: tof = LoadVesuvio("14188-14193",SpectrumList="135-142", SumSpectra=True, Mode="SingleDifference") - print "Number of spectra:", tof.getNumberHistograms() + print("Number of spectra: {}".format(tof.getNumberHistograms())) Output:: diff --git a/docs/source/algorithms/LoadVisionElasticBS-v1.rst b/docs/source/algorithms/LoadVisionElasticBS-v1.rst index 45608eed77dd9a7a487c61d8337a7ee9fe6b0900..2767b3a719dc8e57f337fb01b8a9f113d4c9c63a 100644 --- a/docs/source/algorithms/LoadVisionElasticBS-v1.rst +++ b/docs/source/algorithms/LoadVisionElasticBS-v1.rst @@ -21,7 +21,7 @@ Usage w1 = LoadVisionElasticBS("VIS_19351.nxs.h5") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: @@ -33,7 +33,7 @@ Usage w1 = LoadVisionElasticBS("VIS_19351.nxs.h5",Banks="bank20") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: diff --git a/docs/source/algorithms/LoadVisionElasticEQ-v1.rst b/docs/source/algorithms/LoadVisionElasticEQ-v1.rst index fd77a4ad9e7f251570d979d71fc9795687749bb0..bb175164fc2167a97e8a8010e7c49a7ee2f9b2d0 100644 --- a/docs/source/algorithms/LoadVisionElasticEQ-v1.rst +++ b/docs/source/algorithms/LoadVisionElasticEQ-v1.rst @@ -21,7 +21,7 @@ Usage w1 = LoadVisionElasticEQ("VIS_19351.nxs.h5") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: @@ -33,7 +33,7 @@ Usage w1 = LoadVisionElasticEQ("VIS_19351.nxs.h5",Banks="bank29") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: diff --git a/docs/source/algorithms/LoadVisionInelastic-v1.rst b/docs/source/algorithms/LoadVisionInelastic-v1.rst index ce2f688244f8085a1837ed69e927846bf4b67833..30a39cdd2ce7dbacfce520fa089089cb3ad81805 100644 --- a/docs/source/algorithms/LoadVisionInelastic-v1.rst +++ b/docs/source/algorithms/LoadVisionInelastic-v1.rst @@ -21,7 +21,7 @@ Usage w1 = LoadVisionInelastic("VIS_19351.nxs.h5") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: @@ -33,7 +33,7 @@ Usage w1 = LoadVisionInelastic("VIS_19351.nxs.h5",Banks="forward") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: @@ -45,7 +45,7 @@ Usage w1 = LoadVisionInelastic("VIS_19351.nxs.h5",Banks="backward,bank3") - print "Number of spectra:", w1.getNumberHistograms() + print("Number of spectra: {}".format(w1.getNumberHistograms())) .. testoutput:: diff --git a/docs/source/algorithms/LoadVulcanCalFile-v1.rst b/docs/source/algorithms/LoadVulcanCalFile-v1.rst index 3777b67d3e15c706196e89889ddbe958e96fbe47..0a10aab6597bf773a8f5be3bef663e4a0b51e0da 100644 --- a/docs/source/algorithms/LoadVulcanCalFile-v1.rst +++ b/docs/source/algorithms/LoadVulcanCalFile-v1.rst @@ -90,9 +90,9 @@ Usage offsetws = mtd["Vulcan_idl_offsets"] groupws = mtd["Vulcan_idl_group"] for iws in [0, 100, 1000, 3500, 7000]: - print "Spectrum %-5d Offset = %.5f of Group %d" % (iws, offsetws.readY(iws)[0], groupws.readY(iws)[0]) + print("Spectrum {:<5} Offset = {:.5f} of Group {:.0f}".format(iws, offsetws.readY(iws)[0], groupws.readY(iws)[0])) maskws = mtd["Vulcan_idl_mask"] - print "Size of mask workspace = %d" % (maskws.getNumberHistograms()) + print("Size of mask workspace = {}".format(maskws.getNumberHistograms())) .. testcleanup:: diff --git a/docs/source/algorithms/Mean-v1.rst b/docs/source/algorithms/Mean-v1.rst index ae79c7182c6224f1aca38bf72a1a126fabc807b9..feb5e3398a26b97c3560c43bef436618138fbfa4 100644 --- a/docs/source/algorithms/Mean-v1.rst +++ b/docs/source/algorithms/Mean-v1.rst @@ -21,7 +21,7 @@ where *m* is the output workspace. The *x* values are copied from the first inpu Restrictions ############ -All input workspaces must have the same shape. +All input workspaces must have the same shape and the x axis must be in the same order. Usage: ------ diff --git a/docs/source/algorithms/ModifyDetectorDotDatFile-v1.rst b/docs/source/algorithms/ModifyDetectorDotDatFile-v1.rst index 77804e6c1579932094faeb5ab041b56fc0184897..58aef3d2ae23e4938044711b203dbd9da31410da 100644 --- a/docs/source/algorithms/ModifyDetectorDotDatFile-v1.rst +++ b/docs/source/algorithms/ModifyDetectorDotDatFile-v1.rst @@ -53,7 +53,7 @@ Usage ModifyDetectorDotDatFile(ws_1, "detector_1.dat", newFile) # Check the output file - print "File Exists:", os.path.exists(newFile) + print("File Exists: {}".format(os.path.exists(newFile))) f = open( newFile, 'r' ) file = f.read().split('\n') @@ -62,7 +62,7 @@ Usage for line in file[0:4]: # print the line truncating before system dependent line break can take effect # also stripping off any trailing spaces - print line[0:89].rstrip() + print(line[0:89].rstrip()) Output: diff --git a/docs/source/algorithms/MolDyn-v1.rst b/docs/source/algorithms/MolDyn-v1.rst index b374a7d5f097963bcd1b6e84cc24b3083bb0c87b..c29281247027363568e038e75c510a95534e1b73 100644 --- a/docs/source/algorithms/MolDyn-v1.rst +++ b/docs/source/algorithms/MolDyn-v1.rst @@ -42,7 +42,7 @@ Usage Functions=['Fqt-total', 'Sqw-total']) for ws_name in out_ws_group.getNames(): - print ws_name + print(ws_name) Output: diff --git a/docs/source/algorithms/MonitorEfficiencyCorUser-v1.rst b/docs/source/algorithms/MonitorEfficiencyCorUser-v1.rst index afcd06af770de77852340d1a1451f3dbf341b11d..abb4a94a46c45fc407e621339586530975ded2f6 100644 --- a/docs/source/algorithms/MonitorEfficiencyCorUser-v1.rst +++ b/docs/source/algorithms/MonitorEfficiencyCorUser-v1.rst @@ -39,17 +39,17 @@ Usage wsSample = LoadMLZ(Filename='TOFTOFTestdata.nxs') wsNorm = MonitorEfficiencyCorUser(wsSample ) # Input and output workspaces have the same structure - print 'Number of histograms of the input and output workspaces:' - print wsSample.getNumberHistograms(), wsNorm.getNumberHistograms() - print 'Number of time channels of the input an output workspaces:' - print wsSample.blocksize(), wsNorm.blocksize() + print('Number of histograms of the input and output workspaces:') + print('{} {}'.format(wsSample.getNumberHistograms(), wsNorm.getNumberHistograms())) + print('Number of time channels of the input an output workspaces:') + print('{} {}'.format( wsSample.blocksize(), wsNorm.blocksize())) # Check calculation of normalisation coefficient between input and output workspaces wsCheck = Divide(wsSample,wsNorm) - print "Coefficient of proportionality between Input and Output of MonitorEfficiencyCorUser algorithm: %5.3f" % wsCheck.readY(102)[1] + print("Coefficient of proportionality between Input and Output of MonitorEfficiencyCorUser algorithm: {:.3f}".format(wsCheck.readY(102)[1])) # Read the values of the incident energy and of the monitor counts from the SampleLogs of wsSample monitor_counts = float(mtd['wsSample'].getRun().getLogData('monitor_counts').value) Ei = float(mtd['wsSample'].getRun().getLogData('Ei').value) - print "Coefficient from theoretical formula = monitor_counts * sqrt(Ei/25.3): %5.3f" % (monitor_counts*np.sqrt(Ei/25.3)) + print("Coefficient from theoretical formula = monitor_counts * sqrt(Ei/25.3): {:.3f}".format(monitor_counts*np.sqrt(Ei/25.3))) Output: diff --git a/docs/source/algorithms/MoveInstrumentComponent-v1.rst b/docs/source/algorithms/MoveInstrumentComponent-v1.rst index 06586de4cb79608d29b14aad5f1012f7487c618b..579eca2db371c6903bfb701ea2092d0da0c954bb 100644 --- a/docs/source/algorithms/MoveInstrumentComponent-v1.rst +++ b/docs/source/algorithms/MoveInstrumentComponent-v1.rst @@ -42,25 +42,25 @@ Example 1: Move a component by name ws = CreateSampleWorkspace() # Original position of instrument component 'bank1' - print ws.getInstrument().getComponentByName('bank1').getPos() + print(ws.getInstrument().getComponentByName('bank1').getPos()) # Move 'bank1' by vector (1,0,0) relative to its original position MoveInstrumentComponent( ws, 'bank1', X=1,Y=0,Z=0 ) # Check the new position of 'bank1' - print ws.getInstrument().getComponentByName('bank1').getPos() + print(ws.getInstrument().getComponentByName('bank1').getPos()) # Move the same bank again by vector (2,0,0) MoveInstrumentComponent( ws, 'bank1', X=2,Y=0,Z=0 ) # Check the new position of 'bank1' - print ws.getInstrument().getComponentByName('bank1').getPos() + print(ws.getInstrument().getComponentByName('bank1').getPos()) # Move 'bank1' to a new absolute position (1,2,3) MoveInstrumentComponent( ws, 'bank1', X=1,Y=2,Z=3, RelativePosition=False ) # Check the new position of 'bank1' - print ws.getInstrument().getComponentByName('bank1').getPos() + print(ws.getInstrument().getComponentByName('bank1').getPos()) Output ^^^^^^ @@ -93,13 +93,13 @@ Example 2: Move a detector by ID ws = mtd['musr_1'] # Original position of detector 33 - print ws.getInstrument().getDetector(33).getPos() + print(ws.getInstrument().getDetector(33).getPos()) # Move detector 33 by vector (1,0,0) relative to its original position MoveInstrumentComponent( ws, DetectorID=33, X=1,Y=0,Z=0 ) # Check the new position of detector 33 - print ws.getInstrument().getDetector(33).getPos() + print(ws.getInstrument().getDetector(33).getPos()) Output ^^^^^^ diff --git a/docs/source/algorithms/MultipleScatteringCylinderAbsorption-v1.rst b/docs/source/algorithms/MultipleScatteringCylinderAbsorption-v1.rst index 1a8ac31cb896dd389b993dfc4493a49cf25037af..8ba34d07e087a113f0bbc3aa19e87538c15bdb94 100644 --- a/docs/source/algorithms/MultipleScatteringCylinderAbsorption-v1.rst +++ b/docs/source/algorithms/MultipleScatteringCylinderAbsorption-v1.rst @@ -51,7 +51,7 @@ Usage #restrict the number of wavelength points to speed up the example wsOut = MultipleScatteringCylinderAbsorption(ws,CylinderSampleRadius=0.2) - print "Output: ", wsOut.readY(0) + print("Output: {}".format(wsOut.readY(0))) Output: diff --git a/docs/source/algorithms/Multiply-v1.rst b/docs/source/algorithms/Multiply-v1.rst index c762700441d8d33c98bf5490376b14fe0d9a8f76..b8eb73ac9f9e53b0902a85c4f9df9b2cec7795f6 100644 --- a/docs/source/algorithms/Multiply-v1.rst +++ b/docs/source/algorithms/Multiply-v1.rst @@ -39,9 +39,9 @@ Usage # perform the algorithm ws = Multiply(ws1, ws2) - print "The X values are: " + str(ws.readX(0)) - print "The Y values are: " + str(ws.readY(0)) - print "The updated Error values are: " + str(ws.readE(0)) + print("The X values are: {}".format(ws.readX(0))) + print("The Y values are: {}".format(ws.readY(0))) + print("The updated Error values are: {}".format(ws.readE(0))) Output: @@ -69,9 +69,9 @@ Output: # perform the algorithm ws = ws1 * ws2 - print "The X values are: " + str(ws.readX(0)) - print "The Y values are: " + str(ws.readY(0)) - print "The updated Error values are: " + str(ws.readE(0)) + print("The X values are: {}".format(ws.readX(0))) + print("The Y values are: {}".format(ws.readY(0))) + print("The updated Error values are: {}".format(ws.readE(0))) Output: @@ -99,9 +99,9 @@ Output: # perform the algorithm ws *= ws1 - print "The X values are: " + str(ws.readX(0)) - print "The Y values are: " + str(ws.readY(0)) - print "The updated Error values are: " + str(ws.readE(0)) + print("The X values are: {}".format(ws.readX(0))) + print("The Y values are: {}".format(ws.readY(0))) + print("The updated Error values are: {}".format(ws.readE(0))) Output: @@ -125,9 +125,9 @@ Output: # perform the algorithm ws = ws1 * 2.5 - print "The X values are: " + str(ws.readX(0)) - print "The Y values are: " + str(ws.readY(0)) - print "The updated Error values are: " + str(ws.readE(0)) + print("The X values are: {}".format(ws.readX(0))) + print("The Y values are: {}".format(ws.readY(0))) + print("The updated Error values are: {}".format(ws.readE(0))) Output: diff --git a/docs/source/algorithms/MultiplyRange-v1.rst b/docs/source/algorithms/MultiplyRange-v1.rst index e5dced2f1a05b2eba6f3d8b3d823e91d473c6ec6..fe72fcb0080c2408bf2421e54cbce970bb7d2b65 100644 --- a/docs/source/algorithms/MultiplyRange-v1.rst +++ b/docs/source/algorithms/MultiplyRange-v1.rst @@ -27,9 +27,9 @@ Usage yres = res.readY(0) # Print out the ratios yres[i] / y[i] for bins with indices 20 to 30 - print yres[20:30] / y[20:30] + print(yres[20:30] / y[20:30]) # Print out the ratios yres[i] / y[i] for bins with indices 70 to 80 - print yres[70:80] / y[70:80] + print(yres[70:80] / y[70:80]) Output ###### diff --git a/docs/source/algorithms/MuonGroupDetectors-v1.rst b/docs/source/algorithms/MuonGroupDetectors-v1.rst index d91570f70f949365c06bdc15a651e73573618ba3..dcf6a7d1d765a0f8a7e414772b3afa21c46dfea1 100644 --- a/docs/source/algorithms/MuonGroupDetectors-v1.rst +++ b/docs/source/algorithms/MuonGroupDetectors-v1.rst @@ -45,10 +45,10 @@ Usage grouped = MuonGroupDetectors('ws', 'grouping') - print 'No. of spectra in grouped workspace:', grouped.getNumberHistograms() - print 'Detectors grouped in spectra 0:', list(grouped.getSpectrum(0).getDetectorIDs()) - print 'Detectors grouped in spectra 1:', list(grouped.getSpectrum(1).getDetectorIDs()) - print 'Detectors grouped in spectra 2:', list(grouped.getSpectrum(2).getDetectorIDs()) + print('No. of spectra in grouped workspace: {}'.format(grouped.getNumberHistograms())) + print('Detectors grouped in spectra 0: {}'.format(list(grouped.getSpectrum(0).getDetectorIDs()))) + print('Detectors grouped in spectra 1: {}'.format(list(grouped.getSpectrum(1).getDetectorIDs()))) + print('Detectors grouped in spectra 2: {}'.format(list(grouped.getSpectrum(2).getDetectorIDs()))) Output: @@ -73,9 +73,9 @@ Output: # Use grouping from one file to group data from different file grouped = MuonGroupDetectors('ws', 'grouping') - print 'No. of periods loaded:', grouped.size() - print 'No. of grouped spectra in first period:', grouped.getItem(0).getNumberHistograms() - print 'No. of grouped spectra in second period:', grouped.getItem(1).getNumberHistograms() + print('No. of periods loaded: {}'.format(grouped.size())) + print('No. of grouped spectra in first period: {}'.format(grouped.getItem(0).getNumberHistograms())) + print('No. of grouped spectra in second period: {}'.format(grouped.getItem(1).getNumberHistograms())) Output: diff --git a/docs/source/algorithms/MuonProcess-v1.rst b/docs/source/algorithms/MuonProcess-v1.rst index b63c4d291ce71f74eb107689f26d319fe3a6aea3..460e2348cfd2e1ada5e070dee427da5b10c6babf 100644 --- a/docs/source/algorithms/MuonProcess-v1.rst +++ b/docs/source/algorithms/MuonProcess-v1.rst @@ -99,7 +99,7 @@ Usage processed = mtd['MuonProcess_output'] output_int = Integration(processed) - print 'Integrated asymmetry for the run: {0:.3f}'.format(output_int.readY(0)[0]) + print('Integrated asymmetry for the run: {0:.3f}'.format(output_int.readY(0)[0])) Output: @@ -132,7 +132,7 @@ Output: PairSecondIndex = 0, Alpha = 0.5) - print 'Output:', output.readY(0) + print('Output: {}'.format(output.readY(0))) Output: @@ -172,7 +172,7 @@ Output: OutputType = 'GroupAsymmetry', GroupIndex = 0,Xmin=0,Xmax=4) - print 'Output:', output.readY(0) + print('Output: {}'.format(output.readY(0))) Output: diff --git a/docs/source/algorithms/MuscatSofQW-v1.rst b/docs/source/algorithms/MuscatSofQW-v1.rst index c44b62025d90d1c754643c28753171b313418326..692b2bb76c7eaaeb7aabb787ff70d4a955536919 100644 --- a/docs/source/algorithms/MuscatSofQW-v1.rst +++ b/docs/source/algorithms/MuscatSofQW-v1.rst @@ -44,9 +44,9 @@ Usage ResolutionWorkspace=resolution, ParameterWorkspace=parameters) - print 'S(Q, w) workspace is intensity as a function of {0} and {1}'.format( + print('S(Q, w) workspace is intensity as a function of {0} and {1}'.format( sqw.getAxis(0).getUnit().unitID(), - sqw.getAxis(1).getUnit().unitID()) + sqw.getAxis(1).getUnit().unitID())) Output: diff --git a/docs/source/algorithms/NMoldyn4Interpolation-v1.rst b/docs/source/algorithms/NMoldyn4Interpolation-v1.rst index b14f416241a9091966cd75c8fde0f9f883fec868..6209957c9c0dd207260d1e56a70b27cb52b3ebee 100644 --- a/docs/source/algorithms/NMoldyn4Interpolation-v1.rst +++ b/docs/source/algorithms/NMoldyn4Interpolation-v1.rst @@ -38,9 +38,9 @@ set** osiris = Rebin(osiris, [-0.6, 0.02, 0.6]) #interpolate the two workspaces interpolated_ws = NMoldyn4Interpolation(sim_ws, osiris) - print 'No. of Q-values in simulation = ' + str(sim_ws.getNumberHistograms()) - print 'No. of Q-values in reference = ' + str(osiris.getNumberHistograms()) - print 'No. of Q-values in interpolated set = '+ str(interpolated_ws.getNumberHistograms()) + print('No. of Q-values in simulation = {}'.format(sim_ws.getNumberHistograms())) + print('No. of Q-values in reference = {}'.format(osiris.getNumberHistograms())) + print('No. of Q-values in interpolated set = {}'.format(interpolated_ws.getNumberHistograms())) Output: diff --git a/docs/source/algorithms/NRCalculateSlitResolution-v1.rst b/docs/source/algorithms/NRCalculateSlitResolution-v1.rst index 5885a547200c0426e61ddc06f37a7ed4fd3bfcdb..bdd830f369c35ee35ef6af028d065c6bb5ed052b 100644 --- a/docs/source/algorithms/NRCalculateSlitResolution-v1.rst +++ b/docs/source/algorithms/NRCalculateSlitResolution-v1.rst @@ -50,7 +50,7 @@ Usage ws = Load('INTER00013460') res = NRCalculateSlitResolution(Workspace = ws, TwoTheta = 0.7 * 2) - print("Resolution: %.4f" % res) + print("Resolution: {:.4f}".format(res)) .. testoutput:: diff --git a/docs/source/algorithms/NormaliseByCurrent-v1.rst b/docs/source/algorithms/NormaliseByCurrent-v1.rst index 45c3e3fb2d065804f9b00307da242bb404686fd9..ad9fbc58e87251e0fa5ff0a85b098a997b5d7833 100644 --- a/docs/source/algorithms/NormaliseByCurrent-v1.rst +++ b/docs/source/algorithms/NormaliseByCurrent-v1.rst @@ -55,16 +55,16 @@ Usage log_p = run1.getLogData('gd_prtn_chrg') # Print the log value - print "Good Proton Charge =",log_p.value + print("Good Proton Charge = {}".format(log_p.value)) #Run the Algorithm wsN = NormaliseByCurrent(ws) norm_factor = wsN.getRun().getLogData('NormalizationFactor').value #Print results - print "Before normalisation", ws.readY(0); - print "After normalisation ", wsN.readY(0); - print "Normalisation factor", norm_factor; + print("Before normalisation {}".format(ws.readY(0))) + print("After normalisation {}".format(wsN.readY(0))) + print("Normalisation factor {}".format(norm_factor)) Output: diff --git a/docs/source/algorithms/NormaliseByDetector-v1.rst b/docs/source/algorithms/NormaliseByDetector-v1.rst index 92c2c43bde8b9ebd10bb4070e6ff9ec028e114f4..a9d4792005530a0e4bbcdc2cfe64d265fe28fb35 100644 --- a/docs/source/algorithms/NormaliseByDetector-v1.rst +++ b/docs/source/algorithms/NormaliseByDetector-v1.rst @@ -200,10 +200,10 @@ Usage #Now we are ready to run the correction wsCorrected = NormaliseByDetector(ws) - print ("The correction will divide the data by an increasing linear function.") - print ("f(x) = 2x + 1") + print("The correction will divide the data by an increasing linear function.") + print("f(x) = 2x + 1") for i in range(0,wsCorrected.blocksize(),10): - print ("The correct value in bin %i is %.2f compared to %.2f" % (i,wsCorrected.readY(0)[i],ws.readY(0)[i])) + print("The correct value in bin {} is {:.2f} compared to {:.2f}".format(i,wsCorrected.readY(0)[i],ws.readY(0)[i])) #clean up the file if os.path.exists(param_file_path): diff --git a/docs/source/algorithms/NormaliseByPeakArea-v1.rst b/docs/source/algorithms/NormaliseByPeakArea-v1.rst index 5fce5080943e3a116e9e6bd7680a21d69ae7326e..fb3e25279aeddd584f1a0cfb7ae3c89c4766b9f9 100644 --- a/docs/source/algorithms/NormaliseByPeakArea-v1.rst +++ b/docs/source/algorithms/NormaliseByPeakArea-v1.rst @@ -55,10 +55,10 @@ Usage normalised, yspace, fitted, symmetrised = \ NormaliseByPeakArea(InputWorkspace=tof_ws, Mass=1.0079,Sum=False) - print "Number of normalised spectra is: %d" % normalised.getNumberHistograms() - print "Number of Y-space spectra is: %d" % yspace.getNumberHistograms() - print "Number of fitted spectra is: %d" % fitted.getNumberHistograms() - print "Number of symmetrised spectra is: %d" % symmetrised.getNumberHistograms() + print("Number of normalised spectra is: {}".format(normalised.getNumberHistograms())) + print("Number of Y-space spectra is: {}".format(yspace.getNumberHistograms())) + print("Number of fitted spectra is: {}".format(fitted.getNumberHistograms())) + print("Number of symmetrised spectra is: {}".format(symmetrised.getNumberHistograms())) .. testoutput:: NormaliseNoSumOutput @@ -87,10 +87,10 @@ Usage normalised, yspace, fitted, symmetrised = \ NormaliseByPeakArea(InputWorkspace=tof_ws, Mass=1.0079,Sum=True) - print "Number of normalised spectra is: %d" % normalised.getNumberHistograms() - print "Number of Y-space spectra is: %d" % yspace.getNumberHistograms() - print "Number of fitted spectra is: %d" % fitted.getNumberHistograms() - print "Number of symmetrised spectra is: %d" % symmetrised.getNumberHistograms() + print("Number of normalised spectra is: {}".format(normalised.getNumberHistograms())) + print("Number of Y-space spectra is: {}".format(yspace.getNumberHistograms())) + print("Number of fitted spectra is: {}".format(fitted.getNumberHistograms())) + print("Number of symmetrised spectra is: {}".format(symmetrised.getNumberHistograms())) .. testoutput:: NormaliseWithSummedOutput diff --git a/docs/source/algorithms/NormaliseByThickness-v1.rst b/docs/source/algorithms/NormaliseByThickness-v1.rst index 8843002d2daddccb7e1dd17274339bb04eb0660d..437f5584ca7c451946eb66d8420a50b666d862cb 100644 --- a/docs/source/algorithms/NormaliseByThickness-v1.rst +++ b/docs/source/algorithms/NormaliseByThickness-v1.rst @@ -24,11 +24,11 @@ Usage norm=NormaliseByThickness(raw,SampleThickness=10) #do a quick check - print norm[1] - print "Min(raw)=",raw.dataY(0).min() - print "Min(norm)=",norm[0].dataY(0).min() - print "Max(raw)=",raw.dataY(0).max() - print "Max(norm)=",norm[0].dataY(0).max() + print(norm[1]) + print("Min(raw)= {}".format(raw.dataY(0).min())) + print("Min(norm)= {}".format(norm[0].dataY(0).min())) + print("Max(raw)= {}".format(raw.dataY(0).max())) + print("Max(norm)= {}".format(norm[0].dataY(0).max())) .. testcleanup:: NormaliseByThicness diff --git a/docs/source/algorithms/NormaliseSpectra-v1.rst b/docs/source/algorithms/NormaliseSpectra-v1.rst index ac5c15344a6162a0e70809562beaa0b503ae8d1c..d7e428c066435768ca84bae1a9401c48a9d23468 100644 --- a/docs/source/algorithms/NormaliseSpectra-v1.rst +++ b/docs/source/algorithms/NormaliseSpectra-v1.rst @@ -32,7 +32,7 @@ Usage out_ws = NormaliseSpectra(InputWorkspace=ws) # Print resulting y values - print out_ws.readY(0) + print(out_ws.readY(0)) Output: diff --git a/docs/source/algorithms/NormaliseToMonitor-v1.rst b/docs/source/algorithms/NormaliseToMonitor-v1.rst index 61a340bcd1e99d2bce15d43a8b31a6c137211b24..1580d16a7d168417a5a084a853e279b5e64c475c 100644 --- a/docs/source/algorithms/NormaliseToMonitor-v1.rst +++ b/docs/source/algorithms/NormaliseToMonitor-v1.rst @@ -81,13 +81,13 @@ Usage wsN = NormaliseToMonitor( ws, MonitorID=1 ) - print "Without normalisation" - print "Monitor ID=1 %.3f, %.3f" % ( ws.readY(0)[0], ws.readY(0)[1] ) - print "Selected data %.6f, %.6f" % ( ws.readY(6)[0], ws.readY(3)[1] ) + print("Without normalisation") + print("Monitor ID=1 {:.3f}, {:.3f}".format(ws.readY(0)[0], ws.readY(0)[1])) + print("Selected data {:.6f}, {:.6f}".format(ws.readY(6)[0], ws.readY(3)[1])) - print "With Normalisation" - print "Monitor ID=1 %.3f, %.3f" % ( wsN.readY(0)[0], wsN.readY(0)[1] ) - print "Selected data %.6f, %.6f" % ( wsN.readY(6)[0], wsN.readY(3)[1] ) + print("With Normalisation") + print("Monitor ID=1 {:.3f}, {:.3f}".format(wsN.readY(0)[0], wsN.readY(0)[1])) + print("Selected data {:.6f}, {:.6f}".format(wsN.readY(6)[0], wsN.readY(3)[1])) Output: diff --git a/docs/source/algorithms/NormaliseToUnity-v1.rst b/docs/source/algorithms/NormaliseToUnity-v1.rst index 6d40f1162ce480b898fa116f17ecc4458123d7e1..059fe586a0999153986feb5a61ff5a4639a896bf 100644 --- a/docs/source/algorithms/NormaliseToUnity-v1.rst +++ b/docs/source/algorithms/NormaliseToUnity-v1.rst @@ -29,20 +29,21 @@ Usage # Run algorithm wsNorm = NormaliseToUnity (ws) - print "Normalised Workspace" + print("Normalised Workspace") for i in range(4): - print "[ %.4f,%.4f,%.4f, %.4f, %.4f ]" % (wsNorm.readY(i)[0], wsNorm.readY(i)[1], - wsNorm.readY(i)[2], wsNorm.readY(i)[3], wsNorm.readY(i)[4],) + print("[ {:.4f}, {:.4f}, {:.4f}, {:.4f}, {:.4f} ]".format( + wsNorm.readY(i)[0], wsNorm.readY(i)[1], wsNorm.readY(i)[2], + wsNorm.readY(i)[3], wsNorm.readY(i)[4])) Output: .. testoutput:: ExNormaliseToUnitySimple Normalised Workspace - [ 0.2239,0.0065,0.0065, 0.0065, 0.0065 ] - [ 0.2239,0.0065,0.0065, 0.0065, 0.0065 ] - [ 0.2239,0.0065,0.0065, 0.0065, 0.0065 ] - [ 0.2239,0.0065,0.0065, 0.0065, 0.0065 ] + [ 0.2239, 0.0065, 0.0065, 0.0065, 0.0065 ] + [ 0.2239, 0.0065, 0.0065, 0.0065, 0.0065 ] + [ 0.2239, 0.0065, 0.0065, 0.0065, 0.0065 ] + [ 0.2239, 0.0065, 0.0065, 0.0065, 0.0065 ] .. categories:: diff --git a/docs/source/algorithms/NormaliseVanadium-v1.rst b/docs/source/algorithms/NormaliseVanadium-v1.rst index 0a0307f0fd22a86e72534e27cb18354e5112c277..f75bac177bb04e2417f2a5756c08011ae0737665 100644 --- a/docs/source/algorithms/NormaliseVanadium-v1.rst +++ b/docs/source/algorithms/NormaliseVanadium-v1.rst @@ -23,7 +23,7 @@ Usage inst = LoadEmptyInstrument(Filename='IDFs_for_UNIT_TESTING/MINITOPAZ_Definition.xml') vanadium = CreateWorkspace(DataX='0,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5', DataY='10.574151,10.873,11.07348,11.22903,11.42286,11.47365,11.37375,11.112,10.512181,10.653397', UnitX='wavelength', ParentWorkspace=inst) norm_van = NormaliseVanadium(InputWorkspace=vanadium) - print "Wavelength = ", norm_van.readX(0)[2], " Y = ", norm_van.readY(0)[2] + print("Wavelength = {} Y = {:.11f}".format(norm_van.readX(0)[2], norm_van.readY(0)[2])) Output: diff --git a/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst b/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst index dbcaee183c6cd7c6593e0305e815bf2b5a986f6d..87bf5b6dc369d097dea3b1e95c6ac002e6be133e 100644 --- a/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst +++ b/docs/source/algorithms/OSIRISDiffractionReduction-v1.rst @@ -67,7 +67,7 @@ Usage vanadium = [os.path.join(os.path.expanduser("~"), van + ".nxs") for van in vanadium] ws = OSIRISDiffractionReduction(Sample=','.join(samples), Vanadium=','.join(vanadium), CalFile="osiris_041_RES10.cal") - print "Number of Spectra: %d, Number of bins: %d" % (ws.getNumberHistograms(), ws.blocksize()) + print("Number of Spectra: {}, Number of bins: {}".format(ws.getNumberHistograms(), ws.blocksize())) Output: diff --git a/docs/source/algorithms/OneMinusExponentialCor-v1.rst b/docs/source/algorithms/OneMinusExponentialCor-v1.rst index 873ca5a627ca7f35874a91083520a7987fe2429e..a35ca4c96320fc16fc5c2d5cc51384ed7f0d25de 100644 --- a/docs/source/algorithms/OneMinusExponentialCor-v1.rst +++ b/docs/source/algorithms/OneMinusExponentialCor-v1.rst @@ -31,13 +31,13 @@ Usage .. testcode:: ExOneMinusExp ws=CreateWorkspace([1,2,3],[1,1,1]) - print "You can divide the data by the factor" + print("You can divide the data by the factor") wsOut=OneMinusExponentialCor(ws,2,3,"Divide") - print wsOut.readY(0) + print(wsOut.readY(0)) - print "Or multiply" + print("Or multiply") wsOut=OneMinusExponentialCor(ws,2,3,"Multiply") - print wsOut.readY(0) + print(wsOut.readY(0)) Output: diff --git a/docs/source/algorithms/OptimizeCrystalPlacement-v1.rst b/docs/source/algorithms/OptimizeCrystalPlacement-v1.rst index 540d3c0d13d4fb7a18cab0c786da3f1ca171f79b..24ab34c7652054f289d6d59da43ecf9d1d1507c3 100644 --- a/docs/source/algorithms/OptimizeCrystalPlacement-v1.rst +++ b/docs/source/algorithms/OptimizeCrystalPlacement-v1.rst @@ -56,7 +56,7 @@ Usage LoadIsawUB(ws,"ls5637.mat") wsd = OptimizeCrystalPlacement(ws) (wsPeakOut,fitInfoTable,chi2overDoF,nPeaks,nParams,nIndexed,covrianceInfoTable) = OptimizeCrystalPlacement(ws) - print "Chi2: %.4f" % chi2overDoF + print("Chi2: {:.4f}".format(chi2overDoF)) Output: diff --git a/docs/source/algorithms/OptimizeLatticeForCellType-v1.rst b/docs/source/algorithms/OptimizeLatticeForCellType-v1.rst index 9dd20d3a95364bedf4b1a027ecc19a6d54eb597f..fb3a18d2d23c9753442f432370756fab1ccdb558 100644 --- a/docs/source/algorithms/OptimizeLatticeForCellType-v1.rst +++ b/docs/source/algorithms/OptimizeLatticeForCellType-v1.rst @@ -29,11 +29,11 @@ Usage ws=LoadIsawPeaks("TOPAZ_3007.peaks") FindUBUsingFFT(ws,MinD=8.0,MaxD=13.0) - print "Before Optimization:" - print ws.sample().getOrientedLattice().getUB() + print("Before Optimization:") + print(ws.sample().getOrientedLattice().getUB()) OptimizeLatticeForCellType(ws,CellType="Monoclinic") - print "\nAfter Optimization:" - print ws.sample().getOrientedLattice().getUB() + print("\nAfter Optimization:") + print(ws.sample().getOrientedLattice().getUB()) Output: diff --git a/docs/source/algorithms/PDFFourierTransform-v1.rst b/docs/source/algorithms/PDFFourierTransform-v1.rst index 41347380030b92148752e40d44f8eb76c8784b70..e1ab0936bfd4d201b9efc06ce15b4e96e2e533a1 100644 --- a/docs/source/algorithms/PDFFourierTransform-v1.rst +++ b/docs/source/algorithms/PDFFourierTransform-v1.rst @@ -144,18 +144,17 @@ Usage .. testcode:: ExPDFFouurierTransform - # Simulates Load of a workspace with all necessary parameters ################# + # Simulates Load of a workspace with all necessary parameters import numpy as np; - xx= np.array(range(0,100))*0.1 - yy = np.exp(-((xx)/.5)**2) - ws=CreateWorkspace(DataX=xx,DataY=yy,UnitX='MomentumTransfer') - Rt= PDFFourierTransform(ws,InputSofQType='S(Q)',PDFType='g(r)'); - # - # Look at sample results: - print("part of S(Q) and its correlation function") - for i in xrange(0,10): - print('! {0:4.2f} ! {1:5f} ! {2:f} ! {3:5f} !'.format(xx[i],yy[i],Rt.readX(0)[i],Rt.readY(0)[i])) + xx = np.array(range(0,100))*0.1 + yy = np.exp(-(2.0 * xx)**2) + ws = CreateWorkspace(DataX=xx, DataY=yy, UnitX='MomentumTransfer') + Rt = PDFFourierTransform(ws, InputSofQType='S(Q)', PDFType='g(r)') + # Look at sample results: + print('part of S(Q) and its correlation function') + for i in range(10): + print('! {0:4.2f} ! {1:5f} ! {2:f} ! {3:5f} !'.format(xx[i], yy[i], Rt.readX(0)[i], Rt.readY(0)[i])) .. testcleanup:: ExPDFFouurierTransform diff --git a/docs/source/algorithms/SaveCanSAS1D-v1.rst b/docs/source/algorithms/SaveCanSAS1D-v1.rst index 975f02de45b3022ae48f19eb6383a8bf3fb3afcf..e13fe9d5b5a3b51123f940ad6bb235a4b73f0550 100644 --- a/docs/source/algorithms/SaveCanSAS1D-v1.rst +++ b/docs/source/algorithms/SaveCanSAS1D-v1.rst @@ -54,7 +54,7 @@ Usage SaveCanSAS1D(out_ws, file_path, Version=1) in_ws = LoadCanSAS1D(file_path) - print "Contents of the file = " + str(in_ws.readY(0)) + "." + print("Contents of the file = " + str(in_ws.readY(0)) + ".") .. testcleanup:: ExSimpleSavingRoundtrip diff --git a/docs/source/algorithms/SaveCanSAS1D-v2.rst b/docs/source/algorithms/SaveCanSAS1D-v2.rst index 5ee3428c800c831f477a80bb91e27955bd7d7819..e704f271dc33bff89348da252643b4c5f077407e 100644 --- a/docs/source/algorithms/SaveCanSAS1D-v2.rst +++ b/docs/source/algorithms/SaveCanSAS1D-v2.rst @@ -54,7 +54,7 @@ Usage SaveCanSAS1D(out_ws, file_path) in_ws = LoadCanSAS1D(file_path) - print "Contents of the file = " + str(in_ws.readY(0)) + "." + print("Contents of the file = " + str(in_ws.readY(0)) + ".") .. testcleanup:: ExSimpleSavingRoundtrip diff --git a/docs/source/algorithms/SaveDaveGrp-v1.rst b/docs/source/algorithms/SaveDaveGrp-v1.rst index 94501913cd804dd405ee295da9c80fab39e9a29d..a2267c636e00347f40723b1b66dacda2ff40067c 100644 --- a/docs/source/algorithms/SaveDaveGrp-v1.rst +++ b/docs/source/algorithms/SaveDaveGrp-v1.rst @@ -27,17 +27,17 @@ a contrived example will be created. ws = ConvertUnits(ws, Target="DeltaE", EMode="Direct", EFixed=3.0) ws = Rebin(ws, Params=[-3,0.01,3], PreserveEvents=False) ws = SofQW(ws, QAxisBinning=[0.2,0.2,3], EMode="Direct", EFixed=3.0) - print "Workspace size = (", ws.getNumberHistograms(), ",", ws.blocksize(), ")" + print("Workspace size = ( {} , {} )".format(ws.getNumberHistograms(), ws.blocksize())) import os savefile = os.path.join(config["default.savedirectory"], "CNCS_7860_sqw.grp") SaveDaveGrp(ws, Filename=savefile) - print "File created:", os.path.exists(savefile) + print("File created: {}".format(os.path.exists(savefile))) ifile = open(savefile, 'r') lines = ifile.readlines() ifile.close() # Number of lines = header(4) + Q axis spec(1 + 14) + E axis spec(1 + 600) # + data(14 * 601) - print "Number of lines =", len(lines) + print("Number of lines = {}".format(len(lines))) Output: diff --git a/docs/source/algorithms/SaveDetectorsGrouping-v1.rst b/docs/source/algorithms/SaveDetectorsGrouping-v1.rst index 8851982509c02aa917ee50839a455fab08202caf..5f356aca0f5c49dc66806023b2fbc2c1a89f8e9a 100644 --- a/docs/source/algorithms/SaveDetectorsGrouping-v1.rst +++ b/docs/source/algorithms/SaveDetectorsGrouping-v1.rst @@ -40,7 +40,7 @@ Usage SaveDetectorsGrouping(grouping, save_path) with open(save_path, 'r') as f: - print f.read().replace('\t', ' ').strip() + print(f.read().replace('\t', ' ').strip()) Output: diff --git a/docs/source/algorithms/SaveDiffFittingAscii-v1.rst b/docs/source/algorithms/SaveDiffFittingAscii-v1.rst index 43ad2ffdcda992b3226ab8b523fc2eb30dd7997d..969d9245746f2c2debd61237d08ba1ac8400d45e 100644 --- a/docs/source/algorithms/SaveDiffFittingAscii-v1.rst +++ b/docs/source/algorithms/SaveDiffFittingAscii-v1.rst @@ -103,7 +103,7 @@ Usage SaveDiffFittingAscii(InputWorkspace = ws, Filename=savefile, RunNumber="21344", Bank = "1", OutMode = "AppendToExistingFile") - print "File Exists:", os.path.exists(savefile) + print("File Exists: {}".format(os.path.exists(savefile))) Output: diff --git a/docs/source/algorithms/SaveDspacemap-v1.rst b/docs/source/algorithms/SaveDspacemap-v1.rst index f38a7f645640615985bf2b356665522b2efbc46c..2ff397771fb27149fcbbcb3942d1d05300a72337 100644 --- a/docs/source/algorithms/SaveDspacemap-v1.rst +++ b/docs/source/algorithms/SaveDspacemap-v1.rst @@ -30,7 +30,7 @@ Usage LoadCalFile(InputWorkspace=ws,CalFilename=r'PG3_golden.cal',MakeGroupingWorkspace='0',MakeMaskWorkspace='0',WorkspaceName='PG3_gold') SaveDspacemap(InputWorkspace="PG3_gold_offsets", DspacemapFile=savefilename) - print "File created = ", os.path.exists(savefilename), ", file size = ", os.path.getsize(savefilename) + print("File created = {} , file size = {}".format(os.path.exists(savefilename), os.path.getsize(savefilename))) .. testcleanup:: ExSavePG3Dmap diff --git a/docs/source/algorithms/SaveFITS-v1.rst b/docs/source/algorithms/SaveFITS-v1.rst index 5bd6fde6a36bad42a744910842b51bb52b77e7b0..ef0260bb3294113af5572217ab58c2ed9802869d 100644 --- a/docs/source/algorithms/SaveFITS-v1.rst +++ b/docs/source/algorithms/SaveFITS-v1.rst @@ -60,26 +60,26 @@ Usage bpp_log = 'BITPIX' try: log = ws.getRun().getLogData(bpp_log).value - print "Bits per pixel in first image: {0}".format(int(log)) + print("Bits per pixel in first image: {0}".format(int(log))) log_reload = ws.getRun().getLogData(bpp_log).value - print "Bits per pixel in second image: {0}".format(int(log_reload)) + print("Bits per pixel in second image: {0}".format(int(log_reload))) except RuntimeError: - print "Could not find the keyword '{0}' in the FITS file" % bpp_log + print("Could not find the keyword '{0}' in the FITS file".format(bpp_log)) axis1_log = 'NAXIS1' axis2_log = 'NAXIS2' try: log1 = ws.getRun().getLogData(axis1_log).value log2 = ws.getRun().getLogData(axis2_log).value - print "Image size in first image: {0} x {1} pixels".format(int(log1), int(log2)) + print("Image size in first image: {0} x {1} pixels".format(int(log1), int(log2))) log1_reload = ws_reload.getRun().getLogData(axis1_log).value log2_reload = ws_reload.getRun().getLogData(axis2_log).value - print "Image size in second image: {0} x {1} pixels".format(int(log1_reload), int(log2_reload)) + print("Image size in second image: {0} x {1} pixels".format(int(log1_reload), int(log2_reload))) except RuntimeError: - print "Could not find the keywords '%s' and '%s' in this FITS file" % (axis1_log, axis2_log) + print("Could not find the keywords '{}' and '{}' in this FITS file".format(axis1_log, axis2_log)) pos_x, pos_y = 22, 33 - print ("Pixel value at coordinates ({0},{1}), first image: {2}, second image: {3}". + print("Pixel value at coordinates ({0},{1}), first image: {2:.1f}, second image: {3:.1f}". format(pos_x, pos_y, ws.readY(pos_y)[pos_x], ws_reload.readY(pos_y)[pos_x])) .. testcleanup:: LoadSaveLoadFITS diff --git a/docs/source/algorithms/SaveFocusedXYE-v1.rst b/docs/source/algorithms/SaveFocusedXYE-v1.rst index e56f6ef981a36c7b9198141f9ce275ecad77a485..734b026405ad1913b96b0450c00a476be843bca5 100644 --- a/docs/source/algorithms/SaveFocusedXYE-v1.rst +++ b/docs/source/algorithms/SaveFocusedXYE-v1.rst @@ -44,7 +44,7 @@ Usage SaveFocusedXYE(ws, path) path = os.path.join(os.path.expanduser("~"), "myworkspace-0.ascii") - print os.path.isfile(path) + print(os.path.isfile(path)) Output: @@ -78,7 +78,7 @@ Output: path = os.path.join(os.path.expanduser("~"), file_name) SaveFocusedXYE(ws, path, SplitFiles=False, IncludeHeader=True, Format='MAUD') - print os.path.isfile(path) + print(os.path.isfile(path)) Output: diff --git a/docs/source/algorithms/SaveGSASInstrumentFile-v1.rst b/docs/source/algorithms/SaveGSASInstrumentFile-v1.rst index ba6570f832b3eb5cf1e97c93f78dff2a6e43351e..f2690b6d6e39a72d8ca68dc90c61e86bf4a0910a 100644 --- a/docs/source/algorithms/SaveGSASInstrumentFile-v1.rst +++ b/docs/source/algorithms/SaveGSASInstrumentFile-v1.rst @@ -86,12 +86,12 @@ Usage gfile.close() # Print out some result - print "Number of lines in GSAS instrument file: ", len(lines) - print "Line 0: ", lines[0].strip() - print "Line 1: ", lines[1].strip() - print "Line 2: ", lines[2].strip() - print "Line 3: ", lines[3].strip() - print "Line 305: ", lines[305].strip() + print("Number of lines in GSAS instrument file: {}".format(len(lines))) + print("Line 0: {}".format(lines[0].strip())) + print("Line 1: {}".format(lines[1].strip())) + print("Line 2: {}".format(lines[2].strip())) + print("Line 3: {}".format(lines[3].strip())) + print("Line 305: {}".format(lines[305].strip())) .. testcleanup:: ExHistSimple diff --git a/docs/source/algorithms/SaveGSS-v1.rst b/docs/source/algorithms/SaveGSS-v1.rst index 8b99e0dd675351cc00e61b90a7cfd58f6ae6e812..22108613927e2c6c9c95ea9c372f4c9886f92699 100644 --- a/docs/source/algorithms/SaveGSS-v1.rst +++ b/docs/source/algorithms/SaveGSS-v1.rst @@ -55,7 +55,7 @@ Usage # Does the file exist path = os.path.join(os.path.expanduser("~"), file_name) - print os.path.isfile(path) + print(os.path.isfile(path)) Output: @@ -93,7 +93,7 @@ Output: path = os.path.join(os.path.expanduser("~"), file_name) SaveGSS(ws, path, SplitFiles=False, ExtendedHeader=True, UseSpectrumNumberAsBankID=True) - print os.path.isfile(path) + print(os.path.isfile(path)) Output: diff --git a/docs/source/algorithms/SaveHKL-v1.rst b/docs/source/algorithms/SaveHKL-v1.rst index 81f8ee26e9f916f63ee9be1dafb1bed7be60d3fc..c2cc616f34603206472fb58ec6b245e4948d635f 100644 --- a/docs/source/algorithms/SaveHKL-v1.rst +++ b/docs/source/algorithms/SaveHKL-v1.rst @@ -57,7 +57,7 @@ Usage peaks = LoadIsawPeaks(Filename=r'Peaks5637.integrate') SaveHKL(peaks, path) - print os.path.isfile(path) + print(os.path.isfile(path)) Output: @@ -86,13 +86,13 @@ Output: #load a peaks workspace from file peaks = LoadIsawPeaks(Filename=r'Peaks5637.integrate') - print "Number of peaks in table %d" % peaks.rowCount() + print("Number of peaks in table {}".format(peaks.rowCount())) path = os.path.join(os.path.expanduser("~"), "MyPeaks.hkl") SaveHKL(peaks, path, MinWavelength=0.5, MaxWavelength=2,MinDSpacing=0.2, SortBy='Bank') peaks = LoadHKL(path) - print "Number of peaks in table %d" % peaks.rowCount() + print("Number of peaks in table {}".format(peaks.rowCount())) Output: diff --git a/docs/source/algorithms/SaveILLCosmosAscii-v1.rst b/docs/source/algorithms/SaveILLCosmosAscii-v1.rst index e232d1f046f643587c870edc48a457dbd1eea682..41d27f23b358a6e912d28cdbe8e2b5d1e31d9d80 100644 --- a/docs/source/algorithms/SaveILLCosmosAscii-v1.rst +++ b/docs/source/algorithms/SaveILLCosmosAscii-v1.rst @@ -40,7 +40,7 @@ Usage # perform the algorithm SaveILLCosmosAscii(InputWorkspace=ws1,Filename=savefile) - print "File Exists:", os.path.exists(savefile) + print("File Exists: {}".format(os.path.exists(savefile))) .. testcleanup:: ExILLCosmosSimple diff --git a/docs/source/algorithms/Transpose-v1.rst b/docs/source/algorithms/Transpose-v1.rst index 15f8b725124bbb7d484339cbcc6395b8a5f95a2f..76e7264c9fe13dcce77b8bdea178ab1f2313ea43 100644 --- a/docs/source/algorithms/Transpose-v1.rst +++ b/docs/source/algorithms/Transpose-v1.rst @@ -47,3 +47,4 @@ Output: .. categories:: .. sourcelink:: + :h: Framework/Algorithms/inc/MantidAlgorithms/Transpose.h diff --git a/docs/source/concepts/FitFunctionsInPython.rst b/docs/source/concepts/FitFunctionsInPython.rst index 090aaa0c934399d7021197a5871a67fb2d0b2b5d..10024a73777d179ca7bdf88d5e42ddd00e950fa4 100644 --- a/docs/source/concepts/FitFunctionsInPython.rst +++ b/docs/source/concepts/FitFunctionsInPython.rst @@ -202,6 +202,30 @@ Also one can put parameters into the function when evaluating. p = Polynomial(n=2) print p([0,1,2,3], 0.0, 0.5, 0.5) #expect [ 0. 1. 3. 6.] -This enables one to fit the functions with ``scipy.optimize.curve_fit``. +This enables one to fit the functions with ``scipy.optimize.curve_fit``. + +Plotting +-------- +Functions may be plotted by calling the ``plot`` method of the function. +``mantidplot`` must be available to import for ``plot`` to work. + +This method can be called in any of the following manners: + +.. code:: python + + f.plot(xValues=[0,2,2.5,3,5]) # for these x-values + f.plot(workspace=ws) # for the x-values of workspace ws + f.plot(workspace=ws, workspaceIndex=i) # for x-values of workspace index i of ws + f.plot(startX=xmin, endX=xmax) # for 20 x-values between xmin and xmax + f.plot(startX=xmin, endX=xmax, nSteps=10) # for 10 x-values between xmin and xmax + f.plot(workspace=ws, startX=xmin, endX=xmax) # for x-values of ws between xmin & xmax + f.plot(workspace=ws, name='Fred') # for plot & its workspace to be called 'Fred' + +If you use ``xValues``, then the list of x values must be in numerical order. +This is not checked and if they are not in order the plot may fail to display properly. + +If you want to display multiple plots of the same function, then use +``name`` to give each plot a unique name. The default value of ``name`` +is the name of the function. .. categories:: Concepts diff --git a/docs/source/concepts/InstrumentDefinitionFile.rst b/docs/source/concepts/InstrumentDefinitionFile.rst index 692ca4aec1438c83e4e74d6f71bdbf477602ec40..fa3dad94a26abe39c803d0eb88a12ee23c036d22 100644 --- a/docs/source/concepts/InstrumentDefinitionFile.rst +++ b/docs/source/concepts/InstrumentDefinitionFile.rst @@ -351,6 +351,8 @@ important reason to insist on this. spectrum may be the sum of counts from a number of detectors and Mantid, behind the scene, use the IDs to keep track of this. +.. warning:: As of version 3.12 of Mantid, Instruments in Mantid will no longer silently discard detectors defined with duplicate IDs. Detector IDs (including Monitors) must be unique across the Instrument. IDFs cannot be loaded if they violate this. + The <idlist> element and the idlist attribute of the elements is used to assign detector IDs. The notation for using idlist is diff --git a/docs/source/diagrams/CalculateMonteCarloAbsorption-v1_wkflw.dot b/docs/source/diagrams/CalculateMonteCarloAbsorption-v1_wkflw.dot new file mode 100644 index 0000000000000000000000000000000000000000..cf9b2023572828c02401c2e99a5f1fec1aabb133 --- /dev/null +++ b/docs/source/diagrams/CalculateMonteCarloAbsorption-v1_wkflw.dot @@ -0,0 +1,202 @@ +digraph CalculateMonteCarloAbsorption { + label="CalculateMonteCarloAbsorption Flowchart" + $global_style + + subgraph params { + $param_style + SampleWorkspace + SampleChemicalFormula + SampleDensityType + SampleDensity + BeamHeight + BeamWidth + NumberOfWavelengthPoints + EventsPerPoint + Interpolation + ContainerWorkspace + ContainerChemicalFormula + ContainerDensityType + ContainerDensity + Shape + SampleWidth + SampleThickness + SampleCenter + SampleAngle + SampleRadius + SampleInnerRadius + SampleOuterRadius + ContainerFrontThickness + ContainerBackThickness + ContainerInnerRadius + ContainerOuterRadius + CorrectionsWorkspace + } + + subgraph decisions { + $decision_style + Shape + is_x_in_wavelength [label="Is x-axis of workspace\nin units of wavelength?"] + is_y_in_wavelength [label="Is y-axis of workspace\nin units of wavelength?"] + is_x_in_energy_transfer [label="Is x-axis of workspace\nin units of energy transfer?"] + is_y_in_energy_transfer [label="Is x-axis of workspace\nin units of energy transfer?"] + emode_is_indirect [label="Is E-Mode of workspace, indirect?"] + is_x_in_momentum_transfer [label="Is x-axis of workspace\nin units of momentum transfer?"] + is_isis_instrument_1 [label="Is instrument in workspace\nan ISIS instrument?"] + is_isis_instrument_2 [label="Is instrument in workspace\nan ISIS instrument?"] + container_supplied [label="Container supplied?"] + shape_value_sample [label="Supplied Shape Value?"] + shape_value_container [label="Supplied Shape Value?"] + } + + subgraph processes { + $process_style + update_instrument_angles [label="Update the instrument angles\nin a given workspace from\nQ-Values and wavelength"] + load_elastic_instrument_definition [label="Load the elastic instrument\ndefinition file into the\nworkspace using the\nLoadInstrument algorithm"] + set_efixed [label="Sets the EFixed parameter\nin the workspace using\nthe SetInstrumentParameter algorithm"] + calculate_wavelengths [label="Calculate wavelengths for\nthe workspace"] + calculate_offset_front [label="Calculate average of two\ninputs and take negative"] + calculate_offset_back [label="Average the two inputs"] + } + + subgraph algorithms { + $algorithm_style + SimpleShapeMonteCarloAbsorption_sample [label="SimpleShapeMonteCarloAbsorption"] + SimpleShapeMonteCarloAbsorption_container [label="SimpleShapeMonteCarloAbsorption"] + SimpleShapeMonteCarloAbsorption_containerm1 [label="SimpleShapeMonteCarloAbsorption"] + SimpleShapeMonteCarloAbsorption_containerm2 [label="SimpleShapeMonteCarloAbsorption"] + CloneWorkspace_wave [label="CloneWorkspace"] + CloneWorkspace_indirect [label="CloneWorkspace"] + Transpose_wave [label="Transpose"] + Transpose_energy [label="Transpose"] + Transpose_indirect [label="Transpose"] + ConvertUnits_energy [label="ConvertUnits"] + ConvertUnits_direct [label="ConvertUnits"] + AddSampleLogMultiple + GroupWorkspaces + Multiply + CropWorkspace + ConvertToHistogram + } + + subgraph values { + $value_style + Wavelength + FlatPlate_sample [label="Flat Plate"] + Annulus_sample [label="Annulus"] + Cylinder_sample [label="Cylinder"] + FlatPlate_container [label="Flat Plate"] + Annulus_container [label="Annulus"] + Cylinder_container [label="Cylinder"] + } + + SampleWorkspace -> is_x_in_wavelength [label="Convert Sample\nto Wavelength"] + ContainerWorkspace -> is_x_in_wavelength [label="Convert Container\nto Wavelength"] + is_x_in_wavelength -> CloneWorkspace_wave [label="Yes"] + is_x_in_wavelength -> is_y_in_wavelength [label="No"] + is_y_in_wavelength -> Transpose_wave [label="Yes"] + is_y_in_wavelength -> is_x_in_energy_transfer [label="No"] + is_x_in_energy_transfer -> ConvertUnits_energy [label="Yes"] + is_x_in_energy_transfer -> is_y_in_energy_transfer [label="No"] + is_y_in_energy_transfer -> Transpose_energy [label="Yes"] + is_y_in_energy_transfer -> emode_is_indirect [label="No"] + emode_is_indirect -> is_x_in_momentum_transfer [label="Yes"] + emode_is_indirect -> ConvertUnits_direct [label="Yes"] + is_x_in_momentum_transfer -> Transpose_indirect [label="Yes"] + is_x_in_momentum_transfer -> CloneWorkspace_indirect [label="Yes"] + Wavelength -> ConvertUnits_energy + Wavelength -> ConvertUnits_direct + CloneWorkspace_indirect -> is_isis_instrument_1 + Transpose_indirect -> is_isis_instrument_1 + is_isis_instrument_1 -> load_elastic_instrument_definition [label="Yes"] + is_isis_instrument_1 -> set_efixed [label="No"] + load_elastic_instrument_definition -> set_efixed + set_efixed -> ConvertToHistogram + ConvertToHistogram -> CropWorkspace + CropWorkspace -> calculate_wavelengths + calculate_wavelengths -> is_isis_instrument_2 + is_isis_instrument_2 -> update_instrument_angles [label="Yes"] + Transpose_energy -> ConvertUnits_energy + + ConvertUnits_energy -> SimpleShapeMonteCarloAbsorption_sample + update_instrument_angles -> SimpleShapeMonteCarloAbsorption_sample + is_isis_instrument_2 -> SimpleShapeMonteCarloAbsorption_sample [label="No"] + CloneWorkspace_wave -> SimpleShapeMonteCarloAbsorption_sample + Transpose_wave -> SimpleShapeMonteCarloAbsorption_sample + ConvertUnits_direct -> SimpleShapeMonteCarloAbsorption_sample + + BeamHeight -> SimpleShapeMonteCarloAbsorption_sample + BeamWidth -> SimpleShapeMonteCarloAbsorption_sample + NumberOfWavelengthPoints -> SimpleShapeMonteCarloAbsorption_sample + EventsPerPoint -> SimpleShapeMonteCarloAbsorption_sample + Interpolation -> SimpleShapeMonteCarloAbsorption_sample + SampleChemicalFormula -> SimpleShapeMonteCarloAbsorption_sample + SampleDensityType -> SimpleShapeMonteCarloAbsorption_sample + SampleDensity -> SimpleShapeMonteCarloAbsorption_sample + Height -> SimpleShapeMonteCarloAbsorption_sample + Shape -> SimpleShapeMonteCarloAbsorption_sample + FlatPlate_sample -> SimpleShapeMonteCarloAbsorption_sample + Annulus_sample -> SimpleShapeMonteCarloAbsorption_sample + Cylinder_sample -> SimpleShapeMonteCarloAbsorption_sample + shape_value_sample -> FlatPlate_sample [label="Flat Plate"] + shape_value_sample -> Annulus_sample [label="Annulus"] + shape_value_sample -> Cylinder_sample [label="Cylinder"] + SampleWidth -> FlatPlate_sample + SampleThickness -> FlatPlate_sample + SampleAngle -> FlatPlate_sample + SampleCenter -> FlatPlate_sample + SampleRadius -> Cylinder_sample + SampleInnerRadius -> Annulus_sample + SampleOuterRadius -> Annulus_sample + + SimpleShapeMonteCarloAbsorption_sample -> AddSampleLogMultiple + AddSampleLogMultiple -> GroupWorkspaces + SimpleShapeMonteCarloAbsorption_sample -> container_supplied + + BeamHeight -> SimpleShapeMonteCarloAbsorption_container + BeamWidth -> SimpleShapeMonteCarloAbsorption_container + NumberOfWavelengthPoints -> SimpleShapeMonteCarloAbsorption_container + EventsPerPoint -> SimpleShapeMonteCarloAbsorption_container + Interpolation -> SimpleShapeMonteCarloAbsorption_container + container_supplied -> SimpleShapeMonteCarloAbsorption_container [label="Yes"] + ContainerChemicalFormula -> SimpleShapeMonteCarloAbsorption_container + ContainerDensityType -> SimpleShapeMonteCarloAbsorption_container + ContainerDensity -> SimpleShapeMonteCarloAbsorption_container + Height -> SimpleShapeMonteCarloAbsorption_container + Shape -> SimpleShapeMonteCarloAbsorption_container + Annulus_container -> SimpleShapeMonteCarloAbsorption_container + Cylinder_container -> SimpleShapeMonteCarloAbsorption_container + shape_value_container -> FlatPlate_container [label="Flat Plate"] + shape_value_container -> Annulus_container [label="Annulus"] + shape_value_container -> Annulus_container [label="Cylinder"] + ContainerInnerRadius -> Annulus_container + ContainerOuterRadius -> Annulus_container + ContainerInnerRadius -> Cylinder_container + ContainerOuterRadius -> Cylinder_container + + BeamHeight -> SimpleShapeMonteCarloAbsorption_containerm1 + BeamWidth -> SimpleShapeMonteCarloAbsorption_containerm1 + NumberOfWavelengthPoints -> SimpleShapeMonteCarloAbsorption_containerm1 + EventsPerPoint -> SimpleShapeMonteCarloAbsorption_containerm1 + Interpolation -> SimpleShapeMonteCarloAbsorption_containerm1 + + BeamHeight -> SimpleShapeMonteCarloAbsorption_containerm2 + BeamWidth -> SimpleShapeMonteCarloAbsorption_containerm2 + NumberOfWavelengthPoints -> SimpleShapeMonteCarloAbsorption_containerm2 + EventsPerPoint -> SimpleShapeMonteCarloAbsorption_containerm2 + Interpolation -> SimpleShapeMonteCarloAbsorption_containerm2 + + FlatPlate_container -> SimpleShapeMonteCarloAbsorption_containerm1 + FlatPlate_container -> SimpleShapeMonteCarloAbsorption_containerm2 + SampleWidth -> SimpleShapeMonteCarloAbsorption_containerm1 + SampleAngle -> SimpleShapeMonteCarloAbsorption_containerm1 + ContainerFrontThickness -> SimpleShapeMonteCarloAbsorption_containerm1 + calculate_offset_front -> SimpleShapeMonteCarloAbsorption_containerm1 + ContainerBackThickness -> SimpleShapeMonteCarloAbsorption_containerm2 + calculate_offset_back -> SimpleShapeMonteCarloAbsorption_containerm2 + + SimpleShapeMonteCarloAbsorption_containerm1 -> Multiply + SimpleShapeMonteCarloAbsorption_containerm2 -> Multiply + + Multiply -> GroupWorkspaces + GroupWorkspaces -> CorrectionsWorkspace +} \ No newline at end of file diff --git a/docs/source/images/FDA_release.png b/docs/source/images/FDA_release.png new file mode 100644 index 0000000000000000000000000000000000000000..50bc27e7a8fead5b77cca4b0178253dbd92f0ea1 Binary files /dev/null and b/docs/source/images/FDA_release.png differ diff --git a/docs/source/images/ISIS_Reflectometry_autoreduction.png b/docs/source/images/ISIS_Reflectometry_autoreduction.png new file mode 100644 index 0000000000000000000000000000000000000000..c0ad3644e49a4b570c6af1931a0ca872906bbc2a Binary files /dev/null and b/docs/source/images/ISIS_Reflectometry_autoreduction.png differ diff --git a/docs/source/release/v3.11.0/diffraction.rst b/docs/source/release/v3.11.0/diffraction.rst index 277eecad1ebd400f324863e9e8889bb2a8fee56b..757b67d6f920244937087933993305197605ad1d 100644 --- a/docs/source/release/v3.11.0/diffraction.rst +++ b/docs/source/release/v3.11.0/diffraction.rst @@ -5,16 +5,6 @@ Diffraction Changes .. contents:: Table of Contents :local: -Crystal Improvements --------------------- - -- :ref:`SCDCalibratePanels <algm-SCDCalibratePanels>` now adjusts the sample offsets and has an option to optimize the initial time-of-flight for better calibration of single crystal data. -- :ref:`SCDCalibratePanels <algm-SCDCalibratePanels>` has CalibrateSnapPanels option to calibrate 3X3 banks of SNAP instrument for single crystal data. -- :ref:`LoadIsawDetCal <algm-LoadIsawDetCal>` has not correctly aligned the detectors for SNAP since release 3.9. This bug that only impacted SNAP has been fixed. - -Engineering Diffraction ------------------------ - Powder Diffraction ------------------ @@ -26,6 +16,7 @@ Powder Diffraction - :ref:`PDCalibration <algm-PDCalibration>` has changed how it calculates constants from peak positions to use a simplex optimization rather than Gauss-Markov method. - :ref:`ResampleX <algm-ResampleX>` has a bug fix in how it automatically determines the data range for a workspace with multiple spectra. - The powder diffraction GUI has had numerous bugfixes and now has an option to override the detector grouping. +- New set of routines for HRPD (:ref:`isis-powder-diffraction-hrpd-ref`), designed to replace and improve on the old CRI scripts Single Crystal Diffraction -------------------------- @@ -35,11 +26,9 @@ Single Crystal Diffraction - :ref:`FindPeaksMD <algm-FindPeaksMD>` has been modified to only add peaks to runs that contributed to that peak. This is a lot faster when multiple runs are in the same MDworkspace. - New algorithm :ref:`MDNormSCDPreprocessIncoherent <algm-MDNormSCDPreprocessIncoherent>` creates the Solid Angle and Flux workspace from Vanadium data for MDNormSCD - :ref:`FindSXPeaks <algm-FindSXPeaks-v1>` now finds all peaks in each spectrum. It also allows for setting more fine-grained resolutions. It can now also accept workspaces both in units of TOF and d-spacing. - -Powder Diffraction ------------------- - -- New set of routines for HRPD (:ref:`isis-powder-diffraction-hrpd-ref`), designed to replace and improve on the old CRI scripts +- :ref:`SCDCalibratePanels <algm-SCDCalibratePanels>` now adjusts the sample offsets and has an option to optimize the initial time-of-flight for better calibration of single crystal data. +- :ref:`SCDCalibratePanels <algm-SCDCalibratePanels>` has CalibrateSnapPanels option to calibrate 3X3 banks of SNAP instrument for single crystal data. +- :ref:`LoadIsawDetCal <algm-LoadIsawDetCal>` has not correctly aligned the detectors for SNAP since release 3.9. This bug that only impacted SNAP has been fixed. Imaging ------- @@ -48,6 +37,5 @@ Imaging Full list of `diffraction <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.11%22+is%3Amerged+label%3A%22Component%3A+Diffraction%22>`_ -and -`imaging <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.11%22+is%3Amerged+label%3A%22Component%3A+Imaging%22>`_ changes on GitHub. +changes on GitHub. diff --git a/docs/source/release/v3.11.0/framework.rst b/docs/source/release/v3.11.0/framework.rst index 665c34a3b3da16562fddee3f817943f0bc1c4e55..54620829f62c24978c6d389e5cf5edee2df3c5a4 100644 --- a/docs/source/release/v3.11.0/framework.rst +++ b/docs/source/release/v3.11.0/framework.rst @@ -35,7 +35,7 @@ Improved - :ref:`FilterEvents <algm-FilterEvents-v1>` has refactored on splitting sample logs. - :ref:`FilterEvents <algm-FilterEvents-v1>` now copies units for the logs in the filtered workspaces - :ref:`GroupDetectors <algm-GroupDetectors-v2>` now supports workspaces with detector scans. -- :ref:`FindPeaksMD <algm-FindPeaksMD-v1>` allows now to normalize by the number of events. This can improve results for data that was originally based on histogram data which has been converted to event-mode. +- :ref:`FindPeaksMD <algm-FindPeaksMD-v1>` now allows users to normalize by the number of events. This can improve results for data that was originally based on histogram data which has been converted to event-mode. - :ref:`FindSXPeaks <algm-FindSXPeaks-v1>` now finds all peaks in each spectrum. It also allows for setting more fine-grained resolutions and takes into account any goniometer set on the workspace. - :ref:`SimpleShapeMonteCarloAbsorption <algm-SimpleShapeMonteCarloAbsorption>` has been added to simplify sample environment inputs for MonteCarloAbsorption - :ref:`IntegreatePeaksMD <algm-IntegratePeaksMD-v2>` makes the culling of the top one percent of the background events optional. @@ -46,9 +46,9 @@ Improved - :ref:`LoadBBY <algm-LoadBBY-v1>` is now better at handling sample information. - :ref:`MonteCarloAbsorption <algm-MonteCarloAbsorption-v1>` has had several improvements: - * it now supports approximating the input instrument with a sparse grid of detectors enabling quick simulation of huge pixel arrays - * the NumberOfWavelengthPoints input property is now validated more rigorously - * a new MaxScatterPtAttempts input has been added to control how many tries are made to generate a random point in the object. Useful for cases such as thin annuli that require a higher number of tries. The previous version was hard coded internally. + * It now supports approximating the input instrument with a sparse grid of detectors enabling quick simulation of huge pixel arrays. + * The NumberOfWavelengthPoints input property is now validated more rigorously. + * A new MaxScatterPtAttempts input has been added to control how many tries are made to generate a random point in the object. Useful for cases such as thin annuli that require a higher number of tries. The previous version was hard coded internally. - :ref:`SaveGSS <algm-SaveGSS-v1>` now supports saving in the legacy GSAS ALT format. This is useful for older tools however the default format FXYE should be used whenever possible. - :ref:`SaveMDWorkspaceToVTK <algm-SaveMDWorkspaceToVTK-v1>` and :ref:`LoadVTK <algm-LoadVTK-v1>` algorithms are now accessible from python. - :ref:`MergeRuns <algm-MergeRuns-v1>` will now merge workspaces with detector scans. @@ -59,11 +59,13 @@ Improved - :ref:`ConvertSpectrumAxis <algm-ConvertSpectrumAxis-v2>`: Added an option to disable the sorting of the resulting axis making it useful especially for scanning workspaces. Also reduced the complexity of the operation for the default (ordered axis) case from *Nˆ2* to *N*. - :ref:`MSDFit <algm-MSDFit>` now supports model selection. Currently has the option of 3 models: MsdGauss, MsdPeters and MsdYi. - :ref:`algm-LineProfile`: Fixed a bug which could cause crashes when the line extended over the right or bottom edge of a workspace. +- :ref:`algm-Mean`: Added error messages if the data is not appropriate. - :ref:`algm-LoadLiveData`: Fixed a bug affecting Live Data Processing in "Replace" mode. The bug meant that changes to Instrument position/rotation were overwitten by defaults on every load. Now fixed so that Instrument state is persistent across loads. +- :ref:`CalMuonDetectorPhasees <algm-CalMuonDetectorPhases-v1>` now fits a cos instead of a sin function. Performance ----------- -- Performance of UB indexing routines addressed. `:ref:`FindUBUsingLatticeParameters` running 2x faster than before. +- Performance of UB indexing routines addressed. :ref:`FindUBUsingLatticeParameters <algm-FindUBUsingLatticeParameters-v1>` running 2x faster than before. - Several changes to the core of how instrument geometry is stored and accessed. These changes have resulted in a few noteworthy performance improvements. * Partial loading of event nexus files has improved by 22%. @@ -94,6 +96,7 @@ Improved - :ref:`CubicSpline <func-CubicSpline>` is fixed to sort the y-values and x-values correctly. - Fix displayed type name for optional boolean properties. - Fix parameters that are tied to functions can now be untied correctly. +- Table workspaces do not have the values changed by viewing them (no rounding). Python ------ @@ -109,6 +112,7 @@ Bugfixes ######## - :ref:`MatchPeaks <algm-MatchPeaks-v1>` is fixed to not to leave temporary hidden workspaces behind. +- Fix a bug where Mantid could crash when trying to update live data if the network connection is lost. Python Fit Functions #################### diff --git a/docs/source/release/v3.11.0/index.rst b/docs/source/release/v3.11.0/index.rst index 14b52acc6fc68bde200c4db67f1a91fcefc43850..7fa5f56bf988cb9e7fb51f2dbc47ad3dca4fe61e 100644 --- a/docs/source/release/v3.11.0/index.rst +++ b/docs/source/release/v3.11.0/index.rst @@ -14,11 +14,9 @@ Mantid 3.11.0 Release Notes .. contents:: Table of Contents :local: -.. warning:: This release is still under construction. The changes can be found in the nightly builds on the `download page`_. - We are proud to announce version 3.11.0 of Mantid. This release celebrates 10 years of the Mantid project supporting Neutron and Muon research. -**TODO: Add paragraph summarizing big changes** +This release includes improvements to allow Mantid to handle Scanning workspaces, where detectors may be in several locations for different time periods, and updates to the VSI improving the performance of slicing regularly binned data. There have also been some significant performance enhancements for various algorithms with the framework due to the continued on improving our handling of he instrument geometry. This is just one of many improvements in this release, so please take a look at the release notes, which are filled with details of the diff --git a/docs/source/release/v3.11.0/indirect_inelastic.rst b/docs/source/release/v3.11.0/indirect_inelastic.rst index 214283d212a8a96f76cd222603cf261886cfdb85..b622b5a9efaa756ad44c8e3345dd7af3563e24ec 100644 --- a/docs/source/release/v3.11.0/indirect_inelastic.rst +++ b/docs/source/release/v3.11.0/indirect_inelastic.rst @@ -5,89 +5,67 @@ Indirect Inelastic Changes .. contents:: Table of Contents :local: -New features ------------- - Algorithms -########## - +---------- + +New +### +- :ref:`SimpleShapeMonteCarloAbsorption <algm-SimpleShapeMonteCarloAbsorption>` has been added to simplify sample environment inputs for MonteCarloAbsorption. +- :ref:`algm-CalculateMonteCarloAbsorption` calculates Paalman Pings absorption factors from a sample and container workspace, given shape specific input. + +Improved +######## +- The following changes were made to the :ref:`algm-MSDFit` algorithm: + - Added model selection to the :ref:`algm-MSDFit` algorithm, with three current models: MsdPeters, MsdYi and MsdPeters. New models now work with workspaces in Q not Q^2 (e.g. _eq workspaces 'Elastic Q'). +- The following changes were made to the the :ref:`algm-ConvolutionFitSequential` algorithm: + - Added 'ExtractMembers' property to :ref:`algm-ConvolutionFitSequential` - this allows for extracting the members of the convolution fitting into their own workspaces. + - Property to pass the workspace index added to :ref:`algm-ConvolutionFitSequential`. + - The :ref:`algm-ConvolutionFitSequential` now performs correct treatment of the resolution function: convolve sample and resolution spectra with same momentum transfer. +- The following changes were made to the the :ref:`algm-ISISIndirectDiffractionReduction` algorithm: + - Manual D-Ranges can now be supplied as a list/range, to the :ref:`algm-ISISIndirectDiffractionReduction` algorithm, each corresponding to their respective runs, in the supplied order. + - The Sum Files option in the :ref:`algm-ISISIndirectDiffractionReduction` algorithm now allows for correctly corresponding each sum of + sample runs defined with a range (e.g. A-B, where A and B are run numbers) to the corresponding vanadium run, dependent on D-Range. + - The 'Sample Runs' field in the :ref:`algm-ISISIndirectDiffractionReduction` algorithm now recognizes 3 operators: '-', '+', ':'. The '-' operator is used to supply a given range of runs and sum them when SumFiles is checked. The '+' operator is used to supply a given list of runs and sum when SumFiles is checked. The ':' operator is used to supply a range of runs, which will never be summed. + - The Grouping Policy in :ref:`algm-ISISIndirectDiffractionReduction`, now allows for grouping with a Workspace. +- :ref:`FlatPlatePaalmanPingsCorrection <algm-FlatPlatePaalmanPingsCorrection>` now supports `Direct` and `Indirect` modes. - :ref:`BASISReduction <algm-BASISReduction>` can save to NXSPE format. - -Vesuvio -####### -- Added flag for disabling multiple scattering corrections: flags['ms_flags']['ms_enabled'] -- Added method for specifying a mass by chemical symbol e.g. H for hydrogen, O for oxygen -- Gamma Corrections are no longer done for back-scattering spectra -- Multiple scattering corrections for back-scattering spectra now approximate hydrogen peak, this peak can be constrained with masses specified by symbol - -Bayes -##### -- Removed fit option from plot options drop-down menu. -- :ref:`SimpleShapeMonteCarloAbsorption <algm-SimpleShapeMonteCarloAbsorption>` has been added to simplify sample environment inputs for MonteCarloAbsorption - -Data Analysis -############# -- Added 'ExtractMembers' property to ConvolutionFitSequential algorithm - this allows for extracting the members of the - convolution fitting into their own workspaces. - -Elwin -~~~~~ - + Bugfixes --------- -- Save Result now writes to file the temperature-dependent elastic intensity normalized to the lowest temperature. - -ConvFit -~~~~~~~ - -Improvements ------------- -- Added 'ExtractMembers' property to ConvolutionFitSequential algorithm - this allows for extracting the members of the - convolution fitting into their own workspaces. - -Bugfixes --------- -- Correct treatment of the resolution function: convolve sample and resolution spectra with same momentum transfer. -- Property to pass the workspace index added to :ref:`algm-ConvolutionFitSequential`. - -MSDFit -~~~~~~ - -Improvements ------------- -- Added model selection to MSDFit, with three current models: MsdPeters, MsdYi and MsdPeters. New models now - work with workspaces in Q not Q^2 (e.g. _eq workspaces 'Elastic Q') +######## +- :ref:`algm-ElasticWindowMultiple` now correctly normalizes by the lowest temperature - rather than the first one. +- An issue has been fixed in :ref:`algm-IndirectILLEnergyTransfer` when handling the data with mirror sense, that have shifted 0 monitor counts in the left and right wings. This was causing the left and right workspaces to have different x-axis binning and to fail to sum during the unmirroring step. +- An issue has been fixed in :ref:`algm-IndirectILLReductionFWS` when the scaling of the data after vanadium calibration was not applied. +- :ref:`algm-CalculateSampleTransmission` now divides by the tabulated wavelength when calculating the absorption cross section. +Indirect Interfaces +------------------- +- The Indirect Absorption Corrections interface has been replaced with Calculate Monte Carlo Absorption Corrections; using the new :ref:`algm-CalculateMonteCarloAbsorption` algorithm. +- In the Indirect ConvFit interface, EISF is now extracted as a parameter when performing a single fit using 'Fit Single Spectrum'. +- The Indirect *S(Q, W)* interface now automatically replaces NaN values with 0. +- The Save Result option in the Indirect Elwin interface now writes to file the temperature-dependent elastic intensity normalized to the lowest temperature. +- Model selection is available in the Indirect MSDFit interface, providing the option to choose one of the three models available in the :ref:`algm-MSDFit` algorithm. +- Removed fit option from plot options drop-down menu, in the Indirect Bayes interface. +- Use Manual Grouping in the Indirect Diffraction interface now functions in the same way as the equivalent option in the Indirect ISISEnergyTransfer interface; providing and option to choose the number of groups and subsequently grouping by detector. +- Plot Current Preview is now an available option across all Indirect interfaces, where a mini-plot is shown within the interface. -Jump Fit -~~~~~~~~ +Vesuvio +------- +- Added flag for disabling multiple scattering corrections: flags['ms_flags']['ms_enabled']. +- Added method for specifying a mass by chemical symbol e.g. H for hydrogen, O for oxygen. +- Multiple scattering corrections for back-scattering spectra now approximate the hydrogen peak, this is done in the :ref:`algm-VesuvioCorrections` algorithm. This feature is incomplete for 3.11. +- :ref:`algm-VesuvioCorrections` has the additional property: 'MassIndexToSymbolMap'. MassIndexToSymbolMap is used to map from an index of mass in the 'Masses' property to a chemical symbol. +- :ref:`algm-VesuvioCorrections` takes the additional property: 'HydrogenConstraints'. HydrogenConstraints are used to constrain the hydrogen peak for multiple scattering corrections in back-scattering spectra. +- Gamma Corrections are no longer done for back-scattering spectra in the :ref:`algm-VesuvioCorrections` algorithm. General -~~~~~~~ - -Improvements ------------- -- Added a flag 'ms_enabled' (default: True) for enabling/disabling multiple scattering in vesuvio user scripts. -- The *S(Q, W)* interface now automatically replaces NaN values with 0. -- EISF is now generated when performing a Single Fit, with a delta function, in the ConvFit interface. -- :ref:`FlatPlatePaalmanPingsCorrection <algm-FlatPlatePaalmanPingsCorrection>` now supports `Direct` and `Indirect` modes. +------- Dropped -------- +####### - `LoadILLIndirect-v1 <http://docs.mantidproject.org/v3.10.1/algorithms/LoadILLIndirect-v1.html>`_, `IndirectILLReduction <http://docs.mantidproject.org/v3.10.1/algorithms/IndirectILLReduction-v1.html>`_, `ILLIN16BCalibration <http://docs.mantidproject.org/v3.10.1/algorithms/ILLIN16BCalibration-v1.html>`_ algorithms deprecated since v3.9, are now removed. - Bugfixes --------- -- ElasticWindowMultiple now correctly normalizes by the lowest temperature - rather than the first one. +######## - A number of Python indirect algorithms that use :py:obj:`mantid.kernel.MaterialBuilder` allowed setting the mass density for a material. The density was set incorrectly where the chemical formula had more than one atom, this is now fixed. -- An issue has been fixed in :ref:`algm-IndirectILLEnergyTransfer` when handling the data with mirror sense, that have shifted 0 monitor counts in the left and right wings. This was causing the left and right workspaces to have different x-axis binning and to fail to sum during the unmirroring step. -- An issue has been fixed in :ref:`algm-IndirectILLReductionFWS` when the scaling of the data after vanadium calibration was not applied. -- :ref:`algm-CalculateSampleTransmission` now divides by the tabulated wavelength when calculating the absorption cross section. -- The Sum Files option in the Indirect Diffraction Reduction interface now allows for correctly corresponding each sum of - sample runs defined with a range (e.g. A-B, where A and B are run numbers) to the corresponding vanadium run, dependent on D-Range. -- The 'Sample Runs' field in the Indirect Diffraction Interface now recognizes 3 operators: '-', '+', ':'. The '-' operator is used - to supply a given range of runs and sum them when SumFiles is checked. The '+' operator is used to supply a given list of runs and - sum when SumFiles is checked. The ':' operator is used to supply a range of runs, which will never be summed. `Full list of changes on GitHub <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.11%22+is%3Amerged+label%3A%22Component%3A+Indirect+Inelastic%22>`_ diff --git a/docs/source/release/v3.11.0/muon.rst b/docs/source/release/v3.11.0/muon.rst index 1a5e381f153be3f3c0b1b2247dbbd0bc900d6d8c..f9a707e6ef361aac6ca324b7d37c9e93778e7778 100644 --- a/docs/source/release/v3.11.0/muon.rst +++ b/docs/source/release/v3.11.0/muon.rst @@ -8,19 +8,15 @@ Muon Analysis Interfaces ---------- +.. figure:: ../../images/FDA_release.png + :class: screenshot + :align: right + :width: 500 px + - Added the Frequency Domain Analysis GUI. At present it is only able to transform data from real space to frequency space. Includes FFT and Maximum entropy methods. - Updated the TF asymmetry fit. It now works with multiple fitting. - Moved the TF Asymmetry checkbox to the data analysis tab. -Muon Analysis -############# - -Algorithms ----------- - -Fit Functions -------------- - Bug Fixes --------- - Mantid would crash when multiple period data was used in single fits (in muon analysis). This has been fixed. diff --git a/docs/source/release/v3.11.0/reflectometry.rst b/docs/source/release/v3.11.0/reflectometry.rst index d407d50c8263edc57da6b3095bc84ac08c0aad8a..d7c30f2a5bc551f3e002f5ff780869b9b96de71d 100644 --- a/docs/source/release/v3.11.0/reflectometry.rst +++ b/docs/source/release/v3.11.0/reflectometry.rst @@ -5,6 +5,60 @@ Reflectometry Changes .. contents:: Table of Contents :local: + +Reflectometry Reduction Interface +--------------------------------- + +ISIS Reflectometry +################## + +.. figure:: ../../images/ISIS_Reflectometry_autoreduction.png + :class: screenshot + :align: center + + New features of the ISIS Reflectometry Interface + +Automatic reduction +^^^^^^^^^^^^^^^^^^^ + +- New 'automatic reduction' functionality has been added for automatically reducing all runs obtained from a given investigation ID. +- With an investigation ID supplied, clicking ``Autoreduce`` searches for runs that are included in the investigation, transfers them to the processing table and processes all runs. +- Automatic reduction can be paused using the new ``Pause`` button. It can be resumed by pressing the ``Autoreduce`` button again. This will continue the automatic reduction from the last processed row. +- Changing the instrument, investigation ID or transfer method while paused means that automatic reduction cannot continue where it left off. Therefore, clicking the ``Autoreduce`` button again will start a new automatic reduction based on the new settings. + +Pausing and resuming reduction +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ + +- A new ``Pause`` button has been added which allows pausing of any reduction, whether started using the ``Process`` or ``Autoreduce`` button. +- The ``Process`` and ``Autoreduce`` buttons are greyed out while a reduction is in progress. They are enabled again when the reduction is paused so that they can be used to resume the reduction. +- When the ``Pause`` button is clicked, the reduction might not stop immediately, but will stop as soon as the current row has finished processing. This ensures that nothing is left in a partially-completed state. +- If the row selection is changed while a reduction is paused, the newly-selected rows will be processed instead of the original rows when the ``Process`` button is clicked. However, the row selection is irrelevant when using ``Autoreduce``, because this will continue from the last-processed row. +- The interface cannot be closed while a reduction is in progress. Therefore, the ``Pause`` button can be used to stop data reduction so that the interface can be closed. +- Data and settings should not be edited while a reduction is in progress. Pausing reduction allows changes to be safely made: + + - Rows and groups may be edited while a reduction is paused. They will be marked as 'unprocessed' so that they are re-processed when the reduction is resumed. + - Altering data within a row will mean that its containing group will also be re-processed. + - Adding/removing rows from a group will mean that the group will be re-processed. + - Deleting or renaming output workspaces of processed rows/groups will mean that that row/group will be re-processed. + +Other changes +^^^^^^^^^^^^^ +- Rows and groups that have been successfully processed are highlighted green: + + - Rows are highlighted when reduction has completed. + - Groups are highlighted when post-processing has completed. Note that if a group does not have any applicable post-processing then it will never be highlighted, even if all of its child rows are highlighted. + +- The interface now operates asynchronously, so that one can still interact with the rest of MantidPlot while data is processing (instead of freezing MantidPlot until processing has finished). + +- The calculation of :math:`\frac{dQ}{Q}` has been fixed in line with the changes to the :ref:`algm-NRCalculateSlitResolution` algorithm detailed below. An additional bug has been fixed where the interface was passing :math:`\theta` to this algorithm instead of :math:`2\theta`. + + +ISIS Reflectometry (Old) +######################## + +- The calculation of :math:`\frac{dQ}{Q}` has been fixed in line with the changes to the :ref:`algm-NRCalculateSlitResolution` algorithm. An additional bug has been fixed where the interface was passing :math:`\theta` to this algorithm instead of :math:`2\theta`. + + Algorithms ---------- @@ -32,36 +86,4 @@ Algorithms - :ref:`algm-LoadILLReflectometry` has been fixed to correctly load D17 files acquired in the TOF mode. -Reflectometry Reduction Interface ---------------------------------- - -ISIS Reflectometry -################## - -- The interface can now operate asynchronously in that one can still interact with Mantid while data is processing (instead of freezing Mantid until it finished): - - - Reduction can be paused using the new 'Pause' button added to the interface. It may be resumed again by clicking on the 'Process' button again. - - Data reduction must be paused first before the interface can be closed. - - When reduction is paused, the interface will finish reducing the current row before pausing. - - Changing item selection while paused will cause the newly selected items to be processed instead. - - Altering data within a row while paused will set that row and its containing group unprocessed. Adding/removing rows from a group will also set the group unprocessed. - - Deleting or renaming output workspaces of processed rows/groups will set that row/group unprocessed. - -- During reduction, rows and groups that have been successfully processed are highlighted green. - -- New 'autoreduce' button added for automatically reducing all runs obtained from a given investigation id. - - - With an id supplied, clicking 'autoreduce' searches for runs that are included in the investigation, transfers them to the processing table and processes all runs. - - Button disabled while reduction in process. Can be re-enabled by pausing autoreduction, where clicking 'autoreduce' again will continue processing rows. - - Changing the instrument, investigation id or transfer method while paused and clicking 'autoreduce' will start a new autoreduction. - -- The calculation of :math:`\frac{dQ}{Q}` has been fixed in line with the changes to the :ref:`algm-NRCalculateSlitResolution` algorithm. An additional bug has been fixed where :math:`\theta` was being passed to this algorithm instead of :math:`2\theta`. - - -ISIS Reflectometry (Old) -######################## - -- The calculation of :math:`\frac{dQ}{Q}` has been fixed in line with the changes to the :ref:`algm-NRCalculateSlitResolution` algorithm. An additional bug has been fixed where :math:`\theta` was being passed to this algorithm instead of :math:`2\theta`. - - `Full list of changes on github <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.11%22+is%3Amerged+label%3A%22Component%3A+Reflectometry%22>`__ diff --git a/docs/source/release/v3.11.0/sans.rst b/docs/source/release/v3.11.0/sans.rst index 8b75217d5b181bbfae9442a2004f7e52485d5a15..3c5e2d2b07c050181476001a651189ec216ad27c 100644 --- a/docs/source/release/v3.11.0/sans.rst +++ b/docs/source/release/v3.11.0/sans.rst @@ -8,17 +8,24 @@ SANS Changes Interfaces ---------- +.. figure:: ../../images/sans_isis_v2_whole_gui.png + :class: screenshot + :align: right + :width: 400 px + - SANS > ISIS SANS v2 experimental interface has become available. It has basic reduction functionalities and makes use of the new reduction backend. +EQSANS +###### + +- Following hardware changes in the instrument, sample and detector offsets were added as parameters of the reduction. + Bug Fixes --------- - Displaying the masked workspace in the mask tab now makes sure that the masks are displayed in a grey color. -EQSANS ------- -- Following hardware changes in the instrument, sample and detector offsets were added as parameters of the reduction. `Full list of changes on github <http://github.com/mantidproject/mantid/pulls?q=is%3Apr+milestone%3A%22Release+3.11%22+is%3Amerged+label%3A%22Component%3A+SANS%22>`__ diff --git a/docs/source/release/v3.11.0/ui.rst b/docs/source/release/v3.11.0/ui.rst index 76c1ecef148de858ee8023746b212a7d66b0c6dc..4f3759838a1e70fe557266c856d3eabbe0addf4e 100644 --- a/docs/source/release/v3.11.0/ui.rst +++ b/docs/source/release/v3.11.0/ui.rst @@ -18,13 +18,29 @@ VSI Improvements :class: screenshot :align: right -- Multislice view uses a custom `representation <https://www.paraview.org/ParaView/index.php/Views_And_Representations>`_ to speed up slicing by taking advantage of the consistent bin +- Upstream ParaView Contributions + + - Fix scaling, orientation and position inputs when nonorthogonal axes are present. + - Speed up MultiSlice view by avoiding repeated allocating and freeing memory. + - Fix the resample to image mapper, which was failing when input contains cell data. + - Expose the SamplingDimensions property when using the resample to image mapper with vtkStructuredGrids. + +- Upstream VTK Contributions + + - Improve surface filter performance using vtkSMPTools + - Refactor the vtkDataSetTriangleFilter for better performance. + - Refactor the threshold filter to take advantage of structured data. + - Minimize duplicate code in vtkDataArrayPrivate and parallelize range calculation. + +- Multislice view uses a custom `representation <https://www.paraview.org/ParaView/index.php/Views_And_Representations>`_ to speed up slicing by taking advantage of the consistent bin sizes in a MDHistoWorkspace. Smooth interaction with typical data sizes (< 10 million cells) is now possible. SliceViewer Improvements ######################## - SliceViewer input of number of bins, thickness, and slice point now waits until the editing is finished to rebin or changing slice point instead of changing with each digit entered. +- Fixed the ability to drag & drop files into Mantid OSX >=10.10 +- The welcome dialog has been redesigned to use less of the screen to fit better onto laptops with small high resolution screens that use screen scaling. Scanning workspaces ################### diff --git a/docs/source/release/v3.12.0/framework.rst b/docs/source/release/v3.12.0/framework.rst index eafb3687f7d0b2df3d7c12e01c26ea9ad3e1dc88..2c426072c9ed9d7eff6654fc7d878aef45a91442 100644 --- a/docs/source/release/v3.12.0/framework.rst +++ b/docs/source/release/v3.12.0/framework.rst @@ -11,6 +11,13 @@ Framework Changes Concepts -------- +Corrupted Instrument Definitions +^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +.. warning:: Instruments in Mantid will no longer silently discard detectors defined with duplicate IDs. This has been a long-standing source of hard to find issue in Mantid. We have endeavoured to ensure that all :ref:`Instrument Definition Files <InstrumentDefinitionFile>` shipped with Mantid are now corrected. **If you have local IDFs, please update them to remove any duplicate IDs, or ask the Mantid Team for help**, the warning and error information in Mantid will give details about duplicates in IDFs that cannot be loaded. + + Beware that :ref:`LoadNexusProcessed <algm-LoadNexusProcessed>` will now **NOT load the Instrument from historic Processed Nexus files if the embedded IDF is corruped with duplicate detector IDs**. The workspace (data) part will still load, but the workspace will not have any Instrument attached. There are new warnings generated that describe the exact problem and the remedy when this happens. Note that the fix is generally easy. You should be able to run :ref:`LoadInstrument <algm-LoadInstrument>` on the Workspace, pointing it to an updated IDF, which is free of duplicates. + +Please contact the Mantid Team if you experience any further problems as a result of these changes. Algorithms ---------- @@ -21,4 +28,4 @@ Data Objects Python ------ -:ref:`Release 3.12.0 <v3.12.0>` \ No newline at end of file +:ref:`Release 3.12.0 <v3.12.0>` diff --git a/docs/sphinxext/mantiddoc/doctest.py b/docs/sphinxext/mantiddoc/doctest.py index f6aa1953d2a99bd81aae4013f8a3d49b77d21bab..8b456db4da45fa17784b576879775689a6e04a41 100644 --- a/docs/sphinxext/mantiddoc/doctest.py +++ b/docs/sphinxext/mantiddoc/doctest.py @@ -171,12 +171,11 @@ class TestSuiteReport(object): @property def nfailed(self): - def sum_failure(fails, case): + fails = 0 + for case in self.testcases: if case.failed: - return fails + 1 - else: - return fails - return reduce(sum_failure, self.testcases, 0) + fails += 1 + return fails @property def npassed(self): diff --git a/instrument/IRIS_elastic_Definition.xml b/instrument/IRIS_elastic_Definition.xml new file mode 100644 index 0000000000000000000000000000000000000000..39899fc49a8a58341aaf2b12c502e281c0a94bab --- /dev/null +++ b/instrument/IRIS_elastic_Definition.xml @@ -0,0 +1,195 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!-- For help on the notation used to specify an Instrument Definition File + see http://www.mantidproject.org/IDF --> +<instrument xmlns="http://www.mantidproject.org/IDF/1.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd" + name="IRIS" + valid-from="1900-01-31 23:59:59" + valid-to="2100-01-31 23:59:59" + last-modified="2010-10-07 00:00:00"> +<!-- modified by FD 7/10/2010 --> + +<defaults> + <length unit="meter" /> + <angle unit="degree" /> + <reference-frame> + <along-beam axis="z" /> + <pointing-up axis="y" /> + <handedness val="right" /> + </reference-frame> + <offsets spherical="delta" /> +</defaults> + +<!-- LIST OF PHYSICAL COMPONENTS (which the instrument consists of) --> + +<!-- source and sample-position components --> + +<component type="moderator"> + <location z="-36.41" /> +</component> + +<type name="moderator" is="Source"> + <properties /> +</type> + +<component type="sample"> + <location z="0.0" /> +</component> + +<type name="sample" is="SamplePos"> + <cuboid id="shape"> + <left-front-bottom-point x="0.02" y="-0.02" z="0.0" /> + <left-front-top-point x="0.02" y="-0.02" z="0.02" /> + <left-back-bottom-point x="-0.02" y="-0.02" z="0.0" /> + <right-front-bottom-point x="0.02" y="0.02" z="0.0" /> + </cuboid> + <algebra val="shape" /> +</type> + +<!-- LIST OF DETECTORS AND MONITORS --> + +<!-- detector components --> + +<component type="graphite" idlist="graphite"> + <properties /> + <location /> +</component> + +<type name="graphite"> + <component type="pix1"> + <location r="1.45" t="27.07" p="0" name="S3" /> + <location r="1.45" t="29.70" p="0" name="S4" /> + <location r="1.45" t="32.32" p="0" name="S5" /> + <location r="1.45" t="34.95" p="0" name="S6" /> + <location r="1.45" t="37.58" p="0" name="S7" /> + <location r="1.45" t="40.21" p="0" name="S8" /> + <location r="1.45" t="42.83" p="0" name="S9" /> + <location r="1.45" t="45.46" p="0" name="S10" /> + <location r="1.45" t="48.08" p="0" name="S11" /> + <location r="1.45" t="50.71" p="0" name="S12" /> + <location r="1.45" t="53.34" p="0" name="S13" /> + <location r="1.45" t="55.96" p="0" name="S14" /> + <location r="1.45" t="58.59" p="0" name="S15" /> + <location r="1.45" t="61.21" p="0" name="S16" /> + <location r="1.45" t="63.84" p="0" name="S17" /> + <location r="1.45" t="66.47" p="0" name="S18" /> + <location r="1.45" t="69.10" p="0" name="S19" /> + <location r="1.45" t="71.72" p="0" name="S20" /> + <location r="1.45" t="74.35" p="0" name="S21" /> + <location r="1.45" t="76.98" p="0" name="S22" /> + <location r="1.45" t="79.60" p="0" name="S23" /> + <location r="1.45" t="82.23" p="0" name="S24" /> + <location r="1.45" t="84.85" p="0" name="S25" /> + <location r="1.45" t="87.48" p="0" name="S26" /> + <location r="1.45" t="90.11" p="0" name="S27" /> + <location r="1.45" t="92.74" p="0" name="S28" /> + <location r="1.45" t="95.36" p="0" name="S29" /> + <location r="1.45" t="97.99" p="0" name="S30" /> + <location r="1.45" t="100.61" p="0" name="S31" /> + <location r="1.45" t="103.24" p="0" name="S32" /> + <location r="1.45" t="105.87" p="0" name="S33" /> + <location r="1.45" t="108.50" p="0" name="S34" /> + <location r="1.45" t="111.12" p="0" name="S35" /> + <location r="1.45" t="113.75" p="0" name="S36" /> + <location r="1.45" t="116.38" p="0" name="S37" /> + <location r="1.45" t="119.00" p="0" name="S38" /> + <location r="1.45" t="121.63" p="0" name="S39" /> + <location r="1.45" t="124.26" p="0" name="S40" /> + <location r="1.45" t="126.88" p="0" name="S41" /> + <location r="1.45" t="129.51" p="0" name="S42" /> + <location r="1.45" t="132.13" p="0" name="S43" /> + <location r="1.45" t="134.76" p="0" name="S44" /> + <location r="1.45" t="137.39" p="0" name="S45" /> + <location r="1.45" t="140.02" p="0" name="S46" /> + <location r="1.45" t="142.64" p="0" name="S47" /> + <location r="1.45" t="145.26" p="0" name="S48" /> + <location r="1.45" t="147.89" p="0" name="S49" /> + <location r="1.45" t="150.52" p="0" name="S50" /> + <location r="1.45" t="153.15" p="0" name="S51" /> + <location r="1.45" t="155.77" p="0" name="S52" /> + <location r="1.45" t="158.40" p="0" name="S53" /> + </component> +</type> + +<idlist idname="graphite"> + <id start="3" end="53" /> +</idlist> + +<type name="pix1" is="detector"> + <cuboid id="app-shape"> + <left-front-bottom-point x="0.005" y="-0.1" z="0.0" /> + <left-front-top-point x="0.005" y="-0.1" z="0.0002" /> + <left-back-bottom-point x="-0.005" y="-0.1" z="0.0" /> + <right-front-bottom-point x="0.005" y="0.1" z="0.0" /> + </cuboid> + <algebra val="app-shape" /> +</type> + +<component type="mica" idlist="mica"> + <properties /> + <location /> +</component> + +<type name="mica"> + <component type="pix1"> + <location r="1.47" t="-21.70" p="0" name="S54" /> + <location r="1.47" t="-24.43" p="0" name="S55" /> + <location r="1.47" t="-27.16" p="0" name="S56" /> + <location r="1.47" t="-29.89" p="0" name="S57" /> + <location r="1.47" t="-32.62" p="0" name="S58" /> + <location r="1.47" t="-35.35" p="0" name="S59" /> + <location r="1.47" t="-38.08" p="0" name="S60" /> + <location r="1.47" t="-40.81" p="0" name="S61" /> + <location r="1.47" t="-43.54" p="0" name="S62" /> + <location r="1.47" t="-46.27" p="0" name="S63" /> + <location r="1.47" t="-49.00" p="0" name="S64" /> + <location r="1.47" t="-51.73" p="0" name="S65" /> + <location r="1.47" t="-54.46" p="0" name="S66" /> + <location r="1.47" t="-57.19" p="0" name="S67" /> + <location r="1.47" t="-59.92" p="0" name="S68" /> + <location r="1.47" t="-62.65" p="0" name="S69" /> + <location r="1.47" t="-65.38" p="0" name="S70" /> + <location r="1.47" t="-68.11" p="0" name="S71" /> + <location r="1.47" t="-70.84" p="0" name="S72" /> + <location r="1.47" t="-73.57" p="0" name="S73" /> + <location r="1.47" t="-76.30" p="0" name="S74" /> + <location r="1.47" t="-79.00" p="0" name="S75" /> + <location r="1.47" t="-81.70" p="0" name="S76" /> + <location r="1.47" t="-84.20" p="0" name="S77" /> + <location r="1.47" t="-86.70" p="0" name="S78" /> + <location r="1.47" t="-89.20" p="0" name="S79" /> + <location r="1.47" t="-91.70" p="0" name="S80" /> + <location r="1.47" t="-94.20" p="0" name="S81" /> + <location r="1.47" t="-96.70" p="0" name="S82" /> + <location r="1.47" t="-99.20" p="0" name="S83" /> + <location r="1.47" t="-101.70" p="0" name="S84" /> + <location r="1.47" t="-104.20" p="0" name="S85" /> + <location r="1.47" t="-106.70" p="0" name="S86" /> + <location r="1.47" t="-109.70" p="0" name="S87" /> + <location r="1.47" t="-112.70" p="0" name="S88" /> + <location r="1.47" t="-115.70" p="0" name="S89" /> + <location r="1.47" t="-118.70" p="0" name="S90" /> + <location r="1.47" t="-121.70" p="0" name="S91" /> + <location r="1.47" t="-124.70" p="0" name="S92" /> + <location r="1.47" t="-127.70" p="0" name="S93" /> + <location r="1.47" t="-130.70" p="0" name="S94" /> + <location r="1.47" t="-133.45" p="0" name="S95" /> + <location r="1.47" t="-136.18" p="0" name="S96" /> + <location r="1.47" t="-138.91" p="0" name="S97" /> + <location r="1.47" t="-141.64" p="0" name="S98" /> + <location r="1.47" t="-144.37" p="0" name="S99" /> + <location r="1.47" t="-147.10" p="0" name="S100" /> + <location r="1.47" t="-149.83" p="0" name="S101" /> + <location r="1.47" t="-152.56" p="0" name="S102" /> + <location r="1.47" t="-155.29" p="0" name="S103" /> + <location r="1.47" t="-158.02" p="0" name="S104" /> + </component> +</type> + +<idlist idname="mica"> + <id start="54" end="104" /> +</idlist> + + +</instrument> diff --git a/instrument/OSIRIS_elastic_Definition.xml b/instrument/OSIRIS_elastic_Definition.xml new file mode 100644 index 0000000000000000000000000000000000000000..dc0ebdf7b9bb9824b311e60c0f78de7ed62a60fd --- /dev/null +++ b/instrument/OSIRIS_elastic_Definition.xml @@ -0,0 +1,127 @@ +<?xml version="1.0" encoding="UTF-8" ?> +<!-- For help on the notation used to specify an Instrument Definition File + see http://www.mantidproject.org/IDF --> +<instrument xmlns="http://www.mantidproject.org/IDF/1.0" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:schemaLocation="http://www.mantidproject.org/IDF/1.0 http://schema.mantidproject.org/IDF/1.0/IDFSchema.xsd" + name="OSIRIS" + valid-from="1900-01-31 23:59:59" + valid-to="2100-01-31 23:59:59" + last-modified="2008-08-26 15:23:52"> + +<defaults> + <length unit="meter" /> + <angle unit="degree" /> + <reference-frame> + <along-beam axis="z" /> + <pointing-up axis="y" /> + <handedness val="right" /> + </reference-frame> + <offsets spherical="delta" /> +</defaults> + + <!-- DESCRIPTION OF INSTRUMENT IN WORDS: + + Instrument layout & coordinates generated by the ArielToMantidXML tool + (2008-08-26T15:23:52). + + Instrument detector description details from Mark Telling + amended by FD 7/10/2010 + + --> + + +<!-- DEFINITION OF SOURCE AND SAMPLE --> +<component type="moderator"> + <location z="-34.0" /> +</component> + +<type name="moderator" is="Source"> + <properties /> +</type> + +<component type="sample"> + <location z="0.0" /> +</component> + +<type name="sample" is="SamplePos"> + <cuboid id="shape"> + <left-front-bottom-point x="0.02" y="-0.02" z="0.0" /> + <left-front-top-point x="0.02" y="-0.02" z="0.02" /> + <left-back-bottom-point x="-0.02" y="-0.02" z="0.0" /> + <right-front-bottom-point x="0.02" y="0.02" z="0.0" /> + </cuboid> + <algebra val="shape" /> +</type> + + +<!-- LIST OF DETECTORS AND MONITORS --> +<component type="graphite" idlist="graphite"> + <properties /> + <location /> +</component> + +<type name="graphite"> + <component type="pix1"> + <location r="1.5825" t="-11.5" p="0" name="g963" /> + <location r="1.5821" t="-14.829" p="0" name="g964" /> + <location r="1.5825" t="-18.159" p="0" name="g965" /> + <location r="1.5825" t="-21.488" p="0" name="g966" /> + <location r="1.5821" t="-24.817" p="0" name="g967" /> + <location r="1.5821" t="-28.146" p="0" name="g968" /> + <location r="1.5825" t="-31.476" p="0" name="g969" /> + <location r="1.5825" t="-34.805" p="0" name="g970" /> + <location r="1.5821" t="-38.134" p="0" name="g971" /> + <location r="1.5821" t="-41.463" p="0" name="g972" /> + <location r="1.5825" t="-44.793" p="0" name="g973" /> + <location r="1.5825" t="-48.122" p="0" name="g974" /> + <location r="1.5821" t="-51.451" p="0" name="g975" /> + <location r="1.5821" t="-54.781" p="0" name="g976" /> + <location r="1.5825" t="-58.11" p="0" name="g977" /> + <location r="1.5825" t="-61.439" p="0" name="g978" /> + <location r="1.5821" t="-64.768" p="0" name="g979" /> + <location r="1.5821" t="-68.098" p="0" name="g980" /> + <location r="1.5825" t="-71.427" p="0" name="g981" /> + <location r="1.5825" t="-74.756" p="0" name="g982" /> + <location r="1.5821" t="-78.085" p="0" name="g983" /> + <location r="1.5821" t="-81.415" p="0" name="g984" /> + <location r="1.5825" t="-84.744" p="0" name="g985" /> + <location r="1.5825" t="-88.073" p="0" name="g986" /> + <location r="1.5821" t="-91.402" p="0" name="g987" /> + <location r="1.5821" t="-94.732" p="0" name="g988" /> + <location r="1.5825" t="-98.061" p="0" name="g989" /> + <location r="1.5825" t="-101.39" p="0" name="g990" /> + <location r="1.5821" t="-104.719" p="0" name="g991" /> + <location r="1.5821" t="-108.049" p="0" name="g992" /> + <location r="1.5825" t="-111.378" p="0" name="g993" /> + <location r="1.5825" t="-114.707" p="0" name="g994" /> + <location r="1.5821" t="-118.037" p="0" name="g995" /> + <location r="1.5821" t="-121.366" p="0" name="g996" /> + <location r="1.5825" t="-124.695" p="0" name="g997" /> + <location r="1.5821" t="-128.024" p="0" name="g998" /> + <location r="1.5821" t="-131.354" p="0" name="g999" /> + <location r="1.5825" t="-134.683" p="0" name="g1000" /> + <location r="1.5825" t="-138.012" p="0" name="g1001" /> + <location r="1.5821" t="-141.342" p="0" name="g1002" /> + <location r="1.5821" t="-144.671" p="0" name="g1003" /> + <location r="1.5825" t="-148.00" p="0" name="g1004" /> + </component> +</type> + +<type name="pix1" is="detector"> + <cuboid id="app-shape"> + <left-front-bottom-point x="0.005" y="-0.1" z="0.0" /> + <left-front-top-point x="0.005" y="-0.1" z="0.0002" /> + <left-back-bottom-point x="-0.005" y="-0.1" z="0.0" /> + <right-front-bottom-point x="0.005" y="0.1" z="0.0" /> + </cuboid> + <algebra val="app-shape" /> +</type> + +<!-- DETECTOR/MONITOR IDs --> + +<idlist idname="graphite"> + <id start="963" end="1004" /> +</idlist> + +</instrument> diff --git a/instrument/TOSCA_graphite_002_Parameters.xml b/instrument/TOSCA_graphite_002_Parameters.xml index 8b6f3b861448fea7a8e47cddfe432816fbbad02a..534f354441807f1a5f16c2f40f3a55321d2799e9 100644 --- a/instrument/TOSCA_graphite_002_Parameters.xml +++ b/instrument/TOSCA_graphite_002_Parameters.xml @@ -31,6 +31,10 @@ <value val="0" /> </parameter> + <parameter name="Workflow.NamingConvention" type="string"> + <value val="RunTitle" /> + </parameter> + </component-link> </parameter-file> diff --git a/qt/scientific_interfaces/DynamicPDF/DPDFFitControl.cpp b/qt/scientific_interfaces/DynamicPDF/DPDFFitControl.cpp index bd3cc6be41de0c796c41460ce264a2e917ab211e..23845d0cfeac46470f93bfd9b3263c8db946c63f 100644 --- a/qt/scientific_interfaces/DynamicPDF/DPDFFitControl.cpp +++ b/qt/scientific_interfaces/DynamicPDF/DPDFFitControl.cpp @@ -360,7 +360,7 @@ void FitControl::saveBuiltInModels() { "Quadratic,A0=0,A1=0,A2=0;name=Gaussian,Height=0," "PeakCentre=0,Sigma=0);name=LinearBackground,A0=0," "A1=0"; - for (auto modelName : models.keys()) { + for (const auto &modelName : models.keys()) { settings.setValue(modelName, models[modelName]); } } diff --git a/qt/scientific_interfaces/EnggDiffraction/EnggDiffFittingPresenter.cpp b/qt/scientific_interfaces/EnggDiffraction/EnggDiffFittingPresenter.cpp index 892aa78f9d975a317bbb71d2f8f889309ae97942..4c894e9c1d775bc72806ca31bf755eddd59f8a26 100644 --- a/qt/scientific_interfaces/EnggDiffraction/EnggDiffFittingPresenter.cpp +++ b/qt/scientific_interfaces/EnggDiffraction/EnggDiffFittingPresenter.cpp @@ -677,7 +677,7 @@ EnggDiffFittingPresenter::enableMultiRun(const std::string &firstRun, bool foundAllRuns = true; - for (const auto runNumber : RunNumberVec) { + for (const auto &runNumber : RunNumberVec) { // Get full path for every run selected std::vector<std::string> foundFileNames; if (findFilePathFromBaseName(workingDirectory, runNumber, foundFileNames)) { @@ -760,7 +760,7 @@ void EnggDiffFittingPresenter::processFitAllPeaks() { const std::string fitPeaksData = validateFittingexpectedPeaks(fittingPeaks); g_log.debug() << "Focused files found are: " << fitPeaksData << '\n'; - for (auto dir : g_multi_run_directories) { + for (const auto &dir : g_multi_run_directories) { g_log.debug() << dir << '\n'; } @@ -1599,7 +1599,7 @@ void EnggDiffFittingPresenter::setBankItems( try { // Keep track of current loop iteration for banks int index = 0; - for (const auto filePath : bankFiles) { + for (const auto &filePath : bankFiles) { const Poco::Path bankFile(filePath); const std::string strVecFile = bankFile.toString(); @@ -1705,7 +1705,7 @@ void EnggDiffFittingPresenter::setDefaultBank( // can be assigned to text-field when number is given else if (!m_view->getFittingRunNumVec().empty()) { auto firstDir = m_view->getFittingRunNumVec().at(0); - auto intialDir = firstDir; + const auto &intialDir = firstDir; m_view->setFittingRunNo(intialDir); } // if nothing found related to text-field input diff --git a/qt/scientific_interfaces/EnggDiffraction/EnggDiffractionPresenter.cpp b/qt/scientific_interfaces/EnggDiffraction/EnggDiffractionPresenter.cpp index f120005d21241126be375d5f872b49ab20621dfa..4b0e6be50161ae5aca463be40ec6ac3e3d448296 100644 --- a/qt/scientific_interfaces/EnggDiffraction/EnggDiffractionPresenter.cpp +++ b/qt/scientific_interfaces/EnggDiffraction/EnggDiffractionPresenter.cpp @@ -729,7 +729,7 @@ std::vector<std::string> EnggDiffractionPresenter::isValidMultiRunNumber( if (paths.empty() || paths.front().empty()) return multi_run_number; - for (auto path : paths) { + for (const auto &path : paths) { std::string run_number; try { if (Poco::File(path).exists()) { @@ -869,7 +869,7 @@ void EnggDiffractionPresenter::parseCalibrateFilename(const std::string &path, ceriaNo = ""; Poco::Path fullPath(path); - const std::string filename = fullPath.getFileName(); + const std::string &filename = fullPath.getFileName(); if (filename.empty()) { return; } diff --git a/qt/scientific_interfaces/General/deltaECalc.cpp b/qt/scientific_interfaces/General/deltaECalc.cpp index 82379971619c4e4b574ed67150cca8689179da76..a6ceaa0eeb92ef64f5aca5a52b04f5df01cf30ba 100644 --- a/qt/scientific_interfaces/General/deltaECalc.cpp +++ b/qt/scientific_interfaces/General/deltaECalc.cpp @@ -88,8 +88,8 @@ void deltaECalc::createProcessingScript(const QStringList &runFiles, (motorName.isEmpty()) ? "None" : QString("r'" + motorName + "'"); QString None = "None"; - auto rebin = None; - auto map_file = None; + const auto &rebin = None; + const auto &map_file = None; pyCode += "mono_sample.prop_man.motor_name = " + pyMotorName + "\n"; pyCode += "mono_sample.prop_man.motor_offset = " + pySeOffset + "\n"; diff --git a/qt/scientific_interfaces/ISISSANS/SANSAddFiles.cpp b/qt/scientific_interfaces/ISISSANS/SANSAddFiles.cpp index c3f4fc1fea8ba3ad1a92b44b6fd4a9c966e4d415..4a3dadb4a6a775cf3f575e044811304382229780 100644 --- a/qt/scientific_interfaces/ISISSANS/SANSAddFiles.cpp +++ b/qt/scientific_interfaces/ISISSANS/SANSAddFiles.cpp @@ -191,7 +191,7 @@ void SANSAddFiles::add2Runs2Add() { // split comma separated file names or run numbers into a list ArrayProperty<std::string> commaSep( "unusedName", m_SANSForm->new2Add_edit->text().toStdString()); - const std::vector<std::string> nam = commaSep; + const std::vector<std::string> &nam = commaSep; for (std::vector<std::string>::const_iterator i = nam.begin(); i != nam.end(); ++i) { // each comma separated item could be a range of run numbers diff --git a/qt/scientific_interfaces/Indirect/AbsorptionCorrections.cpp b/qt/scientific_interfaces/Indirect/AbsorptionCorrections.cpp index 2ca090fe8e91e27937e9e759f57a69cbd6e623f0..f736a085f1c08f0ba1e211c827781bf37aa83328 100644 --- a/qt/scientific_interfaces/Indirect/AbsorptionCorrections.cpp +++ b/qt/scientific_interfaces/Indirect/AbsorptionCorrections.cpp @@ -48,84 +48,55 @@ void AbsorptionCorrections::setup() {} void AbsorptionCorrections::run() { // Get correct corrections algorithm QString sampleShape = m_uiForm.cbShape->currentText().replace(" ", ""); - QString algorithmName = "Indirect" + sampleShape + "Absorption"; - IAlgorithm_sptr absCorAlgo = - AlgorithmManager::Instance().create(algorithmName.toStdString()); - absCorAlgo->initialize(); + IAlgorithm_sptr monteCarloAbsCor = + AlgorithmManager::Instance().create("CalculateMonteCarloAbsorption"); + monteCarloAbsCor->initialize(); + + monteCarloAbsCor->setProperty("Shape", sampleShape.toStdString()); + + addShapeSpecificSampleOptions(monteCarloAbsCor, sampleShape); // Sample details QString sampleWsName = m_uiForm.dsSampleInput->getCurrentDataName(); - absCorAlgo->setProperty("SampleWorkspace", sampleWsName.toStdString()); + monteCarloAbsCor->setProperty("SampleWorkspace", sampleWsName.toStdString()); - absCorAlgo->setProperty( + monteCarloAbsCor->setProperty( "SampleDensityType", m_uiForm.cbSampleDensity->currentText().toStdString()); - absCorAlgo->setProperty("SampleDensity", m_uiForm.spSampleDensity->value()); + monteCarloAbsCor->setProperty("SampleDensity", + m_uiForm.spSampleDensity->value()); QString sampleChemicalFormula = m_uiForm.leSampleChemicalFormula->text(); - absCorAlgo->setProperty("SampleChemicalFormula", - sampleChemicalFormula.toStdString()); - - addShapeSpecificSampleOptions(absCorAlgo, sampleShape); + monteCarloAbsCor->setProperty("SampleChemicalFormula", + sampleChemicalFormula.toStdString()); // General details - absCorAlgo->setProperty("BeamHeight", m_uiForm.spBeamHeight->value()); - absCorAlgo->setProperty("BeamWidth", m_uiForm.spBeamWidth->value()); + monteCarloAbsCor->setProperty("BeamHeight", m_uiForm.spBeamHeight->value()); + monteCarloAbsCor->setProperty("BeamWidth", m_uiForm.spBeamWidth->value()); long wave = static_cast<long>(m_uiForm.spNumberWavelengths->value()); - absCorAlgo->setProperty("NumberWavelengths", wave); + monteCarloAbsCor->setProperty("NumberOfWavelengthPoints", wave); long events = static_cast<long>(m_uiForm.spNumberEvents->value()); - absCorAlgo->setProperty("Events", events); + monteCarloAbsCor->setProperty("EventsPerPoint", events); // Can details bool useCan = m_uiForm.ckUseCan->isChecked(); if (useCan) { std::string canWsName = m_uiForm.dsCanInput->getCurrentDataName().toStdString(); - std::string shiftedCanName = canWsName + "_shifted"; - IAlgorithm_sptr clone = - AlgorithmManager::Instance().create("CloneWorkspace"); - clone->initialize(); - clone->setProperty("InputWorkspace", canWsName); - clone->setProperty("OutputWorkspace", shiftedCanName); - clone->execute(); - - MatrixWorkspace_sptr shiftedCan = - AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( - shiftedCanName); - if (m_uiForm.ckShiftCan->isChecked()) { - IAlgorithm_sptr scaleX = AlgorithmManager::Instance().create("ScaleX"); - scaleX->initialize(); - scaleX->setProperty("InputWorkspace", shiftedCan); - scaleX->setProperty("OutputWorkspace", shiftedCanName); - scaleX->setProperty("Factor", m_uiForm.spCanShift->value()); - scaleX->setProperty("Operation", "Add"); - scaleX->execute(); - IAlgorithm_sptr rebin = - AlgorithmManager::Instance().create("RebinToWorkspace"); - rebin->initialize(); - rebin->setProperty("WorkspaceToRebin", shiftedCan); - rebin->setProperty("WorkspaceToMatch", sampleWsName.toStdString()); - rebin->setProperty("OutputWorkspace", shiftedCanName); - rebin->execute(); - } - absCorAlgo->setProperty("CanWorkspace", shiftedCanName); + monteCarloAbsCor->setProperty("ContainerWorkspace", canWsName); - bool useCanCorrections = m_uiForm.ckUseCanCorrections->isChecked(); - absCorAlgo->setProperty("UseCanCorrections", useCanCorrections); + monteCarloAbsCor->setProperty( + "ContainerDensityType", + m_uiForm.cbCanDensity->currentText().toStdString()); + monteCarloAbsCor->setProperty("ContainerDensity", + m_uiForm.spCanDensity->value()); - if (useCanCorrections) { - - absCorAlgo->setProperty( - "CanDensityType", m_uiForm.cbCanDensity->currentText().toStdString()); - absCorAlgo->setProperty("CanDensity", m_uiForm.spCanDensity->value()); - - QString canChemicalFormula = m_uiForm.leCanChemicalFormula->text(); - absCorAlgo->setProperty("CanChemicalFormula", - canChemicalFormula.toStdString()); - } + QString canChemicalFormula = m_uiForm.leCanChemicalFormula->text(); + monteCarloAbsCor->setProperty("ContainerChemicalFormula", + canChemicalFormula.toStdString()); - addShapeSpecificCanOptions(absCorAlgo, sampleShape); + addShapeSpecificCanOptions(monteCarloAbsCor, sampleShape); } // Generate workspace names @@ -135,20 +106,16 @@ void AbsorptionCorrections::run() { QString outputBaseName = sampleWsName.left(nameCutIndex); - QString outputWsName = outputBaseName + "_" + sampleShape + "_red"; - absCorAlgo->setProperty("OutputWorkspace", outputWsName.toStdString()); + QString outputWsName = outputBaseName + "_" + sampleShape + "_Corrections"; - // Set the correction workspace to keep the factors if desired - bool keepCorrectionFactors = m_uiForm.ckKeepFactors->isChecked(); - QString outputFactorsWsName = outputBaseName + "_" + sampleShape + "_Factors"; - if (keepCorrectionFactors) - absCorAlgo->setProperty("CorrectionsWorkspace", - outputFactorsWsName.toStdString()); + monteCarloAbsCor->setProperty("CorrectionsWorkspace", + outputWsName.toStdString()); // Add correction algorithm to batch - m_batchAlgoRunner->addAlgorithm(absCorAlgo); + m_batchAlgoRunner->addAlgorithm(monteCarloAbsCor); + + m_absCorAlgo = monteCarloAbsCor; - m_absCorAlgo = absCorAlgo; // Run algorithm batch m_batchAlgoRunner->executeBatchAsync(); @@ -164,9 +131,10 @@ void AbsorptionCorrections::run() { */ void AbsorptionCorrections::addShapeSpecificSampleOptions(IAlgorithm_sptr alg, QString shape) { + if (shape == "FlatPlate") { double sampleHeight = m_uiForm.spFlatSampleHeight->value(); - alg->setProperty("SampleHeight", sampleHeight); + alg->setProperty("Height", sampleHeight); double sampleWidth = m_uiForm.spFlatSampleWidth->value(); alg->setProperty("SampleWidth", sampleWidth); @@ -178,24 +146,21 @@ void AbsorptionCorrections::addShapeSpecificSampleOptions(IAlgorithm_sptr alg, alg->setProperty("SampleAngle", sampleAngle); } else if (shape == "Annulus") { + double sampleHeight = m_uiForm.spAnnSampleHeight->value(); + alg->setProperty("Height", sampleHeight); + double sampleInnerRadius = m_uiForm.spAnnSampleInnerRadius->value(); alg->setProperty("SampleInnerRadius", sampleInnerRadius); double sampleOuterRadius = m_uiForm.spAnnSampleOuterRadius->value(); alg->setProperty("SampleOuterRadius", sampleOuterRadius); - double canInnerRadius = m_uiForm.spAnnCanInnerRadius->value(); - alg->setProperty("CanInnerRadius", canInnerRadius); - - double canOuterRadius = m_uiForm.spAnnCanOuterRadius->value(); - alg->setProperty("CanOuterRadius", canOuterRadius); - } else if (shape == "Cylinder") { double sampleRadius = m_uiForm.spCylSampleRadius->value(); alg->setProperty("SampleRadius", sampleRadius); double sampleHeight = m_uiForm.spCylSampleHeight->value(); - alg->setProperty("SampleHeight", sampleHeight); + alg->setProperty("Height", sampleHeight); } } @@ -211,13 +176,23 @@ void AbsorptionCorrections::addShapeSpecificCanOptions(IAlgorithm_sptr alg, QString shape) { if (shape == "FlatPlate") { double canFrontThickness = m_uiForm.spFlatCanFrontThickness->value(); - alg->setProperty("CanFrontThickness", canFrontThickness); + alg->setProperty("ContainerFrontThickness", canFrontThickness); double canBackThickness = m_uiForm.spFlatCanBackThickness->value(); - alg->setProperty("CanBackThickness", canBackThickness); + alg->setProperty("ContainerBackThickness", canBackThickness); } else if (shape == "Cylinder") { - double canRadius = m_uiForm.spCylCanRadius->value(); - alg->setProperty("CanRadius", canRadius); + double canInnerRadius = m_uiForm.spCylCanInnerRadius->value(); + alg->setProperty("ContainerInnerRadius", canInnerRadius); + + double canOuterRadius = m_uiForm.spCylCanOuterRadius->value(); + alg->setProperty("ContainerOuterRadius", canOuterRadius); + + } else if (shape == "Annulus") { + double canInnerRadius = m_uiForm.spAnnCanInnerRadius->value(); + alg->setProperty("ContainerInnerRadius", canInnerRadius); + + double canOuterRadius = m_uiForm.spAnnCanOuterRadius->value(); + alg->setProperty("ContainerOuterRadius", canOuterRadius); } } @@ -251,12 +226,10 @@ bool AbsorptionCorrections::validate() { if (useCan) { uiv.checkDataSelectorIsValid("Container", m_uiForm.dsCanInput); - bool useCanCorrections = m_uiForm.ckUseCanCorrections->isChecked(); - if (useCanCorrections) { - if (uiv.checkFieldIsNotEmpty("Container Chemical Formula", - m_uiForm.leCanChemicalFormula)) - uiv.checkFieldIsValid("Container Chemical Formula", - m_uiForm.leCanChemicalFormula); + if (uiv.checkFieldIsNotEmpty("Container Chemical Formula", + m_uiForm.leCanChemicalFormula)) { + uiv.checkFieldIsValid("Container Chemical Formula", + m_uiForm.leCanChemicalFormula); } } @@ -284,17 +257,7 @@ void AbsorptionCorrections::algorithmComplete(bool error) { emit showMessageBox( "Could not run absorption corrections.\nSee Results Log for details."); } - if (m_uiForm.ckShiftCan->isChecked()) { - IAlgorithm_sptr shiftLog = - AlgorithmManager::Instance().create("AddSampleLog"); - shiftLog->initialize(); - shiftLog->setProperty("Workspace", m_pythonExportWsName); - shiftLog->setProperty("LogName", "container_shift"); - shiftLog->setProperty("logType", "Number"); - shiftLog->setProperty("LogText", boost::lexical_cast<std::string>( - m_uiForm.spCanShift->value())); - shiftLog->execute(); - } + // Enable plot and save m_uiForm.pbPlot->setEnabled(true); m_uiForm.pbSave->setEnabled(true); @@ -336,12 +299,11 @@ void AbsorptionCorrections::saveClicked() { if (checkADSForPlotSaveWorkspace(m_pythonExportWsName, false)) addSaveWorkspaceToQueue(QString::fromStdString(m_pythonExportWsName)); - if (m_uiForm.ckKeepFactors->isChecked()) { - std::string factorsWs = - m_absCorAlgo->getPropertyValue("CorrectionsWorkspace"); - if (checkADSForPlotSaveWorkspace(factorsWs, false)) - addSaveWorkspaceToQueue(QString::fromStdString(factorsWs)); - } + std::string factorsWs = + m_absCorAlgo->getPropertyValue("CorrectionsWorkspace"); + if (checkADSForPlotSaveWorkspace(factorsWs, false)) + addSaveWorkspaceToQueue(QString::fromStdString(factorsWs)); + m_batchAlgoRunner->executeBatchAsync(); } @@ -354,17 +316,16 @@ void AbsorptionCorrections::plotClicked() { m_uiForm.dsSampleInput->getCurrentDataName()}; auto outputFactorsWsName = m_absCorAlgo->getPropertyValue("CorrectionsWorkspace"); - if (m_uiForm.ckKeepFactors->isChecked()) { - QStringList plotCorr = {QString::fromStdString(outputFactorsWsName) + - "_ass"}; - if (m_uiForm.ckUseCanCorrections->isChecked()) { - plotCorr.push_back(QString::fromStdString(outputFactorsWsName) + "_acc"); - QString shiftedWs = QString::fromStdString( - m_absCorAlgo->getPropertyValue("CanWorkspace")); - plotData.push_back(shiftedWs); - } - plotSpectrum(plotCorr, 0); + + QStringList plotCorr = {QString::fromStdString(outputFactorsWsName) + "_ass"}; + if (m_uiForm.ckUseCan->isChecked()) { + plotCorr.push_back(QString::fromStdString(outputFactorsWsName) + "_acc"); + QString shiftedWs = QString::fromStdString( + m_absCorAlgo->getPropertyValue("ContainerWorkspace")); + plotData.push_back(shiftedWs); } + plotSpectrum(plotCorr, 0); + plotSpectrum(plotData, 0); } diff --git a/qt/scientific_interfaces/Indirect/AbsorptionCorrections.ui b/qt/scientific_interfaces/Indirect/AbsorptionCorrections.ui index e6c1de5d189be2a71167ac3739a9ec051312086b..8d92333c8db380415834010d6267a8f0bb4d70c3 100644 --- a/qt/scientific_interfaces/Indirect/AbsorptionCorrections.ui +++ b/qt/scientific_interfaces/Indirect/AbsorptionCorrections.ui @@ -276,16 +276,7 @@ </property> <widget class="QWidget" name="pgAbsCorFlatPlate"> <layout class="QGridLayout" name="loFlatPlate"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> + <property name="margin"> <number>0</number> </property> <item row="1" column="3"> @@ -415,19 +406,22 @@ </widget> </item> </layout> + <zorder>spFlatSampleHeight</zorder> + <zorder>lbFlatSampleThickness</zorder> + <zorder>spFlatCanFrontThickness</zorder> + <zorder>lbFlatCanFrontThickness</zorder> + <zorder>lbFlatSampleWidth</zorder> + <zorder>lbFlatSampleHeight</zorder> + <zorder>spFlatCanBackThickness</zorder> + <zorder>spFlatSampleThickness</zorder> + <zorder>lbFlatCanBackThickness</zorder> + <zorder>spFlatSampleAngle</zorder> + <zorder>lbFlatSampleAngle</zorder> + <zorder>spFlatSampleWidth</zorder> </widget> <widget class="QWidget" name="pgAbsCorAnnulus"> <layout class="QGridLayout" name="loAnnulus"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> + <property name="margin"> <number>0</number> </property> <item row="1" column="0"> @@ -546,20 +540,11 @@ </widget> <widget class="QWidget" name="pgAbsCorCylinder"> <layout class="QGridLayout" name="loCylinder"> - <property name="leftMargin"> - <number>0</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> + <property name="margin"> <number>0</number> </property> <item row="0" column="3"> - <widget class="QDoubleSpinBox" name="spCylCanRadius"> + <widget class="QDoubleSpinBox" name="spCylCanInnerRadius"> <property name="enabled"> <bool>false</bool> </property> @@ -588,12 +573,12 @@ </widget> </item> <item row="0" column="2"> - <widget class="QLabel" name="lbCylCanRadius"> + <widget class="QLabel" name="lbCylCanInnerRadius"> <property name="enabled"> <bool>false</bool> </property> <property name="text"> - <string>Container Radius:</string> + <string>Container Inner Radius:</string> </property> </widget> </item> @@ -624,6 +609,29 @@ </property> </widget> </item> + <item row="1" column="2"> + <widget class="QLabel" name="lbCylCanOuterRadius"> + <property name="text"> + <string>Container Outer Radius</string> + </property> + </widget> + </item> + <item row="1" column="3"> + <widget class="QDoubleSpinBox" name="spCylCanOuterRadius"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="suffix"> + <string> cm</string> + </property> + <property name="decimals"> + <number>5</number> + </property> + <property name="singleStep"> + <double>0.100000000000000</double> + </property> + </widget> + </item> </layout> </widget> </widget> @@ -696,14 +704,21 @@ <string>Container Details</string> </property> <layout class="QGridLayout" name="gridLayout_2"> - <item row="4" column="2"> - <widget class="QLabel" name="lbCanChemicalFormula"> - <property name="text"> - <string>Chemical Formula:</string> - </property> + <item row="2" 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> - <item row="4" column="1"> + <item row="2" column="1"> <widget class="QDoubleSpinBox" name="spCanDensity"> <property name="enabled"> <bool>false</bool> @@ -722,7 +737,14 @@ </property> </widget> </item> - <item row="4" column="3"> + <item row="2" column="2"> + <widget class="QLabel" name="lbCanChemicalFormula"> + <property name="text"> + <string>Chemical Formula:</string> + </property> + </widget> + </item> + <item row="2" column="3"> <widget class="QLineEdit" name="leCanChemicalFormula"> <property name="enabled"> <bool>false</bool> @@ -735,79 +757,6 @@ </property> </widget> </item> - <item row="2" column="3"> - <widget class="QDoubleSpinBox" name="spCanScale"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="decimals"> - <number>5</number> - </property> - <property name="singleStep"> - <double>0.100000000000000</double> - </property> - <property name="value"> - <double>1.000000000000000</double> - </property> - </widget> - </item> - <item row="2" column="2"> - <widget class="QCheckBox" name="ckScaleCan"> - <property name="text"> - <string>Scale:</string> - </property> - </widget> - </item> - <item row="3" column="3"> - <widget class="QDoubleSpinBox" name="spCanShift"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="decimals"> - <number>5</number> - </property> - <property name="minimum"> - <double>-1000.000000000000000</double> - </property> - <property name="maximum"> - <double>999.999990000000025</double> - </property> - <property name="singleStep"> - <double>0.010000000000000</double> - </property> - <property name="value"> - <double>0.000000000000000</double> - </property> - </widget> - </item> - <item row="3" column="2"> - <widget class="QCheckBox" name="ckShiftCan"> - <property name="text"> - <string>Shift x-values of container by adding:</string> - </property> - </widget> - </item> - <item row="2" column="0" colspan="2"> - <widget class="QCheckBox" name="ckUseCanCorrections"> - <property name="text"> - <string>Use Container Corrections</string> - </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> @@ -823,26 +772,6 @@ <string>Output Options</string> </property> <layout class="QHBoxLayout" name="horizontalLayout_2"> - <item> - <widget class="QCheckBox" name="ckKeepFactors"> - <property name="text"> - <string>Keep Correction Factors</string> - </property> - </widget> - </item> - <item> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> - </property> - </spacer> - </item> <item> <widget class="QPushButton" name="pbPlot"> <property name="enabled"> @@ -890,28 +819,32 @@ </customwidgets> <tabstops> <tabstop>ckUseCan</tabstop> + <tabstop>spNumberWavelengths</tabstop> + <tabstop>spNumberEvents</tabstop> + <tabstop>spBeamWidth</tabstop> + <tabstop>spBeamHeight</tabstop> <tabstop>cbShape</tabstop> <tabstop>spFlatSampleWidth</tabstop> <tabstop>spFlatSampleHeight</tabstop> <tabstop>spFlatSampleThickness</tabstop> + <tabstop>spFlatSampleAngle</tabstop> <tabstop>spFlatCanFrontThickness</tabstop> <tabstop>spFlatCanBackThickness</tabstop> <tabstop>spAnnSampleInnerRadius</tabstop> <tabstop>spAnnSampleOuterRadius</tabstop> + <tabstop>spAnnSampleHeight</tabstop> <tabstop>spAnnCanInnerRadius</tabstop> <tabstop>spAnnCanOuterRadius</tabstop> <tabstop>spCylSampleRadius</tabstop> - <tabstop>spCylCanRadius</tabstop> + <tabstop>spCylCanInnerRadius</tabstop> + <tabstop>spCylSampleHeight</tabstop> + <tabstop>spCylCanOuterRadius</tabstop> + <tabstop>cbSampleDensity</tabstop> <tabstop>spSampleDensity</tabstop> <tabstop>leSampleChemicalFormula</tabstop> - <tabstop>ckUseCanCorrections</tabstop> - <tabstop>ckScaleCan</tabstop> - <tabstop>spCanScale</tabstop> - <tabstop>ckShiftCan</tabstop> - <tabstop>spCanShift</tabstop> + <tabstop>cbCanDensity</tabstop> <tabstop>spCanDensity</tabstop> <tabstop>leCanChemicalFormula</tabstop> - <tabstop>ckKeepFactors</tabstop> <tabstop>pbPlot</tabstop> <tabstop>pbSave</tabstop> </tabstops> @@ -924,8 +857,8 @@ <slot>setCurrentIndex(int)</slot> <hints> <hint type="sourcelabel"> - <x>782</x> - <y>291</y> + <x>783</x> + <y>324</y> </hint> <hint type="destinationlabel"> <x>315</x> @@ -934,274 +867,290 @@ </hints> </connection> <connection> - <sender>ckScaleCan</sender> + <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spCanScale</receiver> + <receiver>dsCanInput</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>549</x> - <y>507</y> + <x>194</x> + <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>509</y> + <x>784</x> + <y>67</y> </hint> </hints> </connection> <connection> - <sender>ckShiftCan</sender> + <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spCanShift</receiver> + <receiver>gbContainerDetails</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>549</x> - <y>533</y> + <x>194</x> + <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>535</y> + <x>305</x> + <y>571</y> + </hint> + </hints> + </connection> + <connection> + <sender>spFlatCanFrontThickness</sender> + <signal>valueChanged(double)</signal> + <receiver>spFlatCanBackThickness</receiver> + <slot>setValue(double)</slot> + <hints> + <hint type="sourcelabel"> + <x>402</x> + <y>424</y> + </hint> + <hint type="destinationlabel"> + <x>784</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>dsCanInput</receiver> + <receiver>lbFlatCanFrontThickness</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>194</x> + <x>140</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>60</y> + <x>175</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>gbContainerDetails</receiver> + <receiver>spFlatCanFrontThickness</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>194</x> + <x>241</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>305</x> - <y>571</y> + <x>402</x> + <y>424</y> </hint> </hints> </connection> <connection> - <sender>ckUseCanCorrections</sender> + <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>leCanChemicalFormula</receiver> + <receiver>lbFlatCanBackThickness</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>175</x> - <y>507</y> + <x>255</x> + <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>561</y> + <x>593</x> + <y>424</y> </hint> </hints> </connection> <connection> - <sender>ckUseCanCorrections</sender> + <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spCanDensity</receiver> + <receiver>spFlatCanBackThickness</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>175</x> - <y>507</y> + <x>229</x> + <y>69</y> </hint> <hint type="destinationlabel"> - <x>386</x> - <y>561</y> + <x>784</x> + <y>424</y> </hint> </hints> </connection> <connection> - <sender>spFlatCanFrontThickness</sender> - <signal>valueChanged(double)</signal> - <receiver>spFlatCanBackThickness</receiver> - <slot>setValue(double)</slot> + <sender>ckUseCan</sender> + <signal>toggled(bool)</signal> + <receiver>lbAnnCanInnerRadius</receiver> + <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>398</x> - <y>370</y> + <x>169</x> + <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>370</y> + <x>65</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>lbFlatCanFrontThickness</receiver> + <receiver>spAnnCanInnerRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>140</x> + <x>246</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>149</x> - <y>370</y> + <x>282</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spFlatCanFrontThickness</receiver> + <receiver>lbAnnCanOuterRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>241</x> + <x>308</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>398</x> - <y>370</y> + <x>501</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>lbFlatCanBackThickness</receiver> + <receiver>spAnnCanOuterRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>255</x> + <x>334</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>590</x> - <y>370</y> + <x>718</x> + <y>424</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spFlatCanBackThickness</receiver> + <receiver>lbCylCanInnerRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>229</x> + <x>132</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>783</x> - <y>370</y> + <x>501</x> + <y>369</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>lbAnnCanInnerRadius</receiver> + <receiver>spCylCanInnerRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>169</x> + <x>243</x> <y>69</y> </hint> <hint type="destinationlabel"> - <x>39</x> - <y>328</y> + <x>718</x> + <y>369</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spAnnCanInnerRadius</receiver> + <receiver>cbCanDensity</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>246</x> - <y>69</y> + <x>208</x> + <y>71</y> </hint> <hint type="destinationlabel"> - <x>65</x> - <y>328</y> + <x>112</x> + <y>579</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>lbAnnCanOuterRadius</receiver> + <receiver>spCanDensity</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>308</x> - <y>69</y> + <x>208</x> + <y>71</y> </hint> <hint type="destinationlabel"> - <x>92</x> - <y>328</y> + <x>305</x> + <y>579</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> <signal>toggled(bool)</signal> - <receiver>spAnnCanOuterRadius</receiver> + <receiver>leCanChemicalFormula</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>334</x> - <y>69</y> + <x>208</x> + <y>71</y> </hint> <hint type="destinationlabel"> - <x>118</x> - <y>328</y> + <x>690</x> + <y>579</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> - <signal>toggled(bool)</signal> - <receiver>lbCylCanRadius</receiver> + <signal>clicked(bool)</signal> + <receiver>lbCylCanOuterRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>132</x> - <y>69</y> + <x>57</x> + <y>67</y> </hint> <hint type="destinationlabel"> - <x>92</x> - <y>310</y> + <x>532</x> + <y>408</y> </hint> </hints> </connection> <connection> <sender>ckUseCan</sender> - <signal>toggled(bool)</signal> - <receiver>spCylCanRadius</receiver> + <signal>clicked(bool)</signal> + <receiver>spCylCanOuterRadius</receiver> <slot>setEnabled(bool)</slot> <hints> <hint type="sourcelabel"> - <x>243</x> - <y>69</y> + <x>38</x> + <y>66</y> </hint> <hint type="destinationlabel"> - <x>118</x> - <y>310</y> + <x>646</x> + <y>411</y> </hint> </hints> </connection> diff --git a/qt/scientific_interfaces/Indirect/ApplyPaalmanPings.cpp b/qt/scientific_interfaces/Indirect/ApplyPaalmanPings.cpp index 04b8947fadc4b0d2af91bec8b1b5e69d5ede4b4c..7670a38feb0a5afe0a248bf7594a60afb6a94714 100644 --- a/qt/scientific_interfaces/Indirect/ApplyPaalmanPings.cpp +++ b/qt/scientific_interfaces/Indirect/ApplyPaalmanPings.cpp @@ -407,9 +407,12 @@ void ApplyPaalmanPings::postProcessComplete(bool error) { // Clean up unwanted workspaces IAlgorithm_sptr deleteAlg = AlgorithmManager::Instance().create("DeleteWorkspace"); - deleteAlg->initialize(); - deleteAlg->setProperty("Workspace", "__algorithm_can"); - deleteAlg->execute(); + if (AnalysisDataService::Instance().doesExist("__algorithm_can")) { + + deleteAlg->initialize(); + deleteAlg->setProperty("Workspace", "__algorithm_can"); + deleteAlg->execute(); + } const auto conv = AnalysisDataService::Instance().doesExist("__algorithm_can_Wavelength"); if (conv) { diff --git a/qt/scientific_interfaces/Indirect/ConvFit.cpp b/qt/scientific_interfaces/Indirect/ConvFit.cpp index fc93a1ccf03b2a02b9208ecc526efdb0883c9965..3a547fc95890def6592ad7b2feb1a912f0f604cc 100644 --- a/qt/scientific_interfaces/Indirect/ConvFit.cpp +++ b/qt/scientific_interfaces/Indirect/ConvFit.cpp @@ -30,8 +30,8 @@ namespace IDA { ConvFit::ConvFit(QWidget *parent) : IndirectDataAnalysisTab(parent), m_stringManager(nullptr), - m_cfTree(nullptr), m_fixedProps(), m_cfInputWS(), m_cfInputWSName(), - m_confitResFileType(), m_runMin(-1), m_runMax(-1) { + m_cfTree(nullptr), m_fixedProps(), m_confitResFileType(), m_runMin(-1), + m_runMax(-1) { m_uiForm.setupUi(parent); } @@ -106,18 +106,16 @@ void ConvFit::setup() { m_cfTree->addProperty(m_properties["LinearBackground"]); // Delta Function - m_properties["DeltaFunction"] = m_grpManager->addProperty("Delta Function"); + m_properties["Delta Function"] = m_grpManager->addProperty("Delta Function"); m_properties["UseDeltaFunc"] = m_blnManager->addProperty("Use"); - m_properties["DeltaHeight"] = m_dblManager->addProperty("Height"); - m_properties["DeltaCentre"] = m_dblManager->addProperty("Centre"); - m_dblManager->setDecimals(m_properties["DeltaHeight"], NUM_DECIMALS); - m_properties["DeltaFunction"]->addSubProperty(m_properties["UseDeltaFunc"]); - m_dblManager->setDecimals(m_properties["DeltaCentre"], NUM_DECIMALS); - m_cfTree->addProperty(m_properties["DeltaFunction"]); + m_properties["Delta Function"]->addSubProperty(m_properties["UseDeltaFunc"]); + m_properties["Delta Function"] = + createFitType(m_properties["Delta Function"], false); + m_cfTree->addProperty(m_properties["Delta Function"]); // Fit functions - m_properties["Lorentzian1"] = createFitType("Lorentzian 1"); - m_properties["Lorentzian2"] = createFitType("Lorentzian 2"); + m_properties["Lorentzian 1"] = createFitType("Lorentzian 1"); + m_properties["Lorentzian 2"] = createFitType("Lorentzian 2"); m_properties["DiffSphere"] = createFitType("DiffSphere"); m_properties["DiffRotDiscreteCircle"] = createFitType("DiffRotDiscreteCircle"); @@ -129,10 +127,14 @@ void ConvFit::setup() { createFitType("InelasticDiffRotDiscreteCircle"); m_properties["StretchedExpFT"] = createFitType("StretchedExpFT"); + // Instrument resolution + m_properties["InstrumentResolution"] = + m_dblManager->addProperty("InstrumentResolution"); + // Update fit parameters in browser when function is selected - connect(m_uiForm.cbFitType, SIGNAL(currentIndexChanged(QString)), this, - SLOT(fitFunctionSelected(const QString &))); - fitFunctionSelected(m_uiForm.cbFitType->currentText()); + connect(m_uiForm.cbFitType, SIGNAL(currentIndexChanged(int)), this, + SLOT(fitFunctionSelected(int))); + fitFunctionSelected(m_uiForm.cbFitType->currentIndex()); m_uiForm.leTempCorrection->setValidator(new QDoubleValidator(m_parentWidget)); @@ -173,10 +175,16 @@ void ConvFit::setup() { // Replot input automatically when file / spec no changes connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, - SLOT(plotSpecChanged(int))); + SLOT(updatePlot())); + connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, + SLOT(updateProperties(int))); + connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, + SLOT(IndirectDataAnalysisTab::setSelectedSpectrum(int))); + connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString &)), this, SLOT(newDataLoaded(const QString &))); - + connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString &)), this, + SLOT(updatePlotRange())); connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString &)), this, SLOT(extendResolutionWorkspace())); connect(m_uiForm.dsResInput, SIGNAL(dataReady(const QString &)), this, @@ -210,15 +218,13 @@ void ConvFit::setup() { SLOT(plotCurrentPreview())); m_uiForm.ckTieCentres->setChecked(true); - m_previousFit = m_uiForm.cbFitType->currentText(); - m_fittedIndex = -1; updatePlotOptions(); } /** Setup FABADA minimizer options -* -*/ + * + */ void ConvFit::initFABADAOptions() { m_properties["FABADA"] = m_grpManager->addProperty("Bayesian"); @@ -283,15 +289,16 @@ void ConvFit::initFABADAOptions() { } /** -* Handles the initial set up and running of the ConvolutionFitSequential -* algorithm -*/ + * Handles the initial set up and running of the ConvolutionFitSequential + * algorithm + */ void ConvFit::run() { // Get input from interface m_runMin = m_uiForm.spSpectraMin->value(); m_runMax = m_uiForm.spSpectraMax->value(); const auto specMin = m_uiForm.spSpectraMin->text().toStdString(); const auto specMax = m_uiForm.spSpectraMax->text().toStdString(); + m_fitFunctions = indexToFitFunctions(m_uiForm.cbFitType->currentIndex()); auto cfs = sequentialFit(specMin, specMax, m_baseName); // Add to batch alg runner and execute @@ -304,11 +311,12 @@ void ConvFit::run() { IAlgorithm_sptr ConvFit::sequentialFit(const std::string &specMin, const std::string &specMax, QString &outputWSName) { - const auto func = createFunction(m_uiForm.ckTieCentres->isChecked()); + const auto func = createFunction(m_uiForm.ckTieCentres->isChecked() && + m_uiForm.ckTieCentres->isVisible()); const auto function = std::string(func->asString()); // Construct expected name - outputWSName = QString::fromStdString(m_cfInputWS->getName()); + outputWSName = QString::fromStdString(inputWorkspace()->getName()); // Remove _red const auto cutIndex = outputWSName.lastIndexOf("_"); @@ -319,7 +327,6 @@ IAlgorithm_sptr ConvFit::sequentialFit(const std::string &specMin, // Add fit specific suffix const auto bgType = backgroundString(); const auto fitType = fitTypeString(); - m_fittedIndex = m_uiForm.cbFitType->currentIndex(); outputWSName += "conv_"; outputWSName += fitType; outputWSName += bgType; @@ -333,7 +340,7 @@ IAlgorithm_sptr ConvFit::sequentialFit(const std::string &specMin, // Run ConvolutionFitSequential Algorithm auto cfs = AlgorithmManager::Instance().create("ConvolutionFitSequential"); cfs->initialize(); - cfs->setProperty("InputWorkspace", m_cfInputWS->getName()); + cfs->setProperty("InputWorkspace", inputWorkspace()); cfs->setProperty("Function", function); cfs->setProperty("PassWSIndexToFunction", true); cfs->setProperty("BackgroundType", @@ -419,36 +426,15 @@ void ConvFit::plotClicked() { } /** - * Plots the current spectrum displayed in the preview plot + * Handles completion of the ConvolutionFitSequential algorithm. + * + * @param error True if the algorithm was stopped due to error, false otherwise + * @param outputWSName The name of the output workspace created from running the + * algorithm. */ -void ConvFit::plotCurrentPreview() { - if (!m_cfInputWS) { - return; - } - if (m_cfInputWS->getName().compare(m_previewPlotData->getName()) == 0) { - // Plot only the sample curve - const auto workspaceIndex = m_uiForm.spPlotSpectrum->value(); - IndirectTab::plotSpectrum( - QString::fromStdString(m_previewPlotData->getName()), workspaceIndex, - workspaceIndex); - } else { - // Plot Sample, Fit and Diff curve - IndirectTab::plotSpectrum( - QString::fromStdString(m_previewPlotData->getName()), 0, 2); - } -} - -/** -* Handles completion of the ConvolutionFitSequential algorithm. -* -* @param error True if the algorithm was stopped due to error, false otherwise -* @param outputWSName The name of the output workspace created from running the -* algorithm. -*/ void ConvFit::algorithmComplete(bool error, const QString &outputWSName) { if (error) { - m_fittedIndex = -1; return; } @@ -465,16 +451,19 @@ void ConvFit::algorithmComplete(bool error, const QString &outputWSName) { addSampleLogsToWorkspace(resultName, "resolution_filename", resFile, "String"); addSampleLogsToWorkspace(groupName, "resolution_filename", resFile, "String"); + bool usedTemperature = false; // Check if temperature is used and is valid if (m_uiForm.ckTempCorrection->isChecked()) { const QString temperature = m_uiForm.leTempCorrection->text(); double temp = 0.0; - if (temperature.toStdString().compare("") != 0) { + + if (!temperature.isEmpty()) { temp = temperature.toDouble(); } if (temp != 0.0) { + usedTemperature = true; // Add sample logs for temperature const auto temperatureStr = temperature.toStdString(); addSampleLogsToWorkspace(resultName, "temperature_correction", "true", @@ -489,20 +478,81 @@ void ConvFit::algorithmComplete(bool error, const QString &outputWSName) { } } m_batchAlgoRunner->executeBatchAsync(); + updatePlot(); + updatePlotRange(); - std::string paramWsName = outputPrefix + "_Parameters"; + std::string paramWsName = outputPrefix + "_Parameters_new"; if (AnalysisDataService::Instance().doesExist(paramWsName)) { - m_paramWs = AnalysisDataService::Instance().retrieveWS<ITableWorkspace>( - paramWsName); - updateParameters(m_uiForm.spPlotSpectrum->value()); + QString prefixPrefix = "f1.f1."; + QString prefixSuffix = usedTemperature ? "f1." : "f0."; + + m_propertyToParameter = createPropertyToParameterMap( + m_fitFunctions, prefixPrefix, prefixSuffix); + m_parameterValues = IndirectTab::extractParametersFromTable( + paramWsName, m_propertyToParameter.values().toSet(), m_runMin, + m_runMax); + + updateProperties(m_uiForm.spPlotSpectrum->value()); } m_uiForm.pbSave->setEnabled(true); m_uiForm.pbPlot->setEnabled(true); } +QHash<QString, QString> +ConvFit::createPropertyToParameterMap(const QVector<QString> &functionNames, + const QString &prefixPrefix, + const QString &prefixSuffix) { + QHash<QString, QString> propertyToParameter; + + if (functionNames.size() == 1) { + QString prefix = prefixPrefix; + + if (functionNames[0] != "Delta Function") { + prefix += prefixSuffix; + } + + extendPropertyToParameterMap(functionNames[0], prefixPrefix + prefixSuffix, + propertyToParameter); + } else { + + for (int i = 0; i < functionNames.size(); ++i) { + extendPropertyToParameterMap(functionNames[i], i, prefixPrefix, + prefixSuffix, propertyToParameter); + } + } + + propertyToParameter["f0.A0"] = "BackgroundA0"; + return propertyToParameter; +} + +void ConvFit::extendPropertyToParameterMap( + const QString &functionName, const int &funcIndex, + const QString &prefixPrefix, const QString &prefixSuffix, + QHash<QString, QString> &propertyToParameter) { + QString prefix; + + if (functionName == "Delta Function") { + prefix = prefixPrefix + prefixSuffix; + } else { + prefix = + prefixPrefix + "f" + QString::number(funcIndex) + "." + prefixSuffix; + } + + extendPropertyToParameterMap(functionName, prefix, propertyToParameter); +} + +void ConvFit::extendPropertyToParameterMap( + const QString &functionName, const QString &prefix, + QHash<QString, QString> &propertyToParameter) { + + for (auto ¶mName : getFunctionParameters(functionName)) { + propertyToParameter[functionName + "." + paramName] = prefix + paramName; + } +} + /** * Sets up and add an instance of the AddSampleLog algorithm to the batch * algorithm runner @@ -526,9 +576,9 @@ void ConvFit::addSampleLogsToWorkspace(const std::string &workspaceName, } /** -* Validates the user's inputs in the ConvFit tab. -* @return If the validation was successful -*/ + * Validates the user's inputs in the ConvFit tab. + * @return If the validation was successful + */ bool ConvFit::validate() { UserInputValidator uiv; @@ -565,28 +615,27 @@ bool ConvFit::validate() { } /** -* Reads in settings files -* @param settings The name of the QSettings object to retrieve data from -*/ + * Reads in settings files + * @param settings The name of the QSettings object to retrieve data from + */ void ConvFit::loadSettings(const QSettings &settings) { m_uiForm.dsSampleInput->readSettings(settings.group()); m_uiForm.dsResInput->readSettings(settings.group()); } /** -* Called when new data has been loaded by the data selector. -* -* Configures ranges for spin boxes before raw plot is done. -* -* @param wsName Name of new workspace loaded -*/ + * Called when new data has been loaded by the data selector. + * + * Configures ranges for spin boxes before raw plot is done. + * + * @param wsName Name of new workspace loaded + */ void ConvFit::newDataLoaded(const QString wsName) { - m_cfInputWSName = wsName; - m_cfInputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( - m_cfInputWSName.toStdString()); + auto inputWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + wsName.toStdString()); + setInputWorkspace(inputWs); - const int maxWsIndex = - static_cast<int>(m_cfInputWS->getNumberHistograms()) - 1; + const int maxWsIndex = static_cast<int>(inputWs->getNumberHistograms()) - 1; m_uiForm.spPlotSpectrum->setMaximum(maxWsIndex); m_uiForm.spPlotSpectrum->setMinimum(0); @@ -603,21 +652,23 @@ void ConvFit::newDataLoaded(const QString wsName) { } /** -* Create a resolution workspace with the same number of histograms as in the -* sample, if the resolution and sample differ in their number of histograms. -* -* Needed to allow DiffSphere and DiffRotDiscreteCircle fit functions to work as -* they need to have the WorkspaceIndex attribute set. -*/ + * Create a resolution workspace with the same number of histograms as in the + * sample, if the resolution and sample differ in their number of histograms. + * + * Needed to allow DiffSphere and DiffRotDiscreteCircle fit functions to work as + * they need to have the WorkspaceIndex attribute set. + */ void ConvFit::extendResolutionWorkspace() { - if (m_cfInputWS && m_uiForm.dsResInput->isValid()) { - const QString resWsName = m_uiForm.dsResInput->getCurrentDataName(); + auto inputWs = inputWorkspace(); + + if (inputWs && m_uiForm.dsResInput->isValid()) { + const std::string resWsName = + m_uiForm.dsResInput->getCurrentDataName().toStdString(); // Check spectra consistency between resolution and sample auto resolutionInputWS = - AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( - resWsName.toStdString()); + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(resWsName); size_t resolutionNumHist = resolutionInputWS->getNumberHistograms(); - size_t numHist = m_cfInputWS->getNumberHistograms(); + size_t numHist = inputWs->getNumberHistograms(); if (resolutionNumHist != 1 && resolutionNumHist != numHist) { std::string msg( "Resolution must have either one or as many spectra as the sample"); @@ -628,7 +679,7 @@ void ConvFit::extendResolutionWorkspace() { AlgorithmManager::Instance().create("CloneWorkspace"); cloneAlg->setLogging(false); cloneAlg->initialize(); - cloneAlg->setProperty("InputWorkspace", resWsName.toStdString()); + cloneAlg->setProperty("InputWorkspace", resWsName); cloneAlg->setProperty("OutputWorkspace", "__ConvFit_Resolution"); cloneAlg->execute(); // Append to cloned workspace if necessary @@ -638,7 +689,7 @@ void ConvFit::extendResolutionWorkspace() { appendAlg->setLogging(false); appendAlg->initialize(); appendAlg->setPropertyValue("InputWorkspace1", "__ConvFit_Resolution"); - appendAlg->setPropertyValue("InputWorkspace2", resWsName.toStdString()); + appendAlg->setPropertyValue("InputWorkspace2", resWsName); appendAlg->setProperty("Number", static_cast<int>(numHist - 1)); appendAlg->setPropertyValue("OutputWorkspace", "__ConvFit_Resolution"); appendAlg->execute(); @@ -652,14 +703,14 @@ namespace { //////////////////////////// /** -* Takes an index and a name, and constructs a single level parameter name -* for use with function ties, etc. -* -* @param index :: the index of the function in the first level. -* @param name :: the name of the parameter inside the function. -* -* @returns the constructed function parameter name. -*/ + * Takes an index and a name, and constructs a single level parameter name + * for use with function ties, etc. + * + * @param index :: the index of the function in the first level. + * @param name :: the name of the parameter inside the function. + * + * @returns the constructed function parameter name. + */ std::string createParName(size_t index, const std::string &name = "") { std::stringstream prefix; prefix << "f" << index << "." << name; @@ -667,57 +718,57 @@ std::string createParName(size_t index, const std::string &name = "") { } /** -* Takes an index, a sub index and a name, and constructs a double level -* (nested) parameter name for use with function ties, etc. -* -* @param index :: the index of the function in the first level. -* @param subIndex :: the index of the function in the second level. -* @param name :: the name of the parameter inside the function. -* -* @returns the constructed function parameter name. -*/ + * Takes an index, a sub index and a name, and constructs a double level + * (nested) parameter name for use with function ties, etc. + * + * @param index :: the index of the function in the first level. + * @param subIndex :: the index of the function in the second level. + * @param name :: the name of the parameter inside the function. + * + * @returns the constructed function parameter name. + */ std::string createParName(size_t index, size_t subIndex, const std::string &name = "") { std::stringstream prefix; prefix << "f" << index << ".f" << subIndex << "." << name; return prefix.str(); } -} +} // namespace /** -* Creates a function to carry out the fitting in the "ConvFit" tab. The -* function consists of various sub functions, with the following structure: -* -* Composite -* | -* +- LinearBackground -* +- Convolution -* | -* +- Resolution -* +- Model (AT LEAST one delta function or one/two lorentzians.) -* | -* +- DeltaFunction(yes/no) -* +- ProductFunction -* | -* +- Lorentzian 1(yes/no) -* +- Temperature Correction(yes/no) -* +- ProductFunction -* | -* +- Lorentzian 2(yes/no) -* +- Temperature Correction(yes/no) -* +- ProductFunction -* | -* +- InelasticDiffSphere(yes/no) -* +- Temperature Correction(yes/no) -* +- ProductFunction -* | -* +- InelasticDiffRotDisCircle(yes/no) -* +- Temperature Correction(yes/no) -* -* @param tieCentres :: whether to tie centres of the two lorentzians. -* -* @returns the composite fitting function. -*/ + * Creates a function to carry out the fitting in the "ConvFit" tab. The + * function consists of various sub functions, with the following structure: + * + * Composite + * | + * +- LinearBackground + * +- Convolution + * | + * +- Resolution + * +- Model (AT LEAST one delta function or one/two lorentzians.) + * | + * +- Delta Function(yes/no) + * +- ProductFunction + * | + * +- Lorentzian 1(yes/no) + * +- Temperature Correction(yes/no) + * +- ProductFunction + * | + * +- Lorentzian 2(yes/no) + * +- Temperature Correction(yes/no) + * +- ProductFunction + * | + * +- InelasticDiffSphere(yes/no) + * +- Temperature Correction(yes/no) + * +- ProductFunction + * | + * +- InelasticDiffRotDisCircle(yes/no) + * +- Temperature Correction(yes/no) + * + * @param tieCentres :: whether to tie centres of the two lorentzians. + * + * @returns the composite fitting function. + */ CompositeFunction_sptr ConvFit::createFunction(bool tieCentres) { auto conv = boost::dynamic_pointer_cast<CompositeFunction>( FunctionFactory::Instance().createFunction("Convolution")); @@ -772,7 +823,7 @@ CompositeFunction_sptr ConvFit::createFunction(bool tieCentres) { func = FunctionFactory::Instance().createFunction("DeltaFunction"); index = model->addFunction(func); std::string parName = createParName(index); - populateFunction(func, model, m_properties["DeltaFunction"], parName, + populateFunction(func, model, m_properties["Delta Function"], parName, false); } @@ -855,8 +906,8 @@ CompositeFunction_sptr ConvFit::createFunction(bool tieCentres) { } /** -* Creates the correction for the temperature -*/ + * Creates the correction for the temperature + */ void ConvFit::createTemperatureCorrection(CompositeFunction_sptr product) { // create temperature correction function to multiply with the lorentzians IFunction_sptr tempFunc; @@ -877,21 +928,18 @@ void ConvFit::createTemperatureCorrection(CompositeFunction_sptr product) { } /** -* Obtains the instrument resolution from the provided workspace -* @param workspaceName The name of the workspaces which holds the instrument -* resolution -* @return The resolution of the instrument. returns 0 if no resolution data -* could be found -*/ -double ConvFit::getInstrumentResolution(std::string workspaceName) { + * Obtains the instrument resolution from the provided workspace + * @param workspaceName The workspaces which holds the instrument + * resolution + * @return The resolution of the instrument. returns 0 if no resolution data + * could be found + */ +double ConvFit::getInstrumentResolution(MatrixWorkspace_sptr workspace) { using namespace Mantid::API; double resolution = 0.0; try { - Mantid::Geometry::Instrument_const_sptr inst = - AnalysisDataService::Instance() - .retrieveWS<MatrixWorkspace>(workspaceName) - ->getInstrument(); + Mantid::Geometry::Instrument_const_sptr inst = workspace->getInstrument(); std::vector<std::string> analysers = inst->getStringParameter("analyser"); if (analysers.empty()) { g_log.warning("Could not load instrument resolution from parameter file"); @@ -913,8 +961,9 @@ double ConvFit::getInstrumentResolution(std::string workspaceName) { IAlgorithm_sptr loadParamFile = AlgorithmManager::Instance().create("LoadParameterFile"); + loadParamFile->setChild(true); loadParamFile->initialize(); - loadParamFile->setProperty("Workspace", workspaceName); + loadParamFile->setProperty("Workspace", workspace); loadParamFile->setProperty( "Filename", idfDirectory + inst->getName() + "_" + analyser + "_" + reflection + "_Parameters.xml"); @@ -926,9 +975,7 @@ double ConvFit::getInstrumentResolution(std::string workspaceName) { return 0.0; } - inst = AnalysisDataService::Instance() - .retrieveWS<MatrixWorkspace>(workspaceName) - ->getInstrument(); + inst = workspace->getInstrument(); } if (inst->getComponentByName(analyser) != NULL) { resolution = inst->getComponentByName(analyser) @@ -947,41 +994,41 @@ double ConvFit::getInstrumentResolution(std::string workspaceName) { } /** -* Initialises the property values for any of the fit type -* @param propName The name of the property group -* @return The populated property group representing a fit type -*/ + * Initialises the property values for any of the fit type + * @param propName The name of the property group + * @return The populated property group representing a fit type + */ QtProperty *ConvFit::createFitType(const QString &propName) { - QtProperty *fitTypeGroup = m_grpManager->addProperty(propName); - QString cbName = propName; - if (propName.compare("Lorentzian 1") == 0) { - cbName = "One Lorentzian"; - } - if (propName.compare("Lorentzian 2") == 0) { - cbName = "Two Lorentzians"; - } + return createFitType(m_grpManager->addProperty(propName)); +} + +QtProperty *ConvFit::createFitType(QtProperty *fitTypeGroup, + const bool &addProperties) { + QString cbName = fitTypeGroup->propertyName(); auto params = getFunctionParameters(cbName); for (auto it = params.begin(); it != params.end(); ++it) { - QString paramName = propName + "." + *it; + QString paramName = cbName + "." + *it; m_properties[paramName] = m_dblManager->addProperty(*it); m_dblManager->setDecimals(m_properties[paramName], NUM_DECIMALS); if (QString(*it).compare("FWHM") == 0) { m_dblManager->setValue(m_properties[paramName], 0.02); } - fitTypeGroup->addSubProperty(m_properties[paramName]); + + if (addProperties) + fitTypeGroup->addSubProperty(m_properties[paramName]); } return fitTypeGroup; } /** -* Populates the properties of a function with given values -* @param func The function currently being added to the composite -* @param comp A composite function of the previously called functions -* @param group The QtProperty representing the fit type -* @param pref The index of the functions eg. (f0.f1) -* @param tie Bool to state if parameters are to be tied together -*/ + * Populates the properties of a function with given values + * @param func The function currently being added to the composite + * @param comp A composite function of the previously called functions + * @param group The QtProperty representing the fit type + * @param pref The index of the functions eg. (f0.f1) + * @param tie Bool to state if parameters are to be tied together + */ void ConvFit::populateFunction(IFunction_sptr func, IFunction_sptr comp, QtProperty *group, const std::string &pref, bool tie) { @@ -1008,14 +1055,14 @@ void ConvFit::populateFunction(IFunction_sptr func, IFunction_sptr comp, } /** -* Generate a string to describe the fit type selected by the user. -* Used when naming the resultant workspaces. -* -* Assertions used to guard against any future changes that don't take -* workspace naming into account. -* -* @returns the generated QString. -*/ + * Generate a string to describe the fit type selected by the user. + * Used when naming the resultant workspaces. + * + * Assertions used to guard against any future changes that don't take + * workspace naming into account. + * + * @returns the generated QString. + */ QString ConvFit::fitTypeString() const { QString fitType(""); @@ -1028,14 +1075,14 @@ QString ConvFit::fitTypeString() const { } /** -* Generate a string to describe the background selected by the user. -* Used when naming the resultant workspaces. -* -* Assertions used to guard against any future changes that don't take -* workspace naming into account. -* -* @returns the generated QString. -*/ + * Generate a string to describe the background selected by the user. + * Used when naming the resultant workspaces. + * + * Assertions used to guard against any future changes that don't take + * workspace naming into account. + * + * @returns the generated QString. + */ QString ConvFit::backgroundString() const { switch (m_uiForm.cbBackground->currentIndex()) { case 0: @@ -1050,11 +1097,11 @@ QString ConvFit::backgroundString() const { } /** -* Generates a string that defines the fitting minimizer based on the user -* options. -* -* @return Minimizer as a string -*/ + * Generates a string that defines the fitting minimizer based on the user + * options. + * + * @return Minimizer as a string + */ QString ConvFit::minimizerString(QString outputName) const { QString minimizer = "Levenberg-Marquardt"; @@ -1114,9 +1161,9 @@ QString ConvFit::minimizerString(QString outputName) const { } /** -* Changes property tree and plot appearance based on Fit Type -* @param index A reference to the Fit Type (0-9) -*/ + * Changes property tree and plot appearance based on Fit Type + * @param index A reference to the Fit Type (0-9) + */ void ConvFit::typeSelection(int index) { auto hwhmRangeSelector = m_uiForm.ppPlot->getRangeSelector("ConvFitHWHM"); @@ -1140,9 +1187,9 @@ void ConvFit::typeSelection(int index) { } /** -* Add/Remove sub property 'BGA1' from background based on Background type -* @param index A reference to the Background type -*/ + * Add/Remove sub property 'BGA1' from background based on Background type + * @param index A reference to the Background type + */ void ConvFit::bgTypeSelection(int index) { if (index == 2) { m_properties["LinearBackground"]->addSubProperty(m_properties["BGA1"]); @@ -1152,43 +1199,32 @@ void ConvFit::bgTypeSelection(int index) { } /** -* Updates the plot in the GUI window -*/ + * Updates the plot in the GUI window + */ void ConvFit::updatePlot() { using Mantid::Kernel::Exception::NotFoundError; - if (!m_cfInputWS) { + auto inputWs = inputWorkspace(); + + if (!inputWs) { g_log.error("No workspace loaded, cannot create preview plot."); return; } bool plotGuess = m_uiForm.ckPlotGuess->isChecked(); - m_uiForm.ckPlotGuess->setChecked(false); + m_uiForm.ckPlotGuess->setChecked(plotGuess); int specNo = m_uiForm.spPlotSpectrum->text().toInt(); m_uiForm.ppPlot->clear(); - m_previewPlotData = m_cfInputWS; - m_uiForm.ppPlot->addSpectrum("Sample", m_cfInputWS, specNo); - - try { - const QPair<double, double> curveRange = - m_uiForm.ppPlot->getCurveRange("Sample"); - const std::pair<double, double> range(curveRange.first, curveRange.second); - m_uiForm.ppPlot->getRangeSelector("ConvFitRange") - ->setRange(range.first, range.second); - m_uiForm.ckPlotGuess->setChecked(plotGuess); - m_dblManager->setValue(m_properties["StartX"], range.first); - m_dblManager->setValue(m_properties["EndX"], range.second); - } catch (std::invalid_argument &exc) { - showMessageBox(exc.what()); - } + setPreviewPlotWorkspace(inputWs); + m_uiForm.ppPlot->addSpectrum("Sample", inputWs, specNo); // Default FWHM to resolution of instrument - double resolution = getInstrumentResolution(m_cfInputWSName.toStdString()); + double resolution = getInstrumentResolution(inputWorkspace()); if (resolution > 0) { - m_dblManager->setValue(m_properties["Lorentzian 1.FWHM"], resolution); - m_dblManager->setValue(m_properties["Lorentzian 2.FWHM"], resolution); + m_dblManager->setValue(m_properties["InstrumentResolution"], resolution); + m_dblManager->setValue(m_properties["InstrumentResolution"], resolution); } // If there is a result workspace plot then plot it @@ -1203,6 +1239,21 @@ void ConvFit::updatePlot() { } } +void ConvFit::updatePlotRange() { + + try { + const QPair<double, double> curveRange = + m_uiForm.ppPlot->getCurveRange("Sample"); + const std::pair<double, double> range(curveRange.first, curveRange.second); + m_uiForm.ppPlot->getRangeSelector("ConvFitRange") + ->setRange(range.first, range.second); + m_dblManager->setValue(m_properties["StartX"], range.first); + m_dblManager->setValue(m_properties["EndX"], range.second); + } catch (std::invalid_argument &exc) { + showMessageBox(exc.what()); + } +} + /* * Plots the specified spectrum of the output group workspace witht the *specified name; @@ -1220,7 +1271,7 @@ void ConvFit::plotOutput(std::string const &outputWsName, int specNo) { MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<MatrixWorkspace>( outputGroup->getItem(specNo - m_runMin)); if (ws) { - m_previewPlotData = ws; + setPreviewPlotWorkspace(ws); m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); m_uiForm.ppPlot->addSpectrum("Diff", ws, 2, Qt::blue); if (m_uiForm.ckPlotGuess->isChecked()) { @@ -1231,90 +1282,67 @@ void ConvFit::plotOutput(std::string const &outputWsName, int specNo) { } } -void ConvFit::updateParameters(int specNo) { - // Check parameter table workspace has been created - if (!m_paramWs) - return; - - size_t row = boost::numeric_cast<size_t>(specNo - m_runMin); - QMap<QString, double> parameters = - IndirectTab::extractRowFromTable(m_paramWs, row); - - QString functionName = m_uiForm.cbFitType->currentText(); - - QStringList params = getFunctionParameters(functionName); - params.reserve(static_cast<int>(parameters.size())); +void ConvFit::updateProperties(int specNo) { + auto parameterNames = m_propertyToParameter.keys(); - // Populate Tree widget with values - // Background should always be f0 - m_dblManager->setValue(m_properties["BGA0"], parameters["f0.A0"]); - m_dblManager->setValue(m_properties["BGA1"], parameters["f0.A1"]); - - const int fitTypeIndex = m_uiForm.cbFitType->currentIndex(); - - int funcIndex = 0; - int subIndex = 0; - - // check if we're using a temperature correction - if (m_uiForm.ckTempCorrection->isChecked() && - !m_uiForm.leTempCorrection->text().isEmpty()) { - subIndex++; + for (auto &fitFunction : + indexToFitFunctions(m_uiForm.cbFitType->currentIndex())) { + updateProperties(specNo, fitFunction); } +} - const bool usingDeltaFunc = m_blnManager->value(m_properties["UseDeltaFunc"]); - - // If using a delta function with any fit type or using two Lorentzians - const bool usingCompositeFunc = - ((usingDeltaFunc && m_fittedIndex > 0) || m_fittedIndex == 2); +void ConvFit::updateProperties(int specNo, const QString &fitFunction) { + bool isTwoLorentzian = fitFunction == "Lorentzian 2"; + bool specOutOfBounds = specNo < m_runMin || m_runMax < specNo; - const QString prefBase = "f1.f1."; + for (auto ¶m : getFunctionParameters(fitFunction)) { + auto propertyName = fitFunction + "." + param; - if (usingDeltaFunc) { - QString key = prefBase; - if (usingCompositeFunc) { - key += "f0."; + if (!specOutOfBounds && m_propertyToParameter.contains(propertyName)) { + auto paramName = m_propertyToParameter[propertyName]; + m_dblManager->setValue(m_properties[propertyName], + m_parameterValues[paramName][specNo]); + } else { + if (isTwoLorentzian) { + m_dblManager->setValue(m_properties[propertyName], + m_defaultParams["default_" + param]); + } else { + m_dblManager->setValue(m_properties[propertyName], + m_defaultParams[param]); + } } - - m_dblManager->setValue(m_properties["DeltaHeight"], - parameters[key + "Height"]); - m_dblManager->setValue(m_properties["DeltaCentre"], - parameters[key + "Centre"]); - funcIndex++; } +} - QString pref = prefBase; +QVector<QString> ConvFit::indexToFitFunctions(const int &fitTypeIndex) { + QVector<QString> fitFunctions = {}; - if (usingCompositeFunc) { - pref += "f" + QString::number(funcIndex) + ".f" + - QString::number(subIndex) + "."; - } else { - pref += "f" + QString::number(subIndex) + "."; + if (m_blnManager->value(m_properties["UseDeltaFunc"])) { + fitFunctions.push_back("Delta Function"); } - if (fitTypeIndex == 2 && m_fittedIndex == 2) { - functionName = "Lorentzian 1"; - IndirectTab::updateProperties(functionName, pref, params, parameters, 0, 3); - - funcIndex++; - pref = prefBase; - pref += "f" + QString::number(funcIndex) + ".f" + - QString::number(subIndex) + "."; - - functionName = "Lorentzian 2"; - IndirectTab::updateProperties(functionName, pref, params, parameters, 3, 0); - } else { - - if (fitTypeIndex == 2 && m_fittedIndex == 1) { - functionName = "Lorentzian 1"; - } - - IndirectTab::updateProperties(functionName, pref, params, parameters, 0, 0); + if (fitTypeIndex == 1) + fitFunctions.push_back("Lorentzian 1"); + else if (fitTypeIndex == 2) { + fitFunctions.push_back("Lorentzian 1"); + fitFunctions.push_back("Lorentzian 2"); + } else if (fitTypeIndex == 3) + fitFunctions.push_back("InelasticDiffSphere"); + else if (fitTypeIndex == 4) + fitFunctions.push_back("InelasticDiffRotDiscreteCircle"); + else if (fitTypeIndex == 5) + fitFunctions.push_back("ElasticDiffSphere"); + else if (fitTypeIndex == 6) + fitFunctions.push_back("ElasticDiffRotDiscreteCircle"); + else if (fitTypeIndex == 7) { + fitFunctions.push_back("StretchedExpFT"); } + return fitFunctions; } /** -* Updates the guess for the plot -*/ + * Updates the guess for the plot + */ void ConvFit::plotGuess() { m_uiForm.ppPlot->removeSpectrum("Guess"); @@ -1330,18 +1358,20 @@ void ConvFit::plotGuess() { bool tieCentres = (m_uiForm.cbFitType->currentIndex() == 2); CompositeFunction_sptr function = createFunction(tieCentres); + auto inputWs = inputWorkspace(); - if (m_cfInputWS == NULL) { + if (!inputWs) { updatePlot(); + return; } const size_t binIndexLow = - m_cfInputWS->binIndexOf(m_dblManager->value(m_properties["StartX"])); + inputWs->binIndexOf(m_dblManager->value(m_properties["StartX"])); const size_t binIndexHigh = - m_cfInputWS->binIndexOf(m_dblManager->value(m_properties["EndX"])); + inputWs->binIndexOf(m_dblManager->value(m_properties["EndX"])); const size_t nData = binIndexHigh - binIndexLow; - const auto &xPoints = m_cfInputWS->points(0); + const auto &xPoints = inputWs->points(0); std::vector<double> dataX(nData); std::copy(&xPoints[binIndexLow], &xPoints[binIndexLow + nData], @@ -1389,6 +1419,7 @@ void ConvFit::singleFit() { m_runMax = specNo; std::string specNoStr = m_uiForm.spPlotSpectrum->text().toStdString(); + m_fitFunctions = indexToFitFunctions(m_uiForm.cbFitType->currentIndex()); auto cfs = sequentialFit(specNoStr, specNoStr, m_singleFitOutputName); // Connection to singleFitComplete SLOT (post algorithm completion) @@ -1399,10 +1430,10 @@ void ConvFit::singleFit() { } /** -* Handle completion of the fit algorithm for single fit. -* -* @param error :: If the fit algorithm failed -*/ + * Handle completion of the fit algorithm for single fit. + * + * @param error :: If the fit algorithm failed + */ void ConvFit::singleFitComplete(bool error) { // Disconnect signal for single fit complete disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, @@ -1410,34 +1441,24 @@ void ConvFit::singleFitComplete(bool error) { algorithmComplete(error, m_singleFitOutputName); } -void ConvFit::plotSpecChanged(int value) { - updatePlot(); - - if (value < m_runMin || value > m_runMax) { - fitFunctionSelected(m_uiForm.cbFitType->currentText()); - } else { - updateParameters(value); - } -} - /** -* Handles the user entering a new minimum spectrum index. -* -* Prevents the user entering an overlapping spectra range. -* -* @param value Minimum spectrum index -*/ + * Handles the user entering a new minimum spectrum index. + * + * Prevents the user entering an overlapping spectra range. + * + * @param value Minimum spectrum index + */ void ConvFit::specMinChanged(int value) { m_uiForm.spSpectraMax->setMinimum(value); } /** -* Handles the user entering a new maximum spectrum index. -* -* Prevents the user entering an overlapping spectra range. -* -* @param value Maximum spectrum index -*/ + * Handles the user entering a new maximum spectrum index. + * + * Prevents the user entering an overlapping spectra range. + * + * @param value Maximum spectrum index + */ void ConvFit::specMaxChanged(int value) { m_uiForm.spSpectraMin->setMaximum(value); } @@ -1481,19 +1502,15 @@ void ConvFit::updateRS(QtProperty *prop, double val) { fitRangeSelector->setMaximum(val); } else if (prop == m_properties["BGA0"]) { backRangeSelector->setMinimum(val); - } else if (prop == m_properties["Lorentzian 1.FWHM"]) { + } else if (prop == m_properties["InstrumentResolution"]) { hwhmUpdateRS(val); - } else if (prop == m_properties["Lorentzian 1.PeakCentre"]) { - hwhmUpdateRS(m_dblManager->value(m_properties["Lorentzian 1.FWHM"])); } } void ConvFit::hwhmUpdateRS(double val) { - const double peakCentre = - m_dblManager->value(m_properties["Lorentzian 1.PeakCentre"]); auto hwhmRangeSelector = m_uiForm.ppPlot->getRangeSelector("ConvFitHWHM"); - hwhmRangeSelector->setMinimum(peakCentre - val / 2); - hwhmRangeSelector->setMaximum(peakCentre + val / 2); + hwhmRangeSelector->setMinimum(-val / 2); + hwhmRangeSelector->setMaximum(+val / 2); } void ConvFit::checkBoxUpdate(QtProperty *prop, bool checked) { @@ -1502,17 +1519,17 @@ void ConvFit::checkBoxUpdate(QtProperty *prop, bool checked) { if (prop == m_properties["UseDeltaFunc"]) { updatePlotOptions(); if (checked) { - m_properties["DeltaFunction"]->addSubProperty( - m_properties["DeltaHeight"]); - m_dblManager->setValue(m_properties["DeltaHeight"], 1.0000); - m_properties["DeltaFunction"]->addSubProperty( - m_properties["DeltaCentre"]); - m_dblManager->setValue(m_properties["DeltaCentre"], 0.0000); + m_properties["Delta Function"]->addSubProperty( + m_properties["Delta Function.Height"]); + m_dblManager->setValue(m_properties["Delta Function.Height"], 1.0000); + m_properties["Delta Function"]->addSubProperty( + m_properties["Delta Function.Centre"]); + m_dblManager->setValue(m_properties["Delta Function.Centre"], 0.0000); } else { - m_properties["DeltaFunction"]->removeSubProperty( - m_properties["DeltaHeight"]); - m_properties["DeltaFunction"]->removeSubProperty( - m_properties["DeltaCentre"]); + m_properties["Delta Function"]->removeSubProperty( + m_properties["Delta Function.Height"]); + m_properties["Delta Function"]->removeSubProperty( + m_properties["Delta Function.Centre"]); } } else if (prop == m_properties["UseFABADA"]) { if (checked) { @@ -1529,9 +1546,9 @@ void ConvFit::checkBoxUpdate(QtProperty *prop, bool checked) { } /** Shows FABADA minimizer options in the property browser -* -* @param advanced :: true if advanced options should be shown, false otherwise -*/ + * + * @param advanced :: true if advanced options should be shown, false otherwise + */ void ConvFit::showFABADA(bool advanced) { m_properties["FABADA"]->addSubProperty(m_properties["OutputFABADAChain"]); @@ -1578,8 +1595,8 @@ void ConvFit::showFABADA(bool advanced) { } /** Hide FABADA minimizer options from the browser -* -*/ + * + */ void ConvFit::hideFABADA() { m_properties["FABADA"]->removeSubProperty(m_properties["OutputFABADAChain"]); @@ -1684,73 +1701,42 @@ void ConvFit::showTieCheckbox(QString fitType) { } /** -* Gets a list of parameters for a given fit function. -* @return List of parameters -*/ -QStringList ConvFit::getFunctionParameters(QString functionName) { - QStringList parameters; - auto currentFitFunction = functionName; - // Add function parameters to QStringList - if (functionName.compare("Zero Lorentzians") != 0) { - if (functionName.compare("One Lorentzian") == 0 || - functionName.compare("Two Lorentzians") == 0) { - currentFitFunction = "Lorentzian"; - } - IFunction_sptr func = FunctionFactory::Instance().createFunction( - currentFitFunction.toStdString()); + * Gets a list of parameters for a given fit function. + * @return List of parameters + */ +QVector<QString> ConvFit::getFunctionParameters(QString functionName) const { + IFunction_sptr func; + bool isLorentzian = boost::starts_with(functionName, "Lorentzian"); - for (size_t i = 0; i < func->nParams(); i++) { - parameters << QString::fromStdString(func->parameterName(i)); - } - } - // Add another Lorentzian function parameter for two Lorentzian fit - if (functionName.compare("Two Lorentzians") == 0) { - currentFitFunction = "Lorentzian"; - IFunction_sptr func = FunctionFactory::Instance().createFunction( - currentFitFunction.toStdString()); - for (size_t i = 0; i < func->nParams(); i++) { - parameters << QString::fromStdString(func->parameterName(i)); - } - } - if (functionName.compare("Zero Lorentzians") == 0) { - parameters.append("Zero"); + if (isLorentzian) { + func = FunctionFactory::Instance().createFunction("Lorentzian"); + } else { + func = FunctionFactory::Instance().createFunction( + functionName.replace(" ", "").toStdString()); } - return parameters; + + return IndirectTab::convertStdStringVector(func->getParameterNames()); } /** -* Handles a new fit function being selected. -* @param functionName Name of new fit function -*/ -void ConvFit::fitFunctionSelected(const QString &functionName) { + * Handles a new fit function being selected. + * @param functionName Name of new fit function + */ +void ConvFit::fitFunctionSelected(int fitTypeIndex) { // If resolution file has been entered update default FWHM to resolution if (m_uiForm.dsResInput->getCurrentDataName().compare("") != 0) { - const auto res = getInstrumentResolution(m_cfInputWS->getName()); + const auto res = getInstrumentResolution(inputWorkspace()); m_defaultParams["FWHM"] = res; m_defaultParams["default_FWHM"] = res; } - // If the previous fit was One Lorentzian and the new fit is Two Lorentzian - // preserve the values of One Lorentzian Fit - const QString currentFitFunction = m_uiForm.cbFitType->currentText(); - if (currentFitFunction.compare("Two Lorentzians") == 0) { - m_uiForm.ckTieCentres->setChecked(true); - - if (m_previousFit.compare("One Lorentzian") == 0) { - const double amplitude = - m_dblManager->value(m_properties["One Lorentzian.Amplitude"]); - const double peakCentre = - m_dblManager->value(m_properties["One Lorentzian.PeakCentre"]); - const double fwhm = - m_dblManager->value(m_properties["One Lorentzian.FWHM"]); - m_defaultParams.insert("PeakCentre", peakCentre); - m_defaultParams.insert("FWHM", fwhm); - m_defaultParams.insert("Amplitude", amplitude); - } - } else { - m_uiForm.ckTieCentres->setChecked(false); + auto fitFunctions = indexToFitFunctions(fitTypeIndex); + if (fitFunctions.isEmpty()) { + return; } + auto lastFunction = fitFunctions.last(); + // Remove previous parameters from tree m_cfTree->removeProperty(m_properties["FitFunction1"]); m_cfTree->removeProperty(m_properties["FitFunction2"]); @@ -1760,96 +1746,86 @@ void ConvFit::fitFunctionSelected(const QString &functionName) { updatePlotOptions(); // Two Lorentzians Fit - if (currentFitFunction.compare("Two Lorentzians") == 0) { + if (lastFunction == "Lorentzian 2") { m_properties["FitFunction1"] = m_grpManager->addProperty("Lorentzian 1"); m_cfTree->addProperty(m_properties["FitFunction1"]); m_properties["FitFunction2"] = m_grpManager->addProperty("Lorentzian 2"); m_cfTree->addProperty(m_properties["FitFunction2"]); } else { - m_properties["FitFunction1"] = m_grpManager->addProperty(functionName); + m_properties["FitFunction1"] = m_grpManager->addProperty(lastFunction); m_cfTree->addProperty(m_properties["FitFunction1"]); } // If there are parameters in the list, add them - const QStringList parameters = getFunctionParameters(functionName); - if (parameters.isEmpty() != true) { - addParametersToTree(parameters, currentFitFunction); - } - m_previousFit = m_uiForm.cbFitType->currentText(); + addDefaultParametersToTree(fitFunctions); } /** -* Adds all the parameters that are required for the currentFitFunction to the -* parameter tree -* @param parameters :: A QStringList of all the parameters -* for -* the current fit function -* @param currentFitFunction :: The name of the current fit function -*/ -void ConvFit::addParametersToTree(const QStringList ¶meters, - const QString ¤tFitFunction) { - const QMap<QString, double> fullPropertyMap = - constructFullPropertyMap(m_defaultParams, parameters, currentFitFunction); - const QStringList keys = fullPropertyMap.keys(); - for (auto i = keys.begin(); i != keys.end(); ++i) { - const auto fullPropertyName = QString(*i); - const auto paramName = fullPropertyName.right( - fullPropertyName.size() - fullPropertyName.lastIndexOf(".") - 1); - const auto propName = - fullPropertyName.left(fullPropertyName.lastIndexOf(".")); - m_properties[fullPropertyName] = m_dblManager->addProperty(paramName); - m_dblManager->setValue(m_properties[fullPropertyName], - fullPropertyMap[fullPropertyName]); - m_dblManager->setDecimals(m_properties[fullPropertyName], NUM_DECIMALS); - if (propName.compare("Lorentzian 2") == 0) { - m_properties["FitFunction2"]->addSubProperty( - m_properties[fullPropertyName]); - } else { - m_properties["FitFunction1"]->addSubProperty( - m_properties[fullPropertyName]); - } + * Adds all the parameters that are required for the fit function to the + * parameter tree + * @param fitFunction :: The name of the fit function + */ +void ConvFit::addDefaultParametersToTree(const QVector<QString> &fitFunctions) { + + for (auto &fitFunction : fitFunctions) { + addDefaultParametersToTree(fitFunction); } } -/** -* Populates the plot combobox -*/ -void ConvFit::updatePlotOptions() { - m_uiForm.cbPlotType->clear(); - const bool deltaFunction = m_blnManager->value(m_properties["UseDeltaFunc"]); - const int fitFunctionType = m_uiForm.cbFitType->currentIndex(); - QStringList plotOptions; +void ConvFit::addDefaultParametersToTree(const QString &fitFunction) { + auto paramNames = getFunctionParameters(fitFunction); + bool isDelta = fitFunction == "Delta Function"; + bool isTwoLorentzian = !isDelta && fitFunction == "Lorentzian 2"; - if (deltaFunction && fitFunctionType < 3) { - plotOptions << "Height"; - } + for (auto ¶mName : paramNames) { + QString propertyName = fitFunction + "." + paramName; + m_properties[propertyName] = m_dblManager->addProperty(paramName); - if (fitFunctionType != 0) { - QStringList params; + if (isTwoLorentzian) { + paramName = "default_" + paramName; + } - if (fitFunctionType != 2) { - params = getFunctionParameters(m_uiForm.cbFitType->currentText()); + if (m_defaultParams.contains(paramName)) { + m_dblManager->setValue(m_properties[propertyName], + m_defaultParams[paramName]); } else { - params = getFunctionParameters(QString("One Lorentzian")); + m_dblManager->setValue(m_properties[propertyName], 0); } - if (fitFunctionType < 3) { - params.removeAll("PeakCentre"); + m_dblManager->setDecimals(m_properties[propertyName], NUM_DECIMALS); + + if (isTwoLorentzian) { + m_properties["FitFunction2"]->addSubProperty(m_properties[propertyName]); + } else if (!isDelta) { + m_properties["FitFunction1"]->addSubProperty(m_properties[propertyName]); } + } +} - plotOptions.append(params); +/** + * Populates the plot combobox + */ +void ConvFit::updatePlotOptions() { + m_uiForm.cbPlotType->clear(); + + const int fitType = m_uiForm.cbFitType->currentIndex(); + const auto fitFunctions = indexToFitFunctions(fitType); + QStringList plotOptions; + + for (auto &fitFunction : fitFunctions) { + plotOptions.append(getFunctionParameters(fitFunction).toList()); } - if (fitFunctionType != 0 || deltaFunction) { + if (fitType != 0 || m_blnManager->value(m_properties["UseDeltaFunc"])) { plotOptions << "All"; } m_uiForm.cbPlotType->addItems(plotOptions); } /** -* Populates the default parameter map with the initial default values -* @param map :: The default value QMap to populate -* @return The QMap populated with default values -*/ + * Populates the default parameter map with the initial default values + * @param map :: The default value QMap to populate + * @return The QMap populated with default values + */ QMap<QString, double> ConvFit::createDefaultParamsMap(QMap<QString, double> map) { // If the parameters from a One Lorentzian fit are present @@ -1872,64 +1848,6 @@ ConvFit::createDefaultParamsMap(QMap<QString, double> map) { return map; } -/** -* Populates a map with ALL parameters names and values for the current fit -* function -* @param defaultMap :: A QMap of any parameters that have non zero default -* values -* @param parameters :: A QStringList of all the parameters for the current -* fit function -* @param fitFunction :: The name of the current fit function -* @return a QMap populated with name, value pairs for parameters where name = -* fitFunction.parametername and value is either from the default map or 0 -*/ -QMap<QString, double> -ConvFit::constructFullPropertyMap(const QMap<QString, double> &defaultMap, - const QStringList ¶meters, - const QString &fitFunction) { - QMap<QString, double> fullMap; - QString fitFuncName = fitFunction; - - // Special case for Two Lorentzian - as it is comprised of 2 single - // Lorentzians - if (fitFunction.compare("Two Lorentzians") == 0) { - fitFuncName = "Lorentzian 1"; - for (auto param = parameters.begin(); param != parameters.end(); ++param) { - const QString qStrParam = QString(*param); - QString fullPropName = fitFuncName + "." + qStrParam; - if (fullMap.contains(fullPropName)) { - // If current property is already in the Map then it's a 2L property - fullPropName = "Lorentzian 2." + qStrParam; - double value = 0; - // Check for default parameter (used for 2L case) - const auto defaultParam = "default_" + qStrParam; - if (defaultMap.contains(defaultParam)) { - value = defaultMap[defaultParam]; - } - fullMap.insert(fullPropName, value); - } else { - if (defaultMap.contains(qStrParam)) { - fullMap.insert(fullPropName, defaultMap[qStrParam]); - } else { - // If property not in Map, assumed to default to value of 0 - fullMap.insert(fullPropName, 0); - } - } - } - } else { // All Other fit functions - for (auto param = parameters.begin(); param != parameters.end(); ++param) { - const QString fullPropName = fitFuncName + "." + QString(*param); - if (defaultMap.contains(QString(*param))) { - fullMap.insert(fullPropName, defaultMap[*param]); - } else { - // If property not in Map, assumed to default to value of 0 - fullMap.insert(fullPropName, 0); - } - } - } - return fullMap; -} - } // namespace IDA } // namespace CustomInterfaces } // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/ConvFit.h b/qt/scientific_interfaces/Indirect/ConvFit.h index 0b9d685d3aa46214b78d86f1d9e38247d0782ee1..9b2e3c4fffda7f2f569452bc4792686d04c034ab 100644 --- a/qt/scientific_interfaces/Indirect/ConvFit.h +++ b/qt/scientific_interfaces/Indirect/ConvFit.h @@ -27,9 +27,9 @@ private slots: void newDataLoaded(const QString wsName); void extendResolutionWorkspace(); void updatePlot(); + void updatePlotRange(); void plotGuess(); void singleFit(); - void plotSpecChanged(int value); void specMinChanged(int value); void specMaxChanged(int value); void minChanged(double); @@ -45,16 +45,19 @@ private slots: void showTieCheckbox(QString); void sequentialFitComplete(bool error); void singleFitComplete(bool error); - void fitFunctionSelected(const QString &); + void fitFunctionSelected(int fitTypeIndex); void saveClicked(); void plotClicked(); - void plotCurrentPreview(); + void updateProperties(int specNo); + void addDefaultParametersToTree(const QString &fitFunction); private: boost::shared_ptr<Mantid::API::CompositeFunction> createFunction(bool tieCentres = false); - double getInstrumentResolution(std::string workspaceName); + double + getInstrumentResolution(Mantid::API::MatrixWorkspace_sptr workspaceName); QtProperty *createFitType(const QString &); + QtProperty *createFitType(QtProperty *, const bool & = true); void createTemperatureCorrection(Mantid::API::CompositeFunction_sptr product); void populateFunction(Mantid::API::IFunction_sptr func, @@ -63,12 +66,12 @@ private: QString fitTypeString() const; QString backgroundString() const; QString minimizerString(QString outputName) const; - QStringList getFunctionParameters(QString); - void updateParameters(int specNo); + QVector<QString> getFunctionParameters(QString) const; + QVector<QString> indexToFitFunctions(const int &fitTypeIndex); + void updateProperties(int specNo, const QString &fitFunction); void updatePlotOptions(); void plotOutput(std::string const &outputWs, int specNo); - void addParametersToTree(const QStringList ¶meters, - const QString ¤tFitFunction); + void addDefaultParametersToTree(const QVector<QString> ¤tFitFunction); void addSampleLogsToWorkspace(const std::string &workspaceName, const std::string &logName, const std::string &logText, @@ -80,20 +83,25 @@ private: const std::string &specMax, QString &outputWSName); void algorithmComplete(bool error, const QString &outputWSName); + QHash<QString, QString> + createPropertyToParameterMap(const QVector<QString> &functionNames, + const QString &prefixPrefix, + const QString &prefixSuffix); + void extendPropertyToParameterMap( + const QString &functionName, const int &funcIndex, + const QString &prefixPrefix, const QString &prefixSuffix, + QHash<QString, QString> &propertyToParameter); + void + extendPropertyToParameterMap(const QString &functionName, + const QString &prefix, + QHash<QString, QString> &propertyToParameter); Ui::ConvFit m_uiForm; QtStringPropertyManager *m_stringManager; QtTreePropertyBrowser *m_cfTree; QMap<QtProperty *, QtProperty *> m_fixedProps; - // Pointer to sample workspace object - Mantid::API::MatrixWorkspace_sptr m_cfInputWS; - Mantid::API::MatrixWorkspace_sptr m_previewPlotData; - Mantid::API::ITableWorkspace_sptr m_paramWs; - QString m_cfInputWSName; - int m_fittedIndex; bool m_confitResFileType; QString m_singleFitOutputName; - QString m_previousFit; QString m_baseName; int m_runMin; int m_runMax; @@ -104,10 +112,10 @@ private: // Used in auto generating defaults for parameters QMap<QString, double> m_defaultParams; QMap<QString, double> createDefaultParamsMap(QMap<QString, double> map); - QMap<QString, double> - constructFullPropertyMap(const QMap<QString, double> &defaultMap, - const QStringList ¶meters, - const QString &fitFunction); + + QVector<QString> m_fitFunctions; + QHash<QString, QHash<size_t, double>> m_parameterValues; + QHash<QString, QString> m_propertyToParameter; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/Elwin.cpp b/qt/scientific_interfaces/Indirect/Elwin.cpp index 3656ae685c8bc93ef36ba84746a85fde5f6f9894..6dbcbcf1a8847014182186d1f3ead5f3e9583cf1 100644 --- a/qt/scientific_interfaces/Indirect/Elwin.cpp +++ b/qt/scientific_interfaces/Indirect/Elwin.cpp @@ -19,7 +19,7 @@ namespace MantidQt { namespace CustomInterfaces { namespace IDA { Elwin::Elwin(QWidget *parent) - : IndirectDataAnalysisTab(parent), m_elwTree(nullptr), m_ElInputWS() { + : IndirectDataAnalysisTab(parent), m_elwTree(nullptr) { m_uiForm.setupUi(parent); } @@ -98,6 +98,8 @@ void Elwin::setup() { SLOT(newPreviewFileSelected(int))); connect(m_uiForm.spPreviewSpec, SIGNAL(valueChanged(int)), this, SLOT(plotInput())); + connect(m_uiForm.spPreviewSpec, SIGNAL(valueChanged(int)), this, + SLOT(IndirectDataAnalysisTab::setSelectedSpectrum(int))); // Handle plot and save connect(m_uiForm.pbSave, SIGNAL(clicked()), this, SLOT(saveClicked())); connect(m_uiForm.pbPlot, SIGNAL(clicked()), this, SLOT(plotClicked())); @@ -347,8 +349,9 @@ void Elwin::newInputFiles() { // Default to the first file m_uiForm.cbPreviewFile->setCurrentIndex(0); QString wsname = m_uiForm.cbPreviewFile->currentText(); - m_ElInputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + auto inputWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( wsname.toStdString()); + setInputWorkspace(inputWs); } /** @@ -524,19 +527,6 @@ void Elwin::saveClicked() { m_batchAlgoRunner->executeBatchAsync(); } -/** -* Plots the current spectrum displayed in the preview plot -*/ -void Elwin::plotCurrentPreview() { - - // Check whether a workspace has been selected - if (m_ElInputWS) { - int specNo = m_uiForm.spPreviewSpec->value(); - IndirectTab::plotSpectrum(QString::fromStdString(m_ElInputWS->getName()), - specNo, specNo); - } -} - } // namespace IDA } // namespace CustomInterfaces } // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/Elwin.h b/qt/scientific_interfaces/Indirect/Elwin.h index 2ad171f2c1651d21b1aca12108746c31c566254e..ba20d5c2182b20954c36c427e5cd02131d2de79b 100644 --- a/qt/scientific_interfaces/Indirect/Elwin.h +++ b/qt/scientific_interfaces/Indirect/Elwin.h @@ -34,12 +34,10 @@ private slots: void unGroupInput(bool error); void saveClicked(); void plotClicked(); - void plotCurrentPreview(); private: Ui::Elwin m_uiForm; QtTreePropertyBrowser *m_elwTree; - Mantid::API::MatrixWorkspace_sptr m_ElInputWS; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/IndirectCorrections.ui b/qt/scientific_interfaces/Indirect/IndirectCorrections.ui index 69e263c35d3cdc36ae746cdc5e68177f83200ced..63ce365efa77fd95356352a28555a59e094de01d 100644 --- a/qt/scientific_interfaces/Indirect/IndirectCorrections.ui +++ b/qt/scientific_interfaces/Indirect/IndirectCorrections.ui @@ -24,13 +24,13 @@ <enum>QTabWidget::Rounded</enum> </property> <property name="currentIndex"> - <number>0</number> + <number>3</number> </property> - <widget class="QWidget" name="tabContainerSubtraction"> - <attribute name="title"> - <string>Container Subtraction</string> - </attribute> - </widget> + <widget class="QWidget" name="tabContainerSubtraction"> + <attribute name="title"> + <string>Container Subtraction</string> + </attribute> + </widget> <widget class="QWidget" name="tabCalculatePaalmanPings"> <attribute name="title"> <string>Calculate Paalman Pings</string> @@ -43,7 +43,7 @@ </widget> <widget class="QWidget" name="tabAbsorptionCorrections"> <attribute name="title"> - <string>Absorption</string> + <string>Calculate Monte Carlo Absorption</string> </attribute> </widget> </widget> diff --git a/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.cpp b/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.cpp index 20e6bcfd57a7e1b8b594d54163ddd60de4195d4f..a4f1534c4c78b9445b314161d4612c2dacad2c9a 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.cpp +++ b/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.cpp @@ -3,12 +3,12 @@ //---------------------- #include "IndirectDataAnalysis.h" +#include "ConvFit.h" #include "Elwin.h" -#include "MSDFit.h" #include "Iqt.h" #include "IqtFit.h" #include "JumpFit.h" -#include "ConvFit.h" +#include "MSDFit.h" #include "MantidQtWidgets/Common/HelpWindow.h" #include "MantidQtWidgets/Common/ManageUserDirectories.h" diff --git a/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.h b/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.h index ee11d4691700095e2c2f37f846cb02a965f896f8..cc9f3af5833ddce712869c41ace1b028138ad183 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.h +++ b/qt/scientific_interfaces/Indirect/IndirectDataAnalysis.h @@ -4,12 +4,12 @@ //---------------------- // Includes //---------------------- -#include "ui_IndirectDataAnalysis.h" -#include "MantidQtWidgets/Common/UserSubWindow.h" #include "IndirectTab.h" +#include "MantidQtWidgets/Common/UserSubWindow.h" +#include "ui_IndirectDataAnalysis.h" -#include <Poco/NObserver.h> #include "MantidKernel/ConfigService.h" +#include <Poco/NObserver.h> class DoubleEditorFactory; class QtCheckBoxFactory; diff --git a/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.cpp b/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.cpp index 59d4af17811974006ec8dd50f88760b64bd381c3..6555aea0120c9649f4f475430449cbb72c21e59c 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.cpp +++ b/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.cpp @@ -1,12 +1,13 @@ #include "IndirectDataAnalysisTab.h" -#include "MantidAPI/MatrixWorkspace.h" + #include "MantidAPI/AnalysisDataService.h" +#include "MantidAPI/MatrixWorkspace.h" #include "boost/shared_ptr.hpp" -#include <qwt_plot.h> -#include <qwt_plot_curve.h> #include <QSettings> #include <QString> +#include <qwt_plot.h> +#include <qwt_plot_curve.h> using namespace Mantid::API; @@ -20,7 +21,8 @@ namespace IDA { */ IndirectDataAnalysisTab::IndirectDataAnalysisTab(QWidget *parent) : IndirectTab(parent), m_dblEdFac(nullptr), m_blnEdFac(nullptr), - m_parent(nullptr) { + m_parent(nullptr), m_inputWorkspace(), m_previewPlotWorkspace(), + m_selectedSpectrum(0) { m_parent = dynamic_cast<IndirectDataAnalysis *>(parent); // Create Editor Factories @@ -44,6 +46,89 @@ void IndirectDataAnalysisTab::loadTabSettings(const QSettings &settings) { */ void IndirectDataAnalysisTab::inputChanged() { validate(); } +/** + * Retrieves the input workspace to be used in data analysis. + * + * @return The input workspace to be used in data analysis. + */ +MatrixWorkspace_sptr IndirectDataAnalysisTab::inputWorkspace() { + return m_inputWorkspace.lock(); +} + +/** + * Sets the input workspace to be used in data analysis. + * + * @param inputWorkspace The workspace to set. + */ +void IndirectDataAnalysisTab::setInputWorkspace( + MatrixWorkspace_sptr inputWorkspace) { + m_inputWorkspace = inputWorkspace; +} + +/** + * Retrieves the workspace containing the data to be displayed in + * the preview plot. + * + * @return The workspace containing the data to be displayed in + * the preview plot. + */ +MatrixWorkspace_sptr IndirectDataAnalysisTab::previewPlotWorkspace() { + return m_previewPlotWorkspace.lock(); +} + +/** + * Sets the workspace containing the data to be displayed in the + * preview plot. + * + * @param previewPlotWorkspace The workspace to set. + */ +void IndirectDataAnalysisTab::setPreviewPlotWorkspace( + MatrixWorkspace_sptr previewPlotWorkspace) { + m_previewPlotWorkspace = previewPlotWorkspace; +} + +/** + * Retrieves the selected spectrum. + * + * @return The selected spectrum. + */ +int IndirectDataAnalysisTab::selectedSpectrum() { return m_selectedSpectrum; } + +/** + * Sets the selected spectrum. + * + * @param spectrum The spectrum to set. + */ +void IndirectDataAnalysisTab::setSelectedSpectrum(int spectrum) { + m_selectedSpectrum = spectrum; +} + +/** + * Plots the current preview workspace, if none is set, plots + * the selected spectrum of the current input workspace. + */ +void IndirectDataAnalysisTab::plotCurrentPreview() { + auto previewWs = previewPlotWorkspace(); + auto inputWs = inputWorkspace(); + + // Check a workspace has been selected + if (previewWs) { + + if (inputWs && previewWs->getName() == inputWs->getName()) { + IndirectTab::plotSpectrum(QString::fromStdString(previewWs->getName()), + m_selectedSpectrum); + } else { + IndirectTab::plotSpectrum(QString::fromStdString(previewWs->getName()), 0, + 2); + } + } else if (inputWs && + inputWs->getNumberHistograms() < + boost::numeric_cast<size_t>(m_selectedSpectrum)) { + IndirectTab::plotSpectrum(QString::fromStdString(inputWs->getName()), + m_selectedSpectrum); + } +} + } // namespace IDA } // namespace CustomInterfaces } // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.h b/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.h index c235b1cf0402d5feedf91770eeb11352c8292607..5065c6f140fd21881abab33d7cf00b217f0f8dfc 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.h +++ b/qt/scientific_interfaces/Indirect/IndirectDataAnalysisTab.h @@ -1,10 +1,12 @@ #ifndef MANTIDQTCUSTOMINTERFACESIDA_IDATAB_H_ #define MANTIDQTCUSTOMINTERFACESIDA_IDATAB_H_ -#include "MantidAPI/AlgorithmManager.h" -#include "MantidAPI/MatrixWorkspace_fwd.h" #include "IndirectDataAnalysis.h" #include "IndirectTab.h" +#include "MantidAPI/AlgorithmManager.h" +#include "MantidAPI/MatrixWorkspace_fwd.h" + +#include <boost/weak_ptr.hpp> class QwtPlotCurve; class QwtPlot; @@ -15,7 +17,7 @@ namespace MantidQt { namespace MantidWidgets { class RangeSelector; } -} +} // namespace MantidQt // Suppress a warning coming out of code that isn't ours #if defined(__INTEL_COMPILER) @@ -26,10 +28,10 @@ class RangeSelector; #endif #pragma GCC diagnostic ignored "-Woverloaded-virtual" #endif -#include "MantidQtWidgets/Common/QtPropertyBrowser/qttreepropertybrowser.h" -#include "MantidQtWidgets/Common/QtPropertyBrowser/qtpropertymanager.h" -#include "MantidQtWidgets/Common/QtPropertyBrowser/qteditorfactory.h" #include "MantidQtWidgets/Common/QtPropertyBrowser/DoubleEditorFactory.h" +#include "MantidQtWidgets/Common/QtPropertyBrowser/qteditorfactory.h" +#include "MantidQtWidgets/Common/QtPropertyBrowser/qtpropertymanager.h" +#include "MantidQtWidgets/Common/QtPropertyBrowser/qttreepropertybrowser.h" #if defined(__INTEL_COMPILER) #pragma warning enable 1125 #elif defined(__GNUC__) @@ -55,6 +57,25 @@ protected: /// Function to run a string as python code void runPythonScript(const QString &pyInput); + /// Retrieve input workspace + Mantid::API::MatrixWorkspace_sptr inputWorkspace(); + + /// Set input workspace + void setInputWorkspace(Mantid::API::MatrixWorkspace_sptr inputWorkspace); + + /// Retrieve preview plot workspace + Mantid::API::MatrixWorkspace_sptr previewPlotWorkspace(); + + /// Set preview plot workspace + void setPreviewPlotWorkspace( + Mantid::API::MatrixWorkspace_sptr previewPlotWorkspace); + + /// Retrieve the selected spectrum + int selectedSpectrum(); + + /// Sets the selected spectrum + void setSelectedSpectrum(int spectrum); + /// DoubleEditorFactory DoubleEditorFactory *m_dblEdFac; /// QtCheckBoxFactory @@ -64,6 +85,9 @@ protected slots: /// Slot that can be called when a user eidts an input. void inputChanged(); + /// Plots the current preview data + void plotCurrentPreview(); + private: /// Overidden by child class. void setup() override = 0; @@ -77,6 +101,9 @@ private: /// A pointer to the parent (friend) IndirectDataAnalysis object. IndirectDataAnalysis *m_parent; + boost::weak_ptr<Mantid::API::MatrixWorkspace> m_inputWorkspace; + boost::weak_ptr<Mantid::API::MatrixWorkspace> m_previewPlotWorkspace; + int m_selectedSpectrum; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.cpp b/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.cpp index 28539ea1f7ce67032a5133387d7012c7c881c595..82b7ca19a95f4fa44ec33a9efb86c07c1f437a29 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.cpp +++ b/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.cpp @@ -24,7 +24,7 @@ Mantid::Kernel::Logger g_log("IndirectDiffractionReduction"); std::string toStdString(const QString &qString) { return qString.toStdString(); } -} // anon namespace +} // namespace DECLARE_SUBWINDOW(IndirectDiffractionReduction) @@ -229,73 +229,38 @@ void IndirectDiffractionReduction::plotResults() { * Handles saving the reductions from the generic algorithm. */ void IndirectDiffractionReduction::saveReductions() { - for (const auto wsName : m_plotWorkspaces) { + for (const auto &wsName : m_plotWorkspaces) { const auto workspaceExists = AnalysisDataService::Instance().doesExist(wsName); if (workspaceExists) { - - QString tofWsName = QString::fromStdString(wsName) + "_tof"; - std::string instName = - (m_uiForm.iicInstrumentConfiguration->getInstrumentName()) - .toStdString(); - std::string mode = - (m_uiForm.iicInstrumentConfiguration->getReflectionName()) - .toStdString(); - BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromConvUnitsProps; - inputFromConvUnitsProps["InputWorkspace"] = tofWsName.toStdString(); - BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromReductionProps; - inputFromReductionProps["InputWorkspace"] = (wsName + "_dRange"); + auto workspace = + AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName); if (m_uiForm.ckGSS->isChecked()) { - if (instName == "OSIRIS" && mode == "diffonly") { - - QString gssFilename = tofWsName + ".gss"; - IAlgorithm_sptr saveGSS = - AlgorithmManager::Instance().create("SaveGSS"); - saveGSS->initialize(); - saveGSS->setProperty("Filename", gssFilename.toStdString()); - m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps); - } else { - - // Convert to TOF for GSS - IAlgorithm_sptr convertUnits = - AlgorithmManager::Instance().create("ConvertUnits"); - convertUnits->initialize(); - convertUnits->setProperty("InputWorkspace", wsName); - convertUnits->setProperty("OutputWorkspace", tofWsName.toStdString()); - convertUnits->setProperty("Target", "TOF"); - m_batchAlgoRunner->addAlgorithm(convertUnits); - - // Save GSS - std::string gssFilename = wsName + ".gss"; - IAlgorithm_sptr saveGSS = - AlgorithmManager::Instance().create("SaveGSS"); - saveGSS->initialize(); - saveGSS->setProperty("Filename", gssFilename); - m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps); + std::string tofWsName = wsName; + + if (workspace->YUnit() != "TOF") { + tofWsName = wsName + "_tof"; + m_batchAlgoRunner->addAlgorithm( + convertUnitsAlgorithm(wsName, tofWsName, "TOF")); } + + BatchAlgorithmRunner::AlgorithmRuntimeProps runtimeInput; + runtimeInput["InputWorkspace"] = tofWsName; + m_batchAlgoRunner->addAlgorithm(saveGSSAlgorithm(wsName + ".gss"), + runtimeInput); } if (m_uiForm.ckNexus->isChecked()) { // Save NEXus using SaveNexusProcessed - std::string nexusFilename = wsName + ".nxs"; - IAlgorithm_sptr saveNexus = - AlgorithmManager::Instance().create("SaveNexusProcessed"); - saveNexus->initialize(); - saveNexus->setProperty("InputWorkspace", wsName); - saveNexus->setProperty("Filename", nexusFilename); - m_batchAlgoRunner->addAlgorithm(saveNexus); + m_batchAlgoRunner->addAlgorithm( + saveNexusProcessedAlgorithm(wsName + ".nxs", wsName)); } if (m_uiForm.ckAscii->isChecked()) { // Save ASCII using SaveAscii version 1 - std::string asciiFilename = wsName + ".dat"; - IAlgorithm_sptr saveASCII = - AlgorithmManager::Instance().create("SaveAscii", 1); - saveASCII->initialize(); - saveASCII->setProperty("InputWorkspace", wsName); - saveASCII->setProperty("Filename", asciiFilename); - m_batchAlgoRunner->addAlgorithm(saveASCII); + m_batchAlgoRunner->addAlgorithm( + saveASCIIAlgorithm(wsName + ".dat", wsName)); } } else showInformationBox(QString::fromStdString( @@ -304,6 +269,100 @@ void IndirectDiffractionReduction::saveReductions() { m_batchAlgoRunner->executeBatchAsync(); } +/** + * Creates an algorithm for saving the workspace with the specified name + * in GSS format into the file with the specified name. + * + * @param filename The name of the file to save to. + * @param inputWsName The name of the workspace to save. + * @return A SaveGSS Algorithm which saves in file with the + * specified name. + */ +IAlgorithm_sptr +IndirectDiffractionReduction::saveGSSAlgorithm(const std::string &filename) { + auto alg = saveAlgorithm("SaveGSS", filename); + alg->setProperty("Append", false); + return alg; +} + +/** + * Creates an algorithm for saving the workspace with the specified name + * in ASCII format into the file with the specified name. + * + * @param filename The name of the file to save to. + * @param inputWsName The name of the workspace to save. + * @return A SaveASCII Algorithm which saves in file with the + * specified name. + */ +IAlgorithm_sptr IndirectDiffractionReduction::saveASCIIAlgorithm( + const std::string &filename, const std::string &inputWsName) { + return saveAlgorithm("SaveAscii", filename, inputWsName, 1); +} + +/** + * Creates an algorithm for saving the workspace with the specified name + * in NexusProcessed format into the file with the specified name. + * + * @param filename The name of the file to save to. + * @param inputWsName The name of the workspace to save. + * @return A NexusProcessed Algorithm which saves in file with + * the specified name. + */ +IAlgorithm_sptr IndirectDiffractionReduction::saveNexusProcessedAlgorithm( + const std::string &filename, const std::string &inputWsName) { + return saveAlgorithm("SaveNexusProcessed", filename, inputWsName); +} + +/** + * Creates a save algorithm with the specified name for saving the + * workspace with the specified name into the file with the specified name. + * + * @param saveAlgName The name of the save algorithm to use. + * @param filename The name of the file to save to. + * @param inputWsName The name of the workspace to save. + * @param version The version of the save algorithm to use. + * @return A Save algorithm for saving the workspace with + * the specified name into the file with the the + * specified name. + */ +IAlgorithm_sptr IndirectDiffractionReduction::saveAlgorithm( + const std::string &saveAlgName, const std::string &filename, + const std::string &inputWsName, const int &version) { + IAlgorithm_sptr saveAlg = + AlgorithmManager::Instance().create(saveAlgName, version); + saveAlg->initialize(); + + if (inputWsName != "") { + saveAlg->setProperty("InputWorkspace", inputWsName); + } + saveAlg->setProperty("Filename", filename); + return saveAlg; +} + +/** + * Creates and algorithm for converting the units of the input workspace + * with the specified name, to the specified target, storing the result + * in an output workspace, with the specified name. + * + * @param inputWsName The name of the input workspace, on which to + * perform the unit conversion. + * @param outputWsName The name of the output workspace, in which to + * store the result of unit conversion. + * @param target The target units of the conversion algorithm. + * @return A unit conversion algorithm. + */ +IAlgorithm_sptr IndirectDiffractionReduction::convertUnitsAlgorithm( + const std::string &inputWsName, const std::string &outputWsName, + const std::string &target) { + IAlgorithm_sptr convertUnits = + AlgorithmManager::Instance().create("ConvertUnits"); + convertUnits->initialize(); + convertUnits->setProperty("InputWorkspace", inputWsName); + convertUnits->setProperty("OutputWorkspace", outputWsName); + convertUnits->setProperty("Target", target); + return convertUnits; +} + /** * Runs a diffraction reduction for any instrument in any mode. * @@ -343,15 +402,6 @@ void IndirectDiffractionReduction::runGenericReduction(QString instName, AlgorithmManager::Instance().create("ISISIndirectDiffractionReduction"); msgDiffReduction->initialize(); - // Get save formats - std::vector<std::string> saveFormats; - if (m_uiForm.ckGSS->isChecked()) - saveFormats.emplace_back("gss"); - if (m_uiForm.ckNexus->isChecked()) - saveFormats.emplace_back("nxs"); - if (m_uiForm.ckAscii->isChecked()) - saveFormats.emplace_back("ascii"); - // Set algorithm properties msgDiffReduction->setProperty("Instrument", instName.toStdString()); msgDiffReduction->setProperty("Mode", mode.toStdString()); @@ -764,10 +814,10 @@ bool IndirectDiffractionReduction::validateVanCal() { } /** -* Checks to see if the cal file and optional rebin fields are valid. -* -* @returns True if calibration file and rebin values are valid, false otherwise -*/ + * Checks to see if the cal file and optional rebin fields are valid. + * + * @returns True if calibration file and rebin values are valid, false otherwise + */ bool IndirectDiffractionReduction::validateCalOnly() { // Check Calib file valid if (m_uiForm.ckUseCalib->isChecked() && !m_uiForm.rfCalFile_only->isValid()) @@ -864,5 +914,5 @@ void IndirectDiffractionReduction::manualGroupingToggled(int state) { return; } } -} -} +} // namespace CustomInterfaces +} // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.h b/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.h index f0cd93360868484c2be3e42e99b061bebe1fc3bb..97c952cf2c83c663e2de889347dc54d4f280e441 100644 --- a/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.h +++ b/qt/scientific_interfaces/Indirect/IndirectDiffractionReduction.h @@ -48,6 +48,21 @@ private: void loadSettings(); void saveSettings(); + Mantid::API::IAlgorithm_sptr saveGSSAlgorithm(const std::string &filename); + Mantid::API::IAlgorithm_sptr + saveASCIIAlgorithm(const std::string &filename, + const std::string &inputWsName); + Mantid::API::IAlgorithm_sptr + saveNexusProcessedAlgorithm(const std::string &filename, + const std::string &inputWsName); + Mantid::API::IAlgorithm_sptr + saveAlgorithm(const std::string &saveAlgName, const std::string &filename, + const std::string &inputWsName = "", const int &version = -1); + Mantid::API::IAlgorithm_sptr + convertUnitsAlgorithm(const std::string &inputWsName, + const std::string &outputWsName, + const std::string &target); + bool validateRebin(); bool validateVanCal(); bool validateCalOnly(); @@ -69,7 +84,7 @@ private: std::vector<std::string> m_plotWorkspaces; std::string m_groupingWsName; }; -} -} +} // namespace CustomInterfaces +} // namespace MantidQt #endif // MANTIDQTCUSTOMINTERFACES_INDIRECTDIFFRACTIONREDUCTION_H_ diff --git a/qt/scientific_interfaces/Indirect/IndirectMolDyn.cpp b/qt/scientific_interfaces/Indirect/IndirectMolDyn.cpp index c4cfba55ee49c6090978899fd093db4570f2838d..c8af0075019289403f11b63e22989ca23876347f 100644 --- a/qt/scientific_interfaces/Indirect/IndirectMolDyn.cpp +++ b/qt/scientific_interfaces/Indirect/IndirectMolDyn.cpp @@ -136,7 +136,7 @@ void IndirectMolDyn::plotClicked() { auto names = diffResultsGroup->getNames(); auto plotType = m_uiForm.cbPlot->currentText(); - for (const auto wsName : names) { + for (const auto &wsName : names) { if (plotType == "Spectra" || plotType == "Both") plotSpectrum(QString::fromStdString(wsName)); diff --git a/qt/scientific_interfaces/Indirect/IndirectTab.cpp b/qt/scientific_interfaces/Indirect/IndirectTab.cpp index 1ac2451295a275c7c3e36063dd542cfbce49d35e..d5ce2d9220fca8386f22f6fac2537d03c49ebfda 100644 --- a/qt/scientific_interfaces/Indirect/IndirectTab.cpp +++ b/qt/scientific_interfaces/Indirect/IndirectTab.cpp @@ -440,6 +440,19 @@ void IndirectTab::plotTimeBin(const QString &workspaceName, int binIndex) { plotTimeBin(workspaceNames, binIndex); } +/* + * Resizes the range (y-axis) of the specified plot preview given the specified + * range + * + * @param preview The plot preview whose range to resize. + * @param range The range to resize to, as a pair of minimum and maximum value + */ +void IndirectTab::resizePlotRange(MantidQt::MantidWidgets::PreviewPlot *preview, + QPair<double, double> range) { + preview->resizeX(); + preview->setAxisRange(range, QwtPlot::yLeft); +} + /* * Updates the values of the function parameters for the function with the * specified name, in the parameters table. @@ -814,5 +827,22 @@ IndirectTab::extractColumnFromTable(Mantid::API::ITableWorkspace_sptr tableWs, return columnValues; } +/* + * Converts a standard vector of standard strings to a QVector of QStrings. + * + * @param stringVec The standard vector of standard strings to convert. + * @return A QVector of QStrings. + */ +QVector<QString> IndirectTab::convertStdStringVector( + const std::vector<std::string> &stringVec) const { + QVector<QString> resultVec; + resultVec.reserve(boost::numeric_cast<int>(stringVec.size())); + + for (auto &str : stringVec) { + resultVec.push_back(QString::fromStdString(str)); + } + return resultVec; +} + } // namespace CustomInterfaces } // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/IndirectTab.h b/qt/scientific_interfaces/Indirect/IndirectTab.h index 04866b8a430838e69690321843f8532fcdbdefcf..c5dd54cd1e77d6223e1bc8bcb50a40106b570201 100644 --- a/qt/scientific_interfaces/Indirect/IndirectTab.h +++ b/qt/scientific_interfaces/Indirect/IndirectTab.h @@ -8,6 +8,7 @@ #include "MantidKernel/System.h" #include "MantidQtWidgets/Common/AlgorithmRunner.h" #include "MantidQtWidgets/Common/BatchAlgorithmRunner.h" +#include "MantidQtWidgets/Common/PreviewPlot.h" #include "MantidQtWidgets/Common/PythonRunner.h" #include "MantidQtWidgets/Common/QtPropertyBrowser/QtIntPropertyManager" #include "MantidQtWidgets/Common/QtPropertyBrowser/QtTreePropertyBrowser" @@ -132,6 +133,10 @@ protected: /// Plot a contour plot of a given workspace void plot2D(const QString &workspaceName); + /// Resizes the specified plot range + void resizePlotRange(MantidQt::MantidWidgets::PreviewPlot *preview, + QPair<double, double> range); + /// Updates the properties in the m_dblManager void updateProperties(const QString &functionName, const QString &prefix, const QStringList ¶mNames, @@ -200,6 +205,10 @@ protected: bool getResolutionRangeFromWs(Mantid::API::MatrixWorkspace_const_sptr ws, QPair<double, double> &res); + /// Converts a standard vector of standard strings to a QVector of QStrings. + QVector<QString> + convertStdStringVector(const std::vector<std::string> &stringVec) const; + /// Function to run an algorithm on a seperate thread void runAlgorithm(const Mantid::API::IAlgorithm_sptr algorithm); diff --git a/qt/scientific_interfaces/Indirect/Iqt.cpp b/qt/scientific_interfaces/Indirect/Iqt.cpp index e6472084c702f3c1a01bcca13ab5f3e7685f973f..b71d6b63ff95db666354a609195e430ce9b48fc8 100644 --- a/qt/scientific_interfaces/Indirect/Iqt.cpp +++ b/qt/scientific_interfaces/Indirect/Iqt.cpp @@ -17,8 +17,7 @@ namespace MantidQt { namespace CustomInterfaces { namespace IDA { Iqt::Iqt(QWidget *parent) - : IndirectDataAnalysisTab(parent), m_iqtTree(nullptr), m_iqtResFileType(), - m_IqtInputWS() { + : IndirectDataAnalysisTab(parent), m_iqtTree(nullptr), m_iqtResFileType() { m_uiForm.setupUi(parent); } @@ -390,8 +389,9 @@ void Iqt::plotInput(const QString &wsname) { } // Set saved workspace - m_IqtInputWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + auto inputWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( wsname.toStdString()); + setInputWorkspace(inputWs); } catch (std::invalid_argument &exc) { showMessageBox(exc.what()); } @@ -399,18 +399,6 @@ void Iqt::plotInput(const QString &wsname) { calculateBinning(); } -/** -* Plots the current spectrum displayed in the preview plot -*/ -void Iqt::plotCurrentPreview() { - - // Check whether an input workspace has been selected and exists - if (m_IqtInputWS) { - IndirectTab::plotSpectrum(QString::fromStdString(m_IqtInputWS->getName()), - 0, 0); - } -} - /** * Updates the range selectors and properties when range selector is moved. * diff --git a/qt/scientific_interfaces/Indirect/Iqt.h b/qt/scientific_interfaces/Indirect/Iqt.h index b16d6c8ae28261a0d523643b423235dbf6023725..ccd77f70ed8f4ce7a68a56522d1a71fd8187a0f3 100644 --- a/qt/scientific_interfaces/Indirect/Iqt.h +++ b/qt/scientific_interfaces/Indirect/Iqt.h @@ -29,13 +29,11 @@ private slots: void saveClicked(); void plotClicked(); void PlotTiled(); - void plotCurrentPreview(); private: Ui::Iqt m_uiForm; QtTreePropertyBrowser *m_iqtTree; bool m_iqtResFileType; - Mantid::API::MatrixWorkspace_sptr m_IqtInputWS; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/IqtFit.cpp b/qt/scientific_interfaces/Indirect/IqtFit.cpp index efe1fdd9f9b7731a8a73d29a5d83169542455e82..51e1a0283c68be24c810d8824d5d66afbe9e8ae0 100644 --- a/qt/scientific_interfaces/Indirect/IqtFit.cpp +++ b/qt/scientific_interfaces/Indirect/IqtFit.cpp @@ -27,8 +27,7 @@ namespace IDA { IqtFit::IqtFit(QWidget *parent) : IndirectDataAnalysisTab(parent), m_stringManager(nullptr), m_iqtFTree(nullptr), m_iqtFRangeManager(nullptr), m_fixedProps(), - m_iqtFInputWS(), m_previewPlotData(), m_ties(), m_runMin(-1), - m_runMax(-1) { + m_ties(), m_runMin(-1), m_runMax(-1) { m_uiForm.setupUi(parent); } @@ -134,6 +133,8 @@ void IqtFit::setup() { SLOT(updatePlot())); connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, SLOT(updateProperties(int))); + connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, + SLOT(IndirectDataAnalysisTab::setSelectedSpectrum(int))); connect(m_uiForm.spSpectraMin, SIGNAL(valueChanged(int)), this, SLOT(specMinChanged(int))); @@ -154,21 +155,23 @@ void IqtFit::setup() { connect(m_uiForm.pbPlot, SIGNAL(clicked()), this, SLOT(plotWorkspace())); connect(m_uiForm.pbSave, SIGNAL(clicked()), this, SLOT(saveResult())); connect(m_uiForm.pbPlotPreview, SIGNAL(clicked()), this, - SLOT(plotCurrentPreview())); + SLOT(IndirectDataAnalysisTab::plotCurrentPreview())); } void IqtFit::run() { + auto inputWs = inputWorkspace(); - if (!m_iqtFInputWS.lock()) { - return; + if (!inputWs) { + QString msg = "Input workspace was deleted from the Analysis Data Service " + "before Algorithm could run."; + showMessageBox(msg); } m_runMin = boost::numeric_cast<size_t>(m_uiForm.spSpectraMin->value()); m_runMax = boost::numeric_cast<size_t>(m_uiForm.spSpectraMax->value()); updateFitFunctions(); - IAlgorithm_sptr iqtFitAlg = - iqtFitAlgorithm(m_iqtFInputWS.lock(), m_runMin, m_runMax); + IAlgorithm_sptr iqtFitAlg = iqtFitAlgorithm(inputWs, m_runMin, m_runMax); m_batchAlgoRunner->addAlgorithm(iqtFitAlg); connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, @@ -272,8 +275,8 @@ void IqtFit::saveResult() { * Plots the current spectrum displayed in the preview plot */ void IqtFit::plotCurrentPreview() { - auto inputWs = m_iqtFInputWS.lock(); - auto previewWs = m_previewPlotData.lock(); + auto inputWs = inputWorkspace(); + auto previewWs = previewPlotWorkspace(); if (!inputWs || !previewWs) { return; @@ -382,7 +385,8 @@ void IqtFit::loadSettings(const QSettings &settings) { void IqtFit::newDataLoaded(const QString wsName) { auto inputWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( wsName.toStdString()); - m_iqtFInputWS = inputWs; + setInputWorkspace(inputWs); + setPreviewPlotWorkspace(inputWs); int maxWsIndex = static_cast<int>(inputWs->getNumberHistograms()) - 1; @@ -605,7 +609,7 @@ void IqtFit::updateCurrentPlotOption(QString newOption) { } void IqtFit::updatePlot() { - auto inputWs = m_iqtFInputWS.lock(); + auto inputWs = inputWorkspace(); if (!inputWs) { g_log.error("No workspace loaded, cannot create preview plot."); @@ -622,7 +626,7 @@ void IqtFit::updatePlot() { specNo <= m_runMax && specNo >= m_runMin) { plotResult(groupName, specNo); } else if (inputWs) { - m_previewPlotData = m_iqtFInputWS; + setPreviewPlotWorkspace(inputWs); m_uiForm.ppPlot->addSpectrum("Sample", inputWs, specNo); } @@ -657,7 +661,7 @@ void IqtFit::plotResult(const std::string &groupName, const size_t &specNo) { m_uiForm.ckPlotGuess->setChecked(false); } - m_previewPlotData = ws; + setPreviewPlotWorkspace(ws); m_uiForm.ppPlot->addSpectrum("Sample", ws, 0, Qt::black); m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); @@ -675,7 +679,7 @@ void IqtFit::setDefaultParameters(const QString &name) { // intensity is always 1-background m_dblManager->setValue(m_properties[name + ".Intensity"], 1.0 - background); - auto inputWs = m_iqtFInputWS.lock(); + auto inputWs = inputWorkspace(); double tau = 0; if (inputWs) { @@ -886,7 +890,7 @@ void IqtFit::singleFit() { updateFitFunctions(); size_t specNo = m_uiForm.spPlotSpectrum->text().toULongLong(); - m_singleFitAlg = iqtFitAlgorithm(m_iqtFInputWS.lock(), specNo, specNo); + m_singleFitAlg = iqtFitAlgorithm(inputWorkspace(), specNo, specNo); connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(singleFitComplete(bool))); @@ -921,7 +925,7 @@ void IqtFit::updateGuessPlot() { void IqtFit::plotGuess(QtProperty *) { CompositeFunction_sptr function = createFunction(true); - auto inputWs = m_iqtFInputWS.lock(); + auto inputWs = inputWorkspace(); // Create the double* array from the input workspace const size_t binIndxLow = diff --git a/qt/scientific_interfaces/Indirect/IqtFit.h b/qt/scientific_interfaces/Indirect/IqtFit.h index 4cf0e40e7becbf32e9f22f29b16829d2c6da7637..b5d4102e67330c75837435dbd78ea4f3ec30b8d9 100644 --- a/qt/scientific_interfaces/Indirect/IqtFit.h +++ b/qt/scientific_interfaces/Indirect/IqtFit.h @@ -89,8 +89,6 @@ private: QtTreePropertyBrowser *m_iqtFTree; ///< IqtFit Property Browser QtDoublePropertyManager *m_iqtFRangeManager; ///< StartX and EndX for IqtFit QMap<QtProperty *, QtProperty *> m_fixedProps; - boost::weak_ptr<Mantid::API::MatrixWorkspace> m_iqtFInputWS; - boost::weak_ptr<Mantid::API::MatrixWorkspace> m_previewPlotData; QString m_ties; Mantid::API::IAlgorithm_sptr m_singleFitAlg; QString m_singleFitOutputName; diff --git a/qt/scientific_interfaces/Indirect/JumpFit.cpp b/qt/scientific_interfaces/Indirect/JumpFit.cpp index 539f9f9c2a3f346f2fa4c97cf78ef2b1c8e77a4b..13a48d0d46a28c3718c2c4b145d6508496278458 100644 --- a/qt/scientific_interfaces/Indirect/JumpFit.cpp +++ b/qt/scientific_interfaces/Indirect/JumpFit.cpp @@ -17,8 +17,7 @@ namespace CustomInterfaces { namespace IDA { JumpFit::JumpFit(QWidget *parent) - : IndirectDataAnalysisTab(parent), m_jfTree(nullptr), m_jfInputWS(), - m_specNo(0) { + : IndirectDataAnalysisTab(parent), m_jfTree(nullptr) { m_uiForm.setupUi(parent); } @@ -76,7 +75,7 @@ void JumpFit::setup() { connect(m_uiForm.pbSave, SIGNAL(clicked()), this, SLOT(saveClicked())); connect(m_uiForm.pbPlot, SIGNAL(clicked()), this, SLOT(plotClicked())); connect(m_uiForm.pbPlotPreview, SIGNAL(clicked()), this, - SLOT(plotCurrentPreview())); + SLOT(IndirectDataAnalysisTab::plotCurrentPreview())); } /** @@ -197,7 +196,7 @@ void JumpFit::fitAlgDone(bool error) { m_uiForm.ckPlotGuess->setChecked(false); } for (auto it = m_properties.begin(); it != m_properties.end(); ++it) { - QString propName(it.key()); + const QString &propName(it.key()); if (propName.startsWith("parameter_")) { size_t row(0), col(0); paramTable->find(propName.split("_")[1].toStdString(), row, col); @@ -234,20 +233,21 @@ void JumpFit::handleSampleInputReady(const QString &filename) { scaleAlg->setProperty("Factor", 0.5); scaleAlg->execute(); - auto ws = Mantid::API::AnalysisDataService::Instance().retrieve( - sample.toStdString()); - m_jfInputWS = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws); + auto ws = + Mantid::API::AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( + sample.toStdString()); + setInputWorkspace(ws); - findAllWidths(m_jfInputWS); + findAllWidths(inputWorkspace()); auto qRangeSelector = m_uiForm.ppPlot->getRangeSelector("JumpFitQ"); if (m_spectraList.size() > 0) { m_uiForm.cbWidth->setEnabled(true); std::string currentWidth = m_uiForm.cbWidth->currentText().toStdString(); - m_specNo = m_spectraList[currentWidth]; + setSelectedSpectrum(m_spectraList[currentWidth]); m_uiForm.ppPlot->clear(); - m_uiForm.ppPlot->addSpectrum("Sample", sample, m_specNo); + m_uiForm.ppPlot->addSpectrum("Sample", sample, selectedSpectrum()); QPair<double, double> res; QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample"); @@ -558,17 +558,6 @@ void JumpFit::saveClicked() { m_batchAlgoRunner->executeBatchAsync(); } -/** -* Plots the current spectrum displayed in the preview plot -*/ -void JumpFit::plotCurrentPreview() { - - // Check if a workspace has been selected - if (m_jfInputWS) { - IndirectTab::plotSpectrum(QString::fromStdString(m_jfInputWS->getName()), - m_specNo, m_specNo); - } -} } // namespace IDA } // namespace CustomInterfaces } // namespace MantidQt diff --git a/qt/scientific_interfaces/Indirect/JumpFit.h b/qt/scientific_interfaces/Indirect/JumpFit.h index 735304473a3a4f6cba74df4b9bd046e0c1fba9fb..e93dd388595325053a33dbf846c2c8f2c28bd6cc 100644 --- a/qt/scientific_interfaces/Indirect/JumpFit.h +++ b/qt/scientific_interfaces/Indirect/JumpFit.h @@ -42,7 +42,6 @@ private slots: /// Handles plotting and saving void saveClicked(); void plotClicked(); - void plotCurrentPreview(); private: /// Gets a list of parameter names for a given fit function @@ -60,15 +59,12 @@ private: // The UI form Ui::JumpFit m_uiForm; - // Map of axis labels to spectrum number + /// Map of axis labels to spectrum number std::map<std::string, int> m_spectraList; QtTreePropertyBrowser *m_jfTree; Mantid::API::IAlgorithm_sptr m_fitAlg; - - Mantid::API::MatrixWorkspace_sptr m_jfInputWS; - int m_specNo; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/MSDFit.cpp b/qt/scientific_interfaces/Indirect/MSDFit.cpp index e0c368613b1780a2e5ec5f08c02fd65592d9bb7a..620e5780a29d08e037d63cb16a195015046a47b8 100644 --- a/qt/scientific_interfaces/Indirect/MSDFit.cpp +++ b/qt/scientific_interfaces/Indirect/MSDFit.cpp @@ -1,7 +1,7 @@ -#include "MantidAPI/AnalysisDataService.h" -#include "MantidAPI/WorkspaceGroup.h" #include "MSDFit.h" #include "../General/UserInputValidator.h" +#include "MantidAPI/AnalysisDataService.h" +#include "MantidAPI/WorkspaceGroup.h" #include "MantidQtWidgets/Common/RangeSelector.h" #include <QFileInfo> @@ -19,7 +19,7 @@ namespace MantidQt { namespace CustomInterfaces { namespace IDA { MSDFit::MSDFit(QWidget *parent) - : IndirectDataAnalysisTab(parent), m_msdTree(nullptr), m_msdInputWS() { + : IndirectDataAnalysisTab(parent), m_msdTree(nullptr) { m_uiForm.setupUi(parent); } @@ -30,16 +30,19 @@ void MSDFit::setup() { m_msdTree->setFactoryForManager(m_dblManager, m_dblEdFac); - m_properties["Start"] = m_dblManager->addProperty("StartX"); - m_dblManager->setDecimals(m_properties["Start"], NUM_DECIMALS); - m_properties["End"] = m_dblManager->addProperty("EndX"); - m_dblManager->setDecimals(m_properties["End"], NUM_DECIMALS); + m_properties["StartX"] = m_dblManager->addProperty("StartX"); + m_dblManager->setDecimals(m_properties["StartX"], NUM_DECIMALS); + m_properties["EndX"] = m_dblManager->addProperty("EndX"); + m_dblManager->setDecimals(m_properties["EndX"], NUM_DECIMALS); - m_msdTree->addProperty(m_properties["Start"]); - m_msdTree->addProperty(m_properties["End"]); + m_properties["Gaussian"] = createModel("Gaussian", {"Intensity", "MSD"}); + m_properties["Peters"] = createModel("Peters", {"Intensity", "MSD", "Beta"}); + m_properties["Yi"] = createModel("Yi", {"Intensity", "MSD", "Sigma"}); auto fitRangeSelector = m_uiForm.ppPlot->addRangeSelector("MSDRange"); + modelSelection(m_uiForm.cbModelInput->currentIndex()); + connect(fitRangeSelector, SIGNAL(minValueChanged(double)), this, SLOT(minChanged(double))); connect(fitRangeSelector, SIGNAL(maxValueChanged(double)), this, @@ -49,23 +52,26 @@ void MSDFit::setup() { connect(m_uiForm.dsSampleInput, SIGNAL(dataReady(const QString &)), this, SLOT(newDataLoaded(const QString &))); + connect(m_uiForm.cbModelInput, SIGNAL(currentIndexChanged(int)), this, + SLOT(modelSelection(int))); connect(m_uiForm.pbSingleFit, SIGNAL(clicked()), this, SLOT(singleFit())); + + connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, + SLOT(IndirectDataAnalysisTab::setSelectedSpectrum(int))); connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, - SLOT(plotInput())); + SLOT(updateProperties(int))); connect(m_uiForm.spPlotSpectrum, SIGNAL(valueChanged(int)), this, - SLOT(plotFit())); + SLOT(updatePlot(int))); connect(m_uiForm.spSpectraMin, SIGNAL(valueChanged(int)), this, SLOT(specMinChanged(int))); connect(m_uiForm.spSpectraMax, SIGNAL(valueChanged(int)), this, SLOT(specMaxChanged(int))); - connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, - SLOT(plotFit())); connect(m_uiForm.pbPlot, SIGNAL(clicked()), this, SLOT(plotClicked())); connect(m_uiForm.pbSave, SIGNAL(clicked()), this, SLOT(saveClicked())); connect(m_uiForm.pbPlotPreview, SIGNAL(clicked()), this, - SLOT(plotCurrentPreview())); + SLOT(IndirectDataAnalysisTab::plotCurrentPreview())); } void MSDFit::run() { @@ -73,33 +79,25 @@ void MSDFit::run() { return; // Set the result workspace for Python script export - QString model = m_uiForm.modelInput->currentText(); + auto model = m_uiForm.cbModelInput->currentText(); QString dataName = m_uiForm.dsSampleInput->getCurrentDataName(); - m_pythonExportWsName = - dataName.left(dataName.lastIndexOf("_")).toStdString() + "_" + - model.toStdString() + "_msd"; - QString wsName = m_uiForm.dsSampleInput->getCurrentDataName(); - double xStart = m_dblManager->value(m_properties["Start"]); - double xEnd = m_dblManager->value(m_properties["End"]); long specMin = m_uiForm.spSpectraMin->value(); long specMax = m_uiForm.spSpectraMax->value(); - IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit"); - msdAlg->initialize(); - msdAlg->setProperty("Model", model.toStdString()); - msdAlg->setProperty("InputWorkspace", wsName.toStdString()); - msdAlg->setProperty("XStart", xStart); - msdAlg->setProperty("XEnd", xEnd); - msdAlg->setProperty("SpecMin", specMin); - msdAlg->setProperty("SpecMax", specMax); - msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName); + m_pythonExportWsName = + dataName.left(dataName.lastIndexOf("_")).toStdString() + "_s" + + std::to_string(specMin) + "_to_s" + std::to_string(specMax) + "_" + + model.toStdString() + "_msd"; + m_parameterToProperty = createParameterToPropertyMap(model); + IAlgorithm_sptr msdAlg = + msdFitAlgorithm(modelToAlgorithmProperty(model), specMin, specMax); m_batchAlgoRunner->addAlgorithm(msdAlg); - m_batchAlgoRunner->executeBatchAsync(); connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool))); + m_batchAlgoRunner->executeBatchAsync(); } void MSDFit::singleFit() { @@ -107,27 +105,55 @@ void MSDFit::singleFit() { return; // Set the result workspace for Python script export + auto model = m_uiForm.cbModelInput->currentText(); QString dataName = m_uiForm.dsSampleInput->getCurrentDataName(); + long fitSpec = m_uiForm.spPlotSpectrum->value(); + m_pythonExportWsName = - dataName.left(dataName.lastIndexOf("_")).toStdString() + "_msd"; + dataName.left(dataName.lastIndexOf("_")).toStdString() + "_s" + + std::to_string(fitSpec) + "_" + model.toStdString() + "_msd"; + m_parameterToProperty = createParameterToPropertyMap(model); - QString wsName = m_uiForm.dsSampleInput->getCurrentDataName(); - double xStart = m_dblManager->value(m_properties["Start"]); - double xEnd = m_dblManager->value(m_properties["End"]); - long fitSpec = m_uiForm.spPlotSpectrum->value(); + IAlgorithm_sptr msdAlg = + msdFitAlgorithm(modelToAlgorithmProperty(model), fitSpec, fitSpec); + m_batchAlgoRunner->addAlgorithm(msdAlg); + + connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, + SLOT(algorithmComplete(bool))); + m_batchAlgoRunner->executeBatchAsync(); +} + +/* + * Creates an initialized MSDFit Algorithm, using the model with the + * specified name, to be run from the specified minimum spectrum to + * the specified maximum spectrum. + * + * @param model The name of the model to be used by the algorithm. + * @param specMin The minimum spectrum to fit. + * @param specMax The maximum spectrum to fit. + * @return An MSDFit Algorithm using the specified model, which + * will run across all spectrum between the specified + * minimum and maximum. + */ +IAlgorithm_sptr MSDFit::msdFitAlgorithm(const std::string &model, long specMin, + long specMax) { + auto wsName = m_uiForm.dsSampleInput->getCurrentDataName().toStdString(); + double xStart = m_dblManager->value(m_properties["StartX"]); + double xEnd = m_dblManager->value(m_properties["EndX"]); + m_runMin = boost::numeric_cast<size_t>(specMin); + m_runMax = boost::numeric_cast<size_t>(specMax); IAlgorithm_sptr msdAlg = AlgorithmManager::Instance().create("MSDFit"); msdAlg->initialize(); - msdAlg->setProperty("InputWorkspace", wsName.toStdString()); + msdAlg->setProperty("InputWorkspace", wsName); + msdAlg->setProperty("Model", model); msdAlg->setProperty("XStart", xStart); msdAlg->setProperty("XEnd", xEnd); - msdAlg->setProperty("SpecMin", fitSpec); - msdAlg->setProperty("SpecMax", fitSpec); + msdAlg->setProperty("SpecMin", specMin); + msdAlg->setProperty("SpecMax", specMax); msdAlg->setProperty("OutputWorkspace", m_pythonExportWsName); - m_batchAlgoRunner->addAlgorithm(msdAlg); - - m_batchAlgoRunner->executeBatchAsync(); + return msdAlg; } bool MSDFit::validate() { @@ -135,8 +161,8 @@ bool MSDFit::validate() { uiv.checkDataSelectorIsValid("Sample input", m_uiForm.dsSampleInput); - auto range = std::make_pair(m_dblManager->value(m_properties["Start"]), - m_dblManager->value(m_properties["End"])); + auto range = std::make_pair(m_dblManager->value(m_properties["StartX"]), + m_dblManager->value(m_properties["EndX"])); uiv.checkValidRange("a range", range); int specMin = m_uiForm.spSpectraMin->value(); @@ -166,53 +192,65 @@ void MSDFit::algorithmComplete(bool error) { if (error) return; + m_parameterValues = IndirectTab::extractParametersFromTable( + m_pythonExportWsName + "_Parameters", + m_parameterToProperty.keys().toSet(), m_runMin, m_runMax); + updateProperties(m_uiForm.spPlotSpectrum->value()); + updatePlot(m_uiForm.spPlotSpectrum->value()); + // Enable plot and save m_uiForm.pbPlot->setEnabled(true); m_uiForm.pbSave->setEnabled(true); } -/** - * Plots fitted data on the mini plot. - * - * @param wsName Name of fit _Workspaces workspace group (defaults to - * Python export WS name + _Workspaces) - * @param specNo Spectrum number relating to input workspace to plot fit - * for (defaults to value of preview spectrum index) - */ -void MSDFit::plotFit(QString wsName, int specNo) { - if (wsName.isEmpty()) - wsName = QString::fromStdString(m_pythonExportWsName) + "_Workspaces"; +void MSDFit::updatePlot(int spectrumNo) { + m_uiForm.ppPlot->clear(); - if (specNo == -1) - specNo = m_uiForm.spPlotSpectrum->value(); + size_t specNo = boost::numeric_cast<size_t>(spectrumNo); + const auto groupName = m_pythonExportWsName + "_Workspaces"; + + if (AnalysisDataService::Instance().doesExist(groupName) && + m_runMin <= specNo && specNo <= m_runMax) { + plotResult(groupName, specNo); + } else { + auto inputWs = inputWorkspace(); + + if (inputWs) { + setPreviewPlotWorkspace(inputWs); + m_uiForm.ppPlot->addSpectrum("Sample", inputWs, specNo); + } else { + g_log.error("No workspace loaded, cannot create preview plot."); + return; + } + } - if (Mantid::API::AnalysisDataService::Instance().doesExist( - wsName.toStdString())) { - // Remove the old fit - m_uiForm.ppPlot->removeSpectrum("Fit"); + updatePlotRange(); +} - // Get the workspace - auto groupWs = - AnalysisDataService::Instance().retrieveWS<const WorkspaceGroup>( - wsName.toStdString()); - auto groupWsNames = groupWs->getNames(); +void MSDFit::updatePlotRange() { - // Find the correct fit workspace and plot it - std::stringstream searchString; - searchString << "_" << specNo << "_Workspace"; - for (auto it = groupWsNames.begin(); it != groupWsNames.end(); ++it) { - std::string wsName = *it; - if (wsName.find(searchString.str()) != std::string::npos) { - // Get the fit workspace - auto ws = - AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName); - m_msdInputWS = ws; - // Plot the new fit - m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); - // Nothing else to do - return; - } - } + try { + QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample"); + m_uiForm.ppPlot->getRangeSelector("MSDRange") + ->setRange(range.first, range.second); + IndirectTab::resizePlotRange(m_uiForm.ppPlot, qMakePair(0.0, 1.0)); + } catch (std::invalid_argument &exc) { + showMessageBox(exc.what()); + } +} + +void MSDFit::plotResult(const std::string &groupWsName, size_t specNo) { + WorkspaceGroup_sptr outputGroup = + AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(groupWsName); + + MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<MatrixWorkspace>( + outputGroup->getItem(specNo - m_runMin)); + + if (ws) { + setPreviewPlotWorkspace(ws); + m_uiForm.ppPlot->addSpectrum("Sample", ws, 0, Qt::black); + m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red); + m_uiForm.ppPlot->addSpectrum("Diff", ws, 2, Qt::blue); } } @@ -224,10 +262,13 @@ void MSDFit::plotFit(QString wsName, int specNo) { * @param wsName Name of new workspace loaded */ void MSDFit::newDataLoaded(const QString wsName) { - m_msdInputWS = + auto workspace = Mantid::API::AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( wsName.toStdString()); - int maxWsIndex = static_cast<int>(m_msdInputWS->getNumberHistograms()) - 1; + int maxWsIndex = static_cast<int>(workspace->getNumberHistograms()) - 1; + setInputWorkspace(workspace); + setPreviewPlotWorkspace(workspace); + m_pythonExportWsName = ""; m_uiForm.spPlotSpectrum->setMaximum(maxWsIndex); m_uiForm.spPlotSpectrum->setMinimum(0); @@ -240,25 +281,7 @@ void MSDFit::newDataLoaded(const QString wsName) { m_uiForm.spSpectraMax->setMinimum(0); m_uiForm.spSpectraMax->setValue(maxWsIndex); - plotInput(); -} - -/** - * Plot the supplied input workspace in the mini-plot. - */ -void MSDFit::plotInput() { - m_uiForm.ppPlot->clear(); - - int wsIndex = m_uiForm.spPlotSpectrum->value(); - m_uiForm.ppPlot->addSpectrum("Sample", m_msdInputWS, wsIndex); - - try { - QPair<double, double> range = m_uiForm.ppPlot->getCurveRange("Sample"); - m_uiForm.ppPlot->getRangeSelector("MSDRange") - ->setRange(range.first, range.second); - } catch (std::invalid_argument &exc) { - showMessageBox(exc.what()); - } + updatePlot(m_uiForm.spPlotSpectrum->value()); } /** @@ -284,22 +307,122 @@ void MSDFit::specMaxChanged(int value) { } void MSDFit::minChanged(double val) { - m_dblManager->setValue(m_properties["Start"], val); + m_dblManager->setValue(m_properties["StartX"], val); } void MSDFit::maxChanged(double val) { - m_dblManager->setValue(m_properties["End"], val); + m_dblManager->setValue(m_properties["EndX"], val); } void MSDFit::updateRS(QtProperty *prop, double val) { auto fitRangeSelector = m_uiForm.ppPlot->getRangeSelector("MSDRange"); - if (prop == m_properties["Start"]) + if (prop == m_properties["StartX"]) fitRangeSelector->setMinimum(val); - else if (prop == m_properties["End"]) + else if (prop == m_properties["EndX"]) fitRangeSelector->setMaximum(val); } +/* + * Creates a property representing a model with the specified name, + * and which takes the specified parameters. + * + * @param modelName The name of the model. + * @param modelParameters The parameters taken by the model. + * @return The created property, which represents the + * model in the property table. + */ +QtProperty *MSDFit::createModel(const QString &modelName, + const std::vector<QString> &modelParameters) { + QtProperty *expGroup = m_grpManager->addProperty(modelName); + + for (auto &modelParam : modelParameters) { + QString paramName = modelName + "." + modelParam; + m_properties[paramName] = m_dblManager->addProperty(modelParam); + m_dblManager->setDecimals(m_properties[paramName], NUM_DECIMALS); + expGroup->addSubProperty(m_properties[paramName]); + } + + return expGroup; +} + +void MSDFit::modelSelection(int selected) { + QString model = m_uiForm.cbModelInput->itemText(selected); + m_msdTree->clear(); + + m_msdTree->addProperty(m_properties["StartX"]); + m_msdTree->addProperty(m_properties["EndX"]); + m_msdTree->addProperty(m_properties[model]); +} + +/* + * Creates a map from the names of the specified model's parameters, + * to the name of the property in the property table, associated with + * this parameter. + * + * @param model The model whose parameters to create a map from. + * @return A map from the model parameter names to the names + * of their associated properties in the property table. + */ +QHash<QString, QString> +MSDFit::createParameterToPropertyMap(const QString &model) { + QHash<QString, QString> parameterToProperty; + parameterToProperty["Height"] = model + ".Intensity"; + parameterToProperty["MSD"] = model + ".MSD"; + + if (model == "Peters") + parameterToProperty["Beta"] = model + ".Beta"; + else if (model == "Yi") { + parameterToProperty["Sigma"] = model + ".Sigma"; + } + return parameterToProperty; +} + +/* + * Given the selected model in the interface, returns the name of + * the associated model to pass to the MSDFit algorithm. + * + * @param model The name of the model as displayed in the interface. + * @return The name of the model as defined in the MSDFit algorithm. + */ +std::string MSDFit::modelToAlgorithmProperty(const QString &model) { + + if (model == "Gaussian") + return "Gauss"; + else if (model == "Peters") + return "Peters"; + else if (model == "Yi") + return "Yi"; + else + return ""; +} + +/* + * Updates the property table using the parameter results for the + * specified spectrum. + * + * @param specNo The spectrum number of the parameters to update + * the property table with. + */ +void MSDFit::updateProperties(int specNo) { + size_t index = boost::numeric_cast<size_t>(specNo); + auto parameterNames = m_parameterValues.keys(); + + if (parameterNames.isEmpty()) { + return; + } + + // Check whether parameter values exist for the specified spectrum number + if (m_parameterValues[parameterNames[0]].contains(index)) { + + for (auto ¶mName : parameterNames) { + auto propertyName = m_parameterToProperty[paramName]; + m_dblManager->setValue(m_properties[propertyName], + m_parameterValues[paramName][index]); + } + } +} + /** * Handles saving of workspace */ @@ -314,32 +437,18 @@ void MSDFit::saveClicked() { * Handles mantid plotting */ void MSDFit::plotClicked() { - auto wsName = QString::fromStdString(m_pythonExportWsName) + "_Workspaces"; - if (checkADSForPlotSaveWorkspace(wsName.toStdString(), true)) { + auto wsName = m_pythonExportWsName + "_Workspaces"; + if (checkADSForPlotSaveWorkspace(wsName, true)) { // Get the workspace auto groupWs = AnalysisDataService::Instance().retrieveWS<const WorkspaceGroup>( - wsName.toStdString()); + wsName); auto groupWsNames = groupWs->getNames(); - if (groupWsNames.size() != 1) { - plotSpectrum(QString::fromStdString(m_pythonExportWsName), 1); - } + if (groupWsNames.size() != 1) + plotSpectrum(QString::fromStdString(m_pythonExportWsName), 1); else - plotSpectrum(wsName, 0, 2); - } -} - -/** -* Plots the current spectrum displayed in the preview plot -*/ -void MSDFit::plotCurrentPreview() { - - // Check a workspace has been selected - if (m_msdInputWS) { - const auto workspaceIndex = m_uiForm.spPlotSpectrum->value(); - IndirectTab::plotSpectrum(QString::fromStdString(m_msdInputWS->getName()), - workspaceIndex, workspaceIndex); + plotSpectrum(QString::fromStdString(wsName), 0, 2); } } diff --git a/qt/scientific_interfaces/Indirect/MSDFit.h b/qt/scientific_interfaces/Indirect/MSDFit.h index 3f6638750b166bf74b19fae3e411c167f29e79ef..b701e35445a5194b2e4d9b4932777452a22f7d07 100644 --- a/qt/scientific_interfaces/Indirect/MSDFit.h +++ b/qt/scientific_interfaces/Indirect/MSDFit.h @@ -1,8 +1,8 @@ #ifndef MANTIDQTCUSTOMINTERFACESIDA_MSDFIT_H_ #define MANTIDQTCUSTOMINTERFACESIDA_MSDFIT_H_ -#include "ui_MSDFit.h" #include "IndirectDataAnalysisTab.h" +#include "ui_MSDFit.h" namespace MantidQt { namespace CustomInterfaces { @@ -21,9 +21,7 @@ private: private slots: void singleFit(); - void plotFit(QString wsName = QString(), int specNo = -1); void newDataLoaded(const QString wsName); - void plotInput(); void specMinChanged(int value); void specMaxChanged(int value); void minChanged(double val); @@ -31,13 +29,28 @@ private slots: void updateRS(QtProperty *prop, double val); void saveClicked(); void plotClicked(); - void plotCurrentPreview(); void algorithmComplete(bool error); + void modelSelection(int selected); + void updatePlot(int specNo); + void updatePlotRange(); + void updateProperties(int specNo); private: + Mantid::API::IAlgorithm_sptr msdFitAlgorithm(const std::string &model, + long specMin, long specMax); + QtProperty *createModel(const QString &modelName, + const std::vector<QString> &modelParameters); + void plotResult(const std::string &groupWsName, size_t specNo); + QHash<QString, QString> createParameterToPropertyMap(const QString &model); + std::string modelToAlgorithmProperty(const QString &model); + Ui::MSDFit m_uiForm; QtTreePropertyBrowser *m_msdTree; - Mantid::API::MatrixWorkspace_sptr m_msdInputWS; + size_t m_runMin; + size_t m_runMax; + + QHash<QString, QHash<size_t, double>> m_parameterValues; + QHash<QString, QString> m_parameterToProperty; }; } // namespace IDA } // namespace CustomInterfaces diff --git a/qt/scientific_interfaces/Indirect/MSDFit.ui b/qt/scientific_interfaces/Indirect/MSDFit.ui index ff46f67a2ea65a6046d7c650a2c1ee1fd1c35016..10f3d8e688486c2b99cf7589be57714de916206e 100644 --- a/qt/scientific_interfaces/Indirect/MSDFit.ui +++ b/qt/scientific_interfaces/Indirect/MSDFit.ui @@ -21,10 +21,10 @@ </property> <layout class="QGridLayout" name="gridLayout"> <item row="0" column="0"> - <widget class="QComboBox" name="modelInput"> + <widget class="QComboBox" name="cbModelInput"> <item> <property name="text"> - <string>Gauss</string> + <string>Gaussian</string> </property> </item> <item> diff --git a/qt/scientific_interfaces/Muon/ALCDataLoadingView.cpp b/qt/scientific_interfaces/Muon/ALCDataLoadingView.cpp index 92223001cd84aa8d9d78901980bf17f25df45c90..47cfb94d1bb054a85470737b280ea29eb211137c 100644 --- a/qt/scientific_interfaces/Muon/ALCDataLoadingView.cpp +++ b/qt/scientific_interfaces/Muon/ALCDataLoadingView.cpp @@ -229,7 +229,7 @@ void ALCDataLoadingView::setAvailableItems( } // Add new items - for (const auto item : items) { + for (const auto &item : items) { if (item != previousValue) { // has already been added comboBox->addItem(QString::fromStdString(item)); } diff --git a/qt/scientific_interfaces/Muon/MuonAnalysisDataLoader.cpp b/qt/scientific_interfaces/Muon/MuonAnalysisDataLoader.cpp index d575891ea32a8bdd8f3b34718d906beaebbf67fc..e3761665e5940d37219dfacf90902dc5519a60e5 100644 --- a/qt/scientific_interfaces/Muon/MuonAnalysisDataLoader.cpp +++ b/qt/scientific_interfaces/Muon/MuonAnalysisDataLoader.cpp @@ -76,7 +76,7 @@ LoadResult MuonAnalysisDataLoader::loadFiles(const QStringList &files) const { const auto toString = [](QStringList qsl) { std::ostringstream oss; qsl.sort(); - for (const QString qs : qsl) { + for (const QString &qs : qsl) { oss << qs.toStdString() << ","; } return oss.str(); @@ -98,7 +98,7 @@ LoadResult MuonAnalysisDataLoader::loadFiles(const QStringList &files) const { std::string instrName; // Instrument name all the run files should belong to // Go through all the files and try to load them - for (const auto fileName : files) { + for (const auto &fileName : files) { std::string file = fileName.toStdString(); // Set up load algorithm diff --git a/qt/scientific_interfaces/Muon/MuonAnalysisFitDataPresenter.cpp b/qt/scientific_interfaces/Muon/MuonAnalysisFitDataPresenter.cpp index 2b6104fdedbf1694ff0ece5690fe136d9f444bf8..8518ad77767fe7b59822dd354be05a8a9e117460 100644 --- a/qt/scientific_interfaces/Muon/MuonAnalysisFitDataPresenter.cpp +++ b/qt/scientific_interfaces/Muon/MuonAnalysisFitDataPresenter.cpp @@ -344,7 +344,7 @@ std::vector<std::string> MuonAnalysisFitDataPresenter::generateWorkspaceNames( } } - for (const auto runsVector : runNumberVectors) { + for (const auto &runsVector : runNumberVectors) { params.runs = runsVector; for (const auto &group : groups) { params.itemType = getItemType(group.toStdString()); diff --git a/qt/scientific_interfaces/Muon/MuonAnalysisHelper.cpp b/qt/scientific_interfaces/Muon/MuonAnalysisHelper.cpp index e5db428d4311fb1a7b96515bbd2f970267e40715..9bc0bf7a5f9cd7f9772e995779c0cd2e84d0b1d5 100644 --- a/qt/scientific_interfaces/Muon/MuonAnalysisHelper.cpp +++ b/qt/scientific_interfaces/Muon/MuonAnalysisHelper.cpp @@ -731,7 +731,7 @@ std::pair<std::string, std::string> findLogRange( const std::vector<Workspace_sptr> &workspaces, const std::string &logName, bool (*isLessThan)(const std::string &first, const std::string &second)) { std::string smallest, largest; - for (auto ws : workspaces) { + for (const auto &ws : workspaces) { auto range = findLogRange(ws, logName, isLessThan); if (smallest.empty() || isLessThan(range.first, smallest)) { smallest = range.first; diff --git a/qt/scientific_interfaces/Muon/MuonAnalysisResultTableTab.cpp b/qt/scientific_interfaces/Muon/MuonAnalysisResultTableTab.cpp index 082fb07e7d8686ebe3c2b1686a2a0f3e95c54c5c..635c7a7ac0ffbd3916a1782d4a63086920bb25b6 100644 --- a/qt/scientific_interfaces/Muon/MuonAnalysisResultTableTab.cpp +++ b/qt/scientific_interfaces/Muon/MuonAnalysisResultTableTab.cpp @@ -576,7 +576,7 @@ void MuonAnalysisResultTableTab::populateLogsAndValues( ++logIt) { for (auto wsIt = m_logValues.constBegin(); wsIt != m_logValues.constEnd(); ++wsIt) { - auto wsLogValues = wsIt.value(); + const auto &wsLogValues = wsIt.value(); if (!wsLogValues.contains(*logIt)) { toRemove.insert(*logIt); break; diff --git a/qt/widgets/common/CMakeLists.txt b/qt/widgets/common/CMakeLists.txt index 0d2841470a66d1389c6767bf002c3d971558f06b..e04bb72b65606baf14e60ea2c83c91f341d1b262 100644 --- a/qt/widgets/common/CMakeLists.txt +++ b/qt/widgets/common/CMakeLists.txt @@ -5,6 +5,7 @@ src/AlgorithmRunner.cpp src/BatchAlgorithmRunner.cpp src/BoolPropertyWidget.cpp + src/DropEventHelper.cpp src/FileDialogHandler.cpp src/FilePropertyWidget.cpp src/GenericDialog.cpp @@ -261,7 +262,8 @@ set ( INC_FILES inc/MantidQtWidgets/Common/AlgorithmRunner.h inc/MantidQtWidgets/Common/BatchAlgorithmRunner.h inc/MantidQtWidgets/Common/DllOption.h - inc/MantidQtWidgets/Common/FileDialogHandler.h + inc/MantidQtWidgets/Common/DropEventHelper.h + inc/MantidQtWidgets/Common/FileDialogHandler.h inc/MantidQtWidgets/Common/FlowLayout.h inc/MantidQtWidgets/Common/GraphOptions.h inc/MantidQtWidgets/Common/DistributionOptions.h @@ -574,6 +576,11 @@ add_library ( MantidQtWidgetsCommon ${ALL_SRC} ${INC_FILES} ${UI_HDRS} ) set_target_properties ( MantidQtWidgetsCommon PROPERTIES COMPILE_DEFINITIONS IN_MANTIDQT_COMMON ) +# Add support for OSX system libraries if this is an OSX machine +if ( ${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + SET( APPLE_SYSTEM_LIBRARIES "-framework CoreFoundation") +endif() + if (OSX_VERSION VERSION_GREATER 10.8) set_target_properties ( MantidQtWidgetsCommon PROPERTIES INSTALL_RPATH "@loader_path/../MacOS;@loader_path/../Libraries") endif () @@ -581,6 +588,7 @@ endif () target_link_libraries ( MantidQtWidgetsCommon LINK_PRIVATE ${TCMALLOC_LIBRARIES_LINKTIME} ${CORE_MANTIDLIBS} ${QT_LIBRARIES} ${QWT_LIBRARIES} ${POCO_LIBRARIES} ${Boost_LIBRARIES} ${PYTHON_LIBRARIES} ${QSCINTILLA_LIBRARIES} + ${APPLE_SYSTEM_LIBRARIES} ) if(MAKE_VATES AND ParaView_FOUND) diff --git a/qt/widgets/common/inc/MantidQtWidgets/Common/DropEventHelper.h b/qt/widgets/common/inc/MantidQtWidgets/Common/DropEventHelper.h new file mode 100644 index 0000000000000000000000000000000000000000..52a66da6ce6d0eecc4bc828f7f1f16c8509e3308 --- /dev/null +++ b/qt/widgets/common/inc/MantidQtWidgets/Common/DropEventHelper.h @@ -0,0 +1,23 @@ +#ifndef MANTIDQT_MANTIDWIDGETS_DROPEVENTHELPER_H +#define MANTIDQT_MANTIDWIDGETS_DROPEVENTHELPER_H + +#include "MantidQtWidgets/Common/DllOption.h" + +#include <QDropEvent> +#include <vector> + +namespace MantidQt { +namespace MantidWidgets { + +namespace DropEventHelper { +/// Get all filenames from a QDropEvent +EXPORT_OPT_MANTIDQT_COMMON QStringList getFileNames(const QDropEvent *event); +/// Get all python files from q QDropEvent +EXPORT_OPT_MANTIDQT_COMMON QStringList +extractPythonFiles(const QDropEvent *event); +} + +} // namespace MantidWidgets +} // namespace MantidQt + +#endif diff --git a/qt/widgets/common/src/AlgorithmPropertiesWidget.cpp b/qt/widgets/common/src/AlgorithmPropertiesWidget.cpp index d3e1ed55b9804d30541ff7aca0b74bf79bb29e18..914e86c179c1c185a0ba4112997191006c3d8e08 100644 --- a/qt/widgets/common/src/AlgorithmPropertiesWidget.cpp +++ b/qt/widgets/common/src/AlgorithmPropertiesWidget.cpp @@ -378,7 +378,7 @@ void AlgorithmPropertiesWidget::hideOrDisableProperties() { for (auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end(); ++pitr) { PropertyWidget *widget = pitr.value(); Mantid::Kernel::Property *prop = widget->getProperty(); - QString propName = pitr.key(); + const QString &propName = pitr.key(); IPropertySettings *settings = prop->getSettings(); // Set the enabled and visible flags based on what the validators say. @@ -441,7 +441,7 @@ void AlgorithmPropertiesWidget::saveInput() { for (auto pitr = m_propWidgets.begin(); pitr != m_propWidgets.end(); ++pitr) { PropertyWidget *widget = pitr.value(); - QString propName = pitr.key(); + const QString &propName = pitr.key(); QString value = widget->getValue(); // Mantid::Kernel::Property *prop = widget->getProperty(); // if (!prop || prop->remember()) diff --git a/qt/widgets/common/src/DataProcessorUI/GenerateNotebook.cpp b/qt/widgets/common/src/DataProcessorUI/GenerateNotebook.cpp index 73b0e7dc4cba8e2df8f9a9cbf0ae4d0ba878f33d..eb64be227b5e3e7a66a02acf5f5c0e6bd7aabfd2 100644 --- a/qt/widgets/common/src/DataProcessorUI/GenerateNotebook.cpp +++ b/qt/widgets/common/src/DataProcessorUI/GenerateNotebook.cpp @@ -363,7 +363,7 @@ QString getReducedWorkspaceName(const RowData &data, const WhiteList &whitelist, // Do we want to use this column to generate the name of the output ws? if (whitelist.showValue(col)) { // Get what's in the column - const QString valueStr = data.at(col); + const QString &valueStr = data.at(col); if (!valueStr.isEmpty()) { // But we may have things like '1+2' which we want to replace with '1_2' auto value = valueStr.split(QRegExp("[+,]"), QString::SkipEmptyParts); @@ -433,13 +433,13 @@ reduceRowString(const RowData &data, const QString &instrument, // instructions // Get the runs - const QString runStr = data.at(col); + const QString &runStr = data.at(col); if (!runStr.isEmpty()) { // Some runs were given for pre-processing // The pre-processing alg - const PreprocessingAlgorithm preprocessor = preprocessMap.at(colName); + const PreprocessingAlgorithm &preprocessor = preprocessMap.at(colName); // The pre-processing options const QString options = preprocessingOptionsMap.count(colName) > 0 ? preprocessingOptionsMap.at(colName) @@ -457,7 +457,7 @@ reduceRowString(const RowData &data, const QString &instrument, // No pre-processing // Just read the property value from the table - const QString propStr = data.at(col); + const QString &propStr = data.at(col); if (!propStr.isEmpty()) { // If it was not empty, we used it as an input property to the reduction @@ -469,14 +469,14 @@ reduceRowString(const RowData &data, const QString &instrument, auto options = parseKeyValueString(processingOptions.toStdString()); - const auto hiddenOptionsStr = data.back(); + const auto &hiddenOptionsStr = data.back(); // Parse and set any user-specified options auto hiddenOptionsMap = parseKeyValueString(hiddenOptionsStr.toStdString()); // Options specified via 'Hidden Options' column will be preferred addProperties(algProperties, hiddenOptionsMap); // 'Options' specified either via 'Options' column or HintinLineEdit - const auto optionsStr = data.at(ncols - 2); + const auto &optionsStr = data.at(ncols - 2); // Parse and set any user-specified options auto optionsMap = parseKeyValueString(optionsStr.toStdString()); // Options specified via 'Options' column will be preferred diff --git a/qt/widgets/common/src/DataProcessorUI/GenericDataProcessorPresenter.cpp b/qt/widgets/common/src/DataProcessorUI/GenericDataProcessorPresenter.cpp index d1825339e25d2ac4200ed07e5a1ec1e59818578d..14cead56daccec3d114978c1287e6aa2314c77eb 100644 --- a/qt/widgets/common/src/DataProcessorUI/GenericDataProcessorPresenter.cpp +++ b/qt/widgets/common/src/DataProcessorUI/GenericDataProcessorPresenter.cpp @@ -762,7 +762,7 @@ GenericDataProcessorPresenter::getReducedWorkspaceName(const QStringList &data, if (m_whitelist.showValue(col)) { // Get what's in the column - auto const valueStr = data.at(col); + auto const &valueStr = data.at(col); // If it's not empty, use it if (!valueStr.isEmpty()) { @@ -983,7 +983,7 @@ void GenericDataProcessorPresenter::reduceRow(RowData *data) { runWS->getName()); } else { // No pre-processing needed - auto propertyValue = data->at(i); + const auto &propertyValue = data->at(i); if (!propertyValue.isEmpty()) alg->setPropertyValue(propertyName.toStdString(), propertyValue.toStdString()); diff --git a/qt/widgets/common/src/DisplayCurveFit.cpp b/qt/widgets/common/src/DisplayCurveFit.cpp index 812d24c13f586581300c6871f359d89e39a10194..91f23a00d5607eabe80a29948277f431699b54de 100644 --- a/qt/widgets/common/src/DisplayCurveFit.cpp +++ b/qt/widgets/common/src/DisplayCurveFit.cpp @@ -115,7 +115,7 @@ QPair<double, double> DisplayCurveFit::getCurveRange( void DisplayCurveFit::addSpectrum( const curveType &aType, const Mantid::API::MatrixWorkspace_sptr workspace, const size_t specIndex) { - const QString curveName{m_curveTypeToQString.at(aType)}; + const QString &curveName{m_curveTypeToQString.at(aType)}; const QColor curveColor(m_curveTypeToColor.at(aType)); m_plotPanel.at(aType) ->addSpectrum(curveName, workspace, specIndex, curveColor); @@ -149,7 +149,7 @@ bool DisplayCurveFit::hasCurve(const curveType &aType) { void DisplayCurveFit::addRangeSelector(const dcRange &adcRange, RangeSelector::SelectType aType) { if (m_rangeSelector.find(adcRange) == m_rangeSelector.end()) { - const QString dcRangeName(m_dcRangeToQString.at(adcRange)); + const QString &dcRangeName(m_dcRangeToQString.at(adcRange)); m_rangeSelector.emplace( adcRange, m_uiForm.fitPlot->addRangeSelector(dcRangeName, aType)); switch (adcRange) { diff --git a/qt/widgets/common/src/DropEventHelper.cpp b/qt/widgets/common/src/DropEventHelper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..5129e3261f8098f56a1f00b2aeb067ef0382871f --- /dev/null +++ b/qt/widgets/common/src/DropEventHelper.cpp @@ -0,0 +1,105 @@ + +#include "MantidQtWidgets/Common/DropEventHelper.h" + +#include <QStringList> +#include <QUrl> +#include <QFileInfo> + +// Compile on OSX only. +#if defined(__APPLE__) +#include <CoreFoundation/CoreFoundation.h> +#endif // defined(__APPLE__) + +using namespace MantidQt::MantidWidgets; + +/** Workaround for file path bug on OSX >=10.10 with Qt4 + * + * On Windows/Linux this simply returns the URL unchanged. + * + * For more information see this bug report: + * https://bugreports.qt.io/browse/QTBUG-40449 + * + * @param url :: the url to correct the path for + * @returns a valid url to a file path + */ +QUrl fixupURL(const QUrl &url) { +#if defined(__APPLE__) + QString localFileQString = url.toLocalFile(); + // Compile on OSX only. + if (localFileQString.startsWith("/.file/id=")) { + CFStringRef relCFStringRef = CFStringCreateWithCString( + kCFAllocatorDefault, localFileQString.toUtf8().constData(), + kCFStringEncodingUTF8); + CFURLRef relCFURL = CFURLCreateWithFileSystemPath( + kCFAllocatorDefault, relCFStringRef, kCFURLPOSIXPathStyle, + false // isDirectory + ); + CFErrorRef error = 0; + CFURLRef absCFURL = + CFURLCreateFilePathURL(kCFAllocatorDefault, relCFURL, &error); + if (!error) { + static const CFIndex maxAbsPathCStrBufLen = 4096; + char absPathCStr[maxAbsPathCStrBufLen]; + if (CFURLGetFileSystemRepresentation( + absCFURL, + true, // resolveAgainstBase + reinterpret_cast<UInt8 *>(&absPathCStr[0]), + maxAbsPathCStrBufLen)) { + localFileQString = QString(absPathCStr); + } + } + CFRelease(absCFURL); + CFRelease(relCFURL); + CFRelease(relCFStringRef); + } + return QUrl(localFileQString); +#else + return url; +#endif // defined(__APPLE__) +} + +/** Extract a list of file names from a drop event. + * + * This is a special OSX version because the OSX broke the way Qt decoded + * the file path in OSX 10.10. This is fixed in Qt5 but not backported to Qt4. + * + * @param event :: the event to extract file names from + * @return a list of file names as a QStringList + */ +QStringList DropEventHelper::getFileNames(const QDropEvent *event) { + QStringList filenames; + const auto mimeData = event->mimeData(); + if (mimeData->hasUrls()) { + const auto urlList = mimeData->urls(); + for (const auto &url : urlList) { + const auto fileUrl = fixupURL(url); + const auto fName = fileUrl.toLocalFile(); + if (fName.size() > 0) { + filenames.append(fName); + } + } + } + return filenames; +} + +/** Extract python file names from a drop event + * + * This will filter the list of file names extracted from a QDropEvent that + * end with the extension .py + * + * @param event :: the QDropEvent to filter filenames from + * @return a list of python file names + */ +QStringList DropEventHelper::extractPythonFiles(const QDropEvent *event) { + QStringList filenames; + + for (const auto &name : getFileNames(event)) { + QFileInfo fi(name); + + if (fi.suffix().toUpper() == "PY") { + filenames.append(name); + } + } + + return filenames; +} diff --git a/qt/widgets/common/src/FileDialogHandler.cpp b/qt/widgets/common/src/FileDialogHandler.cpp index b3ff0ebf42c3d43712ed0d786a37eb5c36569046..5c7f51f0b2cff664f4b2cf06154f16806a69febb 100644 --- a/qt/widgets/common/src/FileDialogHandler.cpp +++ b/qt/widgets/common/src/FileDialogHandler.cpp @@ -156,7 +156,7 @@ QString getCaption(const std::string &dialogName, // generate the dialog title auto dialogTitle = QString::fromStdString(dialogName); if (bool(prop)) { - const auto name = prop->name(); + const auto &name = prop->name(); if (name != "Filename" && prop->name() != "Directory" && prop->name() != "Dir") { dialogTitle.append(" - "); diff --git a/qt/widgets/common/src/FunctionBrowser.cpp b/qt/widgets/common/src/FunctionBrowser.cpp index 2f3a9edfd063da3cedc379ab9ec7a140ab682bc5..9cdf0a13470f930e288ca7d229ca185a2a788ed7 100644 --- a/qt/widgets/common/src/FunctionBrowser.cpp +++ b/qt/widgets/common/src/FunctionBrowser.cpp @@ -1551,7 +1551,7 @@ FunctionBrowser::getParameterProperty(const QString &funcIndex, */ void FunctionBrowser::updateParameters(const Mantid::API::IFunction &fun) { const auto paramNames = fun.getParameterNames(); - for (const auto parameter : paramNames) { + for (const auto ¶meter : paramNames) { const QString qName = QString::fromStdString(parameter); setParameter(qName, fun.getParameter(parameter)); const size_t index = fun.parameterIndex(parameter); diff --git a/qt/widgets/common/src/MWRunFiles.cpp b/qt/widgets/common/src/MWRunFiles.cpp index 384d3d04aa5885b694e736d3ae9785f06a2c0646..324ba1c02348428e2a7df205954ede577410db6c 100644 --- a/qt/widgets/common/src/MWRunFiles.cpp +++ b/qt/widgets/common/src/MWRunFiles.cpp @@ -1,4 +1,5 @@ #include "MantidQtWidgets/Common/MWRunFiles.h" +#include "MantidQtWidgets/Common/DropEventHelper.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/FacilityInfo.h" @@ -26,6 +27,7 @@ using namespace Mantid::Kernel; using namespace Mantid::API; using namespace MantidQt::API; +namespace DropEventHelper = MantidQt::MantidWidgets::DropEventHelper; //////////////////////////////////////////////////////////////////// // FindFilesThread @@ -1064,9 +1066,9 @@ void MWRunFiles::checkEntry() { */ void MWRunFiles::dropEvent(QDropEvent *de) { const QMimeData *mimeData = de->mimeData(); - if (mimeData->hasUrls()) { - auto url_list = mimeData->urls(); - m_uiForm.fileEditor->setText(url_list[0].toLocalFile()); + const auto filenames = DropEventHelper::getFileNames(de); + if (!filenames.empty()) { + m_uiForm.fileEditor->setText(filenames[0]); de->acceptProposedAction(); } else if (mimeData->hasText()) { QString text = mimeData->text(); diff --git a/qt/widgets/common/src/MantidTreeWidget.cpp b/qt/widgets/common/src/MantidTreeWidget.cpp index b7ea908799b7146bc8c5a0d9a032bfff6e703e3a..1da5d6c8a3bcd211097c4509a1f43a57c25cca6c 100644 --- a/qt/widgets/common/src/MantidTreeWidget.cpp +++ b/qt/widgets/common/src/MantidTreeWidget.cpp @@ -1,9 +1,9 @@ #include "MantidQtWidgets/Common/MantidTreeWidget.h" #include <MantidQtWidgets/Common/WorkspacePresenter/QWorkspaceDockView.h> -#include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/MatrixWorkspace.h" #include "MantidAPI/WorkspaceGroup.h" +#include "MantidQtWidgets/Common/DropEventHelper.h" #include "MantidQtWidgets/Common/MantidDisplayBase.h" #include <QApplication> @@ -56,17 +56,7 @@ void MantidTreeWidget::dragEnterEvent(QDragEnterEvent *de) { * @param de :: The drag drop event */ void MantidTreeWidget::dropEvent(QDropEvent *de) { - QStringList filenames; - const QMimeData *mimeData = de->mimeData(); - if (mimeData->hasUrls()) { - QList<QUrl> urlList = mimeData->urls(); - for (int i = 0; i < urlList.size(); ++i) { - QString fName = urlList[i].toLocalFile(); - if (fName.size() > 0) { - filenames.append(fName); - } - } - } + const auto filenames = DropEventHelper::getFileNames(de); de->acceptProposedAction(); for (int i = 0; i < filenames.size(); ++i) { diff --git a/qt/widgets/common/src/MantidWSIndexDialog.cpp b/qt/widgets/common/src/MantidWSIndexDialog.cpp index b79171e12acf4067735238ed926afc474ec4b614..b403700ab9bbd89e6d3240b62be9b10c987b9bf3 100644 --- a/qt/widgets/common/src/MantidWSIndexDialog.cpp +++ b/qt/widgets/common/src/MantidWSIndexDialog.cpp @@ -122,7 +122,7 @@ int MantidWSIndexWidget::getPlotIndex() const { if (!userInput.empty()) { const auto indexList = userInput.values(); if (!indexList.empty()) { - const auto spectrumIndexes = indexList.at(0); + const auto &spectrumIndexes = indexList.at(0); if (!spectrumIndexes.empty()) { spectrumIndex = *spectrumIndexes.begin(); } @@ -634,7 +634,7 @@ void MantidWSIndexWidget::populateLogComboBox() { // If this is a single-value numeric log, add it to the list of counts if (dynamic_cast<Mantid::Kernel::PropertyWithValue<int> *>(log) || dynamic_cast<Mantid::Kernel::PropertyWithValue<double> *>(log)) { - const std::string name = log->name(); + const std::string &name = log->name(); if (logCounts.find(name) != logCounts.end()) { logCounts[name]++; } else { @@ -1182,7 +1182,7 @@ void IntervalList::addIntervals(QString intervals) { } void IntervalList::addIntervalList(const IntervalList &intervals) { - const QList<Interval> list = intervals.getList(); + const QList<Interval> &list = intervals.getList(); QList<Interval>::const_iterator it = list.constBegin(); diff --git a/qt/widgets/common/src/MuonFitPropertyBrowser.cpp b/qt/widgets/common/src/MuonFitPropertyBrowser.cpp index b174368d41dd28be74be362a0ce7dbdb211c855e..d428ac98db1e776a6f70690ab253264e7cef112f 100644 --- a/qt/widgets/common/src/MuonFitPropertyBrowser.cpp +++ b/qt/widgets/common/src/MuonFitPropertyBrowser.cpp @@ -348,6 +348,12 @@ void MuonFitPropertyBrowser::setWorkspaceName(const QString &wsName) { * @param prop :: A pointer to the function name property */ void MuonFitPropertyBrowser::enumChanged(QtProperty *prop) { + if (m_workspaceNames.empty()) { + if (this->isVisible()) { + g_log.error("No Data available. Please load Some data."); + } + return; + } if (!m_changeSlotsEnabled) return; if (prop == m_groupsToFit) { @@ -1099,7 +1105,7 @@ void MuonFitPropertyBrowser::finishAfterSimultaneousFit( // Group output together std::string groupName = fitAlg->getPropertyValue("Output"); - std::string baseName = groupName; + const std::string &baseName = groupName; if (ads.doesExist(groupName)) { ads.deepRemoveGroup(groupName); } @@ -1262,7 +1268,7 @@ void MuonFitPropertyBrowser::setAvailableGroups(const QStringList &groups) { } clearGroupCheckboxes(); QSettings settings; - for (const auto group : groups) { + for (const auto &group : groups) { addGroupCheckbox(group); } } @@ -1336,7 +1342,7 @@ void MuonFitPropertyBrowser::setAllGroups() { clearChosenGroups(); for (auto iter = m_groupBoxes.constBegin(); iter != m_groupBoxes.constEnd(); ++iter) { - for (auto group : m_groupsList) { + for (const auto &group : m_groupsList) { if (iter.key().toStdString() == group) { m_boolManager->setValue(iter.value(), true); } @@ -1351,7 +1357,7 @@ void MuonFitPropertyBrowser::setAllPairs() { for (auto iter = m_groupBoxes.constBegin(); iter != m_groupBoxes.constEnd(); ++iter) { bool isItGroup = false; - for (auto group : m_groupsList) { + for (const auto &group : m_groupsList) { if (iter.key().toStdString() == group) { isItGroup = true; } @@ -1449,7 +1455,7 @@ void MuonFitPropertyBrowser::setAvailablePeriods(const QStringList &periods) { clearPeriodCheckboxes(); - for (const auto group : periods) { + for (const auto &group : periods) { addPeriodCheckbox(group); } } @@ -1524,10 +1530,9 @@ QStringList MuonFitPropertyBrowser::getChosenPeriods() const { void MuonFitPropertyBrowser::setChosenPeriods( const QStringList &chosenPeriods) { clearChosenPeriods(); - for (auto selected : chosenPeriods) { + for (const auto &selected : chosenPeriods) { for (auto iter = m_periodBoxes.constBegin(); iter != m_periodBoxes.constEnd(); ++iter) { - auto tmp = iter.key(); if (iter.key() == selected) { m_boolManager->setValue(iter.value(), true); } @@ -1542,7 +1547,6 @@ void MuonFitPropertyBrowser::setChosenPeriods(const QString &period) { clearChosenPeriods(); for (auto iter = m_periodBoxes.constBegin(); iter != m_periodBoxes.constEnd(); ++iter) { - auto tmp = iter.key(); if (iter.key() == period) { m_boolManager->setValue(iter.value(), true); } diff --git a/qt/widgets/common/src/PreviewPlot.cpp b/qt/widgets/common/src/PreviewPlot.cpp index 74575bac9d6c470ae8e17fefb64073eb690e46df..1d0b073d55bee6737224b8db482df1b227499f3b 100644 --- a/qt/widgets/common/src/PreviewPlot.cpp +++ b/qt/widgets/common/src/PreviewPlot.cpp @@ -839,7 +839,7 @@ void PreviewPlot::handleAxisTypeSelect() { // Hide range selectors on X axis when X axis scale is X^2 bool xIsSquared = xAxisType == "Squared"; for (auto it = m_rangeSelectors.begin(); it != m_rangeSelectors.end(); ++it) { - QString rsName = it.key(); + const QString &rsName = it.key(); RangeSelector *rs = it.value(); RangeSelector::SelectType type = rs->getType(); diff --git a/qt/widgets/common/src/QtPropertyBrowser/qtpropertybrowser.cpp b/qt/widgets/common/src/QtPropertyBrowser/qtpropertybrowser.cpp index 00c4ceb409ce260fb3447f47eeea3ad79a48104e..6dc16eaf598944a0ce67124f5f9d1015743d8e8a 100644 --- a/qt/widgets/common/src/QtPropertyBrowser/qtpropertybrowser.cpp +++ b/qt/widgets/common/src/QtPropertyBrowser/qtpropertybrowser.cpp @@ -1306,7 +1306,7 @@ void QtAbstractPropertyBrowserPrivate::createBrowserIndexes( if (it == m_propertyToIndexes.constEnd()) return; - QList<QtBrowserItem *> indexes = it.value(); + const QList<QtBrowserItem *> &indexes = it.value(); QListIterator<QtBrowserItem *> itIndex(indexes); while (itIndex.hasNext()) { QtBrowserItem *idx = itIndex.next(); @@ -1322,7 +1322,7 @@ void QtAbstractPropertyBrowserPrivate::createBrowserIndexes( if (it == m_propertyToIndexes.constEnd()) return; - QList<QtBrowserItem *> indexes = it.value(); + const QList<QtBrowserItem *> &indexes = it.value(); QListIterator<QtBrowserItem *> itIndex(indexes); while (itIndex.hasNext()) { QtBrowserItem *idx = itIndex.next(); @@ -1373,7 +1373,7 @@ void QtAbstractPropertyBrowserPrivate::removeBrowserIndexes( if (it == m_propertyToIndexes.constEnd()) return; - QList<QtBrowserItem *> indexes = it.value(); + const QList<QtBrowserItem *> &indexes = it.value(); QListIterator<QtBrowserItem *> itIndex(indexes); while (itIndex.hasNext()) { QtBrowserItem *idx = itIndex.next(); @@ -1462,7 +1462,7 @@ void QtAbstractPropertyBrowserPrivate::slotPropertyDataChanged( if (it == m_propertyToIndexes.constEnd()) return; - QList<QtBrowserItem *> indexes = it.value(); + const QList<QtBrowserItem *> &indexes = it.value(); QListIterator<QtBrowserItem *> itIndex(indexes); while (itIndex.hasNext()) { QtBrowserItem *idx = itIndex.next(); diff --git a/qt/widgets/common/src/QtPropertyBrowser/qtpropertymanager.cpp b/qt/widgets/common/src/QtPropertyBrowser/qtpropertymanager.cpp index 2d9020c46fc591a0ce0c09159b2e364259cd9d92..807314d4253a466994eb56746a317761e96d39f7 100644 --- a/qt/widgets/common/src/QtPropertyBrowser/qtpropertymanager.cpp +++ b/qt/widgets/common/src/QtPropertyBrowser/qtpropertymanager.cpp @@ -2448,7 +2448,7 @@ QString QtLocalePropertyManager::valueText(const QtProperty *property) const { if (it == d_ptr->m_values.constEnd()) return QString(); - QLocale loc = it.value(); + const QLocale &loc = it.value(); int langIdx = 0; int countryIdx = 0; diff --git a/qt/widgets/common/src/QwtHelper.cpp b/qt/widgets/common/src/QwtHelper.cpp index 6bcaf933357995f47f52acd918f2917c4d554bdc..5a0ddc89476984ba28841ec8ce2e1b368c087348 100644 --- a/qt/widgets/common/src/QwtHelper.cpp +++ b/qt/widgets/common/src/QwtHelper.cpp @@ -22,7 +22,7 @@ boost::shared_ptr<QwtData> curveDataFromWs(MatrixWorkspace_const_sptr ws, size_t wsIndex) { const double *x = &ws->x(wsIndex)[0]; const double *y = &ws->y(wsIndex)[0]; - size_t size = ws->blocksize(); + size_t size = ws->y(wsIndex).size(); return boost::make_shared<QwtArrayData>(x, y, size); } diff --git a/qt/widgets/common/src/RepoModel.cpp b/qt/widgets/common/src/RepoModel.cpp index 005eaa24b753f6a8dd61704922194b6e7c3cd0e7..2ddd13066cd69b4cc47ddf468f54457786d91848 100644 --- a/qt/widgets/common/src/RepoModel.cpp +++ b/qt/widgets/common/src/RepoModel.cpp @@ -214,7 +214,7 @@ QVariant RepoModel::data(const QModelIndex &index, int role) const { return QVariant(); RepoItem *item = static_cast<RepoItem *>(index.internalPointer()); try { - QString path = item->path(); + const QString &path = item->path(); Mantid::API::ScriptInfo inf; Mantid::API::SCRIPTSTATUS status; // return the data for the display role diff --git a/qt/widgets/common/src/SignalRange.cpp b/qt/widgets/common/src/SignalRange.cpp index 1bd3d2de143e55c6517281d2727efcbcf1e31582..f3f73baa8741294eae7dc7553e029e838767d739 100644 --- a/qt/widgets/common/src/SignalRange.cpp +++ b/qt/widgets/common/src/SignalRange.cpp @@ -71,8 +71,7 @@ QwtDoubleInterval SignalRange::getRange( PRAGMA_OMP( parallel for schedule(dynamic, 1)) for (int i = 0; i < int(iterators.size()); i++) { Mantid::API::IMDIterator *it = iterators[i]; - QwtDoubleInterval range = this->getRange(it); - intervals[i] = range; + intervals[i] = this->getRange(it); // don't delete iterator in parallel. MSVC doesn't like it // when the iterator points to a mock object. } @@ -87,14 +86,12 @@ QwtDoubleInterval SignalRange::getRange( signal = intervals[i].minValue(); if (!std::isfinite(signal)) continue; - if (signal < minSignal) - minSignal = signal; + minSignal = std::min(signal, minSignal); signal = intervals[i].maxValue(); if (!std::isfinite(signal)) continue; - if (signal > maxSignal) - maxSignal = signal; + maxSignal = std::max(signal, maxSignal); } if (minSignal == DBL_MAX) { @@ -118,10 +115,9 @@ QwtDoubleInterval SignalRange::getRange( * @return the min/max range, or INFINITY if not found */ QwtDoubleInterval SignalRange::getRange(Mantid::API::IMDIterator *it) { - if (!it) - return QwtDoubleInterval(0., 1.0); - if (!it->valid()) + if ((it == nullptr) || (!it->valid())) return QwtDoubleInterval(0., 1.0); + // Use the current normalization it->setNormalization(m_normalization); diff --git a/qt/widgets/common/src/WorkspacePresenter/QWorkspaceDockView.cpp b/qt/widgets/common/src/WorkspacePresenter/QWorkspaceDockView.cpp index d3d77cc276053010ced08123b39054ea753afe67..92284177af4665501647c76e59ada63509b8fb3b 100644 --- a/qt/widgets/common/src/WorkspacePresenter/QWorkspaceDockView.cpp +++ b/qt/widgets/common/src/WorkspacePresenter/QWorkspaceDockView.cpp @@ -915,9 +915,21 @@ void QWorkspaceDockView::addMatrixWorkspaceMenuItems( menu->addAction(m_plotAdvanced); // Don't plot a spectrum if only one X value - m_plotSpec->setEnabled(matrixWS->blocksize() > 1); - m_plotSpecErr->setEnabled(matrixWS->blocksize() > 1); - m_plotAdvanced->setEnabled(matrixWS->blocksize() > 1); + bool multipleBins = false; + try { + multipleBins = (matrixWS->blocksize() > 1); + } catch (...) { + const size_t numHist = matrixWS->getNumberHistograms(); + for (size_t i = 0; i < numHist; ++i) { + if (matrixWS->y(i).size() > 1) { + multipleBins = true; + break; + } + } + } + m_plotSpec->setEnabled(multipleBins); + m_plotSpecErr->setEnabled(multipleBins); + m_plotAdvanced->setEnabled(multipleBins); menu->addAction(m_showSpectrumViewer); // The 2D spectrum viewer diff --git a/qt/widgets/instrumentview/src/InstrumentWidgetTreeTab.cpp b/qt/widgets/instrumentview/src/InstrumentWidgetTreeTab.cpp index f4f7b63401c3b90ef8659936b3397edded26047f..c703547ff0b7fa8a98c4bf2a988528b88fb2f079 100644 --- a/qt/widgets/instrumentview/src/InstrumentWidgetTreeTab.cpp +++ b/qt/widgets/instrumentview/src/InstrumentWidgetTreeTab.cpp @@ -107,7 +107,7 @@ std::string InstrumentWidgetTreeTab::saveToProject() const { auto names = m_instrumentTree->findExpandedComponents(); tab.writeLine("ExpandedItems"); - for (auto name : names) { + for (const auto &name : names) { tab << name; } diff --git a/qt/widgets/instrumentview/src/OneCurvePlot.cpp b/qt/widgets/instrumentview/src/OneCurvePlot.cpp index ff30ed95fbbd9ae9c8acaf67536faa3a749a4842..0d1aa09304ff03d848c34c97d3efb8bab376e3bf 100644 --- a/qt/widgets/instrumentview/src/OneCurvePlot.cpp +++ b/qt/widgets/instrumentview/src/OneCurvePlot.cpp @@ -23,7 +23,7 @@ namespace MantidWidgets { OneCurvePlot::OneCurvePlot(QWidget *parent) : QwtPlot(parent), m_curve(nullptr), m_xUnits("") { - QFont font = parent->font(); + const QFont &font = parent->font(); setAxisFont(QwtPlot::xBottom, font); setAxisFont(QwtPlot::yLeft, font); QwtText dummyText; diff --git a/qt/widgets/instrumentview/src/Shape2DCollection.cpp b/qt/widgets/instrumentview/src/Shape2DCollection.cpp index 8fd19f515b5f0bcb7585ba770fa7123f40312d71..9221f4d52d23b6fc16205f5cb98532418777b1cb 100644 --- a/qt/widgets/instrumentview/src/Shape2DCollection.cpp +++ b/qt/widgets/instrumentview/src/Shape2DCollection.cpp @@ -741,7 +741,7 @@ void Shape2DCollection::eraseFree(const QPolygonF &polygon) { */ void Shape2DCollection::loadFromProject(const std::string &lines) { API::TSVSerialiser tsv(lines); - for (auto shapeLines : tsv.sections("shape")) { + for (const auto &shapeLines : tsv.sections("shape")) { Shape2D *shape = Shape2D::loadFromProject(shapeLines); m_shapes.push_back(shape); emit shapeCreated(); diff --git a/qt/widgets/plugins/algorithm_dialogs/src/FitDialog.cpp b/qt/widgets/plugins/algorithm_dialogs/src/FitDialog.cpp index 6a750fe059d1263ac58fc9e254c46b01e01ccf78..57174fe4381a67d3b26f4b6778655031d67d7eaa 100644 --- a/qt/widgets/plugins/algorithm_dialogs/src/FitDialog.cpp +++ b/qt/widgets/plugins/algorithm_dialogs/src/FitDialog.cpp @@ -216,8 +216,8 @@ MWPropertiesWidget::MWPropertiesWidget(InputWorkspaceWidget *parent) if (ws) { m_workspaceIndex->setRange(0, static_cast<int>(ws->getNumberHistograms())); - if (ws->blocksize() > 0) { - const Mantid::MantidVec &x = ws->readX(0); + const Mantid::MantidVec &x = ws->readX(0); + if (!x.empty()) { m_startX->setText(QString::number(x.front())); m_endX->setText(QString::number(x.back())); } diff --git a/qt/widgets/sliceviewer/inc/MantidQtWidgets/SliceViewer/SliceViewer.h b/qt/widgets/sliceviewer/inc/MantidQtWidgets/SliceViewer/SliceViewer.h index 03024095d57d41342ca061d095363cb672b06325..857354641c78022a44be0f9a72017566a5bf4015 100644 --- a/qt/widgets/sliceviewer/inc/MantidQtWidgets/SliceViewer/SliceViewer.h +++ b/qt/widgets/sliceviewer/inc/MantidQtWidgets/SliceViewer/SliceViewer.h @@ -424,6 +424,8 @@ private: AspectRatioType m_lastRatioState; QwtScaleDrawNonOrthogonal *m_nonOrthAxis0; QwtScaleDrawNonOrthogonal *m_nonOrthAxis1; + + bool m_holdDisplayUpdates; }; } // namespace SliceViewer diff --git a/qt/widgets/sliceviewer/src/PeakViewFactory.cpp b/qt/widgets/sliceviewer/src/PeakViewFactory.cpp index 96c37c93d7e9cce8e9a906a627d03c4efb2cf574..95f76b939ee155ce2e1b3cc8d02bc6f992b82ee1 100644 --- a/qt/widgets/sliceviewer/src/PeakViewFactory.cpp +++ b/qt/widgets/sliceviewer/src/PeakViewFactory.cpp @@ -168,9 +168,11 @@ PeakRepresentation_sptr PeakViewFactory::createPeakRepresentationEllipsoid( dynamic_cast<const Mantid::DataObjects::PeakShapeEllipsoid &>(shape); // Ellipsoidd paramters - const auto abcRadii = ellipsoidShape.abcRadii(); - const auto abcRadiiBackgroundInner = ellipsoidShape.abcRadiiBackgroundInner(); - const auto abcRadiiBackgroundOuter = ellipsoidShape.abcRadiiBackgroundOuter(); + const auto &abcRadii = ellipsoidShape.abcRadii(); + const auto &abcRadiiBackgroundInner = + ellipsoidShape.abcRadiiBackgroundInner(); + const auto &abcRadiiBackgroundOuter = + ellipsoidShape.abcRadiiBackgroundOuter(); // Extract directions for the displayed frame const auto dimension0 = m_mdWS->getDimension(0); diff --git a/qt/widgets/sliceviewer/src/PeaksViewer.cpp b/qt/widgets/sliceviewer/src/PeaksViewer.cpp index 6e96e5872d051604d3448ec5a25557ee94b7ac14..22d539db6aa555082eb92326fc6c40e446ed2c51 100644 --- a/qt/widgets/sliceviewer/src/PeaksViewer.cpp +++ b/qt/widgets/sliceviewer/src/PeaksViewer.cpp @@ -197,7 +197,7 @@ void PeaksViewer::loadFromProject(const std::string &lines) { return; // load presented workspaces - for (auto section : tsv.sections("peaksworkspace")) + for (const auto §ion : tsv.sections("peaksworkspace")) loadPresentedWorkspace(section); // Apply zooming/peak selection @@ -280,7 +280,7 @@ std::string PeaksViewer::saveToProject() const { // save all workspaces auto workspaces = m_presenter->presentedWorkspaces(); - for (auto ws : workspaces) + for (const auto &ws : workspaces) tsv.writeSection("peaksworkspace", savePresentedWorkspace(ws)); // save zoom a particular peak diff --git a/qt/widgets/sliceviewer/src/SliceViewer.cpp b/qt/widgets/sliceviewer/src/SliceViewer.cpp index ee8c1fa0eeb7e26352247d5cac9281476caf19b7..880e3e869981585df9ab2d36a234555d9e1b42ab 100644 --- a/qt/widgets/sliceviewer/src/SliceViewer.cpp +++ b/qt/widgets/sliceviewer/src/SliceViewer.cpp @@ -87,7 +87,8 @@ SliceViewer::SliceViewer(QWidget *parent) m_peaksPresenter(boost::make_shared<CompositePeaksPresenter>(this)), m_proxyPeaksPresenter( boost::make_shared<ProxyCompositePeaksPresenter>(m_peaksPresenter)), - m_peaksSliderWidget(nullptr), m_lastRatioState(Guess) { + m_peaksSliderWidget(nullptr), m_lastRatioState(Guess), + m_holdDisplayUpdates(false) { ui.setupUi(this); std::string enableNonOrthogonal; @@ -155,6 +156,16 @@ SliceViewer::SliceViewer(QWidget *parent) QObject::connect(m_algoRunner, SIGNAL(algorithmComplete(bool)), this, SLOT(dynamicRebinComplete(bool))); + // disconnect and reconnect here + QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this, + SLOT(checkForHKLDimension())); + QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this, + SLOT(switchAxis())); + QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this, + SLOT(switchQWTRaster(bool))); + QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this, + SLOT(setNonOrthogonalbtn())); + initMenus(); loadSettings(); @@ -727,18 +738,16 @@ void SliceViewer::switchQWTRaster(bool useNonOrthogonal) { * @param ws :: IMDWorkspace to show. */ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) { + struct ScopedFlag { + explicit ScopedFlag(bool &b) : m_flag(b) { m_flag = true; } + ~ScopedFlag() { m_flag = false; } + bool &value() { return m_flag; } + bool &m_flag; + }; + ScopedFlag holdDisplayUpdates(m_holdDisplayUpdates); m_ws = ws; m_coordinateTransform = createCoordinateTransform(*ws, m_dimX, m_dimY); - // disconnect and reconnect here - QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this, - SLOT(checkForHKLDimension())); - QObject::connect(this, SIGNAL(changedShownDim(size_t, size_t)), this, - SLOT(switchAxis())); - QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this, - SLOT(switchQWTRaster(bool))); - QObject::connect(ui.btnNonOrthogonalToggle, SIGNAL(toggled(bool)), this, - SLOT(setNonOrthogonalbtn())); m_firstNonOrthogonalWorkspaceOpen = true; m_data->setWorkspace(ws); m_plot->setWorkspace(ws); @@ -830,11 +839,8 @@ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) { } // Initial display update - this->updateDisplay( - !m_firstWorkspaceOpen /*Force resetting the axes, the first time*/); - - // Don't reset axes next time - m_firstWorkspaceOpen = true; + // this->updateDisplay( + // !m_firstWorkspaceOpen /*Force resetting the axes, the first time*/); // For showing the original coordinates ui.frmMouseInfo->setVisible(false); @@ -855,6 +861,13 @@ void SliceViewer::setWorkspace(Mantid::API::IMDWorkspace_sptr ws) { // Send out a signal emit changedShownDim(m_dimX, m_dimY); m_canSwitchScales = true; + + holdDisplayUpdates.value() = false; + this->updateDisplay( + !m_firstWorkspaceOpen /*Force resetting the axes, the first time*/); + + // Don't reset axes next time + m_firstWorkspaceOpen = true; } //------------------------------------------------------------------------------ @@ -1597,7 +1610,7 @@ void SliceViewer::showInfoAt(double x, double y) { //------------------------------------------------------------------------------ /** Update the 2D plot using all the current controls settings */ void SliceViewer::updateDisplay(bool resetAxes) { - if (!m_ws) + if (!m_ws || m_holdDisplayUpdates) return; size_t oldX = m_dimX; size_t oldY = m_dimY; @@ -1714,7 +1727,6 @@ void SliceViewer::changedShownDim(int index, int dim, int oldDim) { } void SliceViewer::checkForHKLDimension() { - if (API::requiresSkewMatrix(*m_ws)) { m_coordinateTransform->checkDimensionsForHKL(*m_ws, m_dimX, m_dimY); auto isHKL = API::isHKLDimensions(*m_ws, m_dimX, m_dimY); @@ -1732,7 +1744,8 @@ void SliceViewer::checkForHKLDimension() { switchQWTRaster(useNonOrthogonal); } } - emit setNonOrthogonalbtn(); + + setNonOrthogonalbtn(); } //============================================================================== //================================ PYTHON METHODS ============================== @@ -2431,7 +2444,7 @@ void SliceViewer::setNonOrthogonalbtn() { }; // temporary to disable if peak overlay is on - emit disableOrthogonalAnalysisTools(ui.btnNonOrthogonalToggle->isChecked()); + disableOrthogonalAnalysisTools(ui.btnNonOrthogonalToggle->isChecked()); } void SliceViewer::disableOrthogonalAnalysisTools(bool checked) { @@ -2881,7 +2894,7 @@ void SliceViewer::loadFromProject(const std::string &lines) { API::TSVSerialiser peaks(peaksViewerLines); QStringList names; - for (auto section : peaks.sections("peaksworkspace")) { + for (const auto §ion : peaks.sections("peaksworkspace")) { API::TSVSerialiser sec(section); QString name; @@ -2975,6 +2988,7 @@ std::string SliceViewer::saveDimensionWidgets() const { } void SliceViewer::switchAxis() { + if (m_canSwitchScales) { // cannot be called when sliceviewer first // initialised because axis is inaccurate auto isHKL = API::isHKLDimensions(*m_ws, m_dimX, m_dimY); diff --git a/qt/widgets/spectrumviewer/src/SpectrumView.cpp b/qt/widgets/spectrumviewer/src/SpectrumView.cpp index 875e049c2303bbf62c11148f13747a802e1692ed..85a2bc01625a6c87b0a6c676135c44b555945644 100644 --- a/qt/widgets/spectrumviewer/src/SpectrumView.cpp +++ b/qt/widgets/spectrumviewer/src/SpectrumView.cpp @@ -367,7 +367,7 @@ std::string SpectrumView::saveToProject(ApplicationWindow *app) { spec.writeLine("ColorMapFileName") << colorMapFileName; spec.writeLine("Workspaces"); - for (auto source : m_dataSource) { + for (const auto &source : m_dataSource) { spec << source->getWorkspace()->getName(); } @@ -396,7 +396,7 @@ std::string SpectrumView::getWindowName() { std::vector<std::string> SpectrumView::getWorkspaceNames() { std::vector<std::string> names; - for (auto source : m_dataSource) { + for (const auto &source : m_dataSource) { names.push_back(source->getWorkspace()->getName()); } return names; 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 3228af7aea85573cd5baea266701c0b222bb5061..01710488dd98aecc1ddb2cab764aa8ba27a7ad9e 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 @@ -35,7 +35,7 @@ class AbsoluteUnitsScript(BaseScriptElement): self.reset() def set_default_pars(self, inst_name): - from Interface.reduction_gui.reduction.inelastic import dgs_utils + from . import dgs_utils ip = dgs_utils.InstrumentParameters(inst_name) AbsoluteUnitsScript.emin = ip.get_parameter("monovan-integr-min") AbsoluteUnitsScript.emax = ip.get_parameter("monovan-integr-max") 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 3bd0e35394f30ed946ed09f0e715ac1504a7903f..699ab5dccc447d965dba771f2662ca7af161631d 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 @@ -37,7 +37,7 @@ class DataCorrectionsScript(BaseScriptElement): self.reset() def set_default_pars(self, inst_name): - from Interface.reduction_gui.reduction.inelastic import dgs_utils + from . import dgs_utils ip = dgs_utils.InstrumentParameters(inst_name) DataCorrectionsScript.monitor_int_low = int(ip.get_parameter("norm-mon1-min")) DataCorrectionsScript.monitor_int_high = int(ip.get_parameter("norm-mon1-max")) 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 a19a8a503bd2a974598f756dc9f36fffeab7d1bc..6d5ac8a647ff3cf9b2a4b0eb22635e014634efaa 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 @@ -38,7 +38,7 @@ class DiagnoseDetectorsScript(BaseScriptElement): self.reset() def set_default_pars(self, inst_name): - from Interface.reduction_gui.reduction.inelastic import dgs_utils + from . import dgs_utils ip = dgs_utils.InstrumentParameters(inst_name) DiagnoseDetectorsScript.high_counts = ip.get_parameter("diag_huge") DiagnoseDetectorsScript.low_counts = ip.get_parameter("diag_tiny") 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 3f9843b91779432e1053e5039293954d656c229b..929f774e6152dfd80797957324ca4cdfd343f53e 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 @@ -39,7 +39,7 @@ class SampleSetupScript(BaseScriptElement): self.reset() def set_default_pars(self, inst_name): - from Interface.reduction_gui.reduction.inelastic import dgs_utils + from . import dgs_utils ip = dgs_utils.InstrumentParameters(inst_name) SampleSetupScript.monitor1_specid = str(int(ip.get_parameter("ei-mon1-spec"))) SampleSetupScript.monitor2_specid = str(int(ip.get_parameter("ei-mon2-spec"))) diff --git a/scripts/Interface/ui/sans_isis/masking_table.py b/scripts/Interface/ui/sans_isis/masking_table.py index c2e86bfcaab18da63deca8a5ec4d9321c8740ed6..99890ac44ea6b633ff965707a25b105e106d2b12 100644 --- a/scripts/Interface/ui/sans_isis/masking_table.py +++ b/scripts/Interface/ui/sans_isis/masking_table.py @@ -56,7 +56,7 @@ class MaskingTable(QtGui.QWidget, ui_masking_table.Ui_MaskingTable): self._call_masking_tab_listeners(lambda listener: listener.on_row_changed()) def on_update_rows(self): - self._call_masking_tab_listeners(lambda listener: listener.update_rows()) + self._call_masking_tab_listeners(lambda listener: listener.on_update_rows()) def on_display(self): self._call_masking_tab_listeners(lambda listener: listener.on_display()) @@ -64,6 +64,7 @@ class MaskingTable(QtGui.QWidget, ui_masking_table.Ui_MaskingTable): def connect_signals(self): self.select_row_combo_box.currentIndexChanged.connect(self.on_row_changed) self.display_mask_push_button.clicked.connect(self.on_display) + self.select_row_push_button.clicked.connect(self.on_update_rows) # ------------------------------------------------------------------------------------------------------------------ # Actions diff --git a/scripts/Interface/ui/sans_isis/sans_data_processor_gui.py b/scripts/Interface/ui/sans_isis/sans_data_processor_gui.py index 2101bbb7dd61fc2380e6ff432b34867a5818420c..3515262d96507ed11929517ee49e3188cfb2e6a1 100644 --- a/scripts/Interface/ui/sans_isis/sans_data_processor_gui.py +++ b/scripts/Interface/ui/sans_isis/sans_data_processor_gui.py @@ -13,6 +13,7 @@ from PyQt4 import QtGui, QtCore from mantid.kernel import (Logger, config) from mantidqtpython import MantidQt + try: from mantidplot import * canMantidPlot = True @@ -22,7 +23,7 @@ except ImportError: from . import ui_sans_data_processor_window as ui_sans_data_processor_window from sans.common.enums import (ReductionDimensionality, OutputMode, SaveType, SANSInstrument, RangeStepType, SampleShape, ReductionMode, FitType) -from sans.gui_logic.gui_common import (get_reduction_mode_from_gui_selection, +from sans.gui_logic.gui_common import (get_reduction_mode_from_gui_selection, get_reduction_mode_strings_for_gui, get_string_for_gui_from_reduction_mode, GENERIC_SETTINGS, load_file) @@ -236,6 +237,9 @@ class SANSDataProcessorGui(QtGui.QMainWindow, ui_sans_data_processor_window.Ui_S instrument_name = SANSInstrument.to_string(self._instrument) self.data_processor_table.setInstrumentList(SANSDataProcessorGui.INSTRUMENTS, instrument_name) + if instrument_name: + self._set_mantid_instrument(instrument_name) + # The widget will emit a 'runAsPythonScript' signal to run python code self.data_processor_table.runAsPythonScript.connect(self._run_python_code) self.data_processor_table.processButtonClicked.connect(self._processed_clicked) @@ -287,9 +291,16 @@ class SANSDataProcessorGui(QtGui.QMainWindow, ui_sans_data_processor_window.Ui_S config.setString("default.instrument", instrument_string) def _handle_instrument_change(self): + # Set instrument as the default instrument instrument_string = str(self.data_processor_table.getCurrentInstrument()) self._set_mantid_instrument(instrument_string) + # Set the reduction mode + if instrument_string: + self._instrument = SANSInstrument.from_string(instrument_string) + reduction_mode_list = get_reduction_mode_strings_for_gui(self._instrument) + self.set_reduction_modes(reduction_mode_list) + def get_user_file_path(self): return str(self.user_file_line_edit.text()) @@ -459,8 +470,8 @@ class SANSDataProcessorGui(QtGui.QMainWindow, ui_sans_data_processor_window.Ui_S return str(self.mask_file_input_line_edit.text()) def _on_load_mask_file(self): - self._load_file(self.mask_file_input_line_edit, "*.*", self.__generic_settings, - self.__mask_file_input_path_key, self.get_mask_file) + load_file(self.mask_file_input_line_edit, "*.*", self.__generic_settings, + self.__mask_file_input_path_key, self.get_mask_file) def _on_mask_file_add(self): self._call_settings_listeners(lambda listener: listener.on_mask_file_add()) @@ -468,10 +479,6 @@ class SANSDataProcessorGui(QtGui.QMainWindow, ui_sans_data_processor_window.Ui_S # ------------------------------------------------------------------------------------------------------------------ # Elements which can be set and read by the model # ------------------------------------------------------------------------------------------------------------------ - def handle_instrument_change(self): - # TODO need to read it and set it as the default instrument - pass - def set_instrument_settings(self, instrument): if instrument: self._instrument = instrument @@ -642,8 +649,12 @@ class SANSDataProcessorGui(QtGui.QMainWindow, ui_sans_data_processor_window.Ui_S def reduction_mode(self, value): # There are two types of values that can be passed: # String: we look for string and we set it - # Convert the value to the correct GUI string + + # Set the correct selection of reduction modes which are available + reduction_mode_list = get_reduction_mode_strings_for_gui(self._instrument) + self.set_reduction_modes(reduction_mode_list) + reduction_mode_as_string = get_string_for_gui_from_reduction_mode(value, self._instrument) if reduction_mode_as_string: index = self.reduction_mode_combo_box.findText(reduction_mode_as_string) diff --git a/scripts/Interface/ui/sans_isis/sans_data_processor_window.ui b/scripts/Interface/ui/sans_isis/sans_data_processor_window.ui index a27f5fa92952885005787fbdd2ab0fe42e4cb50f..77b9c66a6bb271ea4426b5cc864a387a3aefe53a 100644 --- a/scripts/Interface/ui/sans_isis/sans_data_processor_window.ui +++ b/scripts/Interface/ui/sans_isis/sans_data_processor_window.ui @@ -64,7 +64,7 @@ QGroupBox::title { <item> <widget class="QStackedWidget" name="main_stacked_widget"> <property name="currentIndex"> - <number>1</number> + <number>0</number> </property> <widget class="QWidget" name="run_page"> <layout class="QVBoxLayout" name="verticalLayout_3"> @@ -339,7 +339,7 @@ QGroupBox::title { <item> <widget class="QTabWidget" name="settings_tab_widget"> <property name="currentIndex"> - <number>2</number> + <number>0</number> </property> <widget class="QWidget" name="general_tab"> <attribute name="title"> @@ -1873,7 +1873,7 @@ QGroupBox::title { <x>0</x> <y>0</y> <width>1211</width> - <height>22</height> + <height>19</height> </rect> </property> <widget class="QMenu" name="menuEdit"> diff --git a/scripts/SANS/ISISCommandInterface.py b/scripts/SANS/ISISCommandInterface.py index d2b27b10ea938ad1516783a1add52508af4f05b2..ed12dda94916fb057de2ad93d5f72344404f1cc0 100644 --- a/scripts/SANS/ISISCommandInterface.py +++ b/scripts/SANS/ISISCommandInterface.py @@ -371,7 +371,7 @@ def GetMismatchedDetList(): # pylint: disable = too-many-branches -def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_suffix=None, combineDet=None, +def WavRangeReduction(wav_start=None, wav_end=None, full_trans_wav=None, name_suffix=None, combineDet=None, # noqa: C901 resetSetup=True, out_fit_settings=dict()): """ Run reduction from loading the raw data to calculating Q. Its optional arguments allows specifics diff --git a/scripts/SANS/SANSBatchMode.py b/scripts/SANS/SANSBatchMode.py index 533a1a271fa929fe2041c94610ca1400129691ed..3bc9e9a3028c28f5ec3e23908860a704084688a8 100644 --- a/scripts/SANS/SANSBatchMode.py +++ b/scripts/SANS/SANSBatchMode.py @@ -178,7 +178,7 @@ def get_geometry_properties(reducer): return geometry_properties -def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'},verbose=False, +def BatchReduce(filename, format, plotresults=False, saveAlgs={'SaveRKH':'txt'},verbose=False, # noqa: C901 centreit=False, reducer=None, combineDet=None, save_as_zero_error_free=False): """ @param filename: the CSV file with the list of runs to analyse diff --git a/scripts/SANS/SANSUtility.py b/scripts/SANS/SANSUtility.py index 9610badf0c38bbd2316c9587821a564239c7bf3d..56e04e1d04fbc6d05d915bc61bd48d70713ea016 100644 --- a/scripts/SANS/SANSUtility.py +++ b/scripts/SANS/SANSUtility.py @@ -365,7 +365,7 @@ def slice2histogram(ws_event, time_start, time_stop, monitor, binning=""): return hist, (tot_t, tot_c, part_t, part_c) -def sliceParser(str_to_parser): +def sliceParser(str_to_parser): # noqa: C901 """ Create a list of boundaries from a string defing the slices. Valid syntax is: diff --git a/scripts/SANS/SANSadd2.py b/scripts/SANS/SANSadd2.py index ac1bfe588c7b01c530d2fd55ccd9122dd3f73dc9..692c0b3b179939930edead428a2c31745dd229ac 100644 --- a/scripts/SANS/SANSadd2.py +++ b/scripts/SANS/SANSadd2.py @@ -18,7 +18,7 @@ ADD_FILES_NEW_TEMPORARY = "AddFilesNewTempory" ADD_FILES_NEW_TEMPORARY_MONITORS = "AddFilesNewTempory_monitors" -def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, +def add_runs(runs, inst='sans2d', defType='.nxs', rawTypes=('.raw', '.s*', 'add','.RAW'), lowMem=False, # noqa: C901 binning='Monitors', saveAsEvent=False, isOverlay = False, time_shifts=None): if inst.upper() == "SANS2DTUBES": inst = "SANS2D" diff --git a/scripts/SANS/isis_reduction_steps.py b/scripts/SANS/isis_reduction_steps.py index 65d072ea271150f764986032f9d09d374a3325dd..5f75bdb166e5a5cabe9ebdeb80db0bc8edcfbbfa 100644 --- a/scripts/SANS/isis_reduction_steps.py +++ b/scripts/SANS/isis_reduction_steps.py @@ -710,7 +710,7 @@ class Mask_ISIS(ReductionStep): return bank - def parse_instruction(self, instName, details): + def parse_instruction(self, instName, details): # noqa: C901 """ Parse an instruction line from an ISIS mask file @param instName Instrument name. Used for MASK Ssp command to tell what bank it refer to @@ -3270,7 +3270,7 @@ class UserFile(ReductionStep): self.executed = True return self.executed - def read_line(self, line, reducer): + def read_line(self, line, reducer): # noqa: C901 # This is so that I can be sure all EOL characters have been removed line = line.lstrip().rstrip() upper_line = line.upper() @@ -3443,7 +3443,7 @@ class UserFile(ReductionStep): reducer._corr_and_scale.rescale = 100.0 # Read a limit line of a mask file - def readLimitValues(self, limit_line, reducer): + def readLimitValues(self, limit_line, reducer): # noqa: C901 limits = limit_line.split('L/') if len(limits) != 2: _issueWarning("Incorrectly formatted limit line ignored \"" + limit_line + "\"") @@ -3541,7 +3541,7 @@ class UserFile(ReductionStep): else: _issueWarning('Error in user file after L/, "%s" is not a valid limit line' % limit_type.upper()) - def _read_mon_line(self, details, reducer): + def _read_mon_line(self, details, reducer): # noqa: C901 # MON/LENTH, MON/SPECTRUM and MON/TRANS all accept the INTERPOLATE option interpolate = False diff --git a/scripts/SANS/sans/algorithm_detail/mask_functions.py b/scripts/SANS/sans/algorithm_detail/mask_functions.py index 3c40b920c99aa0bd5387637c2e9b02cb90606618..025c1280e4e9f83cffa4b09f086476dfd77982ef 100644 --- a/scripts/SANS/sans/algorithm_detail/mask_functions.py +++ b/scripts/SANS/sans/algorithm_detail/mask_functions.py @@ -49,9 +49,9 @@ def get_geometry_information(ipf_path, detector_type): number_of_pixels_override=number_of_pixels_override) # Determine the prefix for the detector - if detector_type is DetectorType.HAB: + if detector_type is DetectorType.LAB: prefix = "low-angle-detector-" - elif detector_type is DetectorType.LAB: + elif detector_type is DetectorType.HAB: prefix = "high-angle-detector-" else: raise RuntimeError("MaskingParser: Tyring to get information for unknown " @@ -125,6 +125,9 @@ class SpectraBlock(object): elif self._instrument is SANSInstrument.LOQ: self._first_spectrum_number = 3 self._detector_orientation = DetectorOrientation.Horizontal + elif self._instrument is SANSInstrument.ZOOM: + self._first_spectrum_number = 9 + self._detector_orientation = DetectorOrientation.Horizontal else: raise RuntimeError("MaskParser: Cannot handle masking request for " "instrument {0}".format(str(self._instrument))) diff --git a/scripts/SANS/sans/algorithm_detail/mask_workspace.py b/scripts/SANS/sans/algorithm_detail/mask_workspace.py index b480b476ce320230b9853505e55a8b2f5b9b3a71..dd1234632a1cd6037421d67c643bdf96a2c980c7 100644 --- a/scripts/SANS/sans/algorithm_detail/mask_workspace.py +++ b/scripts/SANS/sans/algorithm_detail/mask_workspace.py @@ -121,7 +121,7 @@ def mask_with_mask_files(mask_info, workspace): # Masker mask_name = "MaskDetectors" - mask_options = {} + mask_options = {"ForceInstrumentMasking": True} mask_alg = create_unmanaged_algorithm(mask_name, **mask_options) for mask_file in mask_files: mask_file = find_full_file_path(mask_file) @@ -394,7 +394,7 @@ class MaskFactory(object): data_info = state.data instrument = data_info.instrument if instrument is SANSInstrument.LARMOR or instrument is SANSInstrument.LOQ or\ - instrument is SANSInstrument.SANS2D: # noqa + instrument is SANSInstrument.SANS2D or instrument is SANSInstrument.ZOOM: # noqa run_number = data_info.sample_scatter_run_number file_name = data_info.sample_scatter _, ipf_path = get_instrument_paths_for_sans_file(file_name) diff --git a/scripts/SANS/sans/algorithm_detail/merge_reductions.py b/scripts/SANS/sans/algorithm_detail/merge_reductions.py index 2d0d0b6ea317f46bcb2fb10d82f1311813c2caab..b2bf3d8ef4feb5b78cb97d29715e7c611bc53f49 100644 --- a/scripts/SANS/sans/algorithm_detail/merge_reductions.py +++ b/scripts/SANS/sans/algorithm_detail/merge_reductions.py @@ -40,6 +40,7 @@ class ISIS1DMerger(Merger): get_partial_workspaces(primary_detector, secondary_detector, reduction_mode_vs_output_bundles, is_sample) # Get the relevant workspaces from the reduction settings. For this we need to first understand what the + # We can have merged reductions can_count_primary, can_norm_primary, can_count_secondary, can_norm_secondary = \ get_partial_workspaces(primary_detector, secondary_detector, reduction_mode_vs_output_bundles, is_can) @@ -140,14 +141,14 @@ def get_partial_workspaces(primary_detector, secondary_detector, reduction_mode_ # Get primary reduction information for specified data type, i.e. sample or can primary = reduction_mode_vs_output_bundles[primary_detector] primary_for_data_type = next((setting for setting in primary if is_data_type(setting)), None) - primary_count = primary_for_data_type.output_workspace_count - primary_norm = primary_for_data_type.output_workspace_norm + primary_count = None if primary_for_data_type is None else primary_for_data_type.output_workspace_count + primary_norm = None if primary_for_data_type is None else primary_for_data_type.output_workspace_norm # Get secondary reduction information for specified data type, i.e. sample or can secondary = reduction_mode_vs_output_bundles[secondary_detector] secondary_for_data_type = next((setting for setting in secondary if is_data_type(setting)), None) - secondary_count = secondary_for_data_type.output_workspace_count - secondary_norm = secondary_for_data_type.output_workspace_norm + secondary_count = None if secondary_for_data_type is None else secondary_for_data_type.output_workspace_count + secondary_norm = None if secondary_for_data_type is None else secondary_for_data_type.output_workspace_norm return primary_count, primary_norm, secondary_count, secondary_norm diff --git a/scripts/SANS/sans/algorithm_detail/move_workspaces.py b/scripts/SANS/sans/algorithm_detail/move_workspaces.py index 8990235ca5c25521c44186a42ad62a694aa199e8..d705983373cec4723e630364e658f6faf44272ab 100644 --- a/scripts/SANS/sans/algorithm_detail/move_workspaces.py +++ b/scripts/SANS/sans/algorithm_detail/move_workspaces.py @@ -243,17 +243,20 @@ def get_detector_component(move_info, component): return component_selection -def move_low_angle_bank_for_SANS2D_and_ZOOM(move_info, workspace, coordinates): +def move_low_angle_bank_for_SANS2D_and_ZOOM(move_info, workspace, coordinates, use_rear_det_z=True): # REAR_DET_Z - lab_detector_z_tag = "Rear_Det_Z" + if use_rear_det_z: + lab_detector_z_tag = "Rear_Det_Z" - log_names = [lab_detector_z_tag] - log_types = [float] - log_values = get_single_valued_logs_from_workspace(workspace, log_names, log_types, - convert_from_millimeter_to_meter=True) + log_names = [lab_detector_z_tag] + log_types = [float] + log_values = get_single_valued_logs_from_workspace(workspace, log_names, log_types, + convert_from_millimeter_to_meter=True) - lab_detector_z = move_info.lab_detector_z \ - if log_values[lab_detector_z_tag] is None else log_values[lab_detector_z_tag] + lab_detector_z = move_info.lab_detector_z \ + if log_values[lab_detector_z_tag] is None else log_values[lab_detector_z_tag] + else: + lab_detector_z = 0. # Perform x and y tilt lab_detector = move_info.detectors[DetectorType.to_string(DetectorType.LAB)] @@ -677,7 +680,7 @@ class SANSMoveLARMORNewStyle(SANSMove): class SANSMoveZOOM(SANSMove): @staticmethod def _move_low_angle_bank(move_info, workspace, coordinates): - move_low_angle_bank_for_SANS2D_and_ZOOM(move_info, workspace, coordinates) + move_low_angle_bank_for_SANS2D_and_ZOOM(move_info, workspace, coordinates, use_rear_det_z=False) def do_move_initial(self, move_info, workspace, coordinates, component, is_transmission_workspace): # For ZOOM we only have to coordinates diff --git a/scripts/SANS/sans/gui_logic/models/state_gui_model.py b/scripts/SANS/sans/gui_logic/models/state_gui_model.py index 9444b2b513926b645a5ee94cc1422371554bd0c3..d2069b18654e5178a5772db7e422298454398624 100644 --- a/scripts/SANS/sans/gui_logic/models/state_gui_model.py +++ b/scripts/SANS/sans/gui_logic/models/state_gui_model.py @@ -395,13 +395,12 @@ class StateGuiModel(object): # ADJUSTMENT TAB # ================================================================================================================== # ================================================================================================================== - def _update_incident_spectrum_info(self, spectrum=None, interpolate=None, is_trans=False): + def _update_incident_spectrum_info(self, spectrum=None, interpolate=False, is_trans=False): if MonId.spectrum in self._user_file_items: settings = self._user_file_items[MonId.spectrum] else: - # If the entry does not already exist, then add it. The -1. is an illegal input which should get overridden - # and if not we want it to fail. - settings = [monitor_spectrum(spectrum=-1, is_trans=is_trans, interpolate=is_trans)] + # If the entry does not already exist, then add it. + settings = [monitor_spectrum(spectrum=spectrum, is_trans=is_trans, interpolate=interpolate)] new_settings = [] for setting in settings: diff --git a/scripts/SANS/sans/gui_logic/presenter/masking_table_presenter.py b/scripts/SANS/sans/gui_logic/presenter/masking_table_presenter.py index fc3bc368f3a961dc53f6528d2fb0ed9d51742149..bf74cb72baa265a36cf4b99b25f32fe77cbc3f94 100644 --- a/scripts/SANS/sans/gui_logic/presenter/masking_table_presenter.py +++ b/scripts/SANS/sans/gui_logic/presenter/masking_table_presenter.py @@ -24,7 +24,7 @@ masking_information = namedtuple("masking_information", "first, second, third") def load_and_mask_workspace(state, workspace_name): workspace_to_mask = load_workspace(state, workspace_name) - return mask_workspace(state, workspace_name, workspace_to_mask) + return mask_workspace(state, workspace_to_mask) def load_workspace(state, workspace_name): @@ -34,16 +34,20 @@ def load_workspace(state, workspace_name): serialized_state = state.property_manager workspace = perform_load(serialized_state) - perform_move(serialized_state, workspace) + perform_move(state, workspace) store_in_ads_as_hidden(workspace_name, workspace) return workspace -def mask_workspace(state, workspace_name, workspace_to_mask): +def mask_workspace(state, workspace_to_mask): serialized_state = state.property_manager masking_algorithm = create_masking_algorithm(serialized_state, workspace_to_mask) + mask_info = state.mask + + detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)] \ + if DetectorType.to_string(DetectorType.HAB) in mask_info.detectors else\ + [DetectorType.to_string(DetectorType.LAB)] # noqa - detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)] for detector in detectors: masking_algorithm.setProperty("Component", detector) masking_algorithm.execute() @@ -73,8 +77,22 @@ def perform_load(serialized_state): return load_algorithm.getProperty("SampleScatterWorkspace").value -def perform_move(serialized_state, workspace): - create_move_algorithm(serialized_state, workspace).execute() +def perform_move(state, workspace): + move_info = state.move + detectors = [DetectorType.to_string(DetectorType.LAB), DetectorType.to_string(DetectorType.HAB)] \ + if DetectorType.to_string(DetectorType.HAB) in move_info.detectors else\ + [DetectorType.to_string(DetectorType.LAB)] # noqa + + serialized_state = state.property_manager + move_name = "SANSMove" + move_options = {"SANSState": serialized_state, + "Workspace": workspace, + "MoveType": "InitialMove"} + move_alg = create_unmanaged_algorithm(move_name, **move_options) + + for detector in detectors: + move_alg.setProperty("Component", detector) + move_alg.execute() def store_in_ads_as_hidden(workspace_name, workspace): @@ -104,14 +122,6 @@ def create_load_algorithm(serialized_state): return create_unmanaged_algorithm(load_name, **load_options) -def create_move_algorithm(serialized_state, workspace_to_move): - move_name = "SANSMove" - move_options = {"SANSState": serialized_state, - "Workspace": workspace_to_move, - "MoveType": "InitialMove"} - return create_unmanaged_algorithm(move_name, **move_options) - - class MaskingTablePresenter(object): DISPLAY_WORKSPACE_NAME = "__sans_mask_display_dummy_workspace" @@ -344,9 +354,9 @@ class MaskingTablePresenter(object): container = [] beam_stop_arm_width = mask_info.beam_stop_arm_width beam_stop_arm_angle = mask_info.beam_stop_arm_angle - beam_stop_arm_pos1 = mask_info.beam_stop_arm_pos1 - beam_stop_arm_pos2 = mask_info.beam_stop_arm_pos2 - if beam_stop_arm_width and beam_stop_arm_angle and beam_stop_arm_pos1 and beam_stop_arm_pos2: + beam_stop_arm_pos1 = mask_info.beam_stop_arm_pos1 if mask_info.beam_stop_arm_pos1 else 0. + beam_stop_arm_pos2 = mask_info.beam_stop_arm_pos2 if mask_info.beam_stop_arm_pos2 else 0. + if beam_stop_arm_width and beam_stop_arm_angle: detail = "LINE {}, {}, {}, {}".format(beam_stop_arm_width, beam_stop_arm_angle, beam_stop_arm_pos1, beam_stop_arm_pos2) container.append(masking_information(first="Arm", second="", third=detail)) @@ -397,7 +407,7 @@ class MaskingTablePresenter(object): masks = [] mask_info_lab = mask_info.detectors[DetectorType.to_string(DetectorType.LAB)] - mask_info_hab = mask_info.detectors[DetectorType.to_string(DetectorType.HAB)] + mask_info_hab = mask_info.detectors[DetectorType.to_string(DetectorType.HAB)] if DetectorType.to_string(DetectorType.HAB) in mask_info.detectors else None # noqa # Add the radius mask radius_mask = self._get_radius(mask_info) @@ -408,8 +418,9 @@ class MaskingTablePresenter(object): masks.extend(spectrum_masks_lab) # Add the spectrum masks for HAB - spectrum_masks_hab = self._get_spectrum_masks(mask_info_hab) - masks.extend(spectrum_masks_hab) + if mask_info_hab: + spectrum_masks_hab = self._get_spectrum_masks(mask_info_hab) + masks.extend(spectrum_masks_hab) # Add the general time mask time_masks_general = self._get_time_masks_general(mask_info) @@ -420,8 +431,9 @@ class MaskingTablePresenter(object): masks.extend(time_masks_lab) # Add the time masks for HAB - time_masks_hab = self._get_time_masks(mask_info_hab) - masks.extend(time_masks_hab) + if mask_info_hab: + time_masks_hab = self._get_time_masks(mask_info_hab) + masks.extend(time_masks_hab) # Add arm mask arm_mask = self._get_arm_mask(mask_info) diff --git a/scripts/SANS/sans/gui_logic/presenter/run_tab_presenter.py b/scripts/SANS/sans/gui_logic/presenter/run_tab_presenter.py index c3e8e455283ce7f3fc4ee1deea50facc9797fa40..b8d398b4f34bfb2d65fc0a8c9761bd9cbd8200aa 100644 --- a/scripts/SANS/sans/gui_logic/presenter/run_tab_presenter.py +++ b/scripts/SANS/sans/gui_logic/presenter/run_tab_presenter.py @@ -233,26 +233,30 @@ class RunTabPresenter(object): 2. Adds a dummy input workspace 3. Adds row index information """ - self.sans_logger.information("Starting processing of batch table.") - # 0. Validate rows - self._create_dummy_input_workspace() - self._validate_rows() - # 1. Set up the states and convert them into property managers - states = self.get_states() - if not states: + try: + self.sans_logger.information("Starting processing of batch table.") + # 0. Validate rows + self._create_dummy_input_workspace() + self._validate_rows() + + # 1. Set up the states and convert them into property managers + states = self.get_states() + if not states: + raise RuntimeError("There seems to have been an issue with setting the states. Make sure that a user file" + "has been loaded") + property_manager_service = PropertyManagerService() + property_manager_service.add_states_to_pmds(states) + + # 2. Add dummy input workspace to Options column + self._remove_dummy_workspaces_and_row_index() + self._set_dummy_workspace() + + # 3. Add dummy row index to Options column + self._set_indices() + except: self._view.halt_process_flag() - raise RuntimeError("There seems to have been an issue with setting the states. Make sure that a user file" - "has been loaded") - property_manager_service = PropertyManagerService() - property_manager_service.add_states_to_pmds(states) - - # 2. Add dummy input workspace to Options column - self._remove_dummy_workspaces_and_row_index() - self._set_dummy_workspace() - - # 3. Add dummy row index to Options column - self._set_indices() + raise def on_processing_finished(self): self._remove_dummy_workspaces_and_row_index() @@ -343,7 +347,6 @@ class RunTabPresenter(object): if not self.is_empty_row(row): sample_scatter = self._view.get_cell(row, 0) if not sample_scatter: - self._view.halt_process_flag() raise RuntimeError("Row {} has not SampleScatter specified. Please correct this.".format(row)) def get_processing_options(self): @@ -843,7 +846,6 @@ class RunTabPresenter(object): self.sans_logger.error("There was a bad entry for row {}. Ensure that the path to your files has " "been added to the Mantid search directories! See here for more " "details: {}".format(row, str(e))) - self._view.halt_process_flag() raise RuntimeError("There was a bad entry for row {}. Ensure that the path to your files has " "been added to the Mantid search directories! See here for more " "details: {}".format(row, str(e))) diff --git a/scripts/SANS/sans/user_file/state_director.py b/scripts/SANS/sans/user_file/state_director.py index a487a0aa335bbc980c3bba9cb047f4766b96c64a..10cf06d6b12619748b4d58d34d1bb78a05e3a3e0 100644 --- a/scripts/SANS/sans/user_file/state_director.py +++ b/scripts/SANS/sans/user_file/state_director.py @@ -1056,11 +1056,16 @@ class StateDirectorISIS(object): if MonId.spectrum in user_file_items: mon_spectrum = user_file_items[MonId.spectrum] mon_spec = [spec for spec in mon_spectrum if not spec.is_trans] - mon_spec = mon_spec[-1] + if mon_spec: + mon_spec = mon_spec[-1] rebin_type = RebinType.InterpolatingRebin if mon_spec.interpolate else RebinType.Rebin self._normalize_to_monitor_builder.set_rebin_type(rebin_type) - self._normalize_to_monitor_builder.set_incident_monitor(mon_spec.spectrum) + + # We have to check if the spectrum is None, this can be the case when the user wants to use the + # default incident monitor spectrum + if mon_spec.spectrum: + self._normalize_to_monitor_builder.set_incident_monitor(mon_spec.spectrum) # The prompt peak correction values set_prompt_peak_correction(self._normalize_to_monitor_builder, user_file_items) @@ -1104,11 +1109,15 @@ class StateDirectorISIS(object): if MonId.spectrum in user_file_items: mon_spectrum = user_file_items[MonId.spectrum] mon_spec = [spec for spec in mon_spectrum if spec.is_trans] - mon_spec = mon_spec[-1] if mon_spec: + mon_spec = mon_spec[-1] rebin_type = RebinType.InterpolatingRebin if mon_spec.interpolate else RebinType.Rebin self._calculate_transmission_builder.set_rebin_type(rebin_type) - self._calculate_transmission_builder.set_incident_monitor(mon_spec.spectrum) + + # We have to check if the spectrum is None, this can be the case when the user wants to use the + # default incident monitor spectrum + if mon_spec.spectrum: + self._calculate_transmission_builder.set_incident_monitor(mon_spec.spectrum) # The general background settings set_background_tof_general(self._calculate_transmission_builder, user_file_items) diff --git a/scripts/test/SANS/gui_logic/state_gui_model_test.py b/scripts/test/SANS/gui_logic/state_gui_model_test.py index d50c9f74f2b4ae3a2dc9b77144d75a36e19f7783..f4f7bad2d74cea01bdd2b813b292f17b8bd4d1a7 100644 --- a/scripts/test/SANS/gui_logic/state_gui_model_test.py +++ b/scripts/test/SANS/gui_logic/state_gui_model_test.py @@ -254,6 +254,12 @@ class StateGuiModelTest(unittest.TestCase): state_gui_model.normalization_incident_monitor = 3 self.assertTrue(state_gui_model.normalization_incident_monitor == 3) + def test_that_can_set_only_interpolation(self): + state_gui_model = StateGuiModel({"test": [1]}) + state_gui_model.normalization_interpolate = True + self.assertTrue(state_gui_model.normalization_incident_monitor is None) + self.assertTrue(state_gui_model.normalization_interpolate) + # ------------------------------------------------------------------------------------------------------------------ # Transmission # ------------------------------------------------------------------------------------------------------------------ @@ -272,6 +278,12 @@ class StateGuiModelTest(unittest.TestCase): state_gui_model.transmission_incident_monitor = 3 self.assertTrue(state_gui_model.transmission_incident_monitor == 3) + def test_that_can_set_only_interpolation(self): + state_gui_model = StateGuiModel({"test": [1]}) + state_gui_model.transmission_interpolate = True + self.assertTrue(state_gui_model.transmission_incident_monitor is None) + self.assertTrue(state_gui_model.transmission_interpolate) + def test_that_can_set_normalization_and_transmission_monitor_and_rebin_type_settings(self): pass