diff --git a/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h b/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h index c17aa1ffc652de4b07ec7fdc42ec0b9377f5c073..62064b7203c7dcf4746a2c00842ebfeb7ffac355 100644 --- a/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h +++ b/Framework/API/inc/MantidAPI/ImmutableCompositeFunction.h @@ -91,7 +91,7 @@ protected: private: /// Keep paramater aliases - std::map<std::string, size_t> m_alias; + std::map<std::string, size_t> m_aliases; }; } // namespace API diff --git a/Framework/API/src/Algorithm.cpp b/Framework/API/src/Algorithm.cpp index 9bc608d984331e4c62b41fd7730eb791a2e1cdf2..b430037b853cf6f4bcae2fe2ea9dd54a87e21b8a 100644 --- a/Framework/API/src/Algorithm.cpp +++ b/Framework/API/src/Algorithm.cpp @@ -234,13 +234,8 @@ const std::vector<std::string> Algorithm::workspaceMethodOn() const { WORKSPACE_TYPES_SEPARATOR, Poco::StringTokenizer::TOK_TRIM | Poco::StringTokenizer::TOK_IGNORE_EMPTY); - std::vector<std::string> res; - res.reserve(tokenizer.count()); - for (auto iter = tokenizer.begin(); iter != tokenizer.end(); ++iter) { - res.push_back(*iter); - } - return res; + return std::vector<std::string>(tokenizer.begin(), tokenizer.end()); } /** @@ -315,8 +310,7 @@ void Algorithm::cacheWorkspaceProperties() { m_outputWorkspaceProps.clear(); m_pureOutputWorkspaceProps.clear(); const std::vector<Property *> &props = this->getProperties(); - for (size_t i = 0; i < props.size(); i++) { - Property *prop = props[i]; + for (auto prop : props) { IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (wsProp) { switch (prop->direction()) { @@ -361,12 +355,12 @@ void Algorithm::lockWorkspaces() { // First, Write-lock the output workspaces auto &debugLog = g_log.debug(); - for (size_t i = 0; i < m_outputWorkspaceProps.size(); i++) { - Workspace_sptr ws = m_outputWorkspaceProps[i]->getWorkspace(); + for (auto &outputWorkspaceProp : m_outputWorkspaceProps) { + Workspace_sptr ws = outputWorkspaceProp->getWorkspace(); if (ws) { // The workspace property says to do locking, // AND it has NOT already been write-locked - if (m_outputWorkspaceProps[i]->isLocking() && + if (outputWorkspaceProp->isLocking() && std::find(m_writeLockedWorkspaces.begin(), m_writeLockedWorkspaces.end(), ws) == m_writeLockedWorkspaces.end()) { @@ -379,12 +373,12 @@ void Algorithm::lockWorkspaces() { } // Next read-lock the input workspaces - for (size_t i = 0; i < m_inputWorkspaceProps.size(); i++) { - Workspace_sptr ws = m_inputWorkspaceProps[i]->getWorkspace(); + for (auto &inputWorkspaceProp : m_inputWorkspaceProps) { + Workspace_sptr ws = inputWorkspaceProp->getWorkspace(); if (ws) { // The workspace property says to do locking, // AND it has NOT already been write-locked - if (m_inputWorkspaceProps[i]->isLocking() && + if (inputWorkspaceProp->isLocking() && std::find(m_writeLockedWorkspaces.begin(), m_writeLockedWorkspaces.end(), ws) == m_writeLockedWorkspaces.end()) { @@ -406,15 +400,13 @@ void Algorithm::unlockWorkspaces() { if (this->isChild()) return; auto &debugLog = g_log.debug(); - for (size_t i = 0; i < m_writeLockedWorkspaces.size(); i++) { - Workspace_sptr ws = m_writeLockedWorkspaces[i]; + for (auto &ws : m_writeLockedWorkspaces) { if (ws) { debugLog << "Unlocking " << ws->getName() << std::endl; ws->getLock()->unlock(); } } - for (size_t i = 0; i < m_readLockedWorkspaces.size(); i++) { - Workspace_sptr ws = m_readLockedWorkspaces[i]; + for (auto &ws : m_readLockedWorkspaces) { if (ws) { debugLog << "Unlocking " << ws->getName() << std::endl; ws->getLock()->unlock(); @@ -466,11 +458,11 @@ bool Algorithm::execute() { if (!validateProperties()) { // Reset name on input workspaces to trigger attempt at collection from ADS const std::vector<Property *> &props = getProperties(); - for (unsigned int i = 0; i < props.size(); ++i) { - IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(props[i]); + for (auto &prop : props) { + IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (wsProp && !(wsProp->getWorkspace())) { // Setting it's name to the same one it already had - props[i]->setValue(props[i]->value()); + prop->setValue(prop->value()); } } // Try the validation again @@ -511,14 +503,14 @@ bool Algorithm::execute() { // Log each issue auto &errorLog = getLogger().error(); auto &warnLog = getLogger().warning(); - for (auto it = errors.begin(); it != errors.end(); it++) { - if (this->existsProperty(it->first)) - errorLog << "Invalid value for " << it->first << ": " << it->second - << "\n"; + for (auto &error : errors) { + if (this->existsProperty(error.first)) + errorLog << "Invalid value for " << error.first << ": " + << error.second << "\n"; else { numErrors -= 1; // don't count it as an error warnLog << "validateInputs() references non-existant property \"" - << it->first << "\"\n"; + << error.first << "\"\n"; } } // Throw because something was invalid @@ -782,11 +774,11 @@ Algorithm_sptr Algorithm::createChildAlgorithm(const std::string &name, // If output workspaces are nameless, give them a temporary name to satisfy // validator const std::vector<Property *> &props = alg->getProperties(); - for (unsigned int i = 0; i < props.size(); ++i) { - auto wsProp = dynamic_cast<IWorkspaceProperty *>(props[i]); - if (props[i]->direction() == Mantid::Kernel::Direction::Output && wsProp) { - if (props[i]->value().empty()) { - props[i]->createTemporaryValue(); + for (auto prop : props) { + auto wsProp = dynamic_cast<IWorkspaceProperty *>(prop); + if (prop->direction() == Mantid::Kernel::Direction::Output && wsProp) { + if (prop->value().empty()) { + prop->createTemporaryValue(); } } } @@ -1132,12 +1124,12 @@ bool Algorithm::checkGroups() { // Unroll the groups or single inputs into vectors of workspace m_groups.clear(); m_groupWorkspaces.clear(); - for (size_t i = 0; i < m_inputWorkspaceProps.size(); i++) { - auto *prop = dynamic_cast<Property *>(m_inputWorkspaceProps[i]); - auto *wsGroupProp = dynamic_cast<WorkspaceProperty<WorkspaceGroup> *>(prop); + for (auto inputWorkspaceProp : m_inputWorkspaceProps) { + auto prop = dynamic_cast<Property *>(inputWorkspaceProp); + auto wsGroupProp = dynamic_cast<WorkspaceProperty<WorkspaceGroup> *>(prop); std::vector<Workspace_sptr> thisGroup; - Workspace_sptr ws = m_inputWorkspaceProps[i]->getWorkspace(); + Workspace_sptr ws = inputWorkspaceProp->getWorkspace(); WorkspaceGroup_sptr wsGroup = boost::dynamic_pointer_cast<WorkspaceGroup>(ws); @@ -1159,12 +1151,12 @@ bool Algorithm::checkGroups() { numGroups++; processGroups = true; std::vector<std::string> names = wsGroup->getNames(); - for (size_t j = 0; j < names.size(); j++) { + for (auto &name : names) { Workspace_sptr memberWS = - AnalysisDataService::Instance().retrieve(names[j]); + AnalysisDataService::Instance().retrieve(name); if (!memberWS) throw std::invalid_argument("One of the members of " + - wsGroup->name() + ", " + names[j] + + wsGroup->name() + ", " + name + " was not found!."); thisGroup.push_back(memberWS); } @@ -1239,8 +1231,8 @@ bool Algorithm::processGroups() { std::vector<WorkspaceGroup_sptr> outGroups; // ---------- Create all the output workspaces ---------------------------- - for (size_t owp = 0; owp < m_pureOutputWorkspaceProps.size(); owp++) { - Property *prop = dynamic_cast<Property *>(m_pureOutputWorkspaceProps[owp]); + for (auto &pureOutputWorkspaceProp : m_pureOutputWorkspaceProps) { + Property *prop = dynamic_cast<Property *>(pureOutputWorkspaceProp); if (prop) { WorkspaceGroup_sptr outWSGrp = WorkspaceGroup_sptr(new WorkspaceGroup()); outGroups.push_back(outWSGrp); @@ -1357,8 +1349,8 @@ bool Algorithm::processGroups() { } // for each entry in each group // restore group notifications - for (size_t i = 0; i < outGroups.size(); i++) { - outGroups[i]->observeADSNotifications(true); + for (auto &outGroup : outGroups) { + outGroup->observeADSNotifications(true); } // We finished successfully. @@ -1379,8 +1371,7 @@ void Algorithm::copyNonWorkspaceProperties(IAlgorithm *alg, int periodNum) { if (!alg) throw std::runtime_error("Algorithm not created!"); std::vector<Property *> props = this->getProperties(); - for (size_t i = 0; i < props.size(); i++) { - Property *prop = props[i]; + for (auto prop : props) { if (prop) { IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); // Copy the property using the string @@ -1419,7 +1410,7 @@ bool Algorithm::isWorkspaceProperty(const Kernel::Property *const prop) const { } const IWorkspaceProperty *const wsProp = dynamic_cast<const IWorkspaceProperty *>(prop); - return (wsProp ? true : false); + return (wsProp != nullptr); } //============================================================================================= @@ -1510,9 +1501,7 @@ void Algorithm::cancel() { m_cancel = true; // Loop over the output workspaces and try to cancel them - for (auto it = m_ChildAlgorithms.begin(); it != m_ChildAlgorithms.end(); - ++it) { - const auto &weakPtr = *it; + for (auto &weakPtr : m_ChildAlgorithms) { if (IAlgorithm_sptr sharedPtr = weakPtr.lock()) { sharedPtr->cancel(); } diff --git a/Framework/API/src/AlgorithmFactory.cpp b/Framework/API/src/AlgorithmFactory.cpp index 099150e852c77cf245af3d51032366d44c029bf5..db39e91f5563a33f165fe249335aaefc4e6b03dc 100644 --- a/Framework/API/src/AlgorithmFactory.cpp +++ b/Framework/API/src/AlgorithmFactory.cpp @@ -366,9 +366,8 @@ AlgorithmFactoryImpl::getDescriptors(bool includeHidden) const { // Traverse each parent category, working our way from the top down. std::string currentLayer = ""; - for (auto layerIt = categoryLayers.begin(); - layerIt != categoryLayers.end(); ++layerIt) { - currentLayer.append(*layerIt); + for (auto &categoryLayer : categoryLayers) { + currentLayer.append(categoryLayer); if (hiddenCategories.find(currentLayer) != hiddenCategories.end()) { // Category is hidden, no need to check any others. diff --git a/Framework/API/src/AlgorithmManager.cpp b/Framework/API/src/AlgorithmManager.cpp index 395423cca97c78a0aa6e5cc09b8ea001f27e279e..5f33af33a94bccb5c10ddacc8b22cc4a366268c8 100644 --- a/Framework/API/src/AlgorithmManager.cpp +++ b/Framework/API/src/AlgorithmManager.cpp @@ -149,9 +149,9 @@ void AlgorithmManagerImpl::setMaxAlgorithms(int n) { */ IAlgorithm_sptr AlgorithmManagerImpl::getAlgorithm(AlgorithmID id) const { Mutex::ScopedLock _lock(this->m_managedMutex); - for (auto a = m_managed_algs.cbegin(); a != m_managed_algs.cend(); ++a) { - if ((**a).getAlgorithmID() == id) - return *a; + for (const auto &managed_alg : m_managed_algs) { + if ((*managed_alg).getAlgorithmID() == id) + return managed_alg; } return IAlgorithm_sptr(); } @@ -207,8 +207,7 @@ std::vector<IAlgorithm_const_sptr> AlgorithmManagerImpl::runningInstancesOf( const std::string &algorithmName) const { std::vector<IAlgorithm_const_sptr> theRunningInstances; Mutex::ScopedLock _lock(this->m_managedMutex); - for (auto alg = m_managed_algs.begin(); alg != m_managed_algs.end(); ++alg) { - auto currentAlgorithm = *alg; + for (auto currentAlgorithm : m_managed_algs) { if (currentAlgorithm->name() == algorithmName && currentAlgorithm->isRunning()) { theRunningInstances.push_back(currentAlgorithm); @@ -221,9 +220,9 @@ std::vector<IAlgorithm_const_sptr> AlgorithmManagerImpl::runningInstancesOf( /// Requests cancellation of all running algorithms void AlgorithmManagerImpl::cancelAll() { Mutex::ScopedLock _lock(this->m_managedMutex); - for (auto it = m_managed_algs.begin(); it != m_managed_algs.end(); ++it) { - if ((*it)->isRunning()) - (*it)->cancel(); + for (auto &managed_alg : m_managed_algs) { + if (managed_alg->isRunning()) + managed_alg->cancel(); } } diff --git a/Framework/API/src/AlgorithmProxy.cpp b/Framework/API/src/AlgorithmProxy.cpp index bd9fb288393de1ea94776887495826280159ad79..e74bbb3ad2638528945d16dad43775e1aba99810 100644 --- a/Framework/API/src/AlgorithmProxy.cpp +++ b/Framework/API/src/AlgorithmProxy.cpp @@ -269,8 +269,8 @@ void AlgorithmProxy::stopped() { */ void AlgorithmProxy::dropWorkspaceReferences() { const std::vector<Property *> &props = getProperties(); - for (unsigned int i = 0; i < props.size(); ++i) { - if (auto *wsProp = dynamic_cast<IWorkspaceProperty *>(props[i])) { + for (auto prop : props) { + if (auto *wsProp = dynamic_cast<IWorkspaceProperty *>(prop)) { wsProp->clear(); } } diff --git a/Framework/API/src/AnalysisDataService.cpp b/Framework/API/src/AnalysisDataService.cpp index 3dc8a983bfabe92474b1026564b87b5511dbe6e3..bb010a5921e5dd3ed74211b8fc897ee33dafb2ef 100644 --- a/Framework/API/src/AnalysisDataService.cpp +++ b/Framework/API/src/AnalysisDataService.cpp @@ -236,10 +236,10 @@ AnalysisDataServiceImpl::topLevelItems() const { auto topLevelNames = this->getObjectNames(); std::set<Workspace_sptr> groupMembers; - for (auto it = topLevelNames.begin(); it != topLevelNames.end(); ++it) { + for (const auto &topLevelName : topLevelNames) { try { - const std::string &name = *it; - auto ws = this->retrieve(*it); + const std::string &name = topLevelName; + auto ws = this->retrieve(topLevelName); topLevel.emplace(name, ws); if (auto group = boost::dynamic_pointer_cast<WorkspaceGroup>(ws)) { group->reportMembers(groupMembers); diff --git a/Framework/API/src/BoxController.cpp b/Framework/API/src/BoxController.cpp index 0a6334c5cc7b168f32f2d9e68f07ddc01287ec2b..6ad49a8ed97982a61721b17a3133566da0b50b33 100644 --- a/Framework/API/src/BoxController.cpp +++ b/Framework/API/src/BoxController.cpp @@ -212,10 +212,7 @@ std::string BoxController::getFilename() const { /** the function left for compartibility with the previous bc python interface. @return true if the workspace is file based and false otherwise */ bool BoxController::useWriteBuffer() const { - if (m_fileIO) - return true; - else - return false; + return static_cast<bool>(m_fileIO); } //------------------------------------------------------------------------------------------------------ diff --git a/Framework/API/src/CatalogManager.cpp b/Framework/API/src/CatalogManager.cpp index 82d458c4274e2087417e9d2319e2149143409ff5..4bb089d8f9b1840f008d62a9c908d3343babcc29 100644 --- a/Framework/API/src/CatalogManager.cpp +++ b/Framework/API/src/CatalogManager.cpp @@ -55,17 +55,15 @@ ICatalog_sptr CatalogManagerImpl::getCatalog(const std::string &sessionID) { if (sessionID.empty()) { auto composite = boost::make_shared<CompositeCatalog>(); - for (auto item = m_activeCatalogs.begin(); item != m_activeCatalogs.end(); - ++item) { - composite->add(item->second); + for (auto &activeCatalog : m_activeCatalogs) { + composite->add(activeCatalog.second); } return composite; } - for (auto iter = m_activeCatalogs.begin(); iter != m_activeCatalogs.end(); - ++iter) { - if (sessionID == iter->first->getSessionId()) - return iter->second; + for (auto &activeCatalog : m_activeCatalogs) { + if (sessionID == activeCatalog.first->getSessionId()) + return activeCatalog.second; } // If we reached this point then the session is corrupt/invalid. @@ -81,9 +79,8 @@ ICatalog_sptr CatalogManagerImpl::getCatalog(const std::string &sessionID) { */ void CatalogManagerImpl::destroyCatalog(const std::string &sessionID) { if (sessionID.empty()) { - for (auto item = m_activeCatalogs.begin(); item != m_activeCatalogs.end(); - ++item) { - item->second->logout(); + for (auto &activeCatalog : m_activeCatalogs) { + activeCatalog.second->logout(); } m_activeCatalogs.clear(); } @@ -103,10 +100,9 @@ void CatalogManagerImpl::destroyCatalog(const std::string &sessionID) { */ std::vector<CatalogSession_sptr> CatalogManagerImpl::getActiveSessions() { std::vector<CatalogSession_sptr> sessions; - - for (auto item = m_activeCatalogs.begin(); item != m_activeCatalogs.end(); - ++item) { - sessions.push_back(item->first); + sessions.reserve(m_activeCatalogs.size()); + for (auto &activeCatalog : m_activeCatalogs) { + sessions.push_back(activeCatalog.first); } return sessions; diff --git a/Framework/API/src/ChopperModel.cpp b/Framework/API/src/ChopperModel.cpp index c6feabf88bb162794e48020117e87cea7601a631..4728f115bf23f5348c467d30318fe37c1dd8dfd7 100644 --- a/Framework/API/src/ChopperModel.cpp +++ b/Framework/API/src/ChopperModel.cpp @@ -50,8 +50,8 @@ void ChopperModel::initialize(const std::string ¶ms) { setBaseParameters(keyValues); - for (auto iter = keyValues.begin(); iter != keyValues.end(); ++iter) { - setParameterValue(iter->first, iter->second); + for (auto &keyValue : keyValues) { + setParameterValue(keyValue.first, keyValue.second); } } diff --git a/Framework/API/src/CompositeCatalog.cpp b/Framework/API/src/CompositeCatalog.cpp index 082d9b781d23bdbf5f04caf1c6c4aa7e15a22bc5..a8ae230ba8bbc8696f59dc4f2176f416b73ad0b3 100644 --- a/Framework/API/src/CompositeCatalog.cpp +++ b/Framework/API/src/CompositeCatalog.cpp @@ -37,9 +37,8 @@ CatalogSession_sptr CompositeCatalog::login(const std::string &username, * Log the user out of all catalogues in the container. */ void CompositeCatalog::logout() { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->logout(); + for (auto &catalog : m_catalogs) { + catalog->logout(); } } @@ -55,9 +54,8 @@ void CompositeCatalog::logout() { void CompositeCatalog::search(const ICat::CatalogSearchParam &inputs, ITableWorkspace_sptr &outputws, const int &offset, const int &limit) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->search(inputs, outputws, offset, limit); + for (auto &catalog : m_catalogs) { + catalog->search(inputs, outputws, offset, limit); } } @@ -68,9 +66,8 @@ void CompositeCatalog::search(const ICat::CatalogSearchParam &inputs, int64_t CompositeCatalog::getNumberOfSearchResults( const ICat::CatalogSearchParam &inputs) { int64_t numberOfSearchResults = 0; - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - numberOfSearchResults += (*catalog)->getNumberOfSearchResults(inputs); + for (auto &catalog : m_catalogs) { + numberOfSearchResults += catalog->getNumberOfSearchResults(inputs); } return numberOfSearchResults; } @@ -81,9 +78,8 @@ int64_t CompositeCatalog::getNumberOfSearchResults( * @param outputws :: The workspace to store the results. */ void CompositeCatalog::myData(ITableWorkspace_sptr &outputws) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->myData(outputws); + for (auto &catalog : m_catalogs) { + catalog->myData(outputws); } } @@ -95,9 +91,8 @@ void CompositeCatalog::myData(ITableWorkspace_sptr &outputws) { */ void CompositeCatalog::getDataSets(const std::string &investigationId, ITableWorkspace_sptr &outputws) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->getDataSets(investigationId, outputws); + for (auto &catalog : m_catalogs) { + catalog->getDataSets(investigationId, outputws); } } @@ -109,9 +104,8 @@ void CompositeCatalog::getDataSets(const std::string &investigationId, */ void CompositeCatalog::getDataFiles(const std::string &investigationId, ITableWorkspace_sptr &outputws) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->getDataFiles(investigationId, outputws); + for (auto &catalog : m_catalogs) { + catalog->getDataFiles(investigationId, outputws); } } @@ -120,9 +114,8 @@ void CompositeCatalog::getDataFiles(const std::string &investigationId, * @param instruments :: A reference to the vector to store the results. */ void CompositeCatalog::listInstruments(std::vector<std::string> &instruments) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->listInstruments(instruments); + for (auto &catalog : m_catalogs) { + catalog->listInstruments(instruments); } } @@ -132,9 +125,8 @@ void CompositeCatalog::listInstruments(std::vector<std::string> &instruments) { */ void CompositeCatalog::listInvestigationTypes( std::vector<std::string> &invstTypes) { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->listInvestigationTypes(invstTypes); + for (auto &catalog : m_catalogs) { + catalog->listInvestigationTypes(invstTypes); } } @@ -142,9 +134,8 @@ void CompositeCatalog::listInvestigationTypes( * Keep each catalog session alive in the container. */ void CompositeCatalog::keepAlive() { - for (auto catalog = m_catalogs.begin(); catalog != m_catalogs.end(); - ++catalog) { - (*catalog)->keepAlive(); + for (auto &catalog : m_catalogs) { + catalog->keepAlive(); } } } diff --git a/Framework/API/src/CompositeFunction.cpp b/Framework/API/src/CompositeFunction.cpp index 9a9086bda8351e2f39a23bbb4bed20e4877a3d1c..86254978c2bde4e89688982b5d515f970e6505ff 100644 --- a/Framework/API/src/CompositeFunction.cpp +++ b/Framework/API/src/CompositeFunction.cpp @@ -62,9 +62,8 @@ std::string CompositeFunction::asString() const { getAttribute("NumDeriv").asBool() == true) { ostr << "composite=" << name(); std::vector<std::string> attr = this->getAttributeNames(); - for (size_t i = 0; i < attr.size(); i++) { - std::string attName = attr[i]; - std::string attValue = this->getAttribute(attr[i]).value(); + for (const auto &attName : attr) { + std::string attValue = this->getAttribute(attName).value(); if (!attValue.empty()) { ostr << ',' << attName << '=' << attValue; } @@ -369,9 +368,7 @@ void CompositeFunction::checkFunction() { std::vector<IFunction_sptr> functions(m_functions.begin(), m_functions.end()); m_functions.clear(); - for (std::vector<IFunction_sptr>::size_type i = 0; i < functions.size(); - i++) { - IFunction_sptr f = functions[i]; + for (auto &f : functions) { CompositeFunction_sptr cf = boost::dynamic_pointer_cast<CompositeFunction>(f); if (cf) diff --git a/Framework/API/src/ExperimentInfo.cpp b/Framework/API/src/ExperimentInfo.cpp index 90a35d1f73f23016639ca42ea97a64646c8c3c45..f6fd911cb38d1f8f1004362de4ea0abc21c070dc 100644 --- a/Framework/API/src/ExperimentInfo.cpp +++ b/Framework/API/src/ExperimentInfo.cpp @@ -73,9 +73,8 @@ void ExperimentInfo::copyExperimentInfoFrom(const ExperimentInfo *other) { if (other->m_moderatorModel) m_moderatorModel = other->m_moderatorModel->clone(); m_choppers.clear(); - for (auto iter = other->m_choppers.begin(); iter != other->m_choppers.end(); - ++iter) { - m_choppers.push_back((*iter)->clone()); + for (const auto &chopper : other->m_choppers) { + m_choppers.push_back(chopper->clone()); } } @@ -106,9 +105,8 @@ const std::string ExperimentInfo::toString() const { // parameter files loaded auto paramFileVector = this->instrumentParameters().getParameterFilenames(); - for (auto itFilename = paramFileVector.begin(); - itFilename != paramFileVector.end(); ++itFilename) { - out << "Parameters from: " << *itFilename; + for (auto &itFilename : paramFileVector) { + out << "Parameters from: " << itFilename; out << "\n"; } @@ -851,11 +849,9 @@ ExperimentInfo::getInstrumentFilename(const std::string &instrumentName, DateAndTime refDateGoodFile("1900-01-31 23:59:00"); // used to help determine // the most recently // starting matching IDF - for (auto instDirs_itr = directoryNames.begin(); - instDirs_itr != directoryNames.end(); ++instDirs_itr) { + for (auto directoryName : directoryNames) { // This will iterate around the directories from user ->etc ->install, and // find the first beat file - std::string directoryName = *instDirs_itr; for (Poco::DirectoryIterator dir_itr(directoryName); dir_itr != end_iter; ++dir_itr) { if (!Poco::File(dir_itr->path()).isFile()) diff --git a/Framework/API/src/Expression.cpp b/Framework/API/src/Expression.cpp index a3d59245d9438eaa20be89de492fa8b7a42a8f01..765c7664ac6d68e6d4621c500296b814f39acb58 100644 --- a/Framework/API/src/Expression.cpp +++ b/Framework/API/src/Expression.cpp @@ -71,16 +71,14 @@ void Expression::add_operators(const std::vector<std::string> &ops) { char j = 0; tokenizer tkz(m_operators->binary[i], " ", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); - for (auto it = tkz.begin(); it != tkz.end(); it++) { - m_operators->precedence[*it] = i + 1; - m_operators->op_number[*it] = j++; + for (const auto &index : tkz) { + m_operators->precedence[index] = i + 1; + m_operators->op_number[index] = j++; } } - for (size_t i = 0; i < ops.size(); i++) { - std::string str = ops[i]; - for (size_t j = 0; j < str.size(); j++) { - char c = str[j]; + for (auto str : ops) { + for (char c : str) { if (c == ' ') continue; m_operators->symbols.insert(c); @@ -90,10 +88,8 @@ void Expression::add_operators(const std::vector<std::string> &ops) { void Expression::add_unary(const std::set<std::string> &ops) { m_operators->unary = ops; - for (auto it = ops.cbegin(); it != ops.cend(); ++it) { - for (auto c = it->cbegin(); c != it->cend(); ++c) { - m_operators->symbols.insert(*c); - } + for (const auto &op : ops) { + m_operators->symbols.insert(op.cbegin(), op.cend()); } } @@ -309,11 +305,7 @@ void Expression::tokenize() { } if (c == '"') { - if (!inString) { - inString = true; - } else { - inString = false; - } + inString = !inString; } } // for i @@ -364,8 +356,8 @@ void Expression::logPrint(const std::string &pads) const { std::string myPads = pads + " "; if (m_terms.size()) { std::cerr << myPads << m_op << '[' << m_funct << ']' << "(" << '\n'; - for (size_t i = 0; i < m_terms.size(); i++) - m_terms[i].logPrint(myPads); + for (const auto &term : m_terms) + term.logPrint(myPads); std::cerr << myPads << ")" << '\n'; } else std::cerr << myPads << m_op << m_funct << '\n'; @@ -401,10 +393,7 @@ void Expression::setFunct(const std::string &name) { bool inQuotes = false; for (std::string::const_iterator c = name.begin(); c != name.end(); ++c) { if (*c == '"') { - if (inQuotes) - inQuotes = false; - else - inQuotes = true; + inQuotes = !inQuotes; continue; } @@ -456,11 +445,11 @@ std::string Expression::str() const { if (m_terms.size()) { if (brackets) res << '('; - for (size_t i = 0; i < m_terms.size(); i++) { - res << m_terms[i].operator_name(); - size_t prec1 = op_prec(m_terms[i].m_funct); + for (const auto &term : m_terms) { + res << term.operator_name(); + size_t prec1 = op_prec(term.m_funct); bool isItUnary = false; - if (m_terms[i].size() == 1 && is_unary(m_terms[i].m_funct)) { + if (term.size() == 1 && is_unary(term.m_funct)) { prec1 = 0; // unary operator isItUnary = true; } @@ -469,7 +458,7 @@ std::string Expression::str() const { res << '('; if (isItUnary) res << ' '; - res << m_terms[i].str(); + res << term.str(); if (bk) res << ')'; } @@ -498,12 +487,12 @@ std::set<std::string> Expression::getVariables() const { out.insert(s); } } else { - for (auto e = begin(); e != end(); ++e) { - if (e->isFunct()) { - std::set<std::string> tout = e->getVariables(); + for (const auto &e : *this) { + if (e.isFunct()) { + std::set<std::string> tout = e.getVariables(); out.insert(tout.begin(), tout.end()); } else { - std::string s = e->name(); + std::string s = e.name(); if (!s.empty() && !isdigit(s[0])) { out.insert(s); } diff --git a/Framework/API/src/FileFinder.cpp b/Framework/API/src/FileFinder.cpp index 2c77a6ef042436bbb6d17dd19368a1e899af190a..32d391eb2606311ce7f1fd9a6b8c4d592b82ca5e 100644 --- a/Framework/API/src/FileFinder.cpp +++ b/Framework/API/src/FileFinder.cpp @@ -37,9 +37,7 @@ Mantid::Kernel::Logger g_log("FileFinder"); * @returns true if extension contains a "*", else false. */ bool containsWildCard(const std::string &ext) { - if (std::string::npos != ext.find("*")) - return true; - return false; + return std::string::npos != ext.find("*"); } } @@ -126,7 +124,7 @@ std::string FileFinderImpl::getFullPath(const std::string &filename, const std::vector<std::string> &searchPaths = Kernel::ConfigService::Instance().getDataSearchDirs(); - for (auto it = searchPaths.cbegin(); it != searchPaths.cend(); ++it) { + for (const auto &searchPath : searchPaths) { // On windows globbing is note working properly with network drives // for example a network drive containing a $ // For this reason, and since windows is case insensitive anyway @@ -134,7 +132,7 @@ std::string FileFinderImpl::getFullPath(const std::string &filename, #ifdef _WIN32 if (fName.find("*") != std::string::npos) { #endif - Poco::Path path(*it, fName); + Poco::Path path(searchPath, fName); Poco::Path pathPattern(path); std::set<std::string> files; Kernel::Glob::glob(pathPattern, files, m_globOption); @@ -147,7 +145,7 @@ std::string FileFinderImpl::getFullPath(const std::string &filename, } #ifdef _WIN32 } else { - Poco::Path path(*it, fName); + Poco::Path path(searchPath, fName); Poco::File file(path); if (file.exists() && !(ignoreDirs && file.isDirectory())) { return path.toString(); @@ -398,8 +396,8 @@ FileFinderImpl::getExtension(const std::string &filename, << "])\n"; // go through the list of supplied extensions - for (auto it = exts.begin(); it != exts.end(); ++it) { - std::string extension = toUpper(*it); + for (const auto &ext : exts) { + std::string extension = toUpper(ext); if (extension.rfind('*') == extension.size() - 1) // there is a wildcard at play { @@ -409,7 +407,7 @@ FileFinderImpl::getExtension(const std::string &filename, std::size_t found = toUpper(filename).rfind(extension); if (found != std::string::npos) { g_log.debug() << "matched extension \"" << extension << "\" based on \"" - << (*it) << "\"\n"; + << ext << "\"\n"; return filename.substr(found); // grab the actual extensions found } } @@ -478,11 +476,10 @@ FileFinderImpl::findRun(const std::string &hintstr, tolower); if (!archiveOpt.empty() && archiveOpt != "off" && !facility.archiveSearch().empty()) { - for (auto it = facility.archiveSearch().cbegin(); - it != facility.archiveSearch().cend(); ++it) { - g_log.debug() << "get archive search for the facility..." << *it - << "\n"; - archs.push_back(ArchiveSearchFactory::Instance().create(*it)); + for (const auto &facilityname : facility.archiveSearch()) { + g_log.debug() << "get archive search for the facility..." + << facilityname << "\n"; + archs.push_back(ArchiveSearchFactory::Instance().create(facilityname)); } } } @@ -684,9 +681,9 @@ FileFinderImpl::getArchivePath(const std::vector<IArchiveSearch_sptr> &archs, const std::set<std::string> &filenames, const std::vector<std::string> &exts) const { std::string path = ""; - for (auto it = archs.cbegin(); it != archs.cend(); ++it) { + for (const auto &arch : archs) { try { - path = (*it)->getArchivePath(filenames, exts); + path = arch->getArchivePath(filenames, exts); if (!path.empty()) { return path; } @@ -730,13 +727,11 @@ FileFinderImpl::getPath(const std::vector<IArchiveSearch_sptr> &archs, // performance when calling findRuns() // with a large range of files, especially when searchPaths consists of // folders containing a large number of runs. - for (auto ext = extensions.begin(); ext != extensions.end(); ++ext) { - for (auto filename = filenames.begin(); filename != filenames.end(); - ++filename) { - for (auto searchPath = searchPaths.begin(); - searchPath != searchPaths.end(); ++searchPath) { + for (auto &extension : extensions) { + for (const auto &filename : filenames) { + for (const auto &searchPath : searchPaths) { try { - Poco::Path path(*searchPath, *filename + *ext); + Poco::Path path(searchPath, filename + extension); Poco::File file(path); if (file.exists()) return path.toString(); @@ -747,9 +742,9 @@ FileFinderImpl::getPath(const std::vector<IArchiveSearch_sptr> &archs, } } - for (auto ext = extensions.cbegin(); ext != extensions.cend(); ++ext) { - for (auto it = filenames.cbegin(); it != filenames.cend(); ++it) { - path = getFullPath(*it + *ext); + for (const auto &extension : extensions) { + for (const auto &filename : filenames) { + path = getFullPath(filename + extension); try { if (!path.empty() && Poco::File(path).exists()) { g_log.debug() << "path returned from getFullPath() = " << path diff --git a/Framework/API/src/FileLoaderRegistry.cpp b/Framework/API/src/FileLoaderRegistry.cpp index dcea84bb2769bec25b9422f743cc417566e19ff3..5f8befb87fbd54222babce9799010ad627f00b47 100644 --- a/Framework/API/src/FileLoaderRegistry.cpp +++ b/Framework/API/src/FileLoaderRegistry.cpp @@ -159,10 +159,7 @@ bool FileLoaderRegistryImpl::canLoad(const std::string &algorithmName, loader = searchForLoader<FileDescriptor, IFileLoader<FileDescriptor>>( filename, names, m_log); } - if (loader) - return true; - else - return false; + return static_cast<bool>(loader); } //---------------------------------------------------------------------------------------------- diff --git a/Framework/API/src/FileProperty.cpp b/Framework/API/src/FileProperty.cpp index 73e02d48fbfa1fd1fd45d0f7ed3845c666a59e99..f151c90941820779f97ce5491ed0a8b716fdfc3f 100644 --- a/Framework/API/src/FileProperty.cpp +++ b/Framework/API/src/FileProperty.cpp @@ -231,8 +231,8 @@ bool FileProperty::extsMatchRunFiles() { auto facilityExtsEnd = facilityExts.cend(); const std::vector<std::string> allowedExts = this->allowedValues(); - for (auto it = allowedExts.begin(); it != allowedExts.end(); ++it) { - if (std::find(facilityExtsBegin, facilityExtsEnd, *it) != + for (const auto &ext : allowedExts) { + if (std::find(facilityExtsBegin, facilityExtsEnd, ext) != facilityExtsEnd) { match = true; break; @@ -279,12 +279,12 @@ std::string FileProperty::setLoadProperty(const std::string &propValue) { toupper); addExtension(upper, exts); } - for (auto it = allowedExts.begin(); it != allowedExts.end(); ++it) { - std::string lower(*it); - std::string upper(*it); - std::transform(it->begin(), it->end(), lower.begin(), tolower); - std::transform(it->begin(), it->end(), upper.begin(), toupper); - addExtension(*it, exts); + for (auto &ext : allowedExts) { + std::string lower(ext); + std::string upper(ext); + std::transform(ext.begin(), ext.end(), lower.begin(), tolower); + std::transform(ext.begin(), ext.end(), upper.begin(), toupper); + addExtension(ext, exts); addExtension(lower, exts); addExtension(upper, exts); } diff --git a/Framework/API/src/FunctionFactory.cpp b/Framework/API/src/FunctionFactory.cpp index c44e9ec25be3110161d9d5e623afcf90208ddd76..80479e1b4e039c3a3b4ffe97e04f254d72d1f5b0 100644 --- a/Framework/API/src/FunctionFactory.cpp +++ b/Framework/API/src/FunctionFactory.cpp @@ -217,8 +217,8 @@ CompositeFunction_sptr FunctionFactoryImpl::createComposite( } cfun->addFunction(fun); size_t i = cfun->nFunctions() - 1; - for (auto att = pAttributes.begin(); att != pAttributes.end(); ++att) { - cfun->setLocalAttributeValue(i, att->first, att->second); + for (auto &pAttribute : pAttributes) { + cfun->setLocalAttributeValue(i, pAttribute.first, pAttribute.second); } } @@ -249,8 +249,8 @@ void FunctionFactoryImpl::inputError(const std::string &str) const { void FunctionFactoryImpl::addConstraints(IFunction_sptr fun, const Expression &expr) const { if (expr.name() == ",") { - for (size_t i = 0; i < expr.size(); i++) { - addConstraint(fun, expr[i]); + for (const auto &constraint : expr) { + addConstraint(fun, constraint); } } else { addConstraint(fun, expr); @@ -279,8 +279,8 @@ void FunctionFactoryImpl::addTies(IFunction_sptr fun, if (expr.name() == "=") { addTie(fun, expr); } else if (expr.name() == ",") { - for (size_t i = 0; i < expr.size(); i++) { - addTie(fun, expr[i]); + for (const auto &constraint : expr) { + addTie(fun, constraint); } } } diff --git a/Framework/API/src/GridDomain.cpp b/Framework/API/src/GridDomain.cpp index 0d8ed05ee4bfc4e91790da93778e2813c2c82d58..c500deb3e9b245b985c50bbff3ca706c478c1797 100644 --- a/Framework/API/src/GridDomain.cpp +++ b/Framework/API/src/GridDomain.cpp @@ -18,18 +18,20 @@ Kernel::Logger g_log("GridDomain"); size_t GridDomain::size() const { if (!m_grids.size()) return 0; - size_t n = 1; - for (auto it = m_grids.begin(); it != m_grids.end(); it++) - n *= (*it)->size(); - return n; + else + return std::accumulate( + m_grids.begin(), m_grids.end(), size_t{1}, + [](size_t n, const boost::shared_ptr<GridDomain> &grid) { + return n * grid->size(); + }); } /// number of dimensions of the grid size_t GridDomain::nDimensions() { - size_t n = 0; - for (auto it = m_grids.begin(); it != m_grids.end(); it++) - n += (*it)->nDimensions(); - return n; + return std::accumulate(m_grids.begin(), m_grids.end(), size_t{0}, + [](size_t n, boost::shared_ptr<GridDomain> &grid) { + return n + grid->nDimensions(); + }); } /* return item of member m_grids @@ -46,8 +48,8 @@ GridDomain_sptr GridDomain::getGrid(size_t index) { } void GridDomain::reScale(const std::string &scaling) { - for (auto it = m_grids.begin(); it != m_grids.end(); it++) - (*it)->reScale(scaling); + for (auto &grid : m_grids) + grid->reScale(scaling); } } // namespace API diff --git a/Framework/API/src/IFunction.cpp b/Framework/API/src/IFunction.cpp index fe6e01ec44d9fc069b24733d0fd32b5082786069..42fc139bec1c9592358d8f1d9734f0d797558db3 100644 --- a/Framework/API/src/IFunction.cpp +++ b/Framework/API/src/IFunction.cpp @@ -128,13 +128,13 @@ void IFunction::addTies(const std::string &ties, bool isDefault) { Expression list; list.parse(ties); list.toList(); - for (auto t = list.begin(); t != list.end(); ++t) { - if (t->name() == "=" && t->size() >= 2) { - size_t n = t->size() - 1; - const std::string value = (*t)[n].str(); + for (const auto &t : list) { + if (t.name() == "=" && t.size() >= 2) { + size_t n = t.size() - 1; + const std::string value = t[n].str(); for (size_t i = n; i != 0;) { --i; - this->tie((*t)[i].name(), value, isDefault); + this->tie(t[i].name(), value, isDefault); } } } @@ -159,9 +159,8 @@ std::string IFunction::asString() const { ostr << "name=" << this->name(); // print the attributes std::vector<std::string> attr = this->getAttributeNames(); - for (size_t i = 0; i < attr.size(); i++) { - std::string attName = attr[i]; - std::string attValue = this->getAttribute(attr[i]).value(); + for (const auto &attName : attr) { + std::string attValue = this->getAttribute(attName).value(); if (!attValue.empty() && attValue != "\"\"") { ostr << ',' << attName << '=' << attValue; } @@ -222,9 +221,9 @@ void IFunction::addConstraints(const std::string &str, bool isDefault) { Expression list; list.parse(str); list.toList(); - for (auto expr = list.begin(); expr != list.end(); ++expr) { + for (const auto &expr : list) { IConstraint *c = - ConstraintFactory::Instance().createInitialized(this, *expr, isDefault); + ConstraintFactory::Instance().createInitialized(this, expr, isDefault); this->addConstraint(c); } } @@ -801,14 +800,13 @@ void IFunction::setMatrixWorkspace( if (!resultUnitStr.empty()) { std::vector<std::string> allUnitStr = Kernel::UnitFactory::Instance().getKeys(); - for (unsigned iUnit = 0; iUnit < allUnitStr.size(); iUnit++) { - size_t found = resultUnitStr.find(allUnitStr[iUnit]); + for (auto &iUnit : allUnitStr) { + size_t found = resultUnitStr.find(iUnit); if (found != std::string::npos) { - size_t len = allUnitStr[iUnit].size(); + size_t len = iUnit.size(); std::stringstream readDouble; Kernel::Unit_sptr unt = - Kernel::UnitFactory::Instance().create( - allUnitStr[iUnit]); + Kernel::UnitFactory::Instance().create(iUnit); readDouble << 1.0 / convertValue(1.0, unt, workspace, wi); resultUnitStr.replace(found, len, readDouble.str()); } @@ -1002,8 +1000,8 @@ void IFunction::setAttributeValue(const std::string &attName, std::vector<std::string> IFunction::getAttributeNames() const { std::vector<std::string> names(nAttributes(), ""); size_t index(0); - for (auto iter = m_attrs.begin(); iter != m_attrs.end(); ++iter) { - names[index] = iter->first; + for (const auto &attr : m_attrs) { + names[index] = attr.first; ++index; } return names; diff --git a/Framework/API/src/IMDEventWorkspace.cpp b/Framework/API/src/IMDEventWorkspace.cpp index 7828791412691129d27513e4d64449ed691d8e8d..fefd831e8a04a6a6aa865edbddf06633bb74312f 100644 --- a/Framework/API/src/IMDEventWorkspace.cpp +++ b/Framework/API/src/IMDEventWorkspace.cpp @@ -55,8 +55,8 @@ const std::string IMDEventWorkspace::toString() const { // Now box controller details std::vector<std::string> stats = getBoxControllerStats(); - for (size_t i = 0; i < stats.size(); i++) { - os << stats[i] << "\n"; + for (auto &stat : stats) { + os << stat << "\n"; } os << MultipleExperimentInfos::toString() << "\n"; diff --git a/Framework/API/src/IPowderDiffPeakFunction.cpp b/Framework/API/src/IPowderDiffPeakFunction.cpp index f619b56a0a727ac6fb0a16e69d87b1014fde97d1..ea300bc3b2bfab24c43ab996fdf198f9160c488a 100644 --- a/Framework/API/src/IPowderDiffPeakFunction.cpp +++ b/Framework/API/src/IPowderDiffPeakFunction.cpp @@ -213,17 +213,12 @@ void IPowderDiffPeakFunction::setPeakRadius(const int &r) { /** Check whether a parameter is a profile parameter */ bool IPowderDiffPeakFunction::hasProfileParameter(std::string paramname) { - std::vector<std::string>::iterator niter; - niter = lower_bound(m_sortedProfileParameterNames.begin(), - m_sortedProfileParameterNames.end(), paramname); - if (niter == m_sortedProfileParameterNames.end()) + auto candname = lower_bound(m_sortedProfileParameterNames.begin(), + m_sortedProfileParameterNames.end(), paramname); + if (candname == m_sortedProfileParameterNames.end()) return false; - std::string candname = *niter; - if (candname.compare(paramname)) - return false; - - return true; + return candname->compare(paramname) != 0; } //------------------------- External Functions diff --git a/Framework/API/src/ImmutableCompositeFunction.cpp b/Framework/API/src/ImmutableCompositeFunction.cpp index 1448918839e69d081f0e6a2ff48e435bda919a77..af20494285249603793137cef6ae92f7bd1e3d80 100644 --- a/Framework/API/src/ImmutableCompositeFunction.cpp +++ b/Framework/API/src/ImmutableCompositeFunction.cpp @@ -37,8 +37,8 @@ void ImmutableCompositeFunction::addFunction(IFunction *fun) { void ImmutableCompositeFunction::setParameter(const std::string &name, const double &value, bool explicitlySet) { - auto alias = m_alias.find(name); - if (alias != m_alias.end()) { + auto alias = m_aliases.find(name); + if (alias != m_aliases.end()) { CompositeFunction::setParameter(alias->second, value, explicitlySet); } else { CompositeFunction::setParameter(name, value, explicitlySet); @@ -52,8 +52,8 @@ void ImmutableCompositeFunction::setParameter(const std::string &name, */ void ImmutableCompositeFunction::setParameterDescription( const std::string &name, const std::string &description) { - auto alias = m_alias.find(name); - if (alias != m_alias.end()) { + auto alias = m_aliases.find(name); + if (alias != m_aliases.end()) { CompositeFunction::setParameterDescription(alias->second, description); } else { CompositeFunction::setParameterDescription(name, description); @@ -66,8 +66,8 @@ void ImmutableCompositeFunction::setParameterDescription( * @return :: The parameter value. */ double ImmutableCompositeFunction::getParameter(const std::string &name) const { - auto alias = m_alias.find(name); - if (alias != m_alias.end()) { + auto alias = m_aliases.find(name); + if (alias != m_aliases.end()) { return CompositeFunction::getParameter(alias->second); } return CompositeFunction::getParameter(name); @@ -79,8 +79,8 @@ double ImmutableCompositeFunction::getParameter(const std::string &name) const { */ size_t ImmutableCompositeFunction::parameterIndex(const std::string &name) const { - auto alias = m_alias.find(name); - if (alias != m_alias.end()) { + auto alias = m_aliases.find(name); + if (alias != m_aliases.end()) { return alias->second; } return CompositeFunction::parameterIndex(name); @@ -90,9 +90,9 @@ ImmutableCompositeFunction::parameterIndex(const std::string &name) const { * Returns the alias or name of parameter i */ std::string ImmutableCompositeFunction::parameterName(size_t i) const { - for (auto alias = m_alias.begin(); alias != m_alias.end(); ++alias) { - if (alias->second == i) - return alias->first; + for (const auto &alias : m_aliases) { + if (alias.second == i) + return alias.first; } return CompositeFunction::parameterName(i); } @@ -107,10 +107,10 @@ std::string ImmutableCompositeFunction::parameterName(size_t i) const { void ImmutableCompositeFunction::setAlias(const std::string &parName, const std::string &alias) { // make sure the alias is unique - if (m_alias.count(alias) > 0) { + if (m_aliases.count(alias) > 0) { throw Kernel::Exception::ExistsError("ImmutableCompositeFunction", alias); } - m_alias[alias] = CompositeFunction::parameterIndex(parName); + m_aliases[alias] = CompositeFunction::parameterIndex(parName); } /** diff --git a/Framework/API/src/JointDomain.cpp b/Framework/API/src/JointDomain.cpp index b489edcd8fd2934fb7d88edbcaad2c234000f149..8ca5de4addb96d17e4d0f7e19a29f1a4d28b34b3 100644 --- a/Framework/API/src/JointDomain.cpp +++ b/Framework/API/src/JointDomain.cpp @@ -2,17 +2,17 @@ // Includes //---------------------------------------------------------------------- #include "MantidAPI/JointDomain.h" +#include <numeric> namespace Mantid { namespace API { /// Return the overall size the domain which is a sum of sizes of the /// member domains. size_t JointDomain::size() const { - size_t n = 0; - for (auto d = m_domains.begin(); d != m_domains.end(); ++d) { - n += (**d).size(); - }; - return n; + return std::accumulate(m_domains.begin(), m_domains.end(), size_t{0}, + [](size_t n, const FunctionDomain_sptr &domain) { + return n + domain->size(); + }); } /// Return the number of parts in the domain size_t JointDomain::getNParts() const { return m_domains.size(); } diff --git a/Framework/API/src/LogManager.cpp b/Framework/API/src/LogManager.cpp index 3b9e88092b1427f9ff953d15f99d2d9f8159d666..6f7738cedef78c5874db15d441bc3ddea672b13c 100644 --- a/Framework/API/src/LogManager.cpp +++ b/Framework/API/src/LogManager.cpp @@ -238,8 +238,7 @@ void LogManager::removeProperty(const std::string &name, bool delProperty) { size_t LogManager::getMemorySize() const { size_t total = 0; std::vector<Property *> props = m_manager.getProperties(); - for (size_t i = 0; i < props.size(); i++) { - Property *p = props[i]; + for (auto p : props) { if (p) total += p->getMemorySize() + sizeof(Property *); } @@ -337,8 +336,8 @@ void LogManager::clearTimeSeriesLogs() { // Loop over the set of properties, identifying those that are time-series // properties // and then clearing them out. - for (auto it = props.begin(); it != props.end(); ++it) { - if (auto tsp = dynamic_cast<ITimeSeriesProperty *>(*it)) { + for (auto prop : props) { + if (auto tsp = dynamic_cast<ITimeSeriesProperty *>(prop)) { tsp->clear(); } } @@ -350,8 +349,8 @@ void LogManager::clearTimeSeriesLogs() { */ void LogManager::clearOutdatedTimeSeriesLogValues() { auto &props = getProperties(); - for (auto it = props.begin(); it != props.end(); ++it) { - if (auto tsp = dynamic_cast<ITimeSeriesProperty *>(*it)) { + for (auto prop : props) { + if (auto tsp = dynamic_cast<ITimeSeriesProperty *>(prop)) { tsp->clearOutdated(); } } @@ -371,9 +370,9 @@ void LogManager::saveNexus(::NeXus::File *file, const std::string &group, // Save all the properties as NXlog std::vector<Property *> props = m_manager.getProperties(); - for (size_t i = 0; i < props.size(); i++) { + for (auto &prop : props) { try { - PropertyNexus::saveProperty(file, props[i]); + PropertyNexus::saveProperty(file, prop); } catch (std::invalid_argument &exc) { g_log.warning(exc.what()); } @@ -398,9 +397,7 @@ void LogManager::loadNexus(::NeXus::File *file, const std::string &group, std::map<std::string, std::string> entries; file->getEntries(entries); - for (auto it = entries.begin(); it != entries.end(); ++it) { - // Get the name/class pair - const std::pair<std::string, std::string> &name_class = *it; + for (const auto &name_class : entries) { // NXLog types are the main one. if (name_class.second == "NXlog") { Property *prop = PropertyNexus::loadProperty(file, name_class.first); diff --git a/Framework/API/src/MDGeometry.cpp b/Framework/API/src/MDGeometry.cpp index 5d119085bb5f0ac34fc14b5f0c4cd16a883e5527..46b07216052a5a9ae2d77a3b0753dbcad04b6c71 100644 --- a/Framework/API/src/MDGeometry.cpp +++ b/Framework/API/src/MDGeometry.cpp @@ -131,11 +131,17 @@ MDGeometry::getDimension(size_t index) const { */ boost::shared_ptr<const Mantid::Geometry::IMDDimension> MDGeometry::getDimensionWithId(std::string id) const { - for (size_t i = 0; i < m_dimensions.size(); ++i) - if (m_dimensions[i]->getDimensionId() == id) - return m_dimensions[i]; - throw std::invalid_argument("Dimension tagged " + id + - " was not found in the Workspace"); + auto dimension = std::find_if( + m_dimensions.begin(), m_dimensions.end(), + [&id]( + const boost::shared_ptr<const Mantid::Geometry::IMDDimension> &dim) { + return dim->getDimensionId() == id; + }); + if (dimension != m_dimensions.end()) + return *dimension; + else + throw std::invalid_argument("Dimension tagged " + id + + " was not found in the Workspace"); } // -------------------------------------------------------------------------------------------- @@ -146,9 +152,7 @@ Mantid::Geometry::VecIMDDimension_const_sptr MDGeometry::getNonIntegratedDimensions() const { using namespace Mantid::Geometry; VecIMDDimension_const_sptr vecCollapsedDimensions; - for (auto it = this->m_dimensions.cbegin(); it != this->m_dimensions.cend(); - ++it) { - IMDDimension_sptr current = (*it); + for (auto current : this->m_dimensions) { if (!current->getIsIntegrated()) { vecCollapsedDimensions.push_back(current); } @@ -282,14 +286,11 @@ void MDGeometry::setBasisVector(size_t index, const Mantid::Kernel::VMD &vec) { * @return True ONLY if ALL the basis vectors have been normalized. */ bool MDGeometry::allBasisNormalized() const { - bool allNormalized = true; - for (auto it = m_basisVectors.begin(); it != m_basisVectors.end(); ++it) { - if (it->length() != 1.0) { - allNormalized = false; - break; - } - } - return allNormalized; + auto normalized = std::find_if(m_basisVectors.begin(), m_basisVectors.end(), + [](const Mantid::Kernel::VMD &basisVector) { + return basisVector.length() != 1.0; + }); + return normalized == m_basisVectors.end(); } //--------------------------------------------------------------------------------------------------- @@ -400,14 +401,13 @@ void MDGeometry::transformDimensions(std::vector<double> &scaling, */ void MDGeometry::deleteNotificationReceived( Mantid::API::WorkspacePreDeleteNotification_ptr notice) { - for (size_t i = 0; i < m_originalWorkspaces.size(); i++) { - Workspace_sptr original = m_originalWorkspaces[i]; + for (auto &original : m_originalWorkspaces) { if (original) { // Compare the pointer being deleted to the one stored as the original. Workspace_sptr deleted = notice->object(); if (original == deleted) { // Clear the reference - m_originalWorkspaces[i].reset(); + original.reset(); } } } diff --git a/Framework/API/src/MatrixWorkspace.cpp b/Framework/API/src/MatrixWorkspace.cpp index 89574de2844a4363adcee4405cff89e2b9db9167..f16b3be474beeb596b027168e1666a7a49b0df1c 100644 --- a/Framework/API/src/MatrixWorkspace.cpp +++ b/Framework/API/src/MatrixWorkspace.cpp @@ -78,8 +78,8 @@ MatrixWorkspace::MatrixWorkspace(const MatrixWorkspace &other) // RJT, 3/10/07: The Analysis Data Service needs to be able to delete // workspaces, so I moved this from protected to public. MatrixWorkspace::~MatrixWorkspace() { - for (unsigned int i = 0; i < m_axes.size(); ++i) { - delete m_axes[i]; + for (auto &axis : m_axes) { + delete axis; } } @@ -469,8 +469,8 @@ detid2index_map MatrixWorkspace::getDetectorIDToWorkspaceIndexMap( map[*detList.begin()] = workspaceIndex; } else { // Allow multiple detectors per workspace index - for (auto it = detList.begin(); it != detList.end(); ++it) - map[*it] = workspaceIndex; + for (auto det : detList) + map[det] = workspaceIndex; } // Ignore if the detector list is empty. @@ -519,12 +519,12 @@ void MatrixWorkspace::getDetectorIDToWorkspaceIndexVector( // Allow multiple detectors per workspace index, or, // If only one is allowed, then this has thrown already - for (auto it = detList.cbegin(); it != detList.cend(); ++it) { - int index = *it + offset; + for (auto det : detList) { + int index = det + offset; if (index < 0 || index >= outSize) { g_log.debug() << "MatrixWorkspace::getDetectorIDToWorkspaceIndexVector(" - "): detector ID found (" << *it - << " at workspace index " << workspaceIndex + "): detector ID found (" + << det << " at workspace index " << workspaceIndex << ") is invalid." << std::endl; } else // Save it at that point. @@ -595,19 +595,18 @@ void MatrixWorkspace::getIndicesFromDetectorIDs( std::map<detid_t, std::set<size_t>> detectorIDtoWSIndices; for (size_t i = 0; i < getNumberHistograms(); ++i) { auto detIDs = getSpectrum(i)->getDetectorIDs(); - for (auto it = detIDs.begin(); it != detIDs.end(); ++it) { - detectorIDtoWSIndices[*it].insert(i); + for (auto detID : detIDs) { + detectorIDtoWSIndices[detID].insert(i); } } indexList.clear(); indexList.reserve(detIdList.size()); - for (size_t j = 0; j < detIdList.size(); ++j) { - auto wsIndices = detectorIDtoWSIndices.find(detIdList[j]); + for (const auto detId : detIdList) { + auto wsIndices = detectorIDtoWSIndices.find(detId); if (wsIndices != detectorIDtoWSIndices.end()) { - for (auto it = wsIndices->second.begin(); it != wsIndices->second.end(); - ++it) { - indexList.push_back(*it); + for (auto index : wsIndices->second) { + indexList.push_back(index); } } } @@ -628,13 +627,13 @@ void MatrixWorkspace::getSpectraFromDetectorIDs( spectraList.clear(); // Try every detector in the list - for (auto it = detIdList.cbegin(); it != detIdList.cend(); ++it) { + for (auto detId : detIdList) { bool foundDet = false; specid_t foundSpecNum = 0; // Go through every histogram for (size_t i = 0; i < this->getNumberHistograms(); i++) { - if (this->getSpectrum(i)->hasDetectorID(*it)) { + if (this->getSpectrum(i)->hasDetectorID(detId)) { foundDet = true; foundSpecNum = this->getSpectrum(i)->getSpectrumNo(); break; @@ -952,7 +951,7 @@ bool &MatrixWorkspace::isDistribution(bool newValue) { * @return whether the workspace contains histogram data */ bool MatrixWorkspace::isHistogramData() const { - return (readX(0).size() == blocksize() ? false : true); + return (readX(0).size() != blocksize()); } /** @@ -1012,11 +1011,11 @@ void MatrixWorkspace::maskWorkspaceIndex(const std::size_t index) { spec->clearData(); const std::set<detid_t> dets = spec->getDetectorIDs(); - for (auto iter = dets.cbegin(); iter != dets.cend(); ++iter) { + for (auto detId : dets) { try { if (const Geometry::Detector *det = dynamic_cast<const Geometry::Detector *>( - sptr_instrument->getDetector(*iter).get())) { + sptr_instrument->getDetector(detId).get())) { m_parmap->addBool(det, "masked", true); // Thread-safe method } } catch (Kernel::Exception::NotFoundError &) { @@ -1097,7 +1096,7 @@ bool MatrixWorkspace::hasMaskedBins(const size_t &workspaceIndex) const { // against throwing here). if (workspaceIndex >= this->getNumberHistograms()) return false; - return (m_masks.find(workspaceIndex) == m_masks.end()) ? false : true; + return m_masks.find(workspaceIndex) != m_masks.end(); } /** Returns the list of masked bins for a spectrum. @@ -1620,9 +1619,9 @@ void MatrixWorkspace::saveSpectraMapNexus( const ::NeXus::NXcompression compression) const { // Count the total number of detectors std::size_t nDetectors = 0; - for (size_t i = 0; i < spec.size(); i++) { - size_t wi = size_t(spec[i]); // Workspace index - nDetectors += this->getSpectrum(wi)->getDetectorIDs().size(); + for (auto index : spec) { + nDetectors += + this->getSpectrum(static_cast<size_t>(index))->getDetectorIDs().size(); } if (nDetectors < 1) { diff --git a/Framework/API/src/ModeratorModel.cpp b/Framework/API/src/ModeratorModel.cpp index 52f068626204cf3de36a37d86b630aa239d3e1c1..b5fe06a7f5cd582958fea4eeefbc359060a166eb 100644 --- a/Framework/API/src/ModeratorModel.cpp +++ b/Framework/API/src/ModeratorModel.cpp @@ -36,8 +36,8 @@ void ModeratorModel::initialize(const std::string ¶ms) { "could be parsed. Check it has the key=value format."); } - for (auto iter = keyValues.begin(); iter != keyValues.end(); ++iter) { - setParameterValue(iter->first, iter->second); + for (auto &keyValue : keyValues) { + setParameterValue(keyValue.first, keyValue.second); } /// Any custom setup diff --git a/Framework/API/src/MultiDomainFunction.cpp b/Framework/API/src/MultiDomainFunction.cpp index c747a669914c5fcef1233a395c23913cb378bb2e..e8a343ca1686c5d69e8bff7a0902e229df1a9b13 100644 --- a/Framework/API/src/MultiDomainFunction.cpp +++ b/Framework/API/src/MultiDomainFunction.cpp @@ -44,9 +44,9 @@ void MultiDomainFunction::setDomainIndices( */ void MultiDomainFunction::countNumberOfDomains() { std::set<size_t> dSet; - for (auto it = m_domains.begin(); it != m_domains.end(); ++it) { - if (it->second.size()) { - dSet.insert(it->second.begin(), it->second.end()); + for (auto &domain : m_domains) { + if (domain.second.size()) { + dSet.insert(domain.second.begin(), domain.second.end()); } } m_nDomains = dSet.size(); @@ -124,11 +124,11 @@ void MultiDomainFunction::function(const FunctionDomain &domain, std::vector<size_t> domains; getDomainIndices(iFun, cd.getNParts(), domains); - for (auto i = domains.begin(); i != domains.end(); ++i) { - const FunctionDomain &d = cd.getDomain(*i); + for (auto &domain : domains) { + const FunctionDomain &d = cd.getDomain(domain); FunctionValues tmp(d); getFunction(iFun)->function(d, tmp); - values.addToCalculated(m_valueOffsets[*i], tmp); + values.addToCalculated(m_valueOffsets[domain], tmp); } } } @@ -162,9 +162,9 @@ void MultiDomainFunction::functionDeriv(const FunctionDomain &domain, std::vector<size_t> domains; getDomainIndices(iFun, cd.getNParts(), domains); - for (auto i = domains.begin(); i != domains.end(); ++i) { - const FunctionDomain &d = cd.getDomain(*i); - PartialJacobian J(&jacobian, m_valueOffsets[*i], paramOffset(iFun)); + for (auto &domain : domains) { + const FunctionDomain &d = cd.getDomain(domain); + PartialJacobian J(&jacobian, m_valueOffsets[domain], paramOffset(iFun)); getFunction(iFun)->functionDeriv(d, J); } } @@ -295,8 +295,8 @@ void MultiDomainFunction::setLocalAttribute(size_t i, } else { // value must be either an int or a list of ints: "a,b,c,..." list.toList(); - for (size_t k = 0; k < list.size(); ++k) { - indx.push_back(boost::lexical_cast<size_t>(list[k].name())); + for (const auto &k : list) { + indx.push_back(boost::lexical_cast<size_t>(k.name())); } } setDomainIndices(i, indx); @@ -319,13 +319,12 @@ MultiDomainFunction::createEquivalentFunctions() const { std::vector<size_t> domains; getDomainIndices(iFun, nDomains, domains); - for (auto i = domains.begin(); i != domains.end(); ++i) { - size_t j = *i; - CompositeFunction_sptr cf = compositeFunctions[j]; + for (auto domainIndex : domains) { + CompositeFunction_sptr cf = compositeFunctions[domainIndex]; if (!cf) { // create a composite function for each domain cf = CompositeFunction_sptr(new CompositeFunction()); - compositeFunctions[j] = cf; + compositeFunctions[domainIndex] = cf; } // add copies of all functions applied to j-th domain to a single // compositefunction diff --git a/Framework/API/src/MultiPeriodGroupWorker.cpp b/Framework/API/src/MultiPeriodGroupWorker.cpp index 1e31be09f804d86dce4cb7554660dace7106fc98..faf3100ca97abad3601361e87b2146859a02c73d 100644 --- a/Framework/API/src/MultiPeriodGroupWorker.cpp +++ b/Framework/API/src/MultiPeriodGroupWorker.cpp @@ -78,10 +78,10 @@ MultiPeriodGroupWorker::findMultiPeriodGroups( sourceAlg->getProperty(this->m_workspacePropertyName); // Inspect all the input workspaces in the ArrayProperty input. - for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { - Workspace_sptr ws = AnalysisDataService::Instance().retrieve(*it); + for (auto &workspace : workspaces) { + Workspace_sptr ws = AnalysisDataService::Instance().retrieve(workspace); if (!ws) { - throw Kernel::Exception::NotFoundError("Workspace", *it); + throw Kernel::Exception::NotFoundError("Workspace", workspace); } tryAddInputWorkspaceToInputGroups(ws, vecWorkspaceGroups); } @@ -91,8 +91,8 @@ MultiPeriodGroupWorker::findMultiPeriodGroups( WorkspaceVector outWorkspaces; sourceAlg->findWorkspaceProperties(inWorkspaces, outWorkspaces); UNUSED_ARG(outWorkspaces); - for (auto it = inWorkspaces.begin(); it != inWorkspaces.end(); ++it) { - tryAddInputWorkspaceToInputGroups(*it, vecWorkspaceGroups); + for (auto &inWorkspace : inWorkspaces) { + tryAddInputWorkspaceToInputGroups(inWorkspace, vecWorkspaceGroups); } } @@ -130,9 +130,8 @@ std::string MultiPeriodGroupWorker::createFormattedInputWorkspaceNames( const size_t &periodIndex, const VecWSGroupType &vecWorkspaceGroups) const { std::string prefix = ""; std::string inputWorkspaces = ""; - for (size_t j = 0; j < vecWorkspaceGroups.size(); ++j) { - inputWorkspaces += - prefix + vecWorkspaceGroups[j]->getItem(periodIndex)->name(); + for (const auto &vecWorkspaceGroup : vecWorkspaceGroups) { + inputWorkspaces += prefix + vecWorkspaceGroup->getItem(periodIndex)->name(); prefix = ","; } return inputWorkspaces; @@ -155,8 +154,7 @@ void MultiPeriodGroupWorker::copyInputWorkspaceProperties( IAlgorithm *targetAlg, IAlgorithm *sourceAlg, const int &periodNumber) const { std::vector<Property *> props = sourceAlg->getProperties(); - for (size_t j = 0; j < props.size(); j++) { - Property *prop = props[j]; + for (auto prop : props) { if (prop) { if (prop->direction() == Direction::Input) { if (const IWorkspaceProperty *wsProp = diff --git a/Framework/API/src/MultipleExperimentInfos.cpp b/Framework/API/src/MultipleExperimentInfos.cpp index e6a2c2891e815d97f3a1a04516129bd7f83372dd..01c60a60f20ff2bf1de8a2e0be3c04b55e187fca 100644 --- a/Framework/API/src/MultipleExperimentInfos.cpp +++ b/Framework/API/src/MultipleExperimentInfos.cpp @@ -97,9 +97,10 @@ uint16_t MultipleExperimentInfos::getNumExperimentInfo() const { void MultipleExperimentInfos::copyExperimentInfos( const MultipleExperimentInfos &other) { m_expInfos.clear(); + m_expInfos.reserve(other.m_expInfos.size()); // Do a deep copy of ExperimentInfo's - for (size_t i = 0; i < other.m_expInfos.size(); i++) { - ExperimentInfo_sptr copy(new ExperimentInfo(*other.m_expInfos[i])); + for (const auto &expInfo : other.m_expInfos) { + ExperimentInfo_sptr copy(new ExperimentInfo(*expInfo)); m_expInfos.push_back(copy); } } diff --git a/Framework/API/src/MultipleFileProperty.cpp b/Framework/API/src/MultipleFileProperty.cpp index b04335cb46dd087fee7e44e341ebf577d1ec5695..d7d699eeb4337c039a05d3a53b4c87f646bc92fd 100644 --- a/Framework/API/src/MultipleFileProperty.cpp +++ b/Framework/API/src/MultipleFileProperty.cpp @@ -29,9 +29,7 @@ Mantid::Kernel::Logger g_log("MultipleFileProperty"); * a "*" wild card in the file extension string passed to it. */ bool doesNotContainWildCard(const std::string &ext) { - if (std::string::npos != ext.find("*")) - return false; - return true; + return std::string::npos == ext.find("*"); } } // anonymous namespace @@ -57,9 +55,9 @@ MultipleFileProperty::MultipleFileProperty(const std::string &name, else m_multiFileLoadingEnabled = false; - for (auto ext = exts.begin(); ext != exts.end(); ++ext) - if (doesNotContainWildCard(*ext)) - m_exts.push_back(*ext); + for (const auto &ext : exts) + if (doesNotContainWildCard(ext)) + m_exts.push_back(ext); } /** @@ -154,8 +152,9 @@ std::vector<std::string> MultipleFileProperty::flattenFileNames( const std::vector<std::vector<std::string>> &fileNames) { std::vector<std::string> flattenedFileNames; - for (auto it = fileNames.cbegin(); it != fileNames.cend(); ++it) { - flattenedFileNames.insert(flattenedFileNames.end(), it->begin(), it->end()); + for (const auto &fileName : fileNames) { + flattenedFileNames.insert(flattenedFileNames.end(), fileName.begin(), + fileName.end()); } return flattenedFileNames; @@ -336,19 +335,14 @@ MultipleFileProperty::setValueAsMultipleFiles(const std::string &propValue) { std::vector<std::string> fullFileNames; - for (auto unresolvedFileName = unresolvedFileNames->begin(); - unresolvedFileName != unresolvedFileNames->end(); - ++unresolvedFileName) { + for (auto &unresolvedFileName : *unresolvedFileNames) { bool useDefaultExt; try { // Check for an extension. - Poco::Path path(*unresolvedFileName); + Poco::Path path(unresolvedFileName); - if (path.getExtension().empty()) - useDefaultExt = true; - else - useDefaultExt = false; + useDefaultExt = path.getExtension().empty(); } catch (Poco::Exception &) { // Just shove the problematic filename straight into FileProperty and // see @@ -361,7 +355,7 @@ MultipleFileProperty::setValueAsMultipleFiles(const std::string &propValue) { if (!useDefaultExt) { FileProperty slaveFileProp("Slave", "", FileProperty::Load, m_exts, Direction::Input); - std::string error = slaveFileProp.setValue(*unresolvedFileName); + std::string error = slaveFileProp.setValue(unresolvedFileName); // If an error was returned then pass it along. if (!error.empty()) { @@ -373,15 +367,15 @@ MultipleFileProperty::setValueAsMultipleFiles(const std::string &propValue) { // If a default ext has been specified/found, then use it. if (!defaultExt.empty()) { fullyResolvedFile = FileFinder::Instance().findRun( - *unresolvedFileName, std::vector<std::string>(1, defaultExt)); + unresolvedFileName, std::vector<std::string>(1, defaultExt)); } else { fullyResolvedFile = - FileFinder::Instance().findRun(*unresolvedFileName, m_exts); + FileFinder::Instance().findRun(unresolvedFileName, m_exts); } if (fullyResolvedFile.empty()) throw std::runtime_error( "Unable to find file matching the string \"" + - *unresolvedFileName + + unresolvedFileName + "\", even after appending suggested file extensions."); } diff --git a/Framework/API/src/NotebookBuilder.cpp b/Framework/API/src/NotebookBuilder.cpp index 48d755c22c8aa6c7d6861921c1560fc4bce27c78..d96d1942c14d33fa269f5b48b99719a670a6c9f2 100644 --- a/Framework/API/src/NotebookBuilder.cpp +++ b/Framework/API/src/NotebookBuilder.cpp @@ -110,8 +110,8 @@ NotebookBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { std::string prop = ""; auto props = algHistory->getProperties(); - for (auto propIter = props.begin(); propIter != props.end(); ++propIter) { - prop = buildPropertyString(*propIter); + for (auto &propIter : props) { + prop = buildPropertyString(propIter); if (prop.length() > 0) { properties << prop << ", "; } @@ -126,11 +126,11 @@ NotebookBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { std::vector<Algorithm_descriptor> descriptors = AlgorithmFactory::Instance().getDescriptors(); - for (auto dit = descriptors.begin(); dit != descriptors.end(); ++dit) { + for (auto &descriptor : descriptors) { // If a newer version of this algorithm exists, then this must be an old // version. - if ((*dit).name == algHistory->name() && - (*dit).version > algHistory->version()) { + if (descriptor.name == algHistory->name() && + descriptor.version > algHistory->version()) { oldVersion = true; break; } diff --git a/Framework/API/src/ParamFunction.cpp b/Framework/API/src/ParamFunction.cpp index 26ac60318a5cd4a13fe6f9b5ced907aae6a4e83b..326252b4f3b0d8f4a5f8711d904d96fd00e3b7f9 100644 --- a/Framework/API/src/ParamFunction.cpp +++ b/Framework/API/src/ParamFunction.cpp @@ -21,12 +21,12 @@ Kernel::Logger g_log("ParamFunction"); /// Destructor ParamFunction::~ParamFunction() { - for (auto it = m_ties.begin(); it != m_ties.end(); ++it) { - delete *it; + for (auto &tie : m_ties) { + delete tie; } m_ties.clear(); - for (auto it = m_constraints.begin(); it != m_constraints.end(); ++it) { - delete *it; + for (auto &constraint : m_constraints) { + delete constraint; } m_constraints.clear(); } @@ -99,7 +99,6 @@ double ParamFunction::getParameter(size_t i) const { void ParamFunction::setParameter(const std::string &name, const double &value, bool explicitlySet) { std::string ucName(name); - // std::transform(name.begin(), name.end(), ucName.begin(), toupper); std::vector<std::string>::const_iterator it = std::find(m_parameterNames.begin(), m_parameterNames.end(), ucName); if (it == m_parameterNames.end()) { @@ -108,8 +107,8 @@ void ParamFunction::setParameter(const std::string &name, const double &value, << ") " << "of function " << this->name(); msg << "\nAllowed parameters: "; - for (size_t ist = 0; ist < m_parameterNames.size(); ++ist) { - msg << m_parameterNames[ist] << ", "; + for (auto ¶meterName : m_parameterNames) { + msg << parameterName << ", "; } throw std::invalid_argument(msg.str()); } @@ -133,8 +132,8 @@ void ParamFunction::setParameterDescription(const std::string &name, msg << "ParamFunction tries to set description to non-exist parameter (" << ucName << "). "; msg << "\nAllowed parameters: "; - for (size_t ist = 0; ist < m_parameterNames.size(); ++ist) - msg << m_parameterNames[ist] << ", "; + for (auto ¶meterName : m_parameterNames) + msg << parameterName << ", "; throw std::invalid_argument(msg.str()); } setParameterDescription(static_cast<int>(it - m_parameterNames.begin()), @@ -157,8 +156,8 @@ double ParamFunction::getParameter(const std::string &name) const { << ucName << ") " << "to function " << this->name(); msg << "\nAllowed parameters: "; - for (size_t ist = 0; ist < m_parameterNames.size(); ++ist) - msg << m_parameterNames[ist] << ", "; + for (const auto ¶meterName : m_parameterNames) + msg << parameterName << ", "; throw std::invalid_argument(msg.str()); } @@ -300,11 +299,11 @@ void ParamFunction::unfix(size_t i) { void ParamFunction::addTie(ParameterTie *tie) { size_t iPar = tie->getIndex(); bool found = false; - for (std::vector<ParameterTie *>::size_type i = 0; i < m_ties.size(); i++) { - if (m_ties[i]->getIndex() == iPar) { + for (auto &m_tie : m_ties) { + if (m_tie->getIndex() == iPar) { found = true; - delete m_ties[i]; - m_ties[i] = tie; + delete m_tie; + m_tie = tie; break; } } @@ -317,8 +316,8 @@ void ParamFunction::addTie(ParameterTie *tie) { * Apply the ties. */ void ParamFunction::applyTies() { - for (auto tie = m_ties.begin(); tie != m_ties.end(); ++tie) { - (**tie).eval(); + for (auto &m_tie : m_ties) { + (*m_tie).eval(); } } @@ -374,10 +373,10 @@ ParameterTie *ParamFunction::getTie(size_t i) const { /** Remove all ties */ void ParamFunction::clearTies() { - for (auto it = m_ties.begin(); it != m_ties.end(); ++it) { - size_t i = getParameterIndex(**it); + for (auto &tie : m_ties) { + size_t i = getParameterIndex(*tie); unfix(i); - delete *it; + delete tie; } m_ties.clear(); } @@ -388,12 +387,11 @@ void ParamFunction::clearTies() { void ParamFunction::addConstraint(IConstraint *ic) { size_t iPar = ic->getIndex(); bool found = false; - for (std::vector<IConstraint *>::size_type i = 0; i < m_constraints.size(); - i++) { - if (m_constraints[i]->getIndex() == iPar) { + for (auto &constraint : m_constraints) { + if (constraint->getIndex() == iPar) { found = true; - delete m_constraints[i]; - m_constraints[i] = ic; + delete constraint; + constraint = ic; break; } } @@ -433,19 +431,19 @@ void ParamFunction::removeConstraint(const std::string &parName) { } void ParamFunction::setUpForFit() { - for (size_t i = 0; i < m_constraints.size(); i++) { - m_constraints[i]->setParamToSatisfyConstraint(); + for (auto &constraint : m_constraints) { + constraint->setParamToSatisfyConstraint(); } } /// Nonvirtual member which removes all declared parameters void ParamFunction::clearAllParameters() { - for (auto it = m_ties.begin(); it != m_ties.end(); ++it) { - delete *it; + for (auto &tie : m_ties) { + delete tie; } m_ties.clear(); - for (auto it = m_constraints.begin(); it != m_constraints.end(); ++it) { - delete *it; + for (auto &constraint : m_constraints) { + delete constraint; } m_constraints.clear(); diff --git a/Framework/API/src/ParameterTie.cpp b/Framework/API/src/ParameterTie.cpp index 1518257b50c3b4e32864b6cade290233654a9a57..af5326381517bcd6474e89f8611de39a9d8114b2 100644 --- a/Framework/API/src/ParameterTie.cpp +++ b/Framework/API/src/ParameterTie.cpp @@ -152,10 +152,10 @@ std::string ParameterTie::asString(const IFunction *fun) const { int iTemp = boost::lexical_cast<int>(res[1]); int i = 0; - for (auto it = m_varMap.cbegin(); it != m_varMap.cend(); ++it) { + for (const auto &var : m_varMap) { if (i == iTemp) { res_expression += - fun->parameterName(fun->getParameterIndex(it->second)); + fun->parameterName(fun->getParameterIndex(var.second)); break; } i++; @@ -176,8 +176,8 @@ std::string ParameterTie::asString(const IFunction *fun) const { * @return True if any of the parameters is used as a variable in the mu::Parser */ bool ParameterTie::findParametersOf(const IFunction *fun) const { - for (auto it = m_varMap.cbegin(); it != m_varMap.cend(); ++it) { - if (it->second.getFunction() == fun) { + for (const auto &varPair : m_varMap) { + if (varPair.second.getFunction() == fun) { return true; } } diff --git a/Framework/API/src/PropertyNexus.cpp b/Framework/API/src/PropertyNexus.cpp index 02083b55ab566249967df3cf3a6b2a86558e0c5f..6d4e9ec76d9f62543180e920e665958462702d9f 100644 --- a/Framework/API/src/PropertyNexus.cpp +++ b/Framework/API/src/PropertyNexus.cpp @@ -145,8 +145,8 @@ Property *loadProperty(::NeXus::File *file, const std::string &group) { // Convert time in seconds to DateAndTime DateAndTime start(startStr); times.reserve(timeSec.size()); - for (size_t i = 0; i < timeSec.size(); i++) { - times.push_back(start + timeSec[i]); + for (double time : timeSec) { + times.push_back(start + time); } } @@ -286,9 +286,9 @@ void saveTimeSeriesPropertyString(::NeXus::File *file, // Find the max length of any string size_t maxlen = 0; - for (size_t i = 0; i < values.size(); i++) - if (values[i].size() > maxlen) - maxlen = values[i].size(); + for (auto &value : values) + if (value.size() > maxlen) + maxlen = value.size(); // Increment by 1 to have the 0 terminator maxlen++; // Copy into one array diff --git a/Framework/API/src/RefAxis.cpp b/Framework/API/src/RefAxis.cpp index f60f806ed7fbe14b7394474de3b59c8cf90ee637..9b975a2459a722d1c09091e170907ff2039a6287 100644 --- a/Framework/API/src/RefAxis.cpp +++ b/Framework/API/src/RefAxis.cpp @@ -86,10 +86,7 @@ bool RefAxis::operator==(const Axis &axis2) const { return false; } const RefAxis *ra2 = dynamic_cast<const RefAxis *>(&axis2); - if (!ra2) { - return false; - } - return true; + return ra2 != nullptr; } /** Check if two numeric axis are equivalent to a given tolerance diff --git a/Framework/API/src/Run.cpp b/Framework/API/src/Run.cpp index 2651921fbb6bbfbbf83df368eccce60cc58bee66..70393726d26927ea71f3fbc285c232e3b1a94200 100644 --- a/Framework/API/src/Run.cpp +++ b/Framework/API/src/Run.cpp @@ -102,14 +102,14 @@ Run &Run::operator+=(const Run &rhs) { mergeMergables(m_manager, rhs.m_manager); // Other properties are added together if they are on the approved list - for (int i = 0; i < ADDABLES; ++i) { - if (rhs.m_manager.existsProperty(ADDABLE[i])) { + for (const auto &name : ADDABLE) { + if (rhs.m_manager.existsProperty(name)) { // get a pointer to the property on the right-hand side workspace - Property *right = rhs.m_manager.getProperty(ADDABLE[i]); + Property *right = rhs.m_manager.getProperty(name); // now deal with the left-hand side - if (m_manager.existsProperty(ADDABLE[i])) { - Property *left = m_manager.getProperty(ADDABLE[i]); + if (m_manager.existsProperty(name)) { + Property *left = m_manager.getProperty(name); left->operator+=(right); } else // no property on the left-hand side, create one and copy the @@ -135,11 +135,10 @@ void Run::splitByTime(TimeSplitterType &splitter, // std::vector<LogManager *> outputsBase(outputs.begin(),outputs.end()); LogManager::splitByTime(splitter, outputs); - size_t n = outputs.size(); // Re-integrate proton charge of all outputs - for (size_t i = 0; i < n; i++) { - if (outputs[i]) { - auto run = dynamic_cast<Run *>(outputs[i]); + for (auto output : outputs) { + if (output) { + auto run = dynamic_cast<Run *>(output); if (run) run->integrateProtonCharge(); } @@ -398,9 +397,7 @@ void Run::loadNexus(::NeXus::File *file, const std::string &group, std::map<std::string, std::string> entries; file->getEntries(entries); - for (auto it = entries.begin(); it != entries.end(); ++it) { - // Get the name/class pair - const std::pair<std::string, std::string> &name_class = *it; + for (const auto &name_class : entries) { if (name_class.second == "NXpositioner") { // Goniometer class m_goniometer.loadNexus(file, name_class.first); @@ -506,15 +503,15 @@ void Run::mergeMergables(Mantid::Kernel::PropertyManager &sum, // get pointers to all the properties on the right-handside and prepare to // loop through them const std::vector<Property *> inc = toAdd.getProperties(); - for (auto it = inc.cbegin(); it != inc.cend(); ++it) { - const std::string rhs_name = (*it)->name(); + for (auto ptr : inc) { + const std::string &rhs_name = ptr->name(); try { // now get pointers to the same properties on the left-handside Property *lhs_prop(sum.getProperty(rhs_name)); - lhs_prop->merge(*it); + lhs_prop->merge(ptr); } catch (Exception::NotFoundError &) { // copy any properties that aren't already on the left hand side - Property *copy = (*it)->clone(); + Property *copy = ptr->clone(); // And we add a copy of that property to *this sum.declareProperty(copy, ""); } diff --git a/Framework/API/src/Sample.cpp b/Framework/API/src/Sample.cpp index 6f0aba1134fb46419fb66e69ee834add02338928..375eb5b786d46810f136637159975514c7c8e894 100644 --- a/Framework/API/src/Sample.cpp +++ b/Framework/API/src/Sample.cpp @@ -193,11 +193,7 @@ void Sample::setCrystalStructure( bool Sample::hasCrystalStructure() const { // Conversion to bool seems to be a problem in VS2012, so this is a bit more // verbose than it should be. - if (m_crystalStructure) { - return true; - } - - return false; + return static_cast<bool>(m_crystalStructure); } /// Destroys the internally stored CrystalStructure-object. diff --git a/Framework/API/src/ScriptBuilder.cpp b/Framework/API/src/ScriptBuilder.cpp index 7868d7e9ed640e7884d5c9bae088a4725cbe80f4..2ebbb038fd4b80a9a5325b4d9f26594c4686f6bb 100644 --- a/Framework/API/src/ScriptBuilder.cpp +++ b/Framework/API/src/ScriptBuilder.cpp @@ -112,9 +112,9 @@ ScriptBuilder::buildCommentString(AlgorithmHistory_const_sptr algHistory) { const std::string name = algHistory->name(); if (name == COMMENT_ALG) { auto props = algHistory->getProperties(); - for (auto propIter = props.begin(); propIter != props.end(); ++propIter) { - if ((*propIter)->name() == "Note") { - comment << "# " << (*propIter)->value(); + for (auto &prop : props) { + if (prop->name() == "Note") { + comment << "# " << prop->value(); } } } @@ -137,8 +137,8 @@ ScriptBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { return buildCommentString(algHistory); auto props = algHistory->getProperties(); - for (auto propIter = props.begin(); propIter != props.end(); ++propIter) { - prop = buildPropertyString(*propIter); + for (auto &propIter : props) { + prop = buildPropertyString(propIter); if (prop.length() > 0) { properties << prop << ", "; } @@ -153,11 +153,11 @@ ScriptBuilder::buildAlgorithmString(AlgorithmHistory_const_sptr algHistory) { std::vector<Algorithm_descriptor> descriptors = AlgorithmFactory::Instance().getDescriptors(); - for (auto dit = descriptors.begin(); dit != descriptors.end(); ++dit) { + for (auto &descriptor : descriptors) { // If a newer version of this algorithm exists, then this must be an old // version. - if ((*dit).name == algHistory->name() && - (*dit).version > algHistory->version()) { + if (descriptor.name == algHistory->name() && + descriptor.version > algHistory->version()) { oldVersion = true; break; } diff --git a/Framework/API/src/WorkspaceGroup.cpp b/Framework/API/src/WorkspaceGroup.cpp index b63ef321a800f8055ea3b88e88e9b07049f8b400..c518849b4be32da072d290943fbebae816b12337 100644 --- a/Framework/API/src/WorkspaceGroup.cpp +++ b/Framework/API/src/WorkspaceGroup.cpp @@ -37,8 +37,8 @@ WorkspaceGroup::~WorkspaceGroup() { observeADSNotifications(false); } const std::string WorkspaceGroup::toString() const { std::string descr = this->id() + "\n"; Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - descr += " -- " + (*it)->name() + "\n"; + for (const auto &workspace : m_workspaces) { + descr += " -- " + workspace->name() + "\n"; } return descr; } @@ -71,16 +71,16 @@ void WorkspaceGroup::observeADSNotifications(const bool observeADS) { } /** - * @param workspace :: A workspace to check. + * @param workspaceToCheck :: A workspace to check. * @return :: True if the workspace is found. */ -bool WorkspaceGroup::isInChildGroup(const Workspace &workspace) const { +bool WorkspaceGroup::isInChildGroup(const Workspace &workspaceToCheck) const { Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto ws = m_workspaces.begin(); ws != m_workspaces.end(); ++ws) { + for (const auto &workspace : m_workspaces) { // check child groups only - WorkspaceGroup *group = dynamic_cast<WorkspaceGroup *>(ws->get()); + WorkspaceGroup *group = dynamic_cast<WorkspaceGroup *>(workspace.get()); if (group) { - if (group->isInGroup(workspace)) + if (group->isInGroup(workspaceToCheck)) return true; } } @@ -112,8 +112,8 @@ void WorkspaceGroup::addWorkspace(Workspace_sptr workspace) { */ bool WorkspaceGroup::contains(const std::string &wsName) const { Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - if ((**it).name() == wsName) + for (const auto &workspace : m_workspaces) { + if ((*workspace).name() == wsName) return true; } return false; @@ -147,8 +147,8 @@ void WorkspaceGroup::reportMembers(std::set<Workspace_sptr> &memberList) const { std::vector<std::string> WorkspaceGroup::getNames() const { Poco::Mutex::ScopedLock _lock(m_mutex); std::vector<std::string> out; - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - out.push_back((**it).name()); + for (const auto &workspace : m_workspaces) { + out.push_back((*workspace).name()); } return out; } @@ -177,9 +177,9 @@ Workspace_sptr WorkspaceGroup::getItem(const size_t index) const { */ Workspace_sptr WorkspaceGroup::getItem(const std::string wsName) const { Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - if ((**it).name() == wsName) - return *it; + for (const auto &workspace : m_workspaces) { + if ((*workspace).name() == wsName) + return workspace; } throw std::out_of_range("Workspace " + wsName + " not contained in the group"); @@ -208,8 +208,8 @@ void WorkspaceGroup::removeByADS(const std::string &wsName) { /// level) void WorkspaceGroup::print() const { Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto itr = m_workspaces.begin(); itr != m_workspaces.end(); ++itr) { - g_log.debug() << "Workspace name in group vector = " << (**itr).name() + for (const auto &workspace : m_workspaces) { + g_log.debug() << "Workspace name in group vector = " << (*workspace).name() << std::endl; } } @@ -273,9 +273,9 @@ void WorkspaceGroup::workspaceReplaceHandle( Poco::Mutex::ScopedLock _lock(m_mutex); const std::string replacedName = notice->objectName(); - for (auto citr = m_workspaces.begin(); citr != m_workspaces.end(); ++citr) { - if ((**citr).name() == replacedName) { - *citr = notice->newObject(); + for (auto &workspace : m_workspaces) { + if ((*workspace).name() == replacedName) { + workspace = notice->newObject(); break; } } @@ -303,8 +303,8 @@ bool WorkspaceGroup::areNamesSimilar() const { return false; // Check all the members are of similar names - for (auto citr = m_workspaces.begin(); citr != m_workspaces.end(); ++citr) { - const std::string wsName = (**citr).name(); + for (const auto &workspace : m_workspaces) { + const std::string wsName = (*workspace).name(); // Find the last underscore _ std::size_t pos = wsName.find_last_of("_"); // No underscore = not similar @@ -331,10 +331,9 @@ bool WorkspaceGroup::isMultiperiod() const { return false; } // Loop through all inner workspaces, checking each one in turn. - for (auto iterator = m_workspaces.cbegin(); iterator != m_workspaces.cend(); - ++iterator) { + for (const auto &workspace : m_workspaces) { if (MatrixWorkspace_sptr ws = - boost::dynamic_pointer_cast<MatrixWorkspace>(*iterator)) { + boost::dynamic_pointer_cast<MatrixWorkspace>(workspace)) { try { Kernel::Property *nPeriodsProp = ws->run().getLogData("nperiods"); int num = -1; @@ -358,24 +357,25 @@ bool WorkspaceGroup::isMultiperiod() const { } /** - * @param workspace :: A workspace to check. + * @param workspaceToCheck :: A workspace to check. * @param level :: The current nesting level. Intended for internal use only by * WorkspaceGroup. * @return :: True if the worspace is found in any of the nested groups in this * group. */ -bool WorkspaceGroup::isInGroup(const Workspace &workspace, size_t level) const { +bool WorkspaceGroup::isInGroup(const Workspace &workspaceToCheck, + size_t level) const { // Check for a cycle. if (level > MAXIMUM_DEPTH) { throw std::runtime_error("WorkspaceGroup nesting level is too deep."); } Poco::Mutex::ScopedLock _lock(m_mutex); - for (auto ws = m_workspaces.begin(); ws != m_workspaces.end(); ++ws) { - if (ws->get() == &workspace) + for (const auto &workspace : m_workspaces) { + if (workspace.get() == &workspaceToCheck) return true; - WorkspaceGroup *group = dynamic_cast<WorkspaceGroup *>(ws->get()); + WorkspaceGroup *group = dynamic_cast<WorkspaceGroup *>(workspace.get()); if (group) { - if (group->isInGroup(workspace, level + 1)) + if (group->isInGroup(workspaceToCheck, level + 1)) return true; } } diff --git a/Framework/API/src/WorkspaceHistory.cpp b/Framework/API/src/WorkspaceHistory.cpp index 6317194090d433ffa106e514dd6edb83c9641739..528c7f674454a91c0e5852bb410d22721431fe9f 100644 --- a/Framework/API/src/WorkspaceHistory.cpp +++ b/Framework/API/src/WorkspaceHistory.cpp @@ -180,9 +180,8 @@ void WorkspaceHistory::saveNexus(::NeXus::File *file) const { // Algorithm History int algCount = 0; - for (auto histIter = m_algorithms.cbegin(); histIter != m_algorithms.cend(); - ++histIter) { - (*histIter)->saveNexus(file, algCount); + for (const auto &algorithm : m_algorithms) { + algorithm->saveNexus(file, algCount); } // close process group @@ -269,8 +268,9 @@ void WorkspaceHistory::loadNestedHistory(::NeXus::File *file, AlgorithmHistory_sptr parent) { // historyNumbers should be sorted by number std::set<int> historyNumbers = findHistoryEntries(file); - for (auto it = historyNumbers.begin(); it != historyNumbers.end(); ++it) { - std::string entryName = "MantidAlgorithm_" + Kernel::Strings::toString(*it); + for (auto historyNumber : historyNumbers) { + std::string entryName = + "MantidAlgorithm_" + Kernel::Strings::toString(historyNumber); std::string rawData; file->openGroup(entryName, "NXnote"); file->readData("data", rawData); @@ -305,8 +305,8 @@ std::set<int> WorkspaceHistory::findHistoryEntries(::NeXus::File *file) { // Histories are numbered MantidAlgorithm_0, ..., MantidAlgorithm_10, etc. // Find all the unique numbers - for (auto it = entries.begin(); it != entries.end(); ++it) { - std::string entryName = it->first; + for (auto &entry : entries) { + std::string entryName = entry.first; if (entryName.find("MantidAlgorithm_") != std::string::npos) { // Just get the number entryName = entryName.substr(16, entryName.size() - 16); diff --git a/Framework/Algorithms/src/AbsorptionCorrection.cpp b/Framework/Algorithms/src/AbsorptionCorrection.cpp index 157502a9dc3a71499d9008ff490c9d629156b052..0715d702cc4bd27a1f0980e0a068f5ffa448a8a7 100644 --- a/Framework/Algorithms/src/AbsorptionCorrection.cpp +++ b/Framework/Algorithms/src/AbsorptionCorrection.cpp @@ -130,9 +130,8 @@ void AbsorptionCorrection::exec() { // If sample not at origin, shift cached positions. const V3D samplePos = m_inputWS->getInstrument()->getSample()->getPos(); if (samplePos != V3D(0, 0, 0)) { - for (auto it = m_elementPositions.begin(); it != m_elementPositions.end(); - ++it) { - (*it) += samplePos; + for (auto &elementPosition : m_elementPositions) { + elementPosition += samplePos; } } diff --git a/Framework/Algorithms/src/AddLogDerivative.cpp b/Framework/Algorithms/src/AddLogDerivative.cpp index ef618c8dc7b5b8f973419a2351fd8e4022e367ed..fa43de6d7e08976f9f3ead4b1603ab7f3ac1af3e 100644 --- a/Framework/Algorithms/src/AddLogDerivative.cpp +++ b/Framework/Algorithms/src/AddLogDerivative.cpp @@ -103,8 +103,8 @@ Mantid::Kernel::TimeSeriesProperty<double> *AddLogDerivative::makeDerivative( DateAndTime start = input->nthTime(0); std::vector<DateAndTime> timeFull; timeFull.reserve(times.size()); - for (size_t i = 0; i < times.size(); i++) - timeFull.push_back(start + times[i]); + for (double time : times) + timeFull.push_back(start + time); // Create the TSP out of it auto out = new TimeSeriesProperty<double>(name); diff --git a/Framework/Algorithms/src/AlignDetectors.cpp b/Framework/Algorithms/src/AlignDetectors.cpp index f1a04f8758fe088639fa0dbf0e9744a948c7abfb..e471dbdf453bfc2d1c65054b99a0a7de0bda55a5 100644 --- a/Framework/Algorithms/src/AlignDetectors.cpp +++ b/Framework/Algorithms/src/AlignDetectors.cpp @@ -91,10 +91,10 @@ public: double difc = 0.; double difa = 0.; double tzero = 0.; - for (auto row = rows.begin(); row != rows.end(); ++row) { - difc += m_difcCol->toDouble(*row); - difa += m_difaCol->toDouble(*row); - tzero += m_tzeroCol->toDouble(*row); + for (auto row : rows) { + difc += m_difcCol->toDouble(row); + difa += m_difaCol->toDouble(row); + tzero += m_tzeroCol->toDouble(row); } if (rows.size() > 1) { double norm = 1. / static_cast<double>(rows.size()); @@ -125,8 +125,8 @@ private: std::set<size_t> getRow(const std::set<detid_t> &detIds) { std::set<size_t> rows; - for (auto detId = detIds.begin(); detId != detIds.end(); ++detId) { - auto rowIter = m_detidToRow.find(*detId); + for (auto detId : detIds) { + auto rowIter = m_detidToRow.find(detId); if (rowIter != m_detidToRow.end()) { // skip if not found rows.insert(rowIter->second); } diff --git a/Framework/Algorithms/src/ChangeTimeZero.cpp b/Framework/Algorithms/src/ChangeTimeZero.cpp index d6f6b8ae6b6008cc6405dc630b6447f3fb2d9cf3..db1f10151eeee65359f1a58a31812276243f364a 100644 --- a/Framework/Algorithms/src/ChangeTimeZero.cpp +++ b/Framework/Algorithms/src/ChangeTimeZero.cpp @@ -171,12 +171,12 @@ void ChangeTimeZero::shiftTimeOfLogs(Mantid::API::MatrixWorkspace_sptr ws, // 2. string properties: here we change the values if they are ISO8601 times auto logs = ws->mutableRun().getLogData(); Progress prog(this, startProgress, stopProgress, logs.size()); - for (auto iter = logs.begin(); iter != logs.end(); ++iter) { - if (isTimeSeries(*iter)) { - shiftTimeInLogForTimeSeries(ws, *iter, timeShift); + for (auto &log : logs) { + if (isTimeSeries(log)) { + shiftTimeInLogForTimeSeries(ws, log, timeShift); } else if (auto stringProperty = - dynamic_cast<PropertyWithValue<std::string> *>(*iter)) { + dynamic_cast<PropertyWithValue<std::string> *>(log)) { shiftTimeOfLogForStringProperty(stringProperty, timeShift); } @@ -356,7 +356,7 @@ bool ChangeTimeZero::checkForDateTime(const std::string &val) const { * @returns true if the offset has been set */ bool ChangeTimeZero::isRelativeTimeShift(double offset) const { - return offset != m_defaultTimeShift ? true : false; + return offset != m_defaultTimeShift; } /** @@ -365,9 +365,7 @@ bool ChangeTimeZero::isRelativeTimeShift(double offset) const { * @returns true if the offset has been set */ bool ChangeTimeZero::isAbsoluteTimeShift(const std::string &offset) const { - return (offset != m_defaultAbsoluteTimeShift && checkForDateTime(offset)) - ? true - : false; + return offset != m_defaultAbsoluteTimeShift && checkForDateTime(offset); } } // namespace Mantid diff --git a/Framework/Algorithms/src/ChopData.cpp b/Framework/Algorithms/src/ChopData.cpp index e071d2db176e90e6236023e44f389f608385c173..258a33f24484afe46feb154083a5483f8c3b8ef7 100644 --- a/Framework/Algorithms/src/ChopData.cpp +++ b/Framework/Algorithms/src/ChopData.cpp @@ -163,8 +163,8 @@ void ChopData::exec() { // Create workspace group that holds output workspaces WorkspaceGroup_sptr wsgroup = WorkspaceGroup_sptr(new WorkspaceGroup()); - for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { - wsgroup->addWorkspace(*it); + for (auto &workspace : workspaces) { + wsgroup->addWorkspace(workspace); } // set the output property setProperty("OutputWorkspace", wsgroup); diff --git a/Framework/Algorithms/src/ClearInstrumentParameters.cpp b/Framework/Algorithms/src/ClearInstrumentParameters.cpp index 3d906b174ae338f195bfdd2de8f6fd1f06ce8895..e82b0d117d4c9c32306a4e5bbb880ed5c2cd929e 100644 --- a/Framework/Algorithms/src/ClearInstrumentParameters.cpp +++ b/Framework/Algorithms/src/ClearInstrumentParameters.cpp @@ -74,15 +74,15 @@ void ClearInstrumentParameters::exec() { ParameterMap::pmap paramsToKeep; // Go through all the parameters, keep a hold of any we don't want to clear. - for (auto paramIt = params->begin(); paramIt != params->end(); ++paramIt) { + for (auto ¶mIt : *params) { // Are we keeping the location parameters? - const std::string pName = (*paramIt).second->name(); + const std::string pName = paramIt.second->name(); if (!clearLocationParams && (pName == "x" || pName == "y" || pName == "z" || pName == "r-position" || pName == "t-position" || pName == "p-position" || pName == "rotx" || pName == "roty" || pName == "rotz")) { - paramsToKeep.insert(*paramIt); + paramsToKeep.insert(paramIt); } } @@ -90,9 +90,8 @@ void ClearInstrumentParameters::exec() { params->clear(); // Add any parameters we're keeping back into the parameter map. - for (auto paramIt = paramsToKeep.begin(); paramIt != paramsToKeep.end(); - ++paramIt) { - params->add((*paramIt).first, (*paramIt).second); + for (auto ¶mIt : paramsToKeep) { + params->add(paramIt.first, paramIt.second); } } diff --git a/Framework/Algorithms/src/CompareWorkspaces.cpp b/Framework/Algorithms/src/CompareWorkspaces.cpp index 26af91da6be756536cc7d80d1b4b0e918d5415e8..cf628fb97dc4aa481d6fade04dcd1a2aa98a9e5e 100644 --- a/Framework/Algorithms/src/CompareWorkspaces.cpp +++ b/Framework/Algorithms/src/CompareWorkspaces.cpp @@ -216,8 +216,7 @@ void CompareWorkspaces::processGroups( const std::vector<Property *> &allProps = this->getProperties(); std::vector<Property *> nonDefaultProps; nonDefaultProps.reserve(allProps.size()); - for (size_t i = 0; i < allProps.size(); ++i) { - Property *p = allProps[i]; + for (auto p : allProps) { const std::string &propName = p->name(); // Skip those not set and the input workspaces if (p->isDefault() || propName == "Workspace1" || propName == "Workspace2") diff --git a/Framework/Algorithms/src/ConvertEmptyToTof.cpp b/Framework/Algorithms/src/ConvertEmptyToTof.cpp index 1203672e158611831e960fb362bdadbc2bd5d227..4cc66b7af20ba567bde07fb5d0006bc514b74496 100644 --- a/Framework/Algorithms/src/ConvertEmptyToTof.cpp +++ b/Framework/Algorithms/src/ConvertEmptyToTof.cpp @@ -131,8 +131,8 @@ void ConvertEmptyToTof::exec() { std::map<int, int> eppMap = findElasticPeakPositions(spectraIndices, channelIndices); - for (auto it = eppMap.begin(); it != eppMap.end(); ++it) { - g_log.debug() << "Spectra idx =" << it->first << ", epp=" << it->second + for (auto &epp : eppMap) { + g_log.debug() << "Spectra idx =" << epp.first << ", epp=" << epp.second << std::endl; } @@ -168,10 +168,10 @@ void ConvertEmptyToTof::validateSpectraIndices(std::vector<int> &v) { for (unsigned int i = 0; i < nHist; ++i) v[i] = i; } else { - for (auto it = v.begin(); it != v.end(); ++it) { - if (*it < 0 || static_cast<size_t>(*it) >= nHist) { + for (auto index : v) { + if (index < 0 || static_cast<size_t>(index) >= nHist) { throw std::runtime_error("Spectra index out of limits: " + - boost::lexical_cast<std::string>(*it)); + boost::lexical_cast<std::string>(index)); } } } @@ -193,10 +193,10 @@ void ConvertEmptyToTof::validateChannelIndices(std::vector<int> &v) { for (unsigned int i = 0; i < blockSize; ++i) v[i] = i; } else { - for (auto it = v.begin(); it != v.end(); ++it) { - if (*it < 0 || static_cast<size_t>(*it) >= blockSize) { + for (auto &index : v) { + if (index < 0 || static_cast<size_t>(index) >= blockSize) { throw std::runtime_error("Channel index out of limits: " + - boost::lexical_cast<std::string>(*it)); + boost::lexical_cast<std::string>(index)); } } } @@ -219,9 +219,8 @@ std::map<int, int> ConvertEmptyToTof::findElasticPeakPositions( g_log.information() << "Peak detection, search for peak " << std::endl; - for (auto it = spectraIndices.begin(); it != spectraIndices.end(); ++it) { + for (auto spectrumIndex : spectraIndices) { - int spectrumIndex = *it; const Mantid::MantidVec &thisSpecY = m_inputWS->dataY(spectrumIndex); int minChannelIndex = *(channelIndices.begin()); @@ -399,9 +398,9 @@ ConvertEmptyToTof::findAverageEppAndEpTof(const std::map<int, int> &eppMap) { std::vector<int> eppList; double firstL2 = getL2(m_inputWS, eppMap.begin()->first); - for (auto it = eppMap.begin(); it != eppMap.end(); ++it) { + for (const auto &epp : eppMap) { - double l2 = getL2(m_inputWS, it->first); + double l2 = getL2(m_inputWS, epp.first); if (!areEqual(l2, firstL2, 0.0001)) { g_log.error() << "firstL2=" << firstL2 << " , " << "l2=" << l2 << std::endl; @@ -414,9 +413,9 @@ ConvertEmptyToTof::findAverageEppAndEpTof(const std::map<int, int> &eppMap) { epTofList.push_back( (calculateTOF(l1, wavelength) + calculateTOF(l2, wavelength)) * 1e6); // microsecs - eppList.push_back(it->first); + eppList.push_back(epp.first); - g_log.debug() << "WS index = " << it->first << ", l1 = " << l1 + g_log.debug() << "WS index = " << epp.first << ", l1 = " << l1 << ", l2 = " << l2 << ", TOF(l1+l2) = " << *(epTofList.end() - 1) << std::endl; } diff --git a/Framework/Algorithms/src/CopyLogs.cpp b/Framework/Algorithms/src/CopyLogs.cpp index ac8cc8976430a67e1308b8675c40a5123f0925a6..6893f3d6f6e732f02fdb303f29d650ef7c20a12b 100644 --- a/Framework/Algorithms/src/CopyLogs.cpp +++ b/Framework/Algorithms/src/CopyLogs.cpp @@ -89,8 +89,7 @@ void CopyLogs::exec() { */ void CopyLogs::mergeReplaceExisting( const std::vector<Kernel::Property *> &inputLogs, Run &outputRun) { - for (auto iter = inputLogs.begin(); iter != inputLogs.end(); ++iter) { - Kernel::Property *prop = *iter; + for (auto prop : inputLogs) { // if the log exists, remove and replace it if (outputRun.hasProperty(prop->name())) { outputRun.removeLogData(prop->name()); @@ -105,8 +104,7 @@ void CopyLogs::mergeReplaceExisting( */ void CopyLogs::mergeKeepExisting( const std::vector<Kernel::Property *> &inputLogs, Run &outputRun) { - for (auto iter = inputLogs.begin(); iter != inputLogs.end(); ++iter) { - Kernel::Property *prop = *iter; + for (auto prop : inputLogs) { // add the log only if it doesn't already exist if (!outputRun.hasProperty(prop->name())) { outputRun.addLogData(prop->clone()); @@ -123,13 +121,13 @@ void CopyLogs::wipeExisting(const std::vector<Kernel::Property *> &inputLogs, auto outputLogs = outputRun.getLogData(); // remove each of the logs from the second workspace - for (auto iter = outputLogs.begin(); iter != outputLogs.end(); ++iter) { - outputRun.removeLogData((*iter)->name()); + for (auto &outputLog : outputLogs) { + outputRun.removeLogData(outputLog->name()); } // add all the logs from the new workspace - for (auto iter = inputLogs.begin(); iter != inputLogs.end(); ++iter) { - outputRun.addLogData((*iter)->clone()); + for (auto inputLog : inputLogs) { + outputRun.addLogData(inputLog->clone()); } } diff --git a/Framework/Algorithms/src/CorelliCrossCorrelate.cpp b/Framework/Algorithms/src/CorelliCrossCorrelate.cpp index 75bfd01219154690408f807d50bf75f27aa7cc33..3662a772e765f856780f61ed595ad797b369692f 100644 --- a/Framework/Algorithms/src/CorelliCrossCorrelate.cpp +++ b/Framework/Algorithms/src/CorelliCrossCorrelate.cpp @@ -164,8 +164,8 @@ void CorelliCrossCorrelate::exec() { int offset_int = getProperty("TimingOffset"); const int64_t offset = static_cast<int64_t>(offset_int); - for (unsigned long i = 0; i < tdc.size(); ++i) - tdc[i] += offset; + for (auto &timing : tdc) + timing += offset; // Determine period from chopper frequency. auto motorSpeed = dynamic_cast<TimeSeriesProperty<double> *>( diff --git a/Framework/Algorithms/src/CorrectToFile.cpp b/Framework/Algorithms/src/CorrectToFile.cpp index 16ffc05612495f12ca72f3ecaea3b4d457acc0f0..8c7bea7a24062cdbe472c23e622deb6d41132f30 100644 --- a/Framework/Algorithms/src/CorrectToFile.cpp +++ b/Framework/Algorithms/src/CorrectToFile.cpp @@ -74,7 +74,7 @@ void CorrectToFile::exec() { const MantidVec &Ecor = rkhInput->readE(0); const bool histogramData = outputWS->isHistogramData(); - const bool divide = (operation == "Divide") ? true : false; + const bool divide = operation == "Divide"; double Yfactor, correctError; const int64_t nOutSpec = diff --git a/Framework/Algorithms/src/CreateCalFileByNames.cpp b/Framework/Algorithms/src/CreateCalFileByNames.cpp index 9f4dfc1a247ca3f2a1576cafe951a5ece57fa324..29ddf8ff74fc763808ab8a85f197ed7a117c6e9c 100644 --- a/Framework/Algorithms/src/CreateCalFileByNames.cpp +++ b/Framework/Algorithms/src/CreateCalFileByNames.cpp @@ -80,9 +80,9 @@ void CreateCalFileByNames::exec() { // Assign incremental number to each group std::map<std::string, int> group_map; int index = 0; - for (auto it = vgroups.begin(); it != vgroups.end(); ++it) { - boost::trim(*it); - group_map[(*it)] = ++index; + for (auto &vgroup : vgroups) { + boost::trim(vgroup); + group_map[vgroup] = ++index; } // Not needed anymore @@ -221,9 +221,9 @@ void CreateCalFileByNames::saveGroupingFile(const std::string &filename, } } else // { - for (auto it = instrcalib.cbegin(); it != instrcalib.cend(); ++it) - writeCalEntry(outfile, (*it).first, ((*it).second).first, 0.0, 1, - ((*it).second).second); + for (const auto &value : instrcalib) + writeCalEntry(outfile, value.first, (value.second).first, 0.0, 1, + (value.second).second); } // Closing diff --git a/Framework/Algorithms/src/CreateDummyCalFile.cpp b/Framework/Algorithms/src/CreateDummyCalFile.cpp index 97f74975568587400c44af91c1d98dcce625ddd2..0485df023b60a1957bf31e1326f7f41b2eb9a721 100644 --- a/Framework/Algorithms/src/CreateDummyCalFile.cpp +++ b/Framework/Algorithms/src/CreateDummyCalFile.cpp @@ -223,9 +223,9 @@ void CreateDummyCalFile::saveGroupingFile(const std::string &filename, } } else // { - for (auto it = instrcalib.cbegin(); it != instrcalib.cend(); ++it) - writeCalEntry(outfile, (*it).first, ((*it).second).first, 0.0, 1, - ((*it).second).second); + for (const auto &value : instrcalib) + writeCalEntry(outfile, value.first, (value.second).first, 0.0, 1, + (value.second).second); } // Closing diff --git a/Framework/Algorithms/src/CreateGroupingWorkspace.cpp b/Framework/Algorithms/src/CreateGroupingWorkspace.cpp index cd3216fa98f77958a2def239409d30eef9fdb421..e731536b5ae9c18ac728a6f7cfc903731ec371ae 100644 --- a/Framework/Algorithms/src/CreateGroupingWorkspace.cpp +++ b/Framework/Algorithms/src/CreateGroupingWorkspace.cpp @@ -241,9 +241,9 @@ void makeGroupingByNames(std::string GroupNames, Instrument_const_sptr inst, // Trim and assign incremental number to each group std::map<std::string, int> group_map; int index = 0; - for (auto it = vgroups.begin(); it != vgroups.end(); ++it) { - boost::trim(*it); - group_map[(*it)] = ++index; + for (auto &vgroup : vgroups) { + boost::trim(vgroup); + group_map[vgroup] = ++index; } // Find Detectors that belong to groups diff --git a/Framework/Algorithms/src/CreateLogPropertyTable.cpp b/Framework/Algorithms/src/CreateLogPropertyTable.cpp index d2e05949367d1fb331a5d1029c25c7cb0deccc1f..249b1236c039707ca6c31303e1de353f73d32b87 100644 --- a/Framework/Algorithms/src/CreateLogPropertyTable.cpp +++ b/Framework/Algorithms/src/CreateLogPropertyTable.cpp @@ -93,27 +93,24 @@ void CreateLogPropertyTable::exec() { this->getProperty("LogPropertyNames"); // Make sure all workspaces contain the properties. - for (auto matrixWs = matrixWsList.begin(); matrixWs != matrixWsList.end(); - ++matrixWs) { - const Run &run = matrixWs->get()->run(); - const std::string wsName = matrixWs->get()->getName(); + for (const auto &matrixWs : matrixWsList) { + const Run &run = matrixWs.get()->run(); + const std::string wsName = matrixWs.get()->getName(); // Throw if a run does not have a property. - for (auto propName = propNames.begin(); propName != propNames.end(); - ++propName) - if (!run.hasProperty(*propName)) + for (const auto &propName : propNames) + if (!run.hasProperty(propName)) throw std::runtime_error("\"" + wsName + "\" does not have a run property of \"" + - *propName + "\"."); + propName + "\"."); } // Set up output table. boost::shared_ptr<ITableWorkspace> outputTable = WorkspaceFactory::Instance().createTable(); // One column for each property. - for (auto propName = propNames.begin(); propName != propNames.end(); - ++propName) - outputTable->addColumn("str", *propName); + for (const auto &propName : propNames) + outputTable->addColumn("str", propName); // One row for each workspace. for (size_t i = 0; i < matrixWsList.size(); ++i) outputTable->appendRow(); @@ -132,13 +129,12 @@ void CreateLogPropertyTable::exec() { TableRow row = outputTable->getRow(i); MatrixWorkspace_sptr matrixWs = matrixWsList[i]; - for (auto propName = propNames.begin(); propName != propNames.end(); - ++propName) { - Property *prop = matrixWs->run().getProperty(*propName); + for (const auto &propName : propNames) { + Property *prop = matrixWs->run().getProperty(propName); std::stringstream propValue; if (prop->type().find("TimeValue") != std::string::npos) { - propValue << matrixWs->run().getLogAsSingleValue(*propName, + propValue << matrixWs->run().getLogAsSingleValue(propName, timeSeriesStat); } else { propValue << prop->value(); @@ -174,12 +170,12 @@ retrieveMatrixWsList(const std::vector<std::string> &wsNames, std::vector<MatrixWorkspace_sptr> matrixWsList; // Get all the workspaces which are to be inspected for log proeprties. - for (auto wsName = wsNames.begin(); wsName != wsNames.end(); ++wsName) { + for (const auto &wsName : wsNames) { WorkspaceGroup_sptr wsGroup = boost::dynamic_pointer_cast<WorkspaceGroup>( - AnalysisDataService::Instance().retrieve(*wsName)); + AnalysisDataService::Instance().retrieve(wsName)); MatrixWorkspace_sptr matrixWs = boost::dynamic_pointer_cast<MatrixWorkspace>( - AnalysisDataService::Instance().retrieve(*wsName)); + AnalysisDataService::Instance().retrieve(wsName)); if (wsGroup) { const std::vector<std::string> childNames = wsGroup->getNames(); @@ -191,20 +187,18 @@ retrieveMatrixWsList(const std::vector<std::string> &wsNames, // Retrieve pointers to all the child workspaces. std::vector<MatrixWorkspace_sptr> childWsList; - for (auto childName = childNames.begin(); childName != childNames.end(); - ++childName) { + for (const auto &childName : childNames) { childWsList.push_back( AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( - *childName)); + childName)); } // Deal with child workspaces according to policy. switch (groupPolicy) { case ALL: { // Append all the children to the list. - for (auto childWs = childWsList.begin(); childWs != childWsList.end(); - ++childWs) - matrixWsList.push_back(*childWs); + for (auto &childWs : childWsList) + matrixWsList.push_back(childWs); break; } case FIRST: @@ -275,8 +269,8 @@ std::set<std::string> getAllGroupPolicyNames() { const std::map<std::string, GroupPolicy> &map = getGroupPolicyMap(); std::set<std::string> groupPolicyNames; - for (auto policy = map.begin(); policy != map.end(); ++policy) - groupPolicyNames.insert(policy->first); + for (const auto &policy : map) + groupPolicyNames.insert(policy.first); return groupPolicyNames; } @@ -330,8 +324,8 @@ std::set<std::string> getAllStatisticTypeNames() { const std::map<std::string, Math::StatisticType> &map = getStatisticTypeMap(); std::set<std::string> statisticTypeNames; - for (auto policy = map.begin(); policy != map.end(); ++policy) - statisticTypeNames.insert(policy->first); + for (const auto &policy : map) + statisticTypeNames.insert(policy.first); return statisticTypeNames; } diff --git a/Framework/Algorithms/src/CreateLogTimeCorrection.cpp b/Framework/Algorithms/src/CreateLogTimeCorrection.cpp index af34e115b26676747089958fc8fda88995b96264..f82a8c43d5f15de9f02cc8f858d456c589840287 100644 --- a/Framework/Algorithms/src/CreateLogTimeCorrection.cpp +++ b/Framework/Algorithms/src/CreateLogTimeCorrection.cpp @@ -108,11 +108,11 @@ void CreateLogTimeCorrection::getInstrumentSetup() { // 2. Get detector IDs std::vector<detid_t> detids = m_instrument->getDetectorIDs(true); - for (size_t i = 0; i < detids.size(); ++i) { - IDetector_const_sptr detector = m_instrument->getDetector(detids[i]); + for (auto &detid : detids) { + IDetector_const_sptr detector = m_instrument->getDetector(detid); V3D detpos = detector->getPos(); double l2 = detpos.distance(samplepos); - m_l2map.emplace(detids[i], l2); + m_l2map.emplace(detid, l2); } // 3. Output information diff --git a/Framework/Algorithms/src/CreatePSDBleedMask.cpp b/Framework/Algorithms/src/CreatePSDBleedMask.cpp index 63317cf6ad48bb64abc8d5b9c4257053374b095e..3ee0438ad8114d343765e0a847ae74429e802795 100644 --- a/Framework/Algorithms/src/CreatePSDBleedMask.cpp +++ b/Framework/Algorithms/src/CreatePSDBleedMask.cpp @@ -268,8 +268,8 @@ bool CreatePSDBleedMask::performBleedTest( void CreatePSDBleedMask::maskTube(const std::vector<int> &tubeIndices, API::MatrixWorkspace_sptr workspace) { const double deadValue(1.0); // delete the data - for (auto citr = tubeIndices.cbegin(); citr != tubeIndices.cend(); ++citr) { - workspace->dataY(*citr)[0] = deadValue; + for (auto tubeIndice : tubeIndices) { + workspace->dataY(tubeIndice)[0] = deadValue; } } } diff --git a/Framework/Algorithms/src/CreateSampleWorkspace.cpp b/Framework/Algorithms/src/CreateSampleWorkspace.cpp index 9508bde6f9d5f400fba32e85b63a11d71e4665a2..a27220d8c83deace522d9835a86589597f0e59cf 100644 --- a/Framework/Algorithms/src/CreateSampleWorkspace.cpp +++ b/Framework/Algorithms/src/CreateSampleWorkspace.cpp @@ -107,9 +107,8 @@ void CreateSampleWorkspace::init() { m_preDefinedFunctionmap.emplace("User Defined", ""); std::vector<std::string> functionOptions; functionOptions.reserve(m_preDefinedFunctionmap.size()); - for (auto iterator = m_preDefinedFunctionmap.begin(); - iterator != m_preDefinedFunctionmap.end(); iterator++) { - functionOptions.push_back(iterator->first); + for (const auto &preDefinedFunction : m_preDefinedFunctionmap) { + functionOptions.push_back(preDefinedFunction.first); } declareProperty("Function", "One Peak", boost::make_shared<StringListValidator>(functionOptions), diff --git a/Framework/Algorithms/src/DetectorDiagnostic.cpp b/Framework/Algorithms/src/DetectorDiagnostic.cpp index ce72c899bdcf38f868a0b8492dd59bf1b4cbec05..6c02598738b4cab27cea0e86e3a3d7d6e0ee5008 100644 --- a/Framework/Algorithms/src/DetectorDiagnostic.cpp +++ b/Framework/Algorithms/src/DetectorDiagnostic.cpp @@ -618,10 +618,8 @@ DetectorDiagnostic::calculateMedian(const API::MatrixWorkspace_sptr input, std::vector<double> medianvec; g_log.debug("Calculating the median count rate of the spectra"); - for (size_t j = 0; j < indexmap.size(); ++j) { + for (auto hists : indexmap) { std::vector<double> medianInput; - std::vector<size_t> hists = indexmap.at(j); - const int nhists = static_cast<int>(hists.size()); // The maximum possible length is that of workspace length medianInput.reserve(nhists); diff --git a/Framework/Algorithms/src/DiffractionFocussing2.cpp b/Framework/Algorithms/src/DiffractionFocussing2.cpp index d06198dab577561677444e25484843ec52ee1f10..6ae37f4b7246b8586d7a241e9d703910948c7faa 100644 --- a/Framework/Algorithms/src/DiffractionFocussing2.cpp +++ b/Framework/Algorithms/src/DiffractionFocussing2.cpp @@ -245,8 +245,8 @@ void DiffractionFocussing2::exec() { m_matrixInputW->maskedBins(i); // Now iterate over the list, adjusting the weights for the affected // bins - for (auto it = mask.cbegin(); it != mask.cend(); ++it) { - const double currentX = Xin[(*it).first]; + for (const auto &bin : mask) { + const double currentX = Xin[bin.first]; // Add an intermediate bin with full weight if masked bins aren't // consecutive if (weight_bins.back() != currentX) { @@ -255,8 +255,8 @@ void DiffractionFocussing2::exec() { } // The weight for this masked bin is 1 - the degree to which this bin // is masked - weights.push_back(1.0 - (*it).second); - weight_bins.push_back(Xin[(*it).first + 1]); + weights.push_back(1.0 - bin.second); + weight_bins.push_back(Xin[bin.first + 1]); } // Add on a final bin with full weight if masking doesn't go up to the // end @@ -368,8 +368,8 @@ void DiffractionFocussing2::execEvent() { const vector<size_t> &indices = this->m_wsIndices[group]; totalHistProcess += static_cast<int>(indices.size()); - for (auto index = indices.cbegin(); index != indices.cend(); ++index) { - size_required[iGroup] += m_eventW->getEventList(*index).getNumberEvents(); + for (auto index : indices) { + size_required[iGroup] += m_eventW->getEventList(index).getNumberEvents(); } prog->report(1, "Pre-counting"); } @@ -454,9 +454,7 @@ void DiffractionFocussing2::execEvent() { PARALLEL_START_INTERUPT_REGION const int group = this->m_validGroups[iGroup]; const std::vector<size_t> &indices = this->m_wsIndices[group]; - for (size_t i = 0; i < indices.size(); i++) { - size_t wi = indices[i]; - + for (auto wi : indices) { // In workspace index iGroup, put what was in the OLD workspace index wi out->getOrAddEventList(iGroup) += m_eventW->getEventList(wi); diff --git a/Framework/Algorithms/src/ExponentialCorrection.cpp b/Framework/Algorithms/src/ExponentialCorrection.cpp index e67649e41915a6bb9181227ba5e9b4df6d264efe..2c3d38864ece6245206acce335672e04a93f8bc3 100644 --- a/Framework/Algorithms/src/ExponentialCorrection.cpp +++ b/Framework/Algorithms/src/ExponentialCorrection.cpp @@ -42,7 +42,7 @@ void ExponentialCorrection::retrieveProperties() { m_c0 = getProperty("C0"); m_c1 = getProperty("C1"); std::string op = getProperty("Operation"); - m_divide = (op == "Divide") ? true : false; + m_divide = op == "Divide"; } void ExponentialCorrection::performUnaryOperation(const double XIn, diff --git a/Framework/Algorithms/src/FilterEvents.cpp b/Framework/Algorithms/src/FilterEvents.cpp index f9e9d115ceea6fe27484bfcc0b6f6f2e1d57084b..9f9b6b5ec4dd1b1487e171f18dd555aec3298b39 100644 --- a/Framework/Algorithms/src/FilterEvents.cpp +++ b/Framework/Algorithms/src/FilterEvents.cpp @@ -507,9 +507,7 @@ void FilterEvents::createOutputWorkspaces() { // Determine the minimum group index number int minwsgroup = INT_MAX; - for (auto groupit = m_workGroupIndexes.begin(); - groupit != m_workGroupIndexes.end(); ++groupit) { - int wsgroup = *groupit; + for (auto wsgroup : m_workGroupIndexes) { if (wsgroup < minwsgroup && wsgroup >= 0) minwsgroup = wsgroup; } @@ -1027,8 +1025,7 @@ void FilterEvents::filterEventsByVectorSplitters(double progressamount) { void FilterEvents::generateSplitters(int wsindex, Kernel::TimeSplitterType &splitters) { splitters.clear(); - for (size_t isp = 0; isp < m_splitters.size(); ++isp) { - Kernel::SplittingInterval splitter = m_splitters[isp]; + for (auto splitter : m_splitters) { int index = splitter.index(); if (index == wsindex) { splitters.push_back(splitter); @@ -1052,8 +1049,7 @@ void FilterEvents::splitLog(EventWorkspace_sptr eventws, std::string logname, << std::endl; return; } else { - for (size_t i = 0; i < splitters.size(); ++i) { - SplittingInterval split = splitters[i]; + for (auto split : splitters) { g_log.debug() << "[FilterEvents DB1226] Going to filter workspace " << eventws->name() << ": " << "log name = " << logname @@ -1075,9 +1071,9 @@ void FilterEvents::getTimeSeriesLogNames(std::vector<std::string> &lognames) { const std::vector<Kernel::Property *> allprop = m_eventWS->mutableRun().getProperties(); - for (size_t ip = 0; ip < allprop.size(); ++ip) { + for (auto ip : allprop) { Kernel::TimeSeriesProperty<double> *timeprop = - dynamic_cast<Kernel::TimeSeriesProperty<double> *>(allprop[ip]); + dynamic_cast<Kernel::TimeSeriesProperty<double> *>(ip); if (timeprop) { std::string pname = timeprop->name(); lognames.push_back(pname); diff --git a/Framework/Algorithms/src/FitPeak.cpp b/Framework/Algorithms/src/FitPeak.cpp index ae34fe7f5e64d13f15ddddbf8060ab30df7fd34a..3d217dfb74a91f1d221636d66f0f944e95f0c449 100644 --- a/Framework/Algorithms/src/FitPeak.cpp +++ b/Framework/Algorithms/src/FitPeak.cpp @@ -1268,16 +1268,16 @@ std::vector<std::string> FitPeak::addFunctionParameterNames(std::vector<std::string> funcnames) { vector<string> vec_funcparnames; - for (size_t i = 0; i < funcnames.size(); ++i) { + for (auto &funcname : funcnames) { // Add original name in - vec_funcparnames.push_back(funcnames[i]); + vec_funcparnames.push_back(funcname); // Add a full function name and parameter names in IFunction_sptr tempfunc = - FunctionFactory::Instance().createFunction(funcnames[i]); + FunctionFactory::Instance().createFunction(funcname); stringstream parnamess; - parnamess << funcnames[i] << " ("; + parnamess << funcname << " ("; vector<string> funcpars = tempfunc->getParameterNames(); for (size_t j = 0; j < funcpars.size(); ++j) { parnamess << funcpars[j]; @@ -1586,18 +1586,18 @@ void FitPeak::setupOutput( // Parameter vector vector<double> vec_fitpeak; - for (size_t i = 0; i < m_peakParameterNames.size(); ++i) { - double value = m_peakFunc->getParameter(m_peakParameterNames[i]); - vec_fitpeak.push_back(value); + vec_fitpeak.reserve(m_peakParameterNames.size()); + for (auto &peakParameterName : m_peakParameterNames) { + vec_fitpeak.push_back(m_peakFunc->getParameter(peakParameterName)); } setProperty("FittedPeakParameterValues", vec_fitpeak); // Background vector<double> vec_fitbkgd; - for (size_t i = 0; i < m_bkgdParameterNames.size(); ++i) { - double value = m_bkgdFunc->getParameter(m_bkgdParameterNames[i]); - vec_fitbkgd.push_back(value); + vec_fitpeak.reserve(m_bkgdParameterNames.size()); + for (auto &bkgdParameterName : m_bkgdParameterNames) { + vec_fitbkgd.push_back(m_bkgdFunc->getParameter(bkgdParameterName)); } setProperty("FittedBackgroundParameterValues", vec_fitbkgd); @@ -1677,8 +1677,7 @@ TableWorkspace_sptr FitPeak::genOutputTableWS( if (m_outputRawParams) { vector<string> peakparnames = peakfunc->getParameterNames(); - for (size_t i = 0; i < peakparnames.size(); ++i) { - string &parname = peakparnames[i]; + for (auto &parname : peakparnames) { double parvalue = peakfunc->getParameter(parname); double error = peakerrormap[parname]; newrow = outtablews->appendRow(); @@ -1701,8 +1700,7 @@ TableWorkspace_sptr FitPeak::genOutputTableWS( if (m_outputRawParams) { vector<string> bkgdparnames = bkgdfunc->getParameterNames(); - for (size_t i = 0; i < bkgdparnames.size(); ++i) { - string &parname = bkgdparnames[i]; + for (auto &parname : bkgdparnames) { double parvalue = bkgdfunc->getParameter(parname); double error = bkgderrormap[parname]; newrow = outtablews->appendRow(); diff --git a/Framework/Algorithms/src/FixGSASInstrumentFile.cpp b/Framework/Algorithms/src/FixGSASInstrumentFile.cpp index 17d9a1014cdbe1e74ba29d46cec2c93e6332c02f..efa3963cef0025130e871ee3126f9418739090b0 100644 --- a/Framework/Algorithms/src/FixGSASInstrumentFile.cpp +++ b/Framework/Algorithms/src/FixGSASInstrumentFile.cpp @@ -98,8 +98,7 @@ void FixGSASInstrumentFile::exec() { throw runtime_error(errss.str()); } - for (size_t i = 0; i < vec_line.size(); ++i) { - string &line = vec_line[i]; + for (auto &line : vec_line) { ofile << line; for (size_t j = line.size(); j < LINESIZE; ++j) ofile << " "; diff --git a/Framework/Algorithms/src/GenerateEventsFilter.cpp b/Framework/Algorithms/src/GenerateEventsFilter.cpp index eed4d7e81674b453bee9be780bdfdcb968275e31..b55c4e821fd9d28df98253bf664e90c8483c6dfa 100644 --- a/Framework/Algorithms/src/GenerateEventsFilter.cpp +++ b/Framework/Algorithms/src/GenerateEventsFilter.cpp @@ -748,11 +748,10 @@ void GenerateEventsFilter::processMultipleValueFilters(double minvalue, // Debug print stringstream dbsplitss; dbsplitss << "Index map size = " << indexwsindexmap.size() << "\n"; - for (auto mit = indexwsindexmap.begin(); mit != indexwsindexmap.end(); - ++mit) { - dbsplitss << "Index " << mit->first << ": WS-group = " << mit->second - << ". Log value range: [" << logvalueranges[mit->first * 2] - << ", " << logvalueranges[mit->first * 2 + 1] << ").\n"; + for (auto &mit : indexwsindexmap) { + dbsplitss << "Index " << mit.first << ": WS-group = " << mit.second + << ". Log value range: [" << logvalueranges[mit.first * 2] << ", " + << logvalueranges[mit.first * 2 + 1] << ").\n"; } g_log.information(dbsplitss.str()); diff --git a/Framework/Algorithms/src/GeneratePeaks.cpp b/Framework/Algorithms/src/GeneratePeaks.cpp index e30b238afbd27f71b9f2434d030b8728c636434f..b5b4d043d5a755a0e9a92494bd049d8a05471aad 100644 --- a/Framework/Algorithms/src/GeneratePeaks.cpp +++ b/Framework/Algorithms/src/GeneratePeaks.cpp @@ -572,8 +572,8 @@ void GeneratePeaks::processTableColumnNames() { << " does not have paramter " << m_funcParameterNames[i] << "\n" << "Allowed function parameters are "; std::vector<std::string> parnames = m_peakFunction->getParameterNames(); - for (size_t k = 0; k < parnames.size(); ++k) - errss << parnames[k] << ", "; + for (auto &parname : parnames) + errss << parname << ", "; throw std::runtime_error(errss.str()); } } @@ -692,10 +692,7 @@ bool GeneratePeaks::hasParameter(API::IFunction_sptr function, std::vector<std::string> parnames = function->getParameterNames(); std::vector<std::string>::iterator piter; piter = std::find(parnames.begin(), parnames.end(), paramname); - if (piter != parnames.end()) - return true; - - return false; + return piter != parnames.end(); } //---------------------------------------------------------------------------------------------- @@ -815,16 +812,16 @@ std::vector<std::string> GeneratePeaks::addFunctionParameterNames(std::vector<std::string> funcnames) { std::vector<std::string> vec_funcparnames; - for (size_t i = 0; i < funcnames.size(); ++i) { + for (auto &funcname : funcnames) { // Add original name in - vec_funcparnames.push_back(funcnames[i]); + vec_funcparnames.push_back(funcname); // Add a full function name and parameter names in IFunction_sptr tempfunc = - FunctionFactory::Instance().createFunction(funcnames[i]); + FunctionFactory::Instance().createFunction(funcname); std::stringstream parnamess; - parnamess << funcnames[i] << " ("; + parnamess << funcname << " ("; std::vector<std::string> funcpars = tempfunc->getParameterNames(); for (size_t j = 0; j < funcpars.size(); ++j) { parnamess << funcpars[j]; diff --git a/Framework/Algorithms/src/GetAllEi.cpp b/Framework/Algorithms/src/GetAllEi.cpp index 5e6974ff5ecdd736a82faa427115fbeef6ab6008..8ed2d0ae48c10da1121a5de4673223137d0425d1 100644 --- a/Framework/Algorithms/src/GetAllEi.cpp +++ b/Framework/Algorithms/src/GetAllEi.cpp @@ -272,8 +272,8 @@ void GetAllEi::exec() { destUnit->initialize(mon1Distance, 0., 0., static_cast<int>(Kernel::DeltaEMode::Elastic), 0., unused); - for (size_t i = 0; i < guess_opening.size(); i++) { - double eGuess = destUnit->singleFromTOF(guess_opening[i]); + for (double time : guess_opening) { + double eGuess = destUnit->singleFromTOF(time); if (eGuess > eMin && eGuess < eMax) { guess_ei.push_back(eGuess); } @@ -282,8 +282,8 @@ void GetAllEi::exec() { boost::lexical_cast<std::string>(guess_ei.size()) + " fell within both monitor's recording energy range\n"; g_log.debug() << " Guess Energies are:\n"; - for (size_t i = 0; i < guess_ei.size(); i++) { - g_log.debug() << boost::str(boost::format(" %8.2f; ") % guess_ei[i]); + for (double ei : guess_ei) { + g_log.debug() << boost::str(boost::format(" %8.2f; ") % ei); } g_log.debug() << std::endl; @@ -399,13 +399,13 @@ void GetAllEi::printDebugModeInfo(const std::vector<double> &guess_opening, << " chopper prospective opening within time frame: " << TOF_range.first << " to: " << TOF_range.second << std::endl; g_log.debug() << " Timings are:\n"; - for (size_t i = 0; i < guess_opening.size(); i++) { - g_log.debug() << boost::str(boost::format(" %8.2f; ") % guess_opening[i]); + for (double time : guess_opening) { + g_log.debug() << boost::str(boost::format(" %8.2f; ") % time); } g_log.debug() << std::endl; g_log.debug() << " Corresponding to energies:\n"; - for (size_t i = 0; i < guess_opening.size(); i++) { - double ei = destUnit->singleFromTOF(guess_opening[i]); + for (double time : guess_opening) { + double ei = destUnit->singleFromTOF(time); g_log.debug() << boost::str(boost::format(" %8.2f; ") % ei); } g_log.debug() << std::endl; diff --git a/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp b/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp index 491ccf9f3005b4014fc4f25a1917c5575c89d3df..e42af2ac5c696d285d0a4d849cf28899008c61c0 100644 --- a/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp +++ b/Framework/Algorithms/src/GetDetOffsetsMultiPeaks.cpp @@ -1148,9 +1148,9 @@ void GetDetOffsetsMultiPeaks::createInformationWorkspaces() { // set up columns m_peakOffsetTableWS->addColumn("int", "WorkspaceIndex"); - for (size_t i = 0; i < m_peakPositions.size(); ++i) { + for (double m_peakPosition : m_peakPositions) { std::stringstream namess; - namess << "@" << std::setprecision(5) << m_peakPositions[i]; + namess << "@" << std::setprecision(5) << m_peakPosition; m_peakOffsetTableWS->addColumn("str", namess.str()); } m_peakOffsetTableWS->addColumn("double", "OffsetDeviation"); diff --git a/Framework/Algorithms/src/GetTimeSeriesLogInformation.cpp b/Framework/Algorithms/src/GetTimeSeriesLogInformation.cpp index 22029c70c9be8a9584ee17381e39be15249c798d..df50000ad3a1428c7eea4d65b3326502858cfa10 100644 --- a/Framework/Algorithms/src/GetTimeSeriesLogInformation.cpp +++ b/Framework/Algorithms/src/GetTimeSeriesLogInformation.cpp @@ -276,10 +276,9 @@ TableWorkspace_sptr GetTimeSeriesLogInformation::generateStatisticTable() { tablews->addColumn("double", "Value"); // 1. Integer part - for (auto intmapiter = m_intInfoMap.begin(); intmapiter != m_intInfoMap.end(); - ++intmapiter) { - string name = intmapiter->first; - size_t value = intmapiter->second; + for (auto &intmapiter : m_intInfoMap) { + string name = intmapiter.first; + size_t value = intmapiter.second; TableRow newrow = tablews->appendRow(); newrow << name << static_cast<double>(value); @@ -406,8 +405,7 @@ Workspace2D_sptr GetTimeSeriesLogInformation::calDistributions( vecCount[i] = 0; // 3. Count - for (size_t i = 0; i < vecdt.size(); ++i) { - double dt = vecdt[i]; + for (double dt : vecdt) { int index; if (dt < 0 && m_ignoreNegativeTime) { index = 0; @@ -418,7 +416,7 @@ Workspace2D_sptr GetTimeSeriesLogInformation::calDistributions( // Out of upper boundary g_log.error() << "Find index = " << index << " > vecX.size = " << vecDeltaT.size() << ".\n"; - } else if (vecdt[i] < vecDeltaT[index]) { + } else if (dt < vecDeltaT[index]) { --index; } diff --git a/Framework/Algorithms/src/GroupWorkspaces.cpp b/Framework/Algorithms/src/GroupWorkspaces.cpp index 66f81de9bb97ea2b0d35414f953b1920fbccb5b6..df14cce79ced80d12c3fbd1a4a662bc4c3f0c0a4 100644 --- a/Framework/Algorithms/src/GroupWorkspaces.cpp +++ b/Framework/Algorithms/src/GroupWorkspaces.cpp @@ -51,8 +51,8 @@ void GroupWorkspaces::exec() { void GroupWorkspaces::addToGroup(const std::vector<std::string> &names) { AnalysisDataServiceImpl &ads = AnalysisDataService::Instance(); - for (auto citr = names.cbegin(); citr != names.cend(); ++citr) { - auto workspace = ads.retrieve(*citr); + for (const auto &name : names) { + auto workspace = ads.retrieve(name); addToGroup(workspace); } } diff --git a/Framework/Algorithms/src/IntegrateByComponent.cpp b/Framework/Algorithms/src/IntegrateByComponent.cpp index 369e061bbb0a3cd79c4bcd797c9bee351f63dac4..5113ea1825fb584f0647bf17ec59ccf04b91019e 100644 --- a/Framework/Algorithms/src/IntegrateByComponent.cpp +++ b/Framework/Algorithms/src/IntegrateByComponent.cpp @@ -78,9 +78,8 @@ void IntegrateByComponent::exec() { std::vector<std::vector<size_t>> specmap = makeMap(integratedWS, parents); API::Progress prog(this, 0.3, 1.0, specmap.size()); // calculate averages - for (size_t j = 0; j < specmap.size(); ++j) { + for (auto hists : specmap) { prog.report(); - std::vector<size_t> hists = specmap.at(j); std::vector<double> averageYInput, averageEInput; Geometry::Instrument_const_sptr instrument = integratedWS->getInstrument(); diff --git a/Framework/Algorithms/src/MaskBins.cpp b/Framework/Algorithms/src/MaskBins.cpp index 4596c5ef4551a2643008c17053d70090347f390a..251dc10e15a5cf12d6a42f67a53e204fb0f4a196 100644 --- a/Framework/Algorithms/src/MaskBins.cpp +++ b/Framework/Algorithms/src/MaskBins.cpp @@ -78,8 +78,7 @@ void MaskBins::exec() { if (this->spectra_list.size() > 0) { const int numHist = static_cast<int>(inputWS->getNumberHistograms()); //--- Validate spectra list --- - for (size_t i = 0; i < this->spectra_list.size(); ++i) { - int wi = this->spectra_list[i]; + for (auto wi : this->spectra_list) { if ((wi < 0) || (wi >= numHist)) { std::ostringstream oss; oss << "One of the workspace indices specified, " << wi diff --git a/Framework/Algorithms/src/MaskDetectorsIf.cpp b/Framework/Algorithms/src/MaskDetectorsIf.cpp index d4bdb1e9bb32232494f902c58cd270c36d071472..b955b1206888ece4fa0cdfb6eb2b7eee4b4fd4a3 100644 --- a/Framework/Algorithms/src/MaskDetectorsIf.cpp +++ b/Framework/Algorithms/src/MaskDetectorsIf.cpp @@ -168,7 +168,7 @@ void MaskDetectorsIf::createNewCalFile(const std::string &oldfile, bool selection; if (it == umap.end()) - selection = (sel == 0) ? false : true; + selection = sel != 0; else selection = (*it).second; diff --git a/Framework/Algorithms/src/MaxEnt.cpp b/Framework/Algorithms/src/MaxEnt.cpp index 483ac6a04e5fd3f90c934bfabb125cbee5c2c418..964940fd2769a4f7257a111a37eff42f1fd8814e 100644 --- a/Framework/Algorithms/src/MaxEnt.cpp +++ b/Framework/Algorithms/src/MaxEnt.cpp @@ -239,13 +239,13 @@ void MaxEnt::exec() { // Apply distance penalty (SB eq. 33) double sum = 0.; - for (size_t i = 0; i < image.size(); i++) - sum += fabs(image[i]); + for (double point : image) + sum += fabs(point); double dist = distance(dirs.s2, beta); if (dist > distEps * sum / background) { - for (size_t k = 0; k < beta.size(); k++) { - beta[k] *= sqrt(sum / dist / background); + for (double &k : beta) { + k *= sqrt(sum / dist / background); } } diff --git a/Framework/Algorithms/src/MedianDetectorTest.cpp b/Framework/Algorithms/src/MedianDetectorTest.cpp index c79c0eb1e07eb0923179fc162f93dc320b7223e2..226f830e34f95996a9a1eda6f56468f91cf9dd51 100644 --- a/Framework/Algorithms/src/MedianDetectorTest.cpp +++ b/Framework/Algorithms/src/MedianDetectorTest.cpp @@ -246,25 +246,25 @@ int MedianDetectorTest::maskOutliers( } for (size_t i = 0; i < indexmap.size(); ++i) { - std::vector<size_t> hists = indexmap.at(i); - double median = medianvec.at(i); + std::vector<size_t> &hists = indexmap[i]; + double median = medianvec[i]; PARALLEL_FOR1(countsWS) for (int j = 0; j < static_cast<int>(hists.size()); ++j) { - const double value = countsWS->readY(hists.at(j))[0]; + const double value = countsWS->readY(hists[j])[0]; if ((value == 0.) && checkForMask) { const std::set<detid_t> &detids = - countsWS->getSpectrum(hists.at(j))->getDetectorIDs(); + countsWS->getSpectrum(hists[j])->getDetectorIDs(); if (instrument->isDetectorMasked(detids)) { numFailed -= 1; // it was already masked } } if ((value < out_lo * median) && (value > 0.0)) { - countsWS->maskWorkspaceIndex(hists.at(j)); + countsWS->maskWorkspaceIndex(hists[j]); PARALLEL_ATOMIC ++numFailed; } else if (value > out_hi * median) { - countsWS->maskWorkspaceIndex(hists.at(j)); + countsWS->maskWorkspaceIndex(hists[j]); PARALLEL_ATOMIC ++numFailed; } diff --git a/Framework/Algorithms/src/MergeRuns.cpp b/Framework/Algorithms/src/MergeRuns.cpp index a47afb661179d00634126797f75df59af67a543e..13bff5dcda3e414f94b1062ecb8b5f9b46bb3299 100644 --- a/Framework/Algorithms/src/MergeRuns.cpp +++ b/Framework/Algorithms/src/MergeRuns.cpp @@ -64,16 +64,15 @@ void MergeRuns::exec() { // This will hold the inputs, with the groups separated off std::vector<std::string> inputs; - for (size_t i = 0; i < inputs_orig.size(); i++) { + for (const auto &input : inputs_orig) { WorkspaceGroup_sptr wsgroup = - AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( - inputs_orig[i]); + AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(input); if (wsgroup) { // Workspace group std::vector<std::string> group = wsgroup->getNames(); inputs.insert(inputs.end(), group.begin(), group.end()); } else { // Single workspace - inputs.push_back(inputs_orig[i]); + inputs.push_back(input); } } @@ -283,9 +282,9 @@ void MergeRuns::execEvent() { boost::shared_ptr<AdditionTable> table = m_tables[workspaceNum - 1]; // Add all the event lists together as the table says to do - for (auto it = table->begin(); it != table->end(); ++it) { - int64_t inWI = it->first; - int64_t outWI = it->second; + for (auto &WI : *table) { + int64_t inWI = WI.first; + int64_t outWI = WI.second; if (outWI >= 0) { outWS->getEventList(outWI) += addee->getEventList(inWI); } else { diff --git a/Framework/Algorithms/src/ModeratorTzero.cpp b/Framework/Algorithms/src/ModeratorTzero.cpp index 68029fa721a27748b4b71b9abe51ec09fb0ea975..69606bacd0028b3c7dba77a692f72512c7be9632 100644 --- a/Framework/Algorithms/src/ModeratorTzero.cpp +++ b/Framework/Algorithms/src/ModeratorTzero.cpp @@ -342,54 +342,44 @@ void ModeratorTzero::execEvent(const std::string &emode) { } if (t2 >= 0) // t2 < 0 when no detector info is available { - double tof; // fix the histogram bins MantidVec &x = evlist.dataX(); - for (auto iter = x.begin(); iter != x.end(); ++iter) { - tof = *iter; + for (double &tof : x) { if (tof < m_t1min + t2) tof -= min_t0_next; else tof -= CalculateT0indirect(tof, L1, t2, E1, parser); - *iter = tof; } MantidVec tofs = evlist.getTofs(); - for (unsigned int itof = 0; itof < tofs.size(); itof++) { - tof = tofs[itof]; + for (double &tof : tofs) { if (tof < m_t1min + t2) tof -= min_t0_next; else tof -= CalculateT0indirect(tof, L1, t2, E1, parser); - tofs[itof] = tof; } evlist.setTofs(tofs); evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED); } // end of if( t2>= 0) } // end of if(emode=="Indirect") else if (emode == "Elastic") { - double tof; // Apply t0 correction to histogram bins MantidVec &x = evlist.dataX(); - for (auto iter = x.begin(); iter != x.end(); ++iter) { - tof = *iter; + for (double &tof : x) { if (tof < m_t1min * (L1 + L2) / L1) tof -= min_t0_next; else tof -= CalculateT0elastic(tof, L1 + L2, E1, parser); - *iter = tof; } MantidVec tofs = evlist.getTofs(); - for (unsigned int itof = 0; itof < tofs.size(); itof++) { + for (double &tof : tofs) { // add a [-0.1,0.1] microsecond noise to avoid artifacts // resulting from original tof data - tof = tofs[itof]; if (tof < m_t1min * (L1 + L2) / L1) tof -= min_t0_next; else tof -= CalculateT0elastic(tof, L1 + L2, E1, parser); - tofs[itof] = tof; } evlist.setTofs(tofs); evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED); @@ -400,13 +390,13 @@ void ModeratorTzero::execEvent(const std::string &emode) { else if (emode == "Direct") { // fix the histogram bins MantidVec &x = evlist.dataX(); - for (auto iter = x.begin(); iter != x.end(); ++iter) { - *iter -= t0_direct; + for (double &tof : x) { + tof -= t0_direct; } MantidVec tofs = evlist.getTofs(); - for (unsigned int itof = 0; itof < tofs.size(); itof++) { - tofs[itof] -= t0_direct; + for (double &tof : tofs) { + tof -= t0_direct; } evlist.setTofs(tofs); evlist.setSortOrder(Mantid::DataObjects::EventSortType::UNSORTED); diff --git a/Framework/Algorithms/src/MonteCarloAbsorption.cpp b/Framework/Algorithms/src/MonteCarloAbsorption.cpp index bb6a80fbcbaa8d15aa5bc6b5c9236dc877090f54..4cfc7131150f86a29f423b8f6fd55a7cacd5c7f6 100644 --- a/Framework/Algorithms/src/MonteCarloAbsorption.cpp +++ b/Framework/Algorithms/src/MonteCarloAbsorption.cpp @@ -296,10 +296,9 @@ bool MonteCarloAbsorption::attenuationFactor(const V3D &startPos, m_container->interceptSurfaces(beforeScatter); } // Attenuation factor is product of factor for each material - for (auto citr = beforeScatter.cbegin(); citr != beforeScatter.cend(); - ++citr) { - length = citr->distInsideObject; - factor *= attenuation(length, citr->object->material(), lambda); + for (const auto &citr : beforeScatter) { + length = citr.distInsideObject; + factor *= attenuation(length, citr.object->material(), lambda); } length = afterScatter.cbegin()->distInsideObject; @@ -310,9 +309,9 @@ bool MonteCarloAbsorption::attenuationFactor(const V3D &startPos, m_container->interceptSurfaces(afterScatter); } // Attenuation factor is product of factor for each material - for (auto citr = afterScatter.cbegin(); citr != afterScatter.cend(); ++citr) { - length = citr->distInsideObject; - factor *= attenuation(length, citr->object->material(), lambda); + for (const auto &citr : afterScatter) { + length = citr.distInsideObject; + factor *= attenuation(length, citr.object->material(), lambda); } return true; diff --git a/Framework/Algorithms/src/MuonGroupDetectors.cpp b/Framework/Algorithms/src/MuonGroupDetectors.cpp index 105188cee04e4f7794ab05415807019397dac28f..9dce66628d9063662431b66b675b10347a36ffbd 100644 --- a/Framework/Algorithms/src/MuonGroupDetectors.cpp +++ b/Framework/Algorithms/src/MuonGroupDetectors.cpp @@ -106,20 +106,20 @@ void MuonGroupDetectors::exec() { // We will be setting them anew outWS->getSpectrum(groupIndex)->clearDetectorIDs(); - for (auto detIt = wsIndices.begin(); detIt != wsIndices.end(); detIt++) { + for (auto &wsIndex : wsIndices) { for (size_t i = 0; i < inWS->blocksize(); ++i) { // Sum the y values - outWS->dataY(groupIndex)[i] += inWS->dataY(*detIt)[i]; + outWS->dataY(groupIndex)[i] += inWS->dataY(wsIndex)[i]; // Sum the errors in quadrature outWS->dataE(groupIndex)[i] = sqrt(pow(outWS->dataE(groupIndex)[i], 2) + - pow(inWS->dataE(*detIt)[i], 2)); + pow(inWS->dataE(wsIndex)[i], 2)); } // Detectors list of the group should contain all the detectors of it's // elements outWS->getSpectrum(groupIndex) - ->addDetectorIDs(inWS->getSpectrum(*detIt)->getDetectorIDs()); + ->addDetectorIDs(inWS->getSpectrum(wsIndex)->getDetectorIDs()); } // Using the first detector X values diff --git a/Framework/Algorithms/src/NormaliseByDetector.cpp b/Framework/Algorithms/src/NormaliseByDetector.cpp index 888e50ba6c0880be2af7ab9f886780ac70ee1964..434cf6c4a025012c2b2f7e1b0338c99e9be91637 100644 --- a/Framework/Algorithms/src/NormaliseByDetector.cpp +++ b/Framework/Algorithms/src/NormaliseByDetector.cpp @@ -116,9 +116,8 @@ void NormaliseByDetector::processHistogram(size_t wsIndex, ParamNames allParamNames = function->getParameterNames(); // Lookup each parameter name. - for (auto it = allParamNames.begin(); it != allParamNames.end(); ++it) { - Geometry::Parameter_sptr param = - paramMap.getRecursive(&(*det), (*it), type); + for (auto &name : allParamNames) { + Geometry::Parameter_sptr param = paramMap.getRecursive(&(*det), name, type); const Geometry::FitParameter &fitParam = tryParseFunctionParameter(param, det); diff --git a/Framework/Algorithms/src/NormaliseToMonitor.cpp b/Framework/Algorithms/src/NormaliseToMonitor.cpp index 1374fc041b43ec7a6656c52e65f5155cb24017fb..2fcf54cd5f5b18fc6775acfa5f94c90fe029aeb9 100644 --- a/Framework/Algorithms/src/NormaliseToMonitor.cpp +++ b/Framework/Algorithms/src/NormaliseToMonitor.cpp @@ -64,10 +64,7 @@ bool MonIDPropChanger::isConditionChanged(const IPropertyManager *algo) const { // std::cout << "MonIDPropChanger::isConditionChanged() called "; // std::cout << monitors_changed << std::endl; - if (!monitors_changed) - return false; - - return true; + return monitors_changed; } // function which modifies the allowed values for the list of monitors. void MonIDPropChanger::applyChanges(const IPropertyManager *algo, diff --git a/Framework/Algorithms/src/OneMinusExponentialCor.cpp b/Framework/Algorithms/src/OneMinusExponentialCor.cpp index 36ab76f347bdea9b29ea047909e2fb72f14a3605..603a176f9ef95e0b46bfde0e3aca4e7590ac5499 100644 --- a/Framework/Algorithms/src/OneMinusExponentialCor.cpp +++ b/Framework/Algorithms/src/OneMinusExponentialCor.cpp @@ -39,7 +39,7 @@ void OneMinusExponentialCor::retrieveProperties() { m_c = getProperty("C"); m_c1 = getProperty("C1"); std::string op = getProperty("Operation"); - m_divide = (op == "Divide") ? true : false; + m_divide = op == "Divide"; } void OneMinusExponentialCor::performUnaryOperation(const double XIn, diff --git a/Framework/Algorithms/src/PDDetermineCharacterizations.cpp b/Framework/Algorithms/src/PDDetermineCharacterizations.cpp index 8d648691225c335c2538870c0c08bd02cc0c7960..6143acd632f72301910f60056aea42c66bfa30c4 100644 --- a/Framework/Algorithms/src/PDDetermineCharacterizations.cpp +++ b/Framework/Algorithms/src/PDDetermineCharacterizations.cpp @@ -80,10 +80,10 @@ PDDetermineCharacterizations::validateInputs() { << expectedNames.size(); result[CHAR_PROP_NAME] = msg.str(); } else { - for (auto it = expectedNames.begin(); it != expectedNames.end(); ++it) { - if (std::find(names.begin(), names.end(), *it) == names.end()) { + for (auto &expectedName : expectedNames) { + if (std::find(names.begin(), names.end(), expectedName) == names.end()) { std::stringstream msg; - msg << "Failed to find column named " << (*it); + msg << "Failed to find column named " << expectedName; result[CHAR_PROP_NAME] = msg.str(); } } @@ -142,10 +142,7 @@ bool closeEnough(const double left, const double right) { // same within 5% const double relativeDiff = diff * 2 / (left + right); - if (relativeDiff < .05) - return true; - - return false; + return relativeDiff < .05; } /// Fill in the property manager from the correct line in the table @@ -216,26 +213,26 @@ double PDDetermineCharacterizations::getLogValue(API::Run &run, validUnits.insert("Hz"); } - for (auto name = names.begin(); name != names.end(); ++name) { - if (run.hasProperty(*name)) { - const std::string units = run.getProperty(*name)->units(); + for (auto &name : names) { + if (run.hasProperty(name)) { + const std::string units = run.getProperty(name)->units(); if (validUnits.find(units) != validUnits.end()) { - double value = run.getLogAsSingleValue(*name); + double value = run.getLogAsSingleValue(name); if (value == 0.) { std::stringstream msg; - msg << "'" << *name << "' has a mean value of zero " << units; + msg << "'" << name << "' has a mean value of zero " << units; g_log.information(msg.str()); } else { std::stringstream msg; - msg << "Found " << label << " in log '" << *name + msg << "Found " << label << " in log '" << name << "' with mean value " << value << " " << units; g_log.information(msg.str()); return value; } } else { std::stringstream msg; - msg << "When looking at " << *name + msg << "When looking at " << name << " log encountered unknown units for " << label << ":" << units; g_log.warning(msg.str()); } @@ -338,12 +335,13 @@ void PDDetermineCharacterizations::exec() { overrideRunNumProperty("NormBackRun", "empty"); std::vector<std::string> expectedNames = getColumnNames(); - for (auto it = expectedNames.begin(); it != expectedNames.end(); ++it) { - if (m_propertyManager->existsProperty(*it)) { - g_log.debug() << (*it) << ":" << m_propertyManager->getPropertyValue(*it) + for (auto &expectedName : expectedNames) { + if (m_propertyManager->existsProperty(expectedName)) { + g_log.debug() << expectedName << ":" + << m_propertyManager->getPropertyValue(expectedName) << "\n"; } else { - g_log.warning() << (*it) << " DOES NOT EXIST\n"; + g_log.warning() << expectedName << " DOES NOT EXIST\n"; } } } diff --git a/Framework/Algorithms/src/PerformIndexOperations.cpp b/Framework/Algorithms/src/PerformIndexOperations.cpp index b8bdb32c058e7709df5063d8a430d1bbd428ed6c..d8df6486947c81718e99153ea223d8b6064d75ac 100644 --- a/Framework/Algorithms/src/PerformIndexOperations.cpp +++ b/Framework/Algorithms/src/PerformIndexOperations.cpp @@ -318,13 +318,9 @@ VecCommands interpret(const std::string &processingInstructions) { commandParsers.push_back(boost::make_shared<AdditionParser>()); VecCommands commands; - for (auto it = processingInstructionsSplit.begin(); - it != processingInstructionsSplit.end(); ++it) { - const std::string candidate = *it; + for (auto candidate : processingInstructionsSplit) { bool parserFound = false; - for (auto parserIt = commandParsers.begin(); - parserIt != commandParsers.end(); ++parserIt) { - auto commandParser = *parserIt; + for (auto commandParser : commandParsers) { Command *command = commandParser->interpret(candidate); boost::shared_ptr<Command> commandSptr(command); if (commandSptr->isValid()) // Do not record invalid commands. diff --git a/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp b/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp index edd094e9a61d277f7ec0b87409dc174d91498f0e..8556848411c6c2930f7148d80f735c5e4ae23d24 100644 --- a/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp +++ b/Framework/Algorithms/src/PlotAsymmetryByLogValue.cpp @@ -378,29 +378,29 @@ void PlotAsymmetryByLogValue::populateOutputWorkspace( auto tAxis = new TextAxis(nplots); if (nplots == 1) { size_t i = 0; - for (auto it = m_logValue.begin(); it != m_logValue.end(); ++it) { - outWS->dataX(0)[i] = it->second; - outWS->dataY(0)[i] = m_redY[it->first]; - outWS->dataE(0)[i] = m_redE[it->first]; + for (auto &value : m_logValue) { + outWS->dataX(0)[i] = value.second; + outWS->dataY(0)[i] = m_redY[value.first]; + outWS->dataE(0)[i] = m_redE[value.first]; i++; } tAxis->setLabel(0, "Asymmetry"); } else { size_t i = 0; - for (auto it = m_logValue.begin(); it != m_logValue.end(); ++it) { - outWS->dataX(0)[i] = it->second; - outWS->dataY(0)[i] = m_diffY[it->first]; - outWS->dataE(0)[i] = m_diffE[it->first]; - outWS->dataX(1)[i] = it->second; - outWS->dataY(1)[i] = m_redY[it->first]; - outWS->dataE(1)[i] = m_redE[it->first]; - outWS->dataX(2)[i] = it->second; - outWS->dataY(2)[i] = m_greenY[it->first]; - outWS->dataE(2)[i] = m_greenE[it->first]; - outWS->dataX(3)[i] = it->second; - outWS->dataY(3)[i] = m_sumY[it->first]; - outWS->dataE(3)[i] = m_sumE[it->first]; + for (auto &value : m_logValue) { + outWS->dataX(0)[i] = value.second; + outWS->dataY(0)[i] = m_diffY[value.first]; + outWS->dataE(0)[i] = m_diffE[value.first]; + outWS->dataX(1)[i] = value.second; + outWS->dataY(1)[i] = m_redY[value.first]; + outWS->dataE(1)[i] = m_redE[value.first]; + outWS->dataX(2)[i] = value.second; + outWS->dataY(2)[i] = m_greenY[value.first]; + outWS->dataE(2)[i] = m_greenE[value.first]; + outWS->dataX(3)[i] = value.second; + outWS->dataY(3)[i] = m_sumY[value.first]; + outWS->dataE(3)[i] = m_sumE[value.first]; i++; } tAxis->setLabel(0, "Red-Green"); @@ -422,20 +422,20 @@ void PlotAsymmetryByLogValue::saveResultsToADS(MatrixWorkspace_sptr &outWS, if (nplots == 2) { size_t i = 0; - for (auto it = m_logValue.begin(); it != m_logValue.end(); ++it) { - size_t run = it->first; + for (auto &value : m_logValue) { + size_t run = value.first; outWS->dataX(0)[i] = static_cast<double>(run); // run number - outWS->dataY(0)[i] = it->second; // log value + outWS->dataY(0)[i] = value.second; // log value outWS->dataY(1)[i] = m_redY[run]; // redY outWS->dataE(1)[i] = m_redE[run]; // redE i++; } } else { size_t i = 0; - for (auto it = m_logValue.begin(); it != m_logValue.end(); ++it) { - size_t run = it->first; + for (auto &value : m_logValue) { + size_t run = value.first; outWS->dataX(0)[i] = static_cast<double>(run); // run number - outWS->dataY(0)[i] = it->second; // log value + outWS->dataY(0)[i] = value.second; // log value outWS->dataY(1)[i] = m_diffY[run]; // diffY outWS->dataE(1)[i] = m_diffE[run]; // diffE outWS->dataY(2)[i] = m_redY[run]; // redY diff --git a/Framework/Algorithms/src/PointByPointVCorrection.cpp b/Framework/Algorithms/src/PointByPointVCorrection.cpp index 19bddb05cf7ace8ece1a461699194653f5970e58..243d7c7f24b7414d916f4290070ff3ad5911df81 100644 --- a/Framework/Algorithms/src/PointByPointVCorrection.cpp +++ b/Framework/Algorithms/src/PointByPointVCorrection.cpp @@ -110,9 +110,9 @@ void PointByPointVCorrection::exec() { // builds which caused the unit tests // to sometimes fail. Maybe this is some compiler bug to do with // using bind2nd within the parrallel macros. - for (auto rY = resultY.begin(); rY != resultY.end(); ++rY) { - *rY *= factor; // Now result is s_i/v_i*Dlam_i*(sum_i s_i)/(sum_i - // S_i/v_i*Dlam_i) + for (double &rY : resultY) { + rY *= factor; // Now result is s_i/v_i*Dlam_i*(sum_i s_i)/(sum_i + // S_i/v_i*Dlam_i) } // Finally get the normalized errors diff --git a/Framework/Algorithms/src/PolarizationCorrection.cpp b/Framework/Algorithms/src/PolarizationCorrection.cpp index 8e6c8e57b0f6e0cb271998fd776cdcc58afcad83..022123f76205803cbf95badc345d551d2b2bb0d3 100644 --- a/Framework/Algorithms/src/PolarizationCorrection.cpp +++ b/Framework/Algorithms/src/PolarizationCorrection.cpp @@ -399,18 +399,17 @@ void PolarizationCorrection::exec() { loadableProperties[cAlphaLabel()] = "calpha"; } - for (auto propName = loadableProperties.begin(); - propName != loadableProperties.end(); ++propName) { - Property *prop = getProperty(propName->first); + for (auto &loadableProperty : loadableProperties) { + Property *prop = getProperty(loadableProperty.first); if (!prop) continue; if (prop->isDefault()) { - auto vals = instrument->getStringParameter(propName->second); + auto vals = instrument->getStringParameter(loadableProperty.second); if (vals.empty()) throw std::runtime_error( - "Cannot find value for " + propName->first + + "Cannot find value for " + loadableProperty.first + " in parameter file. Please specify this property manually."); prop->setValue(vals[0]); } diff --git a/Framework/Algorithms/src/PolynomialCorrection.cpp b/Framework/Algorithms/src/PolynomialCorrection.cpp index 19907dbb77e6b9b460328ce4ab5651c979161245..ce28866b0e42a448a65f8852b68762f83f49507f 100644 --- a/Framework/Algorithms/src/PolynomialCorrection.cpp +++ b/Framework/Algorithms/src/PolynomialCorrection.cpp @@ -41,7 +41,7 @@ void PolynomialCorrection::retrieveProperties() { m_coeffs = getProperty("Coefficients"); m_polySize = m_coeffs.size(); std::string operation = getProperty("Operation"); - m_isOperationMultiply = operation == "Multiply" ? true : false; + m_isOperationMultiply = operation == "Multiply"; } void PolynomialCorrection::performUnaryOperation(const double XIn, diff --git a/Framework/Algorithms/src/Q1D2.cpp b/Framework/Algorithms/src/Q1D2.cpp index a7906aeeb68477ddb8334a4fe7a64d9034ac1fb3..9748a5c2309bc3f9db280c877125730ac0d887b0 100644 --- a/Framework/Algorithms/src/Q1D2.cpp +++ b/Framework/Algorithms/src/Q1D2.cpp @@ -120,7 +120,7 @@ void Q1D2::exec() { // iterations of the loop below // Flag to decide if Q Resolution is to be used - auto useQResolution = qResolution ? true : false; + auto useQResolution = static_cast<bool>(qResolution); // this will become the output workspace from this algorithm MatrixWorkspace_sptr outputWS = diff --git a/Framework/Algorithms/src/Q1DWeighted.cpp b/Framework/Algorithms/src/Q1DWeighted.cpp index 67b1b593e7cf6e59377b05fe2a456ae84dc0e7e2..e77e43b04d779f8ab497a5d531a830dab854a6fa 100644 --- a/Framework/Algorithms/src/Q1DWeighted.cpp +++ b/Framework/Algorithms/src/Q1DWeighted.cpp @@ -333,8 +333,8 @@ void Q1DWeighted::exec() { // Create workspace group that holds output workspaces WorkspaceGroup_sptr wsgroup = WorkspaceGroup_sptr(new WorkspaceGroup()); - for (auto it = wedgeWorkspaces.begin(); it != wedgeWorkspaces.end(); ++it) { - wsgroup->addWorkspace(*it); + for (auto &wedgeWorkspace : wedgeWorkspaces) { + wsgroup->addWorkspace(wedgeWorkspace); } // set the output property std::string outputWSGroupName = getPropertyValue("WedgeWorkspace"); diff --git a/Framework/Algorithms/src/Qxy.cpp b/Framework/Algorithms/src/Qxy.cpp index b791d857ac10d6f6c45cc217d95f3feb626bfebd..91432132ff8de1fa1739a7af8504cf61e02cb8fd 100644 --- a/Framework/Algorithms/src/Qxy.cpp +++ b/Framework/Algorithms/src/Qxy.cpp @@ -297,8 +297,8 @@ void Qxy::exec() { // left to be executed here for computational efficiency size_t numHist = weights->getNumberHistograms(); for (size_t i = 0; i < numHist; i++) { - for (size_t j = 0; j < weights->dataE(i).size(); j++) { - weights->dataE(i)[j] = sqrt(weights->dataE(i)[j]); + for (double &j : weights->dataE(i)) { + j = sqrt(j); } } diff --git a/Framework/Algorithms/src/ReadGroupsFromFile.cpp b/Framework/Algorithms/src/ReadGroupsFromFile.cpp index b1034751578e4c222981ecbd997aeaa78e2418bf..2310604ab44960ecc4883554808d9e07f93c83a5 100644 --- a/Framework/Algorithms/src/ReadGroupsFromFile.cpp +++ b/Framework/Algorithms/src/ReadGroupsFromFile.cpp @@ -223,11 +223,11 @@ void ReadGroupsFromFile::readXMLGroupingFile(const std::string &filename) { Poco::StringTokenizer data(ids, ",", Poco::StringTokenizer::TOK_TRIM); if (data.begin() != data.end()) { - for (auto it = data.begin(); it != data.end(); ++it) { + for (const auto &value : data) { // cast the string to an int int detID; try { - detID = boost::lexical_cast<int>(*it); + detID = boost::lexical_cast<int>(value); } catch (boost::bad_lexical_cast &) { throw Mantid::Kernel::Exception::FileError( "Could cast string to integer in input XML file", filename); diff --git a/Framework/Algorithms/src/RecordPythonScript.cpp b/Framework/Algorithms/src/RecordPythonScript.cpp index 29b86d8435e609039d0348a687513ae854cc5d59..f23fc23ad801184a30becac361042645ec4984ba 100644 --- a/Framework/Algorithms/src/RecordPythonScript.cpp +++ b/Framework/Algorithms/src/RecordPythonScript.cpp @@ -72,13 +72,13 @@ void RecordPythonScript::startingHandle(API::IAlgorithm_sptr alg) { auto props = alg->getProperties(); std::string algString; - for (auto p = props.begin(); p != props.end(); ++p) { + for (auto &prop : props) { std::string opener = "='"; - if ((**p).value().find('\\') != std::string::npos) { + if ((*prop).value().find('\\') != std::string::npos) { opener = "=r'"; } - std::string paramString = (**p).name() + opener + (**p).value() + "'"; + std::string paramString = (*prop).name() + opener + (*prop).value() + "'"; // Miss out parameters that are empty. if (paramString.length() != 0) { diff --git a/Framework/Algorithms/src/ReflectometryReductionOne.cpp b/Framework/Algorithms/src/ReflectometryReductionOne.cpp index 4b4e63bd8110fdba8368df1663de112c8ef004f4..a9db0f1ccbbdec4aaae0de743d2f2b00732e8fa6 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOne.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOne.cpp @@ -288,9 +288,9 @@ ReflectometryReductionOne::correctPosition(API::MatrixWorkspace_sptr &toCorrect, } else { auto specNumbers = getSpectrumNumbers(toCorrect); correctPosAlg->setProperty("SpectrumNumbersOfDetectors", specNumbers); - for (size_t t = 0; t < specNumbers.size(); ++t) { + for (auto specNumber : specNumbers) { std::stringstream buffer; - buffer << "Writing out: " << specNumbers[t]; + buffer << "Writing out: " << specNumber; g_log.notice(buffer.str()); } } diff --git a/Framework/Algorithms/src/ReflectometryReductionOneAuto.cpp b/Framework/Algorithms/src/ReflectometryReductionOneAuto.cpp index ab3278e5374903c96542742bce4b3c74477b9a3f..9f95d289c133591ff8c97fcc7bfdc756ae43fc2c 100644 --- a/Framework/Algorithms/src/ReflectometryReductionOneAuto.cpp +++ b/Framework/Algorithms/src/ReflectometryReductionOneAuto.cpp @@ -582,11 +582,11 @@ bool ReflectometryReductionOneAuto::processGroups() { // Copy all the non-workspace properties over std::vector<Property *> props = this->getProperties(); - for (auto prop = props.begin(); prop != props.end(); ++prop) { - if (*prop) { - IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(*prop); + for (auto &prop : props) { + if (prop) { + IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (!wsProp) - alg->setPropertyValue((*prop)->name(), (*prop)->value()); + alg->setPropertyValue(prop->name(), prop->value()); } } diff --git a/Framework/Algorithms/src/RemoveBackground.cpp b/Framework/Algorithms/src/RemoveBackground.cpp index 54df033197e32675ce06e7a776c47965f56397dc..8e1e2973d8f21ec508781dd38d6ea13fcbf65efc 100644 --- a/Framework/Algorithms/src/RemoveBackground.cpp +++ b/Framework/Algorithms/src/RemoveBackground.cpp @@ -168,11 +168,9 @@ BackgroundHelper::~BackgroundHelper() { this->deleteUnitsConverters(); } /** The method deletes all units converter allocated*/ void BackgroundHelper::deleteUnitsConverters() { - for (size_t i = 0; i < m_WSUnit.size(); i++) { - if (m_WSUnit[i]) { - delete m_WSUnit[i]; - m_WSUnit[i] = NULL; - } + for (auto &unit : m_WSUnit) { + delete unit; + unit = nullptr; } } diff --git a/Framework/Algorithms/src/RemoveBins.cpp b/Framework/Algorithms/src/RemoveBins.cpp index fcb1d36ee50f38abfdba77f5daef32ad27f2a5ad..3e491cddc069b94bbeac7f61ce59ad369409dea4 100644 --- a/Framework/Algorithms/src/RemoveBins.cpp +++ b/Framework/Algorithms/src/RemoveBins.cpp @@ -197,7 +197,7 @@ void RemoveBins::checkProperties() { } const std::string interpolation = getProperty("Interpolation"); - m_interpolate = (interpolation == "Linear" ? true : false); + m_interpolate = (interpolation == "Linear"); return; } diff --git a/Framework/Algorithms/src/RemoveLowResTOF.cpp b/Framework/Algorithms/src/RemoveLowResTOF.cpp index c56d99b7c4f7d61fe9802f7d8da6a0c5e0c6375f..bdf0ee25cb138da2fdfc129f84254e188153dda8 100644 --- a/Framework/Algorithms/src/RemoveLowResTOF.cpp +++ b/Framework/Algorithms/src/RemoveLowResTOF.cpp @@ -308,8 +308,8 @@ double RemoveLowResTOF::calcTofMin(const std::size_t workspaceIndex) { } } else { double l2 = 0; - for (auto it = detSet.cbegin(); it != detSet.cend(); ++it) { - l2 += m_instrument->getDetector(*it)->getDistance(*m_sample); + for (auto det : detSet) { + l2 += m_instrument->getDetector(det)->getDistance(*m_sample); } l2 /= static_cast<double>(detSet.size()); diff --git a/Framework/Algorithms/src/RemovePromptPulse.cpp b/Framework/Algorithms/src/RemovePromptPulse.cpp index ae43e1db8dbe835485aa5c68b3b806afb63fd5b4..a4e52853fe722269ad913c72caf5569497f6d2f6 100644 --- a/Framework/Algorithms/src/RemovePromptPulse.cpp +++ b/Framework/Algorithms/src/RemovePromptPulse.cpp @@ -122,15 +122,15 @@ void RemovePromptPulse::exec() { return; } g_log.information() << "Calculated prompt pulses at "; - for (size_t i = 0; i < pulseTimes.size(); ++i) - g_log.information() << pulseTimes[i] << " "; + for (double pulseTime : pulseTimes) + g_log.information() << pulseTime << " "; g_log.information() << " microseconds\n"; MatrixWorkspace_sptr outputWS; - for (auto left = pulseTimes.begin(); left != pulseTimes.end(); ++left) { - double right = (*left) + width; + for (double &pulseTime : pulseTimes) { + double right = pulseTime + width; - g_log.notice() << "Filtering tmin=" << *left << ", tmax=" << right + g_log.notice() << "Filtering tmin=" << pulseTime << ", tmax=" << right << " microseconds\n"; // run maskbins to do the work on the first prompt pulse @@ -147,7 +147,7 @@ void RemovePromptPulse::exec() { } // always write to correct output workspace algo->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", outputWS); - algo->setProperty<double>("XMin", *left); + algo->setProperty<double>("XMin", pulseTime); algo->setProperty<double>("XMax", right); algo->executeAsChildAlg(); diff --git a/Framework/Algorithms/src/ResetNegatives.cpp b/Framework/Algorithms/src/ResetNegatives.cpp index 8e3d93ed905652e84c0cc7adcbdf04737f67516e..c85d91f134b03f255c3d375eabb46bbc2dda324c 100644 --- a/Framework/Algorithms/src/ResetNegatives.cpp +++ b/Framework/Algorithms/src/ResetNegatives.cpp @@ -153,8 +153,8 @@ void ResetNegatives::pushMinimum(MatrixWorkspace_const_sptr minWS, if (minValue <= 0) { minValue *= -1.; MantidVec &y = wksp->dataY(i); - for (auto it = y.begin(); it != y.end(); ++it) { - *it = fixZero(*it + minValue); + for (double &value : y) { + value = fixZero(value + minValue); } } prog.report(); @@ -168,12 +168,13 @@ void ResetNegatives::pushMinimum(MatrixWorkspace_const_sptr minWS, * them to the supplied value. * * @param minWS A workspace of minimum values for each spectra. - * @param value Reset negative values in the spectra to this number. + * @param spectrumNegativeValues Reset negative values in the spectra to this + * number. * @param wksp The workspace to modify. * @param prog The progress. */ void ResetNegatives::changeNegatives(MatrixWorkspace_const_sptr minWS, - const double value, + const double spectrumNegativeValues, MatrixWorkspace_sptr wksp, Progress &prog) { int64_t nHist = wksp->getNumberHistograms(); @@ -184,11 +185,11 @@ void ResetNegatives::changeNegatives(MatrixWorkspace_const_sptr minWS, 0.) // quick check to see if there is a reason to bother { MantidVec &y = wksp->dataY(i); - for (auto it = y.begin(); it != y.end(); ++it) { - if (*it < 0.) { - *it = value; + for (double &value : y) { + if (value < 0.) { + value = spectrumNegativeValues; } else - *it = fixZero(*it); + value = fixZero(value); } } prog.report(); diff --git a/Framework/Algorithms/src/SetInstrumentParameter.cpp b/Framework/Algorithms/src/SetInstrumentParameter.cpp index 49febf5ad3af162c866765d47615f933f11045cb..f76d23abf4752b9256b56886a221d1b446acc88d 100644 --- a/Framework/Algorithms/src/SetInstrumentParameter.cpp +++ b/Framework/Algorithms/src/SetInstrumentParameter.cpp @@ -101,13 +101,13 @@ void SetInstrumentParameter::exec() { auto ¶mMap = ws->instrumentParameters(); if (!dets.empty()) { - for (auto it = dets.begin(); it != dets.end(); ++it) { - addParameter(paramMap, (*it).get(), paramName, paramType, paramValue); + for (auto &det : dets) { + addParameter(paramMap, det.get(), paramName, paramType, paramValue); } } else { if (cmptList.size() > 0) { - for (auto it = cmptList.begin(); it != cmptList.end(); ++it) { - addParameter(paramMap, it->get(), paramName, paramType, paramValue); + for (auto &cmpt : cmptList) { + addParameter(paramMap, cmpt.get(), paramName, paramType, paramValue); } } else { g_log.warning("Could not find the component requested."); diff --git a/Framework/Algorithms/src/SmoothNeighbours.cpp b/Framework/Algorithms/src/SmoothNeighbours.cpp index 32e7e2a3629f05024f3d1202626931a6ac44207b..be07f8c8d57629d718316382efa69b0fc2c77aea 100644 --- a/Framework/Algorithms/src/SmoothNeighbours.cpp +++ b/Framework/Algorithms/src/SmoothNeighbours.cpp @@ -237,7 +237,7 @@ void SmoothNeighbours::findNeighboursRectangular() { int EndY = AdjY; int SumX = getProperty("SumPixelsX"); int SumY = getProperty("SumPixelsY"); - bool sum = (SumX * SumY > 1) ? true : false; + bool sum = SumX * SumY > 1; if (sum) { StartX = 0; StartY = 0; @@ -294,8 +294,8 @@ void SmoothNeighbours::findNeighboursRectangular() { // Adjust the weights of each neighbour to normalize to unity if (!sum || expandSumAllPixels) - for (size_t q = 0; q < neighbours.size(); q++) - neighbours[q].second /= totalWeight; + for (auto &neighbour : neighbours) + neighbour.second /= totalWeight; // Save the list of neighbours for this output workspace index. m_neighbours[outWI] = neighbours; @@ -394,11 +394,11 @@ void SmoothNeighbours::findNeighboursUbiqutious() { std::vector<weightedNeighbour> neighbours; // Convert from spectrum numbers to workspace indices - for (auto it = neighbSpectra.begin(); it != neighbSpectra.end(); ++it) { - specid_t spec = it->first; + for (auto &specDistance : neighbSpectra) { + specid_t spec = specDistance.first; // Use the weighting strategy to calculate the weight. - double weight = WeightedSum->weightAt(it->second); + double weight = WeightedSum->weightAt(specDistance.second); if (weight > 0) { // Find the corresponding workspace index @@ -428,8 +428,8 @@ void SmoothNeighbours::findNeighboursUbiqutious() { // Adjust the weights of each neighbour to normalize to unity if (sum == 1) - for (size_t q = 0; q < neighbours.size(); q++) - neighbours[q].second /= totalWeight; + for (auto &neighbour : neighbours) + neighbour.second /= totalWeight; // Save the list of neighbours for this output workspace index. m_neighbours[outWI] = neighbours; @@ -537,8 +537,8 @@ Check whether the properties provided are all in their default state. */ bool areAllDefault(ConstVecProperties &properties) { bool areAllDefault = false; - for (auto it = properties.cbegin(); it != properties.cend(); ++it) { - if (!(*it)->isDefault()) { + for (auto property : properties) { + if (!property->isDefault()) { return areAllDefault; } } diff --git a/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp b/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp index 098707270cd6368a06463236d83561a66ccdfd0e..dd2623c960199043df8253b3127ce056791650d9 100644 --- a/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp +++ b/Framework/Algorithms/src/SofQWNormalisedPolygon.cpp @@ -338,8 +338,8 @@ void SofQWNormalisedPolygon::initAngularCachesPSD( specid_t deltaPlusT = inSpec + this->m_detNeighbourOffset; specid_t deltaMinusT = inSpec - this->m_detNeighbourOffset; - for (auto it = neighbours.begin(); it != neighbours.end(); ++it) { - specid_t spec = it->first; + for (auto &neighbour : neighbours) { + specid_t spec = neighbour.first; g_log.debug() << "Neighbor ID: " << spec << std::endl; if (spec == deltaPlus1 || spec == deltaMinus1 || spec == deltaPlusT || spec == deltaMinusT) { diff --git a/Framework/Algorithms/src/SpatialGrouping.cpp b/Framework/Algorithms/src/SpatialGrouping.cpp index 64129a296ec92c901aa2443d98b87907bb75a43e..da2a034e0d5620ee94c8e78232e514b65406c10b 100644 --- a/Framework/Algorithms/src/SpatialGrouping.cpp +++ b/Framework/Algorithms/src/SpatialGrouping.cpp @@ -82,13 +82,13 @@ void SpatialGrouping::exec() { Mantid::API::Progress prog(this, 0.0, 1.0, m_detectors.size()); - for (auto detIt = m_detectors.begin(); detIt != m_detectors.end(); ++detIt) { + for (auto &detector : m_detectors) { prog.report(); // The detector - Mantid::Geometry::IDetector_const_sptr det = detIt->second; + Mantid::Geometry::IDetector_const_sptr &det = detector.second; // The spectrum number of the detector - specid_t specNo = detIt->first; + specid_t specNo = detector.first; // We are not interested in Monitors and we don't want them to be included // in @@ -174,8 +174,8 @@ void SpatialGrouping::exec() { inputWorkspace->getIndexFromSpectrumNumber((*grpIt)[i]); const std::set<detid_t> &detIds = inputWorkspace->getSpectrum(workspaceIndex)->getDetectorIDs(); - for (auto it = detIds.cbegin(); it != detIds.cend(); ++it) { - xml << "," << (*it); + for (auto detId : detIds) { + xml << "," << detId; } } xml << "\"/></group>\n"; @@ -212,45 +212,45 @@ bool SpatialGrouping::expandNet( if (incoming == 0) { potentials = inputWorkspace->getNeighbours(det.get()); } else { - for (auto nrsIt = nearest.begin(); nrsIt != nearest.end(); ++nrsIt) { + for (auto &nrsIt : nearest) { std::map<specid_t, Mantid::Kernel::V3D> results; - results = inputWorkspace->getNeighbours(m_detectors[nrsIt->first].get()); - for (auto resIt = results.begin(); resIt != results.end(); ++resIt) { - potentials[resIt->first] = resIt->second; + results = inputWorkspace->getNeighbours(m_detectors[nrsIt.first].get()); + for (auto &result : results) { + potentials[result.first] = result.second; } } } - for (auto potIt = potentials.begin(); potIt != potentials.end(); ++potIt) { + for (auto &potential : potentials) { // We do not want to include the detector in it's own list of nearest // neighbours - if (potIt->first == spec) { + if (potential.first == spec) { continue; } // Or detectors that are already in the nearest list passed into this // function - auto nrsIt = nearest.find(potIt->first); + auto nrsIt = nearest.find(potential.first); if (nrsIt != nearest.end()) { continue; } // We should not include detectors already included in a group (or monitors // for that matter) - auto inclIt = m_included.find(potIt->first); + auto inclIt = m_included.find(potential.first); if (inclIt != m_included.end()) { continue; } // If we get this far, we need to determine if the detector is of a suitable // distance - Mantid::Kernel::V3D pos = m_detectors[potIt->first]->getPos(); + Mantid::Kernel::V3D pos = m_detectors[potential.first]->getPos(); if (!bbox.isPointInside(pos)) { continue; } // Elsewise, it's all good. - nearest[potIt->first] = potIt->second; + nearest[potential.first] = potential.second; } if (nearest.size() == incoming) { diff --git a/Framework/Algorithms/src/SpecularReflectionAlgorithm.cpp b/Framework/Algorithms/src/SpecularReflectionAlgorithm.cpp index dde76efc181c3f8372f869f06369e8c4971eb753..c4bdd25f0f0f104f485e1decfa9def44fd6b6659 100644 --- a/Framework/Algorithms/src/SpecularReflectionAlgorithm.cpp +++ b/Framework/Algorithms/src/SpecularReflectionAlgorithm.cpp @@ -165,9 +165,9 @@ SpecularReflectionAlgorithm::getDetectorComponent( auto specToWorkspaceIndex = workspace->getSpectrumToWorkspaceIndexMap(); DetectorGroup_sptr allDetectors = boost::make_shared<DetectorGroup>(); bool warnIfMasked = true; - for (size_t i = 0; i < spectrumNumbers.size(); ++i) { - const size_t &spectrumNumber = spectrumNumbers[i]; - auto it = specToWorkspaceIndex.find(spectrumNumbers[i]); + for (auto index : spectrumNumbers) { + const size_t spectrumNumber{static_cast<size_t>(index)}; + auto it = specToWorkspaceIndex.find(index); if (it == specToWorkspaceIndex.end()) { std::stringstream message; message << "Spectrum number " << spectrumNumber diff --git a/Framework/Algorithms/src/SpecularReflectionPositionCorrect.cpp b/Framework/Algorithms/src/SpecularReflectionPositionCorrect.cpp index 4568bc4765562cf642b39c9028d349b44c9c758c..f4815b2314ea361b1e0f478ef376e455363788e5 100644 --- a/Framework/Algorithms/src/SpecularReflectionPositionCorrect.cpp +++ b/Framework/Algorithms/src/SpecularReflectionPositionCorrect.cpp @@ -163,8 +163,8 @@ void SpecularReflectionPositionCorrect::moveDetectors( /* * We have to move individual components. */ - for (size_t i = 0; i < detectors.size(); ++i) { - moveDetectors(toCorrect, detectors[i], sample, upOffset, acrossOffset, + for (const auto &detector : detectors) { + moveDetectors(toCorrect, detector, sample, upOffset, acrossOffset, detectorPosition); // Recursive call } } diff --git a/Framework/Algorithms/src/Stitch1D.cpp b/Framework/Algorithms/src/Stitch1D.cpp index 6ee41612d24897405c9e5928f9038edfd67fc6d5..326507f660fcf402185a506b50ae29f4ce0470c4 100644 --- a/Framework/Algorithms/src/Stitch1D.cpp +++ b/Framework/Algorithms/src/Stitch1D.cpp @@ -638,20 +638,20 @@ void Stitch1D::reinsertSpecialValues(MatrixWorkspace_sptr ws) { // Copy over the data MantidVec &sourceY = ws->dataY(i); - for (size_t j = 0; j < m_nanYIndexes[i].size(); ++j) { - sourceY[m_nanYIndexes[i][j]] = std::numeric_limits<double>::quiet_NaN(); + for (auto j : m_nanYIndexes[i]) { + sourceY[j] = std::numeric_limits<double>::quiet_NaN(); } - for (size_t j = 0; j < m_infYIndexes[i].size(); ++j) { - sourceY[m_infYIndexes[i][j]] = std::numeric_limits<double>::infinity(); + for (auto j : m_infYIndexes[i]) { + sourceY[j] = std::numeric_limits<double>::infinity(); } - for (size_t j = 0; j < m_nanEIndexes[i].size(); ++j) { - sourceY[m_nanEIndexes[i][j]] = std::numeric_limits<double>::quiet_NaN(); + for (auto j : m_nanEIndexes[i]) { + sourceY[j] = std::numeric_limits<double>::quiet_NaN(); } - for (size_t j = 0; j < m_infEIndexes[i].size(); ++j) { - sourceY[m_infEIndexes[i][j]] = std::numeric_limits<double>::infinity(); + for (auto j : m_infEIndexes[i]) { + sourceY[j] = std::numeric_limits<double>::infinity(); } PARALLEL_END_INTERUPT_REGION diff --git a/Framework/Algorithms/src/Stitch1DMany.cpp b/Framework/Algorithms/src/Stitch1DMany.cpp index da43501fa7b14433aa4c573525dd0a9656726c54..8b576b8d6df86ab7f97f155086ab9bdb2e716a73 100644 --- a/Framework/Algorithms/src/Stitch1DMany.cpp +++ b/Framework/Algorithms/src/Stitch1DMany.cpp @@ -71,13 +71,12 @@ std::map<std::string, std::string> Stitch1DMany::validateInputs() { if (inputWorkspacesStr.size() < 2) errors["InputWorkspaces"] = "At least 2 input workspaces required."; - for (auto ws = inputWorkspacesStr.begin(); ws != inputWorkspacesStr.end(); - ++ws) { - if (AnalysisDataService::Instance().doesExist(*ws)) { + for (const auto &ws : inputWorkspacesStr) { + if (AnalysisDataService::Instance().doesExist(ws)) { m_inputWorkspaces.push_back( - AnalysisDataService::Instance().retrieveWS<Workspace>(*ws)); + AnalysisDataService::Instance().retrieveWS<Workspace>(ws)); } else { - errors["InputWorkspaces"] = *ws + " is not a valid workspace."; + errors["InputWorkspaces"] = ws + " is not a valid workspace."; break; } } @@ -85,9 +84,8 @@ std::map<std::string, std::string> Stitch1DMany::validateInputs() { // Check that all the workspaces are of the same type if (m_inputWorkspaces.size() > 0) { const std::string id = m_inputWorkspaces[0]->id(); - for (auto it = m_inputWorkspaces.begin(); it != m_inputWorkspaces.end(); - ++it) { - if ((*it)->id() != id) { + for (auto &inputWorkspace : m_inputWorkspaces) { + if (inputWorkspace->id() != id) { errors["InputWorkspaces"] = "All workspaces must be the same type."; break; } @@ -98,10 +96,9 @@ std::map<std::string, std::string> Stitch1DMany::validateInputs() { boost::dynamic_pointer_cast<WorkspaceGroup>(m_inputWorkspaces[0]); if (firstGroup) { size_t groupSize = firstGroup->size(); - for (auto it = m_inputWorkspaces.begin(); it != m_inputWorkspaces.end(); - ++it) { + for (auto &inputWorkspace : m_inputWorkspaces) { WorkspaceGroup_sptr group = - boost::dynamic_pointer_cast<WorkspaceGroup>(*it); + boost::dynamic_pointer_cast<WorkspaceGroup>(inputWorkspace); if (group->size() != groupSize) { errors["InputWorkspaces"] = "All group workspaces must be the same size."; @@ -183,9 +180,8 @@ void Stitch1DMany::exec() { if (!isChild()) { // Copy each input workspace's history into our output workspace's history - for (auto inWS = m_inputWorkspaces.begin(); - inWS != m_inputWorkspaces.end(); ++inWS) - lhsWS->history().addHistory((*inWS)->getHistory()); + for (auto &inputWorkspace : m_inputWorkspaces) + lhsWS->history().addHistory(inputWorkspace->getHistory()); } // We're a child algorithm, but we're recording history anyway else if (isRecordingHistoryForChild() && m_parentHistory) { @@ -197,10 +193,10 @@ void Stitch1DMany::exec() { // We're dealing with group workspaces else { std::vector<WorkspaceGroup_sptr> groupWorkspaces; - for (auto it = m_inputWorkspaces.begin(); it != m_inputWorkspaces.end(); - ++it) + groupWorkspaces.reserve(m_inputWorkspaces.size()); + for (auto &inputWorkspace : m_inputWorkspaces) groupWorkspaces.push_back( - boost::dynamic_pointer_cast<WorkspaceGroup>(*it)); + boost::dynamic_pointer_cast<WorkspaceGroup>(inputWorkspace)); // List of workspaces to be grouped std::vector<std::string> toGroup; @@ -215,8 +211,8 @@ void Stitch1DMany::exec() { // The name of the resulting workspace std::string outName = groupName; - for (size_t j = 0; j < groupWorkspaces.size(); ++j) { - const std::string wsName = groupWorkspaces[j]->getItem(i)->name(); + for (auto &groupWorkspace : groupWorkspaces) { + const std::string wsName = groupWorkspace->getItem(i)->name(); toProcess.push_back(wsName); outName += "_" + wsName; } diff --git a/Framework/Algorithms/src/SumEventsByLogValue.cpp b/Framework/Algorithms/src/SumEventsByLogValue.cpp index 825339895a44dc51cbbfbbfa54abcd14e96cb1dd..948f69844cf41c321dbb9432572169a968b13e82 100644 --- a/Framework/Algorithms/src/SumEventsByLogValue.cpp +++ b/Framework/Algorithms/src/SumEventsByLogValue.cpp @@ -204,8 +204,8 @@ void SumEventsByLogValue::createTableOutput( // Get a list of the other time-series logs in the input workspace auto otherLogs = getNumberSeriesLogs(); // Add a column for each of these 'other' logs - for (auto it = otherLogs.begin(); it != otherLogs.end(); ++it) { - auto newColumn = outputWorkspace->addColumn("double", it->first); + for (auto &otherLog : otherLogs) { + auto newColumn = outputWorkspace->addColumn("double", otherLog.first); // For the benefit of MantidPlot, set these columns to be containing X // values newColumn->setPlotType(1); @@ -229,8 +229,8 @@ void SumEventsByLogValue::createTableOutput( // Calculate the time covered by this log value and add it to the table double duration = 0.0; - for (auto it = filter.begin(); it != filter.end(); ++it) { - duration += it->duration(); + for (auto &time : filter) { + duration += time.duration(); } timeCol->cell<double>(row) = duration; @@ -241,13 +241,13 @@ void SumEventsByLogValue::createTableOutput( sumProtonCharge(protonChargeLog, filter); interruption_point(); - for (auto log = otherLogs.begin(); log != otherLogs.end(); ++log) { + for (auto &otherLog : otherLogs) { // Calculate the average value of each 'other' log for the current value // of the main log // Have to (maybe inefficiently) fetch back column by name - move outside // loop if too slow - outputWorkspace->getColumn(log->first)->cell<double>(row) = - log->second->averageValueInFilter(filter); + outputWorkspace->getColumn(otherLog.first)->cell<double>(row) = + otherLog.second->averageValueInFilter(filter); } prog.report(); } @@ -273,15 +273,14 @@ void SumEventsByLogValue::filterEventList( return; const auto pulseTimes = eventList.getPulseTimes(); - for (std::size_t eventIndex = 0; eventIndex < pulseTimes.size(); - ++eventIndex) { + for (auto pulseTime : pulseTimes) { // Find the value of the log at the time of this event // This algorithm is really concerned with 'slow' logs so we don't care // about // the time of the event within the pulse. // NB: If the pulse time is before the first log entry, we get the first // value. - const int logValue = log->getSingleValue(pulseTimes[eventIndex]); + const int logValue = log->getSingleValue(pulseTime); if (logValue >= minVal && logValue <= maxVal) { // In this scenario it's easy to know what bin to increment @@ -345,8 +344,8 @@ SumEventsByLogValue::getNumberSeriesLogs() { std::vector<std::pair<std::string, const Kernel::ITimeSeriesProperty *>> numberSeriesProps; const auto &logs = m_inputWorkspace->run().getLogData(); - for (auto log = logs.begin(); log != logs.end(); ++log) { - const std::string logName = (*log)->name(); + for (auto log : logs) { + const std::string logName = log->name(); // Don't add the log that's the one being summed against if (logName == m_logName) continue; @@ -355,7 +354,7 @@ SumEventsByLogValue::getNumberSeriesLogs() { if (logName == "proton_charge") continue; // Try to cast to an ITimeSeriesProperty - auto tsp = dynamic_cast<const ITimeSeriesProperty *>(*log); + auto tsp = dynamic_cast<const ITimeSeriesProperty *>(log); // Move on to the next one if this is not a TSP if (tsp == NULL) continue; @@ -363,8 +362,8 @@ SumEventsByLogValue::getNumberSeriesLogs() { // if ( tsp->realSize() < 2 ) continue; // Now make sure it's either an int or double tsp, and if so add log to the // list - if (dynamic_cast<TimeSeriesProperty<double> *>(*log) || - dynamic_cast<TimeSeriesProperty<int> *>(*log)) { + if (dynamic_cast<TimeSeriesProperty<double> *>(log) || + dynamic_cast<TimeSeriesProperty<int> *>(log)) { numberSeriesProps.emplace_back(logName, tsp); } } @@ -425,10 +424,9 @@ void SumEventsByLogValue::createBinnedOutput( PARALLEL_START_INTERUPT_REGION const IEventList &eventList = m_inputWorkspace->getEventList(spec); const auto pulseTimes = eventList.getPulseTimes(); - for (std::size_t eventIndex = 0; eventIndex < pulseTimes.size(); - ++eventIndex) { + for (auto pulseTime : pulseTimes) { // Find the value of the log at the time of this event - const double logValue = log->getSingleValue(pulseTimes[eventIndex]); + const double logValue = log->getSingleValue(pulseTime); if (logValue >= XValues.front() && logValue < XValues.back()) { PARALLEL_ATOMIC ++Y[VectorHelper::getBinIndex(XValues, logValue)]; diff --git a/Framework/Algorithms/src/SumSpectra.cpp b/Framework/Algorithms/src/SumSpectra.cpp index 612141dab3fa7cc3a3bfe4e75dded4cb76441bbf..a2aeb96921188c45903dc3713f11111e1d73aa5f 100644 --- a/Framework/Algorithms/src/SumSpectra.cpp +++ b/Framework/Algorithms/src/SumSpectra.cpp @@ -196,9 +196,9 @@ SumSpectra::getOutputSpecId(MatrixWorkspace_const_sptr localworkspace) { int totalSpec = static_cast<int>(localworkspace->getNumberHistograms()); specid_t temp; - for (auto it = this->m_indices.begin(); it != this->m_indices.end(); ++it) { - if (*(it) < totalSpec) { - temp = localworkspace->getSpectrum(*(it))->getSpectrumNo(); + for (auto index : this->m_indices) { + if (index < totalSpec) { + temp = localworkspace->getSpectrum(index)->getSpectrumNo(); if (temp < specId) specId = temp; } diff --git a/Framework/Algorithms/src/UnwrapMonitor.cpp b/Framework/Algorithms/src/UnwrapMonitor.cpp index 75f157e303c869f8998128214aba0449a2aa25f7..e6baa8d0ac522a9bff473268dd2343d75177f21c 100644 --- a/Framework/Algorithms/src/UnwrapMonitor.cpp +++ b/Framework/Algorithms/src/UnwrapMonitor.cpp @@ -378,11 +378,11 @@ void UnwrapMonitor::unwrapYandE(const API::MatrixWorkspace_sptr &tempWS, if (m_inputWS->hasMaskedBins(spectrum)) { const MatrixWorkspace::MaskList &inputMasks = m_inputWS->maskedBins(spectrum); - for (auto it = inputMasks.cbegin(); it != inputMasks.cend(); ++it) { - const int maskIndex = static_cast<int>((*it).first); + for (const auto &inputMask : inputMasks) { + const int maskIndex = static_cast<int>(inputMask.first); if (maskIndex >= rangeBounds[0] && maskIndex < rangeBounds[1]) tempWS->flagMasked(spectrum, maskIndex - rangeBounds[0], - (*it).second); + inputMask.second); } } } diff --git a/Framework/Algorithms/src/UpdateScriptRepository.cpp b/Framework/Algorithms/src/UpdateScriptRepository.cpp index a0a8e10eb472ccaeadb9736b93f333fa94b0465e..c6b2a587a5957fa7f48286622efee2b64b6e3940 100644 --- a/Framework/Algorithms/src/UpdateScriptRepository.cpp +++ b/Framework/Algorithms/src/UpdateScriptRepository.cpp @@ -58,8 +58,8 @@ void UpdateScriptRepository::exec() { std::stringstream info; info << "Information about ScriptRepository:\n" << " A more recent version of the following files was installed:\n"; - for (unsigned short i = 0; i < f_list.size(); i++) { - info << " * " << f_list[i] << "\n"; + for (auto &file : f_list) { + info << " * " << file << "\n"; } info << "Please check these files before using them. " << "Note: These files were configured for AutoUpdate."; diff --git a/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h b/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h index 613ea215729143b6b8c21771123cf83f0bd0d775..58e51a51514fb18c5fb8fc9868c7bc141c4156e8 100644 --- a/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h +++ b/Framework/Crystal/inc/MantidCrystal/IntegratePeakTimeSlices.h @@ -21,6 +21,8 @@ #include "MantidKernel/V3D.h" #include "MantidAPI/IAlgorithm.h" +#include <array> + namespace Mantid { namespace Crystal { /** @@ -255,7 +257,7 @@ private: std::string m_ParameterNames[7]; boost::shared_ptr<DataModeHandler> m_AttributeValues; - double m_ParameterValues[7]; + std::array<double, 7> m_ParameterValues; Mantid::detid2index_map m_wi_to_detid_map; diff --git a/Framework/Crystal/src/CentroidPeaks.cpp b/Framework/Crystal/src/CentroidPeaks.cpp index 875cfecb80e11ecd90d45d1cbda4ece2fe7806ae..068416cbc742eb915241a09b9eef3889c5d5ef17 100644 --- a/Framework/Crystal/src/CentroidPeaks.cpp +++ b/Framework/Crystal/src/CentroidPeaks.cpp @@ -381,11 +381,8 @@ bool CentroidPeaks::edgePixel(std::string bankName, int col, int row, boost::shared_ptr<const RectangularDetector> RDet = boost::dynamic_pointer_cast<const RectangularDetector>(parent); - if (col < Edge || col >= (RDet->xpixels() - Edge) || row < Edge || - row >= (RDet->ypixels() - Edge)) - return true; - else - return false; + return col < Edge || col >= (RDet->xpixels() - Edge) || row < Edge || + row >= (RDet->ypixels() - Edge); } else { std::vector<Geometry::IComponent_const_sptr> children; boost::shared_ptr<const Geometry::ICompAssembly> asmb = @@ -398,11 +395,8 @@ bool CentroidPeaks::edgePixel(std::string bankName, int col, int row, int NROWS = static_cast<int>(grandchildren.size()); int NCOLS = static_cast<int>(children.size()); // Wish pixels and tubes start at 1 not 0 - if (col - 1 < Edge || col - 1 >= (NCOLS - Edge) || row - 1 < Edge || - row - 1 >= (NROWS - Edge)) - return true; - else - return false; + return col - 1 < Edge || col - 1 >= (NCOLS - Edge) || row - 1 < Edge || + row - 1 >= (NROWS - Edge); } return false; } diff --git a/Framework/Crystal/src/Cluster.cpp b/Framework/Crystal/src/Cluster.cpp index 9d79b4205466a2029addfff3bdb8138a9d0c7b61..6a5680ec70bdee3716ece2ee64a383031a43fd7d 100644 --- a/Framework/Crystal/src/Cluster.cpp +++ b/Framework/Crystal/src/Cluster.cpp @@ -59,9 +59,9 @@ void Cluster::addIndex(const size_t &index) { m_indexes.push_back(index); } */ void Cluster::writeTo(Mantid::API::IMDHistoWorkspace_sptr ws) const { const size_t label = this->getLabel(); - for (size_t i = 0; i < m_indexes.size(); ++i) { - ws->setSignalAt(m_indexes[i], static_cast<Mantid::signal_t>(label)); - ws->setErrorSquaredAt(m_indexes[i], 0); + for (auto index : m_indexes) { + ws->setSignalAt(index, static_cast<Mantid::signal_t>(label)); + ws->setErrorSquaredAt(index, 0); } } @@ -75,9 +75,9 @@ Cluster::integrate(Mantid::API::IMDHistoWorkspace_const_sptr ws) const { double errorIntSQ = 0; double sigInt = 0; // Integrate accross indexes owned by this workspace. - for (size_t i = 0; i < m_indexes.size(); ++i) { - sigInt += ws->getSignalAt(m_indexes[i]); - double errorSQ = ws->getErrorAt(m_indexes[i]); + for (auto index : m_indexes) { + sigInt += ws->getSignalAt(index); + double errorSQ = ws->getErrorAt(index); errorSQ *= errorSQ; errorIntSQ += errorSQ; } diff --git a/Framework/Crystal/src/ClusterRegister.cpp b/Framework/Crystal/src/ClusterRegister.cpp index a94bc0b635078d16ccdbff8ef6140dc600055810..f0765ac08e465c175ecc82d20eebe0141be7a49e 100644 --- a/Framework/Crystal/src/ClusterRegister.cpp +++ b/Framework/Crystal/src/ClusterRegister.cpp @@ -55,8 +55,7 @@ public: GroupType containingAny; GroupType containingNone; // ------------- Find equivalent sets - for (auto i = m_groups.begin(); i != m_groups.end(); ++i) { - GroupType::value_type &cluster = *i; + for (auto &cluster : m_groups) { if (cluster.find(aLabel) != cluster.end()) { containingAny.push_back(cluster); } else if (cluster.find(bLabel) != cluster.end()) { @@ -83,8 +82,7 @@ public: GroupType::value_type masterSet; masterSet.insert(aLabel); // Incase it doesn't already contain a masterSet.insert(bLabel); // Incase it doesn't already contain b - for (auto i = containingAny.begin(); i != containingAny.end(); ++i) { - GroupType::value_type &childSet = *i; + for (auto &childSet : containingAny) { masterSet.insert(childSet.begin(), childSet.end()); // Build the master set. } @@ -101,11 +99,10 @@ public: */ std::list<boost::shared_ptr<CompositeCluster>> makeCompositeClusters() { std::list<boost::shared_ptr<CompositeCluster>> composites; - for (auto i = m_groups.begin(); i != m_groups.end(); ++i) { - GroupType::value_type &labelSet = *i; + for (auto &labelSet : m_groups) { auto composite = boost::make_shared<CompositeCluster>(); - for (auto j = labelSet.begin(); j != labelSet.end(); ++j) { - boost::shared_ptr<ICluster> &cluster = m_register[(*j)]; + for (auto j : labelSet) { + boost::shared_ptr<ICluster> &cluster = m_register[j]; composite->add(cluster); } composites.push_back(composite); @@ -168,8 +165,7 @@ ClusterRegister::MapCluster ClusterRegister::clusters() const { MapCluster temp; temp.insert(m_Impl->m_unique.begin(), m_Impl->m_unique.end()); auto mergedClusters = m_Impl->makeCompositeClusters(); - for (auto i = mergedClusters.begin(); i != mergedClusters.end(); ++i) { - const auto &merged = *i; + for (const auto &merged : mergedClusters) { temp.emplace(merged->getLabel(), merged); } return temp; @@ -186,8 +182,7 @@ ClusterRegister::clusters(std::vector<DisjointElement> &elements) const { MapCluster temp; temp.insert(m_Impl->m_unique.begin(), m_Impl->m_unique.end()); auto mergedClusters = m_Impl->makeCompositeClusters(); - for (auto i = mergedClusters.begin(); i != mergedClusters.end(); ++i) { - const auto &merged = *i; + for (auto &merged : mergedClusters) { merged->toUniformMinimum(elements); temp.emplace(merged->getLabel(), merged); } diff --git a/Framework/Crystal/src/CombinePeaksWorkspaces.cpp b/Framework/Crystal/src/CombinePeaksWorkspaces.cpp index 292aae1d67d38ee168bd0aa2412a7df56f3db1ab..56db99baf44b3c3c5431a09f4ca2c7ede28797eb 100644 --- a/Framework/Crystal/src/CombinePeaksWorkspaces.cpp +++ b/Framework/Crystal/src/CombinePeaksWorkspaces.cpp @@ -91,8 +91,8 @@ void CombinePeaksWorkspaces::exec() { if (!CombineMatchingPeaks) { // Loop over the peaks in the second workspace, appending each one to the // output - for (size_t i = 0; i < rhsPeaks.size(); ++i) { - output->addPeak(rhsPeaks[i]); + for (const auto &rhsPeak : rhsPeaks) { + output->addPeak(rhsPeak); progress.report(); } } else // Check for matching peaks @@ -105,15 +105,14 @@ void CombinePeaksWorkspaces::exec() { // Loop over the peaks in the second workspace, appending ones that don't // match any in first workspace - for (size_t i = 0; i < rhsPeaks.size(); ++i) { - const Peak ¤tPeak = rhsPeaks[i]; + for (const auto ¤tPeak : rhsPeaks) { // Now have to go through the first workspace checking for matches // Not doing anything clever as peaks workspace are typically not large - // just a linear search bool match = false; - for (size_t j = 0; j < lhsPeaks.size(); ++j) { + for (const auto &lhsPeak : lhsPeaks) { const V3D deltaQ = - currentPeak.getQSampleFrame() - lhsPeaks[j].getQSampleFrame(); + currentPeak.getQSampleFrame() - lhsPeak.getQSampleFrame(); if (deltaQ.nullVector( Tolerance)) // Using a V3D method that does the job { diff --git a/Framework/Crystal/src/CompositeCluster.cpp b/Framework/Crystal/src/CompositeCluster.cpp index b504298aea1a8ac8f831f97c25dfab80487736f5..5f336efa62de11ff6e889cc064b12a91d4f655bb 100644 --- a/Framework/Crystal/src/CompositeCluster.cpp +++ b/Framework/Crystal/src/CompositeCluster.cpp @@ -41,8 +41,8 @@ ICluster::ClusterIntegratedValues CompositeCluster::integrate( double errorIntSQ = 0; double sigInt = 0; // Integrate owned clusters and add those results too. - for (size_t i = 0; i < m_ownedClusters.size(); ++i) { - auto integratedValues = m_ownedClusters[i]->integrate(ws); + for (const auto &ownedCluster : m_ownedClusters) { + auto integratedValues = ownedCluster->integrate(ws); sigInt += integratedValues.get<0>(); errorIntSQ += integratedValues.get<1>(); } @@ -55,8 +55,8 @@ ICluster::ClusterIntegratedValues CompositeCluster::integrate( */ void CompositeCluster::writeTo( boost::shared_ptr<Mantid::API::IMDHistoWorkspace> ws) const { - for (size_t i = 0; i < m_ownedClusters.size(); ++i) { - m_ownedClusters[i]->writeTo(ws); + for (const auto &ownedCluster : m_ownedClusters) { + ownedCluster->writeTo(ws); } } @@ -87,8 +87,8 @@ size_t CompositeCluster::getOriginalLabel() const { return getLabel(); } */ size_t CompositeCluster::size() const { size_t size = 0; - for (size_t i = 0; i < m_ownedClusters.size(); ++i) { - size += m_ownedClusters[i]->size(); + for (const auto &ownedCluster : m_ownedClusters) { + size += ownedCluster->size(); } return size; } @@ -133,9 +133,9 @@ void CompositeCluster::toUniformMinimum( } m_label = minLabel; - for (size_t i = 0; i < m_ownedClusters.size(); ++i) { - m_ownedClusters[i]->setRootCluster(minCluster); - m_ownedClusters[i]->toUniformMinimum(disjointSet); + for (auto &ownedCluster : m_ownedClusters) { + ownedCluster->setRootCluster(minCluster); + ownedCluster->toUniformMinimum(disjointSet); } } } @@ -153,8 +153,8 @@ size_t CompositeCluster::getRepresentitiveIndex() const { * @param root : Root cluster to use */ void CompositeCluster::setRootCluster(ICluster const *root) { - for (size_t i = 0; i < m_ownedClusters.size(); ++i) { - m_ownedClusters[i]->setRootCluster(root); + for (auto &ownedCluster : m_ownedClusters) { + ownedCluster->setRootCluster(root); } } diff --git a/Framework/Crystal/src/ConnectedComponentLabeling.cpp b/Framework/Crystal/src/ConnectedComponentLabeling.cpp index aa183dc399ab9514a9029b1936344a0b4db1a334..6ae60fbbc2e59b75edafe3edf15ee0123c37312d 100644 --- a/Framework/Crystal/src/ConnectedComponentLabeling.cpp +++ b/Framework/Crystal/src/ConnectedComponentLabeling.cpp @@ -134,8 +134,7 @@ size_t doConnectedComponentLabeling(IMDIterator *iterator, nonEmptyNeighbourIndexes.reserve(maxNeighbours); SetIds neighbourIds; // Discover non-empty neighbours - for (size_t i = 0; i < neighbourIndexes.size(); ++i) { - size_t neighIndex = neighbourIndexes[i]; + for (auto neighIndex : neighbourIndexes) { if (!iterator->isWithinBounds(neighIndex)) { /* Record labels which appear to belong to the same cluster, but cannot be combined in this @@ -181,8 +180,7 @@ size_t doConnectedComponentLabeling(IMDIterator *iterator, DisjointElement &parentElement = neighbourElements[candidateSourceParentIndex]; // Union remainder parents with the chosen parent - for (size_t i = 0; i < nonEmptyNeighbourIndexes.size(); ++i) { - size_t neighIndex = nonEmptyNeighbourIndexes[i]; + for (auto neighIndex : nonEmptyNeighbourIndexes) { if (neighIndex != candidateSourceParentIndex) { neighbourElements[neighIndex].unionWith(&parentElement); } @@ -346,10 +344,10 @@ ClusterMap ConnectedComponentLabeling::calculateDisjointTree( // equivalent clusters. Must be done in sequence. // Combine cluster maps processed by each thread. ClusterRegister clusterRegister; - for (auto it = parallelClusterMapVec.begin(); - it != parallelClusterMapVec.end(); ++it) { - for (auto itt = it->begin(); itt != it->end(); ++itt) { - clusterRegister.add(itt->first, itt->second); + for (auto ¶llelClusterMap : parallelClusterMapVec) { + for (auto it = parallelClusterMap.begin(); it != parallelClusterMap.end(); + ++it) { + clusterRegister.add(it->first, it->second); } } @@ -357,11 +355,10 @@ ClusterMap ConnectedComponentLabeling::calculateDisjointTree( // ambiguity. g_log.debug("Percolate minimum label across boundaries"); - for (auto it = parallelEdgeVec.begin(); it != parallelEdgeVec.end(); ++it) { - VecEdgeIndexPair &indexPairVec = *it; - for (auto iit = indexPairVec.begin(); iit != indexPairVec.end(); ++iit) { - DisjointElement &a = neighbourElements[iit->get<0>()]; - DisjointElement &b = neighbourElements[iit->get<1>()]; + for (auto &indexPairVec : parallelEdgeVec) { + for (auto &iit : indexPairVec) { + DisjointElement &a = neighbourElements[iit.get<0>()]; + DisjointElement &b = neighbourElements[iit.get<1>()]; clusterRegister.merge(a, b); } } @@ -439,8 +436,8 @@ ClusterTuple ConnectedComponentLabeling::executeAndFetchClusters( // Get the keys (label ids) first in order to do the next stage in parallel. VecIndexes keys; keys.reserve(clusters.size()); - for (auto it = clusters.begin(); it != clusters.end(); ++it) { - keys.push_back(it->first); + for (auto &cluster : clusters) { + keys.push_back(cluster.first); } // Write each cluster out to the output workspace PARALLEL_FOR_NO_WSP_CHECK() diff --git a/Framework/Crystal/src/DiffPeaksWorkspaces.cpp b/Framework/Crystal/src/DiffPeaksWorkspaces.cpp index 69d29d1048e3310fedb10ad5fb048c18709e266d..ef4c1358f43eb618ca68f0a4e5779333d139eb9d 100644 --- a/Framework/Crystal/src/DiffPeaksWorkspaces.cpp +++ b/Framework/Crystal/src/DiffPeaksWorkspaces.cpp @@ -84,8 +84,7 @@ void DiffPeaksWorkspaces::exec() { // Loop over the peaks in the second workspace, searching for a match in the // first - for (size_t i = 0; i < rhsPeaks.size(); ++i) { - const Peak ¤tPeak = rhsPeaks[i]; + for (const auto ¤tPeak : rhsPeaks) { // Now have to go through the first workspace checking for matches // Not doing anything clever as peaks workspace are typically not large - // just a linear search diff --git a/Framework/Crystal/src/FindClusterFaces.cpp b/Framework/Crystal/src/FindClusterFaces.cpp index 2ecedb4d4ecc9ac343544664da40032c5a1592a3..8d11ba8f73e1c69d6c73746f81a9d80f6ae88155 100644 --- a/Framework/Crystal/src/FindClusterFaces.cpp +++ b/Framework/Crystal/src/FindClusterFaces.cpp @@ -120,8 +120,7 @@ void findFacesAtIndex(const size_t linearIndex, IMDIterator *mdIterator, indexes); const auto neighbours = mdIterator->findNeighbourIndexesFaceTouching(); - for (size_t i = 0; i < neighbours.size(); ++i) { - size_t neighbourLinearIndex = neighbours[i]; + for (auto neighbourLinearIndex : neighbours) { const int neighbourId = static_cast<int>(clusterImage->getSignalAt(neighbourLinearIndex)); @@ -372,11 +371,9 @@ void FindClusterFaces::exec() { for (int i = 0; i < nIterators; ++i) { const ClusterFaces &localClusterFaces = clusterFaces[i]; - for (auto it = localClusterFaces.begin(); it != localClusterFaces.end(); - ++it) { + for (const auto &clusterFace : localClusterFaces) { if (!limitRows || (out->rowCount() < size_t(maxRows))) { TableRow row = out->appendRow(); - const ClusterFace &clusterFace = *it; row << clusterFace.clusterId << double(clusterFace.workspaceIndex) << clusterFace.faceNormalDimension << clusterFace.maxEdge << clusterFace.radius; diff --git a/Framework/Crystal/src/FindSXPeaks.cpp b/Framework/Crystal/src/FindSXPeaks.cpp index a2cdbc16f408aba18adec1153b38260ee6183580..f61872ceb4f5a4a06f3814cf14912e31b5ea1935 100644 --- a/Framework/Crystal/src/FindSXPeaks.cpp +++ b/Framework/Crystal/src/FindSXPeaks.cpp @@ -211,27 +211,33 @@ then convert SXPeaks objects to PeakObjects and add them to the output workspace void FindSXPeaks::reducePeakList(const peakvector &pcv) { double resol = getProperty("Resolution"); peakvector finalv; - bool found = false; - for (std::size_t i = 0; i < pcv.size(); i++) { - for (std::size_t j = 0; j < finalv.size(); j++) { - if (pcv[i].compare(finalv[j], resol)) { - finalv[j] += pcv[i]; + + for (const auto ¤tPeak : pcv) { + /*for (auto & finalPeak : finalv) { + if (currentPeak.compare(finalPeak, resol)) { + finalPeak += currentPeak; found = true; break; } - } - if (!found) - finalv.push_back(pcv[i]); - found = false; + }*/ + auto pos = std::find_if(finalv.begin(), finalv.end(), + [¤tPeak, resol](SXPeak &peak) { + bool result = currentPeak.compare(peak, resol); + if (result) + peak += currentPeak; + return result; + }); + if (pos == finalv.end()) + finalv.push_back(currentPeak); } - for (std::size_t i = 0; i < finalv.size(); i++) { - finalv[i].reduce(); + for (auto &finalPeak : finalv) { + finalPeak.reduce(); try { - Geometry::IPeak *peak = m_peaks->createPeak(finalv[i].getQ()); + Geometry::IPeak *peak = m_peaks->createPeak(finalPeak.getQ()); if (peak) { - peak->setIntensity(finalv[i].getIntensity()); - peak->setDetectorID(finalv[i].getDetectorId()); + peak->setIntensity(finalPeak.getIntensity()); + peak->setDetectorID(finalPeak.getDetectorId()); m_peaks->addPeak(*peak); delete peak; } diff --git a/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp b/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp index 8f8e0f8e59466530bf596784d8bf106ebd6d8f74..e75e45f913a6a6f0d053d3582c8122d3d3136914 100644 --- a/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp +++ b/Framework/Crystal/src/GoniometerAnglesFromPhiRotation.cpp @@ -218,9 +218,8 @@ void GoniometerAnglesFromPhiRotation::exec() { API::FrameworkManager::Instance(); - for (size_t d = 0; d < directionList.size(); d++) + for (auto dir : directionList) for (int sgn = 1; sgn > -2; sgn -= 2) { - V3D dir = directionList[d]; dir.normalize(); Quat Q(sgn * dphi, dir); Q.normalize(); diff --git a/Framework/Crystal/src/IntegratePeakTimeSlices.cpp b/Framework/Crystal/src/IntegratePeakTimeSlices.cpp index 308310317c72e76ca59834d56081a1baab5bf1a1..89a707257518dad34140d273402ebec94b34d186 100644 --- a/Framework/Crystal/src/IntegratePeakTimeSlices.cpp +++ b/Framework/Crystal/src/IntegratePeakTimeSlices.cpp @@ -127,8 +127,9 @@ IntegratePeakTimeSlices::IntegratePeakTimeSlices() // for (int i = 0; i < NAttributes; i++) // m_AttributeValues[i] = 0; - for (int i = 0; i < NParameters; i++) - m_ParameterValues[i] = 0; + for (double &m_ParameterValue : m_ParameterValues) + m_ParameterValue = 0; + std::fill(m_ParameterValues.begin(), m_ParameterValues.end(), 0.0); } double SQRT(double v) { @@ -445,7 +446,8 @@ void IntegratePeakTimeSlices::exec() { std::vector<std::string> names; if (m_AttributeValues->StatBaseVals(ISSIxx) > 0 && - m_AttributeValues->IsEnoughData(m_ParameterValues, g_log) && + m_AttributeValues->IsEnoughData(m_ParameterValues.data(), + g_log) && m_ParameterValues[ITINTENS] > 0) { double chisqOverDOF; @@ -532,7 +534,8 @@ void IntegratePeakTimeSlices::exec() { g_log.debug("Try Merge 2 time slices"); if (m_AttributeValues->StatBaseVals(ISSIxx) >= 0 && - m_AttributeValues->IsEnoughData(m_ParameterValues, g_log)) + m_AttributeValues->IsEnoughData(m_ParameterValues.data(), + g_log)) Fit(Data, chisqOverDOF, done, names, params, errs, lastRow, lastCol, neighborRadius); @@ -1762,13 +1765,10 @@ bool DataModeHandler::isEdgePeak(const double *params, int nparams) { double Ry = lastRCRadius / CellHeight - EdgeY; // span from center in y direction - if (Rx * Rx < - NStdDevPeakSpan * NStdDevPeakSpan * std::max<double>(Varx, VarxHW) || - Ry * Ry < - NStdDevPeakSpan * NStdDevPeakSpan * std::max<double>(Vary, VaryHW)) - return true; - - return false; + return Rx * Rx < NStdDevPeakSpan * NStdDevPeakSpan * + std::max<double>(Varx, VarxHW) || + Ry * Ry < + NStdDevPeakSpan * NStdDevPeakSpan * std::max<double>(Vary, VaryHW); } /** diff --git a/Framework/Crystal/src/LoadIsawUB.cpp b/Framework/Crystal/src/LoadIsawUB.cpp index a4521d204b6970f6df29504e2e2e5b72d27c530c..c63ad864694e9dc470db2981513be0feb7d61475 100644 --- a/Framework/Crystal/src/LoadIsawUB.cpp +++ b/Framework/Crystal/src/LoadIsawUB.cpp @@ -90,12 +90,12 @@ void LoadIsawUB::exec() { readToEndOfLine(in, true); double latVals[6]; - for (size_t col = 0; col < 6; col++) { + for (double &latVal : latVals) { s = getWord(in, true); if (!convert(s, val)) throw std::runtime_error("The string '" + s + "' in the file was not understood as a number."); - latVals[col] = val; + latVal = val; } // Adjust the UB by transposing diff --git a/Framework/Crystal/src/MaskPeaksWorkspace.cpp b/Framework/Crystal/src/MaskPeaksWorkspace.cpp index af3e3935a41f4ddc6b0aeb3fac44ad13cc3a6d17..0ac78b522f3ae653f0805ce1bad60c73ed5a5b42 100644 --- a/Framework/Crystal/src/MaskPeaksWorkspace.cpp +++ b/Framework/Crystal/src/MaskPeaksWorkspace.cpp @@ -96,7 +96,7 @@ void MaskPeaksWorkspace::exec() { PARALLEL_FOR3(m_inputW, peaksW, tablews) for (int i = 0; i < static_cast<int>(peaks.size()); i++) { PARALLEL_START_INTERUPT_REGION - Peak peak = peaks[i]; + const Peak &peak = peaks[i]; // get the peak location on the detector double col = peak.getCol(); double row = peak.getRow(); @@ -106,7 +106,7 @@ void MaskPeaksWorkspace::exec() { << " y=" << yPeak << "\n"; // the detector component for the peak will have all pixels that we mask - const string bankName = peak.getBankName(); + const string &bankName = peak.getBankName(); if (bankName.compare("None") == 0) continue; Geometry::IComponent_const_sptr comp = inst->getComponentByName(bankName); diff --git a/Framework/Crystal/src/OptimizeCrystalPlacement.cpp b/Framework/Crystal/src/OptimizeCrystalPlacement.cpp index fab4b77795149f1b3a06b07133fe56a6e724e57a..752eb9382ef2bc463c8f8cf8abe36635392f123b 100644 --- a/Framework/Crystal/src/OptimizeCrystalPlacement.cpp +++ b/Framework/Crystal/src/OptimizeCrystalPlacement.cpp @@ -242,9 +242,7 @@ void OptimizeCrystalPlacement::exec() { //--------------- std::vector<std::string> ChRunNumList; std::string predChar = ""; - for (auto it = RunNumList.begin(); it != RunNumList.end(); ++it) { - int runNum = *it; - + for (auto runNum : RunNumList) { auto it1 = NOoptimizeRuns.begin(); for (; it1 != NOoptimizeRuns.end() && *it1 != runNum; ++it1) { } diff --git a/Framework/Crystal/src/OptimizeExtinctionParameters.cpp b/Framework/Crystal/src/OptimizeExtinctionParameters.cpp index de1769271aae36d8b605e3f9601bc67139ba9293..676ce9ff13b394e7708418df64d6039dd5a81c19 100644 --- a/Framework/Crystal/src/OptimizeExtinctionParameters.cpp +++ b/Framework/Crystal/src/OptimizeExtinctionParameters.cpp @@ -78,8 +78,8 @@ void OptimizeExtinctionParameters::init() { "Becker-Coppens Crystallite Radius (micron)", Direction::InOut); std::vector<std::string> propOptions; - for (size_t i = 0; i < m_pointGroups.size(); ++i) - propOptions.push_back(m_pointGroups[i]->getName()); + for (auto &pointGroup : m_pointGroups) + propOptions.push_back(pointGroup->getName()); declareProperty("PointGroup", propOptions[0], boost::make_shared<StringListValidator>(propOptions), "Which point group applies to this crystal?"); diff --git a/Framework/Crystal/src/OptimizeLatticeForCellType.cpp b/Framework/Crystal/src/OptimizeLatticeForCellType.cpp index 99a521fda95ef83222a5d2d1c68a5c7a01b0011b..bcb6f41f51155247883daf7c59f8431d92bab810 100644 --- a/Framework/Crystal/src/OptimizeLatticeForCellType.cpp +++ b/Framework/Crystal/src/OptimizeLatticeForCellType.cpp @@ -100,26 +100,26 @@ void OptimizeLatticeForCellType::exec() { const std::vector<Peak> &peaks_all = ws->getPeaks(); int run = 0; int count = 0; - for (size_t i = 0; i < peaks_all.size(); i++) { - if (peaks_all[i].getRunNumber() != run) { + for (const auto &peak : peaks_all) { + if (peak.getRunNumber() != run) { count++; // first entry in runWS is input workspace - DataObjects::PeaksWorkspace_sptr cloneWS(new PeaksWorkspace()); + auto cloneWS = boost::make_shared<PeaksWorkspace>(); cloneWS->setInstrument(ws->getInstrument()); cloneWS->copyExperimentInfoFrom(ws.get()); runWS.push_back(cloneWS); - runWS[count]->addPeak(peaks_all[i]); - run = peaks_all[i].getRunNumber(); + runWS[count]->addPeak(peak); + run = peak.getRunNumber(); AnalysisDataService::Instance().addOrReplace( boost::lexical_cast<std::string>(run) + ws->getName(), runWS[count]); } else { - runWS[count]->addPeak(peaks_all[i]); + runWS[count]->addPeak(peak); } } } // finally do the optimization - for (size_t i_run = 0; i_run < runWS.size(); i_run++) { - DataObjects::PeaksWorkspace_sptr peakWS(runWS[i_run]->clone().release()); + for (auto &i_run : runWS) { + DataObjects::PeaksWorkspace_sptr peakWS(i_run->clone().release()); AnalysisDataService::Instance().addOrReplace("_peaks", peakWS); const DblMatrix UB = peakWS->sample().getOrientedLattice().getUB(); std::vector<double> lat(6); @@ -174,16 +174,16 @@ void OptimizeLatticeForCellType::exec() { refinedCell.errorbeta(), refinedCell.errorgamma()); // Show the modified lattice parameters - g_log.notice() << runWS[i_run]->getName() << " " << o_lattice << "\n"; + g_log.notice() << i_run->getName() << " " << o_lattice << "\n"; - runWS[i_run]->mutableSample().setOrientedLattice(&o_lattice); + i_run->mutableSample().setOrientedLattice(&o_lattice); setProperty("OutputChi2", chisq); if (apply) { // Reindex peaks with new UB Mantid::API::IAlgorithm_sptr alg = createChildAlgorithm("IndexPeaks"); - alg->setPropertyValue("PeaksWorkspace", runWS[i_run]->getName()); + alg->setPropertyValue("PeaksWorkspace", i_run->getName()); alg->setProperty("Tolerance", tolerance); alg->executeAsChildAlg(); } @@ -195,25 +195,23 @@ void OptimizeLatticeForCellType::exec() { // Save Peaks Mantid::API::IAlgorithm_sptr savePks_alg = createChildAlgorithm("SaveIsawPeaks"); - savePks_alg->setPropertyValue("InputWorkspace", runWS[i_run]->getName()); - savePks_alg->setProperty("Filename", outputdir + "ls" + - runWS[i_run]->getName() + + savePks_alg->setPropertyValue("InputWorkspace", i_run->getName()); + savePks_alg->setProperty("Filename", outputdir + "ls" + i_run->getName() + ".integrate"); savePks_alg->executeAsChildAlg(); g_log.notice() << "See output file: " - << outputdir + "ls" + runWS[i_run]->getName() + - ".integrate" + << outputdir + "ls" + i_run->getName() + ".integrate" << "\n"; // Save UB Mantid::API::IAlgorithm_sptr saveUB_alg = createChildAlgorithm("SaveIsawUB"); - saveUB_alg->setPropertyValue("InputWorkspace", runWS[i_run]->getName()); - saveUB_alg->setProperty("Filename", outputdir + "ls" + - runWS[i_run]->getName() + ".mat"); + saveUB_alg->setPropertyValue("InputWorkspace", i_run->getName()); + saveUB_alg->setProperty("Filename", + outputdir + "ls" + i_run->getName() + ".mat"); saveUB_alg->executeAsChildAlg(); // Show the names of files written g_log.notice() << "See output file: " - << outputdir + "ls" + runWS[i_run]->getName() + ".mat" + << outputdir + "ls" + i_run->getName() + ".mat" << "\n"; } } @@ -262,11 +260,8 @@ bool OptimizeLatticeForCellType::edgePixel(PeaksWorkspace_sptr ws, boost::shared_ptr<const RectangularDetector> RDet = boost::dynamic_pointer_cast<const RectangularDetector>(parent); - if (col < Edge || col >= (RDet->xpixels() - Edge) || row < Edge || - row >= (RDet->ypixels() - Edge)) - return true; - else - return false; + return col < Edge || col >= (RDet->xpixels() - Edge) || row < Edge || + row >= (RDet->ypixels() - Edge); } else { std::vector<Geometry::IComponent_const_sptr> children; boost::shared_ptr<const Geometry::ICompAssembly> asmb = @@ -288,11 +283,8 @@ bool OptimizeLatticeForCellType::edgePixel(PeaksWorkspace_sptr ws, int NROWS = static_cast<int>(grandchildren.size()); int NCOLS = static_cast<int>(children.size()); // Wish pixels and tubes start at 1 not 0 - if (col - startI < Edge || col - startI >= (NCOLS - Edge) || - row - startI < Edge || row - startI >= (NROWS - Edge)) - return true; - else - return false; + return col - startI < Edge || col - startI >= (NCOLS - Edge) || + row - startI < Edge || row - startI >= (NROWS - Edge); } return false; } diff --git a/Framework/Crystal/src/PeakHKLErrors.cpp b/Framework/Crystal/src/PeakHKLErrors.cpp index 3b93119e3b44cc8f4ca995ddfdc11334e1520754..7ba7638b76cc21a6b47b9285b8ae129c6cac50f1 100644 --- a/Framework/Crystal/src/PeakHKLErrors.cpp +++ b/Framework/Crystal/src/PeakHKLErrors.cpp @@ -71,12 +71,10 @@ void PeakHKLErrors::setUpOptRuns() { boost::split(OptRunNums, OptRunstemp, boost::is_any_of("/")); - for (size_t i = 0; i < OptRunNums.size(); i++) { - declareParameter("phi" + OptRunNums[i], 0.0, - "Phi sample orientation value"); - declareParameter("chi" + OptRunNums[i], 0.0, - "Chi sample orientation value"); - declareParameter("omega" + OptRunNums[i], 0.0, + for (auto &OptRunNum : OptRunNums) { + declareParameter("phi" + OptRunNum, 0.0, "Phi sample orientation value"); + declareParameter("chi" + OptRunNum, 0.0, "Chi sample orientation value"); + declareParameter("omega" + OptRunNum, 0.0, "Omega sample orientation value"); } } @@ -118,39 +116,39 @@ void PeakHKLErrors::cLone( if (component->isParametrized()) { std::set<std::string> nms = pmapSv->names(component.get()); - for (auto it = nms.begin(); it != nms.end(); ++it) { + for (const auto &nm : nms) { - if (pmapSv->contains(component.get(), *it, "double")) { + if (pmapSv->contains(component.get(), nm, "double")) { std::vector<double> dparams = - pmapSv->getDouble(component->getName(), *it); - pmap->addDouble(component.get(), *it, dparams[0]); + pmapSv->getDouble(component->getName(), nm); + pmap->addDouble(component.get(), nm, dparams[0]); continue; } - if (pmapSv->contains(component.get(), *it, "V3D")) { - std::vector<V3D> V3Dparams = pmapSv->getV3D(component->getName(), *it); - pmap->addV3D(component.get(), *it, V3Dparams[0]); + if (pmapSv->contains(component.get(), nm, "V3D")) { + std::vector<V3D> V3Dparams = pmapSv->getV3D(component->getName(), nm); + pmap->addV3D(component.get(), nm, V3Dparams[0]); continue; } - if (pmapSv->contains(component.get(), *it, "int")) { + if (pmapSv->contains(component.get(), nm, "int")) { std::vector<int> iparams = - pmapSv->getType<int>(component->getName(), *it); - pmap->addInt(component.get(), *it, iparams[0]); + pmapSv->getType<int>(component->getName(), nm); + pmap->addInt(component.get(), nm, iparams[0]); continue; } - if (pmapSv->contains(component.get(), *it, "string")) { + if (pmapSv->contains(component.get(), nm, "string")) { std::vector<std::string> sparams = - pmapSv->getString(component->getName(), *it); - pmap->addString(component.get(), *it, sparams[0]); + pmapSv->getString(component->getName(), nm); + pmap->addString(component.get(), nm, sparams[0]); continue; } - if (pmapSv->contains(component.get(), *it, "Quat")) { + if (pmapSv->contains(component.get(), nm, "Quat")) { std::vector<Kernel::Quat> sparams = - pmapSv->getType<Kernel::Quat>(component->getName(), *it); - pmap->addQuat(component.get(), *it, sparams[0]); + pmapSv->getType<Kernel::Quat>(component->getName(), nm); + pmap->addQuat(component.get(), nm, sparams[0]); continue; } } diff --git a/Framework/Crystal/src/PredictFractionalPeaks.cpp b/Framework/Crystal/src/PredictFractionalPeaks.cpp index 3770ba6b21cdbe8ea9a009056222990ff547d3cd..0cd767f63348337714f5a35aafa64e475080e2c4 100644 --- a/Framework/Crystal/src/PredictFractionalPeaks.cpp +++ b/Framework/Crystal/src/PredictFractionalPeaks.cpp @@ -159,16 +159,16 @@ void PredictFractionalPeaks::exec() { bool done = false; int ErrPos = 1; // Used to determine position in code of a throw while (!done) { - for (size_t hoffset = 0; hoffset < hOffsets.size(); hoffset++) - for (size_t koffset = 0; koffset < kOffsets.size(); koffset++) - for (size_t loffset = 0; loffset < lOffsets.size(); loffset++) + for (double hOffset : hOffsets) { + for (double kOffset : kOffsets) { + for (double lOffset : lOffsets) { try { V3D hkl1(hkl); ErrPos = 0; - hkl1[0] += hOffsets[hoffset]; - hkl1[1] += kOffsets[koffset]; - hkl1[2] += lOffsets[loffset]; + hkl1[0] += hOffset; + hkl1[1] += kOffset; + hkl1[2] += lOffset; Kernel::V3D Qs = UB * hkl1; Qs *= 2.0; @@ -208,6 +208,9 @@ void PredictFractionalPeaks::exec() { if (ErrPos != 1) // setQLabFrame in createPeak throws exception throw new std::invalid_argument("Invalid data at this point"); } + } + } + } if (includePeaksInRange) { hkl[0]++; if (hkl[0] > Hmax) { diff --git a/Framework/Crystal/src/PredictPeaks.cpp b/Framework/Crystal/src/PredictPeaks.cpp index 1ec7d9f829616c41dec2059125a8f8d3699c5963..ac09af98dca087113d89d7154bd2463a98b72886 100644 --- a/Framework/Crystal/src/PredictPeaks.cpp +++ b/Framework/Crystal/src/PredictPeaks.cpp @@ -67,8 +67,8 @@ void PredictPeaks::init() { // Build up a list of reflection conditions to use std::vector<std::string> propOptions; - for (size_t i = 0; i < m_refConds.size(); ++i) - propOptions.push_back(m_refConds[i]->getName()); + for (auto &refCond : m_refConds) + propOptions.push_back(refCond->getName()); declareProperty("ReflectionCondition", "Primitive", boost::make_shared<StringListValidator>(propOptions), "Which reflection condition applies to this crystal, " @@ -234,10 +234,9 @@ void PredictPeaks::exec() { Progress prog(this, 0.0, 1.0, possibleHKLs.size() * gonioVec.size()); prog.setNotifyStep(0.01); - for (auto goniometerMatrix = gonioVec.begin(); - goniometerMatrix != gonioVec.end(); ++goniometerMatrix) { + for (auto &goniometerMatrix : gonioVec) { // Final transformation matrix (HKL to Q in lab frame) - DblMatrix orientedUB = (*goniometerMatrix) * ub; + DblMatrix orientedUB = goniometerMatrix * ub; /* Because of the additional filtering step it's better to keep track of the * allowed peaks with a counter. */ @@ -245,10 +244,10 @@ void PredictPeaks::exec() { size_t allowedPeakCount = 0; - for (auto hkl = possibleHKLs.begin(); hkl != possibleHKLs.end(); ++hkl) { - if (lambdaFilter.isAllowed(*hkl)) { + for (auto &possibleHKL : possibleHKLs) { + if (lambdaFilter.isAllowed(possibleHKL)) { ++allowedPeakCount; - calculateQAndAddToOutput(*hkl, orientedUB, *goniometerMatrix); + calculateQAndAddToOutput(possibleHKL, orientedUB, goniometerMatrix); } prog.report(); } @@ -307,12 +306,13 @@ void PredictPeaks::fillPossibleHKLsUsingGenerator( // --- Reflection condition ---- // Use the primitive by default - ReflectionCondition_sptr refCond(new ReflectionConditionPrimitive()); + ReflectionCondition_sptr refCond = + boost::make_shared<ReflectionConditionPrimitive>(); // Get it from the property std::string refCondName = getPropertyValue("ReflectionCondition"); - for (size_t i = 0; i < m_refConds.size(); ++i) - if (m_refConds[i]->getName() == refCondName) - refCond = m_refConds[i]; + for (const auto &m_refCond : m_refConds) + if (m_refCond->getName() == refCondName) + refCond = m_refCond; HKLGenerator gen(orientedLattice, dMin); auto filter = diff --git a/Framework/Crystal/src/SCDCalibratePanels.cpp b/Framework/Crystal/src/SCDCalibratePanels.cpp index 8b9322f460d2ffbc7749824c717c0f4d7200716b..54c64086a602780ce68bd269ce13e5c52689329c 100644 --- a/Framework/Crystal/src/SCDCalibratePanels.cpp +++ b/Framework/Crystal/src/SCDCalibratePanels.cpp @@ -183,8 +183,7 @@ void SCDCalibratePanels::CalculateGroups( Groups.clear(); if (Grouping == "OnePanelPerGroup") { - for (auto it = AllBankNames.begin(); it != AllBankNames.end(); ++it) { - string bankName = (*it); + for (auto bankName : AllBankNames) { vector<string> vbankName; vbankName.push_back(bankName); Groups.push_back(vbankName); @@ -193,9 +192,7 @@ void SCDCalibratePanels::CalculateGroups( } else if (Grouping == "AllPanelsInOneGroup") { vector<string> vbankName; - for (auto it = AllBankNames.begin(); it != AllBankNames.end(); ++it) { - string bankName = (*it); - + for (auto bankName : AllBankNames) { vbankName.push_back(bankName); } @@ -208,9 +205,7 @@ void SCDCalibratePanels::CalculateGroups( boost::split(GroupA, bankingCode, boost::is_any_of("]")); set<string> usedInts; - for (size_t Gr = 0; Gr < GroupA.size(); ++Gr) { - string S = GroupA[Gr]; - + for (auto S : GroupA) { boost::trim(S); if (S.empty()) @@ -226,9 +221,7 @@ void SCDCalibratePanels::CalculateGroups( boost::split(GroupB, S, boost::is_any_of(",")); vector<string> Group0; - for (size_t panelRange = 0; panelRange < GroupB.size(); ++panelRange) { - string rangeOfBanks = GroupB[panelRange]; - + for (auto rangeOfBanks : GroupB) { boost::trim(rangeOfBanks); vector<string> StrtStopStep; @@ -317,8 +310,7 @@ boost::shared_ptr<const Instrument> SCDCalibratePanels::GetNewCalibInstrument( boost::shared_ptr<const ParameterMap> pmap0 = instrument->getParameterMap(); boost::shared_ptr<ParameterMap> pmap1(new ParameterMap()); - for (auto vit = AllBankNames.begin(); vit != AllBankNames.end(); ++vit) { - string bankName = (*vit); + for (auto bankName : AllBankNames) { updateBankParams(instrument->getComponentByName(bankName), pmap1, pmap0); } @@ -618,8 +610,8 @@ void SCDCalibratePanels::exec() { PARALLEL_START_INTERUPT_REGION auto group = Groups.begin() + iGr; vector<string> banksVec; - for (auto bankName = group->begin(); bankName != group->end(); ++bankName) { - banksVec.push_back(*bankName); + for (auto &bankName : *group) { + banksVec.push_back(bankName); } if (!GoodStart(peaksWs, a, b, c, alpha, beta, gamma, tolerance)) { g_log.warning() << "**** Indexing is NOT compatible with given lattice " @@ -1236,9 +1228,7 @@ void SCDCalibratePanels::createResultWorkspace(const int numGroups, // determine the field names, the leading '_' is the break point vector<string> TableFieldNames; - for (size_t p = 0; p < names.size(); ++p) { - string fieldName = names[p]; - + for (auto fieldName : names) { size_t dotPos = fieldName.find('_'); if (dotPos < fieldName.size()) fieldName = fieldName.substr(dotPos + 1); @@ -1640,9 +1630,7 @@ void SCDCalibratePanels::FixUpBankParameterMap( boost::shared_ptr<const ParameterMap> const pmapOld, bool RotCenters) { boost::shared_ptr<ParameterMap> pmap = NewInstrument->getParameterMap(); - for (auto it1 = bankNames.cbegin(); it1 != bankNames.cend(); ++it1) { - - const string bankName = (*it1); + for (auto bankName : bankNames) { boost::shared_ptr<const IComponent> bank1 = NewInstrument->getComponentByName(bankName); @@ -1726,8 +1714,8 @@ void SCDCalibratePanels::saveXmlFile( ParameterMap_sptr pmap = instrument->getParameterMap(); // write out the detector banks - for (auto it = Groups.begin(); it != Groups.end(); ++it) { - for (auto it1 = (*it).begin(); it1 != (*it).end(); ++it1) { + for (const auto &Group : Groups) { + for (auto it1 = Group.begin(); it1 != Group.end(); ++it1) { string bankName = (*it1); oss3 << "<component-link name=\"" << bankName << "\">" << endl; diff --git a/Framework/Crystal/src/SCDPanelErrors.cpp b/Framework/Crystal/src/SCDPanelErrors.cpp index 6c4e20429033eea57fb8bd5754dc464705ed17af..458e02e291206f3a80dd69509e35107f65e6323b 100644 --- a/Framework/Crystal/src/SCDPanelErrors.cpp +++ b/Framework/Crystal/src/SCDPanelErrors.cpp @@ -665,8 +665,7 @@ void SCDPanelErrors::functionDeriv1D(Jacobian *out, const double *xValues, AllBankNames.insert(m_peaks->getPeak(i).getBankName()); Instrument_sptr instrNew = getNewInstrument(m_peaks->getPeak(0)); - for (auto it = AllBankNames.begin(); it != AllBankNames.end(); ++it) { - std::string bankName = (*it); + for (auto bankName : AllBankNames) { boost::shared_ptr<const IComponent> panel = instrNew->getComponentByName(bankName); bankDetMap[bankName] = panel; @@ -779,8 +778,8 @@ void SCDPanelErrors::functionDeriv1D(Jacobian *out, const double *xValues, for (size_t gr = 0; gr < Groups.size(); ++gr) { vector<string> banknames; boost::split(banknames, Groups[gr], boost::is_any_of("/")); - for (auto it = banknames.begin(); it != banknames.end(); ++it) - bankName2Group[(*it)] = gr; + for (auto &bankname : banknames) + bankName2Group[bankname] = gr; } // derivative formulas documentation // Qvec=-K*Vvec +K*v_mag*beamDir @@ -1225,10 +1224,10 @@ SCDPanelErrors::calcWorkspace(DataObjects::PeaksWorkspace_sptr &pwks, Mantid::MantidVecPtr yvals; Mantid::MantidVec &yvalB = yvals.access(); - for (size_t k = 0; k < bankNames.size(); ++k) + for (auto &bankName : bankNames) for (size_t j = 0; j < pwks->rowCount(); ++j) { Geometry::IPeak &peak = pwks->getPeak(static_cast<int>(j)); - if (peak.getBankName().compare(bankNames[k]) == 0) + if (peak.getBankName().compare(bankName) == 0) if (peak.getH() != 0 || peak.getK() != 0 || peak.getL() != 0) if (peak.getH() - floor(peak.getH()) < tolerance || floor(peak.getH() + 1) - peak.getH() < tolerance) diff --git a/Framework/Crystal/src/SaveIsawPeaks.cpp b/Framework/Crystal/src/SaveIsawPeaks.cpp index 76e1bd621522a9852edd6b6ba1aae8533154ec94..3a91d98459667cd1a3d874a4bc63bef176bd8b28 100644 --- a/Framework/Crystal/src/SaveIsawPeaks.cpp +++ b/Framework/Crystal/src/SaveIsawPeaks.cpp @@ -300,8 +300,7 @@ void SaveIsawPeaks::exec() { out << header << std::endl; // Go through each peak at this run / bank - for (size_t i = 0; i < ids.size(); i++) { - size_t wi = ids[i]; + for (auto wi : ids) { Peak &p = peaks[wi]; // Sequence (run) number diff --git a/Framework/Crystal/src/SelectCellWithForm.cpp b/Framework/Crystal/src/SelectCellWithForm.cpp index 276f84df1cf8edc5e929f7e5ffd3d190cb17dec1..220a55246561d9b38c26b5d6e8acc1f663e97094 100644 --- a/Framework/Crystal/src/SelectCellWithForm.cpp +++ b/Framework/Crystal/src/SelectCellWithForm.cpp @@ -96,8 +96,8 @@ Kernel::Matrix<double> SelectCellWithForm::DetermineErrors( } if (!latErrorsValid) { - for (size_t i = 0; i < sigabc.size(); i++) - sigabc[i] = 0; + for (double &sig : sigabc) + sig = 0; return UB; } else diff --git a/Framework/Crystal/src/SortHKL.cpp b/Framework/Crystal/src/SortHKL.cpp index d23588b19657e7a1d92bc69c9cf937d16fe74973..75546b6d3eef079f3971224aad978ecf852f799c 100644 --- a/Framework/Crystal/src/SortHKL.cpp +++ b/Framework/Crystal/src/SortHKL.cpp @@ -45,15 +45,17 @@ void SortHKL::init() { /* TODO: These two properties with string lists keep appearing - * Probably there should be a dedicated Property type or validator. */ std::vector<std::string> pgOptions; - for (size_t i = 0; i < m_pointGroups.size(); ++i) - pgOptions.push_back(m_pointGroups[i]->getName()); + pgOptions.reserve(m_pointGroups.size()); + for (auto &pointGroup : m_pointGroups) + pgOptions.push_back(pointGroup->getName()); declareProperty("PointGroup", pgOptions[0], boost::make_shared<StringListValidator>(pgOptions), "Which point group applies to this crystal?"); std::vector<std::string> centeringOptions; - for (size_t i = 0; i < m_refConds.size(); ++i) - centeringOptions.push_back(m_refConds[i]->getName()); + centeringOptions.reserve(m_refConds.size()); + for (auto &refCond : m_refConds) + centeringOptions.push_back(refCond->getName()); declareProperty("LatticeCentering", centeringOptions[0], boost::make_shared<StringListValidator>(centeringOptions), "Appropriate lattice centering for the peaks."); @@ -169,9 +171,9 @@ ReflectionCondition_sptr SortHKL::getCentering() const { boost::make_shared<ReflectionConditionPrimitive>(); std::string refCondName = getPropertyValue("LatticeCentering"); - for (size_t i = 0; i < m_refConds.size(); ++i) - if (m_refConds[i]->getName() == refCondName) - centering = m_refConds[i]; + for (const auto &refCond : m_refConds) + if (refCond->getName() == refCondName) + centering = refCond; return centering; } @@ -183,9 +185,9 @@ PointGroup_sptr SortHKL::getPointgroup() const { PointGroupFactory::Instance().createPointGroup("-1"); std::string pointGroupName = getPropertyValue("PointGroup"); - for (size_t i = 0; i < m_pointGroups.size(); ++i) - if (m_pointGroups[i]->getName() == pointGroupName) - pointGroup = m_pointGroups[i]; + for (const auto &m_pointGroup : m_pointGroups) + if (m_pointGroup->getName() == pointGroupName) + pointGroup = m_pointGroup; return pointGroup; } diff --git a/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp b/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp index e40d598310d4541b4ee2c6993a2b0fae84b454cf..f685784f879dd4370e3de07330d9ecf62afb704a 100644 --- a/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp +++ b/Framework/Crystal/src/StatisticsOfPeaksWorkspace.cpp @@ -44,8 +44,9 @@ void StatisticsOfPeaksWorkspace::init() { Direction::Input), "An input PeaksWorkspace with an instrument."); std::vector<std::string> propOptions; - for (size_t i = 0; i < m_pointGroups.size(); ++i) - propOptions.push_back(m_pointGroups[i]->getName()); + propOptions.reserve(m_pointGroups.size()); + for (auto &pointGroup : m_pointGroups) + propOptions.push_back(pointGroup->getName()); declareProperty("PointGroup", propOptions[0], boost::make_shared<StringListValidator>(propOptions), "Which point group applies to this crystal?"); @@ -53,8 +54,9 @@ void StatisticsOfPeaksWorkspace::init() { std::vector<std::string> centeringOptions; std::vector<ReflectionCondition_sptr> reflectionConditions = getAllReflectionConditions(); - for (size_t i = 0; i < reflectionConditions.size(); ++i) - centeringOptions.push_back(reflectionConditions[i]->getName()); + centeringOptions.reserve(reflectionConditions.size()); + for (auto &reflectionCondition : reflectionConditions) + centeringOptions.push_back(reflectionCondition->getName()); declareProperty("LatticeCentering", centeringOptions[0], boost::make_shared<StringListValidator>(centeringOptions), "Appropriate lattice centering for the peaks."); diff --git a/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp b/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp index 3d3c2c6a52806eb810030e5cc81c8a2d8a95eae1..39b08f20066600bf5a48f14d68d41a405f4a3f5d 100644 --- a/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp +++ b/Framework/CurveFitting/src/Algorithms/CalculateChiSquared.cpp @@ -467,14 +467,14 @@ void CalculateChiSquared::estimateErrors() { // If there are more than 1, find the one with the smallest chi^2. double chiMin = std::numeric_limits<double>::max(); double parMin = par0; - for (size_t i = 0; i < minima.size(); ++i) { - double value = base->eval(minima[i], P); + for (double minimum : minima) { + double value = base->eval(minimum, P); if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { - g_log.debug() << minima[i] << " (" << value << ") "; + g_log.debug() << minimum << " (" << value << ") "; } if (value < chiMin) { chiMin = value; - parMin = minima[i]; + parMin = minimum; } } if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { @@ -514,8 +514,8 @@ void CalculateChiSquared::estimateErrors() { if (g_log.is(Kernel::Logger::Priority::PRIO_DEBUG)) { g_log.debug() << "Roots: "; - for (size_t i = 0; i < roots.size(); ++i) { - g_log.debug() << roots[i] << ' '; + for (double root : roots) { + g_log.debug() << root << ' '; } g_log.debug() << std::endl; } @@ -668,8 +668,8 @@ void CalculateChiSquared::unfixParameters() { /// Restore the "fixed" status of previously unfixed paramters. void CalculateChiSquared::refixParameters() { - for (auto i = m_fixedParameters.begin(); i != m_fixedParameters.end(); ++i) { - m_function->fix(*i); + for (auto &fixedParameter : m_fixedParameters) { + m_function->fix(fixedParameter); } } diff --git a/Framework/CurveFitting/src/Algorithms/CalculateMSVesuvio.cpp b/Framework/CurveFitting/src/Algorithms/CalculateMSVesuvio.cpp index fe23d129f2dc779767d1ea5d0aad7ad4ffe28202..06c11099d6294d4ac19f396c089b701849259786 100644 --- a/Framework/CurveFitting/src/Algorithms/CalculateMSVesuvio.cpp +++ b/Framework/CurveFitting/src/Algorithms/CalculateMSVesuvio.cpp @@ -651,8 +651,8 @@ CalculateMSVesuvio::calculateE1Range(const double theta, double e1min(1e10), e1max(-1e10); // large so that anything else is smaller const auto &atoms = m_sampleProps->atoms; - for (size_t i = 0; i < atoms.size(); ++i) { - const double mass = atoms[i].mass; + for (const auto &atom : atoms) { + const double mass = atom.mass; const double fraction = (cth + sqrt(mass * mass - sth * sth)) / (1.0 + mass); @@ -661,7 +661,7 @@ CalculateMSVesuvio::calculateE1Range(const double theta, const double qr = sqrt(k0 * k0 + k1 * k1 - 2.0 * k0 * k1 * cth); const double wr = en0 - en1; const double width = PhysicalConstants::E_mev_toNeutronWavenumberSq * - atoms[i].profile * qr / mass; + atom.profile * qr / mass; const double e1a = en0 - wr - 10.0 * width; const double e1b = en0 - wr + 10.0 * width; if (e1a < e1min) @@ -694,20 +694,20 @@ double CalculateMSVesuvio::partialDiffXSec(const double en0, const double en1, const auto &atoms = m_sampleProps->atoms; if (q > 0.0) // avoid continuous checking in loop { - for (size_t i = 0; i < atoms.size(); ++i) { - const double jstddev = atoms[i].profile; - const double mass = atoms[i].mass; + for (const auto &atom : atoms) { + const double jstddev = atom.profile; + const double mass = atom.mass; const double y = mass * w / (4.18036 * q) - 0.5 * q; const double jy = exp(-0.5 * y * y / (jstddev * jstddev)) / (jstddev * rt2pi); const double sqw = mass * jy / (4.18036 * q); - const double sclength = atoms[i].sclength; + const double sclength = atom.sclength; pdcs += sclength * sclength * (k1 / k0) * sqw; } } else { - for (size_t i = 0; i < atoms.size(); ++i) { - const double sclength = atoms[i].sclength; + for (const auto &atom : atoms) { + const double sclength = atom.sclength; pdcs += sclength * sclength; } } diff --git a/Framework/CurveFitting/src/Algorithms/ConvertToYSpace.cpp b/Framework/CurveFitting/src/Algorithms/ConvertToYSpace.cpp index 1f2ba6bfb145c5dc580e11219a74c281bbb5966b..5e27a466007a23ae98de3985611a1fb019bba5b5 100644 --- a/Framework/CurveFitting/src/Algorithms/ConvertToYSpace.cpp +++ b/Framework/CurveFitting/src/Algorithms/ConvertToYSpace.cpp @@ -101,8 +101,8 @@ double ConvertToYSpace::getComponentParameter( boost::dynamic_pointer_cast<const Geometry::DetectorGroup>(comp)) { const auto dets = group->getDetectors(); double avg(0.0); - for (auto it = dets.begin(); it != dets.end(); ++it) { - auto param = pmap.getRecursive((*it)->getComponentID(), name); + for (const auto &det : dets) { + auto param = pmap.getRecursive(det->getComponentID(), name); if (param) avg += param->value<double>(); else diff --git a/Framework/CurveFitting/src/Algorithms/Fit.cpp b/Framework/CurveFitting/src/Algorithms/Fit.cpp index b10b66a8a918dca32327fc32d80a04a0136e399e..691c80925982e6ae5a54273bd4949e54a93a50e6 100644 --- a/Framework/CurveFitting/src/Algorithms/Fit.cpp +++ b/Framework/CurveFitting/src/Algorithms/Fit.cpp @@ -33,8 +33,7 @@ void Fit::initConcrete() { "the fitting function."); declareProperty("Constraints", "", Kernel::Direction::Input); getPointerToProperty("Constraints")->setDocumentation("List of constraints"); - auto mustBePositive = boost::shared_ptr<Kernel::BoundedValidator<int>>( - new Kernel::BoundedValidator<int>()); + auto mustBePositive = boost::make_shared<Kernel::BoundedValidator<int>>(); mustBePositive->setLower(0); declareProperty( "MaxIterations", 500, mustBePositive->clone(), @@ -63,11 +62,11 @@ void Fit::initConcrete() { std::vector<std::string> costFuncOptions = API::CostFunctionFactory::Instance().getKeys(); // select only CostFuncFitting variety - for (auto it = costFuncOptions.begin(); it != costFuncOptions.end(); ++it) { + for (auto &costFuncOption : costFuncOptions) { auto costFunc = boost::dynamic_pointer_cast<CostFunctions::CostFuncFitting>( - API::CostFunctionFactory::Instance().create(*it)); + API::CostFunctionFactory::Instance().create(costFuncOption)); if (!costFunc) { - *it = ""; + costFuncOption = ""; } } declareProperty( @@ -109,11 +108,11 @@ void Fit::initConcrete() { */ void Fit::copyMinimizerOutput(const API::IFuncMinimizer &minimizer) { auto &properties = minimizer.getProperties(); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - if ((**prop).direction() == Kernel::Direction::Output && - (**prop).isValid() == "") { - Kernel::Property *property = (**prop).clone(); - declareProperty(property); + for (auto property : properties) { + if ((*property).direction() == Kernel::Direction::Output && + (*property).isValid() == "") { + Kernel::Property *clonedProperty = (*property).clone(); + declareProperty(clonedProperty); } } } diff --git a/Framework/CurveFitting/src/Algorithms/FitPowderDiffPeaks.cpp b/Framework/CurveFitting/src/Algorithms/FitPowderDiffPeaks.cpp index 2971289eff1e4bdd818468de59caefe5237264d9..769166f1478efff4f8d4f3aab5d4fd3fc1f7d1f5 100644 --- a/Framework/CurveFitting/src/Algorithms/FitPowderDiffPeaks.cpp +++ b/Framework/CurveFitting/src/Algorithms/FitPowderDiffPeaks.cpp @@ -433,8 +433,7 @@ void FitPowderDiffPeaks::fitPeaksRobust() { "Failed to fit the right most peak. Unable to process. "); stringstream robmsgss; - for (size_t i = 0; i < peakparnames.size(); ++i) { - string &parname = peakparnames[i]; + for (auto &parname : peakparnames) { robmsgss << parname << " = " << thispeak->getParameter(parname) << endl; } g_log.information() << "[DB1151] Robust Fit Result: Chi^2 = " << chi2 @@ -1212,8 +1211,7 @@ void FitPowderDiffPeaks::fitPeaksWithGoodStartingValues() { } else { // Fit overlapped peaks vector<BackToBackExponential_sptr> peaksgroup; - for (size_t index = 0; index < indexpeakgroup.size(); ++index) { - size_t ipk = indexpeakgroup[index]; + for (auto ipk : indexpeakgroup) { BackToBackExponential_sptr temppeak = m_vecPeakFunctions[ipk].second.second; peaksgroup.push_back(temppeak); @@ -1469,8 +1467,7 @@ bool FitPowderDiffPeaks::fitSinglePeakConfident( stringstream debugss; debugss << "DB1251 Single Peak Confident Fit Result: Chi^2 = " << chi2 << endl; - for (size_t i = 0; i < parnames.size(); ++i) { - string &parname = parnames[i]; + for (auto &parname : parnames) { debugss << parname << " = " << peak->getParameter(parname) << endl; } g_log.notice(debugss.str()); @@ -1659,8 +1656,8 @@ void FitPowderDiffPeaks::storeFunctionParameters( IFunction_sptr function, std::map<string, double> ¶mmaps) { vector<string> paramnames = function->getParameterNames(); parammaps.clear(); - for (size_t i = 0; i < paramnames.size(); ++i) - parammaps.emplace(paramnames[i], function->getParameter(paramnames[i])); + for (auto ¶mname : paramnames) + parammaps.emplace(paramname, function->getParameter(paramname)); return; } @@ -1670,8 +1667,7 @@ void FitPowderDiffPeaks::storeFunctionParameters( void FitPowderDiffPeaks::restoreFunctionParameters( IFunction_sptr function, map<string, double> parammap) { vector<string> paramnames = function->getParameterNames(); - for (size_t i = 0; i < paramnames.size(); ++i) { - string &parname = paramnames[i]; + for (auto &parname : paramnames) { auto miter = parammap.find(parname); if (miter != parammap.end()) function->setParameter(parname, miter->second); @@ -1701,8 +1697,8 @@ bool FitPowderDiffPeaks::doFit1PeakSimple( dbss << peakfunction->asString() << endl; dbss << "Starting Value: "; vector<string> names = peakfunction->getParameterNames(); - for (size_t i = 0; i < names.size(); ++i) - dbss << names[i] << "= " << peakfunction->getParameter(names[i]) << ", \t"; + for (auto &name : names) + dbss << name << "= " << peakfunction->getParameter(name) << ", \t"; for (size_t i = 0; i < dataws->readX(workspaceindex).size(); ++i) dbss << dataws->readX(workspaceindex)[i] << "\t\t" << dataws->readY(workspaceindex)[i] << "\t\t" @@ -1983,8 +1979,8 @@ bool FitPowderDiffPeaks::fitOverlappedPeaks( // 7. Set up the composite function CompositeFunction_sptr peaksfunction(new CompositeFunction()); - for (size_t i = 0; i < peaks.size(); ++i) - peaksfunction->addFunction(peaks[i]); + for (auto &peak : peaks) + peaksfunction->addFunction(peak); // 8. Fit multiple peaks vector<double> chi2s; @@ -2171,9 +2167,7 @@ void FitPowderDiffPeaks::estimatePeakHeightsLeBail( */ void FitPowderDiffPeaks::setOverlappedPeaksConstraints( vector<BackToBackExponential_sptr> peaks) { - for (size_t ipk = 0; ipk < peaks.size(); ++ipk) { - BackToBackExponential_sptr thispeak = peaks[ipk]; - + for (auto thispeak : peaks) { // 1. Set constraint on X. double fwhm = thispeak->fwhm(); double centre = thispeak->centre(); @@ -2199,8 +2193,8 @@ bool FitPowderDiffPeaks::doFitNPeaksSimple( stringstream dbss0; dbss0 << "Starting Value: "; vector<string> names = peaksfunc->getParameterNames(); - for (size_t i = 0; i < names.size(); ++i) - dbss0 << names[i] << "= " << peaksfunc->getParameter(names[i]) << ", \t"; + for (auto &name : names) + dbss0 << name << "= " << peaksfunc->getParameter(name) << ", \t"; g_log.information() << "DBx430 " << dbss0.str() << endl; // 2. Create fit @@ -2225,8 +2219,8 @@ bool FitPowderDiffPeaks::doFitNPeaksSimple( // 4. Output stringstream dbss; dbss << "Fit N-Peaks @ "; - for (size_t i = 0; i < peakfuncs.size(); ++i) - dbss << peakfuncs[i]->centre() << ", "; + for (auto &peakfunc : peakfuncs) + dbss << peakfunc->centre() << ", "; if (isexecute) { // Figure out result @@ -2911,8 +2905,7 @@ FitPowderDiffPeaks::genPeak(map<string, int> hklmap, // Set peak parameters std::map<std::string, double>::iterator miter; - for (size_t ipn = 0; ipn < tnb2bfuncparnames.size(); ++ipn) { - string parname = tnb2bfuncparnames[ipn]; + for (auto parname : tnb2bfuncparnames) { if (parname.compare("Height") != 0) { miter = m_instrumentParmaeters.find(parname); if (miter == m_instrumentParmaeters.end()) { diff --git a/Framework/CurveFitting/src/Algorithms/LeBailFit.cpp b/Framework/CurveFitting/src/Algorithms/LeBailFit.cpp index f55df11c200e7395020b7a295adf94a0f070601f..209e6c7447b5b609dc41df6be9a31558211bc40a 100644 --- a/Framework/CurveFitting/src/Algorithms/LeBailFit.cpp +++ b/Framework/CurveFitting/src/Algorithms/LeBailFit.cpp @@ -671,8 +671,7 @@ void LeBailFit::execRefineBackground() { outtablews->addColumn("double", "Value"); outtablews->addColumn("double", "Error"); - for (size_t i = 0; i < m_bkgdParameterNames.size(); ++i) { - string parname = m_bkgdParameterNames[i]; + for (auto parname : m_bkgdParameterNames) { double parvalue = m_backgroundFunction->getParameter(parname); TableRow newrow = outtablews->appendRow(); @@ -1616,14 +1615,14 @@ void LeBailFit::doMarkovChain(const map<string, Parameter> ¶mmap, for (size_t icycle = 1; icycle <= maxcycles; ++icycle) { // Refine parameters (for all parameters in turn) to data with background // removed - for (auto giter = m_MCGroups.begin(); giter != m_MCGroups.end(); ++giter) { + for (auto &MCGroup : m_MCGroups) { // Propose new value for ONE AND ONLY ONE Monte Carlo parameter group /* int igroup = giter->first; // group id g_log.debug() << "BigTrouble: Group " << igroup << "\n"; */ bool hasnewvalues = - proposeNewValues(giter->second, currR, mapCurrParameter, newparammap, + proposeNewValues(MCGroup.second, currR, mapCurrParameter, newparammap, prevcyclebetterR); if (!hasnewvalues) { @@ -1650,10 +1649,7 @@ void LeBailFit::doMarkovChain(const map<string, Parameter> ¶mmap, } else { acceptchange = acceptOrDeny(currR, newR); - if (newR.Rwp < currR.Rwp) - prevcyclebetterR = true; - else - prevcyclebetterR = false; + prevcyclebetterR = newR.Rwp < currR.Rwp; } g_log.debug() << "[DBx317] Step " << icycle @@ -1859,8 +1855,8 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { m_MCGroups.emplace(0, geomparams); dboutss << "Geometry parameters: "; - for (size_t i = 0; i < geomparams.size(); ++i) - dboutss << geomparams[i] << "\t\t"; + for (auto &geomparam : geomparams) + dboutss << geomparam << "\t\t"; dboutss << "\n"; // b. Alphas @@ -1872,8 +1868,8 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { m_MCGroups.emplace(1, alphs); dboutss << "Alpha parameters"; - for (size_t i = 0; i < alphs.size(); ++i) - dboutss << alphs[i] << "\t\t"; + for (auto &alph : alphs) + dboutss << alph << "\t\t"; dboutss << "\n"; // c. Beta @@ -1885,8 +1881,8 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { m_MCGroups.emplace(2, betas); dboutss << "Beta parameters"; - for (size_t i = 0; i < betas.size(); ++i) - dboutss << betas[i] << "\t\t"; + for (auto &beta : betas) + dboutss << beta << "\t\t"; dboutss << "\n"; // d. Sig @@ -1897,8 +1893,8 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { m_MCGroups.emplace(3, sigs); dboutss << "Sig parameters"; - for (size_t i = 0; i < sigs.size(); ++i) - dboutss << sigs[i] << "\t\t"; + for (auto &sig : sigs) + dboutss << sig << "\t\t"; dboutss << "\n"; g_log.notice(dboutss.str()); @@ -1907,16 +1903,14 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { // 2. Dictionary for each parameter for non-negative, mcX0, mcX1 // a) Sig0, Sig1, Sig2 - for (size_t i = 0; i < sigs.size(); ++i) { - string parname = sigs[i]; + for (auto parname : sigs) { m_funcParameters[parname].mcA0 = 2.0; m_funcParameters[parname].mcA1 = 1.0; m_funcParameters[parname].nonnegative = true; } // b) Alpha - for (size_t i = 0; i < alphs.size(); ++i) { - string parname = alphs[i]; + for (auto parname : alphs) { m_funcParameters[parname].mcA1 = 1.0; m_funcParameters[parname].nonnegative = false; } @@ -1926,8 +1920,7 @@ void LeBailFit::setupBuiltInRandomWalkStrategy() { m_funcParameters["Alph1t"].mcA0 = 0.05; // c) Beta - for (size_t i = 0; i < betas.size(); ++i) { - string parname = betas[i]; + for (auto parname : betas) { m_funcParameters[parname].mcA1 = 1.0; m_funcParameters[parname].nonnegative = false; } @@ -2158,9 +2151,8 @@ bool LeBailFit::proposeNewValues(vector<string> mcgroup, Rfactor r, // Find out parameters to refine in this step/MC group g_log.debug() << "Parameter Number In Group = " << mcgroup.size() << "\n"; - for (size_t i = 0; i < mcgroup.size(); ++i) { + for (auto paramname : mcgroup) { // Find out the i-th parameter to be refined or not - string paramname = mcgroup[i]; auto mapiter = curparammap.find(paramname); if (mapiter == curparammap.end()) { stringstream errmsg; diff --git a/Framework/CurveFitting/src/Algorithms/LeBailFunction.cpp b/Framework/CurveFitting/src/Algorithms/LeBailFunction.cpp index 39501a81671b31e39ad45a69e7e96a292a8d078a..f9b594569d6099f9570b9ca4d12fd6e0a3d086d1 100644 --- a/Framework/CurveFitting/src/Algorithms/LeBailFunction.cpp +++ b/Framework/CurveFitting/src/Algorithms/LeBailFunction.cpp @@ -67,8 +67,7 @@ LeBailFunction::LeBailFunction(std::string peaktype) { m_orderedProfileParameterNames.end()); // Peak parameter values - for (size_t i = 0; i < m_peakParameterNameVec.size(); ++i) { - string parname = m_peakParameterNameVec[i]; + for (auto parname : m_peakParameterNameVec) { m_functionParameters.emplace(parname, 0.0); } @@ -320,8 +319,7 @@ IPowderDiffPeakFunction_sptr LeBailFunction::generatePeak(int h, int k, int l) { boost::dynamic_pointer_cast<IPowderDiffPeakFunction>(f); peak->setMillerIndex(h, k, l); - for (size_t i = 0; i < m_peakParameterNameVec.size(); ++i) { - string parname = m_peakParameterNameVec[i]; + for (auto parname : m_peakParameterNameVec) { double parvalue = m_functionParameters[parname]; peak->setParameter(parname, parvalue); } @@ -371,8 +369,7 @@ bool LeBailFunction::calculatePeaksIntensities( } // Set zero to all peaks out of boundary - for (size_t i = 0; i < outboundpeakvec.size(); ++i) { - IPowderDiffPeakFunction_sptr peak = outboundpeakvec[i]; + for (auto peak : outboundpeakvec) { peak->setHeight(0.); } @@ -477,9 +474,9 @@ bool LeBailFunction::calculateGroupPeakIntensities( << ", TOF_h = " << thispeak->centre() << ", FWHM = " << thispeak->fwhm() << "\n"; vector<string> peakparamnames = thispeak->getParameterNames(); - for (size_t ipar = 0; ipar < peakparamnames.size(); ++ipar) { - errss << "\t" << peakparamnames[ipar] << " = " - << thispeak->getParameter(peakparamnames[ipar]) << "\n"; + for (auto &peakparamname : peakparamnames) { + errss << "\t" << peakparamname << " = " + << thispeak->getParameter(peakparamname) << "\n"; } } diff --git a/Framework/CurveFitting/src/Algorithms/PlotPeakByLogValue.cpp b/Framework/CurveFitting/src/Algorithms/PlotPeakByLogValue.cpp index 80cb69dec153f273a1682b88a415735293bf24af..cc22a39584e37889407a39af610813ba4b8b9922 100644 --- a/Framework/CurveFitting/src/Algorithms/PlotPeakByLogValue.cpp +++ b/Framework/CurveFitting/src/Algorithms/PlotPeakByLogValue.cpp @@ -360,13 +360,12 @@ void PlotPeakByLogValue::exec() { groupAlg->execute(); } - for (auto it = m_minimizerWorkspaces.begin(); - it != m_minimizerWorkspaces.end(); ++it) { - const std::string paramName = (*it).first; + for (auto &minimizerWorkspace : m_minimizerWorkspaces) { + const std::string paramName = minimizerWorkspace.first; API::IAlgorithm_sptr groupAlg = AlgorithmManager::Instance().createUnmanaged("GroupWorkspaces"); groupAlg->initialize(); - groupAlg->setProperty("InputWorkspaces", (*it).second); + groupAlg->setProperty("InputWorkspaces", minimizerWorkspace.second); groupAlg->setProperty("OutputWorkspace", m_baseName + "_" + paramName); groupAlg->execute(); } @@ -519,8 +518,8 @@ PlotPeakByLogValue::makeNames() const { typedef Poco::StringTokenizer tokenizer; tokenizer names(inputList, ";", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); - for (auto it = names.begin(); it != names.end(); ++it) { - tokenizer params(*it, ",", tokenizer::TOK_TRIM); + for (const auto &input : names) { + tokenizer params(input, ",", tokenizer::TOK_TRIM); std::string name = params[0]; int wi = default_wi; int spec = default_spec; @@ -572,8 +571,8 @@ PlotPeakByLogValue::makeNames() const { boost::dynamic_pointer_cast<API::WorkspaceGroup>(ws); if (wsg) { std::vector<std::string> wsNames = wsg->getNames(); - for (auto i = wsNames.begin(); i != wsNames.end(); ++i) { - nameList.push_back(InputData(*i, wi, -1, period, start, end)); + for (auto &wsName : wsNames) { + nameList.push_back(InputData(wsName, wi, -1, period, start, end)); } continue; } @@ -602,13 +601,13 @@ PlotPeakByLogValue::getMinimizerString(const std::string &wsName, auto minimizer = FuncMinimizerFactory::Instance().createMinimizer(format); auto minimizerProps = minimizer->getProperties(); - for (auto it = minimizerProps.begin(); it != minimizerProps.end(); ++it) { + for (auto &minimizerProp : minimizerProps) { Mantid::API::WorkspaceProperty<> *wsProp = - dynamic_cast<Mantid::API::WorkspaceProperty<> *>(*it); + dynamic_cast<Mantid::API::WorkspaceProperty<> *>(minimizerProp); if (wsProp) { - std::string wsPropValue = (*it)->value(); + std::string wsPropValue = minimizerProp->value(); if (wsPropValue != "") { - std::string wsPropName = (*it)->name(); + std::string wsPropName = minimizerProp->name(); m_minimizerWorkspaces[wsPropName].push_back(wsPropValue); } } diff --git a/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters.cpp b/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters.cpp index efcba12be4acdaaf8c953fb11a8ee16982ec273b..6908a7607e20d6b3d2ad797cd3a5dc472ae71714 100644 --- a/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters.cpp +++ b/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters.cpp @@ -243,8 +243,7 @@ void RefinePowderInstrumentParameters::fitInstrumentParameters() { stringstream msgss; msgss << "Set Instrument Function Parameter : " << endl; std::map<std::string, double>::iterator paramiter; - for (size_t i = 0; i < funparamnames.size(); ++i) { - string parname = funparamnames[i]; + for (auto parname : funparamnames) { paramiter = m_FuncParameters.find(parname); if (paramiter == m_FuncParameters.end()) { // Not found and thus skip @@ -336,8 +335,7 @@ void RefinePowderInstrumentParameters::fitInstrumentParameters() { cout << "Homemade Chi^2 = " << selfchi2 << endl; // 5. Update fitted parameters - for (size_t i = 0; i < funparamnames.size(); ++i) { - std::string parname = funparamnames[i]; + for (auto parname : funparamnames) { double parvalue = fitfunc->getParameter(parname); m_FuncParameters[parname] = parvalue; } @@ -723,11 +721,7 @@ void RefinePowderInstrumentParameters::doParameterSpaceRandomWalk( // << ". Acceptance Prob. = " << prob << "; Random = " << randnumber // << endl; - if (randnumber < prob) { - accept = true; - } else { - accept = false; - } + accept = randnumber < prob; // d. Adjust step size if (false) { @@ -890,26 +884,26 @@ void RefinePowderInstrumentParameters::genPeaksFromTable( sigma2 = -1; API::TableRow row = peakparamws->getRow(ir); - for (size_t ic = 0; ic < colnames.size(); ++ic) { - if (colnames[ic].compare("H") == 0) + for (auto &colname : colnames) { + if (colname.compare("H") == 0) row >> h; - else if (colnames[ic].compare("K") == 0) + else if (colname.compare("K") == 0) row >> k; - else if (colnames[ic].compare("L") == 0) + else if (colname.compare("L") == 0) row >> l; - else if (colnames[ic].compare("Alpha") == 0) + else if (colname.compare("Alpha") == 0) row >> alpha; - else if (colnames[ic].compare("Beta") == 0) + else if (colname.compare("Beta") == 0) row >> beta; - else if (colnames[ic].compare("Sigma2") == 0) + else if (colname.compare("Sigma2") == 0) row >> sigma2; - else if (colnames[ic].compare("Sigma") == 0) + else if (colname.compare("Sigma") == 0) row >> sigma; - else if (colnames[ic].compare("Chi2") == 0) + else if (colname.compare("Chi2") == 0) row >> chi2; - else if (colnames[ic].compare("Height") == 0) + else if (colname.compare("Height") == 0) row >> height; - else if (colnames[ic].compare("TOF_h") == 0) + else if (colname.compare("TOF_h") == 0) row >> tof_h; else { try { @@ -1074,9 +1068,8 @@ void RefinePowderInstrumentParameters::importMonteCarloParametersFromTable( // 3. Retrieve the information for geometry parameters map<string, vector<double>>::iterator mit; - for (size_t i = 0; i < parameternames.size(); ++i) { + for (auto parname : parameternames) { // a) Get on hold of the MC parameter vector - string parname = parameternames[i]; mit = mcparameters.find(parname); if (mit == mcparameters.end()) { // Not found the parameter. raise error! @@ -1129,8 +1122,7 @@ void RefinePowderInstrumentParameters::calculateThermalNeutronSpecial( double width = m_Function->getParameter("Width"); double tcross = m_Function->getParameter("Tcross"); - for (size_t i = 0; i < vec_d.size(); ++i) { - double dh = vec_d[i]; + for (double dh : vec_d) { double n = 0.5 * gsl_sf_erfc(width * (tcross - 1 / dh)); vec_n.push_back(n); } @@ -1249,8 +1241,8 @@ RefinePowderInstrumentParameters::genMCResultTable() { tablews->addColumn("double", "Chi2"); tablews->addColumn("double", "GSLChi2"); - for (size_t i = 0; i < m_PeakFunctionParameterNames.size(); ++i) { - tablews->addColumn("double", m_PeakFunctionParameterNames[i]); + for (auto &peakFunctionParameterName : m_PeakFunctionParameterNames) { + tablews->addColumn("double", peakFunctionParameterName); } // 2. Put values in diff --git a/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters3.cpp b/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters3.cpp index 797cfe0a6f61320798f1e7fc365e66b43b634804..20816c8166ca4635d99345a4087f8d7a14ce7e16 100644 --- a/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters3.cpp +++ b/Framework/CurveFitting/src/Algorithms/RefinePowderInstrumentParameters3.cpp @@ -516,13 +516,12 @@ double RefinePowderInstrumentParameters3::doSimulatedAnnealing( void RefinePowderInstrumentParameters3::proposeNewValues( vector<string> mcgroup, map<string, Parameter> &curparammap, map<string, Parameter> &newparammap, double currchisq) { - for (size_t i = 0; i < mcgroup.size(); ++i) { + for (auto paramname : mcgroup) { // random number between -1 and 1 double randomnumber = 2 * static_cast<double>(rand()) / static_cast<double>(RAND_MAX) - 1.0; // parameter information - string paramname = mcgroup[i]; Parameter param = curparammap[paramname]; double stepsize = m_dampingFactor * currchisq * (param.curvalue * param.mcA1 + param.mcA0) * @@ -719,8 +718,8 @@ void RefinePowderInstrumentParameters3::setupRandomWalkStrategy( mcgroups.push_back(geomparams); dboutss << "Geometry parameters: "; - for (size_t i = 0; i < geomparams.size(); ++i) - dboutss << geomparams[i] << "\t\t"; + for (auto &geomparam : geomparams) + dboutss << geomparam << "\t\t"; dboutss << endl; g_log.notice(dboutss.str()); @@ -1183,8 +1182,7 @@ void RefinePowderInstrumentParameters3::setFunctionParameterValues( msgss << "Set Instrument Function Parameter : " << endl; std::map<std::string, Parameter>::iterator paramiter; - for (size_t i = 0; i < funparamnames.size(); ++i) { - string parname = funparamnames[i]; + for (auto parname : funparamnames) { paramiter = params.find(parname); if (paramiter != params.end()) { @@ -1409,8 +1407,7 @@ void restoreFunctionParameterValue( map<string, Parameter> ¶mmap) { vector<string> parnames = function->getParameterNames(); - for (size_t i = 0; i < parnames.size(); ++i) { - string &parname = parnames[i]; + for (auto &parname : parnames) { map<string, pair<double, double>>::iterator miter; miter = parvaluemap.find(parname); diff --git a/Framework/CurveFitting/src/Algorithms/SplineBackground.cpp b/Framework/CurveFitting/src/Algorithms/SplineBackground.cpp index c9ba83eb4f203689aa8651bdf57762652a205b0c..0fb49b14a9c4755c7872d673ec6b276e6e9012b9 100644 --- a/Framework/CurveFitting/src/Algorithms/SplineBackground.cpp +++ b/Framework/CurveFitting/src/Algorithms/SplineBackground.cpp @@ -67,8 +67,8 @@ void SplineBackground::exec() { std::vector<int> masked(Y.size()); if (isMasked) { auto maskedBins = inWS->maskedBins(spec); - for (auto it = maskedBins.begin(); it != maskedBins.end(); ++it) - masked[it->first] = 1; + for (auto &maskedBin : maskedBins) + masked[maskedBin.first] = 1; n -= static_cast<int>(inWS->maskedBins(spec).size()); } diff --git a/Framework/CurveFitting/src/FuncMinimizers/DampingMinimizer.cpp b/Framework/CurveFitting/src/FuncMinimizers/DampingMinimizer.cpp index 08114e04a546b699b4f359ba826924cf850a1917..5f009d69c922e016876ab0a12a30735909adb645 100644 --- a/Framework/CurveFitting/src/FuncMinimizers/DampingMinimizer.cpp +++ b/Framework/CurveFitting/src/FuncMinimizers/DampingMinimizer.cpp @@ -110,11 +110,7 @@ bool DampingMinimizer::iterate(size_t) { GSLVector p(n); m_leastSquares->getParameters(p); double dx_norm = gsl_blas_dnrm2(dx.gsl()); - if (dx_norm < m_relTol) { - return false; - } - - return true; + return dx_norm >= m_relTol; } /// Return current value of the cost function diff --git a/Framework/CurveFitting/src/Functions/ChebfunBase.cpp b/Framework/CurveFitting/src/Functions/ChebfunBase.cpp index 00c5646d0092a33700510ba77bb56db4ed9b9089..b8b205f88ac6007cc4b8504f39bc718d55db6f5b 100644 --- a/Framework/CurveFitting/src/Functions/ChebfunBase.cpp +++ b/Framework/CurveFitting/src/Functions/ChebfunBase.cpp @@ -170,8 +170,8 @@ bool ChebfunBase::hasConverged(const std::vector<double> &a, double maxA, if (a.empty()) return true; if (maxA == 0.0) { - for (auto it = a.begin(); it != a.end(); ++it) { - double tmp = fabs(*it); + for (double coeff : a) { + double tmp = fabs(coeff); if (tmp > maxA) { maxA = tmp; } @@ -186,10 +186,7 @@ bool ChebfunBase::hasConverged(const std::vector<double> &a, double maxA, for (auto i = a.rbegin() + shift; i != a.rend() - 1; ++i) { if (*i == 0.0) continue; - if ((fabs(*i) + fabs(*(i + 1))) / maxA / 2 < tolerance) - return true; - else - return false; + return (fabs(*i) + fabs(*(i + 1))) / maxA / 2 < tolerance; } return false; } @@ -400,8 +397,8 @@ ChebfunBase::bestFitTempl(double start, double end, FunctionType f, a = base.calcA(p2); if (calcMaxA) { maxA = 0.0; - for (auto it = a.begin(); it != a.end(); ++it) { - double tmp = fabs(*it); + for (double coeff : a) { + double tmp = fabs(coeff); if (tmp > maxA) { maxA = tmp; } @@ -492,8 +489,8 @@ std::vector<double> ChebfunBase::linspace(size_t n) const { std::vector<double> space(n); double x = m_start; const double dx = width() / double(n - 1); - for (auto s = space.begin(); s != space.end(); ++s) { - *s = x; + for (double &s : space) { + s = x; x += dx; } space.back() = m_end; diff --git a/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp b/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp index fa9ed893cb00c3a6785ce0b2285aafa9fe457461..e42ae776c6b9b51d4ab82628a586013b6075dedc 100644 --- a/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp +++ b/Framework/CurveFitting/src/Functions/ComptonScatteringCountRate.cpp @@ -309,8 +309,8 @@ void ComptonScatteringCountRate::cacheComptonProfile( const size_t paramsOffset) { m_profiles.push_back(profile.get()); auto fixedParams = profile->intensityParameterIndices(); - for (size_t j = 0; j < fixedParams.size(); ++j) { - const size_t indexOfFixed = paramsOffset + fixedParams[j]; + for (auto fixedParam : fixedParams) { + const size_t indexOfFixed = paramsOffset + fixedParam; this->fix(indexOfFixed); m_fixedParamIndices.push_back(indexOfFixed); } diff --git a/Framework/CurveFitting/src/Functions/Convolution.cpp b/Framework/CurveFitting/src/Functions/Convolution.cpp index 3040b82b33ab02654240fb8de542a71961c27f5c..b86738b13b44bcb172d92e6757780c9f1ef9c7c3 100644 --- a/Framework/CurveFitting/src/Functions/Convolution.cpp +++ b/Framework/CurveFitting/src/Functions/Convolution.cpp @@ -260,8 +260,7 @@ void Convolution::function(const FunctionDomain &domain, std::transform(out, out + nData, tmp.data(), out, std::plus<double>()); } else if (!dltFuns.empty()) { std::vector<double> x(nData); - for (auto it = dltFuns.begin(); it != dltFuns.end(); ++it) { - auto df = *it; + for (auto df : dltFuns) { double shift = -df->getParameter("Centre"); dltF = df->getParameter("Height") * df->HeightPrefactor(); std::transform(xValues, xValues + nData, x.data(), diff --git a/Framework/CurveFitting/src/Functions/DiffSphere.cpp b/Framework/CurveFitting/src/Functions/DiffSphere.cpp index f65b53e3f6cbe554f0b32ce3f28f0743f2e6dcaf..22d2e0f8baa899ce887ef6783b8d966b3abe4828 100644 --- a/Framework/CurveFitting/src/Functions/DiffSphere.cpp +++ b/Framework/CurveFitting/src/Functions/DiffSphere.cpp @@ -133,10 +133,10 @@ void InelasticDiffSphere::initAlphaCoeff() { * numerical indeterminacies. To avoid them, we will interpolate linearly. */ void InelasticDiffSphere::initLinJlist() { - for (size_t i = 0; i < m_xnl.size(); i++) { + for (auto &coeff : m_xnl) { linearJ abJ; - double x = m_xnl[i].x; // eigenvalue for a (n, l) pair - unsigned int l = static_cast<unsigned int>(m_xnl[i].l); + double x = coeff.x; // eigenvalue for a (n, l) pair + unsigned int l = static_cast<unsigned int>(coeff.l); double Qa = x - m_divZone; // left of the numerical divergence point double J0 = (Qa * boost::math::sph_bessel(l + 1, Qa) - l * boost::math::sph_bessel(l, Qa)) / diff --git a/Framework/CurveFitting/src/Functions/PawleyFunction.cpp b/Framework/CurveFitting/src/Functions/PawleyFunction.cpp index 33ca783ae1cb436bc4919d2cda947888a670fec7..592b966ed50125747d516be163c6795e01fca567 100644 --- a/Framework/CurveFitting/src/Functions/PawleyFunction.cpp +++ b/Framework/CurveFitting/src/Functions/PawleyFunction.cpp @@ -497,8 +497,8 @@ void PawleyFunction::setPeaks(const std::vector<Kernel::V3D> &hkls, double fwhm, double height) { clearPeaks(); - for (size_t i = 0; i < hkls.size(); ++i) { - addPeak(hkls[i], fwhm, height); + for (const auto &hkl : hkls) { + addPeak(hkl, fwhm, height); } } diff --git a/Framework/CurveFitting/src/Functions/ProcessBackground.cpp b/Framework/CurveFitting/src/Functions/ProcessBackground.cpp index f2c8318059a3e69f77e91532096b0458751996d5..2dbd2247574549c2d0f79ad0f0cc3f0f3aead376 100644 --- a/Framework/CurveFitting/src/Functions/ProcessBackground.cpp +++ b/Framework/CurveFitting/src/Functions/ProcessBackground.cpp @@ -587,9 +587,9 @@ void ProcessBackground::selectFromGivenFunction() { int bkgdorder = static_cast<int>(parmap.size() - 1); // A0 - A(n) total n+1 parameters bkgdfunc->setAttributeValue("n", bkgdorder); - for (auto mit = parmap.begin(); mit != parmap.end(); ++mit) { - string parname = mit->first; - double parvalue = mit->second; + for (auto &mit : parmap) { + string parname = mit.first; + double parvalue = mit.second; bkgdfunc->setParameter(parname, parvalue); } @@ -1085,8 +1085,8 @@ size_t RemovePeaks::excludePeaks(vector<double> v_inX, vector<bool> &v_useX, // Count non-excluded region size_t count = 0; - for (size_t i = 0; i < v_useX.size(); ++i) - if (v_useX[i]) + for (auto &&useX : v_useX) + if (useX) ++count; return count; diff --git a/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp b/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp index 568f42ad24ddb8f563f929fca59c3213d3a20907..8d7ad1be517ed59b3e465654ad9f17c689942149 100644 --- a/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp +++ b/Framework/CurveFitting/src/Functions/TabulatedFunction.cpp @@ -55,9 +55,9 @@ void TabulatedFunction::eval(double scaling, double xshift, double xscale, // shift and scale the domain over which the function is defined std::vector<double> xData(m_xData); - for (auto it = xData.begin(); it != xData.end(); ++it) { - *it *= xscale; - *it += xshift; + for (double &value : xData) { + value *= xscale; + value += xshift; } const double xStart = xData.front(); diff --git a/Framework/CurveFitting/src/GSLVector.cpp b/Framework/CurveFitting/src/GSLVector.cpp index cdbc2a12db0e7f571b5a8703754af69f1805cfd1..95ae1c7e434ddad71dbf0574b4ab897d67c906e2 100644 --- a/Framework/CurveFitting/src/GSLVector.cpp +++ b/Framework/CurveFitting/src/GSLVector.cpp @@ -138,8 +138,8 @@ double GSLVector::norm() const { return sqrt(norm2()); } /// Get vector's norm squared double GSLVector::norm2() const { double res = 0.0; - for (auto el = m_data.begin(); el != m_data.end(); ++el) { - res += (*el) * (*el); + for (double el : m_data) { + res += el * el; } return res; } diff --git a/Framework/CurveFitting/src/IFittingAlgorithm.cpp b/Framework/CurveFitting/src/IFittingAlgorithm.cpp index 49001631dab17f6f22bbcced21f2b069b6ceb536..f82e9b0356defd1123abf6f349d2a43488c09e84 100644 --- a/Framework/CurveFitting/src/IFittingAlgorithm.cpp +++ b/Framework/CurveFitting/src/IFittingAlgorithm.cpp @@ -238,10 +238,10 @@ void IFittingAlgorithm::addWorkspaces() { new MultiDomainCreator(this, m_workspacePropertyNames)); } auto props = getProperties(); - for (auto prop = props.begin(); prop != props.end(); ++prop) { - if ((**prop).direction() == Kernel::Direction::Input && - dynamic_cast<API::IWorkspaceProperty *>(*prop)) { - const std::string workspacePropertyName = (**prop).name(); + for (auto &prop : props) { + if ((*prop).direction() == Kernel::Direction::Input && + dynamic_cast<API::IWorkspaceProperty *>(prop)) { + const std::string workspacePropertyName = (*prop).name(); API::Workspace_const_sptr ws = getProperty(workspacePropertyName); IDomainCreator *creator = createDomainCreator(m_function.get(), ws.get(), workspacePropertyName, diff --git a/Framework/CurveFitting/src/MultiDomainCreator.cpp b/Framework/CurveFitting/src/MultiDomainCreator.cpp index 202c4dbd10aed99cdfb06ef99bb83e9972117cb7..f27cb25fb60f7adcb7b7f6cb3d1c578b08d79592 100644 --- a/Framework/CurveFitting/src/MultiDomainCreator.cpp +++ b/Framework/CurveFitting/src/MultiDomainCreator.cpp @@ -43,12 +43,12 @@ void MultiDomainCreator::createDomain( auto jointDomain = new API::JointDomain; API::FunctionValues_sptr values; i0 = 0; - for (auto c = m_creators.begin(); c != m_creators.end(); ++c) { - if (!(*c)) { + for (auto &creator : m_creators) { + if (!creator) { throw std::runtime_error("Missing domain creator"); } API::FunctionDomain_sptr domain; - (**c).createDomain(domain, values, i0); + (*creator).createDomain(domain, values, i0); jointDomain->addDomain(domain); i0 += domain->size(); } diff --git a/Framework/CurveFitting/src/SeqDomain.cpp b/Framework/CurveFitting/src/SeqDomain.cpp index 8a704c1745664d0961b48088642ba0fdffc410e6..b23d2b0b0245579ea3f37c9fd35220481ff2f8e8 100644 --- a/Framework/CurveFitting/src/SeqDomain.cpp +++ b/Framework/CurveFitting/src/SeqDomain.cpp @@ -10,8 +10,8 @@ namespace CurveFitting { /// Return the number of points in the domain size_t SeqDomain::size() const { size_t n = 0; - for (auto it = m_creators.begin(); it != m_creators.end(); ++it) { - n += (**it).getDomainSize(); + for (const auto &creator : m_creators) { + n += creator->getDomainSize(); } return n; } diff --git a/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp b/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp index 1a9fc5688f86ba5be061c175d3a8c1d1aa5fcb65..84889b2cbf4033d95a65ac424fa851507c63cf6a 100644 --- a/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp +++ b/Framework/DataHandling/src/AppendGeometryToSNSNexus.cpp @@ -220,11 +220,11 @@ void AppendGeometryToSNSNexus::exec() { polar_angle.reserve(dets.size()); azimuthal_angle.reserve(dets.size()); - for (std::size_t i = 0; i < dets.size(); i++) { - pixel_id.push_back(dets[i]->getID()); - distance.push_back(dets[i]->getDistance(*sample)); - azimuthal_angle.push_back(dets[i]->getPhi()); - polar_angle.push_back(ws->detectorTwoTheta(dets[i])); + for (auto &det : dets) { + pixel_id.push_back(det->getID()); + distance.push_back(det->getDistance(*sample)); + azimuthal_angle.push_back(det->getPhi()); + polar_angle.push_back(ws->detectorTwoTheta(det)); } // Write Pixel ID to file diff --git a/Framework/DataHandling/src/CreateChunkingFromInstrument.cpp b/Framework/DataHandling/src/CreateChunkingFromInstrument.cpp index a9b9b61848453294ded4892fdd96e6962e6a5b97..486164218792e12d1031aedbb2980b32348a872c 100644 --- a/Framework/DataHandling/src/CreateChunkingFromInstrument.cpp +++ b/Framework/DataHandling/src/CreateChunkingFromInstrument.cpp @@ -241,17 +241,17 @@ string parentName(IComponent_const_sptr comp, const string &prefix) { */ string parentName(IComponent_const_sptr comp, const vector<string> &names) { // handle the special case of the component has the name - for (auto name = names.begin(); name != names.end(); ++name) - if (name->compare(comp->getName()) == 0) - return (*name); + for (const auto &name : names) + if (name.compare(comp->getName()) == 0) + return name; // find the parent with the correct name IComponent_const_sptr parent = comp->getParent(); if (parent) { // see if this is the parent - for (auto name = names.begin(); name != names.end(); ++name) - if (name->compare(parent->getName()) == 0) - return (*name); + for (const auto &name : names) + if (name.compare(parent->getName()) == 0) + return name; // or recurse return parentName(parent, names); @@ -443,12 +443,13 @@ void CreateChunkingFromInstrument::exec() { throw std::runtime_error("Failed to find any banks in the instrument"); // fill in the table workspace - for (auto group = grouping.begin(); group != grouping.end(); ++group) { + for (auto &group : grouping) { stringstream banks; - for (auto bank = group->second.begin(); bank != group->second.end(); - ++bank) - banks << (*bank) << ","; - + // for (auto bank = group.second.begin(); bank != group.second.end(); + // ++bank) + for (auto bank : group.second) { + banks << bank << ","; + } // remove the trailing comma string banksStr = banks.str(); banksStr = banksStr.substr(0, banksStr.size() - 1); diff --git a/Framework/DataHandling/src/CreateSimulationWorkspace.cpp b/Framework/DataHandling/src/CreateSimulationWorkspace.cpp index 686bcf0a35f10f0ad4f8eb8eb9f6c21991103a48..1782db8987b6e658f92d9e3828466cdf7e57eb61 100644 --- a/Framework/DataHandling/src/CreateSimulationWorkspace.cpp +++ b/Framework/DataHandling/src/CreateSimulationWorkspace.cpp @@ -302,12 +302,12 @@ MantidVecPtr CreateSimulationWorkspace::createBinBoundaries() const { */ void CreateSimulationWorkspace::applyDetectorMapping() { size_t wsIndex(0); - for (auto iter = m_detGroups.begin(); iter != m_detGroups.end(); ++iter) { + for (auto &detGroup : m_detGroups) { ISpectrum *spectrum = m_outputWS->getSpectrum(wsIndex); spectrum->setSpectrumNo( static_cast<specid_t>(wsIndex + 1)); // Ensure a contiguous mapping spectrum->clearDetectorIDs(); - spectrum->addDetectorIDs(iter->second); + spectrum->addDetectorIDs(detGroup.second); ++wsIndex; } } diff --git a/Framework/DataHandling/src/DetermineChunking.cpp b/Framework/DataHandling/src/DetermineChunking.cpp index 0f0f865ae6b46e770fc06cd67c6065b5ef939262..90b880d1931192e044870e1a5b3f731eba861171 100644 --- a/Framework/DataHandling/src/DetermineChunking.cpp +++ b/Framework/DataHandling/src/DetermineChunking.cpp @@ -148,8 +148,8 @@ void DetermineChunking::exec() { string dataDir; LoadPreNexus lp; lp.parseRuninfo(filename, dataDir, eventFilenames); - for (size_t i = 0; i < eventFilenames.size(); i++) { - BinaryFile<DasEvent> eventfile(dataDir + eventFilenames[i]); + for (auto &eventFilename : eventFilenames) { + BinaryFile<DasEvent> eventfile(dataDir + eventFilename); // Factor of 2 for compression filesize += static_cast<double>(eventfile.getNumElements()) * 48.0 / (1024.0 * 1024.0 * 1024.0); @@ -326,8 +326,8 @@ std::string DetermineChunking::setTopEntryName(std::string filename) { */ FileType DetermineChunking::getFileType(const string &filename) { // check for prenexus - for (int i = 0; i < NUM_EXT_PRENEXUS; ++i) { - if (filename.find(PRENEXUS_EXT[i]) != std::string::npos) { + for (const auto &extension : PRENEXUS_EXT) { + if (filename.find(extension) != std::string::npos) { g_log.information() << "Determined \'" << filename << "\' is a prenexus file\n"; return PRENEXUS_FILE; @@ -335,8 +335,8 @@ FileType DetermineChunking::getFileType(const string &filename) { } // check for histogram nexus - for (int i = 0; i < NUM_EXT_HISTO_NEXUS; ++i) { - if (filename.find(HISTO_NEXUS_EXT[i]) != std::string::npos) { + for (const auto &extension : HISTO_NEXUS_EXT) { + if (filename.find(extension) != std::string::npos) { g_log.information() << "Determined \'" << filename << "\' is a histogram nexus file\n"; return HISTO_NEXUS_FILE; @@ -344,8 +344,8 @@ FileType DetermineChunking::getFileType(const string &filename) { } // check for event nexus - must be last because a valid extension is ".nxs" - for (int i = 0; i < NUM_EXT_EVENT_NEXUS; ++i) { - if (filename.find(EVENT_NEXUS_EXT[i]) != std::string::npos) { + for (const auto &extension : EVENT_NEXUS_EXT) { + if (filename.find(extension) != std::string::npos) { g_log.information() << "Determined \'" << filename << "\' is an event nexus file\n"; return EVENT_NEXUS_FILE; @@ -353,8 +353,8 @@ FileType DetermineChunking::getFileType(const string &filename) { } // check for isis raw files - for (int i = 0; i < NUM_EXT_RAW; ++i) { - if (filename.find(RAW_EXT[i]) != std::string::npos) { + for (const auto &extension : RAW_EXT) { + if (filename.find(extension) != std::string::npos) { g_log.information() << "Determined \'" << filename << "\' is an ISIS raw file\n"; return RAW_FILE; diff --git a/Framework/DataHandling/src/DownloadInstrument.cpp b/Framework/DataHandling/src/DownloadInstrument.cpp index d4ec987ce6de9cd83a70d67ef7dcc0cd77bd6ac6..8df3f25d29e63809b35e5726baf9a8bdecbd7351 100644 --- a/Framework/DataHandling/src/DownloadInstrument.cpp +++ b/Framework/DataHandling/src/DownloadInstrument.cpp @@ -107,9 +107,9 @@ void DownloadInstrument::exec() { << " from the instrument repository" << std::endl; } - for (auto itMap = fileMap.begin(); itMap != fileMap.end(); ++itMap) { + for (auto &itMap : fileMap) { // download a file - doDownloadFile(itMap->first, itMap->second); + doDownloadFile(itMap.first, itMap.second); } setProperty("FileDownloadCount", static_cast<int>(fileMap.size())); @@ -179,8 +179,7 @@ DownloadInstrument::StringToStringMap DownloadInstrument::processRepository() { std::set<std::string> repoFilenames; - for (Json::ArrayIndex i = 0; i < serverContents.size(); ++i) { - const auto &serverElement = serverContents[i]; + for (auto &serverElement : serverContents) { std::string name = serverElement.get("name", "").asString(); repoFilenames.insert(name); Poco::Path filePath(localPath, name); @@ -272,7 +271,7 @@ size_t DownloadInstrument::removeOrphanedFiles( const std::set<std::string> &filenamesToKeep) const { // hold files to delete in a set so we don't remove files while iterating over // the directory. - std::set<std::string> filesToDelete; + std::vector<std::string> filesToDelete; try { using Poco::DirectoryIterator; @@ -285,7 +284,7 @@ size_t DownloadInstrument::removeOrphanedFiles( filenamesToKeep.end()) { g_log.debug() << "File not found in remote instrument repository, will " "be deleted: " << entryPath.getFileName() << std::endl; - filesToDelete.insert(it->path()); + filesToDelete.push_back(it->path()); } } } catch (Poco::Exception &ex) { @@ -302,8 +301,8 @@ size_t DownloadInstrument::removeOrphanedFiles( // delete any identified files try { - for (auto it = filesToDelete.begin(); it != filesToDelete.end(); ++it) { - Poco::File file(*it); + for (const auto &filename : filesToDelete) { + Poco::File file(filename); file.remove(); } } catch (Poco::Exception &ex) { diff --git a/Framework/DataHandling/src/EventWorkspaceCollection.cpp b/Framework/DataHandling/src/EventWorkspaceCollection.cpp index 34e6e4ed15088eff3c65bbc6dbfd56b63d29effb..3e98e6664a2f9389e28d18d5dab4b8894a1be108 100644 --- a/Framework/DataHandling/src/EventWorkspaceCollection.cpp +++ b/Framework/DataHandling/src/EventWorkspaceCollection.cpp @@ -29,9 +29,9 @@ void copyLogs(const EventWorkspace_sptr &from, EventWorkspace_sptr &to) { // from the logs, get all the properties that don't overwrite any // prop. already set in the sink workspace (like 'filename'). auto props = from->mutableRun().getLogData(); - for (size_t j = 0; j < props.size(); j++) { - if (!to->mutableRun().hasProperty(props[j]->name())) { - to->mutableRun().addLogData(props[j]->clone()); + for (auto &prop : props) { + if (!to->mutableRun().hasProperty(prop->name())) { + to->mutableRun().addLogData(prop->clone()); } } } @@ -110,8 +110,8 @@ void EventWorkspaceCollection::setNPeriods( } void EventWorkspaceCollection::reserveEventListAt(size_t wi, size_t size) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->getEventList(wi).reserve(size); + for (auto &ws : m_WsVec) { + ws->getEventList(wi).reserve(size); } } @@ -128,8 +128,8 @@ API::Workspace_sptr EventWorkspaceCollection::combinedWorkspace() { final = getSingleHeldWorkspace(); } else { auto wsg = boost::make_shared<API::WorkspaceGroup>(); - for (size_t i = 0; i < m_WsVec.size(); ++i) { - wsg->addWorkspace(m_WsVec[i]); + for (auto &ws : m_WsVec) { + wsg->addWorkspace(ws); } final = wsg; } @@ -160,10 +160,10 @@ EventWorkspaceCollection::getSpectrum(const size_t index) const { void EventWorkspaceCollection::setSpectrumNumbersFromUniqueSpectra( const std::set<int> uniqueSpectra) { // For each workspace, update all the spectrum numbers - for (auto ws = m_WsVec.begin(); ws != m_WsVec.end(); ++ws) { + for (auto &ws : m_WsVec) { size_t counter = 0; - for (auto it = uniqueSpectra.begin(); it != uniqueSpectra.end(); ++it) { - (*ws)->getSpectrum(counter)->setSpectrumNo(*it); + for (auto spectrum : uniqueSpectra) { + ws->getSpectrum(counter)->setSpectrumNo(spectrum); ++counter; } } @@ -171,16 +171,16 @@ void EventWorkspaceCollection::setSpectrumNumbersFromUniqueSpectra( void EventWorkspaceCollection::setSpectrumNumberForAllPeriods( const size_t spectrumNumber, const specid_t specid) { - for (auto ws = m_WsVec.begin(); ws != m_WsVec.end(); ++ws) { - auto spec = (*ws)->getSpectrum(spectrumNumber); + for (auto &ws : m_WsVec) { + auto spec = ws->getSpectrum(spectrumNumber); spec->setSpectrumNo(specid); } } void EventWorkspaceCollection::setDetectorIdsForAllPeriods( const size_t spectrumNumber, const detid_t id) { - for (auto ws = m_WsVec.begin(); ws != m_WsVec.end(); ++ws) { - auto spec = (*ws)->getSpectrum(spectrumNumber); + for (auto &ws : m_WsVec) { + auto spec = ws->getSpectrum(spectrumNumber); spec->setDetectorID(id); } } @@ -228,40 +228,40 @@ Kernel::DateAndTime EventWorkspaceCollection::getFirstPulseTime() const { return m_WsVec[0]->getFirstPulseTime(); } void EventWorkspaceCollection::setAllX(Kernel::cow_ptr<MantidVec> &x) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->setAllX(x); + for (auto &ws : m_WsVec) { + ws->setAllX(x); } } size_t EventWorkspaceCollection::getNumberEvents() const { return m_WsVec[0]->getNumberEvents(); // Should be the sum across all periods? } void EventWorkspaceCollection::resizeTo(const size_t size) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->resizeTo(size); // Creates the EventLists + for (auto &ws : m_WsVec) { + ws->resizeTo(size); // Creates the EventLists } } void EventWorkspaceCollection::padSpectra(const std::vector<int32_t> &padding) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->padSpectra(padding); // Set detector ids and spectrum numbers + for (auto &ws : m_WsVec) { + ws->padSpectra(padding); // Set detector ids and spectrum numbers } } void EventWorkspaceCollection::setInstrument( const Geometry::Instrument_const_sptr &inst) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->setInstrument(inst); + for (auto &ws : m_WsVec) { + ws->setInstrument(inst); } } void EventWorkspaceCollection::setMonitorWorkspace( const boost::shared_ptr<API::MatrixWorkspace> &monitorWS) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->setMonitorWorkspace( + for (auto &ws : m_WsVec) { + ws->setMonitorWorkspace( monitorWS); // TODO, do we really set the same monitor on all periods??? } } void EventWorkspaceCollection::updateSpectraUsing( const API::SpectrumDetectorMapping &map) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->updateSpectraUsing(map); + for (auto &ws : m_WsVec) { + ws->updateSpectraUsing(map); } } @@ -271,43 +271,43 @@ DataObjects::EventList *EventWorkspaceCollection::getEventListPtr(size_t i) { } void EventWorkspaceCollection::populateInstrumentParameters() { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->populateInstrumentParameters(); + for (auto &ws : m_WsVec) { + ws->populateInstrumentParameters(); } } void EventWorkspaceCollection::setGeometryFlag(const int flag) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->mutableSample().setGeometryFlag(flag); + for (auto &ws : m_WsVec) { + ws->mutableSample().setGeometryFlag(flag); } } void EventWorkspaceCollection::setThickness(const float flag) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->mutableSample().setThickness(flag); + for (auto &ws : m_WsVec) { + ws->mutableSample().setThickness(flag); } } void EventWorkspaceCollection::setHeight(const float flag) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->mutableSample().setHeight(flag); + for (auto &ws : m_WsVec) { + ws->mutableSample().setHeight(flag); } } void EventWorkspaceCollection::setWidth(const float flag) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->mutableSample().setWidth(flag); + for (auto &ws : m_WsVec) { + ws->mutableSample().setWidth(flag); } } void EventWorkspaceCollection::setTitle(std::string title) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - m_WsVec[i]->setTitle(title); + for (auto &ws : m_WsVec) { + ws->setTitle(title); } } void EventWorkspaceCollection::applyFilter( boost::function<void(MatrixWorkspace_sptr)> func) { - for (size_t i = 0; i < m_WsVec.size(); ++i) { - func(m_WsVec[i]); + for (auto &ws : m_WsVec) { + func(ws); } } diff --git a/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp b/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp index 8f52b179fe538ba904bb4fcff6cc53de33a5f17c..cefa605741b11c350c107dcf0fec4539fb8db31b 100644 --- a/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp +++ b/Framework/DataHandling/src/FilterEventsByLogValuePreNexus.cpp @@ -173,14 +173,12 @@ static string generateMappingfileName(EventWorkspace_sptr &wksp) { const string CAL("_CAL"); const size_t CAL_LEN = CAL.length(); // cache to make life easier vector<string> files; - for (size_t i = 0; i < dirs.size(); ++i) { - if ((dirs[i].length() > CAL_LEN) && - (dirs[i].compare(dirs[i].length() - CAL.length(), CAL.length(), CAL) == - 0)) { - if (Poco::File(base.path() + "/" + dirs[i] + "/calibrations/" + mapping) + for (auto &dir : dirs) { + if ((dir.length() > CAL_LEN) && + (dir.compare(dir.length() - CAL.length(), CAL.length(), CAL) == 0)) { + if (Poco::File(base.path() + "/" + dir + "/calibrations/" + mapping) .exists()) - files.push_back(base.path() + "/" + dirs[i] + "/calibrations/" + - mapping); + files.push_back(base.path() + "/" + dir + "/calibrations/" + mapping); } } @@ -509,8 +507,8 @@ void FilterEventsByLogValuePreNexus::processProperties() { m_loadOnlySomeSpectra = (this->m_spectraList.size() > 0); // Turn the spectra list into a map, for speed of access - for (auto it = m_spectraList.begin(); it != m_spectraList.end(); it++) - spectraLoadMap[*it] = true; + for (auto spectra : m_spectraList) + spectraLoadMap[spectra] = true; //--------------------------------------------------------------------------- // Other features @@ -777,8 +775,8 @@ void FilterEventsByLogValuePreNexus::runLoadInstrument( vector<string> eventExts(EVENT_EXTS, EVENT_EXTS + NUM_EXT); std::reverse(eventExts.begin(), eventExts.end()); - for (size_t i = 0; i < eventExts.size(); ++i) { - size_t pos = instrument.find(eventExts[i]); + for (auto &eventExt : eventExts) { + size_t pos = instrument.find(eventExt); if (pos != string::npos) { instrument = instrument.substr(0, pos); break; @@ -2244,13 +2242,13 @@ void FilterEventsByLogValuePreNexus::setupPixelSpectrumMap( eventws->getInstrument()->getDetectors(detector_map); // Set up - for (auto it = detector_map.begin(); it != detector_map.end(); it++) { - if (!it->second->isMonitor()) { + for (auto &det : detector_map) { + if (!det.second->isMonitor()) { // Add non-monitor detector ID - size_t workspaceIndex = m_pixelToWkspindex[it->first]; + size_t workspaceIndex = m_pixelToWkspindex[det.first]; // this->m_pixelToWkspindex[it->first] = workspaceIndex; EventList &spec = eventws->getOrAddEventList(workspaceIndex); - spec.addDetectorID(it->first); + spec.addDetectorID(det.first); // Start the spectrum number at 1 spec.setSpectrumNo(specid_t(workspaceIndex + 1)); } diff --git a/Framework/DataHandling/src/FindDetectorsPar.cpp b/Framework/DataHandling/src/FindDetectorsPar.cpp index 9f79f21d05501466ce1037f654d3105d47901a1c..4874b561d55fdfaeb5b1558cdc76badab7408381 100644 --- a/Framework/DataHandling/src/FindDetectorsPar.cpp +++ b/Framework/DataHandling/src/FindDetectorsPar.cpp @@ -378,16 +378,16 @@ void FindDetectorsPar::extractAndLinearize( this->detID.resize(nDetectors); nDetectors = 0; - for (size_t i = 0; i < detPar.size(); i++) { - if (detPar[i].detID < 0) + for (const auto ¶meter : detPar) { + if (parameter.detID < 0) continue; - azimuthal[nDetectors] = detPar[i].azimutAngle; - polar[nDetectors] = detPar[i].polarAngle; - azimuthalWidth[nDetectors] = detPar[i].azimWidth; - polarWidth[nDetectors] = detPar[i].polarWidth; - secondaryFlightpath[nDetectors] = detPar[i].secondaryFlightPath; - detID[nDetectors] = static_cast<size_t>(detPar[i].detID); + azimuthal[nDetectors] = parameter.azimutAngle; + polar[nDetectors] = parameter.polarAngle; + azimuthalWidth[nDetectors] = parameter.azimWidth; + polarWidth[nDetectors] = parameter.polarWidth; + secondaryFlightpath[nDetectors] = parameter.secondaryFlightPath; + detID[nDetectors] = static_cast<size_t>(parameter.detID); nDetectors++; } // store caluclated value diff --git a/Framework/DataHandling/src/GroupDetectors2.cpp b/Framework/DataHandling/src/GroupDetectors2.cpp index f3388a94e41f5d3da0d75c8bc1d584670c227054..ffbb3bcf6f0de47d10323369159b43e29da43a15 100644 --- a/Framework/DataHandling/src/GroupDetectors2.cpp +++ b/Framework/DataHandling/src/GroupDetectors2.cpp @@ -528,8 +528,7 @@ void GroupDetectors2::processXMLFile(std::string fname, std::vector<size_t> &wsindexes = sit->second; - for (size_t i = 0; i < detids.size(); i++) { - detid_t detid = detids[i]; + for (auto detid : detids) { auto ind = detIdToWiMap.find(detid); if (ind != detIdToWiMap.end()) { size_t wsid = ind->second; @@ -557,8 +556,7 @@ void GroupDetectors2::processXMLFile(std::string fname, std::vector<size_t> &wsindexes = sit->second; - for (size_t i = 0; i < spectra.size(); i++) { - int specid = spectra[i]; + for (auto specid : spectra) { auto ind = specs2index.find(specid); if (ind != specs2index.end()) { size_t wsid = ind->second; @@ -618,9 +616,8 @@ void GroupDetectors2::processGroupingWorkspace( det_ids.push_back(det->getID()); } - for (auto dit = det_ids.begin(); dit != det_ids.end(); ++dit) { + for (auto det_id : det_ids) { // translate detectors to target det ws indexes - detid_t det_id = *dit; size_t targetWSIndex = detIdToWiMap[det_id]; targetWSIndexSet.insert(targetWSIndex); // mark as used @@ -635,10 +632,9 @@ void GroupDetectors2::processGroupingWorkspace( } // Build m_GroupSpecInds (group -> list of ws indices) - for (auto dit = group2WSIndexSetmap.begin(); dit != group2WSIndexSetmap.end(); - ++dit) { - size_t groupid = dit->first; - std::set<size_t> &targetWSIndexSet = dit->second; + for (auto &dit : group2WSIndexSetmap) { + size_t groupid = dit.first; + std::set<size_t> &targetWSIndexSet = dit.second; std::vector<size_t> tempv; tempv.assign(targetWSIndexSet.begin(), targetWSIndexSet.end()); m_GroupSpecInds.insert( @@ -687,9 +683,8 @@ void GroupDetectors2::processMatrixWorkspace( if (detGroup) { det_ids = detGroup->getDetectorIDs(); - for (auto dit = det_ids.begin(); dit != det_ids.end(); ++dit) { + for (auto det_id : det_ids) { // translate detectors to target det ws indexes - detid_t det_id = *dit; size_t targetWSIndex = detIdToWiMap[det_id]; targetWSIndexSet.insert(targetWSIndex); // mark as used @@ -704,10 +699,9 @@ void GroupDetectors2::processMatrixWorkspace( } // Build m_GroupSpecInds (group -> list of ws indices) - for (auto dit = group2WSIndexSetmap.begin(); dit != group2WSIndexSetmap.end(); - ++dit) { - size_t groupid = dit->first; - std::set<size_t> &targetWSIndexSet = dit->second; + for (auto &dit : group2WSIndexSetmap) { + size_t groupid = dit.first; + std::set<size_t> &targetWSIndexSet = dit.second; if (!targetWSIndexSet.empty()) { std::vector<size_t> tempv; tempv.assign(targetWSIndexSet.begin(), targetWSIndexSet.end()); @@ -853,11 +847,11 @@ void GroupDetectors2::readSpectraIndexes(std::string line, std::string seperator) { // remove comments and white space Poco::StringTokenizer dataComment(line, seperator, IGNORE_SPACES); - for (auto itr = dataComment.begin(); itr != dataComment.end(); ++itr) { + for (const auto &itr : dataComment) { std::vector<size_t> specNums; specNums.reserve(output.capacity()); - RangeHelper::getList(*itr, specNums); + RangeHelper::getList(itr, specNums); std::vector<size_t>::const_iterator specN = specNums.begin(); for (; specN != specNums.end(); ++specN) { @@ -960,10 +954,7 @@ size_t GroupDetectors2::formGroups(API::MatrixWorkspace_const_sptr inputWS, size_t nonMaskedSpectra(0); beh->dataX(outIndex)[0] = 0.0; beh->dataE(outIndex)[0] = 0.0; - for (auto wsIter = it->second.cbegin(); wsIter != it->second.cend(); - ++wsIter) { - const size_t originalWI = *wsIter; - + for (auto originalWI : it->second) { // detectors to add to firstSpecNum const ISpectrum *fromSpectrum = inputWS->getSpectrum(originalWI); @@ -1068,10 +1059,7 @@ GroupDetectors2::formGroupsEvent(DataObjects::EventWorkspace_const_sptr inputWS, size_t nonMaskedSpectra(0); beh->dataX(outIndex)[0] = 0.0; beh->dataE(outIndex)[0] = 0.0; - for (auto wsIter = it->second.cbegin(); wsIter != it->second.cend(); - ++wsIter) { - const size_t originalWI = *wsIter; - + for (auto originalWI : it->second) { const EventList &fromEL = inputWS->getEventList(originalWI); // Add the event lists with the operator outEL += fromEL; @@ -1138,11 +1126,10 @@ void GroupDetectors2::moveOthers(const std::set<int64_t> &unGroupedSet, static_cast<double>(unGroupedSet.size()); // go thorugh all the spectra in the input workspace - for (auto copyFrIt = unGroupedSet.cbegin(); copyFrIt != unGroupedSet.cend(); - ++copyFrIt) { - if (*copyFrIt == USED) + for (auto copyFrIt : unGroupedSet) { + if (copyFrIt == USED) continue; // Marked as not to be used - size_t sourceIndex = static_cast<size_t>(*copyFrIt); + size_t sourceIndex = static_cast<size_t>(copyFrIt); // The input spectrum we'll copy const ISpectrum *inputSpec = inputWS->getSpectrum(sourceIndex); @@ -1196,11 +1183,10 @@ void GroupDetectors2::moveOthersEvent( static_cast<double>(unGroupedSet.size()); // go thorugh all the spectra in the input workspace - for (auto copyFrIt = unGroupedSet.cbegin(); copyFrIt != unGroupedSet.cend(); - ++copyFrIt) { - if (*copyFrIt == USED) + for (auto copyFrIt : unGroupedSet) { + if (copyFrIt == USED) continue; // Marked as not to be used - size_t sourceIndex = static_cast<size_t>(*copyFrIt); + size_t sourceIndex = static_cast<size_t>(copyFrIt); // The input spectrum we'll copy const EventList &inputSpec = inputWS->getEventList(sourceIndex); @@ -1321,8 +1307,7 @@ void translateAdd(const std::string &instructions, boost::split(spectra, instructions, boost::is_any_of("+")); std::vector<int> outSpectra; - for (auto sIt = spectra.begin(); sIt != spectra.end(); ++sIt) { - std::string spectrum = *sIt; + for (auto spectrum : spectra) { // remove leading/trailing whitespace boost::trim(spectrum); // add this spectrum to the group we're about to add @@ -1416,8 +1401,7 @@ void GroupDetectors2::translateInstructions(const std::string &instructions, std::vector<std::string> groups; boost::split(groups, instructions, boost::is_any_of(",")); - for (auto gIt = groups.begin(); gIt != groups.end(); ++gIt) { - std::string groupStr = *gIt; + for (auto groupStr : groups) { // remove leading/trailing whitespace boost::trim(groupStr); @@ -1442,9 +1426,9 @@ void GroupDetectors2::translateInstructions(const std::string &instructions, // We now have the groups as a vector of a vector of ints. Turn this into a // string, just like the contents of a map file. commands << outGroups.size() << "\n"; - for (size_t i = 0; i < outGroups.size(); ++i) { - const int groupId = outGroups[i][0] + 1; - const int groupSize = static_cast<int>(outGroups[i].size()); + for (auto &outGroup : outGroups) { + const int groupId = outGroup[0] + 1; + const int groupSize = static_cast<int>(outGroup.size()); // Comment the output for readability commands << "# Group " << groupId; @@ -1456,8 +1440,8 @@ void GroupDetectors2::translateInstructions(const std::string &instructions, // Group members // So far we've been using 0-indexed ids, but the mapfile syntax expects // 1-indexed ids, so we add 1 to the spectra ids here. - for (size_t j = 0; j < outGroups[i].size(); ++j) - commands << (j > 0 ? " " : "") << outGroups[i][j] + 1; + for (size_t j = 0; j < outGroup.size(); ++j) + commands << (j > 0 ? " " : "") << outGroup[j] + 1; commands << "\n"; } } diff --git a/Framework/DataHandling/src/ISISDataArchive.cpp b/Framework/DataHandling/src/ISISDataArchive.cpp index 7bea0f139c19b804241589b8e5b5a9933ddcaceb..480ac90a3d9b70f8032d0bbe2870ad5d10ba041c 100644 --- a/Framework/DataHandling/src/ISISDataArchive.cpp +++ b/Framework/DataHandling/src/ISISDataArchive.cpp @@ -42,16 +42,16 @@ const char *URL_PREFIX = "http://data.isis.rl.ac.uk/where.py/unixdir?name="; std::string ISISDataArchive::getArchivePath(const std::set<std::string> &filenames, const std::vector<std::string> &exts) const { - for (auto iter = filenames.cbegin(); iter != filenames.cend(); ++iter) { - g_log.debug() << *iter << ")\n"; + for (const auto &filename : filenames) { + g_log.debug() << filename << ")\n"; } - for (auto iter = exts.cbegin(); iter != exts.cend(); ++iter) { - g_log.debug() << *iter << ")\n"; + for (const auto &ext : exts) { + g_log.debug() << ext << ")\n"; } - for (auto ext = exts.cbegin(); ext != exts.cend(); ++ext) { - for (auto it = filenames.cbegin(); it != filenames.cend(); ++it) { - const std::string fullPath = getPath(*it + *ext); + for (const auto &ext : exts) { + for (const auto &filename : filenames) { + const std::string fullPath = getPath(filename + ext); if (!fullPath.empty()) return fullPath; } // it diff --git a/Framework/DataHandling/src/ISISRunLogs.cpp b/Framework/DataHandling/src/ISISRunLogs.cpp index 5502c31b438857fe7263e889effb98a5935478e4..5978bba9167c7ce4756ab0375f697fedb4166753 100644 --- a/Framework/DataHandling/src/ISISRunLogs.cpp +++ b/Framework/DataHandling/src/ISISRunLogs.cpp @@ -25,9 +25,9 @@ ISISRunLogs::ISISRunLogs(const API::Run &icpRun, const int totalNumPeriods) : m_logParser(), m_numOfPeriods(totalNumPeriods) { // ICP event either in form icp_event or icpevent static const char *icpLogNames[2] = {"icp_event", "icpevent"}; - for (int i = 0; i < 2; ++i) { + for (auto &icpLogName : icpLogNames) { try { - Kernel::Property *icpLog = icpRun.getLogData(icpLogNames[i]); + Kernel::Property *icpLog = icpRun.getLogData(icpLogName); m_logParser.reset(new LogParser(icpLog)); return; } catch (std::runtime_error &) { diff --git a/Framework/DataHandling/src/Load.cpp b/Framework/DataHandling/src/Load.cpp index 1193e606e4b7bce45b844f875269ce3c243866ba..2ebe08683fb39b8d19b22d17156204045b1a3716 100644 --- a/Framework/DataHandling/src/Load.cpp +++ b/Framework/DataHandling/src/Load.cpp @@ -53,11 +53,11 @@ bool isSingleFile(const std::vector<std::vector<std::string>> &fileNames) { std::string generateWsNameFromFileNames(std::vector<std::string> filenames) { std::string wsName(""); - for (size_t i = 0; i < filenames.size(); ++i) { + for (auto &filename : filenames) { if (!wsName.empty()) wsName += "_"; - Poco::Path path(filenames[i]); + Poco::Path path(filename); wsName += path.getBaseName(); } @@ -214,9 +214,9 @@ API::IAlgorithm_sptr Load::getFileLoader(const std::string &filePath) { void Load::findFilenameProperty(const API::IAlgorithm_sptr &loader) { // Use the first file property as the main Filename const auto &props = loader->getProperties(); - for (auto it = props.begin(); it != props.end(); ++it) { - auto *fp = dynamic_cast<API::MultipleFileProperty *>(*it); - auto *fp2 = dynamic_cast<API::FileProperty *>(*it); + for (auto prop : props) { + auto *fp = dynamic_cast<API::MultipleFileProperty *>(prop); + auto *fp2 = dynamic_cast<API::FileProperty *>(prop); if (fp) { m_filenamePropName = fp->name(); break; @@ -244,8 +244,8 @@ void Load::declareLoaderProperties(const API::IAlgorithm_sptr &loader) { // so take care of ensuring Load has the correct ones // THIS IS A COPY as the properties are mutated as we move through them const std::vector<Property *> existingProps = this->getProperties(); - for (size_t i = 0; i < existingProps.size(); ++i) { - const std::string name = existingProps[i]->name(); + for (auto existingProp : existingProps) { + const std::string name = existingProp->name(); // Wipe all properties except the Load native ones if (m_baseProps.find(name) == m_baseProps.end()) { this->removeProperty(name); @@ -438,10 +438,9 @@ void Load::loadMultipleFiles() { std::vector<std::string> childWsNames = group->getNames(); size_t count = 1; - for (auto childWsName = childWsNames.begin(); - childWsName != childWsNames.end(); ++childWsName) { - if (*childWsName == outputWsName) { - Mantid::API::Workspace_sptr child = group->getItem(*childWsName); + for (auto &childWsName : childWsNames) { + if (childWsName == outputWsName) { + Mantid::API::Workspace_sptr child = group->getItem(childWsName); // child->setName(child->getName() + "_" + // boost::lexical_cast<std::string>(count)); const std::string childName = @@ -453,14 +452,13 @@ void Load::loadMultipleFiles() { childWsNames = group->getNames(); count = 1; - for (auto childWsName = childWsNames.begin(); - childWsName != childWsNames.end(); ++childWsName) { - Workspace_sptr childWs = group->getItem(*childWsName); + for (auto &childWsName : childWsNames) { + Workspace_sptr childWs = group->getItem(childWsName); std::string outWsPropName = "OutputWorkspace_" + boost::lexical_cast<std::string>(count); ++count; declareProperty(new WorkspaceProperty<Workspace>( - outWsPropName, *childWsName, Direction::Output)); + outWsPropName, childWsName, Direction::Output)); setProperty(outWsPropName, childWs); } } @@ -515,13 +513,13 @@ void Load::setUpLoader(API::IAlgorithm_sptr &loader, const double startProgress, // If output workspaces are nameless, give them a temporary name to satisfy // validator const std::vector<Property *> &props = loader->getProperties(); - for (unsigned int i = 0; i < props.size(); ++i) { - auto wsProp = dynamic_cast<IWorkspaceProperty *>(props[i]); + for (auto prop : props) { + auto wsProp = dynamic_cast<IWorkspaceProperty *>(prop); if (wsProp && !wsProp->isOptional() && - props[i]->direction() == Direction::Output) { - if (props[i]->value().empty()) - props[i]->setValue("LoadChildWorkspace"); + prop->direction() == Direction::Output) { + if (prop->value().empty()) + prop->setValue("LoadChildWorkspace"); } } if (startProgress >= 0. && endProgress > startProgress && endProgress <= 1.) { @@ -646,8 +644,8 @@ API::Workspace_sptr Load::loadFileToWs(const std::string &fileName, const std::vector<Kernel::Property *> &props = getProperties(); // Loop through and set the properties on the Child Algorithm - for (auto prop = props.cbegin(); prop != props.cend(); ++prop) { - const std::string &propName = (*prop)->name(); + for (auto prop : props) { + const std::string &propName = prop->name(); if (this->existsProperty(propName)) { if (propName == "Filename") { @@ -730,9 +728,9 @@ API::WorkspaceGroup_sptr Load::groupWsList(const std::vector<API::Workspace_sptr> &wsList) { WorkspaceGroup_sptr group = WorkspaceGroup_sptr(new WorkspaceGroup); - for (auto ws = wsList.begin(); ws != wsList.end(); ++ws) { + for (const auto &ws : wsList) { WorkspaceGroup_sptr isGroup = - boost::dynamic_pointer_cast<WorkspaceGroup>(*ws); + boost::dynamic_pointer_cast<WorkspaceGroup>(ws); // If the ws to add is already a group, then add its children individually. if (isGroup) { std::vector<std::string> childrenNames = isGroup->getNames(); @@ -749,7 +747,7 @@ Load::groupWsList(const std::vector<API::Workspace_sptr> &wsList) { // Remove the old group from the ADS AnalysisDataService::Instance().remove(isGroup->getName()); } else { - group->addWorkspace(*ws); + group->addWorkspace(ws); } } diff --git a/Framework/DataHandling/src/LoadAscii.cpp b/Framework/DataHandling/src/LoadAscii.cpp index ee39464e0c9157d562dee20310c21efeb745c2e8..8f3de67bd410d205f27c8be7613efe9a4f7a28e7 100644 --- a/Framework/DataHandling/src/LoadAscii.cpp +++ b/Framework/DataHandling/src/LoadAscii.cpp @@ -279,8 +279,7 @@ void LoadAscii::fillInputValues(std::vector<double> &values, const std::list<std::string> &columns) const { values.resize(columns.size()); int i = 0; - for (auto itr = columns.cbegin(); itr != columns.cend(); ++itr) { - std::string value = *itr; + for (auto value : columns) { boost::trim(value); boost::to_lower(value); if (value == "nan" || value == "1.#qnan") // ignores nans (not a number) and diff --git a/Framework/DataHandling/src/LoadAscii2.cpp b/Framework/DataHandling/src/LoadAscii2.cpp index 284ed879bc66f58b10ec66e8b574229c535161f0..cf50263d52a2a9454e3aaf27af30b5bbe851511e 100644 --- a/Framework/DataHandling/src/LoadAscii2.cpp +++ b/Framework/DataHandling/src/LoadAscii2.cpp @@ -556,8 +556,7 @@ void LoadAscii2::fillInputValues(std::vector<double> &values, const std::list<std::string> &columns) const { values.resize(columns.size()); int i = 0; - for (auto itr = columns.cbegin(); itr != columns.cend(); ++itr) { - std::string value = *itr; + for (auto value : columns) { boost::trim(value); boost::to_lower(value); if (value == "nan" || value == "1.#qnan") // ignores nans (not a number) and @@ -597,10 +596,10 @@ void LoadAscii2::init() { {"UserDefined", "UserDefined"}}; // For the ListValidator std::vector<std::string> sepOptions; - for (size_t i = 0; i < 7; ++i) { - std::string option = spacers[i][0]; + for (auto &spacer : spacers) { + std::string option = spacer[0]; m_separatorIndex.insert( - std::pair<std::string, std::string>(option, spacers[i][1])); + std::pair<std::string, std::string>(option, spacer[1])); sepOptions.push_back(option); } declareProperty("Separator", "Automatic", diff --git a/Framework/DataHandling/src/LoadBBY.cpp b/Framework/DataHandling/src/LoadBBY.cpp index fe3bedfd40c0b21dc26bf816ebaa0735f3a05d22..7b927d18fa86427d37ad546061d0a35121142626 100644 --- a/Framework/DataHandling/src/LoadBBY.cpp +++ b/Framework/DataHandling/src/LoadBBY.cpp @@ -93,12 +93,14 @@ int LoadBBY::confidence(Kernel::FileDescriptor &descriptor) const { size_t hdfFiles = 0; size_t binFiles = 0; const std::vector<std::string> &subFiles = file.files(); - for (auto itr = subFiles.begin(); itr != subFiles.end(); ++itr) { - auto len = itr->length(); - if ((len > 4) && (itr->find_first_of("\\/", 0, 2) == std::string::npos)) { - if ((itr->rfind(".hdf") == len - 4) && (itr->compare(0, 3, "BBY") == 0)) + for (const auto &subFile : subFiles) { + auto len = subFile.length(); + if ((len > 4) && + (subFile.find_first_of("\\/", 0, 2) == std::string::npos)) { + if ((subFile.rfind(".hdf") == len - 4) && + (subFile.compare(0, 3, "BBY") == 0)) hdfFiles++; - else if (itr->rfind(".bin") == len - 4) + else if (subFile.rfind(".bin") == len - 4) binFiles++; } } @@ -223,9 +225,9 @@ void LoadBBY::exec() { // set title const std::vector<std::string> &subFiles = tarFile.files(); - for (auto itr = subFiles.begin(); itr != subFiles.end(); ++itr) - if (itr->compare(0, 3, "BBY") == 0) { - std::string title = *itr; + for (const auto &subFile : subFiles) + if (subFile.compare(0, 3, "BBY") == 0) { + std::string title = subFile; if (title.rfind(".hdf") == title.length() - 4) title.resize(title.length() - 4); @@ -490,9 +492,9 @@ LoadBBY::createInstrument(ANSTO::Tar::File &tarFile, // extract hdf file int64_t fileSize = 0; const std::vector<std::string> &files = tarFile.files(); - for (auto itr = files.begin(); itr != files.end(); ++itr) - if (itr->rfind(".hdf") == itr->length() - 4) { - tarFile.select(itr->c_str()); + for (const auto &file : files) + if (file.rfind(".hdf") == file.length() - 4) { + tarFile.select(file.c_str()); fileSize = tarFile.selected_size(); break; } @@ -700,9 +702,9 @@ void LoadBBY::loadEvents(API::Progress &prog, const char *progMsg, // select bin file int64_t fileSize = 0; const std::vector<std::string> &files = tarFile.files(); - for (auto itr = files.begin(); itr != files.end(); ++itr) - if (itr->rfind(".bin") == itr->length() - 4) { - tarFile.select(itr->c_str()); + for (const auto &file : files) + if (file.rfind(".bin") == file.length() - 4) { + tarFile.select(file.c_str()); fileSize = tarFile.selected_size(); break; } diff --git a/Framework/DataHandling/src/LoadCalFile.cpp b/Framework/DataHandling/src/LoadCalFile.cpp index db07f9e65078dec260828710224475a5c21dca11..38793cb2faec4e8a4cecb3a021367054e7a379e7 100644 --- a/Framework/DataHandling/src/LoadCalFile.cpp +++ b/Framework/DataHandling/src/LoadCalFile.cpp @@ -69,10 +69,7 @@ bool LoadCalFile::instrumentIsSpecified(API::Algorithm *alg) { return true; std::string InstrumentFilename = alg->getPropertyValue("InstrumentFilename"); - if (!InstrumentFilename.empty()) - return true; - - return false; + return !InstrumentFilename.empty(); } //---------------------------------------------------------------------------------------------- diff --git a/Framework/DataHandling/src/LoadDetectorsGroupingFile.cpp b/Framework/DataHandling/src/LoadDetectorsGroupingFile.cpp index 083ce280b05e8b0535dc80ead758c3237a4e3a14..7cfcd914bd6daba5f82b9d244ccf741f1df85594 100644 --- a/Framework/DataHandling/src/LoadDetectorsGroupingFile.cpp +++ b/Framework/DataHandling/src/LoadDetectorsGroupingFile.cpp @@ -144,10 +144,10 @@ void LoadDetectorsGroupingFile::exec() { // 6. Add group names, if user has specified any std::map<int, std::string> groupNamesMap = loader.getGroupNamesMap(); - for (auto it = groupNamesMap.begin(); it != groupNamesMap.end(); it++) { - std::string groupIdStr = boost::lexical_cast<std::string>(it->first); + for (auto &group : groupNamesMap) { + std::string groupIdStr = boost::lexical_cast<std::string>(group.first); m_groupWS->mutableRun().addProperty("GroupName_" + groupIdStr, - it->second); + group.second); } } else if (ext == "map") { // Deal with file as map @@ -208,16 +208,15 @@ void LoadDetectorsGroupingFile::setByComponents() { m_groupWS->getDetectorIDToWorkspaceIndexMap(true); // 2. Set - for (auto it = m_groupComponentsMap.begin(); it != m_groupComponentsMap.end(); - ++it) { - g_log.debug() << "Group ID = " << it->first << " With " << it->second.size() - << " Components" << std::endl; + for (auto &componentMap : m_groupComponentsMap) { + g_log.debug() << "Group ID = " << componentMap.first << " With " + << componentMap.second.size() << " Components" << std::endl; - for (size_t i = 0; i < it->second.size(); i++) { + for (auto &name : componentMap.second) { // a) get component Geometry::IComponent_const_sptr component = - m_instrument->getComponentByName(it->second[i]); + m_instrument->getComponentByName(name); // b) component -> component assembly --> children (more than detectors) boost::shared_ptr<const Geometry::ICompAssembly> asmb = @@ -225,13 +224,12 @@ void LoadDetectorsGroupingFile::setByComponents() { std::vector<Geometry::IComponent_const_sptr> children; asmb->getChildren(children, true); - g_log.debug() << "Component Name = " << it->second[i] + g_log.debug() << "Component Name = " << name << " Component ID = " << component->getComponentID() << "Number of Children = " << children.size() << std::endl; - for (size_t ic = 0; ic < children.size(); ic++) { + for (auto child : children) { // c) convert component to detector - Geometry::IComponent_const_sptr child = children[ic]; Geometry::IDetector_const_sptr det = boost::dynamic_pointer_cast<const Geometry::IDetector>(child); @@ -241,7 +239,7 @@ void LoadDetectorsGroupingFile::setByComponents() { auto itx = indexmap.find(detid); if (itx != indexmap.end()) { size_t wsindex = itx->second; - m_groupWS->dataY(wsindex)[0] = it->first; + m_groupWS->dataY(wsindex)[0] = componentMap.first; } else { g_log.error() << "Pixel w/ ID = " << detid << " Cannot Be Located" << std::endl; @@ -285,17 +283,15 @@ void LoadDetectorsGroupingFile::setByDetectors() { m_groupWS->getDetectorIDToWorkspaceIndexMap(true); // 2. Set GroupingWorkspace - for (auto it = m_groupDetectorsMap.begin(); it != m_groupDetectorsMap.end(); - ++it) { - g_log.debug() << "Group ID = " << it->first << std::endl; + for (auto &detectorMap : m_groupDetectorsMap) { + g_log.debug() << "Group ID = " << detectorMap.first << std::endl; - for (size_t i = 0; i < it->second.size(); i++) { - detid_t detid = it->second[i]; + for (auto detid : detectorMap.second) { auto itx = indexmap.find(detid); if (itx != indexmap.end()) { size_t wsindex = itx->second; - m_groupWS->dataY(wsindex)[0] = it->first; + m_groupWS->dataY(wsindex)[0] = detectorMap.first; } else { g_log.error() << "Pixel w/ ID = " << detid << " Cannot Be Located" << std::endl; @@ -320,8 +316,7 @@ void LoadDetectorsGroupingFile::setBySpectrumIDs() { for (gsiter = m_groupSpectraMap.begin(); gsiter != m_groupSpectraMap.end(); ++gsiter) { int groupid = gsiter->first; - for (size_t isp = 0; isp < gsiter->second.size(); isp++) { - int specid = gsiter->second[isp]; + for (auto specid : gsiter->second) { s2iter = s2imap.find(specid); if (s2iter == s2imap.end()) { g_log.error() @@ -376,10 +371,9 @@ void LoadDetectorsGroupingFile::generateNoInstrumentGroupWorkspace() { for (groupspeciter = m_groupSpectraMap.begin(); groupspeciter != m_groupSpectraMap.end(); ++groupspeciter) { int groupid = groupspeciter->first; - for (size_t i = 0; i < groupspeciter->second.size(); i++) { - spectrumidgroupmap.insert( - std::pair<int, int>(groupspeciter->second[i], groupid)); - specids.push_back(groupspeciter->second[i]); + for (auto specid : groupspeciter->second) { + spectrumidgroupmap.emplace(specid, groupid); + specids.push_back(specid); } } diff --git a/Framework/DataHandling/src/LoadDiffCal.cpp b/Framework/DataHandling/src/LoadDiffCal.cpp index e3c143ab8f69848f86a9cc659241bc9b1b5c89b3..908a5ccf2cf9a2360a655e23cbab276dac11e5f1 100644 --- a/Framework/DataHandling/src/LoadDiffCal.cpp +++ b/Framework/DataHandling/src/LoadDiffCal.cpp @@ -134,8 +134,8 @@ std::vector<NumT> readArrayCoerce(DataSet &dataset, } else if (PredType::NATIVE_FLOAT == dataType) { std::vector<float> temp(dataSpace.getSelectNpoints()); dataset.read(&temp[0], dataType, dataSpace); - for (auto it = temp.begin(); it != temp.end(); ++it) - result.push_back(static_cast<NumT>(*it)); + for (float value : temp) + result.push_back(static_cast<NumT>(value)); } else { throw DataTypeIException(); } @@ -197,11 +197,11 @@ std::vector<double> LoadDiffCal::readDoubleArray(Group &group, << "\n"; } - for (size_t i = 0; i < result.size(); ++i) { - if (std::abs(result[i]) < 1.e-10) { - result[i] = 0.; - } else if (result[i] != result[i]) { // check for NaN - result[i] = 0.; + for (double &value : result) { + if (std::abs(value) < 1.e-10) { + value = 0.; + } else if (value != value) { // check for NaN + value = 0.; } } diff --git a/Framework/DataHandling/src/LoadDspacemap.cpp b/Framework/DataHandling/src/LoadDspacemap.cpp index 495f6f281292c8921b293dcfd33614ef14dff3cd..bb790240545d2dd1148fd971d897cf6589a36b18 100644 --- a/Framework/DataHandling/src/LoadDspacemap.cpp +++ b/Framework/DataHandling/src/LoadDspacemap.cpp @@ -373,9 +373,9 @@ void LoadDspacemap::readVulcanBinaryFile(const std::string &fileName, BinaryFile<VulcanCorrectionFactor> file(fileName); std::vector<VulcanCorrectionFactor> *results = file.loadAll(); if (results) { - for (auto it = results->begin(); it != results->end(); ++it) { + for (auto &result : *results) { // std::cout << it->pixelID << " :! " << it->factor << std::endl; - vulcan[static_cast<detid_t>(it->pixelID)] = it->factor; + vulcan[static_cast<detid_t>(result.pixelID)] = result.factor; } } diff --git a/Framework/DataHandling/src/LoadEventNexus.cpp b/Framework/DataHandling/src/LoadEventNexus.cpp index f20accc92a945015cabc63f15c511e5654cef437..63711f7c12f6ea9b026579bc51cd458ea498d3e7 100644 --- a/Framework/DataHandling/src/LoadEventNexus.cpp +++ b/Framework/DataHandling/src/LoadEventNexus.cpp @@ -57,9 +57,9 @@ void copyLogs(const Mantid::DataHandling::EventWorkspaceCollection_sptr &from, // from the logs, get all the properties that don't overwrite any // prop. already set in the sink workspace (like 'filename'). auto props = from->mutableRun().getLogData(); - for (size_t j = 0; j < props.size(); j++) { - if (!to->mutableRun().hasProperty(props[j]->name())) { - to->mutableRun().addLogData(props[j]->clone()); + for (auto &prop : props) { + if (!to->mutableRun().hasProperty(prop->name())) { + to->mutableRun().addLogData(prop->clone()); } } } @@ -516,9 +516,9 @@ public: // Now, we look through existing ones to see if it is already loaded // thisBankPulseTimes = NULL; - for (size_t i = 0; i < alg->m_bankPulseTimes.size(); i++) { - if (alg->m_bankPulseTimes[i]->equals(thisNumPulses, thisStartTime)) { - thisBankPulseTimes = alg->m_bankPulseTimes[i]; + for (auto &bankPulseTime : alg->m_bankPulseTimes) { + if (bankPulseTime->equals(thisNumPulses, thisStartTime)) { + thisBankPulseTimes = bankPulseTime; return; } } @@ -1802,27 +1802,24 @@ void LoadEventNexus::loadEvents(API::Progress *const prog, bool SingleBankPixelsOnly = getProperty("SingleBankPixelsOnly"); if ((!someBanks.empty()) && (!monitors)) { // check that all of the requested banks are in the file - for (auto someBank = someBanks.begin(); someBank != someBanks.end(); - ++someBank) { + for (auto &someBank : someBanks) { bool foundIt = false; - for (auto bankName = bankNames.begin(); bankName != bankNames.end(); - ++bankName) { - if ((*bankName) == (*someBank) + "_events") { + for (auto &bankName : bankNames) { + if (bankName == someBank + "_events") { foundIt = true; break; } } if (!foundIt) { - throw std::invalid_argument("No entry named '" + (*someBank) + + throw std::invalid_argument("No entry named '" + someBank + "' was found in the .NXS file.\n"); } } // change the number of banks to load bankNames.clear(); - for (auto someBank = someBanks.begin(); someBank != someBanks.end(); - ++someBank) - bankNames.push_back((*someBank) + "_events"); + for (auto &someBank : someBanks) + bankNames.push_back(someBank + "_events"); // how many events are in a bank bankNumEvents.clear(); @@ -2142,13 +2139,12 @@ void LoadEventNexus::deleteBanks(EventWorkspaceCollection_sptr workspace, } if (detList.size() == 0) return; - for (int i = 0; i < static_cast<int>(detList.size()); i++) { + for (auto &det : detList) { bool keep = false; - boost::shared_ptr<RectangularDetector> det = detList[i]; std::string det_name = det->getName(); - for (int j = 0; j < static_cast<int>(bankNames.size()); j++) { - size_t pos = bankNames[j].find("_events"); - if (det_name.compare(bankNames[j].substr(0, pos)) == 0) + for (auto &bankName : bankNames) { + size_t pos = bankName.find("_events"); + if (det_name.compare(bankName.substr(0, pos)) == 0) keep = true; if (keep) break; @@ -2160,21 +2156,20 @@ void LoadEventNexus::deleteBanks(EventWorkspaceCollection_sptr workspace, boost::shared_ptr<const Geometry::ICompAssembly> asmb = boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent); asmb->getChildren(children, false); - for (int col = 0; col < static_cast<int>(children.size()); col++) { + for (auto &col : children) { boost::shared_ptr<const Geometry::ICompAssembly> asmb2 = - boost::dynamic_pointer_cast<const Geometry::ICompAssembly>( - children[col]); + boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(col); std::vector<Geometry::IComponent_const_sptr> grandchildren; asmb2->getChildren(grandchildren, false); - for (int row = 0; row < static_cast<int>(grandchildren.size()); row++) { - Detector *d = dynamic_cast<Detector *>( - const_cast<IComponent *>(grandchildren[row].get())); + for (auto &row : grandchildren) { + Detector *d = + dynamic_cast<Detector *>(const_cast<IComponent *>(row.get())); if (d) inst->removeDetector(d); } } - IComponent *comp = dynamic_cast<IComponent *>(detList[i].get()); + IComponent *comp = dynamic_cast<IComponent *>(det.get()); inst->remove(comp); } } @@ -2203,12 +2198,12 @@ void LoadEventNexus::createSpectraMapping( if (!monitorsOnly && !bankNames.empty()) { std::vector<IDetector_const_sptr> allDets; - for (auto name = bankNames.begin(); name != bankNames.end(); ++name) { + for (const auto &bankName : bankNames) { // Only build the map for the single bank std::vector<IDetector_const_sptr> dets; - m_ws->getInstrument()->getDetectorsInBank(dets, (*name)); + m_ws->getInstrument()->getDetectorsInBank(dets, bankName); if (dets.empty()) - throw std::runtime_error("Could not find the bank named '" + (*name) + + throw std::runtime_error("Could not find the bank named '" + bankName + "' as a component assembly in the instrument " "tree; or it did not contain any detectors." " Try unchecking SingleBankPixelsOnly."); @@ -2506,11 +2501,11 @@ bool LoadEventNexus::loadSpectraMapping(const std::string &filename, if (!m_specList.empty()) { int i = 0; std::vector<int32_t> spec_temp, udet_temp; - for (auto it = spec.begin(); it != spec.end(); it++) { - if (find(m_specList.begin(), m_specList.end(), *it) != + for (auto &element : spec) { + if (find(m_specList.begin(), m_specList.end(), element) != m_specList.end()) // spec element *it is not in spec_list { - spec_temp.push_back(*it); + spec_temp.push_back(element); udet_temp.push_back(udet.at(i)); } i++; @@ -2741,9 +2736,8 @@ void LoadEventNexus::loadTimeOfFlightData(::NeXus::File &file, // spread the events uniformly inside the bin boost::uniform_real<> distribution(left, right); std::vector<double> random_numbers(m); - for (auto it = random_numbers.begin(); it != random_numbers.end(); - ++it) { - *it = distribution(rand_gen); + for (double &random_number : random_numbers) { + random_number = distribution(rand_gen); } std::sort(random_numbers.begin(), random_numbers.end()); auto it = random_numbers.begin(); diff --git a/Framework/DataHandling/src/LoadEventPreNexus.cpp b/Framework/DataHandling/src/LoadEventPreNexus.cpp index 601539f5f9f37912b017b1f68c2abeafc2a17419..33d940eb5d92bf2a8ba18ccdc53e75e29747b9a7 100644 --- a/Framework/DataHandling/src/LoadEventPreNexus.cpp +++ b/Framework/DataHandling/src/LoadEventPreNexus.cpp @@ -234,14 +234,12 @@ static string generateMappingfileName(EventWorkspace_sptr &wksp) { // const string CAL("_CAL"); const size_t CAL_LEN = CAL.length(); // cache to make life easier vector<string> files; - for (size_t i = 0; i < dirs.size(); ++i) { - if ((dirs[i].length() > CAL_LEN) && - (dirs[i].compare(dirs[i].length() - CAL.length(), CAL.length(), CAL) == - 0)) { - if (Poco::File(base.path() + "/" + dirs[i] + "/calibrations/" + mapping) + for (auto &dir : dirs) { + if ((dir.length() > CAL_LEN) && + (dir.compare(dir.length() - CAL.length(), CAL.length(), CAL) == 0)) { + if (Poco::File(base.path() + "/" + dir + "/calibrations/" + mapping) .exists()) - files.push_back(base.path() + "/" + dirs[i] + "/calibrations/" + - mapping); + files.push_back(base.path() + "/" + dir + "/calibrations/" + mapping); } } @@ -476,8 +474,8 @@ void LoadEventPreNexus::procEvents( loadOnlySomeSpectra = (this->spectra_list.size() > 0); // Turn the spectra list into a map, for speed of access - for (auto it = spectra_list.begin(); it != spectra_list.end(); it++) - spectraLoadMap[*it] = true; + for (auto &spectrum : spectra_list) + spectraLoadMap[spectrum] = true; CPUTimer tim; diff --git a/Framework/DataHandling/src/LoadEventPreNexus2.cpp b/Framework/DataHandling/src/LoadEventPreNexus2.cpp index 2dcdb6f5968abd7b9db2f560fdeaad748348a38f..8acdd753f3e836e71167dbeaa3a2e7ad31ead25d 100644 --- a/Framework/DataHandling/src/LoadEventPreNexus2.cpp +++ b/Framework/DataHandling/src/LoadEventPreNexus2.cpp @@ -170,14 +170,12 @@ static string generateMappingfileName(EventWorkspace_sptr &wksp) { const string CAL("_CAL"); const size_t CAL_LEN = CAL.length(); // cache to make life easier vector<string> files; - for (size_t i = 0; i < dirs.size(); ++i) { - if ((dirs[i].length() > CAL_LEN) && - (dirs[i].compare(dirs[i].length() - CAL.length(), CAL.length(), CAL) == - 0)) { - if (Poco::File(base.path() + "/" + dirs[i] + "/calibrations/" + mapping) + for (auto &dir : dirs) { + if ((dir.length() > CAL_LEN) && + (dir.compare(dir.length() - CAL.length(), CAL.length(), CAL) == 0)) { + if (Poco::File(base.path() + "/" + dir + "/calibrations/" + mapping) .exists()) - files.push_back(base.path() + "/" + dirs[i] + "/calibrations/" + - mapping); + files.push_back(base.path() + "/" + dir + "/calibrations/" + mapping); } } @@ -609,8 +607,8 @@ void LoadEventPreNexus2::runLoadInstrument( vector<string> eventExts(EVENT_EXTS, EVENT_EXTS + NUM_EXT); std::reverse(eventExts.begin(), eventExts.end()); - for (size_t i = 0; i < eventExts.size(); ++i) { - size_t pos = instrument.find(eventExts[i]); + for (auto &eventExt : eventExts) { + size_t pos = instrument.find(eventExt); if (pos != string::npos) { instrument = instrument.substr(0, pos); break; @@ -726,8 +724,8 @@ void LoadEventPreNexus2::procEvents( loadOnlySomeSpectra = (this->spectra_list.size() > 0); // Turn the spectra list into a map, for speed of access - for (auto it = spectra_list.begin(); it != spectra_list.end(); it++) - spectraLoadMap[*it] = true; + for (auto &spectrum : spectra_list) + spectraLoadMap[spectrum] = true; CPUTimer tim; diff --git a/Framework/DataHandling/src/LoadFITS.cpp b/Framework/DataHandling/src/LoadFITS.cpp index 2be0a20623bf3f7a43cac9883797092e411f7ce0..5a5be0d2dcc16c740f8b7c17ab6945c29fca6c0a 100644 --- a/Framework/DataHandling/src/LoadFITS.cpp +++ b/Framework/DataHandling/src/LoadFITS.cpp @@ -754,11 +754,10 @@ void LoadFITS::addAxesInfoAndLogs(Workspace2D_sptr ws, bool loadAsRectImg, ws->setYUnitLabel("brightness"); // Add all header info to log. - for (auto it = fileInfo.headerKeys.begin(); it != fileInfo.headerKeys.end(); - ++it) { - ws->mutableRun().removeLogData(it->first, true); + for (const auto &headerKey : fileInfo.headerKeys) { + ws->mutableRun().removeLogData(headerKey.first, true); ws->mutableRun().addLogData( - new PropertyWithValue<std::string>(it->first, it->second)); + new PropertyWithValue<std::string>(headerKey.first, headerKey.second)); } // Add rotational data to log. Clear first from copied WS diff --git a/Framework/DataHandling/src/LoadFullprofResolution.cpp b/Framework/DataHandling/src/LoadFullprofResolution.cpp index 592c3b8e900ff2a670c7f198e2a27af58cd568ba..96ed31b751deda5618997939fd26135fc996f4fd 100644 --- a/Framework/DataHandling/src/LoadFullprofResolution.cpp +++ b/Framework/DataHandling/src/LoadFullprofResolution.cpp @@ -125,8 +125,8 @@ void LoadFullprofResolution::exec() { if (useBankIDsInFile) sort(vec_bankinirf.begin(), vec_bankinirf.end()); - for (size_t i = 0; i < vec_bankinirf.size(); ++i) - g_log.debug() << "Irf containing bank " << vec_bankinirf[i] << ".\n"; + for (auto bank : vec_bankinirf) + g_log.debug() << "Irf containing bank " << bank << ".\n"; // Bank-workspace correspondence map<int, size_t> workspaceOfBank; @@ -148,8 +148,7 @@ void LoadFullprofResolution::exec() { // Deal with banks sort(outputbankids.begin(), outputbankids.end()); - for (size_t i = 0; i < outputbankids.size(); ++i) { - int outputbankid = outputbankids[i]; + for (auto outputbankid : outputbankids) { if (outputbankid < 0) { g_log.warning() << "Input bank ID (" << outputbankid << ") is negative. It is not allowed and is ignored. " @@ -359,10 +358,9 @@ void LoadFullprofResolution::scanBanks(const vector<string> &lines, g_log.debug() << "[DB1112] Number of bank IDs = " << banks.size() << ", " << "Number of ranges = " << bankstartindexmap.size() << endl; - for (size_t i = 0; i < banks.size(); ++i) { - g_log.debug() << "Bank " << banks[i] << " From line " - << bankstartindexmap[banks[i]] << " to " - << bankendindexmap[banks[i]] << endl; + for (auto &bank : banks) { + g_log.debug() << "Bank " << bank << " From line " << bankstartindexmap[bank] + << " to " << bankendindexmap[bank] << endl; } return; diff --git a/Framework/DataHandling/src/LoadGSASInstrumentFile.cpp b/Framework/DataHandling/src/LoadGSASInstrumentFile.cpp index 705418ecea44fae2e294e5ee5099540ef98d7e94..a8e7acbd528190f408a0feb04d2de391b4b54516 100644 --- a/Framework/DataHandling/src/LoadGSASInstrumentFile.cpp +++ b/Framework/DataHandling/src/LoadGSASInstrumentFile.cpp @@ -172,17 +172,17 @@ void LoadGSASInstrumentFile::exec() { if (bankIds.size()) { // If user provided a list of banks, check that they exist in the .prm // file - for (size_t i = 0; i < bankIds.size(); i++) { - if (!bankparammap.count(bankIds[i])) { + for (auto bankId : bankIds) { + if (!bankparammap.count(bankId)) { std::stringstream errorString; - errorString << "Bank " << bankIds[i] << " not found in .prm file"; + errorString << "Bank " << bankId << " not found in .prm file"; throw runtime_error(errorString.str()); } } } else { // Else, use all available banks - for (auto it = bankparammap.begin(); it != bankparammap.end(); ++it) { - bankIds.push_back(static_cast<int>(it->first)); + for (auto &bank : bankparammap) { + bankIds.push_back(static_cast<int>(bank.first)); } } diff --git a/Framework/DataHandling/src/LoadIDFFromNexus.cpp b/Framework/DataHandling/src/LoadIDFFromNexus.cpp index 85ee0a0b0ce15a38532009e8e2f21b62cd3cd071..9d18c0e0ebb1babbbde8a1f3e385dae84d882bc8 100644 --- a/Framework/DataHandling/src/LoadIDFFromNexus.cpp +++ b/Framework/DataHandling/src/LoadIDFFromNexus.cpp @@ -155,12 +155,11 @@ LoadIDFFromNexus::getParameterCorrectionFile(const std::string &instName) { std::vector<std::string> directoryNames = ConfigService::Instance().getInstrumentDirectories(); - for (auto instDirs_itr = directoryNames.begin(); - instDirs_itr != directoryNames.end(); ++instDirs_itr) { + for (auto &directoryName : directoryNames) { // This will iterate around the directories from user ->etc ->install, and // find the first appropriate file Poco::Path iPath( - *instDirs_itr, + directoryName, "embedded_instrument_corrections"); // Go to correction file subfolder // First see if the directory exists Poco::File ipDir(iPath); @@ -279,11 +278,9 @@ void LoadIDFFromNexus::LoadParameters( ConfigService::Instance().getInstrumentDirectories(); const std::string instrumentName = localWorkspace->getInstrument()->getName(); - for (auto instDirs_itr = directoryNames.begin(); - instDirs_itr != directoryNames.end(); ++instDirs_itr) { + for (auto directoryName : directoryNames) { // This will iterate around the directories from user ->etc ->install, and // find the first appropriate file - std::string directoryName = *instDirs_itr; const std::string paramFile = directoryName + instrumentName + "_Parameters.xml"; diff --git a/Framework/DataHandling/src/LoadILL.cpp b/Framework/DataHandling/src/LoadILL.cpp index 5eb5ab14b9e1e8dbad0baa4245f9cbd232a42219..b1de11c6682b2e59a8eb1eb84f124333a2e063b7 100644 --- a/Framework/DataHandling/src/LoadILL.cpp +++ b/Framework/DataHandling/src/LoadILL.cpp @@ -516,15 +516,16 @@ void LoadILL::loadDataIntoTheWorkSpace( // The binning for monitors is considered the same as for detectors size_t spec = 0; - for (auto it = monitors.begin(); it != monitors.end(); ++it) { + for (const auto &monitor : monitors) { m_localWorkspace->dataX(spec) .assign(detectorTofBins.begin(), detectorTofBins.end()); // Assign Y - m_localWorkspace->dataY(spec).assign(it->begin(), it->end()); + m_localWorkspace->dataY(spec).assign(monitor.begin(), monitor.end()); // Assign Error MantidVec &E = m_localWorkspace->dataE(spec); - std::transform(it->begin(), it->end(), E.begin(), LoadILL::calculateError); + std::transform(monitor.begin(), monitor.end(), E.begin(), + LoadILL::calculateError); ++spec; } diff --git a/Framework/DataHandling/src/LoadISISNexus2.cpp b/Framework/DataHandling/src/LoadISISNexus2.cpp index 9a7a68009520647f5d3481f479fbc7ce28d279f6..5c7e3bc56362734344784201c4411bb6ce9f4357 100644 --- a/Framework/DataHandling/src/LoadISISNexus2.cpp +++ b/Framework/DataHandling/src/LoadISISNexus2.cpp @@ -720,8 +720,8 @@ size_t LoadISISNexus2::prepareSpectraBlocks( } // count the number of spectra size_t nSpec = 0; - for (auto it = m_spectraBlocks.begin(); it != m_spectraBlocks.end(); ++it) { - nSpec += it->last - it->first + 1; + for (auto &spectraBlock : m_spectraBlocks) { + nSpec += spectraBlock.last - spectraBlock.first + 1; } return nSpec; } @@ -743,10 +743,9 @@ void LoadISISNexus2::loadPeriodData( int64_t period_index(period - 1); // int64_t first_monitor_spectrum = 0; - for (auto block = m_spectraBlocks.begin(); block != m_spectraBlocks.end(); - ++block) { - if (block->isMonitor) { - NXData monitor = entry.openNXData(block->monName); + for (auto &spectraBlock : m_spectraBlocks) { + if (spectraBlock.isMonitor) { + NXData monitor = entry.openNXData(spectraBlock.monName); NXInt mondata = monitor.openIntData(); m_progress->report("Loading monitor"); mondata.load(1, static_cast<int>(period - 1)); // TODO this is just wrong @@ -780,9 +779,9 @@ void LoadISISNexus2::loadPeriodData( // divisible by the block-size // and if not have an extra read of the left overs const int64_t blocksize = 8; - const int64_t rangesize = block->last - block->first + 1; + const int64_t rangesize = spectraBlock.last - spectraBlock.first + 1; const int64_t fullblocks = rangesize / blocksize; - int64_t spectra_no = block->first; + int64_t spectra_no = spectraBlock.first; // For this to work correctly, we assume that the spectrum list increases // monotonically @@ -1174,8 +1173,8 @@ bool LoadISISNexus2::findSpectraDetRangeInFile( // number of groups. // identify monitor ID range. - for (auto it = monitors.begin(); it != monitors.end(); it++) { - int64_t mon_id = static_cast<int64_t>(it->first); + for (auto &monitor : monitors) { + int64_t mon_id = static_cast<int64_t>(monitor.first); if (m_monBlockInfo.spectraID_min > mon_id) m_monBlockInfo.spectraID_min = mon_id; if (m_monBlockInfo.spectraID_max < mon_id) @@ -1272,15 +1271,15 @@ bool LoadISISNexus2::findSpectraDetRangeInFile( std::map<int64_t, std::string> remaining_monitors; if (removeMonitors) { - for (auto it = monitors.begin(); it != monitors.end(); it++) { - if (it->first >= m_detBlockInfo.spectraID_min && - it->first <= m_detBlockInfo.spectraID_max) { // monitors ID-s are - // included with spectra - // ID-s -- let's try not - // to load it twice. - OvelapMonitors.insert(*it); + for (auto &monitor : monitors) { + if (monitor.first >= m_detBlockInfo.spectraID_min && + monitor.first <= m_detBlockInfo.spectraID_max) { // monitors ID-s are + // included with spectra + // ID-s -- let's try not + // to load it twice. + OvelapMonitors.insert(monitor); } else { - remaining_monitors.insert(*it); + remaining_monitors.insert(monitor); } } } diff --git a/Framework/DataHandling/src/LoadInstrument.cpp b/Framework/DataHandling/src/LoadInstrument.cpp index 431df970f99177607c23fd62805d0f2a4af4f3df..87710eedef6fd32fe247c106275e8af9cda03875 100644 --- a/Framework/DataHandling/src/LoadInstrument.cpp +++ b/Framework/DataHandling/src/LoadInstrument.cpp @@ -222,11 +222,9 @@ void LoadInstrument::runLoadParameterFile() { std::vector<std::string> directoryNames = configService.getInstrumentDirectories(); - for (auto instDirs_itr = directoryNames.begin(); - instDirs_itr != directoryNames.end(); ++instDirs_itr) { + for (auto directoryName : directoryNames) { // This will iterate around the directories from user ->etc ->install, and // find the first beat file - std::string directoryName = *instDirs_itr; fullPathParamIDF = getFullPathParamIDF(directoryName); // stop when you find the first one if (!fullPathParamIDF.empty()) diff --git a/Framework/DataHandling/src/LoadIsawDetCal.cpp b/Framework/DataHandling/src/LoadIsawDetCal.cpp index 6d1fe37a67a70572d7cb78bb63e6072e11d1530d..d3b381b9f22725f1d50783f12840795571ef3152 100644 --- a/Framework/DataHandling/src/LoadIsawDetCal.cpp +++ b/Framework/DataHandling/src/LoadIsawDetCal.cpp @@ -139,8 +139,8 @@ void LoadIsawDetCal::exec() { std::vector<IComponent_const_sptr> comps; inst->getChildren(comps, true); - for (size_t i = 0; i < comps.size(); i++) { - std::string bankName = comps[i]->getName(); + for (auto &comp : comps) { + std::string bankName = comp->getName(); boost::trim(bankName); boost::erase_all(bankName, bankPart); int bank = 0; diff --git a/Framework/DataHandling/src/LoadLog.cpp b/Framework/DataHandling/src/LoadLog.cpp index 445f4bdfcf0c4ca66b40960c3cf5e37864eed641..3801258b6042e123a32f454dd511aed1f10a0a1a 100644 --- a/Framework/DataHandling/src/LoadLog.cpp +++ b/Framework/DataHandling/src/LoadLog.cpp @@ -466,8 +466,8 @@ bool LoadLog::SNSTextFormatColumns(const std::string &str, boost::split(strs, str, boost::is_any_of("\t ")); double val; // Every column must evaluate to a double - for (size_t i = 0; i < strs.size(); i++) { - if (!Strings::convert<double>(strs[i], val)) + for (auto &str : strs) { + if (!Strings::convert<double>(str, val)) return false; else out.push_back(val); diff --git a/Framework/DataHandling/src/LoadLogsForSNSPulsedMagnet.cpp b/Framework/DataHandling/src/LoadLogsForSNSPulsedMagnet.cpp index e500e036ba41ed0d46ad8761dcb430c7dd345ea0..6cb1180c9a093f5e8cb890c33734aa004c987552 100644 --- a/Framework/DataHandling/src/LoadLogsForSNSPulsedMagnet.cpp +++ b/Framework/DataHandling/src/LoadLogsForSNSPulsedMagnet.cpp @@ -210,9 +210,9 @@ void LoadLogsForSNSPulsedMagnet::ParsePulseIDLogFile() { BinaryFile<Pulse> pulseFile(m_pulseidfilename); this->m_numpulses = pulseFile.getNumElements(); pulses = pulseFile.loadAll(); - for (auto it = pulses->begin(); it != pulses->end(); ++it) { - this->m_pulseidseconds.push_back(it->seconds); - this->m_pulseidnanoseconds.push_back(it->nanoseconds); + for (auto &pulse : *pulses) { + this->m_pulseidseconds.push_back(pulse.seconds); + this->m_pulseidnanoseconds.push_back(pulse.nanoseconds); } delete pulses; } diff --git a/Framework/DataHandling/src/LoadMLZ.cpp b/Framework/DataHandling/src/LoadMLZ.cpp index 485165c1de5f5bf3d77c4b8ca4a92cdbe85e667c..c85dbf23fb7f7db0415c72da0f7a7a1d1fb8ecb5 100644 --- a/Framework/DataHandling/src/LoadMLZ.cpp +++ b/Framework/DataHandling/src/LoadMLZ.cpp @@ -138,9 +138,9 @@ void LoadMLZ::maskDetectors(NeXus::NXEntry &entry) { g_log.debug() << "Number of masked detectors: " << masked_detectors.size() << std::endl; - for (size_t i = 0; i < masked_detectors.size(); i++) { + for (auto masked_detector : masked_detectors) { g_log.debug() << "List of masked detectors: "; - g_log.debug() << masked_detectors[i]; + g_log.debug() << masked_detector; g_log.debug() << ", "; } g_log.debug() << std::endl; diff --git a/Framework/DataHandling/src/LoadMask.cpp b/Framework/DataHandling/src/LoadMask.cpp index 60b3f96cbe075d53b2e1f2b250b05593da6f5c51..7ca5b9fd033711b91e7006428d15466b6034a32a 100644 --- a/Framework/DataHandling/src/LoadMask.cpp +++ b/Framework/DataHandling/src/LoadMask.cpp @@ -180,8 +180,7 @@ void LoadMask::processMaskOnDetectors(bool tomask, << " Final Single IDs Size = " << singledetids.size() << std::endl; - for (size_t i = 0; i < singledetids.size(); i++) { - detid_t detid = singledetids[i]; + for (auto detid : singledetids) { detid2index_map::const_iterator it; it = indexmap.find(detid); if (it != indexmap.end()) { @@ -197,7 +196,7 @@ void LoadMask::processMaskOnDetectors(bool tomask, } // 3. Mask pairs - for (size_t i = 0; i < pairdetids_low.size(); i++) { + for (size_t i = 0; i < pairdetids_low.size(); ++i) { g_log.error() << "To Be Implemented Soon For Pair (" << pairdetids_low[i] << ", " << pairdetids_up[i] << "!" << std::endl; } @@ -213,18 +212,18 @@ void LoadMask::componentToDetectors(std::vector<std::string> componentnames, std::vector<int32_t> &detectors) { Geometry::Instrument_const_sptr minstrument = m_maskWS->getInstrument(); - for (size_t i = 0; i < componentnames.size(); i++) { - g_log.debug() << "Component name = " << componentnames[i] << std::endl; + for (auto &componentname : componentnames) { + g_log.debug() << "Component name = " << componentname << std::endl; // a) get component Geometry::IComponent_const_sptr component = - minstrument->getComponentByName(componentnames[i]); + minstrument->getComponentByName(componentname); if (component) g_log.debug() << "Component ID = " << component->getComponentID() << std::endl; else { // A non-exiting component. Ignore - g_log.warning() << "Component " << componentnames[i] << " does not exist!" + g_log.warning() << "Component " << componentname << " does not exist!" << std::endl; continue; } @@ -241,9 +240,8 @@ void LoadMask::componentToDetectors(std::vector<std::string> componentnames, int32_t id_min = 1000000; int32_t id_max = 0; - for (size_t ic = 0; ic < children.size(); ic++) { + for (auto child : children) { // c) convert component to detector - Geometry::IComponent_const_sptr child = children[ic]; Geometry::IDetector_const_sptr det = boost::dynamic_pointer_cast<const Geometry::IDetector>(child); @@ -274,18 +272,18 @@ void LoadMask::bankToDetectors(std::vector<std::string> singlebanks, std::vector<int32_t> &detectorpairsup) { std::stringstream infoss; infoss << "Bank IDs to be converted to detectors: " << endl; - for (size_t i = 0; i < singlebanks.size(); i++) { - infoss << "Bank: " << singlebanks[i] << std::endl; + for (auto &singlebank : singlebanks) { + infoss << "Bank: " << singlebank << std::endl; } g_log.debug(infoss.str()); Geometry::Instrument_const_sptr minstrument = m_maskWS->getInstrument(); - for (size_t ib = 0; ib < singlebanks.size(); ib++) { + for (auto &singlebank : singlebanks) { std::vector<Geometry::IDetector_const_sptr> idetectors; - minstrument->getDetectorsInBank(idetectors, singlebanks[ib]); - g_log.debug() << "Bank: " << singlebanks[ib] << " has " << idetectors.size() + minstrument->getDetectorsInBank(idetectors, singlebank); + g_log.debug() << "Bank: " << singlebank << " has " << idetectors.size() << " detectors" << std::endl; // a) get information @@ -306,8 +304,7 @@ void LoadMask::bankToDetectors(std::vector<std::string> singlebanks, << "DetID: " << detid_first << ", " << detid_last << std::endl; - for (size_t i = 0; i < idetectors.size(); i++) { - Geometry::IDetector_const_sptr det = idetectors[i]; + for (auto det : idetectors) { int32_t detid = det->getID(); detectors.push_back(detid); } @@ -397,9 +394,7 @@ void LoadMask::detectorToDetectors(std::vector<int32_t> singles, << std::endl; } */ - for (size_t i = 0; i < singles.size(); i++) { - detectors.push_back(singles[i]); - } + detectors.insert(detectors.end(), singles.begin(), singles.end()); for (size_t i = 0; i < pairslow.size(); i++) { for (int32_t j = 0; j < pairsup[i] - pairslow[i] + 1; j++) { int32_t detid = pairslow[i] + j; @@ -585,16 +580,15 @@ void LoadMask::parseSpectrumIDs(std::string inputstr, bool tomask) { // 2. Set to data storage if (tomask) { - for (size_t i = 0; i < singles.size(); i++) { - mask_specid_single.push_back(singles[i]); - } + mask_specid_single.insert(mask_specid_single.end(), singles.begin(), + singles.end()); for (size_t i = 0; i < pairs.size() / 2; i++) { mask_specid_pair_low.push_back(pairs[2 * i]); mask_specid_pair_up.push_back(pairs[2 * i + 1]); } } else { - for (size_t i = 0; i < singles.size(); i++) { - unmask_specid_single.push_back(singles[i]); + for (auto single : singles) { + unmask_specid_single.push_back(single); } for (size_t i = 0; i < pairs.size() / 2; i++) { unmask_specid_pair_low.push_back(pairs[2 * i]); @@ -618,17 +612,15 @@ void LoadMask::parseDetectorIDs(std::string inputstr, bool tomask) { // 2. Set to data storage if (tomask) { - for (size_t i = 0; i < singles.size(); i++) { - mask_detid_single.push_back(singles[i]); - } + mask_detid_single.insert(unmask_detid_single.end(), singles.begin(), + singles.end()); for (size_t i = 0; i < pairs.size() / 2; i++) { mask_detid_pair_low.push_back(pairs[2 * i]); mask_detid_pair_up.push_back(pairs[2 * i + 1]); } } else { - for (size_t i = 0; i < singles.size(); i++) { - unmask_detid_single.push_back(singles[i]); - } + unmask_detid_single.insert(unmask_detid_single.end(), singles.begin(), + singles.end()); for (size_t i = 0; i < pairs.size() / 2; i++) { unmask_detid_pair_low.push_back(pairs[2 * i]); unmask_detid_pair_up.push_back(pairs[2 * i + 1]); @@ -652,35 +644,35 @@ void LoadMask::parseRangeText(std::string inputstr, // 2. Filter std::vector<std::string> strsingles; std::vector<std::string> strpairs; - for (size_t i = 0; i < rawstrings.size(); i++) { + for (auto &rawstring : rawstrings) { // a) Find '-': bool containto = false; - const char *tempchs = rawstrings[i].c_str(); - for (size_t j = 0; j < rawstrings[i].size(); j++) + const char *tempchs = rawstring.c_str(); + for (size_t j = 0; j < rawstring.size(); j++) if (tempchs[j] == '-') { containto = true; break; } // b) Rebin if (containto) - strpairs.push_back(rawstrings[i]); + strpairs.push_back(rawstring); else - strsingles.push_back(rawstrings[i]); + strsingles.push_back(rawstring); } // ENDFOR i // 3. Treat singles - for (size_t i = 0; i < strsingles.size(); i++) { - int32_t itemp = atoi(strsingles[i].c_str()); + for (auto &strsingle : strsingles) { + int32_t itemp = atoi(strsingle.c_str()); singles.push_back(itemp); } // 4. Treat pairs - for (size_t i = 0; i < strpairs.size(); i++) { + for (auto &strpair : strpairs) { // a) split and check std::vector<std::string> ptemp; - this->splitString(strpairs[i], ptemp, "-"); + this->splitString(strpair, ptemp, "-"); if (ptemp.size() != 2) { - g_log.error() << "Range string " << strpairs[i] << " has a wrong format!" + g_log.error() << "Range string " << strpair << " has a wrong format!" << std::endl; throw std::invalid_argument("Wrong format"); } @@ -689,7 +681,7 @@ void LoadMask::parseRangeText(std::string inputstr, int32_t intstart = atoi(ptemp[0].c_str()); int32_t intend = atoi(ptemp[1].c_str()); if (intstart >= intend) { - g_log.error() << "Range string " << strpairs[i] << " has a reversed order" + g_log.error() << "Range string " << strpair << " has a reversed order" << std::endl; throw std::invalid_argument("Wrong format"); } diff --git a/Framework/DataHandling/src/LoadMcStas.cpp b/Framework/DataHandling/src/LoadMcStas.cpp index 3b16dd7d06682b44ea1f37644ac022b39aa0cef7..5d8765d26a70b3a160e1b328ceac9a5e07ac41d1 100644 --- a/Framework/DataHandling/src/LoadMcStas.cpp +++ b/Framework/DataHandling/src/LoadMcStas.cpp @@ -97,9 +97,9 @@ void LoadMcStas::exec() { std::map<std::string, std::string> histogramEntries; // populate eventEntries and histogramEntries - for (auto eit = dataEntries.begin(); eit != dataEntries.end(); ++eit) { - std::string dataName = eit->first; - std::string dataType = eit->second; + for (auto &dataEntry : dataEntries) { + std::string dataName = dataEntry.first; + std::string dataType = dataEntry.second; if (dataName == "content_nxs" || dataType != "NXdata") continue; // can be removed if sure no Nexus files contains // "content_nxs" @@ -116,19 +116,18 @@ void LoadMcStas::exec() { auto nxdataEntries = nxFile.getEntries(); - for (auto nit = nxdataEntries.begin(); nit != nxdataEntries.end(); - ++nit) { - if (nit->second == "NXparameters") + for (auto &nxdataEntry : nxdataEntries) { + if (nxdataEntry.second == "NXparameters") continue; - nxFile.openData(nit->first); + nxFile.openData(nxdataEntry.first); if (nxFile.hasAttr("long_name")) { std::string nameAttrValue; nxFile.getAttr("long_name", nameAttrValue); if (nameAttrValue.find("Neutron_ID") != std::string::npos) { - eventEntries[eit->first] = eit->second; + eventEntries[dataEntry.first] = dataEntry.second; } else { - histogramEntries[eit->first] = eit->second; + histogramEntries[dataEntry.first] = dataEntry.second; } } nxFile.closeData(); @@ -247,9 +246,9 @@ void LoadMcStas::readEventData( const size_t numEventEntries = eventEntries.size(); Progress progEntries(this, progressFractionInitial, 1.0, numEventEntries * 2); - for (auto eit = eventEntries.begin(); eit != eventEntries.end(); ++eit) { - std::string dataName = eit->first; - std::string dataType = eit->second; + for (const auto &eventEntry : eventEntries) { + const std::string &dataName = eventEntry.first; + const std::string &dataType = eventEntry.second; // open second level entry nxFile.openGroup(dataName, dataType); @@ -416,10 +415,9 @@ void LoadMcStas::readHistogramData( std::string nameAttrValueYLABEL; - for (auto eit = histogramEntries.begin(); eit != histogramEntries.end(); - ++eit) { - std::string dataName = eit->first; - std::string dataType = eit->second; + for (const auto &histogramEntry : histogramEntries) { + const std::string &dataName = histogramEntry.first; + const std::string &dataType = histogramEntry.second; // open second level entry nxFile.openGroup(dataName, dataType); @@ -435,20 +433,20 @@ void LoadMcStas::readHistogramData( // Find the axis names auto nxdataEntries = nxFile.getEntries(); std::string axis1Name, axis2Name; - for (auto nit = nxdataEntries.begin(); nit != nxdataEntries.end(); ++nit) { - if (nit->second == "NXparameters") + for (auto &nxdataEntry : nxdataEntries) { + if (nxdataEntry.second == "NXparameters") continue; - if (nit->first == "ncount") + if (nxdataEntry.first == "ncount") continue; - nxFile.openData(nit->first); + nxFile.openData(nxdataEntry.first); if (nxFile.hasAttr("axis")) { int axisNo(0); nxFile.getAttr("axis", axisNo); if (axisNo == 1) - axis1Name = nit->first; + axis1Name = nxdataEntry.first; else if (axisNo == 2) - axis2Name = nit->first; + axis2Name = nxdataEntry.first; else throw std::invalid_argument("Unknown axis number"); } diff --git a/Framework/DataHandling/src/LoadMcStasNexus.cpp b/Framework/DataHandling/src/LoadMcStasNexus.cpp index fa4a798e93b93a6ef9f1b3954d26a25a25e61f44..d4c35942e46bd015d1b1389242db86a76f8998ba 100644 --- a/Framework/DataHandling/src/LoadMcStasNexus.cpp +++ b/Framework/DataHandling/src/LoadMcStasNexus.cpp @@ -85,9 +85,9 @@ void LoadMcStasNexus::exec() { nxFile.openGroup(name, type); auto dataEntries = nxFile.getEntries(); - for (auto eit = dataEntries.begin(); eit != dataEntries.end(); ++eit) { - std::string dataName = eit->first; - std::string dataType = eit->second; + for (auto &dataEntry : dataEntries) { + const std::string &dataName = dataEntry.first; + const std::string &dataType = dataEntry.second; if (dataName == "content_nxs" || dataType != "NXdata") continue; g_log.debug() << "Opening " << dataName << " " << dataType << std::endl; @@ -97,18 +97,17 @@ void LoadMcStasNexus::exec() { // Find the axis names auto nxdataEntries = nxFile.getEntries(); std::string axis1Name, axis2Name; - for (auto nit = nxdataEntries.begin(); nit != nxdataEntries.end(); - ++nit) { - if (nit->second == "NXparameters") + for (auto &nxdataEntry : nxdataEntries) { + if (nxdataEntry.second == "NXparameters") continue; - nxFile.openData(nit->first); + nxFile.openData(nxdataEntry.first); if (nxFile.hasAttr("axis")) { int axisNo(0); nxFile.getAttr("axis", axisNo); if (axisNo == 1) - axis1Name = nit->first; + axis1Name = nxdataEntry.first; else if (axisNo == 2) - axis2Name = nit->first; + axis2Name = nxdataEntry.first; else throw std::invalid_argument("Unknown axis number"); } diff --git a/Framework/DataHandling/src/LoadMuonLog.cpp b/Framework/DataHandling/src/LoadMuonLog.cpp index 16a6232e1d39ed43d671019cdd534bb9b6ce54e2..e0fe11b8b63398b5c0c2c6fcbdc642b68112696d 100644 --- a/Framework/DataHandling/src/LoadMuonLog.cpp +++ b/Framework/DataHandling/src/LoadMuonLog.cpp @@ -110,9 +110,8 @@ void LoadMuonLog::exec() { * @returns The string but with all characters in lower case */ std::string LoadMuonLog::stringToLower(std::string strToConvert) { - for (unsigned int i = 0; i < strToConvert.length(); i++) { - strToConvert[i] = static_cast<char>(tolower(strToConvert[i])); - } + std::transform(strToConvert.begin(), strToConvert.end(), strToConvert.begin(), + ::tolower); return strToConvert; // return the converted string } diff --git a/Framework/DataHandling/src/LoadMuonNexus1.cpp b/Framework/DataHandling/src/LoadMuonNexus1.cpp index d7a1621c0f981e0a87c08c3509fb0c59df159a00..688f268c7867b090cb2da3c55a750ad3c7b40db7 100644 --- a/Framework/DataHandling/src/LoadMuonNexus1.cpp +++ b/Framework/DataHandling/src/LoadMuonNexus1.cpp @@ -27,6 +27,7 @@ #include <Poco/Path.h> #include <limits> #include <cmath> +#include <boost/iterator/counting_iterator.hpp> #include <boost/shared_ptr.hpp> #include <boost/scoped_array.hpp> @@ -260,10 +261,10 @@ void LoadMuonNexus1::exec() { } // Read in the spectra in the optional list parameter, if set if (m_list) { - for (size_t i = 0; i < m_spec_list.size(); ++i) { + for (auto specid : m_spec_list) { specid_t histToRead = - static_cast<specid_t>(m_spec_list[i] - 1 + period * nxload.t_nsp1); - specid_t specNo = static_cast<specid_t>(m_spec_list[i]); + static_cast<specid_t>(specid - 1 + period * nxload.t_nsp1); + specid_t specNo = static_cast<specid_t>(specid); loadData(counter, histToRead, specNo, nxload, lengthIn - 1, localWorkspace); counter++; @@ -346,12 +347,12 @@ void LoadMuonNexus1::loadDeadTimes(NXRoot &root) { // Set the spectrum list that should be loaded if (m_interval || m_list) { // Load only selected spectra - for (int64_t i = m_spec_min; i < m_spec_max; i++) { - specToLoad.push_back(static_cast<int>(i)); - } - for (auto it = m_spec_list.begin(); it != m_spec_list.end(); ++it) { - specToLoad.push_back(*it); - } + specToLoad.insert( + specToLoad.end(), + boost::counting_iterator<int>(static_cast<int>(m_spec_min)), + boost::counting_iterator<int>(static_cast<int>(m_spec_max))); + specToLoad.insert(specToLoad.end(), m_spec_list.begin(), + m_spec_list.end()); } else { // Load all the spectra // Start from 1 to N+1 to be consistent with @@ -379,8 +380,8 @@ void LoadMuonNexus1::loadDeadTimes(NXRoot &root) { // Simpliest case - one dead time for one detector // Populate deadTimes - for (auto it = specToLoad.begin(); it != specToLoad.end(); ++it) { - deadTimes.push_back(deadTimesData[*it - 1]); + for (auto &spectra : specToLoad) { + deadTimes.emplace_back(deadTimesData[spectra - 1]); } // Load into table TableWorkspace_sptr table = createDeadTimeTable(specToLoad, deadTimes); @@ -394,8 +395,8 @@ void LoadMuonNexus1::loadDeadTimes(NXRoot &root) { for (int64_t i = 0; i < m_numberOfPeriods; i++) { // Populate deadTimes - for (auto it = specToLoad.begin(); it != specToLoad.end(); ++it) { - int index = static_cast<int>(*it - 1 + i * m_numberOfSpectra); + for (auto spec : specToLoad) { + int index = static_cast<int>(spec - 1 + i * m_numberOfSpectra); deadTimes.push_back(deadTimesData[index]); } @@ -435,12 +436,12 @@ Workspace_sptr LoadMuonNexus1::loadDetectorGrouping(NXRoot &root) { // Set the spectrum list that should be loaded if (m_interval || m_list) { // Load only selected spectra - for (int64_t i = m_spec_min; i < m_spec_max; i++) { - specToLoad.push_back(static_cast<int>(i)); - } - for (auto it = m_spec_list.begin(); it != m_spec_list.end(); ++it) { - specToLoad.push_back(*it); - } + specToLoad.insert( + specToLoad.end(), + boost::counting_iterator<int>(static_cast<int>(m_spec_min)), + boost::counting_iterator<int>(static_cast<int>(m_spec_max))); + specToLoad.insert(specToLoad.end(), m_spec_list.begin(), + m_spec_list.end()); } else { // Load all the spectra // Start from 1 to N+1 to be consistent with @@ -466,21 +467,20 @@ Workspace_sptr LoadMuonNexus1::loadDetectorGrouping(NXRoot &root) { if (m_numberOfPeriods == 1) { // Simpliest case - one grouping entry per spectrum - + grouping.reserve(grouping.size() + specToLoad.size()); if (!m_entrynumber) { // m_entrynumber = 0 && m_numberOfPeriods = 1 means that user did not // select // any periods but there is only one in the dataset - for (auto it = specToLoad.begin(); it != specToLoad.end(); ++it) { - int index = *it - 1; - grouping.push_back(groupingData[index]); + for (auto spec : specToLoad) { + grouping.emplace_back(groupingData[spec - 1]); } } else { // User selected an entry number - for (auto it = specToLoad.begin(); it != specToLoad.end(); ++it) { - int index = *it - 1 + static_cast<int>((m_entrynumber - 1) * - m_numberOfSpectra); - grouping.push_back(groupingData[index]); + for (auto &spec : specToLoad) { + int index = spec - 1 + static_cast<int>((m_entrynumber - 1) * + m_numberOfSpectra); + grouping.emplace_back(groupingData[index]); } } @@ -499,9 +499,9 @@ Workspace_sptr LoadMuonNexus1::loadDetectorGrouping(NXRoot &root) { // Get the grouping grouping.clear(); - for (auto it = specToLoad.begin(); it != specToLoad.end(); ++it) { - int index = *it - 1 + i * static_cast<int>(m_numberOfSpectra); - grouping.push_back(groupingData[index]); + for (auto &spec : specToLoad) { + int index = spec - 1 + i * static_cast<int>(m_numberOfSpectra); + grouping.emplace_back(groupingData[index]); } // Set table for period i @@ -573,11 +573,11 @@ LoadMuonNexus1::createDetectorGroupingTable(std::vector<int> specToLoad, groupingMap[grouping[i]].push_back(specToLoad[i]); } - for (auto it = groupingMap.begin(); it != groupingMap.end(); ++it) { - if (it->first != 0) // Skip 0 group + for (auto &group : groupingMap) { + if (group.first != 0) // Skip 0 group { TableRow newRow = detectorGroupingTable->appendRow(); - newRow << it->second; + newRow << group.second; } } diff --git a/Framework/DataHandling/src/LoadMuonNexus2.cpp b/Framework/DataHandling/src/LoadMuonNexus2.cpp index abf0bd22c28179a046332498b055ac894a6c9816..7f6013589c6f69fe71717297370836e6d208180b 100644 --- a/Framework/DataHandling/src/LoadMuonNexus2.cpp +++ b/Framework/DataHandling/src/LoadMuonNexus2.cpp @@ -116,10 +116,10 @@ void LoadMuonNexus2::doExec() { std::string detectorName; // Only the first NXdata found - for (unsigned int i = 0; i < entry.groups().size(); i++) { - std::string className = entry.groups()[i].nxclass; + for (auto &group : entry.groups()) { + std::string className = group.nxclass; if (className == "NXdata") { - detectorName = entry.groups()[i].nxname; + detectorName = group.nxname; break; } } @@ -254,8 +254,7 @@ void LoadMuonNexus2::doExec() { // Read in the spectra in the optional list parameter, if set if (m_list) { - for (unsigned int i = 0; i < m_spec_list.size(); ++i) { - int spec = m_spec_list[i]; + for (auto spec : m_spec_list) { int k = index_spectrum[spec]; // if spec not found k is 0 loadData(counts, timeBins, counter, period, k, localWorkspace); localWorkspace->getSpectrum(counter)->setSpectrumNo(spectrum_index[k]); diff --git a/Framework/DataHandling/src/LoadNexusLogs.cpp b/Framework/DataHandling/src/LoadNexusLogs.cpp index 6df5f9622fe7dbb141d55beefdb67a1b3466fb50..55b8fc69f16ad06eb2d47297613572f8f42c2fb5 100644 --- a/Framework/DataHandling/src/LoadNexusLogs.cpp +++ b/Framework/DataHandling/src/LoadNexusLogs.cpp @@ -229,9 +229,9 @@ void LoadNexusLogs::exec() { ptime.reserve(event_frame_number.size()); std::vector<Mantid::Kernel::DateAndTime> plogt = plog->timesAsVector(); std::vector<double> plogv = plog->valuesAsVector(); - for (size_t i = 0; i < event_frame_number.size(); ++i) { - ptime.push_back(plogt[event_frame_number[i]]); - pval.push_back(plogv[event_frame_number[i]]); + for (auto number : event_frame_number) { + ptime.push_back(plogt[number]); + pval.push_back(plogv[number]); } pcharge->create(ptime, pval); pcharge->setUnits("uAh"); diff --git a/Framework/DataHandling/src/LoadNexusMonitors2.cpp b/Framework/DataHandling/src/LoadNexusMonitors2.cpp index 8b835b0ad98a9e9d0fc24510f7bc4e8f06b713cf..2e05b3a09d63e6c081453b89bf3ef1e0f711219a 100644 --- a/Framework/DataHandling/src/LoadNexusMonitors2.cpp +++ b/Framework/DataHandling/src/LoadNexusMonitors2.cpp @@ -149,15 +149,14 @@ void LoadNexusMonitors2::exec() { int numEventThings = 0; // number of things that are eventish - should be 3 string_map_t inner_entries = file.getEntries(); // get list of entries - for (auto inner = inner_entries.begin(); inner != inner_entries.end(); - ++inner) { - if (inner->first == "event_index") { + for (auto &entry : inner_entries) { + if (entry.first == "event_index") { numEventThings += 1; continue; - } else if (inner->first == "event_time_offset") { + } else if (entry.first == "event_time_offset") { numEventThings += 1; continue; - } else if (inner->first == "event_time_zero") { + } else if (entry.first == "event_time_zero") { numEventThings += 1; continue; } @@ -234,9 +233,8 @@ void LoadNexusMonitors2::exec() { // number if (monitorNumber2Name.size() == monitorNames.size()) { monitorNames.clear(); - for (auto it = monitorNumber2Name.begin(); it != monitorNumber2Name.end(); - ++it) { - monitorNames.push_back(it->second); + for (auto &numberName : monitorNumber2Name) { + monitorNames.push_back(numberName.second); } } } else if (numEventMon == m_monitor_count) { diff --git a/Framework/DataHandling/src/LoadNexusProcessed.cpp b/Framework/DataHandling/src/LoadNexusProcessed.cpp index 556d63c54c7c070d251760ac9e28db09112c5d1d..67ecc7213dc5b8e9c0abd10ce53cc6101fdb7a28 100644 --- a/Framework/DataHandling/src/LoadNexusProcessed.cpp +++ b/Framework/DataHandling/src/LoadNexusProcessed.cpp @@ -1095,8 +1095,7 @@ API::Workspace_sptr LoadNexusProcessed::loadPeaksEntry(NXEntry &entry) { peakWS->addPeak(*p); } - for (size_t i = 0; i < columnNames.size(); i++) { - const std::string str = columnNames[i]; + for (auto str : columnNames) { if (!str.compare("column_1")) { NXInt nxInt = nx_tw.openNXInt(str.c_str()); nxInt.load(); @@ -1743,10 +1742,7 @@ bool UDlesserExecCount(NXClassInfo elem1, NXClassInfo elem2) { is1 >> execNum1; is2 >> execNum2; - if (execNum1 < execNum2) - return true; - else - return false; + return execNum1 < execNum2; } //------------------------------------------------------------------------------------------------- diff --git a/Framework/DataHandling/src/LoadPreNexus.cpp b/Framework/DataHandling/src/LoadPreNexus.cpp index d81fd0694fa8fdd063c24a750380d55b4e1dbce8..fb76fda3ab088ce498c21ce757cde15f8e0e0b6f 100644 --- a/Framework/DataHandling/src/LoadPreNexus.cpp +++ b/Framework/DataHandling/src/LoadPreNexus.cpp @@ -256,8 +256,8 @@ void LoadPreNexus::parseRuninfo(const string &runinfo, string &dataDir, g_log.debug() << "Found 1 event file: \"" << eventFilenames[0] << "\"\n"; } else { g_log.debug() << "Found " << eventFilenames.size() << " event files:"; - for (size_t i = 0; i < eventFilenames.size(); i++) { - g_log.debug() << "\"" << eventFilenames[i] << "\" "; + for (auto &eventFilename : eventFilenames) { + g_log.debug() << "\"" << eventFilename << "\" "; } g_log.debug() << "\n"; } @@ -293,20 +293,19 @@ void LoadPreNexus::runLoadNexusLogs(const string &runinfo, // run the algorithm bool loadedLogs = false; - for (size_t i = 0; i < possibilities.size(); i++) { - if (Poco::File(possibilities[i]).exists()) { - g_log.information() << "Loading logs from \"" << possibilities[i] - << "\"\n"; + for (auto &possibility : possibilities) { + if (Poco::File(possibility).exists()) { + g_log.information() << "Loading logs from \"" << possibility << "\"\n"; IAlgorithm_sptr alg = this->createChildAlgorithm("LoadNexusLogs", prog_start, prog_stop); alg->setProperty("Workspace", m_outputWorkspace); - alg->setProperty("Filename", possibilities[i]); + alg->setProperty("Filename", possibility); alg->setProperty("OverwriteLogs", false); alg->executeAsChildAlg(); loadedLogs = true; // Reload instrument so SNAP can use log values - std::string entry_name = LoadTOFRawNexus::getEntryName(possibilities[i]); - LoadEventNexus::runLoadInstrument(possibilities[i], m_outputWorkspace, + std::string entry_name = LoadTOFRawNexus::getEntryName(possibility); + LoadEventNexus::runLoadInstrument(possibility, m_outputWorkspace, entry_name, this); break; } diff --git a/Framework/DataHandling/src/LoadRKH.cpp b/Framework/DataHandling/src/LoadRKH.cpp index d737c518fdb8159da986971a604294e2851b21d6..caae56f49b11505c3b0d9170cda373b9f782d4c5 100644 --- a/Framework/DataHandling/src/LoadRKH.cpp +++ b/Framework/DataHandling/src/LoadRKH.cpp @@ -97,8 +97,8 @@ int LoadRKH::confidence(Kernel::FileDescriptor &descriptor) const { "-SEP-", "-OCT-", "-NOV-", "-DEC-"}; bool foundMonth(false); - for (size_t i = 0; i < 12; ++i) { - if (!boost::ifind_first(fileline, MONTHS[i]).empty()) { + for (auto &month : MONTHS) { + if (!boost::ifind_first(fileline, month).empty()) { foundMonth = true; break; } @@ -342,8 +342,8 @@ const MatrixWorkspace_sptr LoadRKH::read2D(const std::string &firstLine) { // now read in the Y values MantidVec &YOut = outWrksp->dataY(i); - for (auto it = YOut.begin(), end = YOut.end(); it != end; ++it) { - m_fileIn >> *it; + for (double &value : YOut) { + m_fileIn >> value; } prog.report("Loading Y data"); } // loop on to the next spectrum @@ -351,8 +351,8 @@ const MatrixWorkspace_sptr LoadRKH::read2D(const std::string &firstLine) { // the error values form one big block after the Y-values for (size_t i = 0; i < nAxis1Values; ++i) { MantidVec &EOut = outWrksp->dataE(i); - for (auto it = EOut.begin(), end = EOut.end(); it != end; ++it) { - m_fileIn >> *it; + for (double &value : EOut) { + m_fileIn >> value; } prog.report("Loading error estimates"); } // loop on to the next spectrum diff --git a/Framework/DataHandling/src/LoadRaw/isisraw.cpp b/Framework/DataHandling/src/LoadRaw/isisraw.cpp index 6c0834013b9dc2aa186be464a7dd3c6ecd1f45b1..eee43d4fb5ade28d7fce3e25594eb7edb2e806ae 100644 --- a/Framework/DataHandling/src/LoadRaw/isisraw.cpp +++ b/Framework/DataHandling/src/LoadRaw/isisraw.cpp @@ -144,8 +144,8 @@ ISISRAW::ISISRAW(ISISCRPT_STRUCT *crpt) ddes(0), dat1(0) { memset(r_title, ' ', sizeof(r_title)); memset(i_inst, ' ', sizeof(i_inst)); - for (int i = 0; i < 256; i++) { - t_pmap[i] = 1; // period number for each basic period + for (auto &value : t_pmap) { + value = 1; // period number for each basic period } memset(t_tcm1, 0, sizeof(t_tcm1)); // time channel mode memset(t_tcp1, 0, sizeof(t_tcp1)); // time channel parameters @@ -169,8 +169,8 @@ ISISRAW::ISISRAW(ISISCRPT_STRUCT *crpt, bool doUpdateFromCRPT) ddes(0), dat1(0) { memset(r_title, ' ', sizeof(r_title)); memset(i_inst, ' ', sizeof(i_inst)); - for (int i = 0; i < 256; i++) { - t_pmap[i] = 1; // period number for each basic period + for (auto &value : t_pmap) { + value = 1; // period number for each basic period } memset(t_tcm1, 0, sizeof(t_tcm1)); // time channel mode memset(t_tcp1, 0, sizeof(t_tcp1)); // time channel parameters diff --git a/Framework/DataHandling/src/LoadRawHelper.cpp b/Framework/DataHandling/src/LoadRawHelper.cpp index 3cbf5c9d9e8c509659b7c6da47ed19923746bef6..d2e79c857342f0fb8f6b08455e449e3ac1b73554 100644 --- a/Framework/DataHandling/src/LoadRawHelper.cpp +++ b/Framework/DataHandling/src/LoadRawHelper.cpp @@ -424,15 +424,15 @@ LoadRawHelper::getmonitorSpectrumList(const SpectrumDetectorMapping &mapping) { if (!m_monitordetectorList.empty()) { const auto &map = mapping.getMapping(); - for (auto it = map.begin(); it != map.end(); ++it) { - auto detIDs = it->second; + for (const auto &SpectrumDetectorPair : map) { + auto detIDs = SpectrumDetectorPair.second; // Both m_monitordetectorList & detIDs should be (very) short so the // nested loop shouldn't be too evil - for (auto detIt = detIDs.begin(); detIt != detIDs.end(); ++detIt) { + for (auto detID : detIDs) { if (std::find(m_monitordetectorList.begin(), m_monitordetectorList.end(), - *detIt) != m_monitordetectorList.end()) { - spectrumIndices.push_back(it->first); + detID) != m_monitordetectorList.end()) { + spectrumIndices.push_back(SpectrumDetectorPair.first); } } } diff --git a/Framework/DataHandling/src/LoadSpice2D.cpp b/Framework/DataHandling/src/LoadSpice2D.cpp index 4312bfd53be4b482ea97fedfd0c5bfc156e0ed5e..ef8dc9a495a4f4173fb853c6345c2a934bbc931e 100644 --- a/Framework/DataHandling/src/LoadSpice2D.cpp +++ b/Framework/DataHandling/src/LoadSpice2D.cpp @@ -206,10 +206,10 @@ void LoadSpice2D::parseDetectorDimensions(const std::string &dims_str) { void LoadSpice2D::addMetadataAsRunProperties( const std::map<std::string, std::string> &metadata) { - for (auto it = metadata.begin(); it != metadata.end(); it++) { - std::string key = it->first; + for (const auto &keyValuePair : metadata) { + std::string key = keyValuePair.first; std::replace(key.begin(), key.end(), '/', '_'); - m_workspace->mutableRun().addProperty(key, it->second, true); + m_workspace->mutableRun().addProperty(key, keyValuePair.second, true); } } @@ -317,12 +317,11 @@ void LoadSpice2D::createWorkspace(const std::vector<int> &data, m_dwavelength); // Store detector pixels - for (auto it = data.begin(); it != data.end(); ++it) { - double count = static_cast<double>(*it); + for (auto count : data) { // Data uncertainties, computed according to the HFIR/IGOR reduction code // The following is what I would suggest instead... // error = count > 0 ? sqrt((double)count) : 0.0; - double error = sqrt(0.5 + fabs(count - 0.5)); + double error = sqrt(0.5 + fabs(static_cast<double>(count) - 0.5)); store_value(m_workspace, specID++, count, error, m_wavelength, m_dwavelength); } diff --git a/Framework/DataHandling/src/LoadSpiceAscii.cpp b/Framework/DataHandling/src/LoadSpiceAscii.cpp index 8001c96a214dd9849e05647ae7f41f9fa6b0df01..cd77173dfce4d07b12f15b7425a229dcb433be77 100644 --- a/Framework/DataHandling/src/LoadSpiceAscii.cpp +++ b/Framework/DataHandling/src/LoadSpiceAscii.cpp @@ -34,10 +34,7 @@ static bool endswith(const std::string &s, const std::string &subs) { // get a substring std::string tail = s.substr(s.size() - subs.size()); - if (tail.compare(subs) != 0) - return false; - - return true; + return tail.compare(subs) == 0; } static bool checkIntersection(std::vector<std::string> v1, @@ -50,10 +47,7 @@ static bool checkIntersection(std::vector<std::string> v1, std::vector<std::string> intersectvec(v1.size() + v2.size()); auto outiter = std::set_intersection(v1.begin(), v1.end(), v2.begin(), v2.end(), intersectvec.begin()); - if (static_cast<int>(outiter - intersectvec.begin()) == 0) - return false; - - return true; + return static_cast<int>(outiter - intersectvec.begin()) != 0; } //---------------------------------------------------------------------------------------------- diff --git a/Framework/DataHandling/src/LoadTOFRawNexus.cpp b/Framework/DataHandling/src/LoadTOFRawNexus.cpp index c26abaf59213a103373484806cfb76b4154c38b7..2e01dc76345cc7b6b2a35e1be0a2287f27af6458 100644 --- a/Framework/DataHandling/src/LoadTOFRawNexus.cpp +++ b/Framework/DataHandling/src/LoadTOFRawNexus.cpp @@ -199,8 +199,8 @@ void LoadTOFRawNexus::countPixels(const std::string &nexusfilename, if (!dims.empty()) { size_t newPixels = 1; - for (size_t i = 0; i < dims.size(); i++) - newPixels *= dims[i]; + for (auto dim : dims) + newPixels *= dim; m_numPixels += newPixels; } } else { @@ -547,9 +547,8 @@ void LoadTOFRawNexus::exec() { // Load each bank sequentially // PARALLEL_FOR1(WS) - for (int i = 0; i < int(bankNames.size()); i++) { + for (auto bankName : bankNames) { // PARALLEL_START_INTERUPT_REGION - std::string bankName = bankNames[i]; prog->report("Loading bank " + bankName); g_log.debug() << "Loading bank " << bankName << std::endl; loadBank(filename, entry_name, bankName, WS, id_to_wi); diff --git a/Framework/DataHandling/src/LoadVulcanCalFile.cpp b/Framework/DataHandling/src/LoadVulcanCalFile.cpp index d50fc14d79a56d659673a639159597ac74d516c8..4e0b22c9fdda8121e41eb7a9e35cb5962722b2ac 100644 --- a/Framework/DataHandling/src/LoadVulcanCalFile.cpp +++ b/Framework/DataHandling/src/LoadVulcanCalFile.cpp @@ -390,9 +390,8 @@ void LoadVulcanCalFile::processOffsets( std::set<int> set_bankID; map<detid_t, pair<bool, int>> map_verify; // key: detector ID, value: flag to have a match, bank ID - for (auto miter = map_detoffset.begin(); miter != map_detoffset.end(); - ++miter) { - detid_t pid = miter->first; + for (auto &miter : map_detoffset) { + detid_t pid = miter.first; auto fiter = map_det2index.find(pid); if (fiter == map_det2index.end()) { map_verify.emplace(pid, make_pair(false, -1)); @@ -418,8 +417,7 @@ void LoadVulcanCalFile::processOffsets( static const size_t arr[] = {21, 22, 23, 26, 27, 28}; vector<size_t> vec_banks(arr, arr + sizeof(arr) / sizeof(arr[0])); - for (size_t i = 0; i < vec_banks.size(); ++i) { - size_t bankindex = vec_banks[i]; + for (auto bankindex : vec_banks) { for (size_t j = 0; j < NUMBERDETECTORPERMODULE; ++j) { detid_t detindex = static_cast<detid_t>(bankindex * NUMBERRESERVEDPERMODULE + j); diff --git a/Framework/DataHandling/src/MergeLogs.cpp b/Framework/DataHandling/src/MergeLogs.cpp index 9e2cd4666870a05e72f243c588d9eddc077108a5..8be9ba582517ef1ea6537b9c31880dfc2ea2a9ab 100644 --- a/Framework/DataHandling/src/MergeLogs.cpp +++ b/Framework/DataHandling/src/MergeLogs.cpp @@ -107,11 +107,7 @@ void Merge2WorkspaceLogs::mergeLogs(std::string ilogname1, // i. Determine which log to work on if (!nocomparison) { - if (times1[index1] < times2[index2]) { - launch1 = true; - } else { - launch1 = false; - } + launch1 = times1[index1] < times2[index2]; } // ii. Retrieve data from source log diff --git a/Framework/DataHandling/src/ProcessDasNexusLog.cpp b/Framework/DataHandling/src/ProcessDasNexusLog.cpp index bf766508f080eb2b4c2e0b7f1ef8da494df410d7..cba798eb1a6bd7f89907daa6d8c7352522947bbd 100644 --- a/Framework/DataHandling/src/ProcessDasNexusLog.cpp +++ b/Framework/DataHandling/src/ProcessDasNexusLog.cpp @@ -177,8 +177,8 @@ void ProcessDasNexusLog::addLog(API::MatrixWorkspace_sptr ws, // 2. Add log auto newlog = new Kernel::TimeSeriesProperty<double>(logname); - for (size_t i = 0; i < timevec.size(); i++) { - newlog->addValue(timevec[i], unifylogvalue); + for (auto &time : timevec) { + newlog->addValue(time, unifylogvalue); } ws->mutableRun().addProperty(newlog, true); @@ -402,11 +402,11 @@ void ProcessDasNexusLog::convertToAbsoluteTime( if (tnow > prevtime) { // (a) Process previous logs std::sort(tofs.begin(), tofs.end()); - for (size_t j = 0; j < tofs.size(); j++) { + for (double tof : tofs) { Kernel::DateAndTime temptime = - prevtime + static_cast<int64_t>(tofs[j] * 100); + prevtime + static_cast<int64_t>(tof * 100); abstimevec.push_back(temptime); - orderedtofs.push_back(tofs[j]); + orderedtofs.push_back(tof); } // (b) Clear tofs.clear(); @@ -422,11 +422,10 @@ void ProcessDasNexusLog::convertToAbsoluteTime( if (!tofs.empty()) { // (a) Process previous logs: note value is in unit of 100 nano-second std::sort(tofs.begin(), tofs.end()); - for (size_t j = 0; j < tofs.size(); j++) { - Kernel::DateAndTime temptime = - prevtime + static_cast<int64_t>(tofs[j] * 100); + for (double tof : tofs) { + Kernel::DateAndTime temptime = prevtime + static_cast<int64_t>(tof * 100); abstimevec.push_back(temptime); - orderedtofs.push_back(tofs[j]); + orderedtofs.push_back(tof); } } else { throw std::runtime_error("Impossible for this to happen!"); @@ -467,11 +466,11 @@ void ProcessDasNexusLog::writeLogtoFile(API::MatrixWorkspace_sptr ws, if (tnow > prevtime) { // (a) Process previous logs std::sort(tofs.begin(), tofs.end()); - for (size_t j = 0; j < tofs.size(); j++) { + for (double tof : tofs) { Kernel::DateAndTime temptime = - prevtime + static_cast<int64_t>(tofs[j] * 100); + prevtime + static_cast<int64_t>(tof * 100); ofs << temptime.totalNanoseconds() << "\t" << tnow.totalNanoseconds() - << "\t" << tofs[j] * 0.1 << std::endl; + << "\t" << tof * 0.1 << std::endl; } // (b) Clear tofs.clear(); @@ -486,11 +485,10 @@ void ProcessDasNexusLog::writeLogtoFile(API::MatrixWorkspace_sptr ws, if (!tofs.empty()) { // (a) Process previous logs: note value is in unit of 100 nano-second std::sort(tofs.begin(), tofs.end()); - for (size_t j = 0; j < tofs.size(); j++) { - Kernel::DateAndTime temptime = - prevtime + static_cast<int64_t>(tofs[j] * 100); + for (double tof : tofs) { + Kernel::DateAndTime temptime = prevtime + static_cast<int64_t>(tof * 100); ofs << temptime.totalNanoseconds() << "\t" << prevtime.totalNanoseconds() - << "\t" << tofs[j] * 0.1 << std::endl; + << "\t" << tof * 0.1 << std::endl; } } else { throw std::runtime_error("Impossible for this to happen!"); diff --git a/Framework/DataHandling/src/SNSDataArchive.cpp b/Framework/DataHandling/src/SNSDataArchive.cpp index 1048c22c38aad4d24f4233b5055e25ad6a03dbcd..cb903d523b0ac65abd12444c46826b7c44279d28 100644 --- a/Framework/DataHandling/src/SNSDataArchive.cpp +++ b/Framework/DataHandling/src/SNSDataArchive.cpp @@ -45,8 +45,8 @@ SNSDataArchive::getArchivePath(const std::set<std::string> &filenames, // ICAT4 web service take upper case filename such as HYSA_2662 std::transform(filename.begin(), filename.end(), filename.begin(), toupper); - for (auto iter2 = exts.cbegin(); iter2 != exts.cend(); ++iter2) { - g_log.debug() << *iter2 << ";"; + for (const auto &ext : exts) { + g_log.debug() << ext << ";"; } g_log.debug() << "\n"; @@ -79,8 +79,8 @@ SNSDataArchive::getArchivePath(const std::set<std::string> &filenames, } } - for (auto ext = exts.begin(); ext != exts.cend(); ++ext) { - std::string datafile = filename + *ext; + for (const auto &ext : exts) { + std::string datafile = filename + ext; std::vector<std::string>::const_iterator iter = locations.begin(); for (; iter != locations.end(); ++iter) { if (boost::algorithm::ends_with((*iter), datafile)) { diff --git a/Framework/DataHandling/src/SaveAscii.cpp b/Framework/DataHandling/src/SaveAscii.cpp index 569ea6ee7683062eaabcca153fe9b7f3f23d54f4..2f8f8490f1e2497222ee2c5897d1240c71691d0c 100644 --- a/Framework/DataHandling/src/SaveAscii.cpp +++ b/Framework/DataHandling/src/SaveAscii.cpp @@ -59,10 +59,10 @@ void SaveAscii::init() { {"SemiColon", ";"}, {"UserDefined", "UserDefined"}}; std::vector<std::string> sepOptions; - for (size_t i = 0; i < 6; ++i) { - std::string option = spacers[i][0]; + for (auto &spacer : spacers) { + std::string option = spacer[0]; m_separatorIndex.insert( - std::pair<std::string, std::string>(option, spacers[i][1])); + std::pair<std::string, std::string>(option, spacer[1])); sepOptions.push_back(option); } @@ -150,11 +150,11 @@ void SaveAscii::exec() { // Add spectra list into the index list if (!spec_list.empty()) { - for (size_t i = 0; i < spec_list.size(); i++) { - if (spec_list[i] >= nSpectra) + for (auto &spec : spec_list) { + if (spec >= nSpectra) throw std::invalid_argument("Inconsistent spectra list"); else - idx.insert(spec_list[i]); + idx.insert(spec); } } if (!idx.empty()) @@ -181,10 +181,10 @@ void SaveAscii::exec() { file << " , DX" << spec; } else - for (auto spec = idx.cbegin(); spec != idx.cend(); ++spec) { - file << comstr << "Y" << *spec << comstr << errstr << *spec << errstr2; + for (auto spec : idx) { + file << comstr << "Y" << spec << comstr << errstr << spec << errstr2; if (write_dx) - file << " , DX" << *spec; + file << " , DX" << spec; } file << std::endl; } @@ -214,11 +214,11 @@ void SaveAscii::exec() { file << ws->readE(spec)[bin]; } else - for (auto spec = idx.cbegin(); spec != idx.cend(); ++spec) { + for (auto spec : idx) { file << sep; - file << ws->readY(*spec)[bin]; + file << ws->readY(spec)[bin]; file << sep; - file << ws->readE(*spec)[bin]; + file << ws->readE(spec)[bin]; } if (write_dx) { diff --git a/Framework/DataHandling/src/SaveAscii2.cpp b/Framework/DataHandling/src/SaveAscii2.cpp index 2f31a286492bbc11ebf9161ff0c12692598768be..9a66965c93f87ef22c693a97b5562fc88fb34d1d 100644 --- a/Framework/DataHandling/src/SaveAscii2.cpp +++ b/Framework/DataHandling/src/SaveAscii2.cpp @@ -71,10 +71,10 @@ void SaveAscii2::init() { {"SemiColon", ";"}, {"UserDefined", "UserDefined"}}; std::vector<std::string> sepOptions; - for (size_t i = 0; i < 6; ++i) { - std::string option = spacers[i][0]; + for (auto &spacer : spacers) { + std::string option = spacer[0]; m_separatorIndex.insert( - std::pair<std::string, std::string>(option, spacers[i][1])); + std::pair<std::string, std::string>(option, spacer[1])); sepOptions.push_back(option); } @@ -181,11 +181,11 @@ void SaveAscii2::exec() { // Add spectra list into the index list if (!spec_list.empty()) { - for (size_t i = 0; i < spec_list.size(); i++) { - if (spec_list[i] >= nSpectra) { + for (auto &spec : spec_list) { + if (spec >= nSpectra) { throw std::invalid_argument("Inconsistent spectra list"); } else { - idx.insert(spec_list[i]); + idx.insert(spec); } } } diff --git a/Framework/DataHandling/src/SaveCSV.cpp b/Framework/DataHandling/src/SaveCSV.cpp index e57a691c56a3a3149ad9b881ebae5d3fcb393ca0..fb4265b3ac313f4637b4d95318cb2473cbc8b195 100644 --- a/Framework/DataHandling/src/SaveCSV.cpp +++ b/Framework/DataHandling/src/SaveCSV.cpp @@ -129,8 +129,8 @@ void SaveCSV::exec() { outCSV_File << "A"; - for (int j = 0; j < static_cast<int>(xValue.size()); j++) { - outCSV_File << std::setw(15) << xValue[j] << m_separator; + for (double j : xValue) { + outCSV_File << std::setw(15) << j << m_separator; } outCSV_File << m_lineSeparator; @@ -147,8 +147,8 @@ void SaveCSV::exec() { if (xValue != xValuePrevious) { outCSV_File << "A"; - for (int j = 0; j < static_cast<int>(xValue.size()); j++) { - outCSV_File << std::setw(15) << xValue[j] << m_separator; + for (double j : xValue) { + outCSV_File << std::setw(15) << j << m_separator; } outCSV_File << m_lineSeparator; @@ -161,8 +161,8 @@ void SaveCSV::exec() { outCSV_File << i; - for (int j = 0; j < static_cast<int>(yValue.size()); j++) { - outCSV_File << std::setw(15) << yValue[j] << m_separator; + for (double j : yValue) { + outCSV_File << std::setw(15) << j << m_separator; } outCSV_File << m_lineSeparator; @@ -177,8 +177,8 @@ void SaveCSV::exec() { outCSV_File << i; - for (int j = 0; j < static_cast<int>(eValue.size()); j++) { - outCSV_File << std::setw(15) << eValue[j] << m_separator; + for (double j : eValue) { + outCSV_File << std::setw(15) << j << m_separator; } outCSV_File << m_lineSeparator; p.report(); @@ -213,8 +213,8 @@ void SaveCSV::saveXerrors(std::ofstream &stream, stream << i; - for (int j = 0; j < static_cast<int>(dXvalue.size()); j++) { - stream << std::setw(15) << dXvalue[j] << m_separator; + for (double j : dXvalue) { + stream << std::setw(15) << j << m_separator; } stream << m_lineSeparator; p.report("Saving x errors..."); diff --git a/Framework/DataHandling/src/SaveCanSAS1D.cpp b/Framework/DataHandling/src/SaveCanSAS1D.cpp index e0feba1bb0286a26766ac4559f6f4981471dd0f9..21a0c230625861ceb96bca17af1d672918f9eca1 100644 --- a/Framework/DataHandling/src/SaveCanSAS1D.cpp +++ b/Framework/DataHandling/src/SaveCanSAS1D.cpp @@ -301,9 +301,9 @@ void SaveCanSAS1D::searchandreplaceSpecialChars(std::string &input) { std::string specialchars = "&<>'\""; std::string::size_type searchIndex = 0; std::string::size_type findIndex; - for (std::string::size_type i = 0; i < specialchars.size(); ++i) { + for (char specialchar : specialchars) { while (searchIndex < input.length()) { - findIndex = input.find(specialchars[i], searchIndex); + findIndex = input.find(specialchar, searchIndex); if (findIndex != std::string::npos) { searchIndex = findIndex + 1; // replace with xml entity refrence diff --git a/Framework/DataHandling/src/SaveDetectorsGrouping.cpp b/Framework/DataHandling/src/SaveDetectorsGrouping.cpp index 59957a2545fbb7cab94f0865a8cd4a3889b07902..6cf919364ca236a5c0170635e2623e61800afce3 100644 --- a/Framework/DataHandling/src/SaveDetectorsGrouping.cpp +++ b/Framework/DataHandling/src/SaveDetectorsGrouping.cpp @@ -116,11 +116,7 @@ void SaveDetectorsGrouping::createGroupDetectorIDMap( << std::endl; throw; } - detid_t detid = 0; - for (auto it = detids.begin(); it != detids.end(); ++it) { - detid = *it; - } - it->second.push_back(detid); + it->second.insert(it->second.end(), detids.begin(), detids.end()); } return; @@ -133,21 +129,21 @@ void SaveDetectorsGrouping::convertToDetectorsRanges( std::map<int, std::vector<detid_t>> groupdetidsmap, std::map<int, std::vector<detid_t>> &groupdetidrangemap) { - for (auto it = groupdetidsmap.begin(); it != groupdetidsmap.end(); ++it) { + for (auto &groupdetids : groupdetidsmap) { // a) Get handler of group ID and detector Id vector - int groupid = it->first; - sort(it->second.begin(), it->second.end()); + int groupid = groupdetids.first; + sort(groupdetids.second.begin(), groupdetids.second.end()); - g_log.debug() << "Group " << groupid << " has " << it->second.size() - << " detectors. " << std::endl; + g_log.debug() << "Group " << groupid << " has " + << groupdetids.second.size() << " detectors. " << std::endl; // b) Group to ranges std::vector<detid_t> detranges; - detid_t st = it->second[0]; + detid_t st = groupdetids.second[0]; detid_t ed = st; - for (size_t i = 1; i < it->second.size(); i++) { - detid_t detid = it->second[i]; + for (size_t i = 1; i < groupdetids.second.size(); i++) { + detid_t detid = groupdetids.second[i]; if (detid == ed + 1) { // consecutive ed = detid; @@ -195,11 +191,10 @@ void SaveDetectorsGrouping::printToXML( } // 3. Append Groups - for (auto it = groupdetidrangemap.begin(); it != groupdetidrangemap.end(); - ++it) { + for (auto &groupdetidrange : groupdetidrangemap) { // a) Group Node - int groupid = it->first; + int groupid = groupdetidrange.first; std::stringstream sid; sid << groupid; @@ -220,12 +215,12 @@ void SaveDetectorsGrouping::printToXML( // b) Detector ID Child Nodes std::stringstream ss; - for (size_t i = 0; i < it->second.size() / 2; i++) { + for (size_t i = 0; i < groupdetidrange.second.size() / 2; i++) { // i. Generate text value bool writedata = true; - detid_t ist = it->second[i * 2]; - detid_t ied = it->second[i * 2 + 1]; + detid_t ist = groupdetidrange.second[i * 2]; + detid_t ied = groupdetidrange.second[i * 2 + 1]; // "a-b" or "a" if (ist < ied) { ss << ist << "-" << ied; @@ -237,12 +232,12 @@ void SaveDetectorsGrouping::printToXML( throw std::invalid_argument("Impossible to have this sitaution!"); } // add "," - if (writedata && i < it->second.size() / 2 - 1) { + if (writedata && i < groupdetidrange.second.size() / 2 - 1) { ss << ","; } - g_log.debug() << "Detectors: " << it->second[i * 2] << ", " - << it->second[i * 2 + 1] << std::endl; + g_log.debug() << "Detectors: " << groupdetidrange.second[i * 2] << ", " + << groupdetidrange.second[i * 2 + 1] << std::endl; } // FOREACH Detectors Range Set std::string textvalue = ss.str(); diff --git a/Framework/DataHandling/src/SaveDiffCal.cpp b/Framework/DataHandling/src/SaveDiffCal.cpp index 9d17f2e8a92aeb6c2af8d0c4ba3930c6e4e0c41b..3749e6cdeb7989770de715e7a3a79636470a4728 100644 --- a/Framework/DataHandling/src/SaveDiffCal.cpp +++ b/Framework/DataHandling/src/SaveDiffCal.cpp @@ -236,10 +236,10 @@ void SaveDiffCal::generateDetidToIndex() { } } -bool SaveDiffCal::tableHasColumn(const std::string name) const { +bool SaveDiffCal::tableHasColumn(const std::string ColumnName) const { const std::vector<std::string> names = m_calibrationWS->getColumnNames(); - for (auto it = names.begin(); it != names.end(); ++it) { - if (name == (*it)) + for (const auto &name : names) { + if (name == ColumnName) return true; } diff --git a/Framework/DataHandling/src/SaveFullprofResolution.cpp b/Framework/DataHandling/src/SaveFullprofResolution.cpp index 4a60a841dae7dd2345de8865f3ea01a45ac5cccf..9cb081f6ea06681d2fd0950cc6f2e0c7126289bf 100644 --- a/Framework/DataHandling/src/SaveFullprofResolution.cpp +++ b/Framework/DataHandling/src/SaveFullprofResolution.cpp @@ -166,8 +166,8 @@ void SaveFullprofResolution::parseTableWorkspace() { size_t numcols = colnames.size(); stringstream dbmsgss("Input table's column names: "); - for (size_t i = 0; i < colnames.size(); ++i) { - dbmsgss << setw(20) << colnames[i]; + for (auto &colname : colnames) { + dbmsgss << setw(20) << colname; } g_log.debug(dbmsgss.str()); diff --git a/Framework/DataHandling/src/SaveGSASInstrumentFile.cpp b/Framework/DataHandling/src/SaveGSASInstrumentFile.cpp index 5b035fac1337cd8b192d6b4918afb8d6608b6038..bd9668632b2691af0fa6e0de746e4b53f0b9ad04 100644 --- a/Framework/DataHandling/src/SaveGSASInstrumentFile.cpp +++ b/Framework/DataHandling/src/SaveGSASInstrumentFile.cpp @@ -231,9 +231,9 @@ ChopperConfiguration::parseStringDbl(const string &instring) const { boost::split(strs, instring, boost::is_any_of(", ")); vector<double> vecdouble; - for (size_t i = 0; i < strs.size(); i++) { - if (strs[i].size() > 0) { - double item = atof(strs[i].c_str()); + for (auto &str : strs) { + if (str.size() > 0) { + double item = atof(str.c_str()); vecdouble.push_back(item); // cout << "[C] |" << strs[i] << "|" << item << "\n"; } @@ -254,9 +254,9 @@ ChopperConfiguration::parseStringUnsignedInt(const string &instring) const { boost::split(strs, instring, boost::is_any_of(", ")); vector<unsigned int> vecinteger; - for (size_t i = 0; i < strs.size(); i++) { - if (strs[i].size() > 0) { - int item = atoi(strs[i].c_str()); + for (auto &str : strs) { + if (str.size() > 0) { + int item = atoi(str.c_str()); if (item < 0) { throw runtime_error( "Found negative number in a string for unsigned integers."); @@ -360,9 +360,8 @@ void SaveGSASInstrumentFile::exec() { // Deal with a default if (m_vecBankID2File.empty()) { // Default is to export all banks - for (auto miter = bankprofileparammap.begin(); - miter != bankprofileparammap.end(); ++miter) { - unsigned int bankid = miter->first; + for (auto &miter : bankprofileparammap) { + unsigned int bankid = miter.first; m_vecBankID2File.push_back(bankid); } sort(m_vecBankID2File.begin(), m_vecBankID2File.end()); @@ -547,8 +546,8 @@ void SaveGSASInstrumentFile::parseProfileTableWorkspace( stringstream db1ss; db1ss << "[DBx912] Number of banks in profile table = " << vecbankindex.size() << " containing bank "; - for (size_t i = 0; i < vecbankindex.size(); ++i) - db1ss << vecbankindex[i] << ", "; + for (auto bankIndex : vecbankindex) + db1ss << bankIndex << ", "; g_log.information(db1ss.str()); // Construct output @@ -699,8 +698,7 @@ void SaveGSASInstrumentFile::convertToGSAS( throw runtime_error("Not set up yet!"); // Set up min-dsp, max-tof - for (size_t i = 0; i < outputbankids.size(); ++i) { - unsigned int bankid = outputbankids[i]; + for (auto bankid : outputbankids) { if (!m_configuration->hasBank(bankid)) throw runtime_error( "Chopper configuration does not have some certain bank."); @@ -719,8 +717,7 @@ void SaveGSASInstrumentFile::convertToGSAS( // Convert and write vector<unsigned int> banks = outputbankids; sort(banks.begin(), banks.end()); - for (size_t ib = 0; ib < banks.size(); ++ib) { - unsigned int bankid = banks[ib]; + for (auto bankid : banks) { if (m_configuration->hasBank(bankid)) { buildGSASTabulatedProfile(bankprofilemap, bankid); writePRMSingleBank(bankprofilemap, bankid, gsasinstrfilename); @@ -1072,9 +1069,8 @@ double SaveGSASInstrumentFile::getProfileParameterValue( stringstream errss; errss << "Profile map does not contain parameter " << paramname << ". Available parameters are "; - for (auto piter = profilemap.cbegin(); piter != profilemap.cend(); - ++piter) { - errss << piter->first << ", "; + for (const auto &piter : profilemap) { + errss << piter.first << ", "; } g_log.error(errss.str()); throw runtime_error(errss.str()); diff --git a/Framework/DataHandling/src/SaveGSS.cpp b/Framework/DataHandling/src/SaveGSS.cpp index 28b217eb934ea68d12ffe76185ab47bb461655b4..b37d8b01d571ad34898d7ad0bd8d0254130b8612 100644 --- a/Framework/DataHandling/src/SaveGSS.cpp +++ b/Framework/DataHandling/src/SaveGSS.cpp @@ -472,10 +472,10 @@ void SaveGSS::writeHeaders(const std::string &format, std::stringstream &os, bool norm_by_monitor = false; const Mantid::API::AlgorithmHistories &algohist = inputWS->getHistory().getAlgorithmHistories(); - for (auto it = algohist.cbegin(); it != algohist.cend(); ++it) { - if ((*it)->name().compare("NormaliseByCurrent") == 0) + for (const auto &algo : algohist) { + if (algo->name().compare("NormaliseByCurrent") == 0) norm_by_current = true; - if ((*it)->name().compare("NormaliseToMonitor") == 0) + if (algo->name().compare("NormaliseToMonitor") == 0) norm_by_monitor = true; } os << "#"; diff --git a/Framework/DataHandling/src/SaveILLCosmosAscii.cpp b/Framework/DataHandling/src/SaveILLCosmosAscii.cpp index 11c2a9ba4b6f5226d2ed165525bb810e9f2e4f6c..e05dc58e5b9a0f7400aabf12274542ca2c380682 100644 --- a/Framework/DataHandling/src/SaveILLCosmosAscii.cpp +++ b/Framework/DataHandling/src/SaveILLCosmosAscii.cpp @@ -66,9 +66,9 @@ void SaveILLCosmosAscii::extraHeaders(std::ofstream &file) { const std::vector<std::string> logList = getProperty("LogList"); /// logs - for (auto log = logList.begin(); log != logList.end(); ++log) { - file << boost::lexical_cast<std::string>(*log) << ": " - << boost::lexical_cast<std::string>(samp.getLogData(*log)->value()) + for (const auto &log : logList) { + file << boost::lexical_cast<std::string>(log) << ": " + << boost::lexical_cast<std::string>(samp.getLogData(log)->value()) << std::endl; } diff --git a/Framework/DataHandling/src/SaveISISNexus.cpp b/Framework/DataHandling/src/SaveISISNexus.cpp index c81079fb6a48f47c647a0b2a89ea9be4089b6036..03a7dda463c9bdd08c3a21ec62dc61d489f4e8f5 100644 --- a/Framework/DataHandling/src/SaveISISNexus.cpp +++ b/Framework/DataHandling/src/SaveISISNexus.cpp @@ -322,8 +322,8 @@ int SaveISISNexus::saveStringVectorOpen(const char *name, } int buff_size = max_str_size; if (buff_size <= 0) - for (std::size_t i = 0; i < str_vec.size(); ++i) { - buff_size = std::max(buff_size, int(str_vec[i].size())); + for (const auto &str : str_vec) { + buff_size = std::max(buff_size, int(str.size())); } if (buff_size <= 0) buff_size = 1; @@ -969,8 +969,8 @@ void SaveISISNexus::selog() { // create a log for each of the found log files std::size_t nBase = base_name.size() + 1; - for (std::size_t i = 0; i < potentialLogFiles.size(); ++i) { - std::string logName = Poco::Path(potentialLogFiles[i]).getFileName(); + for (auto &potentialLogFile : potentialLogFiles) { + std::string logName = Poco::Path(potentialLogFile).getFileName(); logName.erase(0, nBase); logName.erase(logName.size() - 4); if (logName.size() > 3) { @@ -980,9 +980,9 @@ void SaveISISNexus::selog() { continue; } - std::ifstream fil(potentialLogFiles[i].c_str()); + std::ifstream fil(potentialLogFile.c_str()); if (!fil) { - g_log.warning("Cannot open log file " + potentialLogFiles[i]); + g_log.warning("Cannot open log file " + potentialLogFile); continue; } diff --git a/Framework/DataHandling/src/SaveIsawDetCal.cpp b/Framework/DataHandling/src/SaveIsawDetCal.cpp index 1403f5f74b4b2441f9fd5d98b5b5f95fa1540713..392eeef81cd1bec1bdd45e5a121979cf4e0b3e6b 100644 --- a/Framework/DataHandling/src/SaveIsawDetCal.cpp +++ b/Framework/DataHandling/src/SaveIsawDetCal.cpp @@ -91,8 +91,8 @@ void SaveIsawDetCal::exec() { std::vector<IComponent_const_sptr> comps; inst->getChildren(comps, true); - for (size_t i = 0; i < comps.size(); i++) { - std::string bankName = comps[i]->getName(); + for (auto &comp : comps) { + std::string bankName = comp->getName(); boost::trim(bankName); boost::erase_all(bankName, bankPart); int bank = 0; @@ -103,8 +103,7 @@ void SaveIsawDetCal::exec() { uniqueBanks.insert(bank); } } else { - for (size_t i = 0; i < bankNames.size(); i++) { - std::string bankName = bankNames[i]; + for (auto bankName : bankNames) { boost::trim(bankName); boost::erase_all(bankName, bankPart); int bank = 0; diff --git a/Framework/DataHandling/src/SaveNXTomo.cpp b/Framework/DataHandling/src/SaveNXTomo.cpp index 02e49ef74d7d4de1bd83849c3b4cc206e0f33e3e..8fb5d241c9c73c06cb484f0c37afb8b275633725 100644 --- a/Framework/DataHandling/src/SaveNXTomo.cpp +++ b/Framework/DataHandling/src/SaveNXTomo.cpp @@ -110,8 +110,8 @@ void SaveNXTomo::processAll() { m_includeError = getProperty("IncludeError"); m_overwriteFile = getProperty("OverwriteFile"); - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - const std::string workspaceID = (*it)->id(); + for (auto &workspace : m_workspaces) { + const std::string workspaceID = workspace->id(); if ((workspaceID.find("Workspace2D") == std::string::npos) && (workspaceID.find("RebinnedOutput") == std::string::npos)) @@ -119,7 +119,7 @@ void SaveNXTomo::processAll() { "SaveNXTomo passed invalid workspaces. Must be Workspace2D"); // Do the full check for common binning - if (!WorkspaceHelpers::commonBoundaries(*it)) { + if (!WorkspaceHelpers::commonBoundaries(workspace)) { g_log.error("The input workspace must have common bins"); throw std::invalid_argument("The input workspace must have common bins"); } @@ -156,8 +156,8 @@ void SaveNXTomo::processAll() { // Create a progress reporting object Progress progress(this, 0, 1, m_workspaces.size()); - for (auto it = m_workspaces.begin(); it != m_workspaces.end(); ++it) { - writeSingleWorkspace(*it, nxFile); + for (auto &workspace : m_workspaces) { + writeSingleWorkspace(workspace, nxFile); progress.report(); } @@ -405,8 +405,7 @@ void SaveNXTomo::writeLogValues(const DataObjects::Workspace2D_sptr workspace, // value std::vector<Property *> logVals = workspace->run().getLogData(); - for (auto it = logVals.begin(); it != logVals.end(); ++it) { - auto prop = *it; + for (auto prop : logVals) { if (prop->name() != "ImageKey" && prop->name() != "Rotation" && prop->name() != "Intensity" && prop->name() != "Axis1" && prop->name() != "Axis2") { diff --git a/Framework/DataHandling/src/SaveNexusProcessed.cpp b/Framework/DataHandling/src/SaveNexusProcessed.cpp index b1cce74d4f66a368b3c58901ee6d4a0f3c64c1eb..316432acd8decccd8571a5f4aed78362fe965389 100644 --- a/Framework/DataHandling/src/SaveNexusProcessed.cpp +++ b/Framework/DataHandling/src/SaveNexusProcessed.cpp @@ -113,8 +113,7 @@ void SaveNexusProcessed::getSpectrumList( for (int i = spec_min; i <= spec_max; i++) spec.push_back(i); if (list) { - for (size_t i = 0; i < spec_list.size(); i++) { - int s = spec_list[i]; + for (auto s : spec_list) { if (s < 0) continue; if (s < spec_min || s > spec_max) @@ -124,8 +123,7 @@ void SaveNexusProcessed::getSpectrumList( } else if (list) { spec_max = 0; spec_min = numberOfHist - 1; - for (size_t i = 0; i < spec_list.size(); i++) { - int s = spec_list[i]; + for (auto s : spec_list) { if (s < 0) continue; spec.push_back(s); diff --git a/Framework/DataHandling/src/SaveOpenGenieAscii.cpp b/Framework/DataHandling/src/SaveOpenGenieAscii.cpp index 002073671c1f1ba5fc27003b0821d923acd4676d..4fc7fc51d417475bedfbcfc7d231bb38a9580369 100644 --- a/Framework/DataHandling/src/SaveOpenGenieAscii.cpp +++ b/Framework/DataHandling/src/SaveOpenGenieAscii.cpp @@ -103,8 +103,8 @@ void SaveOpenGenieAscii::exec() { // writes out x, y, e to vector std::string alpha; - for (int Num = 0; Num < 3; Num++) { - alpha = Alpha[Num]; + for (const auto &Num : Alpha) { + alpha = Num; axisToFile(alpha, singleSpc, fourspc, nBins, isHistogram); } @@ -236,10 +236,10 @@ std::string SaveOpenGenieAscii::getAxisValues(std::string alpha, int bin, void SaveOpenGenieAscii::getSampleLogs(std::string fourspc) { const std::vector<Property *> &logData = ws->run().getLogData(); - for (auto log = logData.begin(); log != logData.end(); ++log) { - std::string name = (*log)->name(); - std::string type = (*log)->type(); - std::string value = (*log)->value(); + for (auto log : logData) { + std::string name = log->name(); + std::string type = log->type(); + std::string value = log->value(); if (type.std::string::find("vector") && type.std::string::find("double") != std::string::npos) { diff --git a/Framework/DataHandling/src/SaveParameterFile.cpp b/Framework/DataHandling/src/SaveParameterFile.cpp index 000d89a2dc342804b138ff6f83344c0cdbf85f63..edb6c8c1ec697ef6a2f436db78ed1fae59fbe4de 100644 --- a/Framework/DataHandling/src/SaveParameterFile.cpp +++ b/Framework/DataHandling/src/SaveParameterFile.cpp @@ -90,14 +90,14 @@ void SaveParameterFile::exec() { Progress prog(this, 0.0, 0.3, params->size()); // Build a list of parameters to save; - for (auto paramsIt = params->begin(); paramsIt != params->end(); ++paramsIt) { + for (auto ¶msIt : *params) { if (prog.hasCancellationBeenRequested()) break; prog.report("Generating parameters"); - const ComponentID cID = (*paramsIt).first; - const std::string pName = (*paramsIt).second->name(); - const std::string pType = (*paramsIt).second->type(); - const std::string pValue = (*paramsIt).second->asString(); + const ComponentID cID = paramsIt.first; + const std::string pName = paramsIt.second->name(); + const std::string pType = paramsIt.second->type(); + const std::string pValue = paramsIt.second->asString(); if (pName == "x" || pName == "y" || pName == "z" || pName == "r-position" || pName == "t-position" || pName == "p-position" || pName == "rotx" || @@ -140,7 +140,7 @@ void SaveParameterFile::exec() { // With fitting parameters we do something special (i.e. silly) // We create an entire XML element to be inserted into the output, // instead of just giving a single fixed value - const FitParameter &fitParam = paramsIt->second->value<FitParameter>(); + const FitParameter &fitParam = paramsIt.second->value<FitParameter>(); const std::string fpName = fitParam.getFunction() + ":" + fitParam.getName(); std::stringstream fpValue; @@ -166,12 +166,12 @@ void SaveParameterFile::exec() { prog.resetNumSteps(static_cast<int64_t>(toSave.size()), 0.6, 1.0); // Iterate through all the parameters we want to save and build an XML // document out of them. - for (auto compIt = toSave.begin(); compIt != toSave.end(); ++compIt) { + for (auto &compIt : toSave) { if (prog.hasCancellationBeenRequested()) break; prog.report("Saving parameters"); // Component data - const ComponentID cID = compIt->first; + const ComponentID cID = compIt.first; const std::string cFullName = cID->getFullName(); const IDetector *cDet = dynamic_cast<IDetector *>(cID); const detid_t cDetID = (cDet) ? cDet->getID() : 0; @@ -180,7 +180,7 @@ void SaveParameterFile::exec() { if (cDetID != 0) file << " id=\"" << cDetID << "\""; file << " name=\"" << cFullName << "\">\n"; - for (auto paramIt = compIt->second.begin(); paramIt != compIt->second.end(); + for (auto paramIt = compIt.second.begin(); paramIt != compIt.second.end(); ++paramIt) { const std::string pName = paramIt->get<0>(); const std::string pType = paramIt->get<1>(); diff --git a/Framework/DataHandling/src/SaveRKH.cpp b/Framework/DataHandling/src/SaveRKH.cpp index cb234936eccfd23ac2f8cf7688325d4d678f7dc2..c111193b3bbd31901025a6ea695b0a8c34fb9de6 100644 --- a/Framework/DataHandling/src/SaveRKH.cpp +++ b/Framework/DataHandling/src/SaveRKH.cpp @@ -46,10 +46,7 @@ void SaveRKH::exec() { // Retrieve the input workspace m_workspace = getProperty("InputWorkspace"); - m_2d = - (m_workspace->getNumberHistograms() > 1 && m_workspace->blocksize() > 1) - ? true - : false; + m_2d = m_workspace->getNumberHistograms() > 1 && m_workspace->blocksize() > 1; // If a 2D workspace, check that it has two numeric axes - bail out if not if (m_2d && !(m_workspace->getAxis(1)->isNumeric())) { @@ -134,7 +131,7 @@ void SaveRKH::writeHeader() { void SaveRKH::write1D() { const size_t noDataPoints = m_workspace->size(); const size_t nhist = m_workspace->getNumberHistograms(); - const bool horizontal = (nhist == 1) ? true : false; + const bool horizontal = nhist == 1; if (horizontal) { g_log.notice() << "Values in first column are the X values\n"; if (m_workspace->getAxis(0)->unit()) diff --git a/Framework/DataHandling/src/SaveReflCustomAscii.cpp b/Framework/DataHandling/src/SaveReflCustomAscii.cpp index e907662a21e855e54d91097c565638614c1f50e2..0f93aa57d7645a5eca97f297615c3c6e3bca6119 100644 --- a/Framework/DataHandling/src/SaveReflCustomAscii.cpp +++ b/Framework/DataHandling/src/SaveReflCustomAscii.cpp @@ -50,9 +50,9 @@ void SaveReflCustomAscii::extraHeaders(std::ofstream &file) { const std::vector<std::string> logList = getProperty("LogList"); /// logs - for (auto log = logList.begin(); log != logList.end(); ++log) { - file << boost::lexical_cast<std::string>(*log) << ": " - << boost::lexical_cast<std::string>(samp.getLogData(*log)->value()) + for (const auto &log : logList) { + file << boost::lexical_cast<std::string>(log) << ": " + << boost::lexical_cast<std::string>(samp.getLogData(log)->value()) << std::endl; } } diff --git a/Framework/DataHandling/src/SaveReflTBL.cpp b/Framework/DataHandling/src/SaveReflTBL.cpp index 080823d4ea0ed24a37eae2ffc0c2245dfa13bee8..f8438af7d21eeac1d050c3abb8abcd3ed6108d22 100644 --- a/Framework/DataHandling/src/SaveReflTBL.cpp +++ b/Framework/DataHandling/src/SaveReflTBL.cpp @@ -73,9 +73,8 @@ void SaveReflTBL::exec() { throw Exception::FileError("Unable to create file: ", filename); } - for (auto iterator = m_stichgroups.begin(); iterator != m_stichgroups.end(); - ++iterator) { - std::vector<size_t> &rowNos = iterator->second; + for (auto &stichgroup : m_stichgroups) { + std::vector<size_t> &rowNos = stichgroup.second; size_t i = 0; for (; i < rowNos.size(); ++i) { // for each row in the group print the first 5 columns to file @@ -101,9 +100,8 @@ void SaveReflTBL::exec() { // now do the same for the ungrouped - for (auto iterator = m_nogroup.begin(); iterator != m_nogroup.end(); - ++iterator) { - TableRow row = ws->getRow(*iterator); + for (auto &iterator : m_nogroup) { + TableRow row = ws->getRow(iterator); for (int j = 0; j < 5; ++j) { writeVal(row.cell<std::string>(j), file); } diff --git a/Framework/DataHandling/src/SaveReflThreeColumnAscii.cpp b/Framework/DataHandling/src/SaveReflThreeColumnAscii.cpp index 4c1fa580d52f98a1025cc40a0837e2d1c179075e..de935f0ca38ce13f9d8b5cbfd6ddc22d9b570f52 100644 --- a/Framework/DataHandling/src/SaveReflThreeColumnAscii.cpp +++ b/Framework/DataHandling/src/SaveReflThreeColumnAscii.cpp @@ -34,9 +34,9 @@ void SaveReflThreeColumnAscii::extraHeaders(std::ofstream &file) { const std::vector<std::string> logList = getProperty("LogList"); /// logs - for (auto log = logList.begin(); log != logList.end(); ++log) { - file << boost::lexical_cast<std::string>(*log) << ": " - << boost::lexical_cast<std::string>(samp.getLogData(*log)->value()) + for (const auto &log : logList) { + file << boost::lexical_cast<std::string>(log) << ": " + << boost::lexical_cast<std::string>(samp.getLogData(log)->value()) << std::endl; } } diff --git a/Framework/DataHandling/src/SaveSavuTomoConfig.cpp b/Framework/DataHandling/src/SaveSavuTomoConfig.cpp index a329ed0bf503cd4ef12670fde12299cb5837d583..1e21343377b16cda4c10bbab789334723cca2964 100644 --- a/Framework/DataHandling/src/SaveSavuTomoConfig.cpp +++ b/Framework/DataHandling/src/SaveSavuTomoConfig.cpp @@ -92,15 +92,16 @@ bool SaveSavuTomoConfig::tableLooksGenuine(const ITableWorkspace_sptr &tws) { std::vector<ITableWorkspace_sptr> SaveSavuTomoConfig::checkTables(const std::vector<std::string> &workspaces) { std::vector<ITableWorkspace_sptr> wss; - for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { - if (AnalysisDataService::Instance().doesExist(*it)) { + for (const auto &workspace : workspaces) { + if (AnalysisDataService::Instance().doesExist(workspace)) { ITableWorkspace_sptr table = - AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(*it); + AnalysisDataService::Instance().retrieveWS<ITableWorkspace>( + workspace); // Check it's valid. Very permissive check for the time being if (table && tableLooksGenuine(table)) { wss.push_back(table); } else { - throw std::runtime_error("Invalid workspace provided: " + *it + + throw std::runtime_error("Invalid workspace provided: " + workspace + ". This algorithm requires a table " "workspace with correct savu plugin/ " "pipeline process information."); @@ -109,7 +110,7 @@ SaveSavuTomoConfig::checkTables(const std::vector<std::string> &workspaces) { throw std::runtime_error( "One or more specified table workspaces don't exist. I could not " "find this one: " + - *it); + workspace); } } return wss; @@ -164,11 +165,10 @@ void SaveSavuTomoConfig::saveFile( // Iterate through all plugin entries (number sub groups 0....n-1) size_t procCount = 0; - for (size_t i = 0; i < wss.size(); ++i) { + for (auto w : wss) { // Concatenate table contents, putting pipeline processing steps in the same // sequence // as they come in the seq of table workspaces - ITableWorkspace_sptr w = wss[i]; for (size_t ti = 0; ti < w->rowCount(); ++ti) { // Column info order is [ID / Params {as json string} / name {description} // / diff --git a/Framework/DataHandling/src/SetScalingPSD.cpp b/Framework/DataHandling/src/SetScalingPSD.cpp index bc5384007eb233fe5d6e3b0f1b3225791389394a..c1bbd1d2e7c38f0bb15a700a05cead1f867cccdb 100644 --- a/Framework/DataHandling/src/SetScalingPSD.cpp +++ b/Framework/DataHandling/src/SetScalingPSD.cpp @@ -265,8 +265,8 @@ void SetScalingPSD::movePos(API::MatrixWorkspace_sptr &WS, // double prog=0.5; Progress prog(this, 0.5, 1.0, static_cast<int>(m_vectDet.size())); // loop over detector (IComps) - for (size_t id = 0; id < m_vectDet.size(); id++) { - comp = m_vectDet[id]; + for (auto &id : m_vectDet) { + comp = id; boost::shared_ptr<const IDetector> det = boost::dynamic_pointer_cast<const IDetector>(comp); int idet = 0; diff --git a/Framework/DataObjects/src/BoxControllerNeXusIO.cpp b/Framework/DataObjects/src/BoxControllerNeXusIO.cpp index a922c6b631fefa816706154fad99c074da65b6c7..109323b13841f85f632b23c67c7ac252b3c8db16 100644 --- a/Framework/DataObjects/src/BoxControllerNeXusIO.cpp +++ b/Framework/DataObjects/src/BoxControllerNeXusIO.cpp @@ -30,8 +30,8 @@ BoxControllerNeXusIO::BoxControllerNeXusIO(API::BoxController *const bc) m_ReadConversion(noConversion) { m_BlockSize[1] = 4 + m_bc->getNDims(); - for (size_t i = 0; i < 2; i++) { - m_EventsTypeHeaders.push_back(EventHeaders[i]); + for (auto &EventHeader : EventHeaders) { + m_EventsTypeHeaders.push_back(EventHeader); } m_EventsTypesSupported.resize(2); diff --git a/Framework/DataObjects/src/EventList.cpp b/Framework/DataObjects/src/EventList.cpp index da0f6969ab56361ed37cf4d59f7bf45281edce75..bb73766a6214a4b81db80ca3a115dfbe30ccbb5b 100644 --- a/Framework/DataObjects/src/EventList.cpp +++ b/Framework/DataObjects/src/EventList.cpp @@ -353,8 +353,8 @@ EventList &EventList::operator+=(const std::vector<TofEvent> &more_events) { // and append to the list this->weightedEventsNoTime.reserve(this->weightedEventsNoTime.size() + more_events.size()); - for (auto it = more_events.begin(); it != more_events.end(); ++it) - this->weightedEventsNoTime.emplace_back(*it); + for (const auto &more_event : more_events) + this->weightedEventsNoTime.emplace_back(more_event); break; } @@ -2560,8 +2560,8 @@ void EventList::convertTofHelper(std::vector<T> &events, void EventList::convertTof(const double factor, const double offset) { // fix the histogram parameter MantidVec &x = this->refX.access(); - for (auto iter = x.begin(); iter != x.end(); ++iter) - *iter = (*iter) * factor + offset; + for (double &iter : x) + iter = iter * factor + offset; // this->refX.access() = x; if ((factor < 0.) && (this->getSortType() == TOF_SORT)) diff --git a/Framework/DataObjects/src/EventWorkspace.cpp b/Framework/DataObjects/src/EventWorkspace.cpp index 9a8d68f4f2e030ae6986d9fce4379f9320f4ffda..0ea219d458a0ce5ecf8be6ce85847d6d1dfa4ecc 100644 --- a/Framework/DataObjects/src/EventWorkspace.cpp +++ b/Framework/DataObjects/src/EventWorkspace.cpp @@ -377,11 +377,10 @@ void EventWorkspace::getEventXMinMax(double &xmin, double &xmax) const { /// The total number of events across all of the spectra. /// @returns The total number of events size_t EventWorkspace::getNumberEvents() const { - size_t total = 0; - for (auto it = this->data.begin(); it != this->data.end(); ++it) { - total += (*it)->getNumberEvents(); - } - return total; + return std::accumulate(data.begin(), data.end(), size_t{0}, + [](size_t total, EventList *list) { + return total + list->getNumberEvents(); + }); } //----------------------------------------------------------------------------- @@ -391,8 +390,8 @@ size_t EventWorkspace::getNumberEvents() const { */ Mantid::API::EventType EventWorkspace::getEventType() const { Mantid::API::EventType out = Mantid::API::TOF; - for (auto it = this->data.begin(); it != this->data.end(); ++it) { - Mantid::API::EventType thisType = (*it)->getEventType(); + for (auto list : this->data) { + Mantid::API::EventType thisType = list->getEventType(); if (static_cast<int>(out) < static_cast<int>(thisType)) { out = thisType; // This is the most-specialized it can get. @@ -448,14 +447,13 @@ void EventWorkspace::clearData() { //----------------------------------------------------------------------------- /// Returns the amount of memory used in bytes size_t EventWorkspace::getMemorySize() const { - size_t total = 0; - // TODO: Add the MRU buffer // Add the memory from all the event lists - for (auto it = this->data.begin(); it != this->data.end(); ++it) { - total += (*it)->getMemorySize(); - } + size_t total = std::accumulate(data.begin(), data.end(), size_t{0}, + [](size_t total, EventList *list) { + return total + list->getMemorySize(); + }); total += run().getMemorySize(); diff --git a/Framework/DataObjects/src/EventWorkspaceMRU.cpp b/Framework/DataObjects/src/EventWorkspaceMRU.cpp index 76ca4af7db542c57767e872e11fd9a7760dd6562..d592e902e31b20389ded74dcb8fc878fc4e12984 100644 --- a/Framework/DataObjects/src/EventWorkspaceMRU.cpp +++ b/Framework/DataObjects/src/EventWorkspaceMRU.cpp @@ -16,22 +16,22 @@ EventWorkspaceMRU::EventWorkspaceMRU() {} */ EventWorkspaceMRU::~EventWorkspaceMRU() { // Make sure you free up the memory in the MRUs - for (size_t i = 0; i < m_bufferedDataY.size(); i++) { - if (m_bufferedDataY[i]) { - m_bufferedDataY[i]->clear(); - delete m_bufferedDataY[i]; + for (auto &data : m_bufferedDataY) { + if (data) { + data->clear(); + delete data; } } - for (size_t i = 0; i < m_bufferedDataE.size(); i++) { - if (m_bufferedDataE[i]) { - m_bufferedDataE[i]->clear(); - delete m_bufferedDataE[i]; + for (auto &data : m_bufferedDataE) { + if (data) { + data->clear(); + delete data; } } - for (size_t i = 0; i < m_markersToDelete.size(); i++) { - delete m_markersToDelete[i]; + for (auto &marker : m_markersToDelete) { + delete marker; } } @@ -44,10 +44,9 @@ void EventWorkspaceMRU::ensureEnoughBuffersE(size_t thread_num) const { Mutex::ScopedLock _lock(m_changeMruListsMutexE); if (m_bufferedDataE.size() <= thread_num) { m_bufferedDataE.resize(thread_num + 1, NULL); - for (size_t i = 0; i < m_bufferedDataE.size(); i++) { - if (!m_bufferedDataE[i]) - m_bufferedDataE[i] = - new mru_list(50); // Create a MRU list with this many entries. + for (auto &data : m_bufferedDataE) { + if (!data) + data = new mru_list(50); // Create a MRU list with this many entries. } } } @@ -60,10 +59,9 @@ void EventWorkspaceMRU::ensureEnoughBuffersY(size_t thread_num) const { Mutex::ScopedLock _lock(m_changeMruListsMutexY); if (m_bufferedDataY.size() <= thread_num) { m_bufferedDataY.resize(thread_num + 1, NULL); - for (size_t i = 0; i < m_bufferedDataY.size(); i++) { - if (!m_bufferedDataY[i]) - m_bufferedDataY[i] = - new mru_list(50); // Create a MRU list with this many entries. + for (auto &data : m_bufferedDataY) { + if (!data) + data = new mru_list(50); // Create a MRU list with this many entries. } } } @@ -74,20 +72,20 @@ void EventWorkspaceMRU::clear() { Mutex::ScopedLock _lock(this->m_toDeleteMutex); // FIXME: don't clear the locked ones! - for (size_t i = 0; i < m_markersToDelete.size(); i++) - if (!m_markersToDelete[i]->m_locked) - delete m_markersToDelete[i]; + for (auto &marker : m_markersToDelete) + if (!marker->m_locked) + delete marker; m_markersToDelete.clear(); // Make sure you free up the memory in the MRUs - for (size_t i = 0; i < m_bufferedDataY.size(); i++) - if (m_bufferedDataY[i]) { - m_bufferedDataY[i]->clear(); + for (auto &data : m_bufferedDataY) + if (data) { + data->clear(); }; - for (size_t i = 0; i < m_bufferedDataE.size(); i++) - if (m_bufferedDataE[i]) { - m_bufferedDataE[i]->clear(); + for (auto &data : m_bufferedDataE) + if (data) { + data->clear(); }; } @@ -162,13 +160,13 @@ void EventWorkspaceMRU::insertE(size_t thread_num, MantidVecWithMarker *data) { */ void EventWorkspaceMRU::deleteIndex(size_t index) { Mutex::ScopedLock _lock1(m_changeMruListsMutexE); - for (size_t i = 0; i < m_bufferedDataE.size(); i++) - if (m_bufferedDataE[i]) - m_bufferedDataE[i]->deleteIndex(index); + for (auto &data : m_bufferedDataE) + if (data) + data->deleteIndex(index); Mutex::ScopedLock _lock2(m_changeMruListsMutexY); - for (size_t i = 0; i < m_bufferedDataY.size(); i++) - if (m_bufferedDataY[i]) - m_bufferedDataY[i]->deleteIndex(index); + for (auto &data : m_bufferedDataY) + if (data) + data->deleteIndex(index); } } // namespace Mantid diff --git a/Framework/DataObjects/src/GroupingWorkspace.cpp b/Framework/DataObjects/src/GroupingWorkspace.cpp index 6ddd541c0a3f8878506ac2d3fba327eb92915635..d4a44681a06820954f0f8c24351d1f293dc60e3a 100644 --- a/Framework/DataObjects/src/GroupingWorkspace.cpp +++ b/Framework/DataObjects/src/GroupingWorkspace.cpp @@ -59,8 +59,8 @@ void GroupingWorkspace::makeDetectorIDToGroupMap( if (group == 0) group = -1; std::set<detid_t> detIDs = this->getDetectorIDs(wi); - for (auto detID = detIDs.begin(); detID != detIDs.end(); ++detID) { - detIDToGroup[*detID] = group; + for (auto detID : detIDs) { + detIDToGroup[detID] = group; if (group > ngroups) ngroups = group; } @@ -85,13 +85,13 @@ void GroupingWorkspace::makeDetectorIDToGroupVector( if (group == 0) group = -1; std::set<detid_t> detIDs = this->getDetectorIDs(wi); - for (auto detID = detIDs.begin(); detID != detIDs.end(); ++detID) { - if ((*detID) < + for (auto detID : detIDs) { + if (detID < 0) // if you need negative detector ids, use the other function continue; - if (detIDToGroup.size() < static_cast<size_t>((*detID) + 1)) - detIDToGroup.resize((*detID) + 1); - detIDToGroup[*detID] = group; + if (detIDToGroup.size() < static_cast<size_t>(detID + 1)) + detIDToGroup.resize(detID + 1); + detIDToGroup[detID] = group; if (group > ngroups) ngroups = group; } diff --git a/Framework/DataObjects/src/MDBoxFlatTree.cpp b/Framework/DataObjects/src/MDBoxFlatTree.cpp index 52532916f57cb952165408b826583f74e64991f0..30f6fcf81737a78697bae3fb8c2b073bb5b2fbb9 100644 --- a/Framework/DataObjects/src/MDBoxFlatTree.cpp +++ b/Framework/DataObjects/src/MDBoxFlatTree.cpp @@ -138,8 +138,7 @@ void MDBoxFlatTree::setBoxesFilePositions(bool setFileBacked) { // Kernel::ISaveable::sortObjByFilePos(m_Boxes); // calculate the box positions in the resulting file and save it on place uint64_t eventsStart = 0; - for (size_t i = 0; i < m_Boxes.size(); i++) { - API::IMDNode *mdBox = m_Boxes[i]; + for (auto mdBox : m_Boxes) { size_t ID = mdBox->getID(); // avoid grid boxes; @@ -403,8 +402,8 @@ void MDBoxFlatTree::loadExperimentInfos( std::map<std::string, std::string> entries; file->getEntries(entries); std::list<uint16_t> ExperimentBlockNum; - for (auto it = entries.begin(); it != entries.end(); ++it) { - std::string name = it->first; + for (auto &entry : entries) { + const std::string &name = entry.first; if (boost::starts_with(name, "experiment")) { try { uint16_t num = diff --git a/Framework/DataObjects/src/MDHistoWorkspace.cpp b/Framework/DataObjects/src/MDHistoWorkspace.cpp index 4a6c1411c052f66eb9c4fbc6dfd27f144358f0fc..64f1b678063fd0f82d9ecb15aa064e3bdb9ad28c 100644 --- a/Framework/DataObjects/src/MDHistoWorkspace.cpp +++ b/Framework/DataObjects/src/MDHistoWorkspace.cpp @@ -132,8 +132,8 @@ MDHistoWorkspace::~MDHistoWorkspace() { void MDHistoWorkspace::init( std::vector<Mantid::Geometry::MDHistoDimension_sptr> &dimensions) { std::vector<IMDDimension_sptr> dim2; - for (size_t i = 0; i < dimensions.size(); i++) - dim2.push_back(boost::dynamic_pointer_cast<IMDDimension>(dimensions[i])); + for (auto &dimension : dimensions) + dim2.push_back(boost::dynamic_pointer_cast<IMDDimension>(dimension)); this->init(dim2); m_nEventsContributed = 0; } diff --git a/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp b/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp index 9f8016d0feb9a7e1296f88983287b1e64dd9e2a1..3eebeb6656247459b2077644bfed4ffa10beed77 100644 --- a/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp +++ b/Framework/DataObjects/src/MDHistoWorkspaceIterator.cpp @@ -526,12 +526,12 @@ MDHistoWorkspaceIterator::findNeighbourIndexesFaceTouching() const { std::vector<size_t> neighbourIndexes; // Accumulate neighbour indexes. std::vector<int> widths( m_nd, 3); // Face touching width is always 3 in each dimension - for (size_t i = 0; i < m_permutationsFaceTouching.size(); ++i) { - if (m_permutationsFaceTouching[i] == 0) { + for (auto permutation : m_permutationsFaceTouching) { + if (permutation == 0) { continue; } - size_t neighbour_index = m_pos + m_permutationsFaceTouching[i]; + size_t neighbour_index = m_pos + permutation; if (neighbour_index < m_ws->getNPoints() && Utils::isNeighbourOfSubject(m_nd, neighbour_index, m_index, m_indexMaker, m_indexMax, widths)) { @@ -655,12 +655,12 @@ std::vector<size_t> MDHistoWorkspaceIterator::findNeighbourIndexesByWidth( // Accumulate neighbour indexes. std::vector<size_t> neighbourIndexes(permutationsVertexTouching.size()); size_t nextFree = 0; - for (size_t i = 0; i < permutationsVertexTouching.size(); ++i) { - if (permutationsVertexTouching[i] == 0) { + for (auto permutation : permutationsVertexTouching) { + if (permutation == 0) { continue; } - size_t neighbour_index = m_pos + permutationsVertexTouching[i]; + size_t neighbour_index = m_pos + permutation; if (neighbour_index < m_ws->getNPoints() && Utils::isNeighbourOfSubject(m_nd, neighbour_index, m_index, m_indexMaker, m_indexMax, widths)) { diff --git a/Framework/DataObjects/src/MaskWorkspace.cpp b/Framework/DataObjects/src/MaskWorkspace.cpp index b6a552d78f265f99c58cf388872a0f4ff6a75ec5..7c722227bdbd944d4914a5744fdeacbd4d50969f 100644 --- a/Framework/DataObjects/src/MaskWorkspace.cpp +++ b/Framework/DataObjects/src/MaskWorkspace.cpp @@ -197,8 +197,8 @@ bool MaskWorkspace::isMasked(const std::set<detid_t> &detectorIDs) const { } bool masked(true); - for (auto it = detectorIDs.cbegin(); it != detectorIDs.cend(); ++it) { - if (!this->isMasked(*it)) { + for (auto detectorID : detectorIDs) { + if (!this->isMasked(detectorID)) { masked = false; break; // allows space for a debug print statement } @@ -234,8 +234,8 @@ void MaskWorkspace::setMasked(const detid_t detectorID, const bool mask) { */ void MaskWorkspace::setMasked(const std::set<detid_t> &detectorIDs, const bool mask) { - for (auto detId = detectorIDs.begin(); detId != detectorIDs.end(); ++detId) { - this->setMasked(*detId, mask); + for (auto detectorID : detectorIDs) { + this->setMasked(detectorID, mask); } } @@ -281,10 +281,7 @@ bool MaskWorkspace::hasInstrument() const { bool hasinst; Geometry::Instrument_const_sptr inst = this->getInstrument(); if (inst) { - if (inst->getNumberDetectors() > 0) - hasinst = true; - else - hasinst = false; + hasinst = inst->getNumberDetectors() > 0; } else hasinst = false; diff --git a/Framework/DataObjects/src/PeakShapeEllipsoid.cpp b/Framework/DataObjects/src/PeakShapeEllipsoid.cpp index b5907b19854cc213952d47c15c6c2cf346b10ae6..0949be271bf566ece6c60035351760683b0b07de 100644 --- a/Framework/DataObjects/src/PeakShapeEllipsoid.cpp +++ b/Framework/DataObjects/src/PeakShapeEllipsoid.cpp @@ -82,8 +82,8 @@ std::vector<Kernel::V3D> PeakShapeEllipsoid::getDirectionInSpecificFrame( "compatible with the direction vector"); } - for (auto it = m_directions.cbegin(); it != m_directions.cend(); ++it) { - directionsInFrame.push_back(invertedGoniometerMatrix * (*it)); + for (const auto &direction : m_directions) { + directionsInFrame.push_back(invertedGoniometerMatrix * direction); } return directionsInFrame; diff --git a/Framework/DataObjects/src/PeaksWorkspace.cpp b/Framework/DataObjects/src/PeaksWorkspace.cpp index 0cd4bd5a1890e3851784a6b9e9a28019f6a596a9..93c1ff6966b2caaf74470cc93613f0be4dc36ba7 100644 --- a/Framework/DataObjects/src/PeaksWorkspace.cpp +++ b/Framework/DataObjects/src/PeaksWorkspace.cpp @@ -77,9 +77,9 @@ public: /** Compare two peaks using the stored criteria */ inline bool operator()(const Peak &a, const Peak &b) { - for (size_t i = 0; i < criteria.size(); i++) { - std::string &col = criteria[i].first; - bool ascending = criteria[i].second; + for (auto &name : criteria) { + std::string &col = name.first; + bool ascending = name.second; bool lessThan = false; if (col == "BankName") { // If this criterion is equal, move on to the next one diff --git a/Framework/DataObjects/src/SpecialWorkspace2D.cpp b/Framework/DataObjects/src/SpecialWorkspace2D.cpp index 2978a692b96a0cc52e20808cc98bdc1a680875e4..1775098c4bcfe4f3ecf5dd5e4f744e8019dd8355 100644 --- a/Framework/DataObjects/src/SpecialWorkspace2D.cpp +++ b/Framework/DataObjects/src/SpecialWorkspace2D.cpp @@ -46,8 +46,8 @@ SpecialWorkspace2D::SpecialWorkspace2D(Geometry::Instrument_const_sptr inst, detID_to_WI.clear(); for (size_t wi = 0; wi < m_noVectors; wi++) { set<detid_t> dets = getSpectrum(wi)->getDetectorIDs(); - for (auto det = dets.begin(); det != dets.end(); ++det) { - detID_to_WI[*det] = wi; + for (auto det : dets) { + detID_to_WI[det] = wi; } } } @@ -66,8 +66,8 @@ SpecialWorkspace2D::SpecialWorkspace2D(API::MatrixWorkspace_const_sptr parent) { detID_to_WI.clear(); for (size_t wi = 0; wi < m_noVectors; wi++) { set<detid_t> dets = getSpectrum(wi)->getDetectorIDs(); - for (auto det = dets.begin(); det != dets.end(); ++det) { - detID_to_WI[*det] = wi; + for (auto det : dets) { + detID_to_WI[det] = wi; } } } @@ -186,8 +186,8 @@ void SpecialWorkspace2D::setValue(const detid_t detectorID, const double value, */ void SpecialWorkspace2D::setValue(const set<detid_t> &detectorIDs, const double value, const double error) { - for (auto detID = detectorIDs.begin(); detID != detectorIDs.end(); ++detID) { - this->setValue(*detID, value, error); + for (auto detectorID : detectorIDs) { + this->setValue(detectorID, value, error); } } diff --git a/Framework/DataObjects/src/TableWorkspace.cpp b/Framework/DataObjects/src/TableWorkspace.cpp index be907c8ddb670a0b650fa3163d300ce73325c373..87f188e6e6bedce06185a27d2cc729fabf0b91ba 100644 --- a/Framework/DataObjects/src/TableWorkspace.cpp +++ b/Framework/DataObjects/src/TableWorkspace.cpp @@ -48,8 +48,8 @@ TableWorkspace::~TableWorkspace() {} size_t TableWorkspace::getMemorySize() const { size_t data_size = 0; - for (auto c = m_columns.cbegin(); c != m_columns.cend(); ++c) { - data_size += (*c)->sizeOfData(); + for (const auto &column : m_columns) { + data_size += column->sizeOfData(); } data_size += m_LogManager->getMemorySize(); return data_size; @@ -98,8 +98,8 @@ API::Column_sptr TableWorkspace::addColumn(const std::string &type, void TableWorkspace::setRowCount(size_t count) { if (count == rowCount()) return; - for (auto ci = m_columns.begin(); ci != m_columns.end(); ci++) - resizeColumn(ci->get(), count); + for (auto &column : m_columns) + resizeColumn(column.get(), count); m_rowCount = count; } @@ -116,9 +116,9 @@ API::Column_sptr TableWorkspace::getColumn(const std::string &name) { /// Gets the shared pointer to a column. API::Column_const_sptr TableWorkspace::getColumn(const std::string &name) const { - for (auto c_it = m_columns.cbegin(); c_it != m_columns.cend(); ++c_it) { - if (c_it->get()->name() == name) { - return *c_it; + for (const auto &column : m_columns) { + if (column.get()->name() == name) { + return column; } } std::string str = "Column " + name + " does not exist.\n"; @@ -162,8 +162,8 @@ void TableWorkspace::removeColumn(const std::string &name) { size_t TableWorkspace::insertRow(size_t index) { if (index >= rowCount()) index = rowCount(); - for (auto ci = m_columns.begin(); ci != m_columns.end(); ci++) - insertInColumn(ci->get(), index); + for (auto &column : m_columns) + insertInColumn(column.get(), index); ++m_rowCount; return index; } @@ -175,16 +175,16 @@ void TableWorkspace::removeRow(size_t index) { g_log.error() << "Attempt to delete a non-existing row (" << index << ")\n"; return; } - for (auto ci = m_columns.begin(); ci != m_columns.end(); ci++) - removeFromColumn(ci->get(), index); + for (auto &column : m_columns) + removeFromColumn(column.get(), index); --m_rowCount; } std::vector<std::string> TableWorkspace::getColumnNames() const { std::vector<std::string> nameList; nameList.reserve(m_columns.size()); - for (auto ci = m_columns.begin(); ci != m_columns.end(); ci++) - nameList.push_back((*ci)->name()); + for (const auto &column : m_columns) + nameList.push_back(column->name()); return nameList; } @@ -256,10 +256,9 @@ void TableWorkspace::sort(std::vector<std::pair<std::string, bool>> &criteria) { // add more records to the back of the queue if (record.keyIndex < criteria.size() - 1) { size_t keyIndex = record.keyIndex + 1; - for (auto range = equalRanges.begin(); range != equalRanges.end(); - ++range) { + for (auto &equalRange : equalRanges) { sortRecords.push( - SortIterationRecord(keyIndex, range->first, range->second)); + SortIterationRecord(keyIndex, equalRange.first, equalRange.second)); } } diff --git a/Framework/Geometry/inc/MantidGeometry/Objects/Track.h b/Framework/Geometry/inc/MantidGeometry/Objects/Track.h index 427f550d7fdb043bab9339049c25662b28aa55bb..3cf5c30aef3b5b34ea9eac9a651228acf6d749f5 100644 --- a/Framework/Geometry/inc/MantidGeometry/Objects/Track.h +++ b/Framework/Geometry/inc/MantidGeometry/Objects/Track.h @@ -178,6 +178,10 @@ public: /// Returns the direction as a unit vector const Kernel::V3D &direction() const { return m_unitVector; } /// Returns an interator to the start of the set of links + LType::iterator begin() { return m_links.begin(); } + /// Returns an interator to one-past-the-end of the set of links + LType::iterator end() { return m_links.end(); } + /// Returns an interator to the start of the set of links LType::const_iterator cbegin() const { return m_links.cbegin(); } /// Returns an interator to one-past-the-end of the set of links LType::const_iterator cend() const { return m_links.cend(); } diff --git a/Framework/Geometry/src/Crystal/CompositeBraggScatterer.cpp b/Framework/Geometry/src/Crystal/CompositeBraggScatterer.cpp index f6bbfa6ee5028399b975232c326e54002185dc4f..bfa7c3c9b6a06903a0ab5640406cadf8435b37d5 100644 --- a/Framework/Geometry/src/Crystal/CompositeBraggScatterer.cpp +++ b/Framework/Geometry/src/Crystal/CompositeBraggScatterer.cpp @@ -59,8 +59,8 @@ void CompositeBraggScatterer::setScatterers( const std::vector<BraggScatterer_sptr> &scatterers) { removeAllScatterers(); - for (auto it = scatterers.begin(); it != scatterers.end(); ++it) { - addScattererImplementation(*it); + for (const auto &scatterer : scatterers) { + addScattererImplementation(scatterer); } redeclareProperties(); @@ -112,8 +112,8 @@ StructureFactor CompositeBraggScatterer::calculateStructureFactor( const Kernel::V3D &hkl) const { StructureFactor sum(0.0, 0.0); - for (auto it = m_scatterers.begin(); it != m_scatterers.end(); ++it) { - sum += (*it)->calculateStructureFactor(hkl); + for (const auto &scatterer : m_scatterers) { + sum += scatterer->calculateStructureFactor(hkl); } return sum; @@ -132,8 +132,8 @@ void CompositeBraggScatterer::propagateProperty( const std::string &propertyName) { std::string propertyValue = getPropertyValue(propertyName); - for (auto it = m_scatterers.begin(); it != m_scatterers.end(); ++it) { - propagatePropertyToScatterer(*it, propertyName, propertyValue); + for (auto &scatterer : m_scatterers) { + propagatePropertyToScatterer(scatterer, propertyName, propertyValue); } } @@ -169,35 +169,34 @@ void CompositeBraggScatterer::addScattererImplementation( void CompositeBraggScatterer::redeclareProperties() { std::map<std::string, size_t> propertyUseCount = getPropertyCountMap(); - for (auto it = m_scatterers.begin(); it != m_scatterers.end(); ++it) { + for (auto &scatterer : m_scatterers) { // Check if any of the declared properties is in this scatterer (and set // value if that's the case) - for (auto prop = propertyUseCount.begin(); prop != propertyUseCount.end(); - ++prop) { - if ((*it)->existsProperty(prop->first)) { - prop->second += 1; + for (auto &prop : propertyUseCount) { + if (scatterer->existsProperty(prop.first)) { + prop.second += 1; - propagatePropertyToScatterer(*it, prop->first, - getPropertyValue(prop->first)); + propagatePropertyToScatterer(scatterer, prop.first, + getPropertyValue(prop.first)); } } // Use the properties of this scatterer which have been marked as exposed to // composite std::vector<Property *> properties = - (*it)->getPropertiesInGroup(getPropagatingGroupName()); - for (auto prop = properties.begin(); prop != properties.end(); ++prop) { - std::string propertyName = (*prop)->name(); + scatterer->getPropertiesInGroup(getPropagatingGroupName()); + for (auto &property : properties) { + std::string propertyName = property->name(); if (!existsProperty(propertyName)) { - declareProperty((*prop)->clone()); + declareProperty(property->clone()); } } } // Remove unused properties - for (auto it = propertyUseCount.begin(); it != propertyUseCount.end(); ++it) { - if (it->second == 0) { - removeProperty(it->first); + for (auto &property : propertyUseCount) { + if (property.second == 0) { + removeProperty(property.first); } } } @@ -208,9 +207,8 @@ CompositeBraggScatterer::getPropertyCountMap() const { std::map<std::string, size_t> propertyUseCount; std::vector<Property *> compositeProperties = getProperties(); - for (auto it = compositeProperties.begin(); it != compositeProperties.end(); - ++it) { - propertyUseCount.emplace((*it)->name(), 0); + for (auto &compositeProperty : compositeProperties) { + propertyUseCount.emplace(compositeProperty->name(), 0); } return propertyUseCount; } diff --git a/Framework/Geometry/src/Crystal/CrystalStructure.cpp b/Framework/Geometry/src/Crystal/CrystalStructure.cpp index d40ffe8bf0a99e95b075b1b3a8b04658be403e31..0650074372e51bc2dacaf8506754eb32095c25cb 100644 --- a/Framework/Geometry/src/Crystal/CrystalStructure.cpp +++ b/Framework/Geometry/src/Crystal/CrystalStructure.cpp @@ -130,10 +130,9 @@ void CrystalStructure::setReflectionConditionFromSpaceGroup( std::vector<ReflectionCondition_sptr> reflectionConditions = getAllReflectionConditions(); - for (auto it = reflectionConditions.begin(); it != reflectionConditions.end(); - ++it) { - if ((*it)->getSymbol() == centering) { - m_centering = *it; + for (auto &reflectionCondition : reflectionConditions) { + if (reflectionCondition->getSymbol() == centering) { + m_centering = reflectionCondition; break; } } diff --git a/Framework/Geometry/src/Crystal/Group.cpp b/Framework/Geometry/src/Crystal/Group.cpp index c878a5fe211ba7e2895df42762aa99ddd8646c23..128cce0355d558df45f137c88a45bc5caf1b59be 100644 --- a/Framework/Geometry/src/Crystal/Group.cpp +++ b/Framework/Geometry/src/Crystal/Group.cpp @@ -71,11 +71,9 @@ Group Group::operator*(const Group &other) const { std::vector<SymmetryOperation> result; result.reserve(order() * other.order()); - for (auto selfOp = m_allOperations.begin(); selfOp != m_allOperations.end(); - ++selfOp) { - for (auto otherOp = other.m_allOperations.begin(); - otherOp != other.m_allOperations.end(); ++otherOp) { - result.push_back((*selfOp) * (*otherOp)); + for (const auto &operation : m_allOperations) { + for (const auto &otherOp : other.m_allOperations) { + result.push_back(operation * otherOp); } } @@ -86,9 +84,9 @@ Group Group::operator*(const Group &other) const { /// operations, vectors are wrapped to [0, 1). std::vector<Kernel::V3D> Group::operator*(const Kernel::V3D &vector) const { std::vector<Kernel::V3D> result; - - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { - result.push_back(Geometry::getWrappedVector((*op) * vector)); + result.reserve(m_allOperations.size()); + for (const auto &operation : m_allOperations) { + result.push_back(Geometry::getWrappedVector(operation * vector)); } std::sort(result.begin(), result.end(), AtomPositionsLessThan()); @@ -159,9 +157,8 @@ void Group::setSymmetryOperations( /// systems have 4 non-zero elements in the matrix, orthogonal have 6. Group::CoordinateSystem Group::getCoordinateSystemFromOperations( const std::vector<SymmetryOperation> &symmetryOperations) const { - for (auto op = symmetryOperations.begin(); op != symmetryOperations.end(); - ++op) { - std::vector<int> matrix = (*op).matrix(); + for (const auto &symmetryOperation : symmetryOperations) { + std::vector<int> matrix = symmetryOperation.matrix(); if (std::count(matrix.begin(), matrix.end(), 0) == 5) { return Group::Hexagonal; } @@ -199,8 +196,8 @@ bool Group::hasIdentity() const { /// Returns true if the inverse of each element is in the group bool Group::eachElementHasInverse() const { // Iterate through all operations, check that the inverse is in the group. - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { - if (!containsOperation((*op).inverse())) { + for (const auto &operation : m_allOperations) { + if (!containsOperation(operation.inverse())) { return false; } } diff --git a/Framework/Geometry/src/Crystal/IndexingUtils.cpp b/Framework/Geometry/src/Crystal/IndexingUtils.cpp index 321ebf7f3ccfa8d7dcfbeb272fc31894cad05e4c..b3dd290a83ce00f304cbe471cd38b87578c4580b 100644 --- a/Framework/Geometry/src/Crystal/IndexingUtils.cpp +++ b/Framework/Geometry/src/Crystal/IndexingUtils.cpp @@ -140,8 +140,8 @@ double IndexingUtils::Find_UB(DblMatrix &UB, const std::vector<V3D> &q_vectors, } } } else { - for (size_t i = 0; i < q_vectors.size(); i++) - sorted_qs.push_back(q_vectors[i]); + for (const auto &q_vector : q_vectors) + sorted_qs.push_back(q_vector); } std::sort(sorted_qs.begin(), sorted_qs.end(), V3D::CompareMagnitude); @@ -330,8 +330,8 @@ double IndexingUtils::Find_UB(DblMatrix &UB, const std::vector<V3D> &q_vectors, } } } else { - for (size_t i = 0; i < q_vectors.size(); i++) - sorted_qs.push_back(q_vectors[i]); + for (const auto &q_vector : q_vectors) + sorted_qs.push_back(q_vector); } std::sort(sorted_qs.begin(), sorted_qs.end(), V3D::CompareMagnitude); @@ -594,9 +594,9 @@ double IndexingUtils::Optimize_UB(DblMatrix &UB, DblMatrix HKLTHKL(3, 3); for (int r = 0; r < 3; r++) for (int c = 0; c < 3; c++) - for (size_t i = 0; i < hkl_vectors.size(); i++) { - HKLTHKL[r][c] += hkl_vectors[i][r] * - hkl_vectors[i][c]; // rounded??? to nearest integer + for (const auto &hkl_vector : hkl_vectors) { + HKLTHKL[r][c] += + hkl_vector[r] * hkl_vector[c]; // rounded??? to nearest integer } HKLTHKL.Invert(); @@ -941,22 +941,22 @@ double IndexingUtils::ScanFor_UB(DblMatrix &UB, std::vector<V3D> selected_b_dirs; std::vector<V3D> selected_c_dirs; - for (size_t a_dir_num = 0; a_dir_num < a_dir_list.size(); a_dir_num++) { - a_dir_temp = a_dir_list[a_dir_num]; + for (auto &a_dir_num : a_dir_list) { + a_dir_temp = a_dir_num; a_dir_temp = V3D(a_dir_temp); a_dir_temp *= a; b_dir_list = MakeCircleDirections(num_b_steps, a_dir_temp, gamma); - for (size_t b_dir_num = 0; b_dir_num < b_dir_list.size(); b_dir_num++) { - b_dir_temp = b_dir_list[b_dir_num]; + for (auto &b_dir_num : b_dir_list) { + b_dir_temp = b_dir_num; b_dir_temp = V3D(b_dir_temp); b_dir_temp *= b; c_dir_temp = Make_c_dir(a_dir_temp, b_dir_temp, c, alpha, beta, gamma); int num_indexed = 0; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { + for (const auto &q_vector : q_vectors) { bool indexes_peak = true; - q_vec = q_vectors[q_num] / (2.0 * M_PI); + q_vec = q_vector / (2.0 * M_PI); dot_prod = a_dir_temp.scalar_prod(q_vec); nearest_int = round(dot_prod); error = fabs(dot_prod - nearest_int); @@ -1004,8 +1004,8 @@ double IndexingUtils::ScanFor_UB(DblMatrix &UB, c_dir_temp = selected_c_dirs[dir_num]; double sum_sq_error = 0; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - q_vec = q_vectors[q_num] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + q_vec = q_vector / (2.0 * M_PI); dot_prod = a_dir_temp.scalar_prod(q_vec); nearest_int = round(dot_prod); error = dot_prod - nearest_int; @@ -1087,16 +1087,14 @@ size_t IndexingUtils::ScanFor_Directions(std::vector<V3D> &directions, std::vector<V3D> selected_dirs; V3D dir_temp; - for (size_t dir_num = 0; dir_num < full_list.size(); dir_num++) { - V3D current_dir = full_list[dir_num]; - + for (auto current_dir : full_list) { for (int step = 0; step <= n_steps; step++) { dir_temp = current_dir; dir_temp *= (min_d + step * delta_d); // increasing size int num_indexed = 0; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - q_vec = q_vectors[q_num] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + q_vec = q_vector / (2.0 * M_PI); dot_prod = dir_temp.scalar_prod(q_vec); nearest_int = round(dot_prod); error = fabs(dot_prod - nearest_int); @@ -1125,8 +1123,8 @@ size_t IndexingUtils::ScanFor_Directions(std::vector<V3D> &directions, directions.clear(); V3D current_dir; V3D diff; - for (size_t dir_num = 0; dir_num < selected_dirs.size(); dir_num++) { - current_dir = selected_dirs[dir_num]; + for (auto &selected_dir : selected_dirs) { + current_dir = selected_dir; GetIndexedPeaks_1D(current_dir, q_vectors, required_tolerance, index_vals, indexed_qs, fit_error); @@ -1137,8 +1135,8 @@ size_t IndexingUtils::ScanFor_Directions(std::vector<V3D> &directions, if (length >= min_d && length <= max_d) // only keep if within range { bool duplicate = false; - for (size_t i = 0; i < directions.size(); i++) { - dir_temp = directions[i]; + for (auto &direction : directions) { + dir_temp = direction; diff = current_dir - dir_temp; // discard same direction if (diff.norm() < 0.001) { @@ -1265,8 +1263,8 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, V3D temp; std::vector<V3D> temp_dirs_2; - for (size_t i = 0; i < temp_dirs.size(); i++) { - GetMagFFT(q_vectors, temp_dirs[i], N_FFT_STEPS, projections, index_factor, + for (auto &temp_dir : temp_dirs) { + GetMagFFT(q_vectors, temp_dir, N_FFT_STEPS, projections, index_factor, magnitude_fft); double position = GetFirstMaxIndex(magnitude_fft, N_FFT_STEPS, threshold); @@ -1274,7 +1272,7 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, double q_val = max_mag_Q / position; double d_val = 1 / q_val; if (d_val >= 0.8 * min_d && d_val <= 1.2 * max_d) { - temp = temp_dirs[i] * d_val; + temp = temp_dir * d_val; temp_dirs_2.push_back(temp); } } @@ -1284,8 +1282,8 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, max_indexed = 0; int num_indexed; V3D current_dir; - for (size_t dir_num = 0; dir_num < temp_dirs_2.size(); dir_num++) { - current_dir = temp_dirs_2[dir_num]; + for (auto &dir_num : temp_dirs_2) { + current_dir = dir_num; num_indexed = NumberIndexed_1D(current_dir, q_vectors, required_tolerance); if (num_indexed > max_indexed) max_indexed = num_indexed; @@ -1294,8 +1292,8 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, // only keep original directions that index // at least 50% of max num indexed temp_dirs.clear(); - for (size_t dir_num = 0; dir_num < temp_dirs_2.size(); dir_num++) { - current_dir = temp_dirs_2[dir_num]; + for (auto &dir_num : temp_dirs_2) { + current_dir = dir_num; num_indexed = NumberIndexed_1D(current_dir, q_vectors, required_tolerance); if (num_indexed >= 0.50 * max_indexed) temp_dirs.push_back(current_dir); @@ -1306,19 +1304,18 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, max_indexed = 0; std::vector<int> index_vals; std::vector<V3D> indexed_qs; - for (size_t dir_num = 0; dir_num < temp_dirs.size(); dir_num++) { - num_indexed = - GetIndexedPeaks_1D(temp_dirs[dir_num], q_vectors, required_tolerance, - index_vals, indexed_qs, fit_error); + for (auto &temp_dir : temp_dirs) { + num_indexed = GetIndexedPeaks_1D(temp_dir, q_vectors, required_tolerance, + index_vals, indexed_qs, fit_error); try { int count = 0; while (count < 5) // 5 iterations should be enough for { // the optimization to stabilize - Optimize_Direction(temp_dirs[dir_num], index_vals, indexed_qs); + Optimize_Direction(temp_dir, index_vals, indexed_qs); - num_indexed = GetIndexedPeaks_1D(temp_dirs[dir_num], q_vectors, - required_tolerance, index_vals, - indexed_qs, fit_error); + num_indexed = + GetIndexedPeaks_1D(temp_dir, q_vectors, required_tolerance, + index_vals, indexed_qs, fit_error); if (num_indexed > max_indexed) max_indexed = num_indexed; @@ -1330,8 +1327,8 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, } // discard those with length out of bounds temp_dirs_2.clear(); - for (size_t i = 0; i < temp_dirs.size(); i++) { - current_dir = temp_dirs[i]; + for (auto &temp_dir : temp_dirs) { + current_dir = temp_dir; double length = current_dir.norm(); if (length >= min_d && length <= max_d) temp_dirs_2.push_back(current_dir); @@ -1339,8 +1336,8 @@ size_t IndexingUtils::FFTScanFor_Directions(std::vector<V3D> &directions, // only keep directions that index at // least 75% of the max number of peaks temp_dirs.clear(); - for (size_t dir_num = 0; dir_num < temp_dirs_2.size(); dir_num++) { - current_dir = temp_dirs_2[dir_num]; + for (auto &dir_num : temp_dirs_2) { + current_dir = dir_num; num_indexed = NumberIndexed_1D(current_dir, q_vectors, required_tolerance); if (num_indexed > max_indexed * 0.75) temp_dirs.push_back(current_dir); @@ -1389,8 +1386,8 @@ double IndexingUtils::GetMagFFT(const std::vector<V3D> &q_vectors, } // project onto direction V3D q_vec; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - q_vec = q_vectors[q_num] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + q_vec = q_vector / (2.0 * M_PI); double dot_prod = current_dir.scalar_prod(q_vec); size_t index = static_cast<size_t>(fabs(index_factor * dot_prod)); if (index < N) @@ -1823,9 +1820,9 @@ void IndexingUtils::DiscardDuplicates(std::vector<V3D> &new_list, */ void IndexingUtils::RoundHKLs(std::vector<V3D> &hkl_list) { - for (size_t entry = 0; entry < hkl_list.size(); entry++) { + for (auto &entry : hkl_list) { for (size_t i = 0; i < 3; i++) { - hkl_list[entry][i] = static_cast<double>(round(hkl_list[entry][i])); + entry[i] = static_cast<double>(round(entry[i])); } } } @@ -1884,9 +1881,7 @@ int IndexingUtils::NumberOfValidIndexes(const std::vector<V3D> &hkls, double l_error; double total_error = 0; int count = 0; - V3D hkl; - for (size_t i = 0; i < hkls.size(); i++) { - hkl = hkls[i]; + for (const auto &hkl : hkls) { if (ValidIndex(hkl, tolerance)) { count++; h_error = fabs(round(hkl[0]) - hkl[0]); @@ -2006,8 +2001,8 @@ int IndexingUtils::NumberIndexed(const DblMatrix &UB, } V3D hkl; - for (size_t i = 0; i < q_vectors.size(); i++) { - hkl = UB_inverse * q_vectors[i] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + hkl = UB_inverse * q_vector / (2.0 * M_PI); if (ValidIndex(hkl, tolerance)) { count++; } @@ -2041,8 +2036,8 @@ int IndexingUtils::NumberIndexed_1D(const V3D &direction, int count = 0; - for (size_t i = 0; i < q_vectors.size(); i++) { - double proj_value = direction.scalar_prod(q_vectors[i]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + double proj_value = direction.scalar_prod(q_vector) / (2.0 * M_PI); int nearest_int = round(proj_value); double error = fabs(proj_value - nearest_int); if (error <= tolerance) { @@ -2084,10 +2079,10 @@ int IndexingUtils::NumberIndexed_3D(const V3D &a_dir, const V3D &b_dir, V3D hkl_vec; int count = 0; - for (size_t i = 0; i < q_vectors.size(); i++) { - hkl_vec[0] = a_dir.scalar_prod(q_vectors[i]) / (2.0 * M_PI); - hkl_vec[1] = b_dir.scalar_prod(q_vectors[i]) / (2.0 * M_PI); - hkl_vec[2] = c_dir.scalar_prod(q_vectors[i]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + hkl_vec[0] = a_dir.scalar_prod(q_vector) / (2.0 * M_PI); + hkl_vec[1] = b_dir.scalar_prod(q_vector) / (2.0 * M_PI); + hkl_vec[2] = c_dir.scalar_prod(q_vector) / (2.0 * M_PI); if (ValidIndex(hkl_vec, tolerance)) { count++; } @@ -2139,8 +2134,8 @@ int IndexingUtils::CalculateMillerIndices(const DblMatrix &UB, double h_error, k_error, l_error; ave_error = 0.0; V3D hkl; - for (size_t i = 0; i < q_vectors.size(); i++) { - hkl = UB_inverse * q_vectors[i] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + hkl = UB_inverse * q_vector / (2.0 * M_PI); if (ValidIndex(hkl, tolerance)) { count++; miller_indices.emplace_back(hkl); @@ -2205,13 +2200,13 @@ int IndexingUtils::GetIndexedPeaks_1D(const V3D &direction, return 0; // any peaks, even though dot product // with Q vectors is always an integer! - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - double proj_value = direction.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + double proj_value = direction.scalar_prod(q_vector) / (2.0 * M_PI); int nearest_int = round(proj_value); double error = fabs(proj_value - nearest_int); if (error < required_tolerance) { fit_error += error * error; - indexed_qs.push_back(q_vectors[q_num]); + indexed_qs.push_back(q_vector); index_vals.push_back(nearest_int); num_indexed++; } @@ -2271,13 +2266,10 @@ int IndexingUtils::GetIndexedPeaks_3D( fit_error = 0; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - double projected_h = - direction_1.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); - double projected_k = - direction_2.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); - double projected_l = - direction_3.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + double projected_h = direction_1.scalar_prod(q_vector) / (2.0 * M_PI); + double projected_k = direction_2.scalar_prod(q_vector) / (2.0 * M_PI); + double projected_l = direction_3.scalar_prod(q_vector) / (2.0 * M_PI); hkl(projected_h, projected_k, projected_l); @@ -2292,7 +2284,7 @@ int IndexingUtils::GetIndexedPeaks_3D( fit_error += h_error * h_error + k_error * k_error + l_error * l_error; - indexed_qs.push_back(q_vectors[q_num]); + indexed_qs.push_back(q_vector); V3D miller_ind(h_int, k_int, l_int); miller_indices.push_back(miller_ind); @@ -2354,8 +2346,8 @@ int IndexingUtils::GetIndexedPeaks(const DblMatrix &UB, throw std::runtime_error("The UB in GetIndexedPeaks() is not valid"); } - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - hkl = UB_inverse * q_vectors[q_num] / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + hkl = UB_inverse * q_vector / (2.0 * M_PI); if (ValidIndex(hkl, required_tolerance)) { for (int i = 0; i < 3; i++) { @@ -2363,7 +2355,7 @@ int IndexingUtils::GetIndexedPeaks(const DblMatrix &UB, fit_error += error * error; } - indexed_qs.push_back(q_vectors[q_num]); + indexed_qs.push_back(q_vector); V3D miller_ind(round(hkl[0]), round(hkl[1]), round(hkl[2])); miller_indices.push_back(miller_ind); @@ -2549,13 +2541,11 @@ int IndexingUtils::SelectDirection(V3D &best_direction, double error; double min_sum_sq_error = 1.0e100; - for (size_t dir_num = 0; dir_num < direction_list.size(); dir_num++) { + for (auto direction : direction_list) { double sum_sq_error = 0; - V3D direction = direction_list[dir_num]; direction /= plane_spacing; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - double dot_product = - direction.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + double dot_product = direction.scalar_prod(q_vector) / (2.0 * M_PI); nearest_int = round(dot_product); error = fabs(dot_product - nearest_int); sum_sq_error += error * error; @@ -2568,9 +2558,8 @@ int IndexingUtils::SelectDirection(V3D &best_direction, } int num_indexed = 0; - for (size_t q_num = 0; q_num < q_vectors.size(); q_num++) { - double proj_value = - best_direction.scalar_prod(q_vectors[q_num]) / (2.0 * M_PI); + for (const auto &q_vector : q_vectors) { + double proj_value = best_direction.scalar_prod(q_vector) / (2.0 * M_PI); nearest_int = round(proj_value); error = fabs(proj_value - nearest_int); if (error < required_tolerance) diff --git a/Framework/Geometry/src/Crystal/NiggliCell.cpp b/Framework/Geometry/src/Crystal/NiggliCell.cpp index bb91bf0167070d508fdb153610699a31bdf8af3d..f5a093c17d7462e30be9c92f17e8687d1ac3a2b8 100644 --- a/Framework/Geometry/src/Crystal/NiggliCell.cpp +++ b/Framework/Geometry/src/Crystal/NiggliCell.cpp @@ -74,7 +74,7 @@ static bool CompareDiffFrom90(const DblMatrix &UB_1, const DblMatrix &UB_2) { @param Umatrix :: orientation matrix U. By default this will be identity matrix */ NiggliCell::NiggliCell(const DblMatrix &Umatrix) : UnitCell() { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -99,7 +99,7 @@ NiggliCell::NiggliCell(const NiggliCell &other) NiggliCell::NiggliCell(const double _a, const double _b, const double _c, const DblMatrix &Umatrix) : UnitCell(_a, _b, _c) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -121,7 +121,7 @@ NiggliCell::NiggliCell(const double _a, const double _b, const double _c, const double _gamma, const DblMatrix &Umatrix, const int angleunit) : UnitCell(_a, _b, _c, _alpha, _beta, _gamma, angleunit) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -134,7 +134,7 @@ NiggliCell::NiggliCell(const double _a, const double _b, const double _c, */ NiggliCell::NiggliCell(const UnitCell &uc, const DblMatrix &Umatrix) : UnitCell(uc), U(Umatrix) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -143,7 +143,7 @@ NiggliCell::NiggliCell(const UnitCell &uc, const DblMatrix &Umatrix) NiggliCell::NiggliCell(const UnitCell *uc, const DblMatrix &Umatrix) : UnitCell(uc), U(Umatrix) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else diff --git a/Framework/Geometry/src/Crystal/OrientedLattice.cpp b/Framework/Geometry/src/Crystal/OrientedLattice.cpp index cd77cfb85825c6e9833a9bc4aaececf4b5283133..c8399b1ca0ad385fffb58300e87ba85daa6f153f 100644 --- a/Framework/Geometry/src/Crystal/OrientedLattice.cpp +++ b/Framework/Geometry/src/Crystal/OrientedLattice.cpp @@ -14,7 +14,7 @@ const double TWO_PI = 2. * M_PI; @param Umatrix :: orientation matrix U. By default this will be identity matrix */ OrientedLattice::OrientedLattice(const DblMatrix &Umatrix) : UnitCell() { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -39,7 +39,7 @@ OrientedLattice::OrientedLattice(const OrientedLattice &other) OrientedLattice::OrientedLattice(const double _a, const double _b, const double _c, const DblMatrix &Umatrix) : UnitCell(_a, _b, _c) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -61,7 +61,7 @@ OrientedLattice::OrientedLattice(const double _a, const double _b, const double _beta, const double _gamma, const DblMatrix &Umatrix, const int angleunit) : UnitCell(_a, _b, _c, _alpha, _beta, _gamma, angleunit) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -74,7 +74,7 @@ OrientedLattice::OrientedLattice(const double _a, const double _b, */ OrientedLattice::OrientedLattice(const UnitCell &uc, const DblMatrix &Umatrix) : UnitCell(uc), U(Umatrix) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else @@ -83,7 +83,7 @@ OrientedLattice::OrientedLattice(const UnitCell &uc, const DblMatrix &Umatrix) OrientedLattice::OrientedLattice(const UnitCell *uc, const DblMatrix &Umatrix) : UnitCell(uc), U(Umatrix) { - if (Umatrix.isRotation() == true) { + if (Umatrix.isRotation()) { U = Umatrix; UB = U * getB(); } else diff --git a/Framework/Geometry/src/Crystal/PeakTransformSelector.cpp b/Framework/Geometry/src/Crystal/PeakTransformSelector.cpp index 1bdc75000aba16d7b63fabc9d35b288b2b26ec61..3584c8f3e6450609858a428a502f3713cc659b77 100644 --- a/Framework/Geometry/src/Crystal/PeakTransformSelector.cpp +++ b/Framework/Geometry/src/Crystal/PeakTransformSelector.cpp @@ -34,10 +34,8 @@ PeakTransformFactory_sptr PeakTransformSelector::makeDefaultChoice() const { PeakTransformFactory_sptr selected; bool found = false; - for (auto it = m_candidateFactories.begin(); it != m_candidateFactories.end(); - ++it) { + for (auto temp : m_candidateFactories) { try { - PeakTransformFactory_sptr temp = (*it); temp->createDefaultTransform(); selected = temp; found = true; @@ -72,10 +70,8 @@ PeakTransformSelector::makeChoice(const std::string labelX, PeakTransformFactory_sptr selected; bool found = false; - for (auto it = m_candidateFactories.begin(); it != m_candidateFactories.end(); - ++it) { + for (auto temp : m_candidateFactories) { try { - PeakTransformFactory_sptr temp = (*it); temp->createTransform(labelX, labelY); selected = temp; found = true; diff --git a/Framework/Geometry/src/Crystal/PointGroup.cpp b/Framework/Geometry/src/Crystal/PointGroup.cpp index 1f614664120587828a516228c4dfc700a6dc7cc6..f7ef601c9161ccfa4c229f41aa36233b1a0b4b2e 100644 --- a/Framework/Geometry/src/Crystal/PointGroup.cpp +++ b/Framework/Geometry/src/Crystal/PointGroup.cpp @@ -105,8 +105,8 @@ std::vector<V3D> PointGroup::getEquivalentSet(const Kernel::V3D &hkl) const { std::vector<V3D> equivalents; equivalents.reserve(m_allOperations.size()); - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { - equivalents.push_back((*op).transformHKL(hkl)); + for (const auto &operation : m_allOperations) { + equivalents.push_back(operation.transformHKL(hkl)); } std::sort(equivalents.begin(), equivalents.end(), std::greater<V3D>()); @@ -131,10 +131,10 @@ std::vector<V3D> PointGroup::getEquivalentSet(const Kernel::V3D &hkl) const { PointGroup::CrystalSystem PointGroup::getCrystalSystemFromGroup() const { std::map<std::string, std::set<V3D>> symbolMap; - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { + for (const auto &operation : m_allOperations) { SymmetryElementWithAxis_sptr element = boost::dynamic_pointer_cast<SymmetryElementWithAxis>( - SymmetryElementFactory::Instance().createSymElement(*op)); + SymmetryElementFactory::Instance().createSymElement(operation)); if (element) { std::string symbol = element->hmSymbol(); @@ -214,8 +214,10 @@ std::vector<PointGroup_sptr> getAllPointGroups() { PointGroupFactory::Instance().getAllPointGroupSymbols(); std::vector<PointGroup_sptr> out; - for (auto it = allSymbols.begin(); it != allSymbols.end(); ++it) { - out.push_back(PointGroupFactory::Instance().createPointGroup(*it)); + out.reserve(allSymbols.size()); + + for (auto &symbol : allSymbols) { + out.push_back(PointGroupFactory::Instance().createPointGroup(symbol)); } return out; @@ -226,8 +228,9 @@ PointGroupCrystalSystemMap getPointGroupsByCrystalSystem() { PointGroupCrystalSystemMap map; std::vector<PointGroup_sptr> pointGroups = getAllPointGroups(); - for (size_t i = 0; i < pointGroups.size(); ++i) { - map.emplace(pointGroups[i]->crystalSystem(), pointGroups[i]); + + for (auto &pointGroup : pointGroups) { + map.emplace(pointGroup->crystalSystem(), pointGroup); } return map; diff --git a/Framework/Geometry/src/Crystal/PointGroupFactory.cpp b/Framework/Geometry/src/Crystal/PointGroupFactory.cpp index f2d1a4243cef2d837968bb32ff4bd4ecb59d1d1d..5c31b248192e2709745eaadef9fdbb4fdf5fdfc6 100644 --- a/Framework/Geometry/src/Crystal/PointGroupFactory.cpp +++ b/Framework/Geometry/src/Crystal/PointGroupFactory.cpp @@ -57,9 +57,9 @@ bool PointGroupFactoryImpl::isSubscribed(const std::string &hmSymbol) const { std::vector<std::string> PointGroupFactoryImpl::getAllPointGroupSymbols() const { std::vector<std::string> pointGroups; - - for (auto it = m_generatorMap.begin(); it != m_generatorMap.end(); ++it) { - pointGroups.push_back(it->first); + pointGroups.reserve(m_generatorMap.size()); + for (const auto &generator : m_generatorMap) { + pointGroups.push_back(generator.first); } return pointGroups; @@ -71,11 +71,11 @@ std::vector<std::string> PointGroupFactoryImpl::getPointGroupSymbols( const PointGroup::CrystalSystem &crystalSystem) { std::vector<std::string> pointGroups; - for (auto it = m_generatorMap.begin(); it != m_generatorMap.end(); ++it) { - PointGroup_sptr pointGroup = getPrototype(it->first); + for (auto &generator : m_generatorMap) { + PointGroup_sptr pointGroup = getPrototype(generator.first); if (pointGroup->crystalSystem() == crystalSystem) { - pointGroups.push_back(it->first); + pointGroups.push_back(generator.first); } } diff --git a/Framework/Geometry/src/Crystal/ProductOfCyclicGroups.cpp b/Framework/Geometry/src/Crystal/ProductOfCyclicGroups.cpp index d2c48bac2c267562d7a09b16e3617515fd88a6fc..3aa2a64504e67418b8aa7b0ffd2f50c4fecea00a 100644 --- a/Framework/Geometry/src/Crystal/ProductOfCyclicGroups.cpp +++ b/Framework/Geometry/src/Crystal/ProductOfCyclicGroups.cpp @@ -32,9 +32,9 @@ std::vector<Group_const_sptr> ProductOfCyclicGroups::getFactorGroups( const std::vector<SymmetryOperation> &symmetryOperations) const { std::vector<Group_const_sptr> groups; - for (auto it = symmetryOperations.begin(); it != symmetryOperations.end(); - ++it) { - groups.push_back(GroupFactory::create<CyclicGroup>((*it).identifier())); + for (const auto &symmetryOperation : symmetryOperations) { + groups.push_back( + GroupFactory::create<CyclicGroup>(symmetryOperation.identifier())); } return groups; diff --git a/Framework/Geometry/src/Crystal/ScalarUtils.cpp b/Framework/Geometry/src/Crystal/ScalarUtils.cpp index e92b977edef531ba35d5a1092e8df1dc1ffe07e4..32a3e80f1db0aa094e482cbc70bcc4895c58df0b 100644 --- a/Framework/Geometry/src/Crystal/ScalarUtils.cpp +++ b/Framework/Geometry/src/Crystal/ScalarUtils.cpp @@ -95,8 +95,8 @@ std::vector<ConventionalCell> ScalarUtils::GetCells(const DblMatrix &UB, temp.clear(); temp.push_back(info); } - for (size_t k = 0; k < temp.size(); k++) - AddIfBest(result, temp[k]); + for (auto &k : temp) + AddIfBest(result, k); } return result; @@ -143,12 +143,12 @@ ScalarUtils::GetCells(const DblMatrix &UB, const std::string &cell_type, UB_list.push_back(UB); } - for (size_t k = 0; k < UB_list.size(); k++) { + for (auto &k : UB_list) { std::vector<ConventionalCell> temp = - GetCellsUBOnly(UB_list[k], cell_type, centering, allowPermutations); + GetCellsUBOnly(k, cell_type, centering, allowPermutations); - for (size_t i = 0; i < temp.size(); i++) - AddIfBest(result, temp[i]); + for (auto &cell : temp) + AddIfBest(result, cell); } return result; @@ -234,8 +234,8 @@ ConventionalCell ScalarUtils::GetCellForForm(const DblMatrix &UB, // Get exact form requested and not permutations UB_list.push_back(UB); } - for (size_t i = 0; i < UB_list.size(); i++) { - IndexingUtils::GetLatticeParameters(UB_list[i], l_params); + for (auto &UB : UB_list) { + IndexingUtils::GetLatticeParameters(UB, l_params); form_0 = ReducedCell(0, l_params[0], l_params[1], l_params[2], l_params[3], l_params[4], l_params[5]); @@ -245,7 +245,7 @@ ConventionalCell ScalarUtils::GetCellForForm(const DblMatrix &UB, double error = form_0.WeightedDistance(form); if (error < min_error) { - info = ConventionalCell(UB_list[i], form_num, allowPermutations); + info = ConventionalCell(UB, form_num, allowPermutations); min_error = error; } } @@ -268,13 +268,13 @@ void ScalarUtils::RemoveHighErrorForms(std::vector<ConventionalCell> &list, std::vector<ConventionalCell> new_list; - for (size_t i = 0; i < list.size(); i++) - if (list[i].GetError() <= level) - new_list.push_back(list[i]); + for (auto &cell : list) + if (cell.GetError() <= level) + new_list.push_back(cell); list.clear(); - for (size_t i = 0; i < new_list.size(); i++) - list.push_back(new_list[i]); + for (const auto &cell : new_list) + list.push_back(cell); } /** @@ -299,15 +299,14 @@ ScalarUtils::GetCellBestError(const std::vector<ConventionalCell> &list, ConventionalCell info = list[0]; double min_error = 1.0e20; - std::string type; bool min_found = false; - for (size_t i = 0; i < list.size(); i++) { - type = list[i].GetCellType(); - double error = list[i].GetError(); + for (const auto &cell : list) { + std::string type = cell.GetCellType(); + double error = cell.GetError(); if ((use_triclinic || type != ReducedCell::TRICLINIC()) && error < min_error) { - info = list[i]; + info = cell; min_error = error; min_found = true; } @@ -411,10 +410,10 @@ std::vector<DblMatrix> ScalarUtils::GetRelatedUBs(const DblMatrix &UB, {c_temp, a_temp, b_temp}, {m_c_temp, b_temp, a_temp}}; - for (size_t perm = 0; perm < 6; perm++) { - a = permutations[perm][0]; - b = permutations[perm][1]; - c = permutations[perm][2]; + for (auto &permutation : permutations) { + a = permutation[0]; + b = permutation[1]; + c = permutation[2]; if (a.norm() <= factor * b.norm() && b.norm() <= factor * c.norm()) // could be Niggli within { // experimental error diff --git a/Framework/Geometry/src/Crystal/SpaceGroup.cpp b/Framework/Geometry/src/Crystal/SpaceGroup.cpp index 995746857c6023bd18ce3193500bc689cc1c976d..05fef03f84135cf408336d9ed6dabf164765df9e 100644 --- a/Framework/Geometry/src/Crystal/SpaceGroup.cpp +++ b/Framework/Geometry/src/Crystal/SpaceGroup.cpp @@ -1,5 +1,6 @@ #include "MantidGeometry/Crystal/SpaceGroup.h" #include "MantidGeometry/Crystal/PointGroupFactory.h" +#include <algorithm> namespace Mantid { namespace Geometry { @@ -59,16 +60,16 @@ std::string SpaceGroup::hmSymbol() const { return m_hmSymbol; } * @return :: true if the reflection is allowed, false otherwise. */ bool SpaceGroup::isAllowedReflection(const Kernel::V3D &hkl) const { - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { - if ((*op).hasTranslation()) { + for (const auto &operation : m_allOperations) { + if (operation.hasTranslation()) { /* Floating point precision problem: * (H . v) % 1.0 is not always exactly 0, so instead: * | [(H . v) + delta] % 1.0 | > 1e-14 is checked * The transformation is only performed if necessary. */ - if ((fabs(fmod(fabs(hkl.scalar_prod((*op).reducedVector())) + 1e-15, + if ((fabs(fmod(fabs(hkl.scalar_prod(operation.reducedVector())) + 1e-15, 1.0)) > 1e-14) && - ((*op).transformHKL(hkl) == hkl)) { + (operation.transformHKL(hkl) == hkl)) { return false; } } @@ -104,15 +105,13 @@ Group_const_sptr SpaceGroup::getSiteSymmetryGroup(const V3D &position) const { V3D wrappedPosition = Geometry::getWrappedVector(position); std::vector<SymmetryOperation> siteSymmetryOps; - AtomPositionsEqual comparator; - - for (auto op = m_allOperations.begin(); op != m_allOperations.end(); ++op) { - if (comparator(Geometry::getWrappedVector((*op) * wrappedPosition), - wrappedPosition)) { - siteSymmetryOps.push_back(*op); - } - } + std::copy_if(m_allOperations.begin(), m_allOperations.end(), + std::inserter(siteSymmetryOps, siteSymmetryOps.begin()), + [&](const SymmetryOperation &op) { + return Geometry::getWrappedVector(op * wrappedPosition) == + wrappedPosition; + }); return GroupFactory::create<Group>(siteSymmetryOps); } diff --git a/Framework/Geometry/src/Crystal/SpaceGroupFactory.cpp b/Framework/Geometry/src/Crystal/SpaceGroupFactory.cpp index 47c912726cd85d067463f8eb2ec4ebc9ffed5860..b51fd2b734b503c8822bc01a062ff5ae05d069e3 100644 --- a/Framework/Geometry/src/Crystal/SpaceGroupFactory.cpp +++ b/Framework/Geometry/src/Crystal/SpaceGroupFactory.cpp @@ -21,9 +21,9 @@ bool isValidGeneratorString(const std::string &generatorString) { std::vector<std::string> generatorStrings; boost::split(generatorStrings, generatorString, boost::is_any_of(";")); - for (auto it = generatorStrings.begin(); it != generatorStrings.end(); ++it) { + for (auto &generatorString : generatorStrings) { try { - SymmetryOperationSymbolParser::parseIdentifier(*it); + SymmetryOperationSymbolParser::parseIdentifier(generatorString); } catch (Kernel::Exception::ParseError) { return false; } @@ -250,8 +250,8 @@ SpaceGroupFactoryImpl::subscribedSpaceGroupSymbols() const { std::vector<std::string> symbols; symbols.reserve(m_generatorMap.size()); - for (auto it = m_generatorMap.begin(); it != m_generatorMap.end(); ++it) { - symbols.push_back(it->first); + for (const auto &generator : m_generatorMap) { + symbols.push_back(generator.first); } return symbols; @@ -410,11 +410,11 @@ SpaceGroup_const_sptr SpaceGroupFactoryImpl::constructFromPrototype( void SpaceGroupFactoryImpl::fillPointGroupMap() { m_pointGroupMap.clear(); - for (auto it = m_generatorMap.begin(); it != m_generatorMap.end(); ++it) { - SpaceGroup_const_sptr spaceGroup = getPrototype(it->first); + for (auto &generator : m_generatorMap) { + SpaceGroup_const_sptr spaceGroup = getPrototype(generator.first); - m_pointGroupMap.insert( - std::make_pair(spaceGroup->getPointGroup()->getSymbol(), it->first)); + m_pointGroupMap.insert(std::make_pair( + spaceGroup->getPointGroup()->getSymbol(), generator.first)); } } diff --git a/Framework/Geometry/src/Crystal/StructureFactorCalculatorSummation.cpp b/Framework/Geometry/src/Crystal/StructureFactorCalculatorSummation.cpp index eabc22952cbd37217570255a766d4f023f170d83..898ac47b67cbef42e79279376483186743cde498 100644 --- a/Framework/Geometry/src/Crystal/StructureFactorCalculatorSummation.cpp +++ b/Framework/Geometry/src/Crystal/StructureFactorCalculatorSummation.cpp @@ -55,9 +55,9 @@ void StructureFactorCalculatorSummation::updateUnitCellScatterers( std::vector<V3D> positions = spaceGroup->getEquivalentPositions(current->getPosition()); - for (auto pos = positions.begin(); pos != positions.end(); ++pos) { + for (auto &position : positions) { BraggScatterer_sptr clone = current->clone(); - clone->setProperty("Position", getV3DasString(*pos)); + clone->setProperty("Position", getV3DasString(position)); braggScatterers.push_back(clone); } diff --git a/Framework/Geometry/src/Crystal/SymmetryElementFactory.cpp b/Framework/Geometry/src/Crystal/SymmetryElementFactory.cpp index 9affcebe8741366a968514da21b0effa9346560d..a3a37ef0477a2e4ae95a859e7fb7a2d74971b6ce 100644 --- a/Framework/Geometry/src/Crystal/SymmetryElementFactory.cpp +++ b/Framework/Geometry/src/Crystal/SymmetryElementFactory.cpp @@ -378,10 +378,9 @@ SymmetryElement_sptr SymmetryElementFactoryImpl::createFromPrototype( /// invalid pointer if no appropriate generator is found. AbstractSymmetryElementGenerator_sptr SymmetryElementFactoryImpl::getGenerator( const SymmetryOperation &operation) const { - for (auto generator = m_generators.begin(); generator != m_generators.end(); - ++generator) { - if ((*generator)->canProcess(operation)) { - return *generator; + for (const auto &generator : m_generators) { + if (generator->canProcess(operation)) { + return generator; } } diff --git a/Framework/Geometry/src/Crystal/SymmetryOperationFactory.cpp b/Framework/Geometry/src/Crystal/SymmetryOperationFactory.cpp index 9cef464466e81b23edf3af80aeb75f16fd755437..35651a9b6bab229e43c57a1090536092dd3c68a0 100644 --- a/Framework/Geometry/src/Crystal/SymmetryOperationFactory.cpp +++ b/Framework/Geometry/src/Crystal/SymmetryOperationFactory.cpp @@ -32,8 +32,8 @@ SymmetryOperationFactoryImpl::createSymOps(const std::string &identifiers) { std::vector<SymmetryOperation> SymmetryOperationFactoryImpl::createSymOps( const std::vector<std::string> &identifiers) { std::vector<SymmetryOperation> symOps; - for (auto it = identifiers.begin(); it != identifiers.end(); ++it) { - symOps.push_back(createSymOp(boost::trim_copy(*it))); + for (const auto &identifier : identifiers) { + symOps.push_back(createSymOp(boost::trim_copy(identifier))); } return symOps; @@ -67,8 +67,8 @@ SymmetryOperationFactoryImpl::subscribedSymbols() const { std::vector<std::string> symbols; symbols.reserve(m_prototypes.size()); - for (auto it = m_prototypes.begin(); it != m_prototypes.end(); ++it) { - symbols.push_back(it->first); + for (const auto &prototype : m_prototypes) { + symbols.push_back(prototype.first); } return symbols; diff --git a/Framework/Geometry/src/Crystal/SymmetryOperationSymbolParser.cpp b/Framework/Geometry/src/Crystal/SymmetryOperationSymbolParser.cpp index a598da3674b53bbf4a6f9dde057bcdaa4f19ae57..f25ff3dd86c1612f0d6b7290cceb906bcbb9f91c 100644 --- a/Framework/Geometry/src/Crystal/SymmetryOperationSymbolParser.cpp +++ b/Framework/Geometry/src/Crystal/SymmetryOperationSymbolParser.cpp @@ -128,7 +128,6 @@ std::string SymmetryOperationSymbolParser::getNormalizedIdentifier( bool SymmetryOperationSymbolParser::isValidMatrixRow(const int *element, size_t columnNumber) { int nulls = 0; - for (size_t i = 0; i < columnNumber; ++i) { if (abs(element[i]) > 1) { return false; diff --git a/Framework/Geometry/src/Instrument.cpp b/Framework/Geometry/src/Instrument.cpp index 010c85d35589ae32d3dffaa4bde2c89345d576b1..35de6daf9cb9742532e161227faf0a3e7b49bd79 100644 --- a/Framework/Geometry/src/Instrument.cpp +++ b/Framework/Geometry/src/Instrument.cpp @@ -182,9 +182,9 @@ void Instrument::getDetectors(detid2det_map &out_map) const { const detid2det_map &in_dets = static_cast<const Instrument *>(m_base)->m_detectorCache; // And turn them into parametrized versions - for (auto it = in_dets.cbegin(); it != in_dets.cend(); ++it) { - out_map.emplace(it->first, ParComponentFactory::createDetector( - it->second.get(), m_map)); + for (const auto &in_det : in_dets) { + out_map.emplace(in_det.first, ParComponentFactory::createDetector( + in_det.second.get(), m_map)); } } else { // You can just return the detector cache directly. @@ -199,14 +199,14 @@ std::vector<detid_t> Instrument::getDetectorIDs(bool skipMonitors) const { if (m_map) { const detid2det_map &in_dets = static_cast<const Instrument *>(m_base)->m_detectorCache; - for (auto it = in_dets.cbegin(); it != in_dets.cend(); ++it) - if (!skipMonitors || !it->second->isMonitor()) - out.push_back(it->first); + for (const auto &in_det : in_dets) + if (!skipMonitors || !in_det.second->isMonitor()) + out.push_back(in_det.first); } else { const detid2det_map &in_dets = m_detectorCache; - for (auto it = in_dets.cbegin(); it != in_dets.cend(); ++it) - if (!skipMonitors || !it->second->isMonitor()) - out.push_back(it->first); + for (const auto &in_det : in_dets) + if (!skipMonitors || !in_det.second->isMonitor()) + out.push_back(in_det.first); } return out; } @@ -227,13 +227,13 @@ std::size_t Instrument::getNumberDetectors(bool skipMonitors) const { if (m_map) { const detid2det_map &in_dets = static_cast<const Instrument *>(m_base)->m_detectorCache; - for (auto it = in_dets.cbegin(); it != in_dets.cend(); ++it) - if (it->second->isMonitor()) + for (const auto &in_det : in_dets) + if (in_det.second->isMonitor()) monitors += 1; } else { const detid2det_map &in_dets = m_detectorCache; - for (auto it = in_dets.begin(); it != in_dets.end(); ++it) - if (it->second->isMonitor()) + for (const auto &in_det : in_dets) + if (in_det.second->isMonitor()) monitors += 1; } return (numDetIDs - monitors); @@ -503,8 +503,8 @@ bool Instrument::isMonitor(const std::set<detid_t> &detector_ids) const { if (detector_ids.empty()) return false; - for (auto it = detector_ids.cbegin(); it != detector_ids.cend(); ++it) { - if (this->isMonitor(*it)) + for (auto detector_id : detector_ids) { + if (this->isMonitor(detector_id)) return true; } return false; @@ -550,8 +550,8 @@ bool Instrument::isDetectorMasked(const std::set<detid_t> &detector_ids) const { if (detector_ids.empty()) return false; - for (auto it = detector_ids.cbegin(); it != detector_ids.cend(); ++it) { - if (!this->isDetectorMasked(*it)) + for (auto detector_id : detector_ids) { + if (!this->isDetectorMasked(detector_id)) return false; } return true; @@ -823,9 +823,8 @@ void Instrument::getBoundingBox(BoundingBox &assemblyBox) const { m_cachedBoundingBox = new BoundingBox(); ComponentID sourceID = getSource()->getComponentID(); // Loop over the children and define a box large enough for all of them - for (auto it = m_children.cbegin(); it != m_children.cend(); ++it) { + for (auto component : m_children) { BoundingBox compBox; - IComponent *component = *it; if (component && component->getComponentID() != sourceID) { component->getBoundingBox(compBox); m_cachedBoundingBox->grow(compBox); @@ -948,15 +947,15 @@ double Instrument::calcConversion( const std::map<detid_t, double> &offsets) { double factor = 0.; double offset; - for (auto iter = detectors.cbegin(); iter != detectors.cend(); ++iter) { - auto off_iter = offsets.find(*iter); + for (auto detector : detectors) { + auto off_iter = offsets.find(detector); if (off_iter != offsets.cend()) { - offset = offsets.find(*iter)->second; + offset = offsets.find(detector)->second; } else { offset = 0.; } factor += calcConversion(l1, beamline, beamline_norm, samplePos, - instrument->getDetector(*iter), offset); + instrument->getDetector(detector), offset); } return factor / static_cast<double>(detectors.size()); } diff --git a/Framework/Geometry/src/Instrument/CompAssembly.cpp b/Framework/Geometry/src/Instrument/CompAssembly.cpp index 7c73ef1e6b9d42ab68a7fe68b79f97ca68ce141d..6fedd5cccf7f2239832c7fcabca3a5b68431f27e 100644 --- a/Framework/Geometry/src/Instrument/CompAssembly.cpp +++ b/Framework/Geometry/src/Instrument/CompAssembly.cpp @@ -65,8 +65,8 @@ CompAssembly::~CompAssembly() { if (m_cachedBoundingBox) delete m_cachedBoundingBox; // Iterate over pointers in m_children, deleting them - for (auto it = m_children.begin(); it != m_children.end(); ++it) { - delete *it; + for (auto &child : m_children) { + delete child; } m_children.clear(); } @@ -371,10 +371,10 @@ void CompAssembly::getBoundingBox(BoundingBox &assemblyBox) const { if (!m_cachedBoundingBox) { m_cachedBoundingBox = new BoundingBox(); // Loop over the children and define a box large enough for all of them - for (auto it = m_children.cbegin(); it != m_children.cend(); ++it) { + for (auto child : m_children) { BoundingBox compBox; - if (*it) { - (*it)->getBoundingBox(compBox); + if (child) { + child->getBoundingBox(compBox); m_cachedBoundingBox->grow(compBox); } } diff --git a/Framework/Geometry/src/Instrument/Component.cpp b/Framework/Geometry/src/Instrument/Component.cpp index 72bb0aa8be0544fcc1b2a796d0ca6a084abd8c1b..62384840a1cb7190737fc5a016a58c4304f31748 100644 --- a/Framework/Geometry/src/Instrument/Component.cpp +++ b/Framework/Geometry/src/Instrument/Component.cpp @@ -445,9 +445,9 @@ Component::getParameterNamesByComponent() const { return retVal; std::set<std::string> names = m_map->names(this); - for (auto itNames = names.begin(); itNames != names.end(); ++itNames) { + for (const auto &name : names) { retVal.insert( - std::pair<std::string, ComponentID>(*itNames, this->getComponentID())); + std::pair<std::string, ComponentID>(name, this->getComponentID())); } // Walk up the tree and find the parameters attached to the parent components diff --git a/Framework/Geometry/src/Instrument/DetectorGroup.cpp b/Framework/Geometry/src/Instrument/DetectorGroup.cpp index 8366e8c9153ddc8215773187742d13ed99e0a2f9..ec9dc2bd8743ae86ab3dc71e41844e29063fd6c7 100644 --- a/Framework/Geometry/src/Instrument/DetectorGroup.cpp +++ b/Framework/Geometry/src/Instrument/DetectorGroup.cpp @@ -353,15 +353,14 @@ std::string DetectorGroup::getParameterAsString(const std::string &pname, void DetectorGroup::getBoundingBox(BoundingBox &boundingBox) const { // boundingBox = BoundingBox(); // this change may modify a lot of behaviour // -> verify - for (auto cit = m_detectors.cbegin(); cit != m_detectors.cend(); ++cit) { + for (const auto &detector : m_detectors) { BoundingBox memberBox; if (!boundingBox.isAxisAligned()) { // coordinate system const std::vector<V3D> *cs = &(boundingBox.getCoordSystem()); memberBox.realign(cs); } - IComponent_const_sptr det = cit->second; - det->getBoundingBox(memberBox); + detector.second->getBoundingBox(memberBox); boundingBox.grow(memberBox); } } diff --git a/Framework/Geometry/src/Instrument/Goniometer.cpp b/Framework/Geometry/src/Instrument/Goniometer.cpp index 0d4e6457b59a8fe648b1002f7382b08e038adffa..fbe525c0c1c87c5b88b37e3b415de826543be1eb 100644 --- a/Framework/Geometry/src/Instrument/Goniometer.cpp +++ b/Framework/Geometry/src/Instrument/Goniometer.cpp @@ -90,7 +90,7 @@ bool Goniometer::isDefined() const { return initFromR || (!motors.empty()); } /// name, direction, sense, angle) /// The angle units shown is degrees std::string Goniometer::axesInfo() { - if (initFromR == true) { + if (initFromR) { return std::string("Goniometer was initialized from a rotation matrix. No " "information about axis is available.\n"); } else { @@ -126,7 +126,7 @@ std::string Goniometer::axesInfo() { */ void Goniometer::pushAxis(std::string name, double axisx, double axisy, double axisz, double angle, int sense, int angUnit) { - if (initFromR == true) { + if (initFromR) { throw std::runtime_error( "Initialized from a rotation matrix, so no axes can be pushed."); } else { @@ -155,7 +155,7 @@ void Goniometer::setRotationAngle(std::string name, double value) { changed = true; } } - if (changed == false) { + if (!changed) { throw std::invalid_argument("Motor name " + name + " not found"); } recalculateR(); diff --git a/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp b/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp index 0f2811e906c1660c7ab59858c9434cdef8ee3b48..378f0bf9d276ea02ca57a9322f3da354b521c12a 100644 --- a/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp +++ b/Framework/Geometry/src/Instrument/InstrumentDefinitionParser.cpp @@ -357,11 +357,10 @@ InstrumentDefinitionParser::parseXML(Kernel::ProgressBase *prog) { if (prog) prog->resetNumSteps(compElems.size(), 0.0, 1.0); - for (size_t i = 0; i < compElems.size(); ++i) { + for (auto pElem : compElems) { if (prog) prog->report("Loading instrument Definition"); - const Element *pElem = compElems[i]; { IdList idList; // structure to possibly be populated with detector IDs @@ -2180,18 +2179,16 @@ void InstrumentDefinitionParser::setComponentLinks( } } - for (size_t i = 0; i < sharedIComp.size(); i++) { + for (auto &ptr : sharedIComp) { boost::shared_ptr<const Geometry::Component> sharedComp = - boost::dynamic_pointer_cast<const Geometry::Component>( - sharedIComp[i]); + boost::dynamic_pointer_cast<const Geometry::Component>(ptr); if (sharedComp) { // Not empty Component if (sharedComp->isParametrized()) { setLogfile(sharedComp->base(), curElem, instrument->getLogfileCache()); } else { - setLogfile(sharedIComp[i].get(), curElem, - instrument->getLogfileCache()); + setLogfile(ptr.get(), curElem, instrument->getLogfileCache()); } } } @@ -2636,10 +2633,10 @@ InstrumentDefinitionParser::convertLocationsElement( std::map<std::string, double> attrValues; // Read all the set attribute values - for (auto it = allAttrs.begin(); it != allAttrs.end(); ++it) { - if (pElem->hasAttribute(*it)) { - attrValues[*it] = - boost::lexical_cast<double>(Strings::strip(pElem->getAttribute(*it))); + for (const auto &attr : allAttrs) { + if (pElem->hasAttribute(attr)) { + attrValues[attr] = boost::lexical_cast<double>( + Strings::strip(pElem->getAttribute(attr))); } } @@ -2647,19 +2644,20 @@ InstrumentDefinitionParser::convertLocationsElement( std::map<std::string, double> rangeAttrSteps; // Find *-end for range attributes and calculate steps - for (auto it = rangeAttrs.begin(); it != rangeAttrs.end(); ++it) { - std::string endAttr = *it + "-end"; + for (const auto &rangeAttr : rangeAttrs) { + std::string endAttr = rangeAttr + "-end"; if (pElem->hasAttribute(endAttr)) { - if (attrValues.find(*it) == attrValues.end()) { + if (attrValues.find(rangeAttr) == attrValues.end()) { throw Exception::InstrumentDefinitionError( "*-end attribute without corresponding * attribute."); } - double from = attrValues[*it]; + double from = attrValues[rangeAttr]; double to = boost::lexical_cast<double>( Strings::strip(pElem->getAttribute(endAttr))); - rangeAttrSteps[*it] = (to - from) / (static_cast<double>(nElements) - 1); + rangeAttrSteps[rangeAttr] = + (to - from) / (static_cast<double>(nElements) - 1); } } @@ -2678,13 +2676,13 @@ InstrumentDefinitionParser::convertLocationsElement( } // Copy values of all the attributes set - for (auto it = attrValues.begin(); it != attrValues.end(); ++it) { - pLoc->setAttribute(it->first, - boost::lexical_cast<std::string>(it->second)); + for (auto &attrValue : attrValues) { + pLoc->setAttribute(attrValue.first, + boost::lexical_cast<std::string>(attrValue.second)); // If attribute has a step, increase the value by the step - if (rangeAttrSteps.find(it->first) != rangeAttrSteps.end()) { - it->second += rangeAttrSteps[it->first]; + if (rangeAttrSteps.find(attrValue.first) != rangeAttrSteps.end()) { + attrValue.second += rangeAttrSteps[attrValue.first]; } } diff --git a/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp b/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp index c461064c44b638c4ee69cf839dc9d3ce6ee70a43..aaa60dd67c81f49b168602f15dfba8eaa2688d79 100644 --- a/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp +++ b/Framework/Geometry/src/Instrument/ObjCompAssembly.cpp @@ -78,8 +78,8 @@ ObjCompAssembly::ObjCompAssembly(const ObjCompAssembly &ass) ObjCompAssembly::~ObjCompAssembly() { // Iterate over pointers in group, deleting them // std::vector<IComponent*>::iterator it; - for (auto it = group.begin(); it != group.end(); ++it) { - delete *it; + for (auto &component : group) { + delete component; } group.clear(); } diff --git a/Framework/Geometry/src/Instrument/ParameterMap.cpp b/Framework/Geometry/src/Instrument/ParameterMap.cpp index ff55a3a0f5e13d4f2b4da1f477b52a16d524ef80..cd7659fd50b7bb7c00ddb7cd674de916914d2509 100644 --- a/Framework/Geometry/src/Instrument/ParameterMap.cpp +++ b/Framework/Geometry/src/Instrument/ParameterMap.cpp @@ -939,10 +939,10 @@ std::set<std::string> ParameterMap::names(const IComponent *comp) const { */ std::string ParameterMap::asString() const { std::stringstream out; - for (auto it = m_map.cbegin(); it != m_map.cend(); ++it) { - boost::shared_ptr<Parameter> p = it->second; - if (p && it->first) { - const IComponent *comp = (const IComponent *)(it->first); + for (const auto &mappair : m_map) { + const boost::shared_ptr<Parameter> &p = mappair.second; + if (p && mappair.first) { + const IComponent *comp = (const IComponent *)(mappair.first); const IDetector *det = dynamic_cast<const IDetector *>(comp); if (det) { out << "detID:" << det->getID(); @@ -1046,14 +1046,10 @@ void ParameterMap::copyFromParameterMap(const IComponent *oldComp, const ParameterMap *oldPMap) { std::set<std::string> oldParameterNames = oldPMap->names(oldComp); - - for (auto it = oldParameterNames.begin(); it != oldParameterNames.end(); - ++it) { - for (const auto ¶meterName : oldParameterNames) { - // Insert the fetched parameter in the m_map - m_map.emplace(newComp->getComponentID(), - oldPMap->get(oldComp, parameterName)); - } + for (const auto &oldParameterName : oldParameterNames) { + Parameter_sptr thisParameter = oldPMap->get(oldComp, oldParameterName); + // Insert the fetched parameter in the m_map + m_map.emplace(newComp->getComponentID(), thisParameter); } } diff --git a/Framework/Geometry/src/MDGeometry/CompositeImplicitFunction.cpp b/Framework/Geometry/src/MDGeometry/CompositeImplicitFunction.cpp index a68e26b2c1cac4b4da407779b2e7455a13204669..fffceddb4c25a3c7685116991d7158b576f31e08 100644 --- a/Framework/Geometry/src/MDGeometry/CompositeImplicitFunction.cpp +++ b/Framework/Geometry/src/MDGeometry/CompositeImplicitFunction.cpp @@ -46,8 +46,8 @@ std::string CompositeImplicitFunction::toXMLString() const { functionElement->appendChild(parameterListElement); std::string functionXML; - for (auto it = m_Functions.begin(); it != m_Functions.end(); ++it) { - functionXML += (*it)->toXMLString(); + for (const auto &Function : m_Functions) { + functionXML += Function->toXMLString(); } AutoPtr<Text> functionFormatText = pDoc->createTextNode("%s"); functionElement->appendChild(functionFormatText); diff --git a/Framework/Geometry/src/MDGeometry/MDGeometryXMLBuilder.cpp b/Framework/Geometry/src/MDGeometry/MDGeometryXMLBuilder.cpp index ff15b1395b13c0e63ec323f1addf80203a4483b7..96e4a637eaf70111f769b20afeea3371800c7514 100644 --- a/Framework/Geometry/src/MDGeometry/MDGeometryXMLBuilder.cpp +++ b/Framework/Geometry/src/MDGeometry/MDGeometryXMLBuilder.cpp @@ -64,8 +64,8 @@ bool MDGeometryBuilderXML<CheckDimensionPolicy>::addOrdinaryDimension( template <typename CheckDimensionPolicy> void MDGeometryBuilderXML<CheckDimensionPolicy>::addManyOrdinaryDimensions( VecIMDDimension_sptr manyDims) const { - for (auto it = manyDims.begin(); it != manyDims.end(); ++it) { - addOrdinaryDimension(*it); + for (auto &manyDim : manyDims) { + addOrdinaryDimension(manyDim); } } diff --git a/Framework/Geometry/src/Math/Acomp.cpp b/Framework/Geometry/src/Math/Acomp.cpp index 3832d0cd6554fc650aea1d2848da1f4671180fea..d846e545a5cac62a7d8ca368114c451d6cf994d3 100644 --- a/Framework/Geometry/src/Math/Acomp.cpp +++ b/Framework/Geometry/src/Math/Acomp.cpp @@ -160,15 +160,11 @@ Order (low first) const int TS = isSingle(); // is this one component const int AS = A.isSingle(); if (TS != AS) - return (TS > AS) ? true : false; + return TS > AS; // PROCESS Intersection/Union if (!TS && Intersect != A.Intersect) { // Union==0 therefore this > A - if (Intersect > 0) { - return true; - } else { - return false; - } + return Intersect > 0; } // PROCESS Units. (order : then size) @@ -192,10 +188,7 @@ Order (low first) if (*ax != *ux) return (*ux < *ax); } - if (uc != Units.end()) - return true; - // everything idential or A.comp bigger: - return false; + return uc != Units.end(); } Acomp &Acomp::operator+=(const Acomp &A) @@ -475,17 +468,17 @@ Units are sorted after this function is returned. int bextra = 0; // find first Component to add // std::cerr<<"Process Union:"<<Ln<<std::endl; - for (unsigned int iu = 0; iu < Ln.length(); iu++) { + for (char iu : Ln) { if (blevel) // we are in a bracket then... { - if (Ln[iu] == ')') // maybe closing outward.. + if (iu == ')') // maybe closing outward.. blevel--; - else if (Ln[iu] == '(') + else if (iu == '(') blevel++; if (blevel || bextra) - Express += Ln[iu]; + Express += iu; } else { - if (Ln[iu] == '+') { + if (iu == '+') { Acomp AX; try { AX.setString(Express); @@ -495,7 +488,7 @@ Units are sorted after this function is returned. } Express.erase(); // reset string addComp(AX); // add components - } else if (Ln[iu] == '(') { + } else if (iu == '(') { blevel++; if (Express.length()) { Express += '('; @@ -503,7 +496,7 @@ Units are sorted after this function is returned. } else bextra = 0; } else - Express += Ln[iu]; + Express += iu; } } if (Express.size() > 0) { diff --git a/Framework/Geometry/src/Objects/BoundingBox.cpp b/Framework/Geometry/src/Objects/BoundingBox.cpp index 25aac8228bcf886153314c991e6c4eca5ee3bf10..b1958d3d7b156b478a302f847c1674a473ca3eef 100644 --- a/Framework/Geometry/src/Objects/BoundingBox.cpp +++ b/Framework/Geometry/src/Objects/BoundingBox.cpp @@ -24,16 +24,12 @@ bool BoundingBox::isPointInside(const V3D &point) const { "this function has not been modified properly")); } - if (point.X() <= xMax() + Kernel::Tolerance && - point.X() >= xMin() - Kernel::Tolerance && - point.Y() <= yMax() + Kernel::Tolerance && - point.Y() >= yMin() - Kernel::Tolerance && - point.Z() <= zMax() + Kernel::Tolerance && - point.Z() >= zMin() - Kernel::Tolerance) { - return true; - } else { - return false; - } + return point.X() <= xMax() + Kernel::Tolerance && + point.X() >= xMin() - Kernel::Tolerance && + point.Y() <= yMax() + Kernel::Tolerance && + point.Y() >= yMin() - Kernel::Tolerance && + point.Z() <= zMax() + Kernel::Tolerance && + point.Z() >= zMin() - Kernel::Tolerance; } /** diff --git a/Framework/Geometry/src/Objects/Object.cpp b/Framework/Geometry/src/Objects/Object.cpp index 4d61efe5820d3ea06ae3e833bbfd9fb74a98197c..fad3d4466bdb62cbbd5fa6c753d2e40bed6b1acf 100644 --- a/Framework/Geometry/src/Objects/Object.cpp +++ b/Framework/Geometry/src/Objects/Object.cpp @@ -1091,8 +1091,8 @@ double Object::triangleSolidAngle(const V3D &observer, std::vector<Kernel::V3D> vectors; this->GetObjectGeom(type, vectors, radius, height); if (type == 1) { - for (size_t i = 0; i < vectors.size(); i++) - vectors[i] *= scaleFactor; + for (auto &vector : vectors) + vector *= scaleFactor; return CuboidSolidAngle(observer, vectors); } else if (type == 2) // this is wrong for scaled objects return SphereSolidAngle(observer, vectors, radius); @@ -1626,13 +1626,13 @@ void Object::calcBoundingBoxByGeometry() { maxX = maxY = maxZ = -huge; // Loop over all corner points to find minima and maxima on each axis - for (auto iter = vectors.cbegin(); iter != vectors.cend(); ++iter) { - minX = std::min(minX, iter->X()); - maxX = std::max(maxX, iter->X()); - minY = std::min(minY, iter->Y()); - maxY = std::max(maxY, iter->Y()); - minZ = std::min(minZ, iter->Z()); - maxZ = std::max(maxZ, iter->Z()); + for (const auto &vector : vectors) { + minX = std::min(minX, vector.X()); + maxX = std::max(maxX, vector.X()); + minY = std::min(minY, vector.Y()); + maxY = std::max(maxY, vector.Y()); + minZ = std::min(minZ, vector.Z()); + maxZ = std::max(maxZ, vector.Z()); } } break; diff --git a/Framework/Geometry/src/Objects/RuleItems.cpp b/Framework/Geometry/src/Objects/RuleItems.cpp index f6b902eca8373cc266ccdeebb768562a5b1da311..1fa1beeaa3c2559aa8800c2b4c9b97b5987eab66 100644 --- a/Framework/Geometry/src/Objects/RuleItems.cpp +++ b/Framework/Geometry/src/Objects/RuleItems.cpp @@ -307,7 +307,7 @@ bool Intersection::isValid(const std::map<int, int> &MX) const { if (!A || !B) return false; - return (A->isValid(MX) && B->isValid(MX)) ? true : false; + return A->isValid(MX) && B->isValid(MX); } int Intersection::simplify() @@ -580,7 +580,7 @@ bool Union::isValid(const Kernel::V3D &Vec) const @retval 0 :: Vec is outside object. */ { - return ((A && A->isValid(Vec)) || (B && B->isValid(Vec))) ? true : false; + return (A && A->isValid(Vec)) || (B && B->isValid(Vec)); } bool Union::isValid(const std::map<int, int> &MX) const @@ -592,7 +592,7 @@ bool Union::isValid(const std::map<int, int> &MX) const @retval 0 :: Neither side is valid */ { - return ((A && A->isValid(MX)) || (B && B->isValid(MX))) ? true : false; + return (A && A->isValid(MX)) || (B && B->isValid(MX)); } std::string Union::display() const @@ -819,7 +819,7 @@ bool SurfPoint::isValid(const std::map<int, int> &MX) const if (lx == MX.end()) return false; const int rtype = (lx->second) ? 1 : -1; - return (rtype * sign) >= 0 ? true : false; + return (rtype * sign) >= 0; } std::string SurfPoint::display() const @@ -1354,7 +1354,7 @@ bool BoolValue::isValid(const Kernel::V3D &pt) const */ { (void)pt; // Avoid compiler warning - return (status > 0) ? true : false; + return status > 0; } bool BoolValue::isValid(const std::map<int, int> &map) const @@ -1365,7 +1365,7 @@ bool BoolValue::isValid(const std::map<int, int> &map) const */ { (void)map; // Avoid compiler warning - return (status > 0) ? true : false; + return status > 0; } int BoolValue::simplify() @@ -1575,7 +1575,7 @@ bool CompGrp::isValid(const std::map<int, int> &SMap) const { // Note:: if isValid is true then return 0: if (A) - return (A->isValid(SMap)) ? false : true; + return !A->isValid(SMap); return true; } diff --git a/Framework/Geometry/src/Rendering/GluGeometryRenderer.cpp b/Framework/Geometry/src/Rendering/GluGeometryRenderer.cpp index b323e0ad994ab0ae7faa3710a8e849838b3c5891..eab44de4fee57285da97d77241fd358243f4913f 100644 --- a/Framework/Geometry/src/Rendering/GluGeometryRenderer.cpp +++ b/Framework/Geometry/src/Rendering/GluGeometryRenderer.cpp @@ -129,14 +129,13 @@ void GluGeometryRenderer::CreateCube(const V3D &Point1, const V3D &Point2, V3D normal; // first face glBegin(GL_QUADS); - for (int i = 0; i < 6; i++) { - normal = - (vertex[faceindex[i][0]] - vertex[faceindex[i][1]]) - .cross_prod((vertex[faceindex[i][0]] - vertex[faceindex[i][2]])); + for (auto &row : faceindex) { + normal = (vertex[row[0]] - vertex[row[1]]) + .cross_prod((vertex[row[0]] - vertex[row[2]])); normal.normalize(); glNormal3d(normal[0], normal[1], normal[2]); for (int j = 0; j < 4; j++) { - int ij = faceindex[i][j]; + int ij = row[j]; if (ij == 0) glTexCoord2i(0, 0); if (ij == 1) diff --git a/Framework/Geometry/src/Rendering/OCGeometryHandler.cpp b/Framework/Geometry/src/Rendering/OCGeometryHandler.cpp index b82c21c7abef491be78eef9b1ad56850ff13c521..5f4dd6569d5757e795c8896cca8202b3c328998c 100644 --- a/Framework/Geometry/src/Rendering/OCGeometryHandler.cpp +++ b/Framework/Geometry/src/Rendering/OCGeometryHandler.cpp @@ -64,7 +64,7 @@ void OCGeometryHandler::Triangulate() { void OCGeometryHandler::Render() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); Renderer->Render(Triangulator->getObjectSurface()); } else if (ObjComp != NULL) { @@ -74,7 +74,7 @@ void OCGeometryHandler::Render() { void OCGeometryHandler::Initialize() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); Renderer->Initialize(Triangulator->getObjectSurface()); } else if (ObjComp != NULL) { @@ -84,7 +84,7 @@ void OCGeometryHandler::Initialize() { int OCGeometryHandler::NumberOfTriangles() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); return Triangulator->getNumberOfTriangles(); } else { @@ -94,7 +94,7 @@ int OCGeometryHandler::NumberOfTriangles() { int OCGeometryHandler::NumberOfPoints() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); return Triangulator->getNumberOfPoints(); } else { @@ -104,7 +104,7 @@ int OCGeometryHandler::NumberOfPoints() { double *OCGeometryHandler::getTriangleVertices() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); return Triangulator->getTriangleVertices(); } else { @@ -114,7 +114,7 @@ double *OCGeometryHandler::getTriangleVertices() { int *OCGeometryHandler::getTriangleFaces() { if (Obj != NULL) { - if (boolTriangulated == false) + if (!boolTriangulated) Triangulate(); return Triangulator->getTriangleFaces(); } else { diff --git a/Framework/ICat/src/CatalogLogout.cpp b/Framework/ICat/src/CatalogLogout.cpp index e8dec03f85de94e631967d868f84a06ddf61ba53..9700320fbfd66f8ca4020f3e468a55557a8c7b9c 100644 --- a/Framework/ICat/src/CatalogLogout.cpp +++ b/Framework/ICat/src/CatalogLogout.cpp @@ -26,12 +26,11 @@ void CatalogLogout::exec() { auto keepAliveInstances = API::AlgorithmManager::Instance().runningInstancesOf("CatalogKeepAlive"); - for (unsigned i = 0; i < keepAliveInstances.size(); ++i) { + for (auto &instance : keepAliveInstances) { auto keepAliveInstance = API::AlgorithmManager::Instance().getAlgorithm( - keepAliveInstances.at(i)->getAlgorithmID()); + instance->getAlgorithmID()); - if (logoutSession == - keepAliveInstances.at(i)->getPropertyValue("Session")) { + if (logoutSession == instance->getPropertyValue("Session")) { keepAliveInstance->cancel(); API::CatalogManager::Instance().destroyCatalog(logoutSession); break; diff --git a/Framework/ICat/src/ICat3/ICat3Helper.cpp b/Framework/ICat/src/ICat3/ICat3Helper.cpp index d350acbaf1cba78f423c7847916fa83f9774a038..14fdfd3ccb06422938def69754ea6ca0190b7a90 100644 --- a/Framework/ICat/src/ICat3/ICat3Helper.cpp +++ b/Framework/ICat/src/ICat3/ICat3Helper.cpp @@ -313,8 +313,8 @@ void CICatHelper::listInstruments(std::vector<std::string> &instruments) { int result = icat.listInstruments(&request, &response); if (result == 0) { - for (unsigned i = 0; i < response.return_.size(); ++i) { - instruments.push_back(response.return_[i]); + for (const auto &instrument : response.return_) { + instruments.push_back(instrument); } } else { CErrorHandling::throwErrorMessages(icat); @@ -339,8 +339,8 @@ void CICatHelper::listInvestigationTypes( int result = icat.listInvestigationTypes(&request, &response); if (result == 0) { - for (unsigned i = 0; i < response.return_.size(); ++i) { - investTypes.push_back(response.return_[i]); + for (const auto &type : response.return_) { + investTypes.push_back(type); } } else { CErrorHandling::throwErrorMessages(icat); diff --git a/Framework/ICat/src/ICat4/ICat4Catalog.cpp b/Framework/ICat/src/ICat4/ICat4Catalog.cpp index 2fe7e1d2ebe997cf044545599d3e4f5d0f8af9b9..b584d496ae3316819fad63f2def85c496199ca82 100644 --- a/Framework/ICat/src/ICat4/ICat4Catalog.cpp +++ b/Framework/ICat/src/ICat4/ICat4Catalog.cpp @@ -443,8 +443,8 @@ void ICat4Catalog::saveDataSets(std::vector<xsd__anyType *> response, } std::string emptyCell = ""; - for (auto iter = response.begin(); iter != response.end(); ++iter) { - ns1__dataset *dataset = dynamic_cast<ns1__dataset *>(*iter); + for (auto &iter : response) { + ns1__dataset *dataset = dynamic_cast<ns1__dataset *>(iter); if (dataset) { API::TableRow table = outputws->appendRow(); @@ -549,8 +549,8 @@ void ICat4Catalog::listInstruments(std::vector<std::string> &instruments) { auto searchResults = performSearch(icat, "Instrument.fullName ORDER BY fullName"); - for (unsigned i = 0; i < searchResults.size(); ++i) { - auto instrument = dynamic_cast<xsd__string *>(searchResults.at(i)); + for (auto &searchResult : searchResults) { + auto instrument = dynamic_cast<xsd__string *>(searchResult); if (instrument) instruments.push_back(instrument->__item); } @@ -568,8 +568,8 @@ void ICat4Catalog::listInvestigationTypes( auto searchResults = performSearch(icat, "InvestigationType.name ORDER BY name"); - for (size_t i = 0; i < searchResults.size(); ++i) { - auto investigationType = dynamic_cast<xsd__string *>(searchResults.at(i)); + for (auto &searchResult : searchResults) { + auto investigationType = dynamic_cast<xsd__string *>(searchResult); if (investigationType) invstTypes.push_back(investigationType->__item); } @@ -802,8 +802,8 @@ int64_t ICat4Catalog::getMantidDatasetId(const std::string &investigationID) { icat, "Dataset <-> Investigation[name = '" + investigationID + "']"); int64_t datasetID = -1; - for (size_t i = 0; i < searchResults.size(); ++i) { - auto dataset = dynamic_cast<ns1__dataset *>(searchResults.at(i)); + for (auto &searchResult : searchResults) { + auto dataset = dynamic_cast<ns1__dataset *>(searchResult); if (dataset && *(dataset->name) == "mantid") datasetID = *(dataset->id); } diff --git a/Framework/Kernel/src/Atom.cpp b/Framework/Kernel/src/Atom.cpp index 43452e3b8d6467c8a4c33a1f2d586910165169f7..023d77e53c18b771b0cd2ac6801bed4d04781e79 100644 --- a/Framework/Kernel/src/Atom.cpp +++ b/Framework/Kernel/src/Atom.cpp @@ -3227,10 +3227,10 @@ Atom getAtom(const std::string &symbol, const uint16_t a_number) { return H3; // linear search - for (size_t i = 0; i < NUM_ATOMS; ++i) { - if (symbol.compare(ATOMS[i].symbol) == 0) { - if (a_number == ATOMS[i].a_number) { - return ATOMS[i]; + for (auto &atom : ATOMS) { + if (symbol.compare(atom.symbol) == 0) { + if (a_number == atom.a_number) { + return atom; } } } diff --git a/Framework/Kernel/src/CompositeValidator.cpp b/Framework/Kernel/src/CompositeValidator.cpp index d0b460a78379de6df3966560fabdfb4101fec428..770bbdc0261f37bf6c4ce59beb59a66d46492c57 100644 --- a/Framework/Kernel/src/CompositeValidator.cpp +++ b/Framework/Kernel/src/CompositeValidator.cpp @@ -20,8 +20,8 @@ std::vector<std::string> CompositeValidator::allowedValues() const { std::multiset<std::string> elem_all; // how many validators return non-empty list of allowed values int n_combinations(0); - for (auto itr = m_children.cbegin(); itr != m_children.cend(); ++itr) { - std::vector<std::string> subs = (*itr)->allowedValues(); + for (const auto &itr : m_children) { + std::vector<std::string> subs = itr->allowedValues(); if (subs.empty()) continue; elem_unique.insert(subs.begin(), subs.end()); @@ -32,13 +32,13 @@ std::vector<std::string> CompositeValidator::allowedValues() const { if (n_combinations < 2) return std::vector<std::string>(elem_unique.begin(), elem_unique.end()); // there is more then one combination and we have to identify its union; - for (auto its = elem_unique.cbegin(); its != elem_unique.cend(); ++its) { - auto im = elem_all.find(*its); + for (const auto &its : elem_unique) { + auto im = elem_all.find(its); elem_all.erase(im); } std::set<std::string> rez; - for (auto im = elem_all.cbegin(); im != elem_all.cend(); ++im) { - rez.insert(*im); + for (const auto &im : elem_all) { + rez.insert(im); } return std::vector<std::string>(rez.begin(), rez.end()); } @@ -50,8 +50,8 @@ std::vector<std::string> CompositeValidator::allowedValues() const { Kernel::IValidator_sptr CompositeValidator::clone() const { boost::shared_ptr<CompositeValidator> copy = boost::make_shared<CompositeValidator>(); - for (auto itr = m_children.cbegin(); itr != m_children.end(); ++itr) { - copy->add((*itr)->clone()); + for (const auto &itr : m_children) { + copy->add(itr->clone()); } return copy; } diff --git a/Framework/Kernel/src/ConfigService.cpp b/Framework/Kernel/src/ConfigService.cpp index d62c8b6bc6e9947e97a17da6924d2bf0f3b564a5..d456154679991c76f42b6255dba1ecb6ac9fd645 100644 --- a/Framework/Kernel/src/ConfigService.cpp +++ b/Framework/Kernel/src/ConfigService.cpp @@ -1000,12 +1000,12 @@ void ConfigServiceImpl::getKeysRecursive( if (rootKeys.empty()) allKeys.push_back(root); - for (auto rkIt = rootKeys.begin(); rkIt != rootKeys.end(); ++rkIt) { + for (auto &rootKey : rootKeys) { std::string searchString; if (root.empty()) { - searchString = *rkIt; + searchString = rootKey; } else { - searchString = root + "." + *rkIt; + searchString = root + "." + rootKey; } getKeysRecursive(searchString, allKeys); @@ -1063,10 +1063,7 @@ bool ConfigServiceImpl::isExecutable(const std::string &target) const { Poco::File tempFile = Poco::File(expTarget); if (tempFile.exists()) { - if (tempFile.canExecute()) - return true; - else - return false; + return tempFile.canExecute(); } else return false; } catch (Poco::Exception &) { @@ -1775,8 +1772,8 @@ void ConfigServiceImpl::updateFacilities(const std::string &fName) { /// Empty the list of facilities, deleting the FacilityInfo objects in the /// process void ConfigServiceImpl::clearFacilities() { - for (auto it = m_facilities.begin(); it != m_facilities.end(); ++it) { - delete *it; + for (auto &facility : m_facilities) { + delete facility; } m_facilities.clear(); } @@ -1805,11 +1802,11 @@ ConfigServiceImpl::getInstrument(const std::string &instrumentName) const { } // Now let's look through the other facilities - for (auto it = m_facilities.cbegin(); it != m_facilities.cend(); ++it) { + for (auto facility : m_facilities) { try { g_log.debug() << "Looking for " << instrumentName << " at " - << (**it).name() << "." << std::endl; - return (**it).instrument(instrumentName); + << (*facility).name() << "." << std::endl; + return (*facility).instrument(instrumentName); } catch (Exception::NotFoundError &) { // Well the instName doesn't exist for this facility... // Move along, there's nothing to see here... @@ -1865,9 +1862,9 @@ ConfigServiceImpl::getFacility(const std::string &facilityName) const { if (facilityName.empty()) return this->getFacility(); - for (auto it = m_facilities.begin(); it != m_facilities.end(); ++it) { - if ((**it).name() == facilityName) { - return **it; + for (auto facility : m_facilities) { + if ((*facility).name() == facilityName) { + return *facility; } } diff --git a/Framework/Kernel/src/DateAndTime.cpp b/Framework/Kernel/src/DateAndTime.cpp index 1597f3bba02c47bbf11f5aad03302f1ae7fc34e0..53ae5894b236c7bcb9f3f9e45739951aa89c5501 100644 --- a/Framework/Kernel/src/DateAndTime.cpp +++ b/Framework/Kernel/src/DateAndTime.cpp @@ -863,9 +863,9 @@ void DateAndTime::createVector(const DateAndTime start, size_t num = seconds.size(); out.resize(num); size_t i = 0; - for (auto it = seconds.begin(); it != seconds.end(); ++it) { + for (double second : seconds) { out[i]._nanoseconds = - startnano + static_cast<int64_t>((*it) * 1000000000.0); + startnano + static_cast<int64_t>(second * 1000000000.0); i++; } } diff --git a/Framework/Kernel/src/DeltaEMode.cpp b/Framework/Kernel/src/DeltaEMode.cpp index 6bbab1943830fc3fd2cc41a40b406ae5cdbaae3e..5a9181b96c28670792dfa4108ab91147377ba928 100644 --- a/Framework/Kernel/src/DeltaEMode.cpp +++ b/Framework/Kernel/src/DeltaEMode.cpp @@ -33,10 +33,10 @@ const std::vector<std::string> DeltaEMode::availableTypes() { std::vector<std::string> modes; modes.reserve(lookup.index.size()); size_t index(0); - for (auto iter = lookup.index.begin(); iter != lookup.index.end(); ++iter) { - if (iter->first == DeltaEMode::Undefined) + for (const auto &iter : lookup.index) { + if (iter.first == DeltaEMode::Undefined) continue; - modes.push_back(iter->second); + modes.push_back(iter.second); ++index; } return modes; @@ -66,10 +66,10 @@ std::string DeltaEMode::asString(const Type mode) { */ DeltaEMode::Type DeltaEMode::fromString(const std::string &modeStr) { const ModeIndex &lookup = typeStringLookup(); - for (auto iter = lookup.index.begin(); iter != lookup.index.end(); ++iter) { - if (boost::iequals(modeStr, iter->second)) // case-insensitive + for (const auto &iter : lookup.index) { + if (boost::iequals(modeStr, iter.second)) // case-insensitive { - return iter->first; + return iter.first; } } // Unknown mode diff --git a/Framework/Kernel/src/FacilityInfo.cpp b/Framework/Kernel/src/FacilityInfo.cpp index d7c68818899f05e38c98f3a2ff9d698975f4d67c..fc6d5bacbf19999d85139e0ac3bf8f2bbdf9eaec 100644 --- a/Framework/Kernel/src/FacilityInfo.cpp +++ b/Framework/Kernel/src/FacilityInfo.cpp @@ -75,8 +75,8 @@ void FacilityInfo::fillExtensions(const Poco::XML::Element *elem) { typedef Poco::StringTokenizer tokenizer; tokenizer exts(extsStr, ",", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); - for (auto it = exts.begin(); it != exts.end(); ++it) { - addExtension(*it); + for (const auto &ext : exts) { + addExtension(ext); } } @@ -190,22 +190,25 @@ const InstrumentInfo &FacilityInfo::instrument(std::string iName) const { } } - for (auto it = m_instruments.cbegin(); it != m_instruments.cend(); ++it) { - if (boost::iequals(it->name(), iName)) // Case-insensitive search + for (const auto &instrument : m_instruments) { + if (boost::iequals(instrument.name(), iName)) // Case-insensitive search { - g_log.debug() << "Instrument '" << iName << "' found as " << it->name() - << " at " << name() << "." << std::endl; - return *it; + g_log.debug() << "Instrument '" << iName << "' found as " + << instrument.name() << " at " << name() << "." + << std::endl; + return instrument; } } // if unsuccessful try shortname - for (auto it = m_instruments.begin(); it != m_instruments.end(); ++it) { - if (boost::iequals(it->shortName(), iName)) // Case-insensitive search + for (const auto &instrument : m_instruments) { + if (boost::iequals(instrument.shortName(), + iName)) // Case-insensitive search { - g_log.debug() << "Instrument '" << iName << "' found as " << it->name() - << " at " << name() << "." << std::endl; - return *it; + g_log.debug() << "Instrument '" << iName << "' found as " + << instrument.name() << " at " << name() << "." + << std::endl; + return instrument; } } diff --git a/Framework/Kernel/src/FileValidator.cpp b/Framework/Kernel/src/FileValidator.cpp index ed0ed61793d02b723b96bf788d6ad13a2c7e917d..ae929f1d345ba14c862b10229a9f8d1195c25e0a 100644 --- a/Framework/Kernel/src/FileValidator.cpp +++ b/Framework/Kernel/src/FileValidator.cpp @@ -21,8 +21,8 @@ FileValidator::FileValidator(const std::vector<std::string> &extensions, bool testFileExists, bool testCanWrite) : TypedValidator<std::string>(), m_testExist(testFileExists), m_testCanWrite(testCanWrite) { - for (auto it = extensions.begin(); it != extensions.end(); ++it) { - const std::string ext = boost::to_lower_copy(*it); + for (const auto &extension : extensions) { + const std::string ext = boost::to_lower_copy(extension); if (std::find(m_extensions.begin(), m_extensions.end(), ext) == m_extensions.end()) { m_extensions.push_back(ext); @@ -66,9 +66,8 @@ std::string FileValidator::checkValidity(const std::string &value) const { g_log.debug() << "Unrecognised extension in file \"" << value << "\""; if (!this->m_extensions.empty()) { g_log.debug() << " [ "; - for (auto it = this->m_extensions.begin(); - it != this->m_extensions.end(); ++it) - g_log.debug() << *it << " "; + for (const auto &extension : this->m_extensions) + g_log.debug() << extension << " "; g_log.debug() << "]"; } g_log.debug() << "\"." << std::endl; @@ -166,10 +165,10 @@ bool FileValidator::endswith(const std::string &value) const { tolower); // check for the ending - for (auto it = m_extensions.begin(); it != m_extensions.end(); ++it) { - if (has_ending(value, *it)) // original case + for (const auto &extension : m_extensions) { + if (has_ending(value, extension)) // original case return true; - if (has_ending(value_copy, *it)) // lower case + if (has_ending(value_copy, extension)) // lower case return true; } return false; diff --git a/Framework/Kernel/src/FilterChannel.cpp b/Framework/Kernel/src/FilterChannel.cpp index c6dab197e19ac841f9ce65520453d0ba5fd0842d..d1bc72823d405c4b0e894ce4bd35357b1307ec7f 100644 --- a/Framework/Kernel/src/FilterChannel.cpp +++ b/Framework/Kernel/src/FilterChannel.cpp @@ -25,8 +25,8 @@ void FilterChannel::setProperty(const std::string &name, if (name.compare(0, 7, "channel") == 0) { StringTokenizer tokenizer(value, ",;", StringTokenizer::TOK_IGNORE_EMPTY | StringTokenizer::TOK_TRIM); - for (auto it = tokenizer.begin(); it != tokenizer.end(); ++it) { - addChannel(LoggingRegistry::defaultRegistry().channelForName(*it)); + for (const auto &piece : tokenizer) { + addChannel(LoggingRegistry::defaultRegistry().channelForName(piece)); } } else if (name.compare(0, 5, "level") == 0) { setPriority(value); diff --git a/Framework/Kernel/src/IPropertyManager.cpp b/Framework/Kernel/src/IPropertyManager.cpp index e6458d0d02ab7a82d3611bc7e6340c11e35a1823..5d2b8ed774e5f65a6b55f070757f9077730a3eda 100644 --- a/Framework/Kernel/src/IPropertyManager.cpp +++ b/Framework/Kernel/src/IPropertyManager.cpp @@ -72,10 +72,10 @@ bool IPropertyManager::existsProperty(const std::string &name) const { */ void IPropertyManager::updatePropertyValues(const IPropertyManager &other) { auto props = this->getProperties(); - for (auto prop = props.begin(); prop != props.end(); ++prop) { - const std::string propName = (**prop).name(); + for (auto &prop : props) { + const std::string propName = (*prop).name(); if (other.existsProperty(propName)) { - (**prop).setValueFromProperty(*other.getPointerToProperty(propName)); + (*prop).setValueFromProperty(*other.getPointerToProperty(propName)); } } } diff --git a/Framework/Kernel/src/InternetHelper.cpp b/Framework/Kernel/src/InternetHelper.cpp index e2f21895d198aea3e7e61d3caf810207bf3f66d0..1e8447bb9446c57c1dde8b4fe656f71467448377 100644 --- a/Framework/Kernel/src/InternetHelper.cpp +++ b/Framework/Kernel/src/InternetHelper.cpp @@ -108,9 +108,8 @@ void InternetHelper::createRequest(Poco::URI &uri) { m_request->setContentLength(m_contentLength); } - for (auto itHeaders = m_headers.begin(); itHeaders != m_headers.end(); - ++itHeaders) { - m_request->set(itHeaders->first, itHeaders->second); + for (auto &header : m_headers) { + m_request->set(header.first, header.second); } if (m_method == "POST") { diff --git a/Framework/Kernel/src/LibraryManager.cpp b/Framework/Kernel/src/LibraryManager.cpp index 4f3997751cc0ae29904422904dc5ce8623149af6..a4af868c88621e6ee484949129ab1fd13a1ef3f4 100644 --- a/Framework/Kernel/src/LibraryManager.cpp +++ b/Framework/Kernel/src/LibraryManager.cpp @@ -89,8 +89,8 @@ bool LibraryManagerImpl::skip(const std::string &filename) { initialized = true; } bool skipme(false); - for (auto itr = excludes.begin(); itr != excludes.end(); ++itr) { - if (filename.find(*itr) != std::string::npos) { + for (const auto &exclude : excludes) { + if (filename.find(exclude) != std::string::npos) { skipme = true; break; } diff --git a/Framework/Kernel/src/MDAxisValidator.cpp b/Framework/Kernel/src/MDAxisValidator.cpp index 2d31271abaebf790218284c715162899a6ae7478..c2ab3086ec97f8ff10a40a8285a38913497939f7 100644 --- a/Framework/Kernel/src/MDAxisValidator.cpp +++ b/Framework/Kernel/src/MDAxisValidator.cpp @@ -12,11 +12,7 @@ namespace Kernel { MDAxisValidator::MDAxisValidator(const std::vector<int> &axes, const size_t nDimensions, const bool checkIfEmpty) - : m_wsDimensions(nDimensions), m_emptyCheck(checkIfEmpty) { - for (auto iter = axes.begin(); iter != axes.end(); iter++) { - m_axes.push_back(*iter); - } -} + : m_axes(axes), m_wsDimensions(nDimensions), m_emptyCheck(checkIfEmpty) {} //---------------------------------------------------------------------------------------------- /** Destructor diff --git a/Framework/Kernel/src/MandatoryValidator.cpp b/Framework/Kernel/src/MandatoryValidator.cpp index 57a04db6d0a1c49580839eaa5769bdca9cf8c6e6..e942e808b4a0dcf82dee4d90d364c9a84d941d65 100644 --- a/Framework/Kernel/src/MandatoryValidator.cpp +++ b/Framework/Kernel/src/MandatoryValidator.cpp @@ -23,10 +23,7 @@ template <> DLLExport bool checkIsEmpty(const std::string &value) { * @return True if the value is considered empty, see EmptyValues.h */ template <> DLLExport bool checkIsEmpty(const double &value) { - if (std::fabs(value - Mantid::EMPTY_DBL()) < 1e-08) - return true; - else - return false; + return std::fabs(value - Mantid::EMPTY_DBL()) < 1e-08; } /** * Specialization of checkIsEmpty for int diff --git a/Framework/Kernel/src/Matrix.cpp b/Framework/Kernel/src/Matrix.cpp index 32f53368f0e29959661d331d755269d6d030ff68..6e24babbb4c145b99f14c891a10fe4441452d05f 100644 --- a/Framework/Kernel/src/Matrix.cpp +++ b/Framework/Kernel/src/Matrix.cpp @@ -94,7 +94,7 @@ Matrix<T>::Matrix(const size_t nrow, const size_t ncol, const bool makeIdentity) // Note:: nx,ny zeroed so setMem always works setMem(nrow, ncol); zeroMatrix(); - if (makeIdentity == true) + if (makeIdentity) identityMatrix(); } diff --git a/Framework/Kernel/src/MultiFileNameParser.cpp b/Framework/Kernel/src/MultiFileNameParser.cpp index 61238cc58744b252ec0f3ced9ffebf3f68062e24..9d542367f4a9525e62171d79a7c8c3e2c8fe2939 100644 --- a/Framework/Kernel/src/MultiFileNameParser.cpp +++ b/Framework/Kernel/src/MultiFileNameParser.cpp @@ -153,8 +153,8 @@ std::string suggestWorkspaceName(const std::vector<std::string> &fileNames) { // For each file name, parse the run number out of it, and add it to a // RunRangeList. - for (size_t i = 0; i < fileNames.size(); ++i) { - parser.parse(fileNames[i]); + for (const auto &fileName : fileNames) { + parser.parse(fileName); runs.addRun(parser.runs()[0][0]); } @@ -198,15 +198,12 @@ Parser::Parser() ConfigServiceImpl &config = ConfigService::Instance(); auto facilities = config.getFacilities(); - for (auto itFacility = facilities.begin(); itFacility != facilities.end(); - ++itFacility) { - const std::vector<InstrumentInfo> instruments = - (**itFacility).instruments(); - - for (auto instrument = instruments.begin(); instrument != instruments.end(); - ++instrument) { - m_validInstNames.insert(instrument->name()); - m_validInstNames.insert(instrument->shortName()); + for (auto &facility : facilities) { + const std::vector<InstrumentInfo> instruments = (*facility).instruments(); + + for (const auto &instrument : instruments) { + m_validInstNames.insert(instrument.name()); + m_validInstNames.insert(instrument.shortName()); } } } @@ -300,11 +297,10 @@ void Parser::split() { throw std::runtime_error("There does not appear to be any runs present."); // See if the user has typed in one of the available instrument names. - for (auto instName = m_validInstNames.begin(); - instName != m_validInstNames.end(); ++instName) { + for (const auto &validInstName : m_validInstNames) { // USE CASELESS MATCHES HERE. - if (matchesFully(base, *instName + ".*", true)) { - m_instString = getMatchingString("^" + *instName, base, true); + if (matchesFully(base, validInstName + ".*", true)) { + m_instString = getMatchingString("^" + validInstName, base, true); break; } } diff --git a/Framework/Kernel/src/MultiFileValidator.cpp b/Framework/Kernel/src/MultiFileValidator.cpp index 97e01e8840028525152ec30731bf9ad4712a0258..cd779904e60bcaa66f3ac74574cf1dbe675078ac 100644 --- a/Framework/Kernel/src/MultiFileValidator.cpp +++ b/Framework/Kernel/src/MultiFileValidator.cpp @@ -56,18 +56,17 @@ std::string MultiFileValidator::checkValidity( std::string accumulatedErrors(""); - for (auto rowIt = values.cbegin(); rowIt != values.cend(); ++rowIt) { - std::vector<std::string> row = (*rowIt); - for (auto valueIt = row.cbegin(); valueIt != row.cend(); ++valueIt) { + for (auto row : values) { + for (const auto &valueIt : row) { // For each filename value, check its validity, and and accumulate any // errors. - std::string error = m_fileValidator.isValid(*valueIt); + std::string error = m_fileValidator.isValid(valueIt); if (!error.empty()) { if (accumulatedErrors.empty()) accumulatedErrors = - "Could not validate the following file(s): " + (*valueIt); + "Could not validate the following file(s): " + valueIt; else - accumulatedErrors = accumulatedErrors + ", " + (*valueIt); + accumulatedErrors = accumulatedErrors + ", " + valueIt; } } } diff --git a/Framework/Kernel/src/NetworkProxyOSX.cpp b/Framework/Kernel/src/NetworkProxyOSX.cpp index 59b316f5195eafe7737ac01c720858af46751dae..513cb60bb533aedc1f37ca199082f142c32c0ade 100644 --- a/Framework/Kernel/src/NetworkProxyOSX.cpp +++ b/Framework/Kernel/src/NetworkProxyOSX.cpp @@ -219,11 +219,10 @@ ProxyInfo findHttpProxy(const std::string &targetURLString, ProxyInfoVec info = proxyInformationFromPac(dict, targetURLString, logger); bool foundHttpProxy = false; - for (auto it = info.begin(); it != info.end(); ++it) { - ProxyInfo proxyInfo = *it; + for (const auto &proxyInfo : info) { if (proxyInfo.isHttpProxy()) { foundHttpProxy = true; - httpProxy = *it; + httpProxy = proxyInfo; break; } } diff --git a/Framework/Kernel/src/NexusDescriptor.cpp b/Framework/Kernel/src/NexusDescriptor.cpp index 23da9f1955b19d550ba590d4c4d0c1862b8368f8..a20aa7ecb9ce752e79ba532698085a368cf041b3 100644 --- a/Framework/Kernel/src/NexusDescriptor.cpp +++ b/Framework/Kernel/src/NexusDescriptor.cpp @@ -235,8 +235,8 @@ void NexusDescriptor::walkFile(::NeXus::File &file, const std::string &rootPath, } if (level == 0) { auto attrInfos = file.getAttrInfos(); - for (size_t i = 0; i < attrInfos.size(); ++i) { - m_rootAttrs.insert(attrInfos[i].name); + for (auto &attrInfo : attrInfos) { + m_rootAttrs.insert(attrInfo.name); } } diff --git a/Framework/Kernel/src/OptionalBool.cpp b/Framework/Kernel/src/OptionalBool.cpp index de502260e59fd79b3f2f6e063d4aebd759fdb66d..b6306c6b802dcde00f6a42a91b1a6fdaa808117c 100644 --- a/Framework/Kernel/src/OptionalBool.cpp +++ b/Framework/Kernel/src/OptionalBool.cpp @@ -59,8 +59,8 @@ std::map<std::string, OptionalBool::Value> OptionalBool::strToEmumMap() { std::map<OptionalBool::Value, std::string> OptionalBool::enumToStrMap() { std::map<Value, std::string> map; auto opposite = strToEmumMap(); - for (auto it = opposite.begin(); it != opposite.end(); ++it) { - map.emplace(it->second, it->first); + for (auto &oppositePair : opposite) { + map.emplace(oppositePair.second, oppositePair.first); } return map; } diff --git a/Framework/Kernel/src/PropertyManager.cpp b/Framework/Kernel/src/PropertyManager.cpp index 5641fe152c761228fd4f2ede1f8b16c0183be69e..6647550964dcd28495bd121503b54298b7a84839 100644 --- a/Framework/Kernel/src/PropertyManager.cpp +++ b/Framework/Kernel/src/PropertyManager.cpp @@ -41,8 +41,8 @@ PropertyManager::PropertyManager(const PropertyManager &other) PropertyManager &PropertyManager::operator=(const PropertyManager &other) { // We need to do a deep copy here if (this != &other) { - for (auto it = m_properties.begin(); it != m_properties.end(); ++it) { - delete it->second; + for (auto &property : m_properties) { + delete property.second; } this->m_properties.clear(); this->m_orderedProperties.resize(other.m_orderedProperties.size()); @@ -162,15 +162,14 @@ void PropertyManager::filterByProperty( const Kernel::TimeSeriesProperty<bool> &filter) { const bool transferOwnership( true); // Make the new FilteredProperty own the original time series - for (auto iter = m_orderedProperties.begin(); - iter != m_orderedProperties.end(); ++iter) { - Property *currentProp = *iter; + for (auto &orderedProperty : m_orderedProperties) { + Property *currentProp = orderedProperty; if (auto doubleSeries = dynamic_cast<TimeSeriesProperty<double> *>(currentProp)) { auto filtered = new FilteredTimeSeriesProperty<double>( doubleSeries, filter, transferOwnership); // Replace the property in the ordered properties list - (*iter) = filtered; + orderedProperty = filtered; // Now replace in the map const std::string key = createKey(currentProp->name()); this->m_properties[key] = filtered; @@ -402,12 +401,12 @@ bool PropertyManager::existsProperty(const std::string &name) const { */ bool PropertyManager::validateProperties() const { bool allValid = true; - for (auto it = m_properties.cbegin(); it != m_properties.cend(); ++it) { + for (const auto &property : m_properties) { // check for errors in each property - std::string error = it->second->isValid(); + std::string error = property.second->isValid(); //"" means no error if (!error.empty()) { - g_log.error() << "Property \"" << it->first + g_log.error() << "Property \"" << property.first << "\" is not set to a valid value: \"" << error << "\"." << std::endl; allValid = false; @@ -575,8 +574,8 @@ void PropertyManager::removeProperty(const std::string &name, */ void PropertyManager::clear() { m_orderedProperties.clear(); - for (auto it = m_properties.begin(); it != m_properties.end(); ++it) { - delete it->second; + for (auto &property : m_properties) { + delete property.second; } m_properties.clear(); } diff --git a/Framework/Kernel/src/Quat.cpp b/Framework/Kernel/src/Quat.cpp index fe600ec5e6632e82dfd2818fcd1ac52503c14212..c3d097f5ac05090fa8d473fee0704878445f0cf8 100644 --- a/Framework/Kernel/src/Quat.cpp +++ b/Framework/Kernel/src/Quat.cpp @@ -352,10 +352,8 @@ Quat &Quat::operator*=(const Quat &_q) { */ bool Quat::operator==(const Quat &q) const { using namespace std; - return (fabs(w - q.w) > Tolerance || fabs(a - q.a) > Tolerance || - fabs(b - q.b) > Tolerance || fabs(c - q.c) > Tolerance) - ? false - : true; + return !(fabs(w - q.w) > Tolerance || fabs(a - q.a) > Tolerance || + fabs(b - q.b) > Tolerance || fabs(c - q.c) > Tolerance); // return (quat_tol(w,q.w) && quat_tol(a,q.a) && quat_tol(b,q.b) && // quat_tol(c,q.c)); diff --git a/Framework/Kernel/src/StartsWithValidator.cpp b/Framework/Kernel/src/StartsWithValidator.cpp index bdd4660a4f5f60a53979811ff1b1c42b1e908ed6..c319babdccbbd86748c93b20c7747885264ce214 100644 --- a/Framework/Kernel/src/StartsWithValidator.cpp +++ b/Framework/Kernel/src/StartsWithValidator.cpp @@ -12,8 +12,8 @@ namespace Kernel { * any of the allowed values" */ std::string StartsWithValidator::checkValidity(const std::string &value) const { - for (auto it = m_allowedValues.begin(); it != m_allowedValues.end(); ++it) { - if (value.substr(0, it->size()) == *it) { + for (const auto &allowedValue : m_allowedValues) { + if (value.substr(0, allowedValue.size()) == allowedValue) { return ""; } } diff --git a/Framework/Kernel/src/Strings.cpp b/Framework/Kernel/src/Strings.cpp index 74e8eb569e9ad5cfd3548ec93cd55fa5bcb3a3be..99e69ed0887a501c1af41de9f67b573d0acfc85f 100644 --- a/Framework/Kernel/src/Strings.cpp +++ b/Framework/Kernel/src/Strings.cpp @@ -266,10 +266,10 @@ int getPartLine(std::istream &fh, std::string &Out, std::string &Excess, std::string removeSpace(const std::string &CLine) { std::string Out; char prev = 'x'; - for (unsigned int i = 0; i < CLine.length(); i++) { - if (!isspace(CLine[i]) || prev == '\\') { - Out += CLine[i]; - prev = CLine[i]; + for (char character : CLine) { + if (!isspace(character) || prev == '\\') { + Out += character; + prev = character; } } return Out; @@ -439,8 +439,8 @@ splitToKeyValues(const std::string &input, const std::string &keyValSep, const int splitOptions = Poco::StringTokenizer::TOK_IGNORE_EMPTY + Poco::StringTokenizer::TOK_TRIM; Poco::StringTokenizer listSplitter(input, listSep); - for (auto iter = listSplitter.begin(); iter != listSplitter.end(); ++iter) { - Poco::StringTokenizer keyValSplitter(*iter, keyValSep, splitOptions); + for (const auto &iter : listSplitter) { + Poco::StringTokenizer keyValSplitter(iter, keyValSep, splitOptions); if (keyValSplitter.count() == 2) { keyValues[keyValSplitter[0]] = keyValSplitter[1]; } @@ -1075,9 +1075,9 @@ std::vector<int> parseRange(const std::string &str, const std::string &elemSep, // Estimation of the resulting number of elements result.reserve(elements->count()); - for (auto it = elements->begin(); it != elements->end(); it++) { + for (const auto &elementString : *elements) { // See above for the reason space is added - Tokenizer rangeElements(*it + " ", rangeSep, Tokenizer::TOK_TRIM); + Tokenizer rangeElements(elementString + " ", rangeSep, Tokenizer::TOK_TRIM); size_t noOfRangeElements = rangeElements.count(); @@ -1085,7 +1085,7 @@ std::vector<int> parseRange(const std::string &str, const std::string &elemSep, if (noOfRangeElements == 1) { int element; if (convert(rangeElements[0], element) != 1) - throw std::invalid_argument("Invalid element: " + *it); + throw std::invalid_argument("Invalid element: " + elementString); result.push_back(element); } // A pair @@ -1094,17 +1094,19 @@ std::vector<int> parseRange(const std::string &str, const std::string &elemSep, if (convert(rangeElements[0], start) != 1 || convert(rangeElements[1], end) != 1) - throw std::invalid_argument("Invalid range: " + *it); + throw std::invalid_argument("Invalid range: " + elementString); if (start >= end) - throw std::invalid_argument("Range boundaries are reversed: " + *it); + throw std::invalid_argument("Range boundaries are reversed: " + + elementString); for (int i = start; i <= end; i++) result.push_back(i); } // Error - e.g. "--"" else { - throw std::invalid_argument("Multiple range separators: " + *it); + throw std::invalid_argument("Multiple range separators: " + + elementString); } } diff --git a/Framework/Kernel/src/ThreadPool.cpp b/Framework/Kernel/src/ThreadPool.cpp index 43115fc93d7d52b79c50d97f9c418edd28abbcdf..716a1d514c16a19fa1388198e56534d58ccaf5c8 100644 --- a/Framework/Kernel/src/ThreadPool.cpp +++ b/Framework/Kernel/src/ThreadPool.cpp @@ -78,10 +78,10 @@ void ThreadPool::start(double waitSec) { throw std::runtime_error("Threads have already started."); // Delete any old threads (they should NOT be running!) - for (size_t i = 0; i < m_threads.size(); ++i) - delete m_threads[i]; - for (size_t i = 0; i < m_runnables.size(); ++i) - delete m_runnables[i]; + for (auto &thread : m_threads) + delete thread; + for (auto &runnable : m_runnables) + delete runnable; // Now, launch that many threads and let them wait for new tasks. m_threads.clear(); @@ -143,8 +143,8 @@ void ThreadPool::joinAll() { if (m_started) { m_started = false; // If any of the threads are running, then YES, it is really started. - for (size_t i = 0; i < m_threads.size(); ++i) - m_started = m_started || m_threads[i]->isRunning(); + for (auto &thread : m_threads) + m_started = m_started || thread->isRunning(); } // Start all the threads if they were not already. @@ -152,21 +152,21 @@ void ThreadPool::joinAll() { this->start(); // Clear any wait times so that the threads stop waiting for new tasks. - for (size_t i = 0; i < m_runnables.size(); i++) - m_runnables[i]->clearWait(); + for (auto &runnable : m_runnables) + runnable->clearWait(); // Sequentially join all the threads. - for (size_t i = 0; i < m_threads.size(); i++) { - m_threads[i]->join(); - delete m_threads[i]; + for (auto &thread : m_threads) { + thread->join(); + delete thread; } // Clear the vectors (the threads are deleted now). m_threads.clear(); // Get rid of the runnables too - for (size_t i = 0; i < m_runnables.size(); i++) - delete m_runnables[i]; + for (auto &runnable : m_runnables) + delete runnable; m_runnables.clear(); // This will make threads restart diff --git a/Framework/Kernel/src/TimeSeriesProperty.cpp b/Framework/Kernel/src/TimeSeriesProperty.cpp index 31350691e35404fc5eb998370278e358e80ce2c9..0c4983eb03814279b13cd1c1dfe69ed2b9953756 100644 --- a/Framework/Kernel/src/TimeSeriesProperty.cpp +++ b/Framework/Kernel/src/TimeSeriesProperty.cpp @@ -343,8 +343,7 @@ void TimeSeriesProperty<TYPE>::filterByTimes( << " Original MP Size = " << m_values.size() << "\n"; // 4. Create new - for (size_t isp = 0; isp < splittervec.size(); ++isp) { - Kernel::SplittingInterval splitter = splittervec[isp]; + for (auto splitter : splittervec) { Kernel::DateAndTime t_start = splitter.start(); Kernel::DateAndTime t_stop = splitter.stop(); @@ -752,16 +751,16 @@ double TimeSeriesProperty<TYPE>::averageValueInFilter( double numerator(0.0), totalTime(0.0); // Loop through the filter ranges - for (auto it = filter.cbegin(); it != filter.cend(); ++it) { + for (const auto &time : filter) { // Calculate the total time duration (in seconds) within by the filter - totalTime += it->duration(); + totalTime += time.duration(); // Get the log value and index at the start time of the filter int index; - double value = getSingleValue(it->start(), index); - DateAndTime startTime = it->start(); + double value = getSingleValue(time.start(), index); + DateAndTime startTime = time.start(); - while (index < realSize() - 1 && m_values[index + 1].time() < it->stop()) { + while (index < realSize() - 1 && m_values[index + 1].time() < time.stop()) { ++index; numerator += DateAndTime::secondsFromDuration(m_values[index].time() - startTime) * @@ -772,7 +771,7 @@ double TimeSeriesProperty<TYPE>::averageValueInFilter( // Now close off with the end of the current filter range numerator += - DateAndTime::secondsFromDuration(it->stop() - startTime) * value; + DateAndTime::secondsFromDuration(time.stop() - startTime) * value; } // 'Normalise' by the total time diff --git a/Framework/Kernel/src/UserStringParser.cpp b/Framework/Kernel/src/UserStringParser.cpp index 98027dcea60bd1b42d41eb7b7ae06ddda2f908c4..8e3c96b0e18ca247f7a378c1701589699516ff42 100644 --- a/Framework/Kernel/src/UserStringParser.cpp +++ b/Framework/Kernel/src/UserStringParser.cpp @@ -78,7 +78,7 @@ void UserStringParser::parse(const std::string &userString, */ bool UserStringParser::Contains(const std::string &input, char ch) { std::string::size_type pos = input.find(ch); - return (pos == std::string::npos ? false : true); + return (pos != std::string::npos); } /**This method parses a given string of numbers into comma separated tokens. @@ -191,7 +191,7 @@ bool UserStringParser::isValidStepSeparator(const std::string &input, step_separator = input.substr(index - 1, 1); } // step values must be preceded by colon ':' - return (!step_separator.compare(":") ? true : false); + return (!step_separator.compare(":")); } return true; } diff --git a/Framework/Kernel/src/V3D.cpp b/Framework/Kernel/src/V3D.cpp index fc9ef31b403d5923fdb627ecd8687344d357bd96..8db36ed8b80dbfd2c664cf1abf5affbab492bec4 100644 --- a/Framework/Kernel/src/V3D.cpp +++ b/Framework/Kernel/src/V3D.cpp @@ -506,7 +506,7 @@ void V3D::rotate(const Kernel::Matrix<double> &A) bool V3D::coLinear(const V3D &Bv, const V3D &Cv) const { const V3D &Av = *this; const V3D Tmp((Bv - Av).cross_prod(Cv - Av)); - return (Tmp.norm() > Tolerance) ? false : true; + return Tmp.norm() <= Tolerance; } bool V3D::nullVector(const double Tol) const diff --git a/Framework/Kernel/src/VMD.cpp b/Framework/Kernel/src/VMD.cpp index 6bcf7be307c63d5934b35a740fb62628123a70dd..59bfe4a12a2153685dc36509edb027bd07ec46f0 100644 --- a/Framework/Kernel/src/VMD.cpp +++ b/Framework/Kernel/src/VMD.cpp @@ -43,8 +43,9 @@ VMDBase<TYPE>::makeVectorsOrthogonal(std::vector<VMDBase> &vectors) { out = V3D::makeVectorsOrthogonal(in); std::vector<VMDBase> retVal; - for (size_t i = 0; i < out.size(); i++) - retVal.push_back(VMDBase(out[i])); + retVal.reserve(out.size()); + for (auto &vector : out) + retVal.emplace_back(vector); return retVal; } diff --git a/Framework/Kernel/src/VectorHelper.cpp b/Framework/Kernel/src/VectorHelper.cpp index 914a2d86cb817f00463417a6bdb9912aecd3074e..a8b27f440a25528ce9b91191653b3389880d830c 100644 --- a/Framework/Kernel/src/VectorHelper.cpp +++ b/Framework/Kernel/src/VectorHelper.cpp @@ -451,10 +451,10 @@ std::vector<NumT> splitStringIntoVector(std::string listString) { split_vector_type strs; boost::split(strs, listString, boost::is_any_of(", ")); - for (auto it = strs.begin(); it != strs.end(); ++it) { - if (!it->empty()) { + for (auto &str : strs) { + if (!str.empty()) { // String not empty - std::stringstream oneNumber(*it); + std::stringstream oneNumber(str); NumT num; oneNumber >> num; values.push_back(num); diff --git a/Framework/LiveData/src/ADARA/ADARAParser.cpp b/Framework/LiveData/src/ADARA/ADARAParser.cpp index 1791d86e3beede79931f62a5d4649f9ff71fe85c..c6035c7f7d78ffba440653be7d12564899d45bb8 100644 --- a/Framework/LiveData/src/ADARA/ADARAParser.cpp +++ b/Framework/LiveData/src/ADARA/ADARAParser.cpp @@ -297,14 +297,13 @@ void Parser::getDiscardedPacketsLogString(std::string &log_info) { uint64_t total_discarded = 0; // Append Each Discarded Packet Type Count... - for (auto it = m_discarded_packets.begin(); it != m_discarded_packets.end(); - ++it) { + for (auto &discarded_packet : m_discarded_packets) { std::stringstream ss; - ss << std::hex << "0x" << it->first << std::dec << "=" << it->second - << "; "; + ss << std::hex << "0x" << discarded_packet.first << std::dec << "=" + << discarded_packet.second << "; "; log_info.append(ss.str()); - total_discarded += it->second; + total_discarded += discarded_packet.second; } // Append Total Discarded Packet Count diff --git a/Framework/LiveData/src/ISISHistoDataListener.cpp b/Framework/LiveData/src/ISISHistoDataListener.cpp index ec0f52f6013336b2aa872f96366742f141c4dc1c..9fc1daa2027aa75ac73edd96ff6f1094ebd04b07 100644 --- a/Framework/LiveData/src/ISISHistoDataListener.cpp +++ b/Framework/LiveData/src/ISISHistoDataListener.cpp @@ -548,9 +548,8 @@ void ISISHistoDataListener::loadTimeRegimes() { m_monitorSpectra[i] = m_specIDs[monitorIndices[i] - 1]; } - for (auto mon = m_monitorSpectra.begin(); mon != m_monitorSpectra.end(); - ++mon) { - g_log.information() << "Monitor spectrum " << *mon << std::endl; + for (auto &mon : m_monitorSpectra) { + g_log.information() << "Monitor spectrum " << mon << std::endl; } const std::string detRTCB = @@ -599,14 +598,13 @@ int ISISHistoDataListener::getTimeRegimeToLoad() const { if (m_monitorSpectra.empty()) return 0; int regime = -1; - for (auto specIt = m_specList.begin(); specIt != m_specList.end(); - ++specIt) { + for (auto specIt : m_specList) { bool isMonitor = - std::find(m_monitorSpectra.begin(), m_monitorSpectra.end(), - *specIt) != m_monitorSpectra.end(); - if (!isMonitor && *specIt > m_totalNumberOfSpectra) + std::find(m_monitorSpectra.begin(), m_monitorSpectra.end(), specIt) != + m_monitorSpectra.end(); + if (!isMonitor && specIt > m_totalNumberOfSpectra) throw std::invalid_argument("Invalid spectra index is found: " + - boost::lexical_cast<std::string>(*specIt)); + boost::lexical_cast<std::string>(specIt)); int specRegime = isMonitor ? 1 : 0; if (regime < 0) { regime = specRegime; diff --git a/Framework/LiveData/src/ISISLiveEventDataListener.cpp b/Framework/LiveData/src/ISISLiveEventDataListener.cpp index e18ca7752a4db9f9f8615d1cd0d2f4eac6f24fb0..284d69dc9750f9e4f00da1b3b49e366118fef8bb 100644 --- a/Framework/LiveData/src/ISISLiveEventDataListener.cpp +++ b/Framework/LiveData/src/ISISLiveEventDataListener.cpp @@ -387,9 +387,11 @@ void ISISLiveEventDataListener::saveEvents( period = 0; } - for (auto it = data.begin(); it != data.end(); ++it) { - Mantid::DataObjects::TofEvent event(it->time_of_flight, pulseTime); - m_eventBuffer[period]->getEventList(it->spectrum).addEventQuickly(event); + for (const auto &streamEvent : data) { + Mantid::DataObjects::TofEvent event(streamEvent.time_of_flight, pulseTime); + m_eventBuffer[period] + ->getEventList(streamEvent.spectrum) + .addEventQuickly(event); } } diff --git a/Framework/LiveData/src/LiveDataAlgorithm.cpp b/Framework/LiveData/src/LiveDataAlgorithm.cpp index fc2f730fe65d483ed16c5cf188c7927be190ebc1..abf1e94e16f676e0cb99557217e0b6d6687f65ec 100644 --- a/Framework/LiveData/src/LiveDataAlgorithm.cpp +++ b/Framework/LiveData/src/LiveDataAlgorithm.cpp @@ -40,9 +40,9 @@ void LiveDataAlgorithm::initProps() { std::vector<std::string> instruments; auto &instrInfo = Kernel::ConfigService::Instance().getFacility().instruments(); - for (auto it = instrInfo.begin(); it != instrInfo.end(); ++it) { - if (!it->liveDataAddress().empty()) { - instruments.push_back(it->name()); + for (const auto &instrument : instrInfo) { + if (!instrument.liveDataAddress().empty()) { + instruments.push_back(instrument.name()); } } #ifndef NDEBUG @@ -155,8 +155,7 @@ void LiveDataAlgorithm::initProps() { */ void LiveDataAlgorithm::copyPropertyValuesFrom(const LiveDataAlgorithm &other) { std::vector<Property *> props = this->getProperties(); - for (size_t i = 0; i < props.size(); i++) { - Property *prop = props[i]; + for (auto prop : props) { this->setPropertyValue(prop->name(), other.getPropertyValue(prop->name())); } } diff --git a/Framework/LiveData/src/LoadLiveData.cpp b/Framework/LiveData/src/LoadLiveData.cpp index cd7bf27a9e95160d938d1a2cc99c201932e3f472..384d156e25e9686e815b17f2808d6f370663c240 100644 --- a/Framework/LiveData/src/LoadLiveData.cpp +++ b/Framework/LiveData/src/LoadLiveData.cpp @@ -108,8 +108,7 @@ LoadLiveData::runProcessing(Mantid::API::Workspace_sptr inputWS, g_log.debug() << "Processing algorithm (" << alg->name() << ") has " << proplist.size() << " properties." << std::endl; bool inputPropertyWorkspaceFound = false; - for (size_t i = 0; i < proplist.size(); ++i) { - Property *prop = proplist[i]; + for (auto prop : proplist) { if ((prop->direction() == 0) && (inputPropertyWorkspaceFound == false)) { if (boost::ends_with(prop->type(), "Workspace")) { diff --git a/Framework/LiveData/src/SNSLiveEventDataListener.cpp b/Framework/LiveData/src/SNSLiveEventDataListener.cpp index b1a2d0057d30a3dfbb0b14f674fca3ae8ed888bd..a092acd24965cc5759e00b8e10f384ddd79f343b 100644 --- a/Framework/LiveData/src/SNSLiveEventDataListener.cpp +++ b/Framework/LiveData/src/SNSLiveEventDataListener.cpp @@ -1399,8 +1399,8 @@ boost::shared_ptr<Workspace> SNSLiveEventDataListener::extractData() { temp->mutableRun().clearOutdatedTimeSeriesLogValues(); // Clear out old monitor logs - for (unsigned i = 0; i < m_monitorLogs.size(); i++) { - temp->mutableRun().removeProperty(m_monitorLogs[i]); + for (auto &monitorLog : m_monitorLogs) { + temp->mutableRun().removeProperty(monitorLog); } m_monitorLogs.clear(); diff --git a/Framework/LiveData/src/TOPAZLiveEventDataListener.cpp b/Framework/LiveData/src/TOPAZLiveEventDataListener.cpp index a0479f82b43b4967a8d26b6c39bbc0982375c7ec..1c776a4c5ca4719e8bb37d94795191d17038c31a 100644 --- a/Framework/LiveData/src/TOPAZLiveEventDataListener.cpp +++ b/Framework/LiveData/src/TOPAZLiveEventDataListener.cpp @@ -588,8 +588,8 @@ boost::shared_ptr<Workspace> TOPAZLiveEventDataListener::extractData() { // TODO: At present, there's no way for monitor logs to be added // to m_monitorLogs. Either implement this feature, or remove // m_monitorLogs! - for (unsigned i = 0; i < m_monitorLogs.size(); i++) { - temp->mutableRun().removeProperty(m_monitorLogs[i]); + for (auto &monitorLog : m_monitorLogs) { + temp->mutableRun().removeProperty(monitorLog); } m_monitorLogs.clear(); diff --git a/Framework/MDAlgorithms/src/AccumulateMD.cpp b/Framework/MDAlgorithms/src/AccumulateMD.cpp index f9ffb02a9505c438bcf16a7acf396954ff9c1334..0f6d266721acf67e2dc43dd22fb37e9b9ebaf530 100644 --- a/Framework/MDAlgorithms/src/AccumulateMD.cpp +++ b/Framework/MDAlgorithms/src/AccumulateMD.cpp @@ -149,14 +149,13 @@ getHistoricalDataSources(const WorkspaceHistory &ws_history, auto view = ws_history.createView(); view->unrollAll(); const std::vector<HistoryItem> history_items = view->getAlgorithmsList(); - for (auto iter = history_items.begin(); iter != history_items.end(); ++iter) { - auto alg_history = iter->getAlgorithmHistory(); + for (const auto &history_item : history_items) { + auto alg_history = history_item.getAlgorithmHistory(); if (alg_history->name() == create_alg_name || alg_history->name() == accumulate_alg_name) { auto props = alg_history->getProperties(); - for (auto prop_iter = props.begin(); prop_iter != props.end(); - ++prop_iter) { - PropertyHistory_const_sptr prop_history = *prop_iter; + for (auto &prop : props) { + PropertyHistory_const_sptr prop_history = prop; if (prop_history->name() == "DataSources") { insertDataSources(prop_history->value(), historical_data_sources); } @@ -188,9 +187,7 @@ void insertDataSources(const std::string &data_sources, boost::bind(boost::algorithm::trim<std::string>, _1, std::locale())); // Insert each data source into our complete set of historical data sources - for (auto it = data_split.begin(); it != data_split.end(); ++it) { - historical_data_sources.insert(*it); - } + historical_data_sources.insert(data_split.begin(), data_split.end()); } // Register the algorithm into the AlgorithmFactory diff --git a/Framework/MDAlgorithms/src/BinMD.cpp b/Framework/MDAlgorithms/src/BinMD.cpp index b7ae382f0ba8b0f349796797cd6911e43f639847..0d64f9ec1b9bd3a8cba2bbd0dc3e7c913e12aec0 100644 --- a/Framework/MDAlgorithms/src/BinMD.cpp +++ b/Framework/MDAlgorithms/src/BinMD.cpp @@ -332,8 +332,8 @@ void BinMD::binByIterating(typename MDEventWorkspace<MDE, nd>::sptr ws) { } // Go through every box for this chunk. - for (size_t i = 0; i < boxes.size(); i++) { - MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxes[i]); + for (auto &boxe : boxes) { + MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxe); // Perform the binning in this separate method. if (box) this->binMDBox(box, chunkMin.data(), chunkMax.data()); diff --git a/Framework/MDAlgorithms/src/BoxControllerSettingsAlgorithm.cpp b/Framework/MDAlgorithms/src/BoxControllerSettingsAlgorithm.cpp index 8fe24a9e938278b945a1b993cc69bbd7e03a7e8f..dde3bb14ec37c4be71754f404d39c14382d6238b 100644 --- a/Framework/MDAlgorithms/src/BoxControllerSettingsAlgorithm.cpp +++ b/Framework/MDAlgorithms/src/BoxControllerSettingsAlgorithm.cpp @@ -35,17 +35,16 @@ void BoxControllerSettingsAlgorithm::initBoxControllerProps( mustBeMoreThen1->setLower(1); // Split up comma-separated properties - std::vector<int> value; typedef Poco::StringTokenizer tokenizer; tokenizer values(SplitInto, ",", tokenizer::TOK_IGNORE_EMPTY | tokenizer::TOK_TRIM); - value.clear(); - value.reserve(values.count()); - for (auto it = values.begin(); it != values.end(); ++it) - value.push_back(boost::lexical_cast<int>(*it)); + std::vector<int> valueVec; + valueVec.reserve(values.count()); + for (const auto &value : values) + valueVec.push_back(boost::lexical_cast<int>(value)); declareProperty( - new ArrayProperty<int>("SplitInto", value), + new ArrayProperty<int>("SplitInto", valueVec), "A comma separated list of into how many sub-grid elements each " "dimension should split; " "or just one to split into the same number for all dimensions. Default " + diff --git a/Framework/MDAlgorithms/src/CalculateCoverageDGS.cpp b/Framework/MDAlgorithms/src/CalculateCoverageDGS.cpp index 7738a7b320153f46af38b140f32686c4a58504a4..0ccc76662d6a60b6acb2e0d5fc2414666af9c474 100644 --- a/Framework/MDAlgorithms/src/CalculateCoverageDGS.cpp +++ b/Framework/MDAlgorithms/src/CalculateCoverageDGS.cpp @@ -168,8 +168,8 @@ void CalculateCoverageDGS::exec() { auto instrument = inputWS->getInstrument(); std::vector<detid_t> detIDS = instrument->getDetectorIDs(true); std::vector<double> tt, phi; - for (int i = 0; i < static_cast<int>(detIDS.size()); i++) { - auto detector = instrument->getDetector(detIDS[i]); + for (auto &id : detIDS) { + auto detector = instrument->getDetector(id); if (!detector->isMasked()) { tt.push_back(detector->getTwoTheta(V3D(0, 0, 0), V3D(0, 0, 1))); phi.push_back(detector->getPhi()); diff --git a/Framework/MDAlgorithms/src/ConvertCWPDMDToSpectra.cpp b/Framework/MDAlgorithms/src/ConvertCWPDMDToSpectra.cpp index ed5a2e70bfe41100b9b689954c41eab768abb3eb..e2b8f7f68369e003c5afeb280ae15f6fc2b2f666 100644 --- a/Framework/MDAlgorithms/src/ConvertCWPDMDToSpectra.cpp +++ b/Framework/MDAlgorithms/src/ConvertCWPDMDToSpectra.cpp @@ -693,8 +693,7 @@ void ConvertCWPDMDToSpectra::setupSampleLogs( const Run &srcrun = lastexpinfo->run(); const std::vector<Kernel::Property *> &vec_srcprop = srcrun.getProperties(); - for (size_t i = 0; i < vec_srcprop.size(); ++i) { - Property *p = vec_srcprop[i]; + for (auto p : vec_srcprop) { targetrun.addProperty(p->clone()); g_log.debug() << "Cloned property " << p->name() << "\n"; } diff --git a/Framework/MDAlgorithms/src/ConvertCWSDExpToMomentum.cpp b/Framework/MDAlgorithms/src/ConvertCWSDExpToMomentum.cpp index 746eb498bc4ad870cb81ff6452f4c2cce3ab69e5..fd5cf6254f74d8069cea6432c9feb24b881c70a2 100644 --- a/Framework/MDAlgorithms/src/ConvertCWSDExpToMomentum.cpp +++ b/Framework/MDAlgorithms/src/ConvertCWSDExpToMomentum.cpp @@ -421,8 +421,8 @@ void ConvertCWSDExpToMomentum::convertSpiceMatrixToMomentumMDEvents( // Add all the other propertys from original data workspace const std::vector<Kernel::Property *> vec_property = dataws->run().getProperties(); - for (size_t i = 0; i < vec_property.size(); ++i) { - expinfo->mutableRun().addProperty(vec_property[i]->clone()); + for (auto property : vec_property) { + expinfo->mutableRun().addProperty(property->clone()); } m_outputWS->addExperimentInfo(expinfo); @@ -570,10 +570,7 @@ ConvertCWSDExpToMomentum::loadSpiceData(const std::string &filename, loader->execute(); dataws = loader->getProperty("OutputWorkspace"); - if (dataws) - loaded = true; - else - loaded = false; + loaded = static_cast<bool>(dataws); } catch (std::runtime_error &runerror) { loaded = false; errmsg = runerror.what(); diff --git a/Framework/MDAlgorithms/src/ConvertSpiceDataToRealSpace.cpp b/Framework/MDAlgorithms/src/ConvertSpiceDataToRealSpace.cpp index 335b93b4f949ab83c5470d5fa17f805d14a34929..66cf1c023bbfaff4dfa49e95c01183fb2b89e8b3 100644 --- a/Framework/MDAlgorithms/src/ConvertSpiceDataToRealSpace.cpp +++ b/Framework/MDAlgorithms/src/ConvertSpiceDataToRealSpace.cpp @@ -554,14 +554,14 @@ void ConvertSpiceDataToRealSpace::addExperimentInfos( API::IMDEventWorkspace_sptr mdws, const std::vector<API::MatrixWorkspace_sptr> vec_ws2d) { // Add N experiment info as there are N measurment points - for (size_t i = 0; i < vec_ws2d.size(); ++i) { + for (const auto &ws2d : vec_ws2d) { // Create an ExperimentInfo object ExperimentInfo_sptr tmp_expinfo = boost::make_shared<ExperimentInfo>(); - Geometry::Instrument_const_sptr tmp_inst = vec_ws2d[i]->getInstrument(); + Geometry::Instrument_const_sptr tmp_inst = ws2d->getInstrument(); tmp_expinfo->setInstrument(tmp_inst); int runnumber = - atoi(vec_ws2d[i]->run().getProperty("run_number")->value().c_str()); + atoi(ws2d->run().getProperty("run_number")->value().c_str()); tmp_expinfo->mutableRun().addProperty( new PropertyWithValue<int>("run_number", runnumber)); @@ -630,8 +630,7 @@ IMDEventWorkspace_sptr ConvertSpiceDataToRealSpace::createDataMDWorkspace( MDEventInserter<MDEventWorkspace<MDEvent<3>, 3>::sptr> inserter( MDEW_MDEVENT_3); - for (size_t iws = 0; iws < vec_ws2d.size(); ++iws) { - API::MatrixWorkspace_sptr thisWorkspace = vec_ws2d[iws]; + for (auto thisWorkspace : vec_ws2d) { short unsigned int runnumber = static_cast<short unsigned int>( atoi(thisWorkspace->run().getProperty("run_number")->value().c_str())); diff --git a/Framework/MDAlgorithms/src/ConvertToDetectorFaceMD.cpp b/Framework/MDAlgorithms/src/ConvertToDetectorFaceMD.cpp index 045541cc996093242e9052fa213df2109e7e4b3d..708ffea4c8e35a9515a2f095249ac70e2c7d72c2 100644 --- a/Framework/MDAlgorithms/src/ConvertToDetectorFaceMD.cpp +++ b/Framework/MDAlgorithms/src/ConvertToDetectorFaceMD.cpp @@ -140,10 +140,10 @@ ConvertToDetectorFaceMD::getBanks() { std::vector<IComponent_const_sptr> comps; inst->getChildren(comps, true); - for (size_t i = 0; i < comps.size(); i++) { + for (auto &comp : comps) { // Retrieve it RectangularDetector_const_sptr det = - boost::dynamic_pointer_cast<const RectangularDetector>(comps[i]); + boost::dynamic_pointer_cast<const RectangularDetector>(comp); if (det) { std::string name = det->getName(); if (name.size() < 5) @@ -157,20 +157,19 @@ ConvertToDetectorFaceMD::getBanks() { } } else { // -- Find detectors using the numbers given --- - for (auto bankNum = bankNums.begin(); bankNum != bankNums.end(); - bankNum++) { + for (auto &bankNum : bankNums) { std::string bankName = - "bank" + Mantid::Kernel::Strings::toString(*bankNum); + "bank" + Mantid::Kernel::Strings::toString(bankNum); IComponent_const_sptr comp = inst->getComponentByName(bankName); RectangularDetector_const_sptr det = boost::dynamic_pointer_cast<const RectangularDetector>(comp); if (det) - banks[*bankNum] = det; + banks[bankNum] = det; } } - for (auto bank = banks.begin(); bank != banks.end(); bank++) { - RectangularDetector_const_sptr det = bank->second; + for (auto &bank : banks) { + RectangularDetector_const_sptr det = bank.second; // Track the largest detector if (det->xpixels() > m_numXPixels) m_numXPixels = det->xpixels(); @@ -268,9 +267,9 @@ void ConvertToDetectorFaceMD::exec() { uint16_t runIndex = outWS->addExperimentInfo(ei); // ---------------- Convert each bank -------------------------------------- - for (auto it = banks.begin(); it != banks.end(); it++) { - int bankNum = it->first; - RectangularDetector_const_sptr det = it->second; + for (auto &bank : banks) { + int bankNum = bank.first; + RectangularDetector_const_sptr det = bank.second; for (int x = 0; x < det->xpixels(); x++) for (int y = 0; y < det->ypixels(); y++) { // Find the workspace index for this pixel coordinate diff --git a/Framework/MDAlgorithms/src/ConvertToDiffractionMDWorkspace.cpp b/Framework/MDAlgorithms/src/ConvertToDiffractionMDWorkspace.cpp index c24f457e8ecc550f0038db39b988d7a3710d22e6..7137dc32969577a6877e8df01c71d327062c5522 100644 --- a/Framework/MDAlgorithms/src/ConvertToDiffractionMDWorkspace.cpp +++ b/Framework/MDAlgorithms/src/ConvertToDiffractionMDWorkspace.cpp @@ -621,8 +621,8 @@ void ConvertToDiffractionMDWorkspace::exec() { << " events. This took " << cputimtotal << " in total.\n"; std::vector<std::string> stats = ws->getBoxControllerStats(); - for (size_t i = 0; i < stats.size(); ++i) - g_log.information() << stats[i] << "\n"; + for (auto &stat : stats) + g_log.information() << stat << "\n"; g_log.information() << std::endl; } diff --git a/Framework/MDAlgorithms/src/ConvertToMD.cpp b/Framework/MDAlgorithms/src/ConvertToMD.cpp index 59fe97134ef322e7d26fe07c0ba1844a3b788aa9..617e26b06a5b97687308b28baefe6244b5cd2b57 100644 --- a/Framework/MDAlgorithms/src/ConvertToMD.cpp +++ b/Framework/MDAlgorithms/src/ConvertToMD.cpp @@ -302,8 +302,8 @@ void ConvertToMD::copyMetaData(API::IMDEventWorkspace_sptr &mdEventWS) const { UnitsConversionHelper &unitConv = m_Convertor->getUnitConversionHelper(); unitConv.updateConversion(spectra_index); - for (size_t i = 0; i < binBoundaries.size(); i++) { - binBoundaries[i] = unitConv.convertUnits(binBoundaries[i]); + for (double &binBoundarie : binBoundaries) { + binBoundarie = unitConv.convertUnits(binBoundarie); } } // sort bin boundaries in case if unit transformation have swapped them. @@ -529,11 +529,7 @@ bool ConvertToMD::doWeNeedNewTargetWorkspace(API::IMDEventWorkspace_sptr spws) { createNewWs = true; } else { bool shouldOverwrite = getProperty("OverwriteExisting"); - if (shouldOverwrite) { - createNewWs = true; - } else { - createNewWs = false; - } + createNewWs = shouldOverwrite; } return createNewWs; } diff --git a/Framework/MDAlgorithms/src/ConvertToMDMinMaxGlobal.cpp b/Framework/MDAlgorithms/src/ConvertToMDMinMaxGlobal.cpp index a3e46d9ce9949f7005b795f89ffc59ed8e355e15..9704469241f431948ebdd49c157037b10ae047d0 100644 --- a/Framework/MDAlgorithms/src/ConvertToMDMinMaxGlobal.cpp +++ b/Framework/MDAlgorithms/src/ConvertToMDMinMaxGlobal.cpp @@ -263,13 +263,13 @@ void ConvertToMDMinMaxGlobal::exec() { } } - for (size_t i = 0; i < OtherDimensions.size(); ++i) { - if (!ws->run().hasProperty(OtherDimensions[i])) { + for (auto &OtherDimension : OtherDimensions) { + if (!ws->run().hasProperty(OtherDimension)) { g_log.error() << "The workspace does not have a property " - << OtherDimensions[i] << std::endl; + << OtherDimension << std::endl; throw std::invalid_argument("Property not found. Please see error log."); } - Kernel::Property *pProperty = (ws->run().getProperty(OtherDimensions[i])); + Kernel::Property *pProperty = (ws->run().getProperty(OtherDimension)); TimeSeriesProperty<double> *p = dynamic_cast<TimeSeriesProperty<double> *>(pProperty); if (p) { @@ -282,8 +282,8 @@ void ConvertToMDMinMaxGlobal::exec() { if (!p) { std::string ERR = " Can not interpret property, used as dimension.\n Property: " + - OtherDimensions[i] + " is neither a time series (run) property nor " - "a property with value<double>"; + OtherDimension + " is neither a time series (run) property nor " + "a property with value<double>"; throw(std::invalid_argument(ERR)); } double val = *p; diff --git a/Framework/MDAlgorithms/src/ConvertToMDMinMaxLocal.cpp b/Framework/MDAlgorithms/src/ConvertToMDMinMaxLocal.cpp index fa4fb038b54237325307a6b358779f25527c9e84..e911eb0965d84b00b4526b71551f6a06bc71f6f1 100644 --- a/Framework/MDAlgorithms/src/ConvertToMDMinMaxLocal.cpp +++ b/Framework/MDAlgorithms/src/ConvertToMDMinMaxLocal.cpp @@ -176,9 +176,9 @@ void ConvertToMDMinMaxLocal::findMinMaxValues(MDWSDescription &WSDescription, std::vector<double> range = pQtransf->getExtremumPoints(x1, x2, iSpctr); // transform coordinates - for (size_t k = 0; k < range.size(); k++) { + for (double &k : range) { - pQtransf->calcMatrixCoord(range[k], locCoord, signal, errorSq); + pQtransf->calcMatrixCoord(k, locCoord, signal, errorSq); // identify min-max ranges for current spectrum for (size_t j = 0; j < nDims; j++) { if (locCoord[j] < MinValues[j]) diff --git a/Framework/MDAlgorithms/src/CreateMD.cpp b/Framework/MDAlgorithms/src/CreateMD.cpp index b697f1e94d7d422db32ad8dc9fbe247e170402f7..ef2ae6dd79b10bbbe115a6fe8655a5432c68fea7 100644 --- a/Framework/MDAlgorithms/src/CreateMD.cpp +++ b/Framework/MDAlgorithms/src/CreateMD.cpp @@ -40,8 +40,8 @@ void padParameterVector(std::vector<double> ¶m_vector, */ bool any_given(const std::vector<std::vector<double>> ¶ms) { std::vector<double> param; - for (auto iter = params.begin(); iter != params.end(); ++iter) { - param = *iter; + for (const auto &iter : params) { + param = iter; if (!param.empty()) { return true; } @@ -57,8 +57,8 @@ bool any_given(const std::vector<std::vector<double>> ¶ms) { */ bool all_given(const std::vector<std::vector<double>> ¶ms) { std::vector<double> param; - for (auto iter = params.begin(); iter != params.end(); ++iter) { - param = *iter; + for (const auto &iter : params) { + param = iter; if (param.empty()) { return false; } @@ -241,9 +241,8 @@ void CreateMD::exec() { } // Clean up temporary workspaces - for (auto ws_iter = to_merge_names.begin(); ws_iter != to_merge_names.end(); - ++ws_iter) { - AnalysisDataService::Instance().remove(*ws_iter); + for (auto &to_merge_name : to_merge_names) { + AnalysisDataService::Instance().remove(to_merge_name); } this->setProperty("OutputWorkspace", output_workspace); diff --git a/Framework/MDAlgorithms/src/CreateMDWorkspace.cpp b/Framework/MDAlgorithms/src/CreateMDWorkspace.cpp index 98f4d776607a3f605f5f37e5c2aaf960ac9745fb..16db3bca14e85b8edbfc961f91fab06052f4a7f4 100644 --- a/Framework/MDAlgorithms/src/CreateMDWorkspace.cpp +++ b/Framework/MDAlgorithms/src/CreateMDWorkspace.cpp @@ -234,8 +234,8 @@ std::map<std::string, std::string> CreateMDWorkspace::validateInputs() { targetFrames.push_back(Mantid::Geometry::QSample::QSampleName); auto isValidFrame = true; - for (auto it = frames.begin(); it != frames.end(); ++it) { - auto result = checkIfFrameValid(*it, targetFrames); + for (auto &frame : frames) { + auto result = checkIfFrameValid(frame, targetFrames); if (!result) { isValidFrame = result; } @@ -262,9 +262,8 @@ std::map<std::string, std::string> CreateMDWorkspace::validateInputs() { */ bool CreateMDWorkspace::checkIfFrameValid( const std::string &frame, const std::vector<std::string> &targetFrames) { - for (auto targetFrame = targetFrames.begin(); - targetFrame != targetFrames.end(); ++targetFrame) { - if (*targetFrame == frame) { + for (const auto &targetFrame : targetFrames) { + if (targetFrame == frame) { return true; } } diff --git a/Framework/MDAlgorithms/src/CutMD.cpp b/Framework/MDAlgorithms/src/CutMD.cpp index 097031448e4b64e6bb4f3a064ae4fefa89c9725d..8a724732f1fc5cbe1e6802822cfcafba268cc976 100644 --- a/Framework/MDAlgorithms/src/CutMD.cpp +++ b/Framework/MDAlgorithms/src/CutMD.cpp @@ -88,10 +88,10 @@ std::vector<MinMax> calculateExtents(const DblMatrix &inMatrix, const double maxDbl = std::numeric_limits<double>::max(); std::vector<MinMax> extents(3, std::make_pair(maxDbl, maxDbl)); - for (auto hIt = hRange.begin(); hIt != hRange.end(); ++hIt) { - for (auto kIt = kRange.begin(); kIt != kRange.end(); ++kIt) { - for (auto lIt = lRange.begin(); lIt != lRange.end(); ++lIt) { - V3D origPos(*hIt, *kIt, *lIt); + for (double &hIt : hRange) { + for (double &kIt : kRange) { + for (double &lIt : lRange) { + V3D origPos(hIt, kIt, lIt); for (size_t i = 0; i < 3; ++i) { const V3D other(invMat[i][0], invMat[i][1], invMat[i][2]); double val = origPos.scalar_prod(other); diff --git a/Framework/MDAlgorithms/src/DisplayNormalizationSetter.cpp b/Framework/MDAlgorithms/src/DisplayNormalizationSetter.cpp index 3f37defafba617216c6e343c70641a639ce9fa35..87bb0ddc8a194b7b2ea6f7551aa7c54d52659d20 100644 --- a/Framework/MDAlgorithms/src/DisplayNormalizationSetter.cpp +++ b/Framework/MDAlgorithms/src/DisplayNormalizationSetter.cpp @@ -39,14 +39,10 @@ void DisplayNormalizationSetter::setNormalizationMDEvent( Mantid::API::IMDWorkspace_sptr mdWorkspace, const Mantid::API::MatrixWorkspace_sptr &underlyingWorkspace, bool isQ, const Mantid::Kernel::DeltaEMode::Type &mode) { - auto isEventWorkspace = true; - if (boost::dynamic_pointer_cast<Mantid::DataObjects::EventWorkspace>( - underlyingWorkspace)) { - isEventWorkspace = true; - } else { - isEventWorkspace = false; - } + auto isEventWorkspace = static_cast<bool>( + boost::dynamic_pointer_cast<Mantid::DataObjects::EventWorkspace>( + underlyingWorkspace)); Mantid::API::MDNormalization displayNormalization( Mantid::API::MDNormalization::VolumeNormalization); Mantid::API::MDNormalization displayNormalizationHisto( diff --git a/Framework/MDAlgorithms/src/DivideMD.cpp b/Framework/MDAlgorithms/src/DivideMD.cpp index 23c762fcd57067b0889ac3b13bcdad8c95b44d36..efbb9a17ad33ced93fe9cfde59bbcca79af48067 100644 --- a/Framework/MDAlgorithms/src/DivideMD.cpp +++ b/Framework/MDAlgorithms/src/DivideMD.cpp @@ -73,8 +73,8 @@ void DivideMD::execEventScalar(typename MDEventWorkspace<MDE, nd>::sptr ws) { dbuff = ws->getBoxController()->getFileIO(); } - for (size_t i = 0; i < boxes.size(); i++) { - MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxes[i]); + for (auto &boxe : boxes) { + MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxe); if (box) { size_t ic(0); typename std::vector<MDE> &events = box->getEvents(); diff --git a/Framework/MDAlgorithms/src/FindPeaksMD.cpp b/Framework/MDAlgorithms/src/FindPeaksMD.cpp index 5f26a22c472e57a7aba84ff4b55a8bf8e5674d42..59355a573a786054ae1a8ba92292597fdc7bd3c9 100644 --- a/Framework/MDAlgorithms/src/FindPeaksMD.cpp +++ b/Framework/MDAlgorithms/src/FindPeaksMD.cpp @@ -341,13 +341,13 @@ void FindPeaksMD::findPeaks(typename MDEventWorkspace<MDE, nd>::sptr ws) { // Compare to all boxes already picked. bool badBox = false; - for (auto it3 = peakBoxes.begin(); it3 != peakBoxes.end(); it3++) { + for (auto &peakBoxe : peakBoxes) { #ifndef MDBOX_TRACK_CENTROID coord_t otherCenter[nd]; (*it3)->calculateCentroid(otherCenter); #else - const coord_t *otherCenter = (*it3)->getCentroid(); + const coord_t *otherCenter = peakBoxe->getCentroid(); #endif // Distance between this box and a box we already put in. @@ -386,9 +386,9 @@ void FindPeaksMD::findPeaks(typename MDEventWorkspace<MDE, nd>::sptr ws) { prog->resetNumSteps(numBoxesFound, 0.95, 1.0); // --- Convert the "boxes" to peaks ---- - for (auto it3 = peakBoxes.begin(); it3 != peakBoxes.end(); it3++) { - // The center of the box = Q in the lab frame - boxPtr box = *it3; + for (auto box : peakBoxes) { +// The center of the box = Q in the lab frame + #ifndef MDBOX_TRACK_CENTROID coord_t boxCenter[nd]; box->calculateCentroid(boxCenter); @@ -515,8 +515,8 @@ void FindPeaksMD::findPeaksHisto( // Compare to all boxes already picked. bool badBox = false; - for (auto it3 = peakBoxes.begin(); it3 != peakBoxes.end(); ++it3) { - VMD otherCenter = ws->getCenter(*it3); + for (auto &peakBoxe : peakBoxes) { + VMD otherCenter = ws->getCenter(peakBoxe); // Distance between this box and a box we already put in. coord_t distSquared = 0.0; @@ -549,8 +549,7 @@ void FindPeaksMD::findPeaksHisto( } } // --- Convert the "boxes" to peaks ---- - for (auto it3 = peakBoxes.begin(); it3 != peakBoxes.end(); ++it3) { - size_t index = *it3; + for (auto index : peakBoxes) { // The center of the box = Q in the lab frame VMD boxCenter = ws->getCenter(index); diff --git a/Framework/MDAlgorithms/src/ImportMDHistoWorkspaceBase.cpp b/Framework/MDAlgorithms/src/ImportMDHistoWorkspaceBase.cpp index ada4baae0f294d626fce1657c9462d476b6a42e1..f73e21ec008b76ed584ced23be474b3f01e190d0 100644 --- a/Framework/MDAlgorithms/src/ImportMDHistoWorkspaceBase.cpp +++ b/Framework/MDAlgorithms/src/ImportMDHistoWorkspaceBase.cpp @@ -172,8 +172,8 @@ ImportMDHistoWorkspaceBase::validateInputs() { targetFrames.push_back(Mantid::Geometry::QSample::QSampleName); auto isValidFrame = true; - for (auto it = frames.begin(); it != frames.end(); ++it) { - auto result = checkIfFrameValid(*it, targetFrames); + for (auto &frame : frames) { + auto result = checkIfFrameValid(frame, targetFrames); if (!result) { isValidFrame = result; } @@ -200,9 +200,8 @@ ImportMDHistoWorkspaceBase::validateInputs() { */ bool ImportMDHistoWorkspaceBase::checkIfFrameValid( const std::string &frame, const std::vector<std::string> &targetFrames) { - for (auto targetFrame = targetFrames.begin(); - targetFrame != targetFrames.end(); ++targetFrame) { - if (*targetFrame == frame) { + for (const auto &targetFrame : targetFrames) { + if (targetFrame == frame) { return true; } } diff --git a/Framework/MDAlgorithms/src/Integrate3DEvents.cpp b/Framework/MDAlgorithms/src/Integrate3DEvents.cpp index c644495d178e25fab1bf98bc5307c9af2eb504ca..b0b54b75681fb366a8eda17f0ec7d905708d9b40 100644 --- a/Framework/MDAlgorithms/src/Integrate3DEvents.cpp +++ b/Framework/MDAlgorithms/src/Integrate3DEvents.cpp @@ -69,8 +69,8 @@ Integrate3DEvents::~Integrate3DEvents() {} */ void Integrate3DEvents::addEvents( std::vector<std::pair<double, V3D>> const &event_qs, bool hkl_integ) { - for (size_t i = 0; i < event_qs.size(); i++) { - addEvent(event_qs[i], hkl_integ); + for (const auto &event_q : event_qs) { + addEvent(event_q, hkl_integ); } } @@ -183,14 +183,14 @@ double Integrate3DEvents::numInEllipsoid( std::vector<std::pair<double, V3D>> const &events, std::vector<V3D> const &directions, std::vector<double> const &sizes) { double count = 0; - for (size_t i = 0; i < events.size(); i++) { + for (const auto &event : events) { double sum = 0; for (size_t k = 0; k < 3; k++) { - double comp = events[i].second.scalar_prod(directions[k]) / sizes[k]; + double comp = event.second.scalar_prod(directions[k]) / sizes[k]; sum += comp * comp; } if (sum <= 1) - count += events[i].first; + count += event.first; } return count; @@ -216,17 +216,17 @@ double Integrate3DEvents::numInEllipsoidBkg( std::vector<double> const &sizesIn) { double count = 0; std::vector<double> eventVec; - for (size_t i = 0; i < events.size(); i++) { + for (const auto &event : events) { double sum = 0; double sumIn = 0; for (size_t k = 0; k < 3; k++) { - double comp = events[i].second.scalar_prod(directions[k]) / sizes[k]; + double comp = event.second.scalar_prod(directions[k]) / sizes[k]; sum += comp * comp; - comp = events[i].second.scalar_prod(directions[k]) / sizesIn[k]; + comp = event.second.scalar_prod(directions[k]) / sizesIn[k]; sumIn += comp * comp; } if (sum <= 1 && sumIn >= 1) - eventVec.push_back(events[i].first); + eventVec.push_back(event.first); } std::sort(eventVec.begin(), eventVec.end()); // Remove top 1% of background @@ -272,8 +272,8 @@ void Integrate3DEvents::makeCovarianceMatrix( for (int row = 0; row < 3; row++) { for (int col = 0; col < 3; col++) { double sum = 0; - for (size_t i = 0; i < events.size(); i++) { - auto event = events[i].second; + for (const auto &value : events) { + const auto &event = value.second; if (event.norm() <= radius) { sum += event[row] * event[col]; } @@ -342,8 +342,8 @@ Integrate3DEvents::stdDev(std::vector<std::pair<double, V3D>> const &events, double stdev = 0; int count = 0; - for (size_t i = 0; i < events.size(); i++) { - auto event = events[i].second; + for (const auto &value : events) { + const auto &event = value.second; if (event.norm() <= radius) { double dot_prod = event.scalar_prod(direction); sum += dot_prod; @@ -589,10 +589,10 @@ double Integrate3DEvents::detectorQ(std::vector<Kernel::V3D> E1Vec, const Mantid::Kernel::V3D QLabFrame, std::vector<double> &r) { double quot = 1.0; - for (auto E1 = E1Vec.begin(); E1 != E1Vec.end(); ++E1) { + for (auto &E1 : E1Vec) { V3D distv = QLabFrame - - *E1 * (QLabFrame.scalar_prod( - *E1)); // distance to the trajectory as a vector + E1 * (QLabFrame.scalar_prod( + E1)); // distance to the trajectory as a vector double quot0 = distv.norm() / *(std::min_element(r.begin(), r.end())); if (quot0 < quot) { quot = quot0; diff --git a/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp b/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp index 317e89943ce9cbbdb6821bb40eb8c35985f1ff37..7e67cb31b0db244fbf9f48f64bfbfab9c0687fdd 100644 --- a/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp +++ b/Framework/MDAlgorithms/src/IntegrateEllipsoids.cpp @@ -89,8 +89,8 @@ void IntegrateEllipsoids::qListFromEventWS(Integrate3DEvents &integrator, const std::vector<WeightedEventNoTime> &raw_events = events.getWeightedEventsNoTime(); std::vector<std::pair<double, V3D>> qList; - for (auto event = raw_events.begin(); event != raw_events.end(); ++event) { - double val = unitConverter.convertUnits(event->tof()); + for (const auto &raw_event : raw_events) { + double val = unitConverter.convertUnits(raw_event.tof()); qConverter.calcMatrixCoord(val, locCoord, signal, errorSq); for (size_t dim = 0; dim < DIMS; ++dim) { buffer[dim] = locCoord[dim]; @@ -98,7 +98,7 @@ void IntegrateEllipsoids::qListFromEventWS(Integrate3DEvents &integrator, V3D qVec(buffer[0], buffer[1], buffer[2]); if (hkl_integ) qVec = UBinv * qVec; - qList.emplace_back(event->m_weight, qVec); + qList.emplace_back(raw_event.m_weight, qVec); } // end of loop over events in list PARALLEL_CRITICAL(addEvents) { integrator.addEvents(qList, hkl_integ); } @@ -596,8 +596,8 @@ void IntegrateEllipsoids::initTargetWSDescr(MatrixWorkspace_sptr &wksp) { void IntegrateEllipsoids::calculateE1(Geometry::Instrument_const_sptr inst) { std::vector<detid_t> detectorIDs = inst->getDetectorIDs(); - for (auto detID = detectorIDs.begin(); detID != detectorIDs.end(); ++detID) { - Mantid::Geometry::IDetector_const_sptr det = inst->getDetector(*detID); + for (auto &detectorID : detectorIDs) { + Mantid::Geometry::IDetector_const_sptr det = inst->getDetector(detectorID); if (det->isMonitor()) continue; // skip monitor if (!det->isMasked()) diff --git a/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp b/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp index 4c1086d629d97ba1905cba372564f4d2bfee1bf9..0469aa39624789f7425eff7113027c658cecf933 100644 --- a/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp +++ b/Framework/MDAlgorithms/src/IntegrateMDHistoWorkspace.cpp @@ -356,7 +356,6 @@ void IntegrateMDHistoWorkspace::exec() { PARALLEL_FOR_NO_WSP_CHECK() for (int i = 0; i < int(outIterators.size()); ++i) { - PARALLEL_START_INTERUPT_REGION boost::scoped_ptr<MDHistoWorkspaceIterator> outIterator( dynamic_cast<MDHistoWorkspaceIterator *>(outIterators[i])); @@ -408,8 +407,8 @@ void IntegrateMDHistoWorkspace::exec() { // calculated what the width vector would need to be. auto neighbourIndexes = inIterator->findNeighbourIndexesByWidth(widthVector); - for (size_t i = 0; i < neighbourIndexes.size(); ++i) { - inIterator->jumpTo(neighbourIndexes[i]); // Go to that neighbour + for (auto neighbourIndex : neighbourIndexes) { + inIterator->jumpTo(neighbourIndex); // Go to that neighbour performWeightedSum(inIterator.get(), box, sumSignal, sumSQErrors, sumNEvents); } diff --git a/Framework/MDAlgorithms/src/IntegratePeaksMD2.cpp b/Framework/MDAlgorithms/src/IntegratePeaksMD2.cpp index 4a3f788c1c701947cf1169c8ee703905f639264c..b404a81d034d790aec683710d111b6f9680a7d7a 100644 --- a/Framework/MDAlgorithms/src/IntegratePeaksMD2.cpp +++ b/Framework/MDAlgorithms/src/IntegratePeaksMD2.cpp @@ -712,8 +712,8 @@ void IntegratePeaksMD2::integrate(typename MDEventWorkspace<MDE, nd>::sptr ws) { void IntegratePeaksMD2::calculateE1(Geometry::Instrument_const_sptr inst) { std::vector<detid_t> detectorIDs = inst->getDetectorIDs(); - for (auto detID = detectorIDs.begin(); detID != detectorIDs.end(); ++detID) { - Mantid::Geometry::IDetector_const_sptr det = inst->getDetector(*detID); + for (auto &detectorID : detectorIDs) { + Mantid::Geometry::IDetector_const_sptr det = inst->getDetector(detectorID); if (det->isMonitor()) continue; // skip monitor if (!det->isMasked()) @@ -739,16 +739,17 @@ void IntegratePeaksMD2::calculateE1(Geometry::Instrument_const_sptr inst) { */ double IntegratePeaksMD2::detectorQ(Mantid::Kernel::V3D QLabFrame, double r) { double edge = r; - for (auto E1 = E1Vec.begin(); E1 != E1Vec.end(); ++E1) { + for (auto &E1 : E1Vec) { V3D distv = QLabFrame - - *E1 * (QLabFrame.scalar_prod( - *E1)); // distance to the trajectory as a vector - if (distv.norm() < std::min(r, edge)) { + E1 * (QLabFrame.scalar_prod( + E1)); // distance to the trajectory as a vector + if (distv.norm() < r) { edge = distv.norm(); } } return edge; } + void IntegratePeaksMD2::runMaskDetectors( Mantid::DataObjects::PeaksWorkspace_sptr peakWS, std::string property, std::string values) { diff --git a/Framework/MDAlgorithms/src/LoadILLAscii.cpp b/Framework/MDAlgorithms/src/LoadILLAscii.cpp index 39be22524c9042a09a9107c3e2ea7bc0234dd751..79364fd82290170b5c7eadb5179bd5ca8af357a7 100644 --- a/Framework/MDAlgorithms/src/LoadILLAscii.cpp +++ b/Framework/MDAlgorithms/src/LoadILLAscii.cpp @@ -248,16 +248,16 @@ void LoadILLAscii::loadsDataIntoTheWS(API::MatrixWorkspace_sptr &thisWorkspace, thisWorkspace->dataX(0)[1] = m_wavelength + 0.001; size_t spec = 0; - for (size_t i = 0; i < thisSpectrum.size(); ++i) { + for (auto value : thisSpectrum) { if (spec > 0) { // just copy the time binning axis to every spectra thisWorkspace->dataX(spec) = thisWorkspace->readX(0); } // Assign Y - thisWorkspace->dataY(spec)[0] = thisSpectrum[i]; + thisWorkspace->dataY(spec)[0] = value; // Assign Error - thisWorkspace->dataE(spec)[0] = thisSpectrum[i] * thisSpectrum[i]; + thisWorkspace->dataE(spec)[0] = value * value; ++spec; } diff --git a/Framework/MDAlgorithms/src/LoadILLAsciiHelper.cpp b/Framework/MDAlgorithms/src/LoadILLAsciiHelper.cpp index b42f1fe655f48dd622d13dc79fc4e6dfab8f1a4b..75d1aaa0be4784d911af2b79d81d31550a8eb3ba 100644 --- a/Framework/MDAlgorithms/src/LoadILLAsciiHelper.cpp +++ b/Framework/MDAlgorithms/src/LoadILLAsciiHelper.cpp @@ -302,8 +302,8 @@ void ILLParser::parseFieldNumeric(std::map<std::string, std::string> &header, for (int i = 0; i < nTextLines; i++) { std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); - for (auto it = s.begin(); it != s.end(); ++it) { - keys[index] = *it; + for (auto &type : s) { + keys[index] = type; index += 1; } } @@ -314,8 +314,8 @@ void ILLParser::parseFieldNumeric(std::map<std::string, std::string> &header, std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); pos += s.size(); - for (auto it = s.begin(); it != s.end(); ++it) { - values[index] = *it; + for (auto &value : s) { + values[index] = value; index += 1; } } @@ -346,9 +346,9 @@ std::vector<int> ILLParser::parseFieldISpec(int fieldWith) { std::getline(fin, line); std::vector<std::string> s = splitLineInFixedWithFields(line, fieldWith); nSpectraRead += static_cast<int>(s.size()); - for (auto it = s.begin(); it != s.end(); ++it) { + for (auto &value : s) { // sscanf is much faster than lexical_cast / erase_spaces - sscanf(it->c_str(), "%8d", &spectrumValues[index]); + sscanf(value.c_str(), "%8d", &spectrumValues[index]); index += 1; } } @@ -361,8 +361,8 @@ std::vector<int> ILLParser::parseFieldISpec(int fieldWith) { */ void ILLParser::showHeader() { std::cout << "* Global header" << '\n'; - for (auto it = header.begin(); it != header.end(); ++it) - std::cout << it->first << " => " << it->second << '\n'; + for (auto &value : header) + std::cout << value.first << " => " << value.second << '\n'; std::cout << "* Spectrum header" << '\n'; int i = 0; @@ -458,12 +458,12 @@ T ILLParser::getValue(const std::string &field, T ret = std::numeric_limits<T>::infinity(); - for (auto it = thisHeader.begin(); it != thisHeader.end(); ++it) { + for (const auto &value : thisHeader) { // std::cout << it->first << "=>" << it->second << '\n'; - std::size_t pos = it->first.find(field); + std::size_t pos = value.first.find(field); if (pos != std::string::npos) { // std::cout << "Found field: " << field << "=>" << it->second << '\n'; - ret = evaluate<T>(it->second); + ret = evaluate<T>(value.second); } } diff --git a/Framework/MDAlgorithms/src/LoadMD.cpp b/Framework/MDAlgorithms/src/LoadMD.cpp index 42f3f007b9c91d3382261142175679483e5b8a3a..39de3ad886211deb74ae0e49e2e73b5c0ad862b4 100644 --- a/Framework/MDAlgorithms/src/LoadMD.cpp +++ b/Framework/MDAlgorithms/src/LoadMD.cpp @@ -715,10 +715,9 @@ void LoadMD::setMDFrameOnWorkspaceFromLegacyFile(API::IMDWorkspace_sptr ws) { // Set the MDFrames for each axes Algorithm_sptr setMDFrameAlg = this->createChildAlgorithm("SetMDFrame"); int axesCounter = 0; - for (auto frame = framesToSet.begin(); frame != framesToSet.end(); - ++frame) { + for (auto &frame : framesToSet) { setMDFrameAlg->setProperty("InputWorkspace", ws); - setMDFrameAlg->setProperty("MDFrame", *frame); + setMDFrameAlg->setProperty("MDFrame", frame); setMDFrameAlg->setProperty("Axes", std::vector<int>(1, axesCounter)); ++axesCounter; setMDFrameAlg->executeAsChildAlg(); @@ -729,9 +728,9 @@ void LoadMD::setMDFrameOnWorkspaceFromLegacyFile(API::IMDWorkspace_sptr ws) { // Revert to the old frames. Algorithm_sptr setMDFrameAlg = this->createChildAlgorithm("SetMDFrame"); int axesCounter = 0; - for (auto frame = oldFrames.begin(); frame != oldFrames.end(); ++frame) { + for (auto &oldFrame : oldFrames) { setMDFrameAlg->setProperty("InputWorkspace", ws); - setMDFrameAlg->setProperty("MDFrame", *frame); + setMDFrameAlg->setProperty("MDFrame", oldFrame); setMDFrameAlg->setProperty("Axes", std::vector<int>(1, axesCounter)); ++axesCounter; setMDFrameAlg->executeAsChildAlg(); diff --git a/Framework/MDAlgorithms/src/MDNormDirectSC.cpp b/Framework/MDAlgorithms/src/MDNormDirectSC.cpp index 10b6c57f2245cb5d7d8b028e825c7bc82140d9db..529f5fba947f3ac90b5d5415634d955854d9d4df 100644 --- a/Framework/MDAlgorithms/src/MDNormDirectSC.cpp +++ b/Framework/MDAlgorithms/src/MDNormDirectSC.cpp @@ -214,9 +214,9 @@ std::string MDNormDirectSC::inputEnergyMode() const { // get dEAnalysisMode PropertyHistories histvec = hist.getAlgorithmHistory(nalgs - 2)->getProperties(); - for (auto it = histvec.begin(); it != histvec.end(); ++it) { - if ((*it)->name() == "dEAnalysisMode") { - emode = (*it)->value(); + for (auto &hist : histvec) { + if (hist->name() == "dEAnalysisMode") { + emode = hist->value(); break; } } @@ -236,11 +236,11 @@ MDHistoWorkspace_sptr MDNormDirectSC::binInputWS() { const auto &props = getProperties(); IAlgorithm_sptr binMD = createChildAlgorithm("BinMD", 0.0, 0.3); binMD->setPropertyValue("AxisAligned", "1"); - for (auto it = props.begin(); it != props.end(); ++it) { - const auto &propName = (*it)->name(); + for (auto prop : props) { + const auto &propName = prop->name(); if (propName != "SolidAngleWorkspace" && propName != "OutputNormalizationWorkspace") { - binMD->setPropertyValue(propName, (*it)->value()); + binMD->setPropertyValue(propName, prop->value()); } } binMD->executeAsChildAlg(); @@ -554,8 +554,7 @@ MDNormDirectSC::removeGroupedIDs(const ExperimentInfo &exptInfo, // double to the correct size once std::set<detid_t> groupedIDs; - for (auto iter = detIDs.begin(); iter != detIDs.end(); ++iter) { - detid_t curID = *iter; + for (auto curID : detIDs) { if (groupedIDs.count(curID) == 1) continue; // Already been processed diff --git a/Framework/MDAlgorithms/src/MDNormSCD.cpp b/Framework/MDAlgorithms/src/MDNormSCD.cpp index 1d88f2acf197adf4e81a62296e35ca7f044caa54..5599ac62b90646b0d71317b2402c3d50230c43ae 100644 --- a/Framework/MDAlgorithms/src/MDNormSCD.cpp +++ b/Framework/MDAlgorithms/src/MDNormSCD.cpp @@ -184,9 +184,9 @@ std::string MDNormSCD::inputEnergyMode() const { // get dEAnalysisMode PropertyHistories histvec = hist.getAlgorithmHistory(nalgs - 2)->getProperties(); - for (auto it = histvec.begin(); it != histvec.end(); ++it) { - if ((*it)->name() == "dEAnalysisMode") { - emode = (*it)->value(); + for (auto &hist : histvec) { + if (hist->name() == "dEAnalysisMode") { + emode = hist->value(); break; } } @@ -206,11 +206,11 @@ MDHistoWorkspace_sptr MDNormSCD::binInputWS() { const auto &props = getProperties(); IAlgorithm_sptr binMD = createChildAlgorithm("BinMD", 0.0, 0.3); binMD->setPropertyValue("AxisAligned", "1"); - for (auto it = props.begin(); it != props.end(); ++it) { - const auto &propName = (*it)->name(); + for (auto prop : props) { + const auto &propName = prop->name(); if (propName != "FluxWorkspace" && propName != "SolidAngleWorkspace" && propName != "OutputNormalizationWorkspace") { - binMD->setPropertyValue(propName, (*it)->value()); + binMD->setPropertyValue(propName, prop->value()); } } binMD->executeAsChildAlg(); @@ -589,8 +589,7 @@ MDNormSCD::removeGroupedIDs(const ExperimentInfo &exptInfo, // double to the correct size once std::set<detid_t> groupedIDs; - for (auto iter = detIDs.begin(); iter != detIDs.end(); ++iter) { - detid_t curID = *iter; + for (auto curID : detIDs) { if (groupedIDs.count(curID) == 1) continue; // Already been processed diff --git a/Framework/MDAlgorithms/src/MDTransfNoQ.cpp b/Framework/MDAlgorithms/src/MDTransfNoQ.cpp index 3f48b364c2e6f734093696143c84ad5a83b873de..f845581e0e8a7fe266f32bb6cd0a5c0275bbde1e 100644 --- a/Framework/MDAlgorithms/src/MDTransfNoQ.cpp +++ b/Framework/MDAlgorithms/src/MDTransfNoQ.cpp @@ -69,10 +69,7 @@ void MDTransfNoQ::initialize(const MDWSDescription &ConvParams) { bool MDTransfNoQ::calcYDepCoordinates(std::vector<coord_t> &Coord, size_t i) { if (m_YAxis) { Coord[1] = static_cast<coord_t>(m_YAxis->operator()(i)); - if (Coord[1] < m_DimMin[1] || Coord[1] >= m_DimMax[1]) - return false; - else - return true; + return !(Coord[1] < m_DimMin[1] || Coord[1] >= m_DimMax[1]); } return false; } diff --git a/Framework/MDAlgorithms/src/MDWSDescription.cpp b/Framework/MDAlgorithms/src/MDWSDescription.cpp index 9d438540ad272d395d88390f00ab3cd7274557e9..5a2b2070cedef31dc4add0ed85cfcd7b1f8ac321 100644 --- a/Framework/MDAlgorithms/src/MDWSDescription.cpp +++ b/Framework/MDAlgorithms/src/MDWSDescription.cpp @@ -322,10 +322,8 @@ void MDWSDescription::getMinMax(std::vector<double> &min, //****************************************************************************************************************************************** /** Method checks if the workspace is expected to be processed in powder mode */ bool MDWSDescription::isPowder() const { - if ((this->AlgID == "|Q|") || - (this->AlgID.size() == 0 && !m_InWS->sample().hasOrientedLattice())) - return true; - return false; + return (this->AlgID == "|Q|") || + (this->AlgID.size() == 0 && !m_InWS->sample().hasOrientedLattice()); } /** Returns symbolic representation of current Emode */ diff --git a/Framework/MDAlgorithms/src/MergeMD.cpp b/Framework/MDAlgorithms/src/MergeMD.cpp index 5965871db3af61c45055b4aabcdbaa51e02b12de..17ea0f4a935889758d2b3a1d29e7e6a76486ae0b 100644 --- a/Framework/MDAlgorithms/src/MergeMD.cpp +++ b/Framework/MDAlgorithms/src/MergeMD.cpp @@ -91,8 +91,7 @@ void MergeMD::createOutputWorkspace(std::vector<std::string> &inputs) { std::vector<coord_t> dimMax(numDims, -1e30f); // Validate each workspace - for (size_t i = 0; i < m_workspaces.size(); i++) { - IMDEventWorkspace_const_sptr ws = m_workspaces[i]; + for (auto &ws : m_workspaces) { if (ws->getNumDims() != numDims) throw std::invalid_argument( "Workspace " + ws->name() + @@ -243,16 +242,15 @@ void MergeMD::exec() { // This will hold the inputs, with the groups separated off std::vector<std::string> inputs; - for (size_t i = 0; i < inputs_orig.size(); i++) { + for (const auto &input : inputs_orig) { WorkspaceGroup_sptr wsgroup = - AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( - inputs_orig[i]); + AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(input); if (wsgroup) { // Workspace group std::vector<std::string> group = wsgroup->getNames(); inputs.insert(inputs.end(), group.begin(), group.end()); } else { // Single workspace - inputs.push_back(inputs_orig[i]); + inputs.push_back(input); } } diff --git a/Framework/MDAlgorithms/src/MergeMDFiles.cpp b/Framework/MDAlgorithms/src/MergeMDFiles.cpp index 052b710d6aac8926929fa4a23ca54e3f739439a6..e373b4a7eba0957f2d6a63e6b318630a1805c8ee 100644 --- a/Framework/MDAlgorithms/src/MergeMDFiles.cpp +++ b/Framework/MDAlgorithms/src/MergeMDFiles.cpp @@ -125,8 +125,7 @@ void MergeMDFiles::loadBoxData() { const std::vector<int> &boxType = m_BoxStruct.getBoxType(); // calculate event positions in the target file. uint64_t eventsStart = 0; - for (size_t i = 0; i < Boxes.size(); i++) { - API::IMDNode *mdBox = Boxes[i]; + for (auto mdBox : Boxes) { mdBox->clear(); size_t ID = mdBox->getID(); @@ -399,11 +398,9 @@ void MergeMDFiles::exec() { } /**Delete all event loaders */ void MergeMDFiles::clearEventLoaders() { - for (size_t i = 0; i < m_EventLoader.size(); i++) { - if (m_EventLoader[i]) { - delete m_EventLoader[i]; - m_EventLoader[i] = NULL; - } + for (auto &loader : m_EventLoader) { + delete loader; + loader = NULL; } } diff --git a/Framework/MDAlgorithms/src/MultiplyMD.cpp b/Framework/MDAlgorithms/src/MultiplyMD.cpp index c9352192194e4a1b8d52a1e4f07de47a4c152438..5689524bc8d6924bd2c2ecd672491a347ebab024 100644 --- a/Framework/MDAlgorithms/src/MultiplyMD.cpp +++ b/Framework/MDAlgorithms/src/MultiplyMD.cpp @@ -74,8 +74,8 @@ void MultiplyMD::execEventScalar(typename MDEventWorkspace<MDE, nd>::sptr ws) { dbuff = ws->getBoxController()->getFileIO(); } - for (size_t i = 0; i < boxes.size(); i++) { - MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxes[i]); + for (auto &boxe : boxes) { + MDBox<MDE, nd> *box = dynamic_cast<MDBox<MDE, nd> *>(boxe); if (box) { typename std::vector<MDE> &events = box->getEvents(); size_t ic(events.size()); diff --git a/Framework/MDAlgorithms/src/PreprocessDetectorsToMD.cpp b/Framework/MDAlgorithms/src/PreprocessDetectorsToMD.cpp index 4dd32f1f301848050c9e5116776ee08ebddbaef3..dd2db69866dd9f4a783a184d9dca9ff46aa6ad33 100644 --- a/Framework/MDAlgorithms/src/PreprocessDetectorsToMD.cpp +++ b/Framework/MDAlgorithms/src/PreprocessDetectorsToMD.cpp @@ -416,9 +416,7 @@ bool PreprocessDetectorsToMD::isDetInfoLost( Mantid::API::MatrixWorkspace_const_sptr inWS2D) const { auto pYAxis = dynamic_cast<API::NumericAxis *>(inWS2D->getAxis(1)); // if this is numeric axis, then the detector's information has been lost: - if (pYAxis) - return true; - return false; + return pYAxis != nullptr; } /** Method returns the efixed or Ei value stored in properties of the input diff --git a/Framework/MDAlgorithms/src/Quantification/Models/MullerAnsatz.cpp b/Framework/MDAlgorithms/src/Quantification/Models/MullerAnsatz.cpp index 708ae56914c03ee9ad4938bfa320723d869616d1..e1435511890f1d0566a68c4d439df882d0e8388e 100644 --- a/Framework/MDAlgorithms/src/Quantification/Models/MullerAnsatz.cpp +++ b/Framework/MDAlgorithms/src/Quantification/Models/MullerAnsatz.cpp @@ -51,8 +51,8 @@ void MullerAnsatz::init() { // setFormFactorIon("Cu2"); // Declare parameters that participate in fitting - for (unsigned int i = 0; i < AnsatzParameters::NPARAMS; ++i) { - declareParameter(AnsatzParameters::PAR_NAMES[i], 0.0); + for (auto &name : AnsatzParameters::PAR_NAMES) { + declareParameter(name, 0.0); } // Declare fixed attributes defaults diff --git a/Framework/MDAlgorithms/src/Quantification/Models/Strontium122.cpp b/Framework/MDAlgorithms/src/Quantification/Models/Strontium122.cpp index d613b2059c84197dbca84c2f6c78568f2de031cc..be744694f64ef6ec7449e200b6b08bbe20b32a45 100644 --- a/Framework/MDAlgorithms/src/Quantification/Models/Strontium122.cpp +++ b/Framework/MDAlgorithms/src/Quantification/Models/Strontium122.cpp @@ -34,13 +34,13 @@ void Strontium122::init() { setFormFactorIon("Fe2"); // Declare parameters that participate in fitting - for (unsigned int i = 0; i < NPARAMS; ++i) { - declareParameter(PAR_NAMES[i], 0.0); + for (auto &name : PAR_NAMES) { + declareParameter(name, 0.0); } // Declare fixed attributes - for (unsigned int i = 0; i < NATTS; ++i) { - declareAttribute(ATTR_NAMES[i], API::IFunction::Attribute(1)); + for (auto &name : ATTR_NAMES) { + declareAttribute(name, API::IFunction::Attribute(1)); } } diff --git a/Framework/MDAlgorithms/src/Quantification/Resolution/TobyFitResolutionModel.cpp b/Framework/MDAlgorithms/src/Quantification/Resolution/TobyFitResolutionModel.cpp index 2e046ad19f749acd6bd68f0caca7028a4f4bcda8..744eb82235e6c70135423094dbc12c6c14df7243 100644 --- a/Framework/MDAlgorithms/src/Quantification/Resolution/TobyFitResolutionModel.cpp +++ b/Framework/MDAlgorithms/src/Quantification/Resolution/TobyFitResolutionModel.cpp @@ -268,8 +268,8 @@ void TobyFitResolutionModel::setAttribute( } else if (name == FOREGROUNDONLY_NAME) { m_foregroundOnly = (value.asInt() != 0); } else { - for (auto iter = m_yvector.begin(); iter != m_yvector.end(); ++iter) { - iter->setAttribute(name, value); + for (auto &iter : m_yvector) { + iter.setAttribute(name, value); } } } diff --git a/Framework/MDAlgorithms/src/Quantification/ResolutionConvolvedCrossSection.cpp b/Framework/MDAlgorithms/src/Quantification/ResolutionConvolvedCrossSection.cpp index dddeb6e4a76bb009a036ef7b0f824b5e10e82b12..d0d850e07eaf08e35732dbb740df5121b80d852b 100644 --- a/Framework/MDAlgorithms/src/Quantification/ResolutionConvolvedCrossSection.cpp +++ b/Framework/MDAlgorithms/src/Quantification/ResolutionConvolvedCrossSection.cpp @@ -142,8 +142,7 @@ void ResolutionConvolvedCrossSection::function( } CHECK_PARALLEL_EXCEPTIONS // Not standard macros. See top of file for reason - for (auto it = iterators.begin(); it != iterators.end(); ++it) { - API::IMDIterator *boxIterator = *it; + for (auto boxIterator : iterators) { delete boxIterator; } } @@ -302,8 +301,8 @@ void ResolutionConvolvedCrossSection::setupResolutionFunction( name, fgModelName, *this); // Pass on the attributes auto names = m_convolution->getAttributeNames(); - for (auto iter = names.begin(); iter != names.end(); ++iter) { - this->declareAttribute(*iter, m_convolution->getAttribute(*iter)); + for (auto &name : names) { + this->declareAttribute(name, m_convolution->getAttribute(name)); } // Pull the foreground parameters on to here const ForegroundModel &fgModel = m_convolution->foregroundModel(); @@ -315,8 +314,8 @@ void ResolutionConvolvedCrossSection::setupResolutionFunction( } // Pull the foreground attributes on to here names = fgModel.getAttributeNames(); - for (auto iter = names.begin(); iter != names.end(); ++iter) { - this->declareAttribute(*iter, fgModel.getAttribute(*iter)); + for (auto &name : names) { + this->declareAttribute(name, fgModel.getAttribute(name)); } } diff --git a/Framework/MDAlgorithms/src/QueryMDWorkspace.cpp b/Framework/MDAlgorithms/src/QueryMDWorkspace.cpp index 6d6f25d2aa3ccf6458d9cc302ff3a589158182a9..d8febfde23151ae93eaf7e49a7d6930110820239 100644 --- a/Framework/MDAlgorithms/src/QueryMDWorkspace.cpp +++ b/Framework/MDAlgorithms/src/QueryMDWorkspace.cpp @@ -148,8 +148,8 @@ void QueryMDWorkspace::getBoxData( std::vector<API::IMDNode *> boxes; ws->getBox()->getBoxes(boxes, depth, true); - for (size_t i = 0; i < boxes.size(); i++) { - MDBoxBase<MDE, nd> *box = dynamic_cast<MDBoxBase<MDE, nd> *>(boxes[i]); + for (auto &boxe : boxes) { + MDBoxBase<MDE, nd> *box = dynamic_cast<MDBoxBase<MDE, nd> *>(boxe); if (!box) throw(std::runtime_error("Can not cast IMDNode to any type of boxes")); size_t d = box->getDepth(); diff --git a/Framework/MDAlgorithms/src/SaveIsawQvector.cpp b/Framework/MDAlgorithms/src/SaveIsawQvector.cpp index eea9d5a7e2d466670e93338649da04d4df341de2..72b9775510f6cac426a4c6cf83c42efff554fd1f 100644 --- a/Framework/MDAlgorithms/src/SaveIsawQvector.cpp +++ b/Framework/MDAlgorithms/src/SaveIsawQvector.cpp @@ -126,8 +126,8 @@ void SaveIsawQvector::exec() { coord_map[2] = 1; } if (this->getProperty("RightHanded")) { - for (size_t dim = 0; dim < DIMS; ++dim) - coord_signs[dim] *= -1.; // everything changes sign + for (double &coord_sign : coord_signs) + coord_sign *= -1.; // everything changes sign } // units conersion helper @@ -165,8 +165,8 @@ void SaveIsawQvector::exec() { double signal(1.); // ignorable garbage double errorSq(1.); // ignorable garbage const std::vector<TofEvent> &raw_events = events.getEvents(); - for (auto event = raw_events.begin(); event != raw_events.end(); ++event) { - double val = unitConv.convertUnits(event->tof()); + for (const auto &raw_event : raw_events) { + double val = unitConv.convertUnits(raw_event.tof()); q_converter->calcMatrixCoord(val, locCoord, signal, errorSq); for (size_t dim = 0; dim < DIMS; ++dim) { buffer[dim] = diff --git a/Framework/MDAlgorithms/src/SaveMD.cpp b/Framework/MDAlgorithms/src/SaveMD.cpp index db7013a7b526128c707d844f26296a82e5a5b96e..ee65de66d48dd521cc4623a0ab67e262ffadeb9e 100644 --- a/Framework/MDAlgorithms/src/SaveMD.cpp +++ b/Framework/MDAlgorithms/src/SaveMD.cpp @@ -155,12 +155,12 @@ void SaveMD::doSaveEvents(typename MDEventWorkspace<MDE, nd>::sptr ws) { // saveable and that the boxes were not saved. BoxFlatStruct.setBoxesFilePositions(true); prog->resetNumSteps(boxes.size(), 0.06, 0.90); - for (size_t i = 0; i < boxes.size(); i++) { - auto saveableTag = boxes[i]->getISaveable(); + for (auto &boxe : boxes) { + auto saveableTag = boxe->getISaveable(); if (saveableTag) // only boxes can be saveable { // do not spend time on empty boxes - if (boxes[i]->getDataInMemorySize() == 0) + if (boxe->getDataInMemorySize() == 0) continue; // save boxes directly using the boxes file postion, precalculated in // boxFlatStructure. diff --git a/Framework/MDAlgorithms/src/SetMDFrame.cpp b/Framework/MDAlgorithms/src/SetMDFrame.cpp index df48ff24fee6bebe9fa8f818686d58552f5042e3..59aa162a6ca186aeb0b9405c94d0fd6f4ed5fa01 100644 --- a/Framework/MDAlgorithms/src/SetMDFrame.cpp +++ b/Framework/MDAlgorithms/src/SetMDFrame.cpp @@ -109,9 +109,9 @@ void SetMDFrame::exec() { return; } - for (auto index = axes.begin(); index != axes.end(); ++index) { + for (auto &axe : axes) { // Get associated dimension - auto dimension = inputWorkspace->getDimension(*index); + auto dimension = inputWorkspace->getDimension(axe); // Provide a new MDFrame std::string frameSelection = getProperty(mdFrameSpecifier); @@ -150,8 +150,8 @@ std::map<std::string, std::string> SetMDFrame::validateInputs() { std::vector<int> axesInts = this->getProperty("Axes"); Kernel::MDAxisValidator axisChecker(axesInts, ws->getNumDims(), true); auto axisErrors = axisChecker.validate(); - for (auto iter = axisErrors.begin(); iter != axisErrors.end(); iter++) { - invalidProperties.insert(*iter); + for (auto &axisError : axisErrors) { + invalidProperties.insert(axisError); } return invalidProperties; diff --git a/Framework/MDAlgorithms/src/SliceMD.cpp b/Framework/MDAlgorithms/src/SliceMD.cpp index ae371f90a4f832269c7f7477923d27665df0bf6b..1b675bf0a82e741e26b3494d1c8efbed23eaf652 100644 --- a/Framework/MDAlgorithms/src/SliceMD.cpp +++ b/Framework/MDAlgorithms/src/SliceMD.cpp @@ -121,8 +121,8 @@ void SliceMD::slice(typename MDEventWorkspace<MDE, nd>::sptr ws) { // Create the ouput workspace typename MDEventWorkspace<OMDE, ond>::sptr outWS( new MDEventWorkspace<OMDE, ond>()); - for (size_t od = 0; od < m_binDimensions.size(); od++) { - outWS->addDimension(m_binDimensions[od]); + for (auto &binDimension : m_binDimensions) { + outWS->addDimension(binDimension); } outWS->setCoordinateSystem(ws->getSpecialCoordinateSystem()); outWS->initialize(); diff --git a/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp b/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp index f444e2555b3dd90dd3d2b722bb71a45411352e68..4d57467498aa20ae911ab7a043b7864841e3a7a9 100644 --- a/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp +++ b/Framework/MDAlgorithms/src/SlicingAlgorithm.cpp @@ -275,9 +275,9 @@ void SlicingAlgorithm::processGeneralTransformProperties() { // Count the number of output dimensions m_outD = 0; std::string dimChars = this->getDimensionChars(); - for (size_t i = 0; i < dimChars.size(); i++) { + for (char dimChar : dimChars) { std::string propName = "BasisVector0"; - propName[11] = dimChars[i]; + propName[11] = dimChar; if (!Strings::strip(this->getPropertyValue(propName)).empty()) m_outD++; } @@ -306,9 +306,9 @@ void SlicingAlgorithm::processGeneralTransformProperties() { m_transformScaling.clear(); // Create the dimensions based on the strings from the user - for (size_t i = 0; i < dimChars.size(); i++) { + for (char dimChar : dimChars) { std::string propName = "BasisVector0"; - propName[11] = dimChars[i]; + propName[11] = dimChar; try { makeBasisVectorFromString(getPropertyValue(propName)); } catch (std::exception &e) { @@ -373,8 +373,8 @@ void SlicingAlgorithm::createGeneralTransform() { ortho.resize(m_bases.size(), VMD(3)); m_bases = ortho; g_log.information() << "Basis vectors forced to be orthogonal: "; - for (size_t i = 0; i < m_bases.size(); i++) - g_log.information() << m_bases[i].toString(",") << "; "; + for (auto &base : m_bases) + g_log.information() << base.toString(",") << "; "; g_log.information() << std::endl; } @@ -529,9 +529,9 @@ void SlicingAlgorithm::createAlignedTransform() { // Validate inputs bool previousWasEmpty = false; size_t numDims = 0; - for (size_t i = 0; i < dimChars.size(); i++) { + for (char dimChar : dimChars) { std::string propName = "AlignedDim0"; - propName[10] = dimChars[i]; + propName[10] = dimChar; std::string prop = Strings::strip(getPropertyValue(propName)); if (!prop.empty()) numDims++; @@ -947,11 +947,11 @@ SlicingAlgorithm::getGeneralImplicitFunction(const size_t *const chunkMin, // Last-resort, totally general case // 2*N planes defined by N basis vectors, in any dimensionality workspace. // Assumes orthogonality! - for (size_t i = 0; i < bases.size(); i++) { + for (auto &base : bases) { // For each basis vector, make two planes, perpendicular to it and facing // inwards - func->addPlane(MDPlane(bases[i], o1)); - func->addPlane(MDPlane(bases[i] * -1.0, o2)); + func->addPlane(MDPlane(base, o1)); + func->addPlane(MDPlane(base * -1.0, o2)); } } @@ -1080,9 +1080,8 @@ SlicingAlgorithm::extractMDFrameForNonAxisAligned( const auto &referenceMDFrame = m_inWS->getDimension(indicesWithProjection[0])->getMDFrame(); - for (auto it = indicesWithProjection.begin(); - it != indicesWithProjection.end(); ++it) { - const auto &toCheckMDFrame = m_inWS->getDimension(*it)->getMDFrame(); + for (auto &index : indicesWithProjection) { + const auto &toCheckMDFrame = m_inWS->getDimension(index)->getMDFrame(); if (!referenceMDFrame.isSameType(toCheckMDFrame)) { g_log.warning() << "Slicing Algorithm: New basis vector tries to " "mix un-mixable MDFrame types."; diff --git a/Framework/MDAlgorithms/src/SmoothMD.cpp b/Framework/MDAlgorithms/src/SmoothMD.cpp index fa68077e87b67a5bcaf983e47258c445ddef75fb..90f8ec765cd8f680b88ab800d0aeeb4f4c73f67d 100644 --- a/Framework/MDAlgorithms/src/SmoothMD.cpp +++ b/Framework/MDAlgorithms/src/SmoothMD.cpp @@ -157,16 +157,16 @@ SmoothMD::hatSmooth(IMDHistoWorkspace_const_sptr toSmooth, size_t nNeighbours = neighbourIndexes.size(); double sumSignal = iterator->getSignal(); double sumSqError = iterator->getError(); - for (size_t i = 0; i < neighbourIndexes.size(); ++i) { + for (auto neighbourIndex : neighbourIndexes) { if (useWeights) { - if ((*weightingWS)->getSignalAt(neighbourIndexes[i]) == 0) { + if ((*weightingWS)->getSignalAt(neighbourIndex) == 0) { // Nothing measured here. We cannot use that neighbouring point. nNeighbours -= 1; continue; } } - sumSignal += toSmooth->getSignalAt(neighbourIndexes[i]); - double error = toSmooth->getErrorAt(neighbourIndexes[i]); + sumSignal += toSmooth->getSignalAt(neighbourIndex); + double error = toSmooth->getErrorAt(neighbourIndex); sumSqError += (error * error); } @@ -285,8 +285,7 @@ std::map<std::string, std::string> SmoothMD::validateInputs() { "have entries for each dimension of the " "InputWorkspace."); } else { - for (auto it = widthVector.begin(); it != widthVector.end(); ++it) { - const int widthEntry = *it; + for (auto widthEntry : widthVector) { if (widthEntry % 2 == 0) { std::stringstream message; message << widthVectorPropertyName diff --git a/Framework/MDAlgorithms/src/TransformMD.cpp b/Framework/MDAlgorithms/src/TransformMD.cpp index e8343786425bce25b01ccf9975acf4c66ef23372..fb7febe455abb9042ddb8618e835bd03f6f4389f 100644 --- a/Framework/MDAlgorithms/src/TransformMD.cpp +++ b/Framework/MDAlgorithms/src/TransformMD.cpp @@ -82,7 +82,7 @@ void TransformMD::doTransform( API::IMDNode::sortObjByID(boxes); PARALLEL_FOR_IF(!ws->isFileBacked()) - for (int i = 0; i < int(boxes.size()); i++) { + for (int i = 0; i < static_cast<int>(boxes.size()); i++) { PARALLEL_START_INTERUPT_REGION MDBoxBase<MDE, nd> *box = dynamic_cast<MDBoxBase<MDE, nd> *>(boxes[i]); if (box) { diff --git a/Framework/MDAlgorithms/src/UnaryOperationMD.cpp b/Framework/MDAlgorithms/src/UnaryOperationMD.cpp index cf04da6df00755ce518c61ba897fcb95e827d910..1f0e786d9549d7f73335ebe85458824227303481 100644 --- a/Framework/MDAlgorithms/src/UnaryOperationMD.cpp +++ b/Framework/MDAlgorithms/src/UnaryOperationMD.cpp @@ -69,8 +69,7 @@ void UnaryOperationMD::exec() { IAlgorithm_sptr alg = this->createChildAlgorithm(matrixAlg); // Copy all properties from THIS to the non-MD version std::vector<Property *> props = this->getProperties(); - for (size_t i = 0; i < props.size(); i++) { - Property *prop = props[i]; + for (auto prop : props) { alg->setPropertyValue(prop->name(), prop->value()); } alg->execute(); diff --git a/Framework/MDAlgorithms/src/UnitsConversionHelper.cpp b/Framework/MDAlgorithms/src/UnitsConversionHelper.cpp index 6f10c5735bd6534f48f96e153aad834e3277fd44..5f79c7e863a63e1b8ae822b42c040c378fc0fcfd 100644 --- a/Framework/MDAlgorithms/src/UnitsConversionHelper.cpp +++ b/Framework/MDAlgorithms/src/UnitsConversionHelper.cpp @@ -59,9 +59,7 @@ UnitsConversionHelper::analyzeUnitsConversion(const std::string &UnitsFrom, /** Test and check if units conversion really occurs. Return true if unit * conversion happens or false if noConversion mode is selected*/ bool UnitsConversionHelper::isUnitConverted() const { - if (m_UnitCnvrsn == CnvrtToMD::ConvertNo) - return false; - return true; + return m_UnitCnvrsn != CnvrtToMD::ConvertNo; } /** Initialize unit conversion helper * This method is interface to internal initialize method, which actually takes @@ -109,18 +107,12 @@ void UnitsConversionHelper::initialize(const MDWSDescription &targetWSDescr, // the helper function which used in the code below to simplify check if the // variable is in range inline bool inRange(const std::pair<double, double> &range, const double &val) { - if (val >= range.first && val <= range.second) - return true; - else - return false; + return val >= range.first && val <= range.second; } // the helper function which used in the code below to simplify check if the // variable is in range inline bool inRange(const double &xMin, const double &xMax, const double &val) { - if (val >= xMin && val <= xMax) - return true; - else - return false; + return val >= xMin && val <= xMax; } /** Method verify if the Units transformation is well defined in the range diff --git a/Framework/Nexus/src/MuonNexusReader.cpp b/Framework/Nexus/src/MuonNexusReader.cpp index 594dc6d35b4d754ce18b5e55e0353563a411072f..5d93fc6f605fbf622ff958b18eb5f34f9fdf5f73 100644 --- a/Framework/Nexus/src/MuonNexusReader.cpp +++ b/Framework/Nexus/src/MuonNexusReader.cpp @@ -44,9 +44,9 @@ MuonNexusReader::~MuonNexusReader() { void MuonNexusReader::openFirstNXentry(NeXus::File &handle) { std::map<string, string> entries = handle.getEntries(); bool found = false; - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->second == NXENTRY) { - handle.openGroup(it->first, NXENTRY); + for (auto &entrie : entries) { + if (entrie.second == NXENTRY) { + handle.openGroup(entrie.first, NXENTRY); found = true; break; } @@ -78,9 +78,9 @@ void MuonNexusReader::readFromFile(const string &filename) { // find all of the NXdata in the entry std::vector<string> nxdataname; std::map<string, string> entries = handle.getEntries(); - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->second == NXDATA) { - nxdataname.push_back(it->first); + for (auto &entrie : entries) { + if (entrie.second == NXDATA) { + nxdataname.push_back(entrie.first); } } handle.openGroup(nxdataname.front(), NXDATA); @@ -129,8 +129,8 @@ void MuonNexusReader::readFromFile(const string &filename) { // If not available set as one period. entries = handle.getEntries(); t_nper = 1; - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->first == "switching_states") { + for (auto &entrie : entries) { + if (entrie.first == "switching_states") { int ssPeriods; handle.readData("switching_states", ssPeriods); t_nper = abs(ssPeriods); @@ -184,9 +184,9 @@ void MuonNexusReader::readLogData(const string &filename) { // memory // Also get the start_time string needed to change these times into ISO times std::map<string, string> entries = handle.getEntries(); - for (auto it = entries.begin(); it != entries.end(); ++it) { - string nxname = it->first; - string nxclass = it->second; + for (auto &entrie : entries) { + string nxname = entrie.first; + string nxclass = entrie.second; if (nxclass == NXLOG) { handle.openGroup(nxname, nxclass); diff --git a/Framework/Nexus/src/NexusClasses.cpp b/Framework/Nexus/src/NexusClasses.cpp index f0266f90289c01b2342eec5c45e20a207610cb5a..971cb422ba722f0c66af8c7bed06492a0410d02c 100644 --- a/Framework/Nexus/src/NexusClasses.cpp +++ b/Framework/Nexus/src/NexusClasses.cpp @@ -8,15 +8,17 @@ namespace NeXus { std::vector<std::string> NXAttributes::names() const { std::vector<std::string> out; - for (auto it = m_values.cbegin(); it != m_values.cend(); ++it) - out.push_back(it->first); + out.reserve(m_values.size()); + for (const auto &value : m_values) + out.push_back(value.first); return out; } std::vector<std::string> NXAttributes::values() const { std::vector<std::string> out; - for (auto it = m_values.begin(); it != m_values.end(); ++it) - out.push_back(it->second); + out.reserve(m_values.size()); + for (const auto &value : m_values) + out.push_back(value.second); return out; } @@ -593,7 +595,7 @@ Kernel::Property *NXLog::createSingleValueProperty() { } else if (nxType == NX_UINT8) { NXDataSetTyped<unsigned char> value(*this, valAttr); value.load(); - bool state = (value[0] == 0) ? false : true; + bool state = value[0] != 0; prop = new Kernel::PropertyWithValue<bool>(name(), state); } else { prop = NULL; diff --git a/Framework/Nexus/src/NexusFileIO.cpp b/Framework/Nexus/src/NexusFileIO.cpp index b8fae30a21b90fcbd6a1610b028a06283e3be478..d25f071c50eca18566cab26c3bd376a401d71e28 100644 --- a/Framework/Nexus/src/NexusFileIO.cpp +++ b/Framework/Nexus/src/NexusFileIO.cpp @@ -219,9 +219,9 @@ bool NexusFileIO::writeNxStringArray( int dimensions[2]; size_t maxlen = 0; dimensions[0] = static_cast<int>(values.size()); - for (size_t i = 0; i < values.size(); i++) - if (values[i].size() > maxlen) - maxlen = values[i].size(); + for (const auto &value : values) + if (value.size() > maxlen) + maxlen = value.size(); dimensions[1] = static_cast<int>(maxlen); NXstatus status = NXmakedata(fileID, name.c_str(), NX_CHAR, 2, dimensions); if (status == NX_ERROR) @@ -1057,8 +1057,8 @@ bool NexusFileIO::checkAttributeName(const std::string &target) const { // clang-format off const std::vector< ::NeXus::AttrInfo> infos = m_filehandle->getAttrInfos(); // clang-format on - for (auto it = infos.begin(); it != infos.end(); ++it) { - if (target.compare(it->name) == 0) + for (const auto &info : infos) { + if (target.compare(info.name) == 0) return true; } @@ -1141,9 +1141,9 @@ int NexusFileIO::findMantidWSEntries() const { // count int count = 0; std::map<std::string, std::string> entries = m_filehandle->getEntries(); - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->second == "NXentry") { - if (it->first.find("mantid_workspace_") == 0) + for (auto &entrie : entries) { + if (entrie.second == "NXentry") { + if (entrie.first.find("mantid_workspace_") == 0) count++; } } @@ -1154,8 +1154,8 @@ int NexusFileIO::findMantidWSEntries() const { bool NexusFileIO::checkEntryAtLevel(const std::string &item) const { // Search the currently open level for name "item" std::map<std::string, std::string> entries = m_filehandle->getEntries(); - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->first == item) + for (auto &entrie : entries) { + if (entrie.first == item) return true; } @@ -1167,13 +1167,13 @@ bool NexusFileIO::checkEntryAtLevelByAttribute(const std::string &attribute, // Search the currently open level for a section with "attribute" and return // entry name std::map<std::string, std::string> entries = m_filehandle->getEntries(); - for (auto it = entries.begin(); it != entries.end(); ++it) { - if (it->second == "SDS") { - m_filehandle->openData(it->first); + for (auto &entrie : entries) { + if (entrie.second == "SDS") { + m_filehandle->openData(entrie.first); bool result = checkAttributeName(attribute); m_filehandle->closeData(); if (result) { - entry = it->first; + entry = entrie.first; return true; } } @@ -1199,9 +1199,9 @@ bool NexusFileIO::writeNexusBinMasking( const API::MatrixWorkspace::MaskList &mList = ws->maskedBins(i); spectra.push_back(spectra_count); spectra.push_back(offset); - for (auto it = mList.cbegin(); it != mList.cend(); ++it) { - bins.push_back(it->first); - weights.push_back(it->second); + for (const auto &mask : mList) { + bins.push_back(mask.first); + weights.push_back(mask.second); } ++spectra_count; offset += static_cast<int>(mList.size()); @@ -1304,9 +1304,9 @@ int getNexusEntryTypes(const std::string &fileName, } // for each entry found, look for "analysis" or "definition" text data fields // and return value plus entry name - for (size_t i = 0; i < entryList.size(); i++) { + for (auto &entry : entryList) { // - stat = NXopengroup(fileH, entryList[i].c_str(), "NXentry"); + stat = NXopengroup(fileH, entry.c_str(), "NXentry"); // loop through field names in this entry while ((stat = NXgetnextentry(fileH, nxname, nxclass, &nxdatatype)) == NX_OK) { @@ -1326,7 +1326,7 @@ int getNexusEntryTypes(const std::string &fileName, value[dims[0]] = '\0'; // return e.g entryName "analysis"/definition "muonTD" definition.push_back(value); - entryName.push_back(entryList[i]); + entryName.push_back(entry); delete[] value; NXclosegroup(fileH); // close data group, then entry stat = NXclosegroup(fileH); diff --git a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp index 2ac092a9535ec005a8d751bce2be6955df4470d2..b4fe68b8d0c4d452b84629efdc11f6edb3d1023a 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmHistory.cpp @@ -28,8 +28,8 @@ boost::python::object getChildrenAsList(boost::shared_ptr<AlgorithmHistory> self) { boost::python::list names; const auto histories = self->getChildHistories(); - for (auto itr = histories.cbegin(); itr != histories.cend(); ++itr) { - names.append(*itr); + for (const auto &historie : histories) { + names.append(historie); } return names; } @@ -43,8 +43,8 @@ getChildrenAsList(boost::shared_ptr<AlgorithmHistory> self) { boost::python::object getPropertiesAsList(AlgorithmHistory &self) { boost::python::list names; const auto histories = self.getProperties(); - for (auto itr = histories.cbegin(); itr != histories.cend(); ++itr) { - names.append(*itr); + for (const auto &historie : histories) { + names.append(historie); } return names; } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp index 98389b50274b1655e6092168ba3fa90e9145a5e4..691ea8d13c2458c1d1e1d75c34621c14ced250c4 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/AlgorithmManager.cpp @@ -43,11 +43,11 @@ boost::python::list runningInstancesOf(AlgorithmManagerImpl &self, const std::string &algName) { boost::python::list algs; auto mgrAlgs = self.runningInstancesOf(algName); - for (auto iter = mgrAlgs.begin(); iter != mgrAlgs.end(); ++iter) { + for (auto &mgrAlg : mgrAlgs) { // boost 1.41 (RHEL6) can't handle registering IAlgorithm_const_sptr so we // have to cast to IAlgorithm_sptr and then convert to Python // The constness is pretty-irrelevant by this point anyway - algs.append(boost::const_pointer_cast<IAlgorithm>(*iter)); + algs.append(boost::const_pointer_cast<IAlgorithm>(mgrAlg)); } return algs; diff --git a/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp b/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp index d775d56815a6965479931625c480cf0f00fe253a..0eef453ea1d93f637b514afe5f122b9431bd0203 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/CatalogManager.cpp @@ -13,8 +13,8 @@ using namespace boost::python; boost::python::object getActiveSessionsAsList(CatalogManagerImpl &self) { boost::python::list sessions; const auto vecSessions = self.getActiveSessions(); - for (auto itr = vecSessions.begin(); itr != vecSessions.end(); ++itr) { - sessions.append(*itr); + for (const auto &vecSession : vecSessions) { + sessions.append(vecSession); } return sessions; } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp b/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp index c8858c3ad77b2fae30af9496691394e1f228b2a2..8872a668ebe7f449a1a421cf5ce94cf1bf09bff6 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/FunctionFactory.cpp @@ -34,8 +34,8 @@ PyObject *getFunctionNames(FunctionFactoryImpl &self) { self.getFunctionNames<Mantid::API::IFunction>(); PyObject *registered = PyList_New(0); - for (auto name = names.begin(); name != names.end(); ++name) { - PyObject *value = PyString_FromString(name->c_str()); + for (const auto &name : names) { + PyObject *value = PyString_FromString(name.c_str()); if (PyList_Append(registered, value)) throw std::runtime_error("Failed to insert value into PyList"); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp b/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp index 61726399180bcf4f23b95ece5ea9b426b8300315..f36dfcda062b1d7e468f61f0cd97b514f2080b06 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/IAlgorithm.cpp @@ -144,8 +144,7 @@ PyObject *getOutputProperties(IAlgorithm &self) { const PropertyVector &properties(self.getProperties()); // No copy // Build the list PyObject *names = PyList_New(0); - for (auto itr = properties.cbegin(); itr != properties.cend(); ++itr) { - Property *p = *itr; + for (auto p : properties) { if (p->direction() == Direction::Output) { PyList_Append(names, PyString_FromString(p->name().c_str())); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp b/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp index a1c53ca6998b84c10a00cdad589dc986897167d0..ee401e48f8f70286003e52305417ffa8509a6358 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/IFunction.cpp @@ -22,9 +22,8 @@ PyObject *getCategories(IFunction &self) { std::vector<std::string> categories = self.categories(); PyObject *registered = PyList_New(0); - for (auto category = categories.begin(); category != categories.end(); - ++category) { - PyObject *value = PyString_FromString(category->c_str()); + for (auto &categorie : categories) { + PyObject *value = PyString_FromString(categorie.c_str()); if (PyList_Append(registered, value)) throw std::runtime_error("Failed to insert value into PyList"); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp b/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp index 0b2dd40fd55a3ba4a224aa9d5fa8679e7c113ef1..b1fdc544b48303ff0d5003e0e388374365c11ab6 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/ITableWorkspace.cpp @@ -293,9 +293,9 @@ void addRowFromDict(ITableWorkspace &self, const bpl::dict &rowItems) { try { // Retrieve and set the value for each column auto columns = self.getColumnNames(); - for (auto iter = columns.begin(); iter != columns.end(); ++iter) { - column = self.getColumn(*iter); - value = rowItems[*iter]; + for (auto &iter : columns) { + column = self.getColumn(iter); + value = rowItems[iter]; setValue(column, rowIndex, value); } } catch (bpl::error_already_set &) { diff --git a/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp b/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp index c739bc51666f77b172acb054c3266249488ec7d7..83d57c115566483a54f6dfdc0121d93f54073495 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/MDGeometry.cpp @@ -25,9 +25,9 @@ boost::python::list getNonIntegratedDimensionsAsPyList(const MDGeometry &self) { auto dimensions = self.getNonIntegratedDimensions(); boost::python::list nonIntegrated; - for (auto it = dimensions.begin(); it != dimensions.end(); ++it) { + for (auto &dimension : dimensions) { nonIntegrated.append( - boost::const_pointer_cast<Mantid::Geometry::IMDDimension>(*it)); + boost::const_pointer_cast<Mantid::Geometry::IMDDimension>(dimension)); } return nonIntegrated; } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp b/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp index 132fa48226b451e945e573c600db1899a5c01ba7..2483eab62bcec70d783d95b9060f8a0c5b152559 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/MultipleFileProperty.cpp @@ -30,16 +30,13 @@ boost::python::object valueAsPyObject(MultipleFileProperty &self) { } else { // Build a list of lists to mimic the behaviour of MultipleFileProperty boost::python::list fileList; - for (auto outerItr = propValue.begin(); outerItr != propValue.end(); - ++outerItr) { - const std::vector<std::string> &filenames = *outerItr; + for (const auto &filenames : propValue) { if (filenames.size() == 1) { fileList.append(filenames.front()); } else { boost::python::list groupList; - for (auto innerItr = filenames.begin(); innerItr != filenames.end(); - ++innerItr) { - groupList.append(*innerItr); + for (const auto &filename : filenames) { + groupList.append(filename); } fileList.append(groupList); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp b/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp index 44476286f56605ed104cc43f1b63e67798582e42..2c0c62022eea928e9527a2271db9f3ad29be0cc5 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/Run.cpp @@ -103,8 +103,8 @@ bpl::object get(bpl::object self, bpl::object key) { bpl::list keys(Run &self) { const std::vector<Mantid::Kernel::Property *> &logs = self.getProperties(); bpl::list names; - for (auto iter = logs.begin(); iter != logs.end(); ++iter) { - names.append((*iter)->name()); + for (auto log : logs) { + names.append(log->name()); } return names; } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp b/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp index 2422b6c7a81b3dace66d938011db87ac2ac29173..a0eeb99a7c0a582a21ef0a7263e80440823fe9e3 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/ScriptRepository.cpp @@ -23,8 +23,8 @@ PyObject *getListFiles(ScriptRepository &self) { std::vector<std::string> files = self.listFiles(); PyObject *registered = PyList_New(0); - for (auto file = files.begin(); file != files.end(); ++file) { - PyObject *value = PyString_FromString(file->c_str()); + for (auto &file : files) { + PyObject *value = PyString_FromString(file.c_str()); if (PyList_Append(registered, value)) throw std::runtime_error("Failed to insert value into PyList"); } diff --git a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp index 7248c1da1feb5bf764896487ed19413c77978624..3c4de854317dd25626992217100d71bd31315712 100644 --- a/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp +++ b/Framework/PythonInterface/mantid/api/src/Exports/WorkspaceHistory.cpp @@ -26,8 +26,8 @@ namespace Policies = Mantid::PythonInterface::Policies; boost::python::object getHistoriesAsList(WorkspaceHistory &self) { boost::python::list names; const auto histories = self.getAlgorithmHistories(); - for (auto itr = histories.cbegin(); itr != histories.cend(); ++itr) { - names.append(*itr); + for (const auto &historie : histories) { + names.append(historie); } return names; } diff --git a/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp b/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp index 28565ab5935ed0fbe38202afe72b96b047313d6d..84ef562c4f59ff2c8639eacc9ba3e526a3168e69 100644 --- a/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp +++ b/Framework/PythonInterface/mantid/geometry/src/Exports/Group.cpp @@ -19,8 +19,8 @@ std::vector<std::string> getSymmetryOperationStrings(Group &self) { const std::vector<SymmetryOperation> &symOps = self.getSymmetryOperations(); std::vector<std::string> pythonSymOps; - for (auto it = symOps.begin(); it != symOps.end(); ++it) { - pythonSymOps.push_back((*it).identifier()); + for (const auto &symOp : symOps) { + pythonSymOps.push_back(symOp.identifier()); } return pythonSymOps; diff --git a/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp b/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp index fd15ca2e476a3037d33bc05b976ad7a703d8de7b..769dd21cf70f83f997fdd915376951913127dce5 100644 --- a/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp +++ b/Framework/PythonInterface/mantid/geometry/src/Exports/PointGroup.cpp @@ -27,8 +27,8 @@ boost::python::list getEquivalents(PointGroup &self, const object &hkl) { self.getEquivalents(Converters::PyObjectToV3D(hkl)()); boost::python::list pythonEquivalents; - for (auto it = equivalents.begin(); it != equivalents.end(); ++it) { - pythonEquivalents.append(*it); + for (const auto &equivalent : equivalents) { + pythonEquivalents.append(equivalent); } return pythonEquivalents; diff --git a/Framework/PythonInterface/mantid/geometry/src/Exports/ReflectionGenerator.cpp b/Framework/PythonInterface/mantid/geometry/src/Exports/ReflectionGenerator.cpp index 83882c117af6c3965b0e7ed3aae8a75d9dab063b..aff0aa0002693e088ac9c1d2d28983f9f7355379 100644 --- a/Framework/PythonInterface/mantid/geometry/src/Exports/ReflectionGenerator.cpp +++ b/Framework/PythonInterface/mantid/geometry/src/Exports/ReflectionGenerator.cpp @@ -12,8 +12,8 @@ using namespace boost::python; namespace { boost::python::list getListFromV3DVector(const std::vector<V3D> &hkls) { boost::python::list hklList; - for (auto it = hkls.begin(); it != hkls.end(); ++it) { - hklList.append(*it); + for (const auto &hkl : hkls) { + hklList.append(hkl); } return hklList; } diff --git a/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp b/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp index 919d784341e24fcb868e2eff89e92e5523843112..736756a095a01629a317d8576f70f61507f8a36b 100644 --- a/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp +++ b/Framework/PythonInterface/mantid/geometry/src/Exports/SpaceGroup.cpp @@ -25,8 +25,8 @@ boost::python::list getEquivalentPositions(SpaceGroup &self, self.getEquivalentPositions(Converters::PyObjectToV3D(point)()); boost::python::list pythonEquivalents; - for (auto it = equivalents.begin(); it != equivalents.end(); ++it) { - pythonEquivalents.append(*it); + for (const auto &equivalent : equivalents) { + pythonEquivalents.append(equivalent); } return pythonEquivalents; diff --git a/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp b/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp index 147ff1e85375cdc32b7c96902b8a1d4fb9ab5104..96222d9b2581d66432b05db8ba2313ce55142c22 100644 --- a/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp +++ b/Framework/PythonInterface/mantid/geometry/src/Exports/SymmetryOperationFactory.cpp @@ -13,8 +13,8 @@ boost::python::list createSymOps(SymmetryOperationFactoryImpl &self, std::vector<SymmetryOperation> symOps = self.createSymOps(identifiers); boost::python::list pythonOperations; - for (auto it = symOps.begin(); it != symOps.end(); ++it) { - pythonOperations.append(*it); + for (auto &symOp : symOps) { + pythonOperations.append(symOp); } return pythonOperations; diff --git a/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp b/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp index ebb53d0a943d56506b82f5cddcb6d15141a43ff6..d8c4798fefc5c3575719869271f09f158dfca28d 100644 --- a/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp +++ b/Framework/RemoteAlgorithms/src/QueryAllRemoteJobs2.cpp @@ -84,16 +84,16 @@ void QueryAllRemoteJobs2::exec() { std::vector<std::string> startDates; std::vector<std::string> completionDates; std::vector<std::string> cmdLine; - for (size_t j = 0; j < infos.size(); ++j) { - jobIds.push_back(infos[j].id); - jobNames.push_back(infos[j].name); - jobStatusStrs.push_back(infos[j].status); - transIds.push_back(infos[j].transactionID); - runNames.push_back(infos[j].runnableName); - submitDates.push_back(infos[j].submitDate.toISO8601String()); - startDates.push_back(infos[j].startDate.toISO8601String()); - completionDates.push_back(infos[j].completionTime.toISO8601String()); - cmdLine.push_back(infos[j].cmdLine); + for (auto &info : infos) { + jobIds.push_back(info.id); + jobNames.push_back(info.name); + jobStatusStrs.push_back(info.status); + transIds.push_back(info.transactionID); + runNames.push_back(info.runnableName); + submitDates.push_back(info.submitDate.toISO8601String()); + startDates.push_back(info.startDate.toISO8601String()); + completionDates.push_back(info.completionTime.toISO8601String()); + cmdLine.push_back(info.cmdLine); } setProperty("JobID", jobIds); setProperty("JobStatusString", jobStatusStrs); diff --git a/Framework/RemoteAlgorithms/src/QueryRemoteFile.cpp b/Framework/RemoteAlgorithms/src/QueryRemoteFile.cpp index 1866d01f12b7e810c2f60537bc0128f01ae47376..7883a6825a49cc06bc63f12bcaa6cf55d765e803 100644 --- a/Framework/RemoteAlgorithms/src/QueryRemoteFile.cpp +++ b/Framework/RemoteAlgorithms/src/QueryRemoteFile.cpp @@ -69,8 +69,8 @@ void QueryRemoteFile::exec() { std::vector<std::string> filenames; std::string oneFile; resp["Files"].getValue(files); - for (unsigned int i = 0; i < files.size(); i++) { - files[i].getValue(oneFile); + for (auto &file : files) { + file.getValue(oneFile); filenames.push_back(oneFile); } diff --git a/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp b/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp index 987fc4a164c7598fc7e6cc4c69e3d9b4ef556440..12f692e5d0ce159e1e420053dbd64561314f1c31 100644 --- a/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp +++ b/Framework/RemoteAlgorithms/src/SCARFTomoReconstruction.cpp @@ -475,13 +475,14 @@ void SCARFTomoReconstruction::doSubmit(const std::string &username) { // %J.error" // Two applications are for now registered on SCARF: - // TOMOPY_0_0_3, PYASTRATOOLBOX_1_1 - std::string appName = "TOMOPY_0_0_3"; + // TOMOPY_0_0_3, PYASTRATOOLBOX_1_1 - old versions + // TOMOPY_0_1_9, PYASTRATOOLBOX_1_6 - newer versions (Dec 2015) + std::string appName = "TOMOPY_0_1_9"; // Basic attempt at guessing the app that we might really need. This // is not fixed/unstable at the moment - if (runnablePath.find("astra-2d-FBP") != std::string::npos || - runnablePath.find("astra-3d-SIRT3D") != std::string::npos) { - appName = "PYASTRATOOLBOX_1_1"; + if (runnablePath.find("--tool astra") != std::string::npos || + runnablePath.find("--tool=astra") != std::string::npos) { + appName = "PYASTRATOOLBOX_1_6"; } // this gets executed (for example via 'exec' or 'python', depending on the @@ -1448,8 +1449,8 @@ void SCARFTomoReconstruction::getAllJobFiles(const std::string &jobId, while (std::getline(ss, PACname, ';')) { filePACNames.push_back(PACname); } - for (size_t i = 0; i < filePACNames.size(); i++) { - getOneJobFile(jobId, filePACNames[i], localDir, t); + for (auto &filePACName : filePACNames) { + getOneJobFile(jobId, filePACName, localDir, t); } } } else { diff --git a/Framework/RemoteJobManagers/src/LSFJobManager.cpp b/Framework/RemoteJobManagers/src/LSFJobManager.cpp index 9d05616b51fef9594ac19c56457c384c2ac6e434..9f8ecb32f5e23813e1724a0560d4a8bf57f97b5b 100644 --- a/Framework/RemoteJobManagers/src/LSFJobManager.cpp +++ b/Framework/RemoteJobManagers/src/LSFJobManager.cpp @@ -460,8 +460,8 @@ void LSFJobManager::stopRemoteTransaction(const std::string &transactionID) { it->second.stopped = true; std::vector<std::string> jobs = it->second.jobIDs; - for (size_t i = 0; i < jobs.size(); i++) { - abortRemoteJob(jobs[i]); + for (auto &job : jobs) { + abortRemoteJob(job); } g_transactions.erase(it); } @@ -573,10 +573,13 @@ std::string LSFJobManager::submitRemoteJob(const std::string &transactionID, addJobInTransaction(jobID); g_log.debug() << "Submitted job, got ID: " << iid << std::endl; } catch (std::exception &e) { - g_log.warning() << "The job has been submitted but the code returned does " - "not seem well formed: '" + - jobID + "'. Detailed error: " + - e.what() << std::endl; + g_log.warning() + << "The job has been submitted but the job ID returned does " + "not seem well formed. Job ID string from server: '" + + jobID + "'. Detailed error when tryint to interpret the code " + "returned as an integer: " + + e.what() + << std::endl; } return jobID; @@ -1223,8 +1226,8 @@ void LSFJobManager::getAllJobFiles(const std::string &jobId, while (std::getline(ss, PACname, ';')) { filePACNames.push_back(PACname); } - for (size_t i = 0; i < filePACNames.size(); i++) { - getOneJobFile(jobId, filePACNames[i], localDir, t); + for (auto &filePACName : filePACNames) { + getOneJobFile(jobId, filePACName, localDir, t); } } } else { diff --git a/Framework/RemoteJobManagers/src/MantidWebServiceAPIJobManager.cpp b/Framework/RemoteJobManagers/src/MantidWebServiceAPIJobManager.cpp index 902e855709a190257ca124d3a65f6eed251c3aca..d9fbd93802ca3a2d4fbb8eb2f435ca7128be1a63 100644 --- a/Framework/RemoteJobManagers/src/MantidWebServiceAPIJobManager.cpp +++ b/Framework/RemoteJobManagers/src/MantidWebServiceAPIJobManager.cpp @@ -255,8 +255,8 @@ std::vector<std::string> MantidWebServiceAPIJobManager::queryRemoteFile( JSONArray files; std::string oneFile; resp["Files"].getValue(files); - for (unsigned int i = 0; i < files.size(); i++) { - files[i].getValue(oneFile); + for (auto &file : files) { + file.getValue(oneFile); filenames.push_back(oneFile); } diff --git a/Framework/RemoteJobManagers/src/SCARFLSFJobManager.cpp b/Framework/RemoteJobManagers/src/SCARFLSFJobManager.cpp index 7bec491000078a86c2884d6a78d149392a259918..94f9e1b3c4885ae36411e9c1d1fdb785a9d12f22 100644 --- a/Framework/RemoteJobManagers/src/SCARFLSFJobManager.cpp +++ b/Framework/RemoteJobManagers/src/SCARFLSFJobManager.cpp @@ -224,8 +224,7 @@ std::string SCARFLSFJobManager::urlComponentEncode(const std::string &in) { out.fill('0'); out << std::hex; - for (std::string::const_iterator i = in.begin(), n = in.end(); i != n; ++i) { - std::string::value_type c = (*i); + for (char c : in) { // unreserved characters go through, where: // unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') { @@ -241,17 +240,21 @@ std::string SCARFLSFJobManager::urlComponentEncode(const std::string &in) { std::string SCARFLSFJobManager::guessJobSubmissionAppName(const std::string &runnablePath, const std::string &jobOptions) { - UNUSED_ARG(jobOptions); + UNUSED_ARG(runnablePath); // Two applications are for now registered and being used on SCARF: - // TOMOPY_0_0_3, PYASTRATOOLBOX_1_1 - std::string appName = "TOMOPY_0_0_3"; + // tomopy and astra toolbox + // The first versions installed were: TOMOPY_0_0_3, PYASTRATOOLBOX_1_1 + // The last versions installed as of this writing are: + // TOMOPY_0_1_9, PYASTRATOOLBOX_1_6 + // Default: tomopy, as it loads the python module/environment + std::string appName = "TOMOPY_0_1_9"; // Basic guess of the app that we might really need. Not // fixed/unstable at the moment - if (runnablePath.find("astra-2d-FBP") != std::string::npos || - runnablePath.find("astra-3d-SIRT3D") != std::string::npos) { - appName = "PYASTRATOOLBOX_1_1"; + if (jobOptions.find("--tool astra") != std::string::npos || + jobOptions.find("--tool=astra") != std::string::npos) { + appName = "PYASTRATOOLBOX_1_6"; } return appName; diff --git a/Framework/SINQ/src/PoldiAnalyseResiduals.cpp b/Framework/SINQ/src/PoldiAnalyseResiduals.cpp index cd9b37b2e687c9f63c372b4a7c02e6516c4f850d..3966fcde4c956381d14007a4b5f7e3d7cd533edb 100644 --- a/Framework/SINQ/src/PoldiAnalyseResiduals.cpp +++ b/Framework/SINQ/src/PoldiAnalyseResiduals.cpp @@ -52,13 +52,12 @@ const std::string PoldiAnalyseResiduals::summary() const { double PoldiAnalyseResiduals::sumCounts( const DataObjects::Workspace2D_sptr &workspace, const std::vector<int> &workspaceIndices) const { - double sum = 0.0; - for (size_t i = 0; i < workspaceIndices.size(); ++i) { - const MantidVec &counts = workspace->readY(workspaceIndices[i]); - sum += std::accumulate(counts.begin(), counts.end(), 0.0); - } - - return sum; + return std::accumulate( + workspaceIndices.begin(), workspaceIndices.end(), 0.0, + [&workspace](double sum, int workspaceIndex) { + const MantidVec &counts = workspace->readY(workspaceIndex); + return sum + std::accumulate(counts.begin(), counts.end(), 0.0); + }); } /// Counts the number of values in each spectrum specified by the list of @@ -66,13 +65,12 @@ double PoldiAnalyseResiduals::sumCounts( size_t PoldiAnalyseResiduals::numberOfPoints( const DataObjects::Workspace2D_sptr &workspace, const std::vector<int> &workspaceIndices) const { - size_t sum = 0; - for (size_t i = 0; i < workspaceIndices.size(); ++i) { - const MantidVec &counts = workspace->readY(workspaceIndices[i]); - sum += counts.size(); - } - - return sum; + return std::accumulate( + workspaceIndices.begin(), workspaceIndices.end(), size_t{0}, + [&workspace](size_t sum, int workspaceIndex) { + const MantidVec &counts = workspace->readY(workspaceIndex); + return sum + counts.size(); + }); } /// Adds the specified value to all spectra specified by the given workspace @@ -80,10 +78,10 @@ size_t PoldiAnalyseResiduals::numberOfPoints( void PoldiAnalyseResiduals::addValue( DataObjects::Workspace2D_sptr &workspace, double value, const std::vector<int> &workspaceIndices) const { - for (size_t i = 0; i < workspaceIndices.size(); ++i) { - MantidVec &counts = workspace->dataY(workspaceIndices[i]); - for (size_t j = 0; j < counts.size(); ++j) { - counts[j] += value; + for (auto workspaceIndex : workspaceIndices) { + MantidVec &counts = workspace->dataY(workspaceIndex); + for (double &count : counts) { + count += value; } } } @@ -196,8 +194,8 @@ double PoldiAnalyseResiduals::relativeCountChange( const DataObjects::Workspace2D_sptr &sum, double totalMeasuredCounts) { const MantidVec &corrCounts = sum->readY(0); double csum = 0.0; - for (auto it = corrCounts.begin(); it != corrCounts.end(); ++it) { - csum += fabs(*it); + for (double corrCount : corrCounts) { + csum += fabs(corrCount); } return csum / totalMeasuredCounts * 100.0; diff --git a/Framework/SINQ/src/PoldiAutoCorrelation5.cpp b/Framework/SINQ/src/PoldiAutoCorrelation5.cpp index 19268cd7d020a1615891a1f48cae15cb119579bb..e27f4009d9ad3a143e49fc3e5a41db8fc5c93eb1 100644 --- a/Framework/SINQ/src/PoldiAutoCorrelation5.cpp +++ b/Framework/SINQ/src/PoldiAutoCorrelation5.cpp @@ -153,8 +153,8 @@ void PoldiAutoCorrelation5::logConfigurationInformation( g_log.information() << "_Poldi - Number of dead wires: " << deadWires.size() << std::endl; g_log.information() << "_Poldi - Wire indices: "; - for (auto dw = deadWires.cbegin(); dw != deadWires.cend(); ++dw) { - g_log.information() << *dw << " "; + for (auto deadWire : deadWires) { + g_log.information() << deadWire << " "; } g_log.information() << std::endl; } diff --git a/Framework/SINQ/src/PoldiFitPeaks1D2.cpp b/Framework/SINQ/src/PoldiFitPeaks1D2.cpp index f5f89dcb7ad90eaa1b1b9be280bd1612a47479c8..421338f044b7b79449b08a563e8641e7e6f05e5a 100644 --- a/Framework/SINQ/src/PoldiFitPeaks1D2.cpp +++ b/Framework/SINQ/src/PoldiFitPeaks1D2.cpp @@ -231,8 +231,8 @@ PoldiFitPeaks1D2::getRangeProfile(const RefinedRange_sptr &range, int n) const { totalProfile->initialize(); std::vector<PoldiPeak_sptr> peaks = range->getPeaks(); - for (auto it = peaks.begin(); it != peaks.end(); ++it) { - totalProfile->addFunction(getPeakProfile(*it)); + for (auto &peak : peaks) { + totalProfile->addFunction(getPeakProfile(peak)); } totalProfile->addFunction(FunctionFactory::Instance().createInitialized( @@ -288,8 +288,7 @@ PoldiFitPeaks1D2::fitPeaks(const PoldiPeakCollection_sptr &peaks) { Workspace2D_sptr dataWorkspace = getProperty("InputWorkspace"); m_fitplots->removeAll(); - for (size_t i = 0; i < reducedRanges.size(); ++i) { - RefinedRange_sptr currentRange = reducedRanges[i]; + for (auto currentRange : reducedRanges) { int nMin = getBestChebyshevPolynomialDegree(dataWorkspace, currentRange); if (nMin > -1) { diff --git a/Framework/SINQ/src/PoldiFitPeaks2D.cpp b/Framework/SINQ/src/PoldiFitPeaks2D.cpp index 4da20abea08a71634ecedcaa74a59d80ac31c884..42d4ebe9bfea03addf787e152ba6a434ebe8e001 100644 --- a/Framework/SINQ/src/PoldiFitPeaks2D.cpp +++ b/Framework/SINQ/src/PoldiFitPeaks2D.cpp @@ -160,10 +160,10 @@ PoldiFitPeaks2D::getNormalizedPeakCollections( std::vector<PoldiPeakCollection_sptr> normalizedPeakCollections; - for (auto pc = peakCollections.begin(); pc != peakCollections.end(); ++pc) { + for (const auto &peakCollection : peakCollections) { // First integrate peak collection, then normalize and append to vector PoldiPeakCollection_sptr integratedPeakCollection = - getIntegratedPeakCollection(*pc); + getIntegratedPeakCollection(peakCollection); normalizedPeakCollections.push_back( getNormalizedPeakCollection(integratedPeakCollection)); @@ -671,21 +671,20 @@ PoldiFitPeaks2D::getUserSpecifiedTies(const IFunction_sptr &poldiFn) { std::vector<std::string> parameters = poldiFn->getParameterNames(); std::vector<std::string> tieComponents; - for (auto it = tieParameters.begin(); it != tieParameters.end(); ++it) { - if (!(*it).empty()) { + for (auto &tieParameter : tieParameters) { + if (!tieParameter.empty()) { std::vector<std::string> matchedParameters; - for (auto parName = parameters.begin(); parName != parameters.end(); - ++parName) { - if (boost::algorithm::ends_with(*parName, *it)) { - matchedParameters.push_back(*parName); + for (auto ¶meter : parameters) { + if (boost::algorithm::ends_with(parameter, tieParameter)) { + matchedParameters.push_back(parameter); } } switch (matchedParameters.size()) { case 0: - g_log.warning("Function does not have a parameter called '" + *it + - "', ignoring."); + g_log.warning("Function does not have a parameter called '" + + tieParameter + "', ignoring."); break; case 1: g_log.warning("There is only one peak, no ties necessary."); @@ -983,9 +982,9 @@ IAlgorithm_sptr PoldiFitPeaks2D::calculateSpectrum( Poldi2DFunction_sptr mdFunction(new Poldi2DFunction); // Add one Poldi2DFunction for each peak collection - for (auto pc = normalizedPeakCollections.begin(); - pc != normalizedPeakCollections.end(); ++pc) { - mdFunction->addFunction(getFunctionFromPeakCollection(*pc)); + for (auto &normalizedPeakCollection : normalizedPeakCollections) { + mdFunction->addFunction( + getFunctionFromPeakCollection(normalizedPeakCollection)); } // And finally background terms @@ -1267,8 +1266,8 @@ void PoldiFitPeaks2D::exec() { Property *profileFunctionProperty = getPointerToProperty("PeakProfileFunction"); if (!profileFunctionProperty->isDefault()) { - for (auto pc = peakCollections.begin(); pc != peakCollections.end(); ++pc) { - (*pc)->setProfileFunctionName(profileFunctionProperty->value()); + for (auto &peakCollection : peakCollections) { + peakCollection->setProfileFunctionName(profileFunctionProperty->value()); } } @@ -1299,8 +1298,8 @@ void PoldiFitPeaks2D::exec() { } else { WorkspaceGroup_sptr peaksGroup = boost::make_shared<WorkspaceGroup>(); - for (auto pc = integralPeaks.begin(); pc != integralPeaks.end(); ++pc) { - peaksGroup->addWorkspace((*pc)->asTableWorkspace()); + for (auto &integralPeak : integralPeaks) { + peaksGroup->addWorkspace(integralPeak->asTableWorkspace()); } setProperty("RefinedPoldiPeakWorkspace", peaksGroup); @@ -1333,8 +1332,8 @@ void PoldiFitPeaks2D::exec() { } else { WorkspaceGroup_sptr cellsGroup = boost::make_shared<WorkspaceGroup>(); - for (auto it = cells.begin(); it != cells.end(); ++it) { - cellsGroup->addWorkspace(*it); + for (auto &cell : cells) { + cellsGroup->addWorkspace(cell); } setProperty("RefinedCellParameters", cellsGroup); diff --git a/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp b/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp index 1622defb7487a3a865b0abd7f8badde466c7688b..84c96e9a4b754a0650c2bad3ead340f0ee354acc 100644 --- a/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp +++ b/Framework/SINQ/src/PoldiIndexKnownCompounds.cpp @@ -163,11 +163,11 @@ void PoldiIndexKnownCompounds::initializeIndexedPeaks( m_indexedPeaks.clear(); - for (size_t i = 0; i < expectedPhases.size(); ++i) { + for (const auto &expectedPhase : expectedPhases) { PoldiPeakCollection_sptr newCollection = boost::make_shared<PoldiPeakCollection>( m_measuredPeaks->intensityType()); - newCollection->setPointGroup(expectedPhases[i]->pointGroup()); + newCollection->setPointGroup(expectedPhase->pointGroup()); newCollection->setProfileFunctionName( m_measuredPeaks->getProfileFunctionName()); @@ -200,10 +200,10 @@ std::vector<Workspace_sptr> PoldiIndexKnownCompounds::getWorkspaces( const std::vector<std::string> &workspaceNames) const { std::vector<Workspace_sptr> workspaces; - for (auto it = workspaceNames.begin(); it != workspaceNames.end(); ++it) { + for (const auto &workspaceName : workspaceNames) { try { Workspace_sptr currentWorkspace = - AnalysisDataService::Instance().retrieveWS<Workspace>(*it); + AnalysisDataService::Instance().retrieveWS<Workspace>(workspaceName); WorkspaceGroup_sptr groupTest = boost::dynamic_pointer_cast<WorkspaceGroup>(currentWorkspace); @@ -231,9 +231,9 @@ std::vector<PoldiPeakCollection_sptr> PoldiIndexKnownCompounds::getPeakCollections( const std::vector<Workspace_sptr> &workspaces) const { std::vector<PoldiPeakCollection_sptr> peakCollections; - for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { + for (const auto &workspace : workspaces) { TableWorkspace_sptr tableWs = - boost::dynamic_pointer_cast<TableWorkspace>(*it); + boost::dynamic_pointer_cast<TableWorkspace>(workspace); if (!tableWs) { throw std::invalid_argument( @@ -251,8 +251,8 @@ std::vector<std::string> PoldiIndexKnownCompounds::getWorkspaceNames( const std::vector<Workspace_sptr> &workspaces) const { std::vector<std::string> names; - for (auto it = workspaces.begin(); it != workspaces.end(); ++it) { - names.push_back((*it)->getName()); + for (const auto &workspace : workspaces) { + names.push_back(workspace->getName()); } return names; @@ -333,12 +333,12 @@ std::vector<double> PoldiIndexKnownCompounds::getNormalizedContributions( } std::vector<double> normalizedContributions; - for (auto it = contributions.begin(); it != contributions.end(); ++it) { - if (*it < 0.0) { + for (double contribution : contributions) { + if (contribution < 0.0) { throw std::invalid_argument("Contributions less than 0 are not allowed."); } - normalizedContributions.push_back(*it / sum); + normalizedContributions.push_back(contribution / sum); } return normalizedContributions; @@ -394,9 +394,9 @@ void PoldiIndexKnownCompounds::scaleToExperimentalValues( double maximumExperimentalIntensity = getMaximumIntensity(measuredPeaks); double maximumCalculatedIntensity = 0.0; - for (auto it = peakCollections.begin(); it != peakCollections.end(); ++it) { - maximumCalculatedIntensity = - std::max(getMaximumIntensity(*it), maximumCalculatedIntensity); + for (const auto &peakCollection : peakCollections) { + maximumCalculatedIntensity = std::max(getMaximumIntensity(peakCollection), + maximumCalculatedIntensity); } scaleIntensityEstimates(peakCollections, @@ -705,9 +705,8 @@ void PoldiIndexKnownCompounds::assignCandidates( * inserted into the * peak collection that holds unindexed peaks. */ - for (auto it = unassignedMeasuredPeaks.begin(); - it != unassignedMeasuredPeaks.end(); ++it) { - collectUnindexedPeak(*it); + for (const auto &unassignedMeasuredPeak : unassignedMeasuredPeaks) { + collectUnindexedPeak(unassignedMeasuredPeak); } } @@ -738,8 +737,8 @@ PoldiIndexKnownCompounds::getIntensitySortedPeakCollection( PoldiPeakCollection_sptr sortedPeaks = boost::make_shared<PoldiPeakCollection>(peaks->intensityType()); - for (size_t i = 0; i < peakVector.size(); ++i) { - sortedPeaks->addPeak(peakVector[i]->clone()); + for (auto &peak : peakVector) { + sortedPeaks->addPeak(peak->clone()); } return sortedPeaks; diff --git a/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp b/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp index fbc92a1f93d215150e4d9bbad871d86e3a8ea156..7753d6d044d508b04552625c74c1d921163d4318 100644 --- a/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp +++ b/Framework/SINQ/src/PoldiUtilities/PoldiAutoCorrelationCore.cpp @@ -267,9 +267,8 @@ std::vector<double> PoldiAutoCorrelationCore::calculateDWeights( std::vector<double> tofs; tofs.reserve(tofsFor1Angstrom.size()); - for (auto tofFor1Angstrom = tofsFor1Angstrom.cbegin(); - tofFor1Angstrom != tofsFor1Angstrom.cend(); ++tofFor1Angstrom) { - tofs.push_back(*tofFor1Angstrom * deltaD); + for (double tofFor1Angstrom : tofsFor1Angstrom) { + tofs.push_back(tofFor1Angstrom * deltaD); } double sum = std::accumulate(tofs.begin(), tofs.end(), 0.0); @@ -301,8 +300,7 @@ PoldiAutoCorrelationCore::getRawCorrelatedIntensity(double dValue, std::vector<UncertainValue> current; current.reserve(m_chopper->slitTimes().size()); - for (auto slitOffset = m_chopper->slitTimes().cbegin(); - slitOffset != m_chopper->slitTimes().cend(); ++slitOffset) { + for (double slitOffset : m_chopper->slitTimes()) { /* For each offset, the sum of correlation intensity and error (for each * detector element) * is computed from the counts in the space/time location possible for @@ -314,7 +312,7 @@ PoldiAutoCorrelationCore::getRawCorrelatedIntensity(double dValue, std::vector<UncertainValue> cmess(m_detector->elementCount()); std::transform(m_indices.begin(), m_indices.end(), cmess.begin(), boost::bind(&PoldiAutoCorrelationCore::getCMessAndCSigma, - this, dValue, *slitOffset, _1)); + this, dValue, slitOffset, _1)); UncertainValue sum = std::accumulate(cmess.begin(), cmess.end(), UncertainValue(0.0, 0.0), @@ -574,10 +572,9 @@ PoldiAutoCorrelationCore::getDistances(const std::vector<int> &elements) const { std::vector<double> distances; distances.reserve(elements.size()); - for (auto element = elements.cbegin(); element != elements.cend(); - ++element) { + for (auto element : elements) { distances.push_back(chopperDistance + - m_detector->distanceFromSample(*element)); + m_detector->distanceFromSample(element)); } return distances; @@ -684,9 +681,8 @@ double PoldiAutoCorrelationCore::getSumOfCounts( double sum = 0.0; for (int t = 0; t < timeBinCount; ++t) { - for (auto e = detectorElements.cbegin(); e != detectorElements.cend(); - ++e) { - sum += getCounts(*e, t); + for (auto detectorElement : detectorElements) { + sum += getCounts(detectorElement, t); } } diff --git a/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp b/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp index ec3e8788dcba75c6aa1f036b0b723e58e0e2ea0c..3dc19e556a08040566a8af759b398854cf8dce63 100644 --- a/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp +++ b/Framework/SINQ/src/PoldiUtilities/PoldiPeakCollection.cpp @@ -60,8 +60,8 @@ PoldiPeakCollection_sptr PoldiPeakCollection::clone() { clone->setPointGroup(m_pointGroup); clone->setUnitCell(m_unitCell); - for (size_t i = 0; i < m_peaks.size(); ++i) { - clone->addPeak(m_peaks[i]->clone()); + for (auto &peak : m_peaks) { + clone->addPeak(peak->clone()); } return clone; diff --git a/Framework/SINQ/src/PoldiUtilities/PoldiResidualCorrelationCore.cpp b/Framework/SINQ/src/PoldiUtilities/PoldiResidualCorrelationCore.cpp index 665b2f1eefa67af58661bb36d0e4c8d86b5c6904..cc7d068fa8d09991f48c65d737f0ae004fd2ee1d 100644 --- a/Framework/SINQ/src/PoldiUtilities/PoldiResidualCorrelationCore.cpp +++ b/Framework/SINQ/src/PoldiUtilities/PoldiResidualCorrelationCore.cpp @@ -85,9 +85,8 @@ void PoldiResidualCorrelationCore::distributeCorrelationCounts( double deltaForD = -dInt / m_weightsForD[i] / static_cast<double>(chopperSlits.size()); - for (auto offset = chopperSlits.begin(); offset != chopperSlits.end(); - ++offset) { - CountLocator locator = getCountLocator(d, *offset, m_indices[k]); + for (double chopperSlit : chopperSlits) { + CountLocator locator = getCountLocator(d, chopperSlit, m_indices[k]); int indexDifference = locator.icmax - locator.icmin; diff --git a/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumDomainFunction.cpp b/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumDomainFunction.cpp index eb6bf20858f5996e6b53dbee65591a9d54e05716..3f9f01e1ece8880868666f41e2c0812c43c70af3 100644 --- a/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumDomainFunction.cpp +++ b/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumDomainFunction.cpp @@ -164,14 +164,13 @@ void PoldiSpectrumDomainFunction::poldiFunction1D( double chopperSlitCount = static_cast<double>(m_chopperSlitOffsets.size()); - for (auto index = indices.begin(); index != indices.end(); ++index) { + for (auto index : indices) { std::vector<double> factors(domain.size()); for (size_t i = 0; i < factors.size(); ++i) { - values.addToCalculated(i, - chopperSlitCount * localValues[i] * - m_timeTransformer->detectorElementIntensity( - domain[i], static_cast<size_t>(*index))); + values.addToCalculated(i, chopperSlitCount * localValues[i] * + m_timeTransformer->detectorElementIntensity( + domain[i], static_cast<size_t>(index))); } } } @@ -271,9 +270,8 @@ std::vector<double> PoldiSpectrumDomainFunction::getChopperSlitOffsets( const std::vector<double> &chopperSlitTimes = chopper->slitTimes(); std::vector<double> offsets; offsets.reserve(chopperSlitTimes.size()); - for (auto time = chopperSlitTimes.cbegin(); time != chopperSlitTimes.cend(); - ++time) { - offsets.push_back(*time + chopper->zeroOffset()); + for (double chopperSlitTime : chopperSlitTimes) { + offsets.push_back(chopperSlitTime + chopper->zeroOffset()); } return offsets; diff --git a/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumPawleyFunction.cpp b/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumPawleyFunction.cpp index 809e96b7e71ab20c41d47d2d6d6a18098c09f757..0302843a91bcef980739af733c4879cfe2e7660d 100644 --- a/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumPawleyFunction.cpp +++ b/Framework/SINQ/src/PoldiUtilities/PoldiSpectrumPawleyFunction.cpp @@ -67,14 +67,13 @@ void PoldiSpectrumPawleyFunction::poldiFunction1D( double chopperSlitCount = static_cast<double>(m_chopperSlitOffsets.size()); - for (auto index = indices.begin(); index != indices.end(); ++index) { + for (auto index : indices) { std::vector<double> factors(domain.size()); for (size_t i = 0; i < factors.size(); ++i) { - values.addToCalculated(i, - chopperSlitCount * localValues[i] * - m_timeTransformer->detectorElementIntensity( - domain[i], static_cast<size_t>(*index))); + values.addToCalculated(i, chopperSlitCount * localValues[i] * + m_timeTransformer->detectorElementIntensity( + domain[i], static_cast<size_t>(index))); } } } diff --git a/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp b/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp index 1cf866607f48b2c8fbe0880175439e2334d23a8b..feefdddd7f417fb7830600255113275fa85b27bd 100644 --- a/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp +++ b/Framework/ScriptRepository/src/ScriptRepositoryImpl.cpp @@ -118,10 +118,7 @@ Test if a file with this filename already exists */ bool fileExists(const std::string &filename) { Poco::File test_file(filename); - if (test_file.exists()) { - return true; - } - return false; + return test_file.exists(); } DECLARE_SCRIPTREPOSITORY(ScriptRepositoryImpl) @@ -618,21 +615,21 @@ void ScriptRepositoryImpl::download_directory( std::string directory_path_with_slash = std::string(directory_path).append("/"); bool found = false; - for (auto it = repo.begin(); it != repo.end(); ++it) { + for (auto &entry : repo) { // skip all entries that are not children of directory_path // the map will list the entries in alphabetical order, so, // when it first find the directory, it will list all the // childrens of this directory, and them, // it will list other things, so we can, break the loop - if (it->first.find(directory_path) != 0) { + if (entry.first.find(directory_path) != 0) { if (found) break; // for the sake of performance else continue; } found = true; - if (it->first != directory_path && - it->first.find(directory_path_with_slash) != 0) { + if (entry.first != directory_path && + entry.first.find(directory_path_with_slash) != 0) { // it is not a children of this entry, just similar. Example: // TofConverter/README // TofConverter.py @@ -641,27 +638,27 @@ void ScriptRepositoryImpl::download_directory( continue; } // now, we are dealing with the children of directory path - if (!it->second.directory) - download_file(it->first, it->second); + if (!entry.second.directory) + download_file(entry.first, entry.second); else { // download the directory. // we will not download the directory, but create one with the // same name, and update the local json - Poco::File dir(std::string(local_repository).append(it->first)); + Poco::File dir(std::string(local_repository).append(entry.first)); dir.createDirectories(); - it->second.status = BOTH_UNCHANGED; - it->second.downloaded_date = DateAndTime( + entry.second.status = BOTH_UNCHANGED; + entry.second.downloaded_date = DateAndTime( Poco::DateTimeFormatter::format(dir.getLastModified(), timeformat)); - it->second.downloaded_pubdate = it->second.pub_date; - updateLocalJson(it->first, it->second); + entry.second.downloaded_pubdate = entry.second.pub_date; + updateLocalJson(entry.first, entry.second); - } // end downloading directory - // update the status - it->second.status = BOTH_UNCHANGED; // update this entry - } // end interaction with all entries + } // end downloading directory + // update the status + entry.second.status = BOTH_UNCHANGED; // update this entry + } // end interaction with all entries } /** @@ -1255,13 +1252,13 @@ std::vector<std::string> ScriptRepositoryImpl::check4Update(void) { std::vector<std::string> output_list; // look for all the files in the list, to check those that // has the auto_update and check it they have changed. - for (auto it = repo.begin(); it != repo.end(); ++it) { - if (it->second.auto_update) { + for (auto &file : repo) { + if (file.second.auto_update) { // THE SAME AS it->status in (REMOTE_CHANGED, BOTH_CHANGED) - if (it->second.status & REMOTE_CHANGED) { - download(it->first); - output_list.push_back(it->first); - g_log.debug() << "Update file " << it->first + if (file.second.status & REMOTE_CHANGED) { + download(file.first); + output_list.push_back(file.first); + g_log.debug() << "Update file " << file.first << " to more recently version available" << std::endl; } } @@ -1430,8 +1427,7 @@ void ScriptRepositoryImpl::parseCentralRepository(Repository &repo) { // as a workaround for a bug in the JsonCpp library (Json::ValueIterator is // not exported) Json::Value::Members member_names = pt.getMemberNames(); - for (unsigned int i = 0; i < member_names.size(); ++i) { - std::string filepath = member_names[i]; + for (auto filepath : member_names) { if (!isEntryValid(filepath)) continue; Json::Value entry_json = pt.get(filepath, ""); @@ -1496,8 +1492,7 @@ void ScriptRepositoryImpl::parseDownloadedEntries(Repository &repo) { // as a workaround for a bug in the JsonCpp library (Json::ValueIterator is // not exported) Json::Value::Members member_names = pt.getMemberNames(); - for (unsigned int i = 0; i < member_names.size(); ++i) { - std::string filepath = member_names[i]; + for (auto filepath : member_names) { Json::Value entry_json = pt.get(filepath, ""); entry_it = repo.find(filepath); @@ -1549,10 +1544,9 @@ void ScriptRepositoryImpl::parseDownloadedEntries(Repository &repo) { } } - for (auto it = entries_to_delete.begin(); it != entries_to_delete.end(); - ++it) { + for (auto &entry : entries_to_delete) { // remove this entry - pt.removeMember(*it); + pt.removeMember(entry); } #if defined(_WIN32) || defined(_WIN64) // set the .repository.json and .local.json not hidden (to be able to edit diff --git a/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp b/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp index ec0b08f295d00ec6393c0167687942b9baf6260c..faec89c29e6b974618ef1627ec4f5395e801ad8d 100644 --- a/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp +++ b/Framework/TestHelpers/src/WorkspaceCreationHelper.cpp @@ -718,10 +718,10 @@ CreateGroupedEventWorkspace(std::vector<std::vector<int>> groups, int numBins, for (size_t g = 0; g < groups.size(); g++) { retVal->getOrAddEventList(g).clearDetectorIDs(); std::vector<int> dets = groups[g]; - for (auto it = dets.begin(); it != dets.end(); ++it) { + for (auto det : dets) { for (int i = 0; i < numBins; i++) retVal->getOrAddEventList(g) += TofEvent((i + 0.5) * binDelta, 1); - retVal->getOrAddEventList(g).addDetectorID(*it); + retVal->getOrAddEventList(g).addDetectorID(det); } } // Create the x-axis for histogramming. diff --git a/Framework/WorkflowAlgorithms/src/AlignAndFocusPowder.cpp b/Framework/WorkflowAlgorithms/src/AlignAndFocusPowder.cpp index 6232ca0a476f9543eb9d449f6a9fd4c22d93e960..5f33a6610d09f47a607e6871c8fee1b7410503e8 100644 --- a/Framework/WorkflowAlgorithms/src/AlignAndFocusPowder.cpp +++ b/Framework/WorkflowAlgorithms/src/AlignAndFocusPowder.cpp @@ -773,8 +773,8 @@ AlignAndFocusPowder::rebin(API::MatrixWorkspace_sptr matrixws) { return matrixws; } else { g_log.information() << "running Rebin( "; - for (auto param = m_params.begin(); param != m_params.end(); ++param) - g_log.information() << (*param) << " "; + for (double param : m_params) + g_log.information() << param << " "; g_log.information() << ")\n"; API::IAlgorithm_sptr rebin3Alg = createChildAlgorithm("Rebin"); rebin3Alg->setProperty("InputWorkspace", matrixws); diff --git a/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp b/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp index 70d9271549b97de90e327a32ae84b571f0a74e4d..4fb956ca7172ce06a1c5c929cc8ffad6e9798f8a 100644 --- a/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp +++ b/Framework/WorkflowAlgorithms/src/ConvolutionFitSequential.cpp @@ -313,20 +313,20 @@ void ConvolutionFitSequential::exec() { Progress logAdderProg(this, 0.96, 0.97, 6); // Add String Logs auto logAdder = createChildAlgorithm("AddSampleLog"); - for (auto it = sampleLogStrings.begin(); it != sampleLogStrings.end(); ++it) { + for (auto &sampleLogString : sampleLogStrings) { logAdder->setProperty("Workspace", resultWs); - logAdder->setProperty("LogName", it->first); - logAdder->setProperty("LogText", it->second); + logAdder->setProperty("LogName", sampleLogString.first); + logAdder->setProperty("LogText", sampleLogString.second); logAdder->setProperty("LogType", "String"); logAdder->executeAsChildAlg(); logAdderProg.report("Add text logs"); } // Add Numeric Logs - for (auto it = sampleLogNumeric.begin(); it != sampleLogNumeric.end(); it++) { + for (auto &logItem : sampleLogNumeric) { logAdder->setProperty("Workspace", resultWs); - logAdder->setProperty("LogName", it->first); - logAdder->setProperty("LogText", it->second); + logAdder->setProperty("LogName", logItem.first); + logAdder->setProperty("LogText", logItem.second); logAdder->setProperty("LogType", "Number"); logAdder->executeAsChildAlg(); logAdderProg.report("Adding Numerical logs"); @@ -367,10 +367,7 @@ void ConvolutionFitSequential::exec() { bool ConvolutionFitSequential::checkForTwoLorentz( const std::string &subFunction) { auto pos = subFunction.rfind("Lorentzian"); - if (pos != std::string::npos) { - return true; - } - return false; + return pos != std::string::npos; } /** diff --git a/Framework/WorkflowAlgorithms/src/DgsReduction.cpp b/Framework/WorkflowAlgorithms/src/DgsReduction.cpp index d3c6620eb7aa1410cb1552a6e983bede362ebd0c..9681cbebc1c2c8c53cecbbf0935fc84b728e6640 100644 --- a/Framework/WorkflowAlgorithms/src/DgsReduction.cpp +++ b/Framework/WorkflowAlgorithms/src/DgsReduction.cpp @@ -688,9 +688,9 @@ void DgsReduction::exec() { // Put all properties except input files/workspaces into property manager. const std::vector<Property *> props = this->getProperties(); - for (auto iter = props.cbegin(); iter != props.cend(); ++iter) { - if (!boost::contains((*iter)->name(), "Input")) { - this->reductionManager->declareProperty((*iter)->clone()); + for (auto prop : props) { + if (!boost::contains(prop->name(), "Input")) { + this->reductionManager->declareProperty(prop->clone()); } } diff --git a/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp b/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp index d854b16afe2fb384c4f461757aa9eb846f63c3b5..93ae31ef193e6ac2069217d1ec58b5e910b0f6c0 100644 --- a/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp +++ b/Framework/WorkflowAlgorithms/src/EQSANSLoad.cpp @@ -128,8 +128,8 @@ std::string EQSANSLoad::findConfigFile(const int &run) { std::string config_file = ""; static boost::regex re1("eqsans_configuration\\.([0-9]+)$"); boost::smatch matches; - for (auto it = searchPaths.cbegin(); it != searchPaths.cend(); ++it) { - Poco::DirectoryIterator file_it(*it); + for (const auto &searchPath : searchPaths) { + Poco::DirectoryIterator file_it(searchPath); Poco::DirectoryIterator end; for (; file_it != end; ++file_it) { if (boost::regex_search(file_it.name(), matches, re1)) { diff --git a/Framework/WorkflowAlgorithms/src/EQSANSPatchSensitivity.cpp b/Framework/WorkflowAlgorithms/src/EQSANSPatchSensitivity.cpp index 6a9c7b400b18e1a29f1b9da9448cd37e74cd3e0c..6d01fd628af6a7e9077fe8eef426a32c5e3c26c5 100644 --- a/Framework/WorkflowAlgorithms/src/EQSANSPatchSensitivity.cpp +++ b/Framework/WorkflowAlgorithms/src/EQSANSPatchSensitivity.cpp @@ -99,13 +99,13 @@ void EQSANSPatchSensitivity::exec() { // Apply patch progress(0.91, "Applying patch"); - for (size_t k = 0; k < patched_ids.size(); k++) { + for (auto patched_id : patched_ids) { const Geometry::ComponentID det = - inputWS->getDetector(patched_ids[k])->getComponentID(); + inputWS->getDetector(patched_id)->getComponentID(); try { if (det) { - MantidVec &YValues = inputWS->dataY(patched_ids[k]); - MantidVec &YErrors = inputWS->dataE(patched_ids[k]); + MantidVec &YValues = inputWS->dataY(patched_id); + MantidVec &YErrors = inputWS->dataE(patched_id); if (useRegression) { YValues[0] = alpha + beta * det->getPos().Y(); YErrors[0] = error; diff --git a/Framework/WorkflowAlgorithms/src/LoadEventAndCompress.cpp b/Framework/WorkflowAlgorithms/src/LoadEventAndCompress.cpp index 76b9c4dd603c698fae330229c65455f750732d0c..9bd28166b8eb7aa8dcceeb5f31db0d588054438c 100644 --- a/Framework/WorkflowAlgorithms/src/LoadEventAndCompress.cpp +++ b/Framework/WorkflowAlgorithms/src/LoadEventAndCompress.cpp @@ -161,8 +161,8 @@ MatrixWorkspace_sptr LoadEventAndCompress::loadChunk(const size_t rowIndex) { // set chunking information if (rowCount > 0.) { const std::vector<string> COL_NAMES = m_chunkingTable->getColumnNames(); - for (auto name = COL_NAMES.begin(); name != COL_NAMES.end(); ++name) { - alg->setProperty(*name, m_chunkingTable->getRef<int>(*name, rowIndex)); + for (const auto &name : COL_NAMES) { + alg->setProperty(name, m_chunkingTable->getRef<int>(name, rowIndex)); } } diff --git a/Framework/WorkflowAlgorithms/src/ProcessIndirectFitParameters.cpp b/Framework/WorkflowAlgorithms/src/ProcessIndirectFitParameters.cpp index 4e6393e0850e9a1aea66cea397b1014e3b702be4..7d7dd90d78a9da8bea3703d1466f5f3299924cd7 100644 --- a/Framework/WorkflowAlgorithms/src/ProcessIndirectFitParameters.cpp +++ b/Framework/WorkflowAlgorithms/src/ProcessIndirectFitParameters.cpp @@ -173,8 +173,7 @@ void ProcessIndirectFitParameters::exec() { workflowProg.report("Converting text axis"); auto axis = new TextAxis(outputWs->getNumberHistograms()); size_t offset = 0; - for (size_t j = 0; j < workspaceNames.size(); j++) { - auto peakWs = workspaceNames.at(j); + for (auto peakWs : workspaceNames) { for (size_t k = 0; k < peakWs.size(); k++) { axis->setLabel((k + offset), peakWs.at(k)); } @@ -258,9 +257,9 @@ ProcessIndirectFitParameters::reorder2DVector( auto reorderedVector = std::vector<std::vector<std::string>>(); for (size_t i = 0; i < maximumLength; i++) { std::vector<std::string> temp; - for (size_t j = 0; j < original.size(); j++) { - if (original.at(j).size() > i) { - temp.push_back(original.at(j).at(i)); + for (const auto &j : original) { + if (j.size() > i) { + temp.push_back(j.at(i)); } } reorderedVector.push_back(temp); diff --git a/Framework/WorkflowAlgorithms/src/SANSSensitivityCorrection.cpp b/Framework/WorkflowAlgorithms/src/SANSSensitivityCorrection.cpp index 522618d464ffe853733305ae93e9f723253a3d1b..c148b8340afa043d0634e9de1b1db68cd88b85a4 100644 --- a/Framework/WorkflowAlgorithms/src/SANSSensitivityCorrection.cpp +++ b/Framework/WorkflowAlgorithms/src/SANSSensitivityCorrection.cpp @@ -93,9 +93,7 @@ bool SANSSensitivityCorrection::fileCheck(const std::string &filePath) { return false; } - if (entryName[0] == "mantid_workspace_1") - return true; - return false; + return entryName[0] == "mantid_workspace_1"; } void SANSSensitivityCorrection::exec() { diff --git a/MantidQt/CustomInterfaces/CMakeLists.txt b/MantidQt/CustomInterfaces/CMakeLists.txt index ce164bd03c6ba9532d70637ec95a4c9bf3e919f7..167b56d2670c0cc17f5409a2b9545ef347a84f41 100644 --- a/MantidQt/CustomInterfaces/CMakeLists.txt +++ b/MantidQt/CustomInterfaces/CMakeLists.txt @@ -406,11 +406,14 @@ set ( UI_FILES inc/MantidQtCustomInterfaces/DataComparison.ui inc/MantidQtCustomInterfaces/SANSRunWindow.ui inc/MantidQtCustomInterfaces/SANSEventSlicing.ui inc/MantidQtCustomInterfaces/StepScan.ui + inc/MantidQtCustomInterfaces/Tomography/ImgFormatsConversion.ui inc/MantidQtCustomInterfaces/Tomography/ImageSelectCoRAndRegions.ui inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtGUI.ui + inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabEnergy.ui inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabFiltersSettings.ui - inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabRun.ui + inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui + inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabVisualize.ui inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigAstra.ui inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigCustom.ui inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigSavu.ui diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h index 44a39674d6f69711716cc7814ba1124a70d29350..03c0623b895116a1f8c1b357c67a3ad0de770c15 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h @@ -3,6 +3,7 @@ #include "MantidAPI/IRemoteJobManager.h" #include "MantidAPI/MatrixWorkspace_fwd.h" +#include "MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h" #include "MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h" #include "MantidQtCustomInterfaces/Tomography/TomoReconToolsUserSettings.h" #include "MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h" @@ -150,6 +151,20 @@ public: */ virtual std::string currentReconTool() const = 0; + /** + * Method/algorithm selected from the TomoPy list. + * + * @return name of the method as used in TomoPy + */ + virtual std::string astraMethod() const = 0; + + /** + * Method/algorithm selected from the Astra list. + * + * @return name of the method as used in Astra Toolbox + */ + virtual std::string tomopyMethod() const = 0; + /** * Updates buttons and banners related to the current login * status. For example, when we are logged in, the 'log in' button @@ -229,6 +244,14 @@ public: */ virtual TomoPathsConfig currentPathsConfig() const = 0; + /** + * Regions and center of rotation, normally defined by the user with + * a graphical rectangle selection tool. + * + * @return current user selection of regions + */ + virtual ImageStackPreParams currentROIEtcParams() const = 0; + /** * Show a tool specific configuration dialog for the user to set it up * @@ -236,15 +259,35 @@ public: */ virtual void showToolConfig(const std::string &name) = 0; + /** + * Path to local scripts (reconstruction). Normally set to the + * installation path, but user modifyable + * + * @return path to the scrtips as a string + */ + virtual std::string pathLocalReconScripts() const = 0; + + /** + * User choice of external (Python) interpreter for third party + * tools + * + * @return path to the interpreter as a string + */ + virtual std::string externalInterpreterPath() const = 0; + /** * Refresh the table, tree etc. that displays info on the running/finished *jobs. * * @param status Job information, as produced for example by the * Mantid remote algorithms. + * + * @param localStatus similar information but for local runs */ - virtual void updateJobsInfoDisplay(const std::vector< - Mantid::API::IRemoteJobManager::RemoteJobInfo> &status) = 0; + virtual void updateJobsInfoDisplay( + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> &status, + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + &localStatus) = 0; /** * Save settings (normally when closing the interface). This refers diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h index 739374aed282d5b19cf3fb1d097b4a95bc583d3e..8d2b39e67d8df9bbdba1a68c1f42f087ba987d82 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h @@ -2,7 +2,7 @@ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_IMAGEROIVIEWQTWIDGET_H_ #include "MantidAPI/WorkspaceGroup_fwd.h" -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" #include "MantidQtCustomInterfaces/Tomography/IImageROIPresenter.h" #include "MantidQtCustomInterfaces/Tomography/IImageROIView.h" @@ -48,7 +48,9 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -class DLLExport ImageROIViewQtWidget : public QWidget, public IImageROIView { +class MANTIDQT_CUSTOMINTERFACES_DLL ImageROIViewQtWidget + : public QWidget, + public IImageROIView { Q_OBJECT public: @@ -61,7 +63,7 @@ public: SelectionState selectionState() const { return m_selectionState; } - void changeSelectionState(const SelectionState& state); + void changeSelectionState(const SelectionState &state); /// show a stack of images given the path to the files void showStack(const std::string &path); diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h index 164a3a475f7229f2b91fe6e9a82e15f102cb7065..e7e95899943bdd8f403e4f873dfea16284461130 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h @@ -1,7 +1,7 @@ #ifndef MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_IMAGESTACKPREPARAMS_H_ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_IMAGESTACKPREPARAMS_H_ -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" #include "MantidKernel/V2D.h" #include <utility> @@ -44,7 +44,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -class ImageStackPreParams { +class MANTIDQT_CUSTOMINTERFACES_DLL ImageStackPreParams { public: ImageStackPreParams(); @@ -54,7 +54,6 @@ public: Mantid::Kernel::V2D cor; Box2D roi; Box2D normalizationRegion; //< also known as 'air' region - bool medianFilter; }; } // namespace CustomInterfaces diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImgFormatsConversion.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImgFormatsConversion.ui new file mode 100644 index 0000000000000000000000000000000000000000..fe0d54efc94900048fa0d572fc1f848a24a15945 --- /dev/null +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ImgFormatsConversion.ui @@ -0,0 +1,322 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>ImgFormatsConversion</class> + <widget class="QWidget" name="ImgFormatsConversion"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>654</width> + <height>426</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QGridLayout" name="gridLayout_3"> + <item row="0" column="0"> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Input:</string> + </property> + <layout class="QGridLayout" name="gridLayout"> + <item row="1" column="3"> + <widget class="QPushButton" name="pushButton_browse_input"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_2"> + <property name="text"> + <string>Path:</string> + </property> + </widget> + </item> + <item row="0" column="2" colspan="2"> + <spacer name="horizontalSpacer_2"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Expanding</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>268</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="0" column="0"> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>Pick format:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="comboBox_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <item> + <property name="text"> + <string>FITS</string> + </property> + </item> + <item> + <property name="text"> + <string>TIFF</string> + </property> + </item> + <item> + <property name="text"> + <string>PNG</string> + </property> + </item> + <item> + <property name="text"> + <string>NXTomo</string> + </property> + </item> + </widget> + </item> + <item row="1" column="1" colspan="2"> + <widget class="QLineEdit" name="lineEdit_input"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>2</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="readOnly"> + <bool>true</bool> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <widget class="QGroupBox" name="groupBox_2"> + <property name="title"> + <string>Output</string> + </property> + <layout class="QGridLayout" name="gridLayout_2"> + <item row="0" column="0"> + <widget class="QLabel" name="label_4"> + <property name="text"> + <string>Format:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="comboBox_3"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <item> + <property name="text"> + <string>PNG</string> + </property> + </item> + <item> + <property name="text"> + <string>TIFF</string> + </property> + </item> + <item> + <property name="text"> + <string>FITS</string> + </property> + </item> + <item> + <property name="text"> + <string>NXTomo</string> + </property> + </item> + </widget> + </item> + <item row="0" column="2"> + <spacer name="horizontalSpacer_3"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Expanding</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>362</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Pixel bit-depth in outputs:</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QComboBox" name="comboBox"> + <item> + <property name="text"> + <string>16 bits</string> + </property> + </item> + </widget> + </item> + <item row="1" column="2"> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>362</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="2" column="0"> + <widget class="QLabel" name="label_6"> + <property name="text"> + <string>Compression:</string> + </property> + </widget> + </item> + <item row="2" column="1"> + <widget class="QComboBox" name="comboBox_4"> + <item> + <property name="text"> + <string>Enable</string> + </property> + </item> + <item> + <property name="text"> + <string>Disable</string> + </property> + </item> + </widget> + </item> + <item row="2" column="2"> + <spacer name="horizontalSpacer_4"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>362</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="3" column="0" colspan="3"> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QLabel" name="label_5"> + <property name="text"> + <string>Path:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_output"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>2</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="readOnly"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_browse_output"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + </item> + <item row="1" column="0"> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <spacer name="horizontalSpacer_5"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>278</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="pushButton_3"> + <property name="text"> + <string>Convert</string> + </property> + </widget> + </item> + </layout> + </item> + <item row="2" column="0"> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h index ee3becb0206f8910ae585ab1f4cedae98c201d29..41cfd297c9c3070723fb715bc1985d08ec4f8976 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h @@ -1,7 +1,7 @@ #ifndef MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMOPATHSCONFIG_H_ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMOPATHSCONFIG_H_ -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" #include "MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h" #include "MantidQtCustomInterfaces/Tomography/ToolConfigCustom.h" #include "MantidQtCustomInterfaces/Tomography/ToolConfigTomoPy.h" @@ -39,7 +39,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -class DLLExport TomoPathsConfig { +class MANTIDQT_CUSTOMINTERFACES_DLL TomoPathsConfig { public: /** * Default constructor, makes a paths configuration which probably diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoRecToolConfig.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoRecToolConfig.h index 256518618dcb17ac301ae2871bf615424cfb1f02..485e585d3a65742c05bb11d3597909d7db42202f 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoRecToolConfig.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoRecToolConfig.h @@ -2,6 +2,7 @@ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMORECTOOLCONFIG_H_ #include <string> +#include <vector> namespace MantidQt { namespace CustomInterfaces { @@ -61,7 +62,7 @@ public: * present it is used in its simplest form: platform and machine * dependent full path to an execuatable or script. */ - TomoRecToolConfig(const std::string &runnable="") : m_runnable(runnable) {} + TomoRecToolConfig(const std::string &runnable = "") : m_runnable(runnable) {} virtual ~TomoRecToolConfig() {} @@ -74,6 +75,16 @@ public: */ virtual bool valid() const { return true; } + /// A vector of tomographic reconstruction algorithms described by a + /// name-in-tool and a human-readable-name + typedef std::vector<std::pair<std::string, std::string>> TomoReconAlgs; + + virtual TomoReconAlgs algorithmsAvailable() const { return m_algs; }; + + virtual void appendOptions(std::string &opts) { + m_appendix = m_appendix + " " + opts; + }; + /** * Produce a command line to run this tool with this configuration. * @@ -100,6 +111,8 @@ public: protected: std::string m_runnable; + std::string m_appendix; + TomoReconAlgs m_algs; }; } // namespace CustomInterfaces diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h index dfaf3ee929779318cc7836d36048c440d11d708d..2097585aff58be8e95d4185fc6b1e393873b81a9 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h @@ -4,7 +4,7 @@ #include "MantidQtCustomInterfaces/Tomography/TomoReconPreprocSettings.h" #include "MantidQtCustomInterfaces/Tomography/TomoReconPostprocSettings.h" -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" namespace MantidQt { namespace CustomInterfaces { @@ -35,7 +35,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -struct DLLExport TomoReconFiltersSettings { +struct MANTIDQT_CUSTOMINTERFACES_DLL TomoReconFiltersSettings { MantidQt::CustomInterfaces::TomoReconPreprocSettings prep; MantidQt::CustomInterfaces::TomoReconPostprocSettings postp; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPostprocSettings.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPostprocSettings.h index f64af57614838c940dacc710a467a7a9b25078d7..9fa1122258fa5eb07cd0815ecebb5891221f2592 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPostprocSettings.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPostprocSettings.h @@ -1,7 +1,7 @@ #ifndef MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMORECONPOSTPROCSETTINGS_H_ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMORECONPOSTPROCSETTINGS_H_ -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" namespace MantidQt { namespace CustomInterfaces { @@ -31,7 +31,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -struct DLLExport TomoReconPostprocSettings { +struct MANTIDQT_CUSTOMINTERFACES_DLL TomoReconPostprocSettings { double circMaskRadius; double cutOffLevel; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPreprocSettings.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPreprocSettings.h index 07d639c489e03484394396827b873fd09de21b25..395473238a0a3ad4bbf74456928e683d69194e89 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPreprocSettings.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoReconPreprocSettings.h @@ -1,7 +1,7 @@ #ifndef MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMORECONPREPROCSETTINGS_H_ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMORECONPREPROCSETTINGS_H_ -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" #include <cstddef> @@ -34,7 +34,7 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -struct DLLExport TomoReconPreprocSettings { +struct MANTIDQT_CUSTOMINTERFACES_DLL TomoReconPreprocSettings { bool normalizeByProtonCharge; bool normalizeByFlatDark; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigAstra.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigAstra.ui index 48ff4e69af6e6ab7f391797b964fb9b3d21602df..6a279bfe7ca13f8d5cbe6c28b8414de0c47cebdb 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigAstra.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigAstra.ui @@ -9,136 +9,31 @@ <rect> <x>0</x> <y>0</y> - <width>563</width> - <height>233</height> + <width>545</width> + <height>179</height> </rect> </property> <property name="windowTitle"> <string>Astra Toolbox Configuration</string> </property> - <layout class="QGridLayout" name="gridLayout_3"> - <item row="0" column="0"> - <layout class="QGridLayout" name="gridLayout_2"> - <item row="4" column="0" colspan="3"> - <widget class="QGroupBox" name="groupBox"> - <property name="title"> - <string>Angles</string> - </property> - <layout class="QGridLayout" name="gridLayout"> - <item row="0" column="0"> - <widget class="QLabel" name="label_runnable_2"> - <property name="text"> - <string>Min:</string> - </property> - </widget> - </item> - <item row="0" column="4"> - <spacer name="horizontalSpacer_2"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>174</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label_runnable_4"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>List:</string> - </property> - </widget> - </item> - <item row="0" column="2"> - <widget class="QLabel" name="label_runnable_3"> - <property name="text"> - <string>Max:</string> - </property> - </widget> - </item> - <item row="1" column="1" colspan="4"> - <widget class="QLineEdit" name="lineEdit"> - <property name="enabled"> - <bool>false</bool> - </property> - </widget> - </item> - <item row="0" column="3"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_max"> - <property name="maximum"> - <double>360.000000000000000</double> - </property> - <property name="value"> - <double>360.000000000000000</double> - </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_min"> - <property name="maximum"> - <double>180.000000000000000</double> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item row="3" column="1"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_center_rot"> - <property name="maximum"> - <double>180.000000000000000</double> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label"> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QLabel" name="label_method"> <property name="text"> <string>Method:</string> </property> </widget> </item> - <item row="2" column="1" colspan="2"> - <widget class="QLineEdit" name="lineEdit_runnable"> - <property name="text"> - <string>/work/imat/runs-scripts/scripts/astra/astra-2d-FBP.py</string> - </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QLabel" name="label_runnable"> - <property name="text"> - <string>Runnable:</string> - </property> - </widget> - </item> - <item row="3" column="0"> - <widget class="QLabel" name="label_cli_options"> - <property name="text"> - <string>Center of rotation:</string> - </property> - </widget> - </item> - <item row="3" column="2"> - <spacer name="horizontalSpacer_4"> - <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 row="1" column="1" colspan="2"> + <item> <widget class="QComboBox" name="comboBox_method"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Preferred" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> <item> <property name="text"> <string>FBP: filtered back propagation</string> @@ -153,7 +48,85 @@ </item> </layout> </item> - <item row="1" column="0"> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Advanced options</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QGridLayout" name="gridLayout"> + <item row="0" column="0"> + <widget class="QLabel" name="label_iter"> + <property name="text"> + <string>Iterations:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QSpinBox" name="spinBox_iter"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>999</number> + </property> + <property name="value"> + <number>5</number> + </property> + </widget> + </item> + <item row="0" column="2" colspan="2"> + <spacer name="horizontalSpacer_4"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>178</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_cli_options"> + <property name="text"> + <string>Regularization:</string> + </property> + </widget> + </item> + <item row="1" column="1" colspan="2"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_regularization"> + <property name="decimals"> + <number>5</number> + </property> + <property name="maximum"> + <double>180.000000000000000</double> + </property> + </widget> + </item> + <item row="1" column="3"> + <spacer name="horizontalSpacer_5"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>305</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + </item> + <item> <spacer name="verticalSpacer"> <property name="orientation"> <enum>Qt::Vertical</enum> @@ -166,7 +139,7 @@ </property> </spacer> </item> - <item row="2" column="0"> + <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <spacer name="horizontalSpacer"> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigCustom.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigCustom.ui index 57122b76646bbc2eaada40f88340112fadc96291..def36df933bfe98d1ad000f48f78713e1bc0551c 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigCustom.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigCustom.ui @@ -25,8 +25,11 @@ </item> <item row="0" column="2"> <widget class="QLineEdit" name="lineEdit_runnable"> + <property name="toolTip"> + <string>Script or binary that can run on the remote environment</string> + </property> <property name="text"> - <string>/work/imat/runs-scripts/scripts/tomopy/imat_recon_FBP.py</string> + <string>/work/imat/phase_commissioning/scripts/Imaging/IMAT/tomo_reconstruct.py</string> </property> </widget> </item> @@ -51,12 +54,15 @@ <verstretch>0</verstretch> </sizepolicy> </property> + <property name="toolTip"> + <string>Command line options to the script or binary</string> + </property> <property name="html"> <string><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><style type="text/css"> p, li { white-space: pre-wrap; } </style></head><body style=" font-family:'Sans Serif'; font-size:9pt; font-weight:400; font-style:normal;"> -<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">--input_dir /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/sample/ --dark /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/dark --white /work/imat/tomo_data_CCD/16\ dec\ 2013\ Test\ Wired/beam/ --output_file /work/imat/remote/output/test_tomopy_FBP.nxs --start_angle 0 --end_angle 30 --center_of_rotation 15</p></body></html></string> +<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;">--help</p></body></html></string> </property> </widget> </item> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigTomoPy.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigTomoPy.ui index 46115129d691867cc0124690bcb7b9e3ce20795a..c285f5b37913b13e3d74f6ed87e6474b4589fb5e 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigTomoPy.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomoToolConfigTomoPy.ui @@ -9,151 +9,128 @@ <rect> <x>0</x> <y>0</y> - <width>584</width> - <height>224</height> + <width>547</width> + <height>177</height> </rect> </property> <property name="windowTitle"> <string>TomoPy Configuration</string> </property> - <layout class="QGridLayout" name="gridLayout_3"> - <item row="0" column="0"> - <layout class="QGridLayout" name="gridLayout_2"> - <item row="4" column="0" colspan="3"> - <widget class="QGroupBox" name="groupBox"> - <property name="title"> - <string>Angles</string> - </property> - <layout class="QGridLayout" name="gridLayout"> - <item row="0" column="0"> - <widget class="QLabel" name="label_runnable_2"> - <property name="text"> - <string>Min:</string> - </property> - </widget> - </item> - <item row="0" column="4"> - <spacer name="horizontalSpacer_2"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>174</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label_runnable_4"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="text"> - <string>List:</string> - </property> - </widget> - </item> - <item row="0" column="2"> - <widget class="QLabel" name="label_runnable_3"> - <property name="text"> - <string>Max:</string> - </property> - </widget> - </item> - <item row="1" column="1" colspan="4"> - <widget class="QLineEdit" name="lineEdit"> - <property name="enabled"> - <bool>false</bool> - </property> - </widget> - </item> - <item row="0" column="3"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_max"> - <property name="maximum"> - <double>180.000000000000000</double> - </property> - <property name="value"> - <double>180.000000000000000</double> - </property> - </widget> - </item> - <item row="0" column="1"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_angle_min"> - <property name="maximum"> - <double>360.000000000000000</double> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item row="3" column="1"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_center_rot"> - <property name="maximum"> - <double>180.000000000000000</double> - </property> - </widget> - </item> - <item row="1" column="0"> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> <widget class="QLabel" name="label"> <property name="text"> <string>Method:</string> </property> </widget> </item> - <item row="2" column="1" colspan="2"> - <widget class="QLineEdit" name="lineEdit_runnable"> - <property name="text"> - <string>/work/imat/runs-scripts/scripts/tomopy/imat_recon_FBP.py</string> - </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QLabel" name="label_runnable"> - <property name="text"> - <string>Runnable:</string> - </property> - </widget> - </item> - <item row="3" column="0"> - <widget class="QLabel" name="label_cli_options"> - <property name="text"> - <string>Center of rotation:</string> - </property> - </widget> - </item> - <item row="3" column="2"> - <spacer name="horizontalSpacer_4"> - <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 row="1" column="1" colspan="2"> + <item> <widget class="QComboBox" name="comboBox_method"> <item> <property name="text"> - <string>FBP: filtered back propagation</string> + <string>gridrec: Fourier grid reconstruction</string> + </property> + </item> + <item> + <property name="text"> + <string>SIRT: Simultaneous algebraic reconstruction technique</string> + </property> + </item> + <item> + <property name="text"> + <string>FBP: filtered back-propagation</string> </property> </item> <item> <property name="text"> - <string>SIRT: statistical image reconstruction</string> + <string>MLEM: Maximum-likelihood expectation maximization</string> </property> </item> </widget> </item> </layout> </item> - <item row="1" column="0"> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Advanced options</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QGridLayout" name="gridLayout"> + <item row="0" column="0"> + <widget class="QLabel" name="label_iter"> + <property name="text"> + <string>Iterations:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QSpinBox" name="spinBox_iter"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>999</number> + </property> + <property name="value"> + <number>5</number> + </property> + </widget> + </item> + <item row="0" column="2" colspan="2"> + <spacer name="horizontalSpacer_4"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>178</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_cli_options"> + <property name="text"> + <string>Regularization:</string> + </property> + </widget> + </item> + <item row="1" column="1" colspan="2"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_regularization"> + <property name="decimals"> + <number>5</number> + </property> + <property name="maximum"> + <double>180.000000000000000</double> + </property> + </widget> + </item> + <item row="1" column="3"> + <spacer name="horizontalSpacer_5"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>305</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + </item> + <item> <spacer name="verticalSpacer"> <property name="orientation"> <enum>Qt::Vertical</enum> @@ -166,7 +143,7 @@ </property> </spacer> </item> - <item row="2" column="0"> + <item> <layout class="QHBoxLayout" name="horizontalLayout"> <item> <spacer name="horizontalSpacer"> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h index 4bd8001060f092397a3dec2d71d888c863d8f279..567505348f45c5196b1687169bf6d0351ef6db75 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h @@ -5,7 +5,9 @@ #include "MantidAPI/ITableWorkspace_fwd.h" #include "MantidAPI/WorkspaceGroup_fwd.h" #include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/Tomography/ImageStackPreParams.h" #include "MantidQtCustomInterfaces/Tomography/TomoPathsConfig.h" +#include "MantidQtCustomInterfaces/Tomography/TomoReconFiltersSettings.h" #include "MantidQtCustomInterfaces/Tomography/TomoReconToolsUserSettings.h" // Qt classes forward declarations @@ -73,6 +75,11 @@ public: return m_jobsStatus; } + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + jobsStatusLocal() const { + return m_jobsStatusLocal; + } + /// Username last logged in, if any. std::string loggedIn() const { return m_loggedInUser; } // TODO: add companion currentComputeResource where LoggedIn() is in @@ -100,11 +107,35 @@ public: /// Get fresh status information on running/recent jobs void doRefreshJobsInfo(const std::string &compRes); + void doRunReconstructionJobLocal(); + /// Update to the current setings given by the user void updateReconToolsSettings(const TomoReconToolsUserSettings &ts) { m_toolsSettings = ts; } + void updateTomopyMethod(const std::string &method) { + m_tomopyMethod = method; + } + + void updateAstraMethod(const std::string &method) { m_astraMethod = method; } + + void updateExternalInterpreterPath(const std::string &interp) { + m_externalInterpreterPath = interp; + } + + void updatePathLocalReconScripts(const std::string &path) { + m_pathLocalReconScripts = path; + } + + void updatePrePostProcSettings(const TomoReconFiltersSettings &filters) { + m_prePostProcSettings = filters; + } + + void updateImageStackPreParams(const ImageStackPreParams &roiEtc) { + m_imageStackPreParams = roiEtc; + } + /// loads an image/picture in FITS format Mantid::API::WorkspaceGroup_sptr loadFITSImage(const std::string &path); @@ -129,20 +160,26 @@ private: /// retrieve info from compute resource into status table void getJobStatusInfo(const std::string &compRes); - std::string validateCompResource(const std::string &res); + std::string validateCompResource(const std::string &res) const; /// makes the command line string to run on the remote/local void makeRunnableWithOptions(const std::string &comp, std::string &run, - std::string &opt); + std::string &opt) const; void checkWarningToolNotSetup(const std::string &tool, const std::string &settings, - const std::string &cmd, const std::string &opt); + const std::string &cmd, + const std::string &opt) const; + + std::string makeTomoRecScriptOptions() const; + + std::string filtersCfgToCmdOpts(const TomoReconFiltersSettings &filters, + const ImageStackPreParams &corRegions) const; void splitCmdLine(const std::string &cmd, std::string &run, - std::string &opts); + std::string &opts) const; - void checkDataPathsSet(); + void checkDataPathsSet() const; /// username last logged in (empty if not in login status), from local /// perspective @@ -164,6 +201,8 @@ private: // status of remote jobs std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> m_jobsStatus; + // status of local runs/jobs + std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> m_jobsStatusLocal; /// reconstruction tools available on SCARF std::vector<std::string> m_SCARFtools; @@ -178,6 +217,18 @@ private: // Settings for the third party (tomographic reconstruction) tools TomoReconToolsUserSettings m_toolsSettings; + std::string m_tomopyMethod; + std::string m_astraMethod; + + std::string m_externalInterpreterPath; + std::string m_pathLocalReconScripts; + + // Settings for the pre-/post-processing filters + TomoReconFiltersSettings m_prePostProcSettings; + + // Parameters set for the ROI, normalization region, etc. + ImageStackPreParams m_imageStackPreParams; + // mutex for the job status info update operations QMutex *m_statusMutex; }; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h index ec29c07091b112cb2ab2b5de01325dacdce081f0..712304b5771c84b17a3e60edc462d26f8280089b 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h @@ -72,6 +72,9 @@ protected: void processSetupReconTool(); void processRunRecon(); + void subprocessRunReconRemote(); + void subprocessRunReconLocal(); + protected slots: /// It may be run on user request, or periodically from a timer/thread void processRefreshJobs(); @@ -97,6 +100,11 @@ private: /// Associated model for this presenter (MVP pattern) const boost::scoped_ptr<TomographyIfaceModel> m_model; + /// To prepare a local run + void makeRunnableWithOptionsLocal(const std::string &comp, std::string &run, + std::string &opt); + + // TODO: replace this with an std::mutex. Also below for threads. // mutex for the job status info update operations on the view QMutex *m_statusMutex; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabEnergy.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabEnergy.ui new file mode 100644 index 0000000000000000000000000000000000000000..609126fc22628d0c3eb0542037c9fd014b4df83f --- /dev/null +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabEnergy.ui @@ -0,0 +1,314 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>TomographyIfaceQtTabEnergy</class> + <widget class="QWidget" name="TomographyIfaceQtTabEnergy"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>725</width> + <height>430</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QGridLayout" name="gridLayout_5"> + <item row="0" column="0"> + <layout class="QGridLayout" name="gridLayout_4"> + <item row="0" column="0"> + <widget class="QGroupBox" name="groupBox"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="title"> + <string>Input:</string> + </property> + <layout class="QGridLayout" name="gridLayout"> + <item row="1" column="3"> + <widget class="QPushButton" name="pushButton_browse_input"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_2"> + <property name="text"> + <string>Path:</string> + </property> + </widget> + </item> + <item row="0" column="2" colspan="2"> + <spacer name="horizontalSpacer_2"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeType"> + <enum>QSizePolicy::Expanding</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>268</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="0" column="0"> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>Pick format:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QComboBox" name="comboBox_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <item> + <property name="text"> + <string>FITS</string> + </property> + </item> + <item> + <property name="text"> + <string>TIFF</string> + </property> + </item> + <item> + <property name="text"> + <string>PNG</string> + </property> + </item> + </widget> + </item> + <item row="1" column="1" colspan="2"> + <widget class="QLineEdit" name="lineEdit_input_path"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>2</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item row="1" column="0"> + <widget class="QGroupBox" name="groupBox_3"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="title"> + <string>Output:</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QGridLayout" name="gridLayout_3"> + <item row="0" column="0"> + <widget class="QRadioButton" name="radioButton"> + <property name="text"> + <string>Uniform</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="0" column="1" colspan="2"> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Number of bands:</string> + </property> + </widget> + </item> + <item row="0" column="3"> + <widget class="QSpinBox" name="spinBox"> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>1000</number> + </property> + </widget> + </item> + <item row="0" column="4"> + <spacer name="horizontalSpacer"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>326</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0" colspan="2"> + <widget class="QRadioButton" name="radioButton_2"> + <property name="text"> + <string>Indices of boundaries:</string> + </property> + <property name="checked"> + <bool>false</bool> + </property> + </widget> + </item> + <item row="1" column="2" colspan="3"> + <widget class="QLineEdit" name="lineEdit_3"/> + </item> + <item row="2" column="0" colspan="2"> + <widget class="QRadioButton" name="radioButton_3"> + <property name="text"> + <string>ToF boundaries:</string> + </property> + </widget> + </item> + <item row="2" column="2" colspan="3"> + <widget class="QLineEdit" name="lineEdit_4"/> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_5"> + <item> + <widget class="QLabel" name="label_6"> + <property name="text"> + <string>Path</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_output_path"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_browse_out"> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + <item row="2" column="0"> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <spacer name="horizontalSpacer_5"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>278</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="pushButton_3"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Aggregate</string> + </property> + </widget> + </item> + </layout> + </item> + <item row="3" column="1"> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>69</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item row="1" column="0"> + <widget class="QGroupBox" name="groupBox_2"> + <property name="title"> + <string>Configuration:</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QGridLayout" name="gridLayout_2"> + <item row="0" column="0"> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QLabel" name="label_4"> + <property name="text"> + <string>Path:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>2</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>C:\MantidInstall\scrips\imaging\IMAT\agg_energy_bands.py</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_2"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Fixed" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabFiltersSettings.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabFiltersSettings.ui index 3b3b24ad0612e412b1181383b9eac48f3776d351..e7531cc1538b54503f86eaeb951f20f799757a06 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabFiltersSettings.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabFiltersSettings.ui @@ -7,418 +7,515 @@ <x>0</x> <y>0</y> <width>769</width> - <height>576</height> + <height>618</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> - <layout class="QVBoxLayout" name="verticalLayout"> - <item> - <widget class="QGroupBox" name="groupBox"> - <property name="title"> - <string>Pre-processing (raw images)</string> + <layout class="QGridLayout" name="gridLayout"> + <item row="0" column="0"> + <widget class="QScrollArea" name="scrollArea"> + <property name="widgetResizable"> + <bool>true</bool> </property> - <layout class="QGridLayout" name="gridLayout"> - <item row="6" column="1"> - <spacer name="horizontalSpacer_3"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>399</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="4" column="1"> - <spacer name="horizontalSpacer_2"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>399</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="1" column="0" colspan="2"> - <widget class="QCheckBox" name="checkBox_normalize_proton_charge"> - <property name="statusTip"> - <string>Normalize every image by their relative proton charges</string> - </property> - <property name="text"> - <string>Normalize by proton charge</string> - </property> - <property name="checked"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="7" column="1"> - <spacer name="horizontalSpacer_4"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>399</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="2" column="0"> - <widget class="QCheckBox" name="checkBox_normalize_flat_dark"> - <property name="statusTip"> - <string>Normalize every image with respect to the reference flat and dark images, if available</string> - </property> - <property name="text"> - <string>Normalize by flat (open beam) and dark field images</string> - </property> - <property name="checked"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="3" column="1"> - <spacer name="horizontalSpacer"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>399</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="7" column="0"> - <widget class="QLabel" name="label_prep_scale_factor"> - <property name="text"> - <string>Scale down factor:</string> - </property> - </widget> - </item> - <item row="6" column="2"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_prep_max_angle"> - <property name="toolTip"> - <string>Maximum angle to use for reconstruction</string> - </property> - <property name="decimals"> - <number>3</number> - </property> - <property name="minimum"> - <double>1.000000000000000</double> - </property> - <property name="maximum"> - <double>360.000000000000000</double> - </property> - <property name="value"> - <double>360.000000000000000</double> - </property> - </widget> - </item> - <item row="4" column="0"> - <widget class="QLabel" name="label_prep_rotation"> - <property name="text"> - <string>Rotation (°, clockwise)</string> - </property> - </widget> - </item> - <item row="3" column="2"> - <widget class="QSpinBox" name="spinBox_prep_median_filter_width"> - <property name="toolTip"> - <string>Set size of the blocks to calculate a median filter. Bigger size implies more smoothing.</string> - </property> - <property name="minimum"> - <number>1</number> - </property> - <property name="maximum"> - <number>1000</number> - </property> - </widget> - </item> - <item row="6" column="0"> - <widget class="QLabel" name="label_prep_max_angle"> - <property name="text"> - <string>Maximum angle:</string> - </property> - </widget> - </item> - <item row="3" column="0"> - <widget class="QLabel" name="label_prep_median"> - <property name="text"> - <string>Dots removal (median filter width):</string> - </property> - </widget> - </item> - <item row="7" column="2"> - <widget class="QSpinBox" name="spinBox_prep_scale_factor"> - <property name="toolTip"> - <string>Sets the size of block to downscale. For example with 2, blocks of 2x2 pixels will be combined into a (median value) pixel</string> - </property> - <property name="minimum"> - <number>0</number> - </property> - <property name="maximum"> - <number>100</number> - </property> - <property name="value"> - <number>0</number> - </property> - </widget> - </item> - <item row="4" column="2"> - <widget class="QComboBox" name="comboBox_prep_rotation"> - <property name="toolTip"> - <string>Rotate all images in the input stacks by this angle</string> - </property> - <item> - <property name="text"> - <string>0</string> + <widget class="QWidget" name="scrollAreaWidgetContents"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>731</width> + <height>643</height> + </rect> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Pre-processing (raw images)</string> </property> - </item> - <item> - <property name="text"> - <string>90</string> + <layout class="QGridLayout" name="gridLayout_5"> + <item row="8" column="2"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_prep_max_angle"> + <property name="toolTip"> + <string>Maximum angle to use for reconstruction</string> + </property> + <property name="decimals"> + <number>3</number> + </property> + <property name="minimum"> + <double>1.000000000000000</double> + </property> + <property name="maximum"> + <double>360.000000000000000</double> + </property> + <property name="value"> + <double>360.000000000000000</double> + </property> + </widget> + </item> + <item row="6" column="2"> + <widget class="QComboBox" name="comboBox_prep_rotation"> + <property name="toolTip"> + <string>Rotate all images in the input stacks by this angle</string> + </property> + <item> + <property name="text"> + <string>0</string> + </property> + </item> + <item> + <property name="text"> + <string>90</string> + </property> + </item> + <item> + <property name="text"> + <string>180</string> + </property> + </item> + <item> + <property name="text"> + <string>270</string> + </property> + </item> + </widget> + </item> + <item row="9" column="0"> + <widget class="QLabel" name="label_prep_scale_factor"> + <property name="text"> + <string>Scale down factor:</string> + </property> + </widget> + </item> + <item row="6" column="1"> + <spacer name="horizontalSpacer_12"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>399</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="2" column="0"> + <widget class="QCheckBox" name="checkBox_normalize_flat_dark"> + <property name="statusTip"> + <string>Normalize every image with respect to the reference flat and dark images, if available</string> + </property> + <property name="text"> + <string>Normalize by flat (open beam) and dark field images</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="4" column="1"> + <spacer name="horizontalSpacer_13"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>399</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="6" column="0"> + <widget class="QLabel" name="label_prep_rotation"> + <property name="text"> + <string>Rotation (°, clockwise)</string> + </property> + </widget> + </item> + <item row="9" column="1"> + <spacer name="horizontalSpacer_14"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>399</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="8" column="1"> + <spacer name="horizontalSpacer_15"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>399</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="0" colspan="2"> + <widget class="QCheckBox" name="checkBox_normalize_proton_charge"> + <property name="statusTip"> + <string>Normalize every image by their relative proton charges</string> + </property> + <property name="text"> + <string>Normalize by air region / proton charge</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="9" column="2"> + <widget class="QSpinBox" name="spinBox_prep_scale_factor"> + <property name="toolTip"> + <string>Sets the size of block to downscale. For example with 2, blocks of 2x2 pixels will be combined into a (median value) pixel</string> + </property> + <property name="minimum"> + <number>0</number> + </property> + <property name="maximum"> + <number>100</number> + </property> + <property name="value"> + <number>0</number> + </property> + </widget> + </item> + <item row="4" column="0"> + <widget class="QLabel" name="label_prep_median"> + <property name="text"> + <string>Dots removal (median filter width):</string> + </property> + </widget> + </item> + <item row="8" column="0"> + <widget class="QLabel" name="label_prep_max_angle"> + <property name="text"> + <string>Maximum angle:</string> + </property> + </widget> + </item> + <item row="4" column="2"> + <widget class="QSpinBox" name="spinBox_prep_median_filter_width"> + <property name="toolTip"> + <string>Set size of the blocks to calculate a median filter. Bigger size implies more smoothing.</string> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>1000</number> + </property> + </widget> + </item> + <item row="5" column="0" colspan="3"> + <layout class="QHBoxLayout" name="horizontalLayout_5"> + <item> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>Sinogram stripes removal / ring artifacts removal</string> + </property> + </widget> + </item> + <item> + <widget class="QComboBox" name="comboBox_3"> + <item> + <property name="text"> + <string>Wavelet-Fourier</string> + </property> + </item> + <item> + <property name="text"> + <string>None</string> + </property> + </item> + </widget> + </item> + </layout> + </item> + <item row="3" column="0"> + <widget class="QCheckBox" name="checkBox_2"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Corrections for MCP detector</string> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> </property> - </item> - <item> - <property name="text"> - <string>180</string> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>15</height> + </size> </property> - </item> - <item> - <property name="text"> - <string>270</string> + </spacer> + </item> + <item> + <widget class="QGroupBox" name="groupBox_2"> + <property name="title"> + <string>Post-processing (reconstructed volume)</string> </property> - </item> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <spacer name="verticalSpacer"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>15</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QGroupBox" name="groupBox_2"> - <property name="title"> - <string>Post-processing (reconstructed volume)</string> - </property> - <layout class="QGridLayout" name="gridLayout_2"> - <item row="0" column="0"> - <widget class="QLabel" name="label_post_cir_mask"> - <property name="text"> - <string>Circular mask radius [0,1]:</string> - </property> - </widget> - </item> - <item row="0" column="1"> - <spacer name="horizontalSpacer_5"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>487</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="0" column="2"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_post_circ_mask"> - <property name="toolTip"> - <string>Set the radius (relative to the smaller edge of the images). All pixels outside the mask are zeroed.</string> - </property> - <property name="decimals"> - <number>3</number> - </property> - <property name="maximum"> - <double>1.000000000000000</double> - </property> - <property name="singleStep"> - <double>0.010000000000000</double> - </property> - <property name="value"> - <double>0.940000000000000</double> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QLabel" name="label_post_cutoff"> - <property name="text"> - <string>Cut-off level (%)</string> - </property> - </widget> - </item> - <item row="1" column="1"> - <spacer name="horizontalSpacer_6"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>487</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="1" column="2"> - <widget class="QDoubleSpinBox" name="doubleSpinBox_post_cutoff"> - <property name="toolTip"> - <string>Cut-off (zeroes) low pixel values, below this level</string> - </property> - <property name="singleStep"> - <double>0.010000000000000</double> - </property> - </widget> - </item> - </layout> - </widget> - </item> - <item> - <spacer name="verticalSpacer_3"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>15</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QGroupBox" name="groupBox_3"> - <property name="title"> - <string>Output options:</string> - </property> - <layout class="QGridLayout" name="gridLayout_4"> - <item row="0" column="0"> - <widget class="QCheckBox" name="checkBox_out_preproc_images"> - <property name="enabled"> - <bool>true</bool> - </property> - <property name="toolTip"> - <string>Write pre-processed images in addition to reconstructed volume</string> - </property> - <property name="text"> - <string>Produce pre-processed images stack</string> - </property> - <property name="checked"> - <bool>true</bool> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QGroupBox" name="groupBox_out_intermediate_prep"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="title"> - <string>Produce intermediate pre-processed images</string> - </property> - <property name="checkable"> - <bool>true</bool> - </property> - <property name="checked"> - <bool>false</bool> - </property> - <layout class="QGridLayout" name="gridLayout_3"> - <item row="0" column="0"> - <widget class="QCheckBox" name="checkBox_output_cropped_images"> - <property name="text"> - <string>Cropped</string> - </property> - </widget> - </item> - <item row="1" column="0"> - <widget class="QCheckBox" name="checkBox_output_normalized_proton_images"> - <property name="text"> - <string>Normalized - proton charge</string> + <layout class="QGridLayout" name="gridLayout_4"> + <item row="0" column="0"> + <widget class="QLabel" name="label_post_cir_mask"> + <property name="text"> + <string>Circular mask radius [0,1]:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <spacer name="horizontalSpacer_9"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>487</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="0" column="2"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_post_circ_mask"> + <property name="toolTip"> + <string>Set the radius (relative to the smaller edge of the images). All pixels outside the mask are zeroed.</string> + </property> + <property name="decimals"> + <number>3</number> + </property> + <property name="maximum"> + <double>1.000000000000000</double> + </property> + <property name="singleStep"> + <double>0.010000000000000</double> + </property> + <property name="value"> + <double>0.940000000000000</double> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QLabel" name="label_post_cutoff"> + <property name="text"> + <string>Cut-off level (%)</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <spacer name="horizontalSpacer_10"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>487</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="1" column="2"> + <widget class="QDoubleSpinBox" name="doubleSpinBox_post_cutoff"> + <property name="toolTip"> + <string>Cut-off (zeroes) low pixel values, below this level</string> + </property> + <property name="singleStep"> + <double>0.010000000000000</double> + </property> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <spacer name="verticalSpacer_3"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>15</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QGroupBox" name="groupBox_3"> + <property name="title"> + <string>Output options:</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_3"> + <item> + <widget class="QCheckBox" name="checkBox_out_preproc_images"> + <property name="enabled"> + <bool>true</bool> + </property> + <property name="toolTip"> + <string>Write pre-processed images in addition to reconstructed volume</string> + </property> + <property name="text"> + <string>Produce pre-processed images stack</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_6"> + <item> + <widget class="QLabel" name="label_4"> + <property name="text"> + <string>Pixel bit-depth in outputs:</string> + </property> + </widget> + </item> + <item> + <widget class="QComboBox" name="comboBox_4"> + <item> + <property name="text"> + <string>16 bits</string> + </property> + </item> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_16"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <widget class="QGroupBox" name="groupBox_out_intermediate_prep"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="title"> + <string>Produce intermediate pre-processed images</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QGridLayout" name="gridLayout_6"> + <item row="3" column="0"> + <widget class="QCheckBox" name="checkBox_output_dot_removal"> + <property name="text"> + <string>Dots removed (median filter)</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + <item row="2" column="0"> + <widget class="QCheckBox" name="checkBox_output_normalized_flat_images"> + <property name="text"> + <string>Normalized - flat, dark images</string> + </property> + </widget> + </item> + <item row="1" column="0"> + <widget class="QCheckBox" name="checkBox_output_normalized_proton_images"> + <property name="text"> + <string>Normalized - proton charge</string> + </property> + </widget> + </item> + <item row="0" column="0"> + <widget class="QCheckBox" name="checkBox_output_cropped_images"> + <property name="text"> + <string>Cropped</string> + </property> + </widget> + </item> + <item row="4" column="0"> + <widget class="QCheckBox" name="checkBox_output_sinograms"> + <property name="text"> + <string>sinograms</string> + </property> + <property name="checked"> + <bool>true</bool> + </property> + </widget> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + </item> + <item> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>14</height> + </size> + </property> + </spacer> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <spacer name="horizontalSpacer_11"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> </property> - </widget> - </item> - <item row="2" column="0"> - <widget class="QCheckBox" name="checkBox_output_normalized_flat_images"> - <property name="text"> - <string>Normalized - flat, dark images</string> + <property name="sizeHint" stdset="0"> + <size> + <width>608</width> + <height>20</height> + </size> </property> - </widget> + </spacer> </item> - <item row="3" column="0"> - <widget class="QCheckBox" name="checkBox_output_dot_removal"> + <item> + <widget class="QPushButton" name="pushButton_reset"> <property name="text"> - <string>Dots removed (median filter)</string> - </property> - <property name="checked"> - <bool>true</bool> + <string>Reset all</string> </property> </widget> </item> </layout> - </widget> - </item> - </layout> + </item> + </layout> + </widget> </widget> </item> - <item> - <spacer name="verticalSpacer_2"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>14</height> - </size> - </property> - </spacer> - </item> - <item> - <layout class="QHBoxLayout" name="horizontalLayout"> - <item> - <spacer name="horizontalSpacer_7"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>608</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item> - <widget class="QPushButton" name="pushButton_reset"> - <property name="text"> - <string>Reset all</string> - </property> - </widget> - </item> - </layout> - </item> </layout> </widget> <resources/> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabRun.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabRun.ui index ea670ee8a7158f0eb58a5f606461f3633d73f3a1..4a8073f85da3cd55f90bfb6c08c09e3900f1a2b0 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabRun.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabRun.ui @@ -9,8 +9,8 @@ <rect> <x>0</x> <y>0</y> - <width>671</width> - <height>451</height> + <width>737</width> + <height>573</height> </rect> </property> <layout class="QGridLayout" name="gridLayout"> @@ -105,8 +105,8 @@ <rect> <x>0</x> <y>0</y> - <width>231</width> - <height>175</height> + <width>256</width> + <height>239</height> </rect> </property> <property name="sizePolicy"> @@ -146,7 +146,20 @@ </widget> <widget class="QWidget" name="layoutWidget_6"> <layout class="QGridLayout" name="gridLayout_14"> - <item row="1" column="1"> + <item row="2" column="2"> + <spacer name="horizontalSpacer_6"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>13</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + <item row="2" column="1"> <widget class="QPushButton" name="pushButton_reconstruct"> <property name="minimumSize"> <size> @@ -171,20 +184,7 @@ </property> </widget> </item> - <item row="1" column="2"> - <spacer name="horizontalSpacer_6"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>13</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - <item row="2" column="1"> + <item row="3" column="1"> <spacer name="verticalSpacer_4"> <property name="orientation"> <enum>Qt::Vertical</enum> @@ -197,7 +197,7 @@ </property> </spacer> </item> - <item row="0" column="0" colspan="3"> + <item row="1" column="0" colspan="3"> <widget class="QGroupBox" name="groupBox_6"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> @@ -233,7 +233,7 @@ <item> <widget class="QLabel" name="label_12"> <property name="text"> - <string>Status:</string> + <string>Remote status:</string> </property> </widget> </item> @@ -242,6 +242,12 @@ <property name="text"> <string>Offline</string> </property> + <property name="autoDefault"> + <bool>false</bool> + </property> + <property name="default"> + <bool>false</bool> + </property> <property name="flat"> <bool>true</bool> </property> @@ -339,7 +345,7 @@ </layout> </widget> </item> - <item row="1" column="0"> + <item row="2" column="0"> <spacer name="horizontalSpacer_7"> <property name="orientation"> <enum>Qt::Horizontal</enum> @@ -352,6 +358,30 @@ </property> </spacer> </item> + <item row="0" column="0" colspan="3"> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QLabel" name="label_rb_number"> + <property name="text"> + <string>RB Number:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_rb_number"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>RB000XXX</string> + </property> + </widget> + </item> + </layout> + </item> </layout> </widget> </widget> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui index ebb4d3ea5f69a3466f07d916f4a09273cd4f0ccf..3816b9d49d540bf211fe17e3e6f03fe1271fcb1a 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabSetup.ui @@ -14,7 +14,7 @@ </rect> </property> <layout class="QGridLayout" name="gridLayout_7"> - <item row="0" column="0"> + <item row="2" column="0"> <widget class="QGroupBox" name="groupBox"> <property name="sizePolicy"> <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> @@ -230,11 +230,20 @@ <property name="title"> <string>Options:</string> </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> <layout class="QGridLayout" name="gridLayout_3"> <item row="2" column="0"> <layout class="QHBoxLayout" name="horizontalLayout_11"> <item> <widget class="QLabel" name="label_23"> + <property name="enabled"> + <bool>false</bool> + </property> <property name="text"> <string>Number of nodes:</string> </property> @@ -242,6 +251,9 @@ </item> <item> <widget class="QSpinBox" name="spinBox_SCARFnumNodes"> + <property name="enabled"> + <bool>false</bool> + </property> <property name="minimumSize"> <size> <width>0</width> @@ -315,6 +327,9 @@ <layout class="QHBoxLayout" name="horizontalLayout_12"> <item> <widget class="QLabel" name="label_24"> + <property name="enabled"> + <bool>false</bool> + </property> <property name="text"> <string>Number of cores:</string> </property> @@ -322,6 +337,9 @@ </item> <item> <widget class="QSpinBox" name="spinBox_SCARFnumCores"> + <property name="enabled"> + <bool>false</bool> + </property> <property name="minimumSize"> <size> <width>0</width> @@ -366,7 +384,7 @@ <item> <widget class="QLineEdit" name="lineEdit_scripts_base_dir"> <property name="text"> - <string>/work/imat/runs-scripts</string> + <string>/work/imat/phase_commissioning</string> </property> </widget> </item> @@ -389,7 +407,7 @@ <string>Local</string> </attribute> <layout class="QGridLayout" name="gridLayout_28"> - <item row="1" column="0"> + <item row="3" column="0"> <spacer name="verticalSpacer_9"> <property name="orientation"> <enum>Qt::Vertical</enum> @@ -402,55 +420,173 @@ </property> </spacer> </item> - <item row="0" column="0"> - <widget class="QGroupBox" name="groupBox_4"> + <item row="1" column="0"> + <widget class="QGroupBox" name="groupBox_5"> <property name="title"> - <string>Options:</string> + <string>Configuration:</string> </property> - <layout class="QGridLayout" name="gridLayout_8"> - <item row="0" column="0"> - <layout class="QHBoxLayout" name="horizontalLayout_6"> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_3"> <item> - <widget class="QLabel" name="label_25"> + <widget class="QLabel" name="label_out_dir"> <property name="text"> - <string>Number of cores:</string> + <string>Tomography data (in/out):</string> </property> </widget> </item> <item> - <widget class="QSpinBox" name="spinBox_localNumCores"> - <property name="minimumSize"> - <size> - <width>0</width> - <height>10</height> - </size> + <widget class="QLineEdit" name="lineEdit_local_out_recon_dir"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> - <property name="maximum"> - <number>99</number> + <property name="text"> + <string>D:/imat/</string> </property> - <property name="value"> - <number>8</number> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_in_out_dir"> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <widget class="QLabel" name="label_recon_scripts"> + <property name="text"> + <string>Reconstruction scripts:</string> </property> </widget> </item> <item> - <spacer name="horizontalSpacer_18"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> + <widget class="QLineEdit" name="lineEdit_local_recon_scripts"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> </property> - <property name="sizeHint" stdset="0"> - <size> - <width>40</width> - <height>20</height> - </size> + <property name="text"> + <string>C:/MantidInstall/scripts/</string> </property> - </spacer> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_recon_scripts_dir"> + <property name="text"> + <string>Browse</string> + </property> + </widget> </item> </layout> </item> </layout> </widget> </item> + <item row="2" column="0"> + <widget class="QGroupBox" name="groupBox_4"> + <property name="title"> + <string>Options:</string> + </property> + <layout class="QGridLayout" name="gridLayout_4"> + <item row="0" column="0"> + <widget class="QLabel" name="label_3"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Max. processes:</string> + </property> + </widget> + </item> + <item row="0" column="1"> + <widget class="QSpinBox" name="spinBox"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="minimum"> + <number>1</number> + </property> + <property name="maximum"> + <number>10</number> + </property> + <property name="value"> + <number>4</number> + </property> + </widget> + </item> + <item row="0" column="2"> + <spacer name="horizontalSpacer_10"> + <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 row="1" column="0"> + <widget class="QLabel" name="label_25"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>Number of cores:</string> + </property> + </widget> + </item> + <item row="1" column="1"> + <widget class="QSpinBox" name="spinBox_localNumCores"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="minimumSize"> + <size> + <width>0</width> + <height>10</height> + </size> + </property> + <property name="maximum"> + <number>99</number> + </property> + <property name="value"> + <number>4</number> + </property> + </widget> + </item> + <item row="1" column="2"> + <spacer name="horizontalSpacer_18"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </widget> + </item> </layout> </widget> </widget> @@ -458,6 +594,19 @@ </layout> </widget> </item> + <item row="4" column="0"> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>120</height> + </size> + </property> + </spacer> + </item> <item row="1" column="0"> <widget class="QGroupBox" name="groupBox_2"> <property name="sizePolicy"> @@ -483,7 +632,7 @@ <number>2</number> </property> <item row="0" column="0"> - <widget class="QLabel" name="label_5"> + <widget class="QLabel" name="label_samples"> <property name="minimumSize"> <size> <width>120</width> @@ -522,7 +671,7 @@ </widget> </item> <item row="1" column="0"> - <widget class="QLabel" name="label_6"> + <widget class="QLabel" name="label_flat"> <property name="minimumSize"> <size> <width>120</width> @@ -536,7 +685,7 @@ </size> </property> <property name="text"> - <string>Open beam dir.:</string> + <string>Flat/open beam:</string> </property> </widget> </item> @@ -557,7 +706,7 @@ </widget> </item> <item row="2" column="0"> - <widget class="QLabel" name="label_7"> + <widget class="QLabel" name="label_darks"> <property name="minimumSize"> <size> <width>120</width> @@ -571,7 +720,7 @@ </size> </property> <property name="text"> - <string>Dark field dir.:</string> + <string>Dark.:</string> </property> </widget> </item> @@ -595,132 +744,50 @@ <zorder>lineEdit_path_FITS</zorder> <zorder>lineEdit_path_flat</zorder> <zorder>lineEdit_path_dark</zorder> - <zorder>label_5</zorder> - <zorder>label_6</zorder> - <zorder>label_7</zorder> + <zorder>label_samples</zorder> + <zorder>label_flat</zorder> + <zorder>label_darks</zorder> <zorder>pushButton_fits_dir</zorder> <zorder>pushButton_flat_dir</zorder> <zorder>pushButton_dark_dir</zorder> </widget> </item> - <item row="2" column="0"> - <widget class="QGroupBox" name="groupBox_run_config"> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> - <horstretch>0</horstretch> - <verstretch>1</verstretch> - </sizepolicy> - </property> - <property name="minimumSize"> - <size> - <width>0</width> - <height>100</height> - </size> - </property> - <property name="title"> - <string>Run Configuration</string> - </property> - <layout class="QGridLayout" name="gridLayout_2"> - <property name="margin"> - <number>3</number> - </property> - <property name="spacing"> - <number>2</number> - </property> - <item row="1" column="0"> - <widget class="QFrame" name="frame"> - <property name="enabled"> - <bool>false</bool> - </property> - <property name="sizePolicy"> - <sizepolicy hsizetype="Preferred" vsizetype="Preferred"> - <horstretch>0</horstretch> - <verstretch>0</verstretch> - </sizepolicy> - </property> - <property name="maximumSize"> - <size> - <width>16777215</width> - <height>60</height> - </size> - </property> - <property name="frameShape"> - <enum>QFrame::StyledPanel</enum> - </property> - <property name="frameShadow"> - <enum>QFrame::Raised</enum> - </property> - <layout class="QHBoxLayout" name="horizontalLayout"> - <property name="leftMargin"> - <number>8</number> - </property> - <property name="topMargin"> - <number>0</number> - </property> - <property name="rightMargin"> - <number>0</number> - </property> - <property name="bottomMargin"> - <number>0</number> - </property> - <item> - <widget class="QCheckBox" name="checkBox"> - <property name="text"> - <string>Automatically Reconstruct every </string> - </property> - </widget> - </item> - <item> - <widget class="QSpinBox" name="spinBox"> - <property name="minimum"> - <number>1</number> - </property> - <property name="maximum"> - <number>5000</number> - </property> - <property name="value"> - <number>1</number> - </property> - </widget> - </item> - <item> - <widget class="QLabel" name="label_3"> - <property name="text"> - <string>files.</string> - </property> - </widget> - </item> - <item> - <spacer name="horizontalSpacer_4"> - <property name="orientation"> - <enum>Qt::Horizontal</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>683</width> - <height>20</height> - </size> - </property> - </spacer> - </item> - </layout> - </widget> - </item> - </layout> - </widget> - </item> - <item row="3" column="0"> - <spacer name="verticalSpacer_2"> - <property name="orientation"> - <enum>Qt::Vertical</enum> - </property> - <property name="sizeHint" stdset="0"> - <size> - <width>20</width> - <height>120</height> - </size> - </property> - </spacer> + <item row="0" column="0"> + <layout class="QHBoxLayout" name="horizontalLayout_9"> + <item> + <widget class="QLabel" name="label_cycle"> + <property name="text"> + <string>Cycle:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_cycle"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>0</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>phase_commissioning</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_9"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>68</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> </item> </layout> </widget> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabVisualize.ui b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabVisualize.ui new file mode 100644 index 0000000000000000000000000000000000000000..eae0a7ebf7bae8b1a93d3ce8f464c9d5d7195428 --- /dev/null +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceQtTabVisualize.ui @@ -0,0 +1,246 @@ +<?xml version="1.0" encoding="UTF-8"?> +<ui version="4.0"> + <class>TomographyIfaceQtTabVisualize</class> + <widget class="QWidget" name="TomographyIfaceQtTabVisualize"> + <property name="geometry"> + <rect> + <x>0</x> + <y>0</y> + <width>511</width> + <height>377</height> + </rect> + </property> + <property name="windowTitle"> + <string>Form</string> + </property> + <layout class="QVBoxLayout" name="verticalLayout_3"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_4"> + <item> + <layout class="QVBoxLayout" name="verticalLayout"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_3"> + <item> + <widget class="QPushButton" name="pushButton_local_default_dir"> + <property name="text"> + <string>Local default</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_remote_default_dir"> + <property name="text"> + <string>Remote default</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="pushButton_browse_files"> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <widget class="QTreeView" name="treeView_files"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Expanding"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QVBoxLayout" name="verticalLayout_2"> + <item> + <spacer name="verticalSpacer_2"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QPushButton" name="pushButton_paraview"> + <property name="text"> + <string>>ParaView</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_octopus"> + <property name="text"> + <string>>Octopus Vis.</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_vgstudio"> + <property name="enabled"> + <bool>false</bool> + </property> + <property name="text"> + <string>>VGStudio</string> + </property> + </widget> + </item> + <item> + <spacer name="verticalSpacer"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>148</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + </layout> + </item> + <item> + <spacer name="verticalSpacer_3"> + <property name="orientation"> + <enum>Qt::Vertical</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>20</width> + <height>40</height> + </size> + </property> + </spacer> + </item> + <item> + <widget class="QGroupBox" name="groupBox"> + <property name="title"> + <string>Configuration</string> + </property> + <property name="checkable"> + <bool>true</bool> + </property> + <property name="checked"> + <bool>false</bool> + </property> + <layout class="QVBoxLayout" name="verticalLayout_4"> + <item> + <layout class="QHBoxLayout" name="horizontalLayout"> + <item> + <widget class="QLabel" name="label"> + <property name="text"> + <string>Processed data subdirectories:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_processed_subpath"> + <property name="text"> + <string>processed</string> + </property> + </widget> + </item> + <item> + <spacer name="horizontalSpacer_3"> + <property name="orientation"> + <enum>Qt::Horizontal</enum> + </property> + <property name="sizeHint" stdset="0"> + <size> + <width>40</width> + <height>20</height> + </size> + </property> + </spacer> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_2"> + <item> + <widget class="QLabel" name="label_2"> + <property name="text"> + <string>ParaView:</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit_paraview_location"> + <property name="text"> + <string>C:\Program Files\ParaView</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton_browse_paraview"> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + <item> + <layout class="QHBoxLayout" name="horizontalLayout_5"> + <item> + <widget class="QLabel" name="label_3"> + <property name="text"> + <string>Octopus Vis.</string> + </property> + </widget> + </item> + <item> + <widget class="QLineEdit" name="lineEdit"> + <property name="sizePolicy"> + <sizepolicy hsizetype="Expanding" vsizetype="Fixed"> + <horstretch>1</horstretch> + <verstretch>0</verstretch> + </sizepolicy> + </property> + <property name="text"> + <string>C:/Program Files/Octopus Imaging/Octopus Visualisation</string> + </property> + </widget> + </item> + <item> + <widget class="QPushButton" name="pushButton"> + <property name="text"> + <string>Browse</string> + </property> + </widget> + </item> + </layout> + </item> + </layout> + </widget> + </item> + </layout> + </widget> + <resources/> + <connections/> +</ui> diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceViewQtGUI.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceViewQtGUI.h index 549b35448283df59d932134d7c63bef0de0a83da..d50f597c84faf9c44e58ed1eb948ea13aa94d07c 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceViewQtGUI.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/TomographyIfaceViewQtGUI.h @@ -1,24 +1,32 @@ #ifndef MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMOGRAPHYIFACEVIEWQTGUI_H_ #define MANTIDQTCUSTOMINTERFACES_TOMOGRAPHY_TOMOGRAPHYIFACEVIEWQTGUI_H_ +#include "MantidAPI/IRemoteJobManager.h" #include "MantidAPI/ITableWorkspace_fwd.h" #include "MantidAPI/MatrixWorkspace_fwd.h" #include "MantidAPI/TableRow.h" #include "MantidQtAPI/UserSubWindow.h" #include "MantidQtCustomInterfaces/DllConfig.h" +#include "MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h" #include "MantidQtCustomInterfaces/Tomography/ITomographyIfacePresenter.h" #include "MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h" #include "MantidQtCustomInterfaces/Tomography/TomoToolConfigDialog.h" #include "ui_ImageSelectCoRAndRegions.h" +#include "ui_ImgFormatsConversion.h" #include "ui_TomographyIfaceQtGUI.h" +#include "ui_TomographyIfaceQtTabEnergy.h" #include "ui_TomographyIfaceQtTabFiltersSettings.h" -#include "ui_TomographyIfaceQtTabSetup.h" #include "ui_TomographyIfaceQtTabRun.h" +#include "ui_TomographyIfaceQtTabSetup.h" +#include "ui_TomographyIfaceQtTabVisualize.h" #include <boost/scoped_ptr.hpp> #include <json/json.h> +// widgets used in this interface +class ImageROIViewQtWidget; + // Qt classes forward declarations class QMutex; @@ -86,6 +94,16 @@ public: std::string getPassword() const; + std::string externalInterpreterPath() const { + return m_localExternalPythonPath; + } + + std::string pathLocalReconScripts() const { return m_setupPathReconScripts; }; + + std::string astraMethod() const { return m_astraMethod; } + + std::string tomopyMethod() const { return m_tomopyMethod; } + void updateLoginControls(bool loggedIn); void enableLoggedActions(bool enable); @@ -99,13 +117,15 @@ public: void updateCompResourceStatus(bool online); void updateJobsInfoDisplay( - const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> &status); + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> &status, + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + &localStatus); std::vector<std::string> processingJobsIDs() const { return m_processingJobsIDs; } - /// Get the current reconstruction tooll settings set by the user + /// Get the current reconstruction tools settings set by the user TomoReconToolsUserSettings reconToolsSettings() const { return m_toolsSettings; } @@ -126,6 +146,10 @@ public: TomoPathsConfig currentPathsConfig() const { return m_pathsConfig; } + ImageStackPreParams currentROIEtcParams() const { + return m_tabROIW->userSelection(); + } + private slots: /// for buttons, run tab, and similar void reconstructClicked(); @@ -133,6 +157,7 @@ private slots: void runVisualizeClicked(); void jobCancelClicked(); void jobTableRefreshClicked(); + void updatedRBNumber(); void compResourceIndexChanged(int); void runToolIndexChanged(int); @@ -141,6 +166,12 @@ private slots: void browseImageClicked(); + void updatedCycleName(); + + void browseLocalInOutDirClicked(); + void browseLocalReconScriptsDirClicked(); + + void resetRemoteSetup(); void fitsPathBrowseClicked(); void flatPathBrowseClicked(); void darkPathBrowseClicked(); @@ -151,6 +182,24 @@ private slots: /// open the MantidQT help window for this interface void openHelpWin(); + // visualization tools / short-cuts + void browseFilesToVisualizeClicked(); + void sendToParaviewClicked(); + void sendToOctopusVisClicked(); + void defaultDirLocalVisualizeClicked(); + void defaultDirRemoteVisualizeClicked(); + void browseVisToolParaviewClicke(); + void browseVisToolOctopusClicked(); + + // convert formats section/tab + void browseImgInputConvertClicked(); + void browseImgOutputConvertClicked(); + + // processing of energy bands + void browseEnergyInputClicked(); + void browseEnergyOutputClicked(); + + // for the savu functionality - waiting for Savu void menuSaveClicked(); void menuSaveAsClicked(); void availablePluginSelected(); @@ -163,6 +212,15 @@ private slots: void paramValModified(QTreeWidgetItem *, int); void expandedItem(QTreeWidgetItem *); +private: + void processLocalRunRecon(); + + void makeRunnableWithOptions(const std::string &comp, std::string &run, + std::string &opt); + + void splitCmdLine(const std::string &cmd, std::string &run, + std::string &opts); + private: /// Setup the interface (tab UI) virtual void initLayout(); @@ -172,6 +230,10 @@ private: void doSetupSectionFilters(); void doSetupGeneralWidgets(); + void doSetupSectionVisualize(); + void doSetupSectionConvert(); + void doSetupSectionEnergy(); + void doSetupSavu(); /// Load default interface settings for each tab, normally on startup @@ -189,6 +251,15 @@ private: void setPrePostProcSettings(TomoReconFiltersSettings &opts) const; + std::string + checkUserBrowsePath(QLineEdit *le, + const std::string &userMsg = "Open directory/folder"); + + void sendToVisTool(const std::string &toolName, const std::string &pathString, + const std::string &appendBin); + + void sendLog(const std::string &msg); + // Begin of Savu related functionality. This will grow and will need // separation. They should find a better place to live. ///@name Savu related methods @@ -222,15 +293,23 @@ private: // end of Savu related methods + static const std::string g_styleSheetOffline; + static const std::string g_styleSheetOnline; + /// Interface definition with widgets for the main interface window Ui::TomographyIfaceQtGUI m_ui; // And its sections/tabs. Note that for compactness they're called simply // 'tabs' // but they could be separate dialogs, widgets, etc. - Ui::TomographyIfaceQtTabFiltersSettings m_uiTabFilters; - Ui::TomographyIfaceQtTabSetup m_uiTabSetup; Ui::TomographyIfaceQtTabRun m_uiTabRun; + Ui::TomographyIfaceQtTabSetup m_uiTabSetup; + Ui::TomographyIfaceQtTabFiltersSettings m_uiTabFilters; Ui::ImageSelectCoRAndRegions m_uiTabCoR; + Ui::TomographyIfaceQtTabVisualize m_uiTabVisualize; + Ui::ImgFormatsConversion m_uiTabConvertFormats; + Ui::TomographyIfaceQtTabEnergy m_uiTabEnergy; + + ImageROIViewQtWidget *m_tabROIW; /// Tool specific setup dialogs Ui::TomoToolConfigAstra m_uiAstra; @@ -245,9 +324,19 @@ private: std::string m_imgPath; + std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> m_localJobsStatus; + + // Settings for external tools. where to find the system Python + static std::string g_defLocalExternalPythonPath; + static std::vector<std::string> g_defAddPathPython; + + std::string m_localExternalPythonPath; + std::vector<std::string> m_defAddPathPython; + static const std::string g_SCARFName; // a general (all tools in principle) default output path - static const std::string g_defOutPath; + static const std::string g_defOutPathLocal; + static const std::string g_defOutPathRemote; static const std::string g_TomoPyTool; static const std::string g_AstraTool; @@ -257,11 +346,40 @@ private: TomoPathsConfig m_pathsConfig; + static const std::string g_defRemotePathScripts; + + // several paths or path components related to where the files are found + // (raw files, reconstructions, pre-post processed files, etc.) + // These are the defaults + static const std::string g_defPathComponentPhase; + static const std::string g_defRBNumber; + // reconstruction scripts (external, but shipped with Mantid) + static const std::string g_defPathReconScripts; + // base dir for the reconstruction outputs + static const std::string g_defPathReconOut; + static const std::string g_defParaviewPath; + static const std::string g_defParaviewAppendPath; + static const std::string g_defOctopusVisPath; + static const std::string g_defOctopusAppendPath; + static const std::string g_defProcessedSubpath; + // And these are the paths set up + std::string m_setupPathComponentPhase; + std::string m_setupRBNumber; + std::string m_setupPathReconScripts; + std::string m_setupPathReconOut; + std::string m_setupParaviewPath; + std::string m_setupOctopusVisPath; + std::string m_setupProcessedSubpath; + // here the view puts messages before notifying the presenter to show them std::vector<std::string> m_logMsgs; /// Settings for the third party (tomographic reconstruction) tools TomoReconToolsUserSettings m_toolsSettings; + static const std::vector<std::pair<std::string, std::string>> + g_tomopy_methods; + std::string m_astraMethod; + std::string m_tomopyMethod; // Basic representation of user settings, read/written on startup/close. // TODO: this could be done more sophisticated, with a class using diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h index 8e4b19d2f7cdac14401455f43f7fbcf0e8c5bc86..f5b9ba9dac6eeda61bf3dbbb4074f14656dad670 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h @@ -3,7 +3,7 @@ #include <string> -#include "MantidKernel/System.h" +#include "MantidQtCustomInterfaces/DllConfig.h" #include "MantidQtCustomInterfaces/Tomography/TomoRecToolConfig.h" namespace MantidQt { @@ -36,12 +36,12 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -class DLLExport ToolConfigAstraToolbox : public TomoRecToolConfig { +class MANTIDQT_CUSTOMINTERFACES_DLL ToolConfigAstraToolbox + : public TomoRecToolConfig { public: ToolConfigAstraToolbox(); - ToolConfigAstraToolbox(const std::string &runnable, double centerRot, - double angleMin, double angleMax, + ToolConfigAstraToolbox(const std::string &runnable, const std::string &pathOut, const std::string &pathDark, const std::string &pathOpen, @@ -49,15 +49,19 @@ public: ~ToolConfigAstraToolbox() {} + // gives the list of methods (reconstruction algorithms) available + static const std::vector<std::pair<std::string, std::string>> methods() { + return g_astraMethods; + } + protected: virtual std::string makeCmdLineOptions() const; virtual std::string makeExecutable() const { return m_runnable; }; private: - double m_centerRot; - double m_angleMin; - double m_angleMax; + static const std::vector<std::pair<std::string, std::string>> g_astraMethods; + std::string m_pathOut; std::string m_pathDark; std::string m_pathOpen; diff --git a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigTomoPy.h b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigTomoPy.h index b3e9054938af5d0c8ecdf4a94751f6ab2628d65e..cd6f115047cbaad20d554c08d26813920beb2a1f 100644 --- a/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigTomoPy.h +++ b/MantidQt/CustomInterfaces/inc/MantidQtCustomInterfaces/Tomography/ToolConfigTomoPy.h @@ -35,30 +35,34 @@ along with this program. If not, see <http://www.gnu.org/licenses/>. File change history is stored at: <https://github.com/mantidproject/mantid> Code Documentation is available at: <http://doxygen.mantidproject.org> */ -class DLLExport ToolConfigTomoPy : public TomoRecToolConfig { +class MANTIDQT_CUSTOMINTERFACES_DLL ToolConfigTomoPy + : public TomoRecToolConfig { public: ToolConfigTomoPy(); ToolConfigTomoPy(const std::string &runnable, const std::string &pathOut, const std::string &pathDark, const std::string &pathOpen, - const std::string &pathSample, double centerRot, - double angleMin, double angleMax); + const std::string &pathSample); ~ToolConfigTomoPy() {} + // gives the list of methods (reconstruction algorithms) available + static const std::vector<std::pair<std::string, std::string>> methods() { + return g_tomopyMethods; + } + protected: virtual std::string makeCmdLineOptions() const; virtual std::string makeExecutable() const { return m_runnable; }; private: + static const std::vector<std::pair<std::string, std::string>> g_tomopyMethods; + std::string m_pathOut; std::string m_pathDark; std::string m_pathOpen; std::string m_pathSample; - double m_centerRot; - double m_angleMin; - double m_angleMax; }; } // namespace CustomInterfaces diff --git a/MantidQt/CustomInterfaces/src/Tomography/ImageROIPresenter.cpp b/MantidQt/CustomInterfaces/src/Tomography/ImageROIPresenter.cpp index 5f411515c231575349bb8e05fc40899892918a63..0461d3356f8e932f022d2a90890d05196594d3a5 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/ImageROIPresenter.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/ImageROIPresenter.cpp @@ -157,6 +157,21 @@ void ImageROIPresenter::processNewStack() { return; } + for (size_t i = 0; i < imgs.size(); i++) { + const std::string extShort = imgs[i].substr(imgs[i].size() - 3); + const std::string extLong = imgs[i].substr(imgs[i].size() - 4); + const std::string expectedShort = "fit"; + const std::string expectedLong = "fits"; + if (extShort != expectedShort && extLong != expectedLong) { + m_view->userWarning("Invalid files found in the stack of images", + "Found files with unrecognized extension. Expected " + "files with extension '" + + expectedShort + "' or '" + expectedLong + + "' but found: " + imgs[i]); + return; + } + } + Mantid::API::WorkspaceGroup_sptr wsg = loadFITSStack(imgs); if (!wsg) return; @@ -226,14 +241,30 @@ void ImageROIPresenter::processShutDown() { m_view->saveSettings(); } Mantid::API::WorkspaceGroup_sptr ImageROIPresenter::loadFITSStack(const std::vector<std::string> &imgs) { + if (imgs.empty()) + return Mantid::API::WorkspaceGroup_sptr(); + const std::string wsName = "__stack_fits_viewer_tomography_gui"; auto &ads = Mantid::API::AnalysisDataService::Instance(); if (ads.doesExist(wsName)) { ads.remove(wsName); } - for (size_t i = 0; i < imgs.size(); ++i) { - loadFITSImage(imgs[i], wsName); + + // This would be the alternative that loads images one by one (one + // algorithm run per image file) + // for (size_t i = 0; i < imgs.size(); ++i) { + // loadFITSImage(imgs[i], wsName); + // } + + // Load all image files using a list with their names + std::string allPaths; + size_t i = 0; + allPaths = imgs[i]; + i++; + while (i < imgs.size()) { + allPaths.append(", " + imgs[i++]); } + loadFITSImage(allPaths, wsName); Mantid::API::WorkspaceGroup_sptr wsg; try { diff --git a/MantidQt/CustomInterfaces/src/Tomography/ImageStackPreParams.cpp b/MantidQt/CustomInterfaces/src/Tomography/ImageStackPreParams.cpp index b343d7c20876fa95bda014ff49ed75407ab2daaf..9e4a5eb32a87896ffdb45a1076c7adf22d569ad6 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/ImageStackPreParams.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/ImageStackPreParams.cpp @@ -5,7 +5,8 @@ using namespace MantidQt::CustomInterfaces; namespace MantidQt { namespace CustomInterfaces { -ImageStackPreParams::ImageStackPreParams() : medianFilter(false) {} +ImageStackPreParams::ImageStackPreParams() + : cor(), roi(), normalizationRegion() {} } // namespace CustomInterfaces } // namespace MantidQt diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomoToolConfigDialog.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomoToolConfigDialog.cpp index d92ac766f89accf755e85a5ab30b825e64d3dea6..4496f36783a6646cee1d0d309af1272cb9590d6f 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/TomoToolConfigDialog.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/TomoToolConfigDialog.cpp @@ -22,12 +22,13 @@ TomoToolConfigDialog::TomoToolConfigDialog(QWidget *parent) : QDialog(parent) { editOpt = new QLineEdit("/work/imat"); hOpt = new QHBoxLayout(); hOpt->addWidget(labelOpt); + hOpt->addWidget(editOpt); okButton = new QPushButton("Ok"); cancelButton = new QPushButton("Cancel"); hBut = new QHBoxLayout(); - hBut->insertStretch(0,1); + hBut->insertStretch(0, 1); hBut->addWidget(okButton); hBut->addWidget(cancelButton); diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceModel.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceModel.cpp index 5c733326408eb7d1492bf90563267468b9a5e2f2..1c34dbeb7410238f03c4f7b576c71372ac3fef9e 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceModel.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceModel.cpp @@ -3,6 +3,8 @@ #include "MantidAPI/AlgorithmManager.h" #include "MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h" +#include <Poco/Process.h> + #include <QMutex> using namespace Mantid::API; @@ -34,7 +36,9 @@ TomographyIfaceModel::TomographyIfaceModel() : m_loggedInUser(""), m_loggedInComp(""), m_facility("ISIS"), m_localCompName("Local"), m_computeRes(), m_computeResStatus(), m_reconTools(), m_reconToolsStatus(), m_jobsStatus(), m_SCARFtools(), - m_toolsSettings(), m_statusMutex(NULL) { + m_toolsSettings(), m_tomopyMethod("gridrec"), m_astraMethod("FBP3D_CUDA"), + m_externalInterpreterPath(""), m_prePostProcSettings(), + m_imageStackPreParams(), m_statusMutex(NULL) { m_computeRes.push_back(g_SCARFName); m_computeRes.push_back(m_localCompName); @@ -80,11 +84,15 @@ void TomographyIfaceModel::cleanup() { * @throws std::runtime_error on inconsistent selection of compute * resource */ -std::string TomographyIfaceModel::validateCompResource(const std::string &res) { +std::string +TomographyIfaceModel::validateCompResource(const std::string &res) const { if (res == m_localCompName) { // Nothing yet - throw std::runtime_error("There is no support for the local compute " - "resource. You should not have got here."); + // throw std::runtime_error("There is no support for the local compute " + // "resource. You should not have got here."); + // all good at the moment - could do basic validation and checks for + // availability of absolutely necessary tools + return "local"; } if (m_computeRes.size() <= 0) { @@ -159,9 +167,11 @@ void TomographyIfaceModel::setupComputeResource() { } m_computeResStatus.push_back(true); - // put local as second compute resource, but disable, as it's not yet sorted - // out how it will work - m_computeResStatus.push_back(false); + // finally, put local as last compute resource, and enable it by default + // TODO: as in validateCompResource() some basic sanity checks could + // be done before enabling it, including availability of the + // necessaryy external tools + m_computeResStatus.push_back(true); } /** @@ -179,7 +189,10 @@ void TomographyIfaceModel::setupRunTool(const std::string &compRes) { // catch all the useable/relevant tools for the compute // resources. For the time being this is rather simple (just // SCARF) and will probably stay like this for a while. - if ("ISIS" == m_facility && (compRes.empty() || g_SCARFName == compRes)) { + std::string low = compRes; + std::transform(low.begin(), low.end(), low.begin(), tolower); + if ("local" == low || + ("ISIS" == m_facility && (compRes.empty() || g_SCARFName == compRes))) { m_reconTools = m_SCARFtools; } else { throw std::runtime_error("Cannot setup this interface for the facility: " + @@ -437,7 +450,7 @@ void TomographyIfaceModel::getJobStatusInfo(const std::string &compRes) { * @throw std::runtime_error if the required fields are not set * properly */ -void TomographyIfaceModel::checkDataPathsSet() { +void TomographyIfaceModel::checkDataPathsSet() const { if (!m_pathsConfig.validate()) { const std::string detail = "Please define the paths to your dataset images. " @@ -452,9 +465,49 @@ void TomographyIfaceModel::checkDataPathsSet() { } } +void TomographyIfaceModel::doRunReconstructionJobLocal() { + const std::string toolName = usingTool(); + try { + std::string run, args; + makeRunnableWithOptions("local", run, args); + + logMsg("Running " + toolName + ", with binary: " + run + + ", with parameters: " + args); + + std::vector<std::string> runArgs = {args}; + // Mantid::Kernel::ConfigService::Instance().launchProcess(run, runArgs); + try { + Poco::ProcessHandle handle = Poco::Process::launch(run, runArgs); + Poco::Process::PID pid = handle.id(); + Mantid::API::IRemoteJobManager::RemoteJobInfo info; + info.id = boost::lexical_cast<std::string>(pid); + info.name = "Mantid_Local"; + info.status = "Running"; + info.cmdLine = run + " " + args; + m_jobsStatusLocal.push_back(info); + } catch (Poco::SystemException &sexc) { + g_log.error() + << "Execution failed. Could not run the tool. Error details: " + << std::string(sexc.what()); + Mantid::API::IRemoteJobManager::RemoteJobInfo info; + info.id = boost::lexical_cast<std::string>(std::rand()); + info.name = "Mantid_Local"; + info.status = "Exit"; + info.cmdLine = run + " " + args; + m_jobsStatusLocal.push_back(info); + } + } catch (std::runtime_error &rexc) { + logMsg("The execution of " + toolName + "failed. details: " + + std::string(rexc.what())); + g_log.error() + << "Execution failed. Coult not execute the tool. Error details: " + << std::string(rexc.what()); + } +} + /** - * Build the components of the command line to run on the remote - * compute resource.Produces a (normally full) path to a runnable, and + * Build the components of the command line to run on the remote or local + * compute resource. Produces a (normally full) path to a runnable, and * the options (quite like $0 and $* in scripts). * * @param comp Compute resource for which the command line is being prepared @@ -463,54 +516,76 @@ void TomographyIfaceModel::checkDataPathsSet() { */ void TomographyIfaceModel::makeRunnableWithOptions(const std::string &comp, std::string &run, - std::string &opt) { - checkDataPathsSet(); - - // For now we only know how to 'aproximately' run commands on SCARF - if (g_SCARFName == comp) { - const std::string tool = usingTool(); - std::string cmd; - - // TODO this is still incomplete, not all tools ready - if (tool == g_TomoPyTool) { - cmd = m_toolsSettings.tomoPy.toCommand(); - // this will make something like: - // run = "/work/imat/z-tests-fedemp/scripts/tomopy/imat_recon_FBP.py"; - // opt = "--input_dir " + base + currentPathFITS() + " " + "--dark " + - // base + - // currentPathDark() + " " + "--white " + base + currentPathFlat(); - } else if (tool == g_AstraTool) { - cmd = m_toolsSettings.astra.toCommand(); - // this will produce something like this: - // run = "/work/imat/scripts/astra/astra-3d-SIRT3D.py"; - // opt = base + currentPathFITS(); - } else if (tool == g_customCmdTool) { - cmd = m_toolsSettings.custom.toCommand(); - } else { - throw std::runtime_error( - "Unable to use this tool. " - "I do not know how to submit jobs to use this tool: " + - tool + ". It seems that this interface is " - "misconfigured or there has been an unexpected " - "failure."); - } - + std::string &opt) const { + const std::string tool = usingTool(); + // Special case. Just pass on user inputs. + if (tool == g_customCmdTool) { + const std::string cmd = m_toolsSettings.custom.toCommand(); splitCmdLine(cmd, run, opt); - checkWarningToolNotSetup(tool, cmd, run, opt); + return; + } + + std::string cmd; + // TODO this is still incomplete, not all tools ready + if ("local" == comp) { + const std::string mainScript = "/Imaging/IMAT/tomo_reconstruct.py"; + cmd = m_pathLocalReconScripts + mainScript; + } else if (tool == g_TomoPyTool) { + cmd = m_toolsSettings.tomoPy.toCommand(); + // this will make something like: + // run = "/work/imat/z-tests-fedemp/scripts/tomopy/imat_recon_FBP.py"; + // opt = "--input_dir " + base + currentPathFITS() + " " + "--dark " + + // base + + // currentPathDark() + " " + "--white " + base + currentPathFlat(); + } else if (tool == g_AstraTool) { + cmd = m_toolsSettings.astra.toCommand(); + // this will produce something like this: + // run = "/work/imat/scripts/astra/astra-3d-SIRT3D.py"; + // opt = base + currentPathFITS(); } else { - run = "error_do_not_know_what_to_do"; - opt = "no_options_known"; - - const std::string details = - "Unrecognized remote compute resource. " - "The remote compute resource that you are trying not used is " - "not known: " + - comp + ". This seems to indicate that this interface is " - "misconfigured or there has been an unexpected failure."; throw std::runtime_error( - "Could not recognize the remote compute resource: '" + comp + "'. " + - details); + "Unable to use this tool. " + "I do not know how to submit jobs to use this tool: " + + tool + ". It seems that this interface is " + "misconfigured or there has been an unexpected " + "failure."); } + + splitCmdLine(cmd, run, opt); + // TODO: this may not make sense any longer: + // checkWarningToolNotSetup(tool, cmd, run, opt); + if (comp == m_localCompName) + run = m_externalInterpreterPath; + + opt = makeTomoRecScriptOptions(); +} + +/** + * Build the command line options string in the way the tomorec + * scripts (remote and local) expect it. + * + * @return command options ready for the tomorec script + */ +std::string TomographyIfaceModel::makeTomoRecScriptOptions() const { + + std::string toolMethodStr = ""; + + const std::string toolName = usingTool(); + if (g_TomoPyTool == toolName) + toolMethodStr += " --tool=tomopy --algorithm=" + m_tomopyMethod; + else if (g_AstraTool == toolName) + toolMethodStr += " --tool=astra --algorithm=" + m_astraMethod; + + if (g_TomoPyTool != toolName || m_tomopyMethod != "gridred" || + m_tomopyMethod != "fbp") + toolMethodStr += " --num-iter=5"; + + // options with all the info from filters and regions + const std::string cmdOpts = + filtersCfgToCmdOpts(m_prePostProcSettings, m_imageStackPreParams); + + std::string tomorecOpts = toolMethodStr + " " + cmdOpts; + return tomorecOpts; } /** @@ -524,10 +599,9 @@ void TomographyIfaceModel::makeRunnableWithOptions(const std::string &comp, * @param opt options for that command/script/executable derived from the * settings */ -void TomographyIfaceModel::checkWarningToolNotSetup(const std::string &tool, - const std::string &settings, - const std::string &cmd, - const std::string &opt) { +void TomographyIfaceModel::checkWarningToolNotSetup( + const std::string &tool, const std::string &settings, + const std::string &cmd, const std::string &opt) const { if (tool.empty() || settings.empty() || cmd.empty() || opt.empty()) { const std::string detail = "Please define the settings of this tool. " @@ -546,7 +620,8 @@ void TomographyIfaceModel::checkWarningToolNotSetup(const std::string &tool, * the code is reorganized to use the tool settings objetcs better. */ void TomographyIfaceModel::splitCmdLine(const std::string &cmd, - std::string &run, std::string &opts) { + std::string &run, + std::string &opts) const { if (cmd.empty()) return; @@ -623,5 +698,96 @@ void TomographyIfaceModel::logMsg(const std::string &msg) { g_log.notice() << msg << std::endl; } +/** + * Produces a comma separated list of coordinates as a string of real values + * + * @param coords Coordinates given as point 1 (x,y), point 2 (x,y) + * + * @returns A string like "x1, y1, x2, y2" + */ +std::string boxCoordinatesToCSV(const ImageStackPreParams::Box2D &coords) { + std::string x1 = std::to_string(coords.first.X()); + std::string y1 = std::to_string(coords.first.Y()); + std::string x2 = std::to_string(coords.second.X()); + std::string y2 = std::to_string(coords.second.Y()); + + return x1 + ", " + y1 + ", " + x2 + ", " + y2; +} + +/** + * Build options string to send them to the tomographic reconstruction + * scripts command line. + * + * @param filters Settings for the pre-post processing steps/filters + * + * @param corRegions center and regions selected by the user (region + * of intererst/analysis area and normalization or air region). + * + * This doesn't belong here and should be move to more appropriate + * place. + */ +std::string TomographyIfaceModel::filtersCfgToCmdOpts( + const TomoReconFiltersSettings &filters, + const ImageStackPreParams &corRegions) const { + std::string opts; + + opts += + " --region-of-interest='[" + boxCoordinatesToCSV(corRegions.roi) + "]'"; + + opts += " --air-region='[" + + boxCoordinatesToCSV(corRegions.normalizationRegion) + "]'"; + + // TODO: (we require here IMAT specific headers to become available soon) + // filters.prep.normalizeByProtonCharge + + opts += " --input-path=" + m_pathsConfig.pathSamples(); + std::string alg = "alg"; + if (g_TomoPyTool == usingTool()) + alg = m_tomopyMethod; + else if (g_AstraTool == usingTool()) + alg = m_astraMethod; + opts += " --output=out_recon_" + m_currentTool + "_" + alg; + if (filters.prep.normalizeByFlatDark) { + const std::string flat = m_pathsConfig.pathOpenBeam(); + if (!flat.empty()) + opts += " --input-path-flat=" + flat; + + const std::string dark = m_pathsConfig.pathDark(); + if (!dark.empty()) + opts += " --input-path-dark=" + dark; + } + + opts += + " --median-filter-size=" + std::to_string(filters.prep.medianFilterWidth); + + int rotationIdx = filters.prep.rotation / 90; + double cor = 0; + if (1 == rotationIdx % 2) { + cor = corRegions.cor.Y(); + } else { + cor = corRegions.cor.X(); + } + opts += " --cor=" + std::to_string(cor); + + // filters.prep.rotation + opts += " --rotation=" + std::to_string(rotationIdx); + + // filters.prep.maxAngle + opts += " --max-angle=" + std::to_string(filters.prep.maxAngle); + + // prep.scaleDownFactor + if (filters.prep.scaleDownFactor > 1) + opts += " --scale-down=" + std::to_string(filters.prep.scaleDownFactor); + + // postp.circMaskRadius + opts += " --circular-mask=" + std::to_string(filters.postp.circMaskRadius); + + // postp.cutOffLevel + if (filters.postp.cutOffLevel > 0.0) + opts += " --cut-off=" + std::to_string(filters.postp.cutOffLevel); + + return opts; +} + } // namespace CustomInterfaces } // namespace MantidQt diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfacePresenter.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfacePresenter.cpp index ef2cad5f09bddc06fd38dd9c798e60f91e150e41..f0e0abbfd96ef67ee2ab32fa53e6a3a3da1a0347 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfacePresenter.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfacePresenter.cpp @@ -3,9 +3,9 @@ #include "MantidAPI/WorkspaceGroup.h" #include "MantidKernel/ConfigService.h" #include "MantidKernel/FacilityInfo.h" +#include "MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h" #include "MantidQtCustomInterfaces/Tomography/TomographyIfaceModel.h" #include "MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h" -#include "MantidQtCustomInterfaces/Tomography/ITomographyIfaceView.h" #include <boost/lexical_cast.hpp> @@ -155,6 +155,13 @@ void TomographyIfacePresenter::processCompResourceChange() { const std::string comp = m_view->currentComputeResource(); m_model->setupRunTool(comp); + + if ("Local" == comp) { + m_view->enableLoggedActions(true); + } else { + const bool status = !m_model->loggedIn().empty(); + m_view->enableLoggedActions(status); + } } void TomographyIfacePresenter::processToolChange() { @@ -169,7 +176,10 @@ void TomographyIfacePresenter::processToolChange() { m_view->enableRunReconstruct(false); m_view->enableConfigTool(true); } else { - m_view->enableRunReconstruct(!(m_model->loggedIn().empty())); + // No need to be logged in anymore when local is selected + const bool runningLocally = "Local" == m_view->currentComputeResource(); + m_view->enableRunReconstruct(runningLocally || + !(m_model->loggedIn().empty())); m_view->enableConfigTool(true); } @@ -197,7 +207,11 @@ void TomographyIfacePresenter::processLogin() { "again if that's what you meant."); } - const std::string compRes = m_view->currentComputeResource(); + std::string compRes = m_view->currentComputeResource(); + // if local is selected, just take the first remote resource + if ("Local" == compRes) { + compRes = "SCARF@STFC"; + } try { const std::string user = m_view->getUsername(); if (user.empty()) { @@ -238,7 +252,12 @@ void TomographyIfacePresenter::processLogout() { } try { - m_model->doLogout(m_view->currentComputeResource(), m_view->getUsername()); + std::string compRes = m_view->currentComputeResource(); + // if local is selected, just take the first remote resource + if ("Local" == compRes) { + compRes = "SCARF@STFC"; + } + m_model->doLogout(compRes, m_view->getUsername()); } catch (std::exception &e) { throw(std::string("Problem when logging out. Error description: ") + e.what()); @@ -251,38 +270,84 @@ void TomographyIfacePresenter::processSetupReconTool() { if (TomographyIfaceModel::g_CCPiTool != m_view->currentReconTool()) { m_view->showToolConfig(m_view->currentReconTool()); m_model->updateReconToolsSettings(m_view->reconToolsSettings()); + + // TODO: this would make sense if the reconstruct action/button + // was only enabled after setting up at least one tool + // m_view->enableToolsSetupsActions(true); } } void TomographyIfacePresenter::processRunRecon() { - if (m_model->loggedIn().empty()) + // m_model->checkDataPathsSet(); + // TODO: validate data path: + TomoPathsConfig paths = m_view->currentPathsConfig(); + if (paths.pathSamples().empty()) { + m_view->userWarning("Sample images path not set!", + "The path to the sample images " + "is strictly required to start " + "a reconstruction"); return; + } + // pre-/post processing steps and filters + m_model->updatePrePostProcSettings(m_view->prePostProcSettings()); + // center of rotation and regions + m_model->updateImageStackPreParams(m_view->currentROIEtcParams()); + m_model->updateTomopyMethod(m_view->tomopyMethod()); + m_model->updateAstraMethod(m_view->astraMethod()); + m_model->updateExternalInterpreterPath(m_view->externalInterpreterPath()); + m_model->updatePathLocalReconScripts(m_view->pathLocalReconScripts()); const std::string &resource = m_view->currentComputeResource(); + if (m_model->localComputeResource() == resource) { + subprocessRunReconLocal(); + } else { + subprocessRunReconRemote(); + } - if (m_model->localComputeResource() != resource) { - try { - m_model->doSubmitReconstructionJob(resource); - } catch (std::exception &e) { - m_view->userWarning("Issue when trying to start a job", e.what()); - } + processRefreshJobs(); +} - processRefreshJobs(); +void TomographyIfacePresenter::subprocessRunReconRemote() { + if (m_model->loggedIn().empty()) { + m_view->updateJobsInfoDisplay(m_model->jobsStatus(), + m_model->jobsStatusLocal()); + return; + } + + try { + + m_model->doSubmitReconstructionJob(m_view->currentComputeResource()); + } catch (std::exception &e) { + m_view->userWarning("Issue when trying to start a job", e.what()); } + + processRefreshJobs(); +} + +void TomographyIfacePresenter::subprocessRunReconLocal() { + m_model->doRunReconstructionJobLocal(); } void TomographyIfacePresenter::processRefreshJobs() { - if (m_model->loggedIn().empty()) + // No need to be logged in, there can be local processes + if (m_model->loggedIn().empty()) { + m_view->updateJobsInfoDisplay(m_model->jobsStatus(), + m_model->jobsStatusLocal()); return; + } - const std::string &comp = m_view->currentComputeResource(); + std::string comp = m_view->currentComputeResource(); + if ("Local" == comp) { + comp = "SCARF@STFC"; + } m_model->doRefreshJobsInfo(comp); { // update widgets from that info QMutexLocker lockit(m_statusMutex); - m_view->updateJobsInfoDisplay(m_model->jobsStatus()); + m_view->updateJobsInfoDisplay(m_model->jobsStatus(), + m_model->jobsStatusLocal()); } } @@ -300,8 +365,8 @@ void TomographyIfacePresenter::processVisualizeJobs() { doVisualize(m_view->processingJobsIDs()); } -void -TomographyIfacePresenter::doVisualize(const std::vector<std::string> &ids) { +void TomographyIfacePresenter::doVisualize( + const std::vector<std::string> &ids) { m_model->logMsg(" Visualizing results from job: " + ids.front()); // TODO: open dialog, send to Paraview, etc. } diff --git a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp index 05b084651b90697bf6319cf982e3c0b23409bdab..1b7bbf798495e0491e27c38fcd509fb026d296d3 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/TomographyIfaceViewQtGUI.cpp @@ -4,7 +4,6 @@ #include "MantidQtAPI/AlgorithmInputHistory.h" #include "MantidQtAPI/HelpWindow.h" -#include "MantidQtCustomInterfaces/Tomography/ImageROIViewQtWidget.h" #include "MantidQtCustomInterfaces/Tomography/TomographyIfaceViewQtGUI.h" #include "MantidQtCustomInterfaces/Tomography/TomographyIfacePresenter.h" #include "MantidQtCustomInterfaces/Tomography/ToolConfigAstraToolbox.h" @@ -16,7 +15,10 @@ using namespace MantidQt::CustomInterfaces; #include <boost/lexical_cast.hpp> +#include <Poco/Path.h> + #include <QFileDialog> +#include <QFileSystemModel> #include <QMessageBox> #include <QPainter> #include <QSettings> @@ -24,11 +26,109 @@ using namespace MantidQt::CustomInterfaces; namespace MantidQt { namespace CustomInterfaces { +const std::string TomographyIfaceViewQtGUI::g_styleSheetOffline = + "QPushButton { " + "margin: 6px;" + "border-color: #0c457e;" + "border-style: outset;" + "border-radius: 3px;" + "border-width: 0px;" + "color: black;" + "background-color: rgb(180, 180, 180); " + "}" + "QPushButton:flat { " + "background-color: rgb(180, 180, 180); " + "}" + "QPushButton:pressed { " + "background-color: rgb(180, 180, 180) " + "}"; + +const std::string TomographyIfaceViewQtGUI::g_styleSheetOnline = + "QPushButton { " + "margin: 6px;" + "border-color: #0c457e;" + "border-style: outset;" + "border-radius: 3px;" + "border-width: 0px;" + "color: black;" + "background-color: rgb(140, 255, 140); " + "}" + "QPushButton:flat { background-color: rgb(120, 255, 120); " + "}" + "QPushButton:pressed { background-color: rgb(120, 255, 120); " + "}"; + size_t TomographyIfaceViewQtGUI::g_nameSeqNo = 0; +std::string TomographyIfaceViewQtGUI::g_defLocalExternalPythonPath = +#ifdef _WIN32 + // assume we're using Aanconda Python and it is installed in c:/local + // could also be c:/local/anaconda/scripts/ipython + "c:/local/anaconda/python.exe"; +#else + // just use the system Python, assuming is in the system path + "python"; +#endif + +// For paths where Python third party tools are installed, if they're +// not included in the system python path. For example you could have +// put the AstraToolbox package in +// C:/local/tomo-tools/astra/astra-1.6-python27-win-x64/astra-1.6 +// Leaving this empty implies that the tools must have been installed +// in the system Python path. As an example, in the Anaconda python +// distribution for windows it could be in: +// c:/local/Anaconda/Lib/site-packages/ +std::vector<std::string> TomographyIfaceViewQtGUI::g_defAddPathPython; + +const std::string TomographyIfaceViewQtGUI::g_defRemotePathScripts = + "/work/imat/phase_commissioning"; + const std::string TomographyIfaceViewQtGUI::g_SCARFName = "SCARF@STFC"; -const std::string TomographyIfaceViewQtGUI::g_defOutPath = - "/work/imat/runs_output"; +const std::string TomographyIfaceViewQtGUI::g_defOutPathLocal = +#ifdef _WIN32 + "D:/imat/"; +#else + "~/imat/"; +#endif + +const std::string TomographyIfaceViewQtGUI::g_defOutPathRemote = +#ifdef _WIN32 + "I:/imat-data/"; +#else + "~/imat-data/"; +#endif + +const std::string TomographyIfaceViewQtGUI::g_defParaviewPath = +#ifdef _WIN32 + "C:\\Program Files\\ParaView\\"; +#else + "/usr/bin/"; +#endif + +const std::string TomographyIfaceViewQtGUI::g_defParaviewAppendPath = +#ifdef _WIN32 + "bin\\paraview.exe"; +#else + "paraview"; +#endif + +const std::string notAvailTool = "This tool is not available on this platform"; + +const std::string TomographyIfaceViewQtGUI::g_defOctopusVisPath = +#ifdef _WIN32 + "C:/Program Files/Octopus Imaging/Octopus Visualisation"; +#else + notAvailTool; +#endif + +const std::string TomographyIfaceViewQtGUI::g_defOctopusAppendPath = +#ifdef _WIN32 + "octoviewer3d.exe"; +#else + notAvailTool; +#endif + +const std::string TomographyIfaceViewQtGUI::g_defProcessedSubpath = "processed"; // names by which we know image/tomography reconstruction tools (3rd party) const std::string TomographyIfaceViewQtGUI::g_TomoPyTool = "TomoPy"; @@ -37,6 +137,26 @@ const std::string TomographyIfaceViewQtGUI::g_CCPiTool = "CCPi CGLS"; const std::string TomographyIfaceViewQtGUI::g_SavuTool = "Savu"; const std::string TomographyIfaceViewQtGUI::g_customCmdTool = "Custom command"; +// phase or cycle component, like: phase_commissioning, cycle_15_4, cycle_16_1 +const std::string TomographyIfaceViewQtGUI::g_defPathComponentPhase = + "phase_commissioning"; + +const std::string TomographyIfaceViewQtGUI::g_defRBNumber = "RB000XXX"; + +const std::string TomographyIfaceViewQtGUI::g_defPathReconScripts = +#ifdef _WIN32 + "C:/MantidInstall/scripts"; +#else + QDir::currentPath().toStdString(); +#endif + +const std::string TomographyIfaceViewQtGUI::g_defPathReconOut = +#ifdef _WIN32 + "D:/imat"; +#else + "~/imat/"; +#endif + // Add this class to the list of specialised dialogs in this namespace DECLARE_SUBWINDOW(TomographyIfaceViewQtGUI) @@ -48,13 +168,18 @@ DECLARE_SUBWINDOW(TomographyIfaceViewQtGUI) * @param parent Parent window (most likely the Mantid main app window). */ TomographyIfaceViewQtGUI::TomographyIfaceViewQtGUI(QWidget *parent) - : UserSubWindow(parent), ITomographyIfaceView(), m_processingJobsIDs(), - m_currentComputeRes(""), m_currentReconTool(""), m_imgPath(""), - m_logMsgs(), m_toolsSettings(), m_settings(), + : UserSubWindow(parent), ITomographyIfaceView(), m_tabROIW(NULL), + m_processingJobsIDs(), m_currentComputeRes(""), m_currentReconTool(""), + m_imgPath(""), m_logMsgs(), m_toolsSettings(), m_settings(), m_settingsGroup("CustomInterfaces/Tomography"), m_availPlugins(), m_currPlugins(), m_currentParamPath(), m_presenter(NULL) { - // TODO: find a better place for this Savu stuff - see other TODOs + // defaults from the tools + m_tomopyMethod = ToolConfigTomoPy::methods().front().first; + m_astraMethod = ToolConfigAstraToolbox::methods().front().first; + + // TODO: find a better place for this Savu stuff when the tool is + // ready - see other TODOs m_availPlugins = Mantid::API::WorkspaceFactory::Instance().createTable(); m_availPlugins->addColumns("str", "name", 4); m_currPlugins = Mantid::API::WorkspaceFactory::Instance().createTable(); @@ -74,20 +199,23 @@ void TomographyIfaceViewQtGUI::initLayout() { m_uiTabSetup.setupUi(tabSetupW); m_ui.tabMain->addTab(tabSetupW, QString("Setup")); - ImageROIViewQtWidget *tabROIW = new ImageROIViewQtWidget(m_ui.tabMain); - m_ui.tabMain->addTab(tabROIW, QString("ROI etc.")); + m_tabROIW = new ImageROIViewQtWidget(m_ui.tabMain); + m_ui.tabMain->addTab(m_tabROIW, QString("ROI etc.")); QWidget *tabFiltersW = new QWidget(); m_uiTabFilters.setupUi(tabFiltersW); m_ui.tabMain->addTab(tabFiltersW, QString("Filters")); QWidget *tabVizW = new QWidget(); + m_uiTabVisualize.setupUi(tabVizW); m_ui.tabMain->addTab(tabVizW, QString("Visualize")); QWidget *tabConvertW = new QWidget(); + m_uiTabConvertFormats.setupUi(tabConvertW); m_ui.tabMain->addTab(tabConvertW, QString("Convert")); QWidget *tabEBandsW = new QWidget(); + m_uiTabEnergy.setupUi(tabEBandsW); m_ui.tabMain->addTab(tabEBandsW, QString("Energy bands")); readSettings(); @@ -98,6 +226,11 @@ void TomographyIfaceViewQtGUI::initLayout() { doSetupSectionRun(); doSetupSectionFilters(); + // extra / experimental tabs: + doSetupSectionVisualize(); + doSetupSectionConvert(); + doSetupSectionEnergy(); + // presenter that knows how to handle a ITomographyIfaceView should take care // of all the logic // note the view needs to now the concrete presenter @@ -123,17 +256,30 @@ void TomographyIfaceViewQtGUI::doSetupGeneralWidgets() { } void TomographyIfaceViewQtGUI::doSetupSectionSetup() { - // disable 'local' for now - m_uiTabSetup.tabWidget_comp_resource->setTabEnabled(false, 1); - m_uiTabSetup.tab_local->setEnabled(false); + // 'local' - not disabled any longer + // m_uiTabSetup.tabWidget_comp_resource->setTabEnabled(false, 1); + // m_uiTabSetup.tab_local->setEnabled(false); - m_uiTabSetup.groupBox_run_config->setEnabled(false); + resetRemoteSetup(); + // log in/out connect(m_uiTabSetup.pushButton_SCARF_login, SIGNAL(released()), this, SLOT(SCARFLoginClicked())); connect(m_uiTabSetup.pushButton_SCARF_logout, SIGNAL(released()), this, SLOT(SCARFLogoutClicked())); + // RB number changes + connect(m_uiTabSetup.lineEdit_cycle, SIGNAL(editingFinished()), this, + SLOT(updatedCycleName())); + + // 'browse' buttons for image paths + connect(m_uiTabSetup.pushButton_fits_dir, SIGNAL(released()), this, + SLOT(fitsPathBrowseClicked())); + connect(m_uiTabSetup.pushButton_flat_dir, SIGNAL(released()), this, + SLOT(flatPathBrowseClicked())); + connect(m_uiTabSetup.pushButton_dark_dir, SIGNAL(released()), this, + SLOT(darkPathBrowseClicked())); + // populate setup values from defaults m_uiTabSetup.lineEdit_path_FITS->setText( QString::fromStdString(m_pathsConfig.pathSamples())); @@ -146,13 +292,22 @@ void TomographyIfaceViewQtGUI::doSetupSectionSetup() { m_uiTabSetup.lineEdit_scripts_base_dir->setText( QString::fromStdString(m_pathsConfig.pathScriptsTools())); - // 'browse' buttons - connect(m_uiTabSetup.pushButton_fits_dir, SIGNAL(released()), this, - SLOT(fitsPathBrowseClicked())); - connect(m_uiTabSetup.pushButton_flat_dir, SIGNAL(released()), this, - SLOT(flatPathBrowseClicked())); - connect(m_uiTabSetup.pushButton_dark_dir, SIGNAL(released()), this, - SLOT(darkPathBrowseClicked())); + // reset setup of the remote + connect(m_uiTabSetup.pushButton_reset_scripts_base_dir, SIGNAL(released()), + this, SLOT(resetRemoteSetup())); + + // 'browse' buttons for local conf: + connect(m_uiTabSetup.pushButton_in_out_dir, SIGNAL(released()), this, + SLOT(browseLocalInOutDirClicked())); + connect(m_uiTabSetup.pushButton_recon_scripts_dir, SIGNAL(released()), this, + SLOT(browseLocalReconScriptsDirClicked())); +} + +void TomographyIfaceViewQtGUI::resetRemoteSetup() { + m_uiTabSetup.lineEdit_scripts_base_dir->setText( + QString::fromStdString(g_defRemotePathScripts)); + m_uiTabSetup.spinBox_SCARFnumNodes->setValue(1); + m_uiTabSetup.spinBox_SCARFnumCores->setValue(8); } void TomographyIfaceViewQtGUI::doSetupSectionRun() { @@ -173,8 +328,13 @@ void TomographyIfaceViewQtGUI::doSetupSectionRun() { m_uiTabRun.label_image_name->setText("none"); - m_uiTabRun.pushButton_reconstruct->setEnabled(false); - m_uiTabRun.pushButton_run_tool_setup->setEnabled(false); + updateCompResourceStatus(false); + + // enable by default, which will use default tools setups + m_uiTabRun.pushButton_reconstruct->setEnabled(true); + // setup always possible with local compute resource + // m_uiTabRun.pushButton_run_tool_setup->setEnabled(false); + m_uiTabRun.pushButton_run_tool_setup->setEnabled(true); m_uiTabRun.pushButton_run_job_cancel->setEnabled(false); m_uiTabRun.pushButton_run_job_visualize->setEnabled(false); @@ -192,6 +352,10 @@ void TomographyIfaceViewQtGUI::doSetupSectionRun() { connect(m_uiTabRun.pushButton_run_job_cancel, SIGNAL(released()), this, SLOT(jobCancelClicked())); + // RB number changes + connect(m_uiTabRun.lineEdit_rb_number, SIGNAL(editingFinished()), this, + SLOT(updatedRBNumber())); + // update tools for a resource connect(m_uiTabRun.comboBox_run_compute_resource, SIGNAL(currentIndexChanged(int)), this, @@ -206,6 +370,73 @@ void TomographyIfaceViewQtGUI::doSetupSectionFilters() { SLOT(resetPrePostFilters())); } +void TomographyIfaceViewQtGUI::doSetupSectionVisualize() { + // TODO: take g_def values first time, when Qsettings are empty, then from + // QSettings + m_setupParaviewPath = g_defParaviewPath; + m_setupProcessedSubpath = g_defProcessedSubpath; + m_setupOctopusVisPath = g_defOctopusVisPath; + + m_uiTabVisualize.lineEdit_processed_subpath->setText( + QString::fromStdString(g_defProcessedSubpath)); + m_uiTabVisualize.lineEdit_paraview_location->setText( + QString::fromStdString(g_defParaviewPath)); + + // make a file system model for the visualization browser + QFileSystemModel *model = new QFileSystemModel; + model->setRootPath(QDir::currentPath()); + + // set the model for the visualization browser + m_uiTabVisualize.treeView_files->setModel(model); + m_uiTabVisualize.treeView_files->setSelectionMode( + QTreeView::ExtendedSelection); + m_uiTabVisualize.treeView_files->setSelectionBehavior(QTreeView::SelectRows); + + // display: current dir + const QString startDir = + QString::fromStdString(Poco::Path::expand(g_defOutPathLocal)); + + // start at default local path when possible + const QString path = + QString::fromStdString(Poco::Path::expand(g_defOutPathLocal)); + if (!path.isEmpty()) { + m_uiTabVisualize.treeView_files->setRootIndex(model->index(path)); + } else { + m_uiTabVisualize.treeView_files->setRootIndex( + model->index(QDir::currentPath())); + } + + connect(m_uiTabVisualize.pushButton_paraview, SIGNAL(released()), this, + SLOT(sendToParaviewClicked())); + + connect(m_uiTabVisualize.pushButton_octopus, SIGNAL(released()), this, + SLOT(sendToOctopusVisClicked())); + + connect(m_uiTabVisualize.pushButton_browse_files, SIGNAL(released()), this, + SLOT(browseFilesToVisualizeClicked())); + + connect(m_uiTabVisualize.pushButton_local_default_dir, SIGNAL(released()), + this, SLOT(defaultDirLocalVisualizeClicked())); + connect(m_uiTabVisualize.pushButton_remote_default_dir, SIGNAL(released()), + this, SLOT(defaultDirRemoteVisualizeClicked())); +} + +void TomographyIfaceViewQtGUI::doSetupSectionConvert() { + connect(m_uiTabConvertFormats.pushButton_browse_input, SIGNAL(released()), + this, SLOT(browseImgInputConvertClicked())); + + connect(m_uiTabConvertFormats.pushButton_browse_output, SIGNAL(released()), + this, SLOT(browseImgOutputConvertClicked())); +} + +void TomographyIfaceViewQtGUI::doSetupSectionEnergy() { + connect(m_uiTabEnergy.pushButton_browse_input, SIGNAL(released()), this, + SLOT(browseEnergyInputClicked())); + + connect(m_uiTabEnergy.pushButton_browse_input, SIGNAL(released()), this, + SLOT(browseEnergyOutputClicked())); +} + void TomographyIfaceViewQtGUI::setComputeResources( const std::vector<std::string> &resources, const std::vector<bool> &enabled) { @@ -318,10 +549,18 @@ void TomographyIfaceViewQtGUI::enableLoggedActions(bool enable) { * @param online whether to show good/working/online status */ void TomographyIfaceViewQtGUI::updateCompResourceStatus(bool online) { - if (online) + if (online) { m_uiTabRun.pushButton_remote_status->setText("Online"); - else + // push buttons won't work with something like: + // m_uiTabRun.pushButton_remote_status->setBackground(QColor(120, 255, + // 120)); + m_uiTabRun.pushButton_remote_status->setStyleSheet( + QString::fromStdString(g_styleSheetOnline)); + } else { m_uiTabRun.pushButton_remote_status->setText("Offline"); + m_uiTabRun.pushButton_remote_status->setStyleSheet( + QString::fromStdString(g_styleSheetOffline)); + } } #ifndef _MSC_VER @@ -378,6 +617,7 @@ void TomographyIfaceViewQtGUI::readSettings() { m_settings.useKeepAlive = qs.value("use-keep-alive", m_settings.useKeepAlive).toInt(); + // Get all the pre-/post-processing options from a stream QByteArray rawFiltersSettings = qs.value("filters-settings").toByteArray(); QDataStream stream(rawFiltersSettings); TomoReconFiltersSettings filtersSettings; @@ -391,6 +631,43 @@ void TomographyIfaceViewQtGUI::readSettings() { setPrePostProcSettings(def); } + // User parameters for reconstructions + m_setupRBNumber = qs.value("RB-number", QString::fromStdString(g_defRBNumber)) + .toString() + .toStdString(); + + m_localExternalPythonPath = + qs.value("path-local-external-python", + QString::fromStdString(g_defLocalExternalPythonPath)) + .toString() + .toStdString(); + + int pathSize = qs.beginReadArray("path-default-add-for-python"); + for (int i = 0; i < pathSize; ++i) { + qs.setArrayIndex(i); + m_defAddPathPython.push_back( + qs.value("value", "").toString().toStdString()); + } + if (0 == m_defAddPathPython.size()) + m_defAddPathPython = g_defAddPathPython; + qs.endArray(); + + m_setupPathComponentPhase = + qs.value("path-default-phase-component", + QString::fromStdString(g_defPathComponentPhase)) + .toString() + .toStdString(); + m_setupPathReconScripts = + qs.value("path-reconstruction-scripts", + QString::fromStdString(g_defPathReconScripts)) + .toString() + .toStdString(); + m_setupPathReconOut = qs.value("path-reconstruction-output", + QString::fromStdString(g_defPathReconOut)) + .toString() + .toStdString(); + + // general GUI state m_ui.tabMain->setCurrentIndex(qs.value("selected-tab-index").toInt()); restoreGeometry(qs.value("interface-win-geometry").toByteArray()); @@ -437,11 +714,35 @@ void TomographyIfaceViewQtGUI::saveSettings() const { m_settings.onCloseAskForConfirmation); qs.setValue("use-keep-alive", m_settings.useKeepAlive); + // Save all the pre-/post-processing options through a stream QByteArray filtersSettings; QDataStream stream(&filtersSettings, QIODevice::WriteOnly); stream << grabPrePostProcSettings(); qs.setValue("filters-settings", filtersSettings); + // User parameters for reconstructions + qs.setValue("RB-number", QString::fromStdString(m_setupRBNumber)); + + qs.setValue("path-local-external-python", + QString::fromStdString(m_localExternalPythonPath)); + + qs.beginWriteArray("path-default-add-for-python"); + for (size_t i = 0; i < m_defAddPathPython.size(); ++i) { + qs.setArrayIndex(static_cast<int>(i)); + qs.setValue("value", QString::fromStdString(m_defAddPathPython[i])); + } + qs.endArray(); + + qs.setValue("path-default-phase-component", + QString::fromStdString(m_setupPathComponentPhase)); + + qs.setValue("path-reconstruction-scripts", + QString::fromStdString(m_setupPathReconScripts)); + + qs.setValue("path-reconstruction-output", + QString::fromStdString(m_setupPathReconOut)); + + // general GUI status qs.setValue("selected-tab-index", m_ui.tabMain->currentIndex()); qs.setValue("interface-win-geometry", saveGeometry()); @@ -566,49 +867,67 @@ void TomographyIfaceViewQtGUI::toolSetupClicked() { * @param name Name of the (tomographic reconstruction) tool */ void TomographyIfaceViewQtGUI::showToolConfig(const std::string &name) { + QString run = "/work/imat/phase_commissioning/scripts/Imaging/IMAT/" + "tomo_reconstruct.py"; // m_uiAstra.lineEdit_runnable->text(); + static size_t reconIdx = 1; + + const std::string localOutNameAppendix = + std::string("/processed/") + "reconstruction_" + std::to_string(reconIdx); + if (g_TomoPyTool == name) { TomoToolConfigTomoPy tomopy; m_uiTomoPy.setupUi(&tomopy); + m_uiTomoPy.comboBox_method->clear(); + auto methods = ToolConfigTomoPy::methods(); + for (size_t i = 0; i < methods.size(); i++) { + m_uiTomoPy.comboBox_method->addItem( + QString::fromStdString(methods[i].second)); + } int res = tomopy.exec(); + if (QDialog::Accepted == res) { // TODO: move this int mi = m_uiTomoPy.comboBox_method->currentIndex(); - QString run = m_uiTomoPy.lineEdit_runnable->text(); - if (1 == mi) { - // hard-coded for now, this is a different script on SCARF that should - // be - // integrated with the FBP script - run = "/work/imat/runs-scripts/scripts/tomopy/imat_recon_SIRT.py"; - } - double minAngle = m_uiTomoPy.doubleSpinBox_angle_min->value(); - double maxAngle = m_uiTomoPy.doubleSpinBox_angle_max->value(); - double cor = m_uiTomoPy.doubleSpinBox_center_rot->value(); TomoPathsConfig paths = currentPathsConfig(); + // TODO: for the output path, probably better to take the sample path, + // then up one level m_toolsSettings.tomoPy = ToolConfigTomoPy( - run.toStdString(), g_defOutPath, paths.pathDark(), - paths.pathOpenBeam(), paths.pathSamples(), cor, minAngle, maxAngle); + run.toStdString(), + g_defOutPathLocal + "/" + + m_uiTabSetup.lineEdit_cycle->text().toStdString() + "/" + + m_uiTabRun.lineEdit_rb_number->text().toStdString() + + localOutNameAppendix, + paths.pathDark(), paths.pathOpenBeam(), paths.pathSamples()); + m_tomopyMethod = methods[mi].first; } } else if (g_AstraTool == name) { TomoToolConfigAstra astra; m_uiAstra.setupUi(&astra); + m_uiAstra.comboBox_method->clear(); + auto methods = ToolConfigAstraToolbox::methods(); + for (size_t i = 0; i < methods.size(); i++) { + m_uiAstra.comboBox_method->addItem( + QString::fromStdString(methods[i].second)); + } int res = astra.exec(); + if (QDialog::Accepted == res) { // TODO: move this int mi = m_uiAstra.comboBox_method->currentIndex(); - QString run = m_uiAstra.lineEdit_runnable->text(); - if (1 == mi) { - // hard-coded for now, this is a different script on SCARF - run = "/work/imat/runs-scripts/scripts/astra/astra-3d-SIRT3D.py"; - } - double cor = m_uiAstra.doubleSpinBox_center_rot->value(); - double minAngle = m_uiAstra.doubleSpinBox_angle_min->value(); - double maxAngle = m_uiAstra.doubleSpinBox_angle_max->value(); TomoPathsConfig paths = currentPathsConfig(); + // TODO: for the output path, probably better to take the sample path, + // then up one level m_toolsSettings.astra = ToolConfigAstraToolbox( - run.toStdString(), cor, minAngle, maxAngle, g_defOutPath, + run.toStdString(), + Poco::Path::expand( + g_defOutPathLocal + "/" + + m_uiTabSetup.lineEdit_cycle->text().toStdString() + "/" + + m_uiTabRun.lineEdit_rb_number->text().toStdString() + + localOutNameAppendix), paths.pathDark(), paths.pathOpenBeam(), paths.pathSamples()); + m_astraMethod = methods[mi].first; } } else if (g_SavuTool == name) { // TODO: savu not ready. This is a temporary kludge, it just shows @@ -625,6 +944,7 @@ void TomographyIfaceViewQtGUI::showToolConfig(const std::string &name) { TomoToolConfigCustom cmd; m_uiCustom.setupUi(&cmd); int res = cmd.exec(); + if (QDialog::Accepted == res) { // TODO: move this QString run = m_uiCustom.lineEdit_runnable->text(); @@ -738,11 +1058,13 @@ void TomographyIfaceViewQtGUI::browseImageClicked() { * information from a recent query to the server. */ void TomographyIfaceViewQtGUI::updateJobsInfoDisplay( - const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> &status) { + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> &status, + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + &localStatus) { QTableWidget *t = m_uiTabRun.tableWidget_run_jobs; bool sort = t->isSortingEnabled(); - t->setRowCount(static_cast<int>(status.size())); + t->setRowCount(static_cast<int>(status.size() + localStatus.size())); for (size_t i = 0; i < status.size(); ++i) { int ii = static_cast<int>(i); @@ -752,12 +1074,66 @@ void TomographyIfaceViewQtGUI::updateJobsInfoDisplay( new QTableWidgetItem(QString::fromStdString(status[i].name))); t->setItem(ii, 2, new QTableWidgetItem(QString::fromStdString(status[i].id))); + t->setItem(ii, 3, new QTableWidgetItem(QString::fromStdString(status[i].status))); + + // beware "Exit" is called "Exited" on the web portal, but the REST + // responses + // call it "Exit" + if (std::string::npos != status[i].status.find("Exit") || + std::string::npos != status[i].status.find("Suspend")) + t->item(ii, 3)->setBackground(QColor(255, 120, 120)); // Qt::red + else if (std::string::npos != status[i].status.find("Pending")) + t->item(ii, 3)->setBackground(QColor(150, 150, 150)); // Qt::gray + else if (std::string::npos != status[i].status.find("Running") || + std::string::npos != status[i].status.find("Active")) + t->item(ii, 3)->setBackground(QColor(120, 120, 255)); // Qt::blue + else if (std::string::npos != status[i].status.find("Finished") || + std::string::npos != status[i].status.find("Done")) + t->item(ii, 3)->setBackground(QColor(120, 255, 120)); // Qt::green + t->setItem(ii, 4, new QTableWidgetItem(QString::fromStdString(status[i].cmdLine))); } + // Local processes + for (size_t i = 0; i < localStatus.size(); ++i) { + + // This won't work well, at least on windows. + // bool runs = Poco::isRunning( + // boost::lexical_cast<Poco::Process::PID>(localStatus[i].id)); + // if (!runs) + // m_localStatus[i].status = "Done"; + + int ii = static_cast<int>(status.size() + i); + t->setItem(ii, 0, new QTableWidgetItem(QString::fromStdString("local"))); + t->setItem(ii, 1, new QTableWidgetItem( + QString::fromStdString(localStatus[i].name))); + t->setItem(ii, 2, + new QTableWidgetItem(QString::fromStdString(localStatus[i].id))); + + t->setItem(ii, 3, new QTableWidgetItem( + QString::fromStdString(localStatus[i].status))); + + // beware "Exit" is called "Exited" on the web portal, but the + // REST responses call it "Exit" + if (std::string::npos != localStatus[i].status.find("Exit") || + std::string::npos != localStatus[i].status.find("Suspend")) + t->item(ii, 3)->setBackground(QColor(255, 120, 120)); // Qt::red + else if (std::string::npos != localStatus[i].status.find("Pending")) + t->item(ii, 3)->setBackground(QColor(150, 150, 150)); // Qt::gray + else if (std::string::npos != localStatus[i].status.find("Running") || + std::string::npos != localStatus[i].status.find("Active")) + t->item(ii, 3)->setBackground(QColor(120, 120, 255)); // Qt::blue + else if (std::string::npos != localStatus[i].status.find("Finished") || + std::string::npos != localStatus[i].status.find("Done")) + t->item(ii, 3)->setBackground(QColor(120, 255, 120)); // Qt::green + + t->setItem(ii, 4, new QTableWidgetItem( + QString::fromStdString(localStatus[i].cmdLine))); + } + t->setSortingEnabled(sort); } @@ -803,6 +1179,16 @@ void TomographyIfaceViewQtGUI::darkPathBrowseClicked() { m_presenter->notify(ITomographyIfacePresenter::TomoPathsChanged); } +void TomographyIfaceViewQtGUI::browseLocalInOutDirClicked() { + m_setupPathReconScripts = + checkUserBrowsePath(m_uiTabSetup.lineEdit_local_out_recon_dir); +} + +void TomographyIfaceViewQtGUI::browseLocalReconScriptsDirClicked() { + m_setupPathReconScripts = + checkUserBrowsePath(m_uiTabSetup.lineEdit_local_recon_scripts); +} + /** * Get path from user and update a line edit and a variable. * @@ -814,12 +1200,16 @@ void TomographyIfaceViewQtGUI::processPathBrowseClick(QLineEdit *le, std::string &data) { QString algPrev = MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); + /* + // This would remember every widget's old value, and not the last path QString prev; if (le->text().isEmpty()) { prev = algPrev; } else { prev = le->text(); } + */ + QString prev = algPrev; QString path(QFileDialog::getExistingDirectory( this, tr("Open directory/folder"), prev)); @@ -837,6 +1227,8 @@ void TomographyIfaceViewQtGUI::processPathBrowseClick(QLineEdit *le, le->setText(QString::fromStdString(pp)); data = pp; + + MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(path); } } @@ -1034,6 +1426,168 @@ void TomographyIfaceViewQtGUI::resetPrePostFilters() { setPrePostProcSettings(def); } +void TomographyIfaceViewQtGUI::sendToOctopusVisClicked() { + sendToVisTool("Octopus Visualization 3D", m_setupOctopusVisPath, + g_defOctopusAppendPath); +} + +void TomographyIfaceViewQtGUI::sendToParaviewClicked() { + sendToVisTool("ParaView", m_setupParaviewPath, g_defParaviewAppendPath); +} + +/** + * Start a third party tool as a process. TODO: This is a very early + * experimental implementation that should be moved out of this view. + * + * @param toolName Human understandable name of the tool/program + * @param pathString Path where the tool is installed + * @param appendBin string to append to the path if required, example: + * bin/tool.exe + */ +void TomographyIfaceViewQtGUI::sendToVisTool(const std::string &toolName, + const std::string &pathString, + const std::string &appendBin) { + // prepare external tool executable path + Poco::Path tmpPath(pathString); + if (!appendBin.empty()) { + tmpPath.append(appendBin); + } + const std::string toolPath = tmpPath.toString(); + + // get path to pass as parameter + const QFileSystemModel *model = dynamic_cast<QFileSystemModel *>( + m_uiTabVisualize.treeView_files->model()); + if (!model) + return; + + auto selection = + m_uiTabVisualize.treeView_files->selectionModel()->selectedIndexes(); + // just take the first selected item/directory + if (selection.empty()) + return; + QString selPath = model->filePath(selection.first()); + + // Execute + std::vector<std::string> args; + args.push_back(selPath.toStdString()); + + sendLog("Executing visualization tool: " + toolName + ". Executing: '" + + toolPath + "', with parameters: '" + args[0] + "'."); + try { + Mantid::Kernel::ConfigService::Instance().launchProcess(toolPath, args); + } catch (std::runtime_error &rexc) { + sendLog("The execution of " + toolName + "failed. details: " + + std::string(rexc.what())); + userWarning("Execution failed ", + "Coult not execute the tool. Error details: " + + std::string(rexc.what())); + } +} + +void TomographyIfaceViewQtGUI::browseFilesToVisualizeClicked() { + // an alternative would be to start from the current selection, instead of the + // current root: + const QFileSystemModel *model = dynamic_cast<QFileSystemModel *>( + m_uiTabVisualize.treeView_files->model()); + if (!model) + return; + + const QString currentPath = model->rootPath(); + QString path(QFileDialog::getExistingDirectory( + this, tr("Select root directory/folder with processed data " + "(reconstructions) under it"), + currentPath)); + + if (!path.isEmpty()) { + m_uiTabVisualize.treeView_files->setRootIndex(model->index(path)); + } +} + +void TomographyIfaceViewQtGUI::defaultDirLocalVisualizeClicked() { + const QFileSystemModel *model = dynamic_cast<QFileSystemModel *>( + m_uiTabVisualize.treeView_files->model()); + if (!model) + return; + + const QString path = + QString::fromStdString(Poco::Path::expand(g_defOutPathLocal)); + if (!path.isEmpty()) { + m_uiTabVisualize.treeView_files->setRootIndex(model->index(path)); + } +} + +void TomographyIfaceViewQtGUI::defaultDirRemoteVisualizeClicked() { + const QFileSystemModel *model = dynamic_cast<QFileSystemModel *>( + m_uiTabVisualize.treeView_files->model()); + if (!model) + return; + + const QString path = + QString::fromStdString(Poco::Path::expand(g_defOutPathRemote)); + if (!path.isEmpty()) { + m_uiTabVisualize.treeView_files->setRootIndex(model->index(path)); + } +} + +void TomographyIfaceViewQtGUI::browseVisToolParaviewClicke() { + m_setupParaviewPath = + checkUserBrowsePath(m_uiTabConvertFormats.lineEdit_input); +} + +void TomographyIfaceViewQtGUI::browseVisToolOctopusClicked() { + m_setupOctopusVisPath = + checkUserBrowsePath(m_uiTabConvertFormats.lineEdit_input); +} + +void TomographyIfaceViewQtGUI::browseImgInputConvertClicked() { + // Not using this path to update the "current" path where to load from, but + // it could be an option. + // const std::string path = + checkUserBrowsePath(m_uiTabConvertFormats.lineEdit_input); + // m_pathsConfig.updatePathDark(str); + // m_presenter->notify(ITomographyIfacePresenter::TomoPathsChanged); +} + +void TomographyIfaceViewQtGUI::browseImgOutputConvertClicked() { + // Not using this path to update the "current" path where to load from, but + // it could be an option. + // const std::string path = + checkUserBrowsePath(m_uiTabConvertFormats.lineEdit_output); + // m_pathsConfig.updatePathDark(str); + // m_presenter->notify(ITomographyIfacePresenter::TomoPathsChanged); +} + +void TomographyIfaceViewQtGUI::browseEnergyInputClicked() { + checkUserBrowsePath(m_uiTabEnergy.lineEdit_input_path); +} + +void TomographyIfaceViewQtGUI::browseEnergyOutputClicked() { + checkUserBrowsePath(m_uiTabEnergy.lineEdit_output_path); +} + +std::string +TomographyIfaceViewQtGUI::checkUserBrowsePath(QLineEdit *le, + const std::string &userMsg) { + + QString prev; + if (le->text().isEmpty()) { + prev = + MantidQt::API::AlgorithmInputHistory::Instance().getPreviousDirectory(); + } else { + prev = le->text(); + } + + QString path(QFileDialog::getExistingDirectory( + this, tr(QString::fromStdString(userMsg)), prev)); + + if (!path.isEmpty()) { + le->setText(path); + MantidQt::API::AlgorithmInputHistory::Instance().setPreviousDirectory(path); + } + + return path.toStdString(); +} + /** * Show a warning message to the user (pop up) * @@ -1048,6 +1602,24 @@ void TomographyIfaceViewQtGUI::userWarning(const std::string &err, QMessageBox::Ok); } +void TomographyIfaceViewQtGUI::updatedCycleName() { + m_setupPathComponentPhase = m_uiTabSetup.lineEdit_cycle->text().toStdString(); +} + +void TomographyIfaceViewQtGUI::updatedRBNumber() { + m_setupRBNumber = m_uiTabRun.lineEdit_rb_number->text().toStdString(); + // Might have to change: m_uiTabRun.lineEdit_local_out_recon_dir as well +} + +/** + * To log a message without waiting. + */ +void TomographyIfaceViewQtGUI::sendLog(const std::string &msg) { + m_logMsgs.push_back(msg); + m_presenter->notify(ITomographyIfacePresenter::LogMsg); + m_logMsgs.clear(); +} + /** * Show an error (serious) message to the user (pop up) * diff --git a/MantidQt/CustomInterfaces/src/Tomography/ToolConfig.cpp b/MantidQt/CustomInterfaces/src/Tomography/ToolConfig.cpp index feb959472f6907482fb64850c5e862ecd2cb79cb..5ef6a0785a70a8878668a596d5cbada971444424 100644 --- a/MantidQt/CustomInterfaces/src/Tomography/ToolConfig.cpp +++ b/MantidQt/CustomInterfaces/src/Tomography/ToolConfig.cpp @@ -7,50 +7,79 @@ namespace MantidQt { namespace CustomInterfaces { +// pairs of name-in-the-tool, human-readable-name +const std::vector< + std::pair<std::string, std::string>> ToolConfigTomoPy::g_tomopyMethods = { + std::make_pair("gridrec", "gridrec: Fourier grid reconstruction " + "algorithm (Dowd, 19999; Rivers, 2006)"), + std::make_pair("sirt", + "sirt: Simultaneous algebraic reconstruction technique"), + + std::make_pair("art", + "art: Algebraic reconstruction technique (Kak, 1998)"), + std::make_pair("bart", "bart: Block algebraic reconstruction technique."), + std::make_pair("fbp", "fbp: Filtered back-projection algorithm"), + std::make_pair("mlem", "mlem: Maximum-likelihood expectation maximization " + "algorithm (Dempster, 1977)"), + std::make_pair("osem", "osem: Ordered-subset expectation maximization " + "algorithm (Hudson, 1994)"), + std::make_pair("ospml_hybrid", + "ospml_hybrid: Ordered-subset penalized maximum " + "likelihood algorithm with weighted " + "linear and quadratic penalties"), + std::make_pair("ospml_quad", "ospml_quad: Ordered-subset penalized maximum " + "likelihood algorithm with quadratic " + "penalties"), + std::make_pair("pml_hybrid", + "pml_hybrid: Penalized maximum likelihood algorithm " + "with weighted linear and quadratic " + "penalties (Chang, 2004)"), + std::make_pair("pml_quad", "pml_quad: Penalized maximum likelihood " + "algorithm with quadratic penalty"), +}; + ToolConfigTomoPy::ToolConfigTomoPy() : TomoRecToolConfig(""), m_pathOut(""), m_pathDark(""), m_pathOpen(""), - m_pathSample(""), m_centerRot(.0), m_angleMin(.0), m_angleMax(180.0) {} + m_pathSample("") {} ToolConfigTomoPy::ToolConfigTomoPy(const std::string &runnable, const std::string &pathOut, const std::string &pathDark, const std::string &pathOpen, - const std::string &pathSample, - double centerRot, double angleMin, - double angleMax) + const std::string &pathSample) : TomoRecToolConfig(runnable), m_pathOut(pathOut), m_pathDark(pathDark), - m_pathOpen(pathOpen), m_pathSample(pathSample), m_centerRot(centerRot), - m_angleMin(angleMin), m_angleMax(angleMax) {} + m_pathOpen(pathOpen), m_pathSample(pathSample) {} std::string ToolConfigTomoPy::makeCmdLineOptions() const { - return "--input_dir " + m_pathSample + " --dark " + m_pathDark + " --white " + - m_pathOpen + " --output " + m_pathOut + " --start_angle " + - boost::lexical_cast<std::string>(m_angleMin) + " --end_angle " + - boost::lexical_cast<std::string>(m_angleMax) + - " --center_of_rotation " + - boost::lexical_cast<std::string>(m_centerRot); + return "--input-path=" + m_pathSample + " --output-path=" + m_pathOut; } ToolConfigAstraToolbox::ToolConfigAstraToolbox() - : TomoRecToolConfig(""), m_centerRot(.0), m_angleMin(.0), m_angleMax(180.0), - m_pathOut(""), m_pathDark(""), m_pathOpen(""), m_pathSample("") {} - -ToolConfigAstraToolbox::ToolConfigAstraToolbox( - const std::string &runnable, double centerRot, double angleMin, - double angleMax, const std::string &pathOut, const std::string &pathDark, - const std::string &pathOpen, const std::string &pathSample) - : TomoRecToolConfig(runnable), m_centerRot(centerRot), m_angleMin(angleMin), - m_angleMax(angleMax), m_pathOut(pathOut), m_pathDark(pathDark), + : TomoRecToolConfig(""), m_pathOut(""), m_pathDark(""), m_pathOpen(""), + m_pathSample("") {} + +ToolConfigAstraToolbox::ToolConfigAstraToolbox(const std::string &runnable, + const std::string &pathOut, + const std::string &pathDark, + const std::string &pathOpen, + const std::string &pathSample) + : TomoRecToolConfig(runnable), m_pathOut(pathOut), m_pathDark(pathDark), m_pathOpen(pathOpen), m_pathSample(pathSample) {} std::string ToolConfigAstraToolbox::makeCmdLineOptions() const { - return "--start_slice " + boost::lexical_cast<std::string>(m_angleMin) + - " --end_slice " + boost::lexical_cast<std::string>(m_angleMax) + - " --center_of_rotation " + - boost::lexical_cast<std::string>(m_centerRot) + " --input_dir " + - m_pathSample + " --dark " + m_pathDark + " --white " + m_pathOpen + - " --output " + m_pathOut; + return " --input-path=" + m_pathSample + " --output-path=" + m_pathOut; } +const std::vector<std::pair< + std::string, std::string>> ToolConfigAstraToolbox::g_astraMethods = { + std::make_pair("FBP3D_CUDA", "FBP 3D: Filtered Back-Propagation"), + std::make_pair( + "SIRT3D_CUDA", + "SIRT 3D: Simultaneous Iterative Reconstruction Technique algorithm"), + std::make_pair("CGLS3D_CUDA", + "CGLS 3D: Conjugate gradient least square algorithm"), + std::make_pair("FDK_CUDA", "FDK 3D: Feldkamp-Davis-Kress algorithm for " + "3D circular cone beam data sets")}; + } // namespace CustomInterfaces } // namespace MantidQt diff --git a/MantidQt/CustomInterfaces/test/TomographyIfacePresenterTest.h b/MantidQt/CustomInterfaces/test/TomographyIfacePresenterTest.h index 06b999c3ab4dace814f0066c319e414ef6554783..c00feb373523533ec1e30071aa142059ed01fc3b 100644 --- a/MantidQt/CustomInterfaces/test/TomographyIfacePresenterTest.h +++ b/MantidQt/CustomInterfaces/test/TomographyIfacePresenterTest.h @@ -212,11 +212,19 @@ public: tools.push_back(g_ccpi); tools.emplace_back("Savu"); - for (size_t i = 0; i < tools.size(); i++) { + TSM_ASSERT_EQUALS("There should be 4 tools in this test", tools.size(), 4); + // up to this index the tools are supported + const size_t indexToolsWork = 1; + for (size_t i = 0; i < 3; i++) { EXPECT_CALL(mockView, currentReconTool()) .Times(1) .WillOnce(Return(tools[i])); - EXPECT_CALL(mockView, currentComputeResource()).Times(0); + if (i <= indexToolsWork) { + EXPECT_CALL(mockView, currentComputeResource()).Times(1); + } else { + EXPECT_CALL(mockView, currentComputeResource()).Times(0); + } + EXPECT_CALL(mockView, enableRunReconstruct(testing::_)).Times(1); EXPECT_CALL(mockView, enableConfigTool(testing::_)).Times(1); @@ -309,7 +317,8 @@ public: MantidQt::CustomInterfaces::TomographyIfacePresenter pres(&mockView); EXPECT_CALL(mockView, currentComputeResource()).Times(0); - EXPECT_CALL(mockView, updateJobsInfoDisplay(testing::_)).Times(0); + EXPECT_CALL(mockView, updateJobsInfoDisplay(testing::_, testing::_)) + .Times(1); // No errors, no warnings EXPECT_CALL(mockView, userError(testing::_, testing::_)).Times(0); @@ -323,7 +332,8 @@ public: MantidQt::CustomInterfaces::TomographyIfacePresenter pres(&mockView); EXPECT_CALL(mockView, currentComputeResource()).Times(0); - EXPECT_CALL(mockView, updateJobsInfoDisplay(testing::_)).Times(0); + EXPECT_CALL(mockView, updateJobsInfoDisplay(testing::_, testing::_)) + .Times(1); // No errors, no warnings EXPECT_CALL(mockView, userError(testing::_, testing::_)).Times(0); @@ -360,12 +370,13 @@ public: "expected (maximum angle)", def.prep.maxAngle, 360.0); - TSM_ASSERT_LESS_THAN_EQUALS("Pre-processing settings default values should be as " - "expected (scale down)", - def.prep.scaleDownFactor, 1); + TSM_ASSERT_LESS_THAN_EQUALS( + "Pre-processing settings default values should be as " + "expected (scale down)", + def.prep.scaleDownFactor, 1); TSM_ASSERT_DELTA("Post-processing settings default values should be as " - "expected (circular mask)", + "expected (circular mask)", def.postp.circMaskRadius, 0.94, 1e-5); TSM_ASSERT_EQUALS("Post-processing settings default values should be as " @@ -387,12 +398,14 @@ public: .Times(1) .WillOnce(Return(TomoPathsConfig())); + // user changes some paths pres.notify(ITomographyIfacePresenter::TomoPathsChanged); EXPECT_CALL(mockView, currentComputeResource()) - .Times(1) - .WillOnce(Return(g_scarfName)); + .Times(2) + .WillRepeatedly(Return(g_scarfName)); + // user changes the compute resource pres.notify(ITomographyIfacePresenter::CompResourceChanged); EXPECT_CALL(mockView, currentReconTool()) @@ -404,15 +417,41 @@ public: .Times(1) .WillOnce(Return(toolsSettings)); + // user opens dialog and sets up a reconstruction tool pres.notify(ITomographyIfacePresenter::SetupReconTool); - // should not use this for now: - EXPECT_CALL(mockView, prePostProcSettings()).Times(0); + TomoPathsConfig pathsCfg; + EXPECT_CALL(mockView, currentPathsConfig()) + .Times(1) + .WillOnce(Return(pathsCfg)); + + ImageStackPreParams roiEtc; + EXPECT_CALL(mockView, currentROIEtcParams()) + .Times(1) + .WillOnce(Return(roiEtc)); + + EXPECT_CALL(mockView, tomopyMethod()).Times(1).WillOnce(Return("")); + + EXPECT_CALL(mockView, astraMethod()).Times(1).WillOnce(Return("")); + + TomoReconFiltersSettings filters; + EXPECT_CALL(mockView, prePostProcSettings()) + .Times(1) + .WillOnce(Return(filters)); + + EXPECT_CALL(mockView, externalInterpreterPath()) + .Times(1) + .WillOnce(Return("")); + + EXPECT_CALL(mockView, pathLocalReconScripts()) + .Times(1) + .WillOnce(Return("")); // No errors, no warnings EXPECT_CALL(mockView, userError(testing::_, testing::_)).Times(0); EXPECT_CALL(mockView, userWarning(testing::_, testing::_)).Times(0); + // finally, user tries to run a reconstruction job pres.notify(ITomographyIfacePresenter::RunReconstruct); } diff --git a/MantidQt/CustomInterfaces/test/TomographyViewMock.h b/MantidQt/CustomInterfaces/test/TomographyViewMock.h index 4adee0e2dee5d023ef04914a4ceafe243a4a974a..027d14bcf1451989ac422dde310f67c20020d9d8 100644 --- a/MantidQt/CustomInterfaces/test/TomographyViewMock.h +++ b/MantidQt/CustomInterfaces/test/TomographyViewMock.h @@ -51,6 +51,12 @@ public: // std::string currentReconTool() const {} MOCK_CONST_METHOD0(currentReconTool, std::string()); + // std::string astraMethod() const {} + MOCK_CONST_METHOD0(astraMethod, std::string()); + + // std::string tomopyMethod() const {} + MOCK_CONST_METHOD0(tomopyMethod, std::string()); + // void updateLoginControls(bool loggedIn) {} MOCK_METHOD1(updateLoginControls, void(bool loggedIn)); @@ -76,14 +82,30 @@ public: MOCK_CONST_METHOD0(currentPathsConfig, MantidQt::CustomInterfaces::TomoPathsConfig()); + // ImageStackPreParams currentROIEtcParams() const = 0; + MOCK_CONST_METHOD0(currentROIEtcParams, + MantidQt::CustomInterfaces::ImageStackPreParams()); + // void showToolConfig(const std::string &name) {} MOCK_METHOD1(showToolConfig, void(const std::string &name)); - // void updateJobsInfoDisplay(const std::vector< - // Mantid::API::IRemoteJobManager::RemoteJobInfo> &status) {} - MOCK_METHOD1(updateJobsInfoDisplay, - void(const std::vector< - Mantid::API::IRemoteJobManager::RemoteJobInfo> &status)); + // std::string pathLocalReconScripts() {} + MOCK_CONST_METHOD0(pathLocalReconScripts, std::string()); + + // std::string externalInterpreterPath() {} + MOCK_CONST_METHOD0(externalInterpreterPath, std::string()); + + // virtual void updateJobsInfoDisplay( const + // std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + // &status, const + // std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> & + // localStatus) = 0; + MOCK_METHOD2( + updateJobsInfoDisplay, + void(const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + &status, + const std::vector<Mantid::API::IRemoteJobManager::RemoteJobInfo> + &localStatus)); // MantidQt::CustomInterfaces::TomoReconToolsUserSettings // reconToolsSettings() const {} diff --git a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py index 2dc3da6a51200cc1f3be7ff9ad6cfba5d0abe62c..43e1d90d29c7d86895fa6bcabbb93ae4af862b97 100644 --- a/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py +++ b/Testing/SystemTests/tests/analysis/ImagingIMATTomoScripts.py @@ -264,6 +264,8 @@ class ImagingIMATTomoTests(unittest.TestCase): pre = cfgs.PreProcConfig() self.assertEquals(pre.input_dir, None) + self.assertEquals(pre.input_dir_flat, None) + self.assertEquals(pre.input_dir_dark, None) self.assertEquals(pre.max_angle, 360) self.assertEquals(pre.normalize_flat_dark, True) self.assertEquals(pre.crop_coords, None) diff --git a/docs/source/images/tomo_tab1_submission_reconstruction_jobs.png b/docs/source/images/tomo_tab1_submission_reconstruction_jobs.png new file mode 100644 index 0000000000000000000000000000000000000000..d2e8760225b5d0c9fa61daa9c8cb83e91fb782fb Binary files /dev/null and b/docs/source/images/tomo_tab1_submission_reconstruction_jobs.png differ diff --git a/docs/source/images/tomo_tab2_setup_authentication.png b/docs/source/images/tomo_tab2_setup_authentication.png new file mode 100644 index 0000000000000000000000000000000000000000..3c322bb8392a94a4da7ef94ce511344661f2b82d Binary files /dev/null and b/docs/source/images/tomo_tab2_setup_authentication.png differ diff --git a/docs/source/images/tomo_tab3_ROI_etc.png b/docs/source/images/tomo_tab3_ROI_etc.png new file mode 100644 index 0000000000000000000000000000000000000000..6abf4163842f379fa1d27c71e24b0c4034449bf6 Binary files /dev/null and b/docs/source/images/tomo_tab3_ROI_etc.png differ diff --git a/docs/source/images/tomo_tab4_pre_post_proc_filters.png b/docs/source/images/tomo_tab4_pre_post_proc_filters.png new file mode 100644 index 0000000000000000000000000000000000000000..b102e9c7e218b89dffadff2cf23f0b309cd84fd4 Binary files /dev/null and b/docs/source/images/tomo_tab4_pre_post_proc_filters.png differ diff --git a/docs/source/images/tomo_tab5_send_to_viz.png b/docs/source/images/tomo_tab5_send_to_viz.png new file mode 100644 index 0000000000000000000000000000000000000000..21fa22130b6131f6c4317263caf6e36f6d0edd8e Binary files /dev/null and b/docs/source/images/tomo_tab5_send_to_viz.png differ diff --git a/docs/source/images/tomo_tab6_formats_convert.png b/docs/source/images/tomo_tab6_formats_convert.png new file mode 100644 index 0000000000000000000000000000000000000000..42833bb8247937b87f4c47ae81f9b906955cb974 Binary files /dev/null and b/docs/source/images/tomo_tab6_formats_convert.png differ diff --git a/docs/source/images/tomo_tab7_energy_bands.png b/docs/source/images/tomo_tab7_energy_bands.png new file mode 100644 index 0000000000000000000000000000000000000000..6d36e575bf84e915556442a34ae9cc211e35da5f Binary files /dev/null and b/docs/source/images/tomo_tab7_energy_bands.png differ diff --git a/docs/source/interfaces/Tomographic_Reconstruction.rst b/docs/source/interfaces/Tomographic_Reconstruction.rst index 03a11b7729d5062928ae3e46ffb46e4cb9043b94..f882680185a7c5df0384eeef6ffcb4eccea4007f 100644 --- a/docs/source/interfaces/Tomographic_Reconstruction.rst +++ b/docs/source/interfaces/Tomographic_Reconstruction.rst @@ -25,10 +25,11 @@ login and through its `web portal <https://portal.scarf.rl.ac.uk/>`_. This resource is available for ISIS users. -.. warning:: This interface is undergoing heavy works. New functionality - is being added and the pre-post-processing and reconstruction - workflow is being modified based on feedback from initial - test data. +.. warning:: This interface is undergoing heavy works. The sections or + tabs are subject to changes and reorganization.New + functionality is being added and the pre-post-processing + and reconstruction workflow is being modified based on + feedback from initial test data. Interface at a glance --------------------- @@ -37,10 +38,9 @@ By default the interface shows the *Run* tab, where you can visualize images, submit reconstruction jobs, see and control the status of the jobs submitted recently. -.. interface:: Tomographic Reconstruction - :widget: runTab - :align: right - :width: 300 +.. figure:: /images/tomo_tab1_submission_reconstruction_jobs.png + :align: right + :scale: 50% In the setup tab you can set the details of the remote and/or local compute resources. Importantly, here is where you can set you username @@ -64,16 +64,15 @@ Open beam directory Dark field directory Where to find the dark image(s) -.. interface:: Tomographic Reconstruction - :widget: setupTab - :align: right - :width: 300 +.. figure:: /images/tomo_tab2_setup_authentication.png + :align: center + :scale: 60% -**NB**: as this interface is in an early stage and under heavy -development, several practical details are missing. This implies that -there may be usability issues at times and some steps may not be as -intuitive or simple as they could. Please, do not hesitate to provide -suggestions and feedback. +**NB**: This interface is under heavy development. Several practical +details lack polishing and/or are missing. This implies that there may +be usability issues at times and some steps may not be as intuitive or +simple as they could. Please, do not hesitate to provide suggestions +and feedback. The next sections provide further details that might be needed to fully understand the process of generating tomographic reconstructions @@ -158,9 +157,13 @@ Data locations This is dependent on the facility and instrument. -TODO: this is work in progress. In principle data will be replicated -in the ISIS archive, the SCARF imat disk space, and possibly an -analysis machine located in R3. +TODO: this is work in progress. At ISIS In principle data will be +replicated in the ISIS archive, the SCARF imat disk space, and +possibly an analysis machine located in R3. + +The tab *Visualization* has simple push buttons to browse the files +available from the local and remote locations, as well as any other +directory or folder selected by the user. Running jobs remotely --------------------- @@ -194,6 +197,10 @@ the tool and/or reconstruction method used. * Area for normalization (open beam, not blocked by sample) * Center of rotation, for tomographic reconstruction +.. figure:: /images/tomo_tab3_ROI_etc.png + :align: center + :scale: 60% + At any stage during the process of selecting the regions it is also possible to see how the selections fit different images by sliding through the images of the stack (using the slider or scroll bar). @@ -230,12 +237,16 @@ jobs. Pre-processing filters are applied on the raw input images before the reconstruction algorithm is run. Post-processing steps are applied on the reconstructed volume produced by the algorithm. +.. figure:: /images/tomo_tab4_pre_post_proc_filters.png + :align: center + :scale: 60% + The tab also shows options to define what outputs should be produced in addition to the reconstructed volume. -The settings are rememberd between session, and it is possible to -reset all the settings to their factory default by clicking on the -reset button. +The settings are remembered between sessions. It is possible to reset +all the settings to their original defaults by clicking on the reset +button. Results from reconstruction jobs -------------------------------- @@ -258,12 +269,54 @@ same location: Running jobs locally -------------------- -This functionality is not available at present. +This capability is being developed at the moment, and it requires +additional setup steps on the local analysis machine. Basic +functionality is supported only on the IMAT data analysis machine. + +Visualization +------------- + +.. warning:: The interface is being extended to have integration with + third party tools for 3D visualization and segmentation. + This is work in progress. + +The **Visualization** tab can be used to browse the local and remote +locations where results are stored. It is also possible to open these +results in third party visualization applications. **NB**: ParaView is +currently supported and additional tools are being integrated. + +.. figure:: /images/tomo_tab5_send_to_viz.png + :align: center + :scale: 60% + +Energy bands +------------ + +.. warning:: The interface is being extended to provide different methods + of combining energy bands from energy selective experiments. + This is work in progress. + +.. figure:: /images/tomo_tab7_energy_bands.png + :align: center + :scale: 60% + +Conversion between formats +-------------------------- + +.. warning:: The interface is being extended to provide a simple graphical + interface to convert between different image formats for + convenience and interoperability with third party tools. + This is work in progress as support for new formats is being + integrated. + +.. figure:: /images/tomo_tab6_formats_convert.png + :align: center + :scale: 60% Example ------- -TODO: ideally, come up with a good and small example data set. +TODO: there should be an example using a small data set. TomoPy ------ diff --git a/scripts/Imaging/IMAT/tomo_reconstruct.py b/scripts/Imaging/IMAT/tomo_reconstruct.py index 1510f3a9357f6a62269712d74fe00dbfcf21184d..acec79cac710033817e23640dcf6bfaa6e2d2885 100644 --- a/scripts/Imaging/IMAT/tomo_reconstruct.py +++ b/scripts/Imaging/IMAT/tomo_reconstruct.py @@ -92,14 +92,19 @@ def setup_cmd_options(): help="Number of iterations (only valid for iterative methods " "(example: SIRT, ART, etc.).") - - grp_recon.add_argument("--max-angle", required=False, type=int, + grp_recon.add_argument("--max-angle", required=False, type=float, help="Maximum angle (of the last projection), assuming first angle=0, and " "uniform angle increment for every projection (note: this " "is overriden by the angles found in the input FITS headers)") grp_pre = parser.add_argument_group('Pre-processing of input raw images/projections') + grp_pre.add_argument("--input-path-flat", required=False, default=None, + type=str, help="Input directory for flat images") + + grp_pre.add_argument("--input-path-dark", required=False, default=None, + type=str, help="Input directory for flat images") + img_formats = ['tiff', 'fits', 'tif', 'fit', 'png'] grp_pre.add_argument("--in-img-format", required=False, default='fits', type=str, help="Format/file extension expected for the input images. Supported: {0}". @@ -171,6 +176,8 @@ def grab_preproc_options(args): pre_config = tomocfg.PreProcConfig() pre_config.input_dir = args.input_path + pre_config.input_dir_flat = args.input_path_flat + pre_config.input_dir_dark = args.input_path_dark if args.in_img_format: pre_config.in_img_format = args.in_img_format @@ -196,7 +203,7 @@ def grab_preproc_options(args): pre_config.crop_coords = ast.literal_eval(args.air_region) if args.median_filter_size: - if not args.median_filter.isdigit(): + if isinstance(args.median_filter_size, str) and not args.median_filter_size.isdigit(): raise RuntimeError("The median filter size/width must be an integer") pre_config.median_filter_size = args.median_filter_size @@ -218,7 +225,7 @@ def grab_tool_alg_options(args): config.algorithm = args.algorithm if args.num_iter: - if not args.num_iter.isdigit(): + if isinstance(args.num_iter, str) and not args.num_iter.isdigit(): raise RuntimeError("The number of iterations must be an integer") config.num_iter = int(args.num_iter) diff --git a/scripts/Imaging/IMAT/tomorec/configs.py b/scripts/Imaging/IMAT/tomorec/configs.py index 6f550dadd031f348ce111ecafe5b58e31315268a..170fc7845d0917f1b35b15f1d8127eda7ba8eb4d 100644 --- a/scripts/Imaging/IMAT/tomorec/configs.py +++ b/scripts/Imaging/IMAT/tomorec/configs.py @@ -74,6 +74,8 @@ class PreProcConfig(object): # defaults that look sensible for the MCP detector: # median_filter=3, rotate=-1, crop=[0, 252, 0, 512], MCP correction: on self.input_dir = None + self.input_dir_flat = None + self.input_dir_dark = None self.in_img_format = 'tiff' self.out_img_format = 'tiff' self.max_angle = 360 @@ -104,6 +106,8 @@ class PreProcConfig(object): else: mystr += "Input path (absolute): {0}\n".format('cannot find because the input ' 'path has not been set') + mystr += "Input path for flat (open beam) images (relative): {0}\n".format(self.input_dir_flat) + mystr += "Input path for dark images (relative): {0}\n".format(self.input_dir_dark) mystr += "Input image format: {0}\n".format(self.in_img_format) mystr += "Output image format: {0}\n".format(self.out_img_format) mystr += "Maximum angle:: {0}\n".format(self.max_angle) diff --git a/scripts/Imaging/IMAT/tomorec/reconstruction_command.py b/scripts/Imaging/IMAT/tomorec/reconstruction_command.py index 822de7cdb504a2e13b72c9f3704fafba6af44337..424daed256a83c757b6e562f042701b99f8dd848 100644 --- a/scripts/Imaging/IMAT/tomorec/reconstruction_command.py +++ b/scripts/Imaging/IMAT/tomorec/reconstruction_command.py @@ -75,7 +75,8 @@ class ReconstructionCommand(object): readme_fullpath = os.path.join(cfg.postproc_cfg.output_dir, self._OUT_README_FNAME) tstart = self.gen_readme_summary_begin(readme_fullpath, cfg, cmd_line) - data, white, dark = self.read_in_stack(cfg.preproc_cfg.input_dir, cfg.preproc_cfg.in_img_format) + data, white, dark = self.read_in_stack(cfg.preproc_cfg.input_dir, cfg.preproc_cfg.in_img_format, + cfg.preproc_cfg.input_dir_flat, cfg.preproc_cfg.input_dir_dark) print "Shape of raw data: {0}, dtype: {1}".format(data.shape, data.dtype) # These imports will raise appropriate exceptions in case of error @@ -756,20 +757,29 @@ class ReconstructionCommand(object): print " * Note: not applied N-dimensional median filter on reconstructed volume" - def read_in_stack(self, sample_path, img_format): + def read_in_stack(self, sample_path, img_format, flat_field_path=None, dark_field_path=None): """ Loads a stack, including sample, white and dark images. @param sample_path :: path to sample images + @param img_format :: image format to expect/use (as a filename extension) + @param flat_field_path :: (optional) path to open beam / white image(s). + Can be a file or directory + + @param dark_field_path :: (optional) path to dark field image(s). + Can be a file or directory + Returns :: stack of images as a 3-elements tuple: numpy array with sample images, white image, and dark image. """ # Note, not giving prefix. It will load all the files found. # Example prefixes are prefix = 'tomo_', prefix = 'LARMOR00', prefix = 'angle_agg' - sample, white, dark = tomoio.read_stack_of_images(sample_path, file_extension=img_format) + sample, white, dark = tomoio.read_stack_of_images(sample_path, flat_field_path=flat_field_path, + dark_field_path=dark_field_path, + file_extension=img_format) if not isinstance(sample, np.ndarray) or not sample.shape \ or not isinstance(sample.shape, tuple) or 3 != len(sample.shape):