/** * This function: 1. loads the instrument and gets the value of deltaE-mode parameter * 2. Based on this value, makes the necessary changes to the form setup (direct or indirect). * @param name :: name of the instrument from the QComboBox */ void IndirectDataReduction::instrumentSelectChanged(const QString& name) { QString defFile = (Mantid::API::ExperimentInfo::getInstrumentFilename(name.toStdString())).c_str(); if((defFile == "") || !m_uiForm.cbInst->isVisible()) { g_log.error("Instument loading failed!"); m_uiForm.cbInst->setEnabled(true); m_uiForm.pbRun->setEnabled(true); return; } QString outWS = "__empty_" + m_uiForm.cbInst->currentText(); m_curInterfaceSetup = name; //Load the empty instrument into the workspace __empty_[name] //This used to be done in Python Mantid::API::IAlgorithm_sptr instLoader = Mantid::API::AlgorithmManager::Instance().create("LoadEmptyInstrument", -1); instLoader->initialize(); instLoader->setProperty("Filename", defFile.toStdString()); instLoader->setProperty("OutputWorkspace", outWS.toStdString()); //Ensure no other algorithm is running m_algRunner->cancelRunningAlgorithm(); m_algRunner->startAlgorithm(instLoader); }
/** Run any algorithm with a variable number of parameters * * @param algorithmName * @param count :: number of arguments given. * @return the algorithm created */ IAlgorithm_sptr FrameworkManagerImpl::exec(const std::string& algorithmName, int count, ...) { // Create the algorithm Mantid::API::IAlgorithm_sptr alg; alg = Mantid::API::AlgorithmManager::Instance().createUnmanaged(algorithmName, -1); alg->initialize(); if (!alg->isInitialized()) throw std::runtime_error(algorithmName + " was not initialized."); if (count % 2 == 1) { throw std::runtime_error("Must have an even number of parameter/value string arguments"); } va_list Params; va_start(Params, count); for(int i = 0; i < count; i += 2 ) { std::string paramName = va_arg(Params, const char *); std::string paramValue = va_arg(Params, const char *); alg->setPropertyValue(paramName, paramValue); } va_end(Params); alg->execute(); return alg; }
void WorkspacePresenter::ungroupWorkspaces() { auto view = lockView(); auto selected = view->getSelectedWorkspaceNames(); if (selected.size() == 0) { view->showCriticalUserMessage("Error Ungrouping Workspaces", "Select a group workspace to Ungroup."); return; } try { // workspace name auto wsname = selected[0]; std::string algName("UnGroupWorkspace"); Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create(algName, -1); alg->initialize(); alg->setProperty("InputWorkspace", wsname); // execute the algorithm bool bStatus = alg->execute(); if (!bStatus) { view->showCriticalUserMessage("MantidPlot - Algorithm error", " Error in UnGroupWorkspace algorithm"); } } catch (...) { view->showCriticalUserMessage("MantidPlot - Algorithm error", " Error in UnGroupWorkspace algorithm"); } }
/** This method executes the ListInstruments algorithm * and fills the instrument box with instrument lists returned by ICat API * @return shared pointer to workspace which contains instrument names */ std::vector<std::string> ICatUtils::executeListInstruments() { QString algName("CatalogListInstruments"); const int version=-1; Mantid::API::IAlgorithm_sptr alg; try { alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version); } catch(...) { throw std::runtime_error("Error when Populating the instrument list box"); } Poco::ActiveResult<bool> result(alg->executeAsync()); while( !result.available() ) { QCoreApplication::processEvents(); } if(!alg->isExecuted()) { //if the algorithm failed check the session id passed is valid if(!isSessionValid(alg)) { //at this point session is invalid, popup loginbox to login if(login()) { //now populate instrument box std::vector<std::string> instruments =executeListInstruments(); return instruments; } else { throw std::runtime_error("Please Login to the information catalog using the login menu provided to do the investigation search."); } } else { return std::vector<std::string>(); } } std::vector<std::string>instrlist; try { instrlist= alg->getProperty("InstrumentList"); } catch (Mantid::Kernel::Exception::NotFoundError&) { throw; } return instrlist; }
/** Add a new algorithm to the list monitored * * @param alg :: algorithm to monitor. */ void AlgorithmMonitor::add(Mantid::API::IAlgorithm_sptr alg) { lock(); alg->addObserver(m_finishedObserver); alg->addObserver(m_errorObserver); alg->addObserver(m_progressObserver); m_algorithms.push_back(alg->getAlgorithmID()); ++m_nRunning; emit algorithmStarted(alg->getAlgorithmID()); emit countChanged(); unlock(); }
/// execute getdatafIles algorithm ITableWorkspace_sptr ICatInvestigation::executeGetdataFiles() { QString algName("CatalogGetDataFiles"); const int version=1; Mantid::API::ITableWorkspace_sptr ws_sptr; Mantid::API::IAlgorithm_sptr alg; try { alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version); } catch(...) { throw std::runtime_error("Error when loading the data files associated to the selected investigation "); } try { alg->setProperty("InvestigationId",m_invstId); alg->setProperty("FilterLogFiles",isDataFilesChecked()); alg->setPropertyValue("OutputWorkspace","datafiles"); } catch(std::invalid_argument& e) { emit error(e.what()); return ws_sptr; } catch (Mantid::Kernel::Exception::NotFoundError& e) { emit error(e.what()); return ws_sptr; } try { Poco::ActiveResult<bool> result(alg->executeAsync()); while( !result.available() ) { QCoreApplication::processEvents(); } } catch(...) { return ws_sptr; } if(AnalysisDataService::Instance().doesExist("datafiles")) { ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace> (AnalysisDataService::Instance().retrieve("datafiles")); } return ws_sptr; }
/** * Execute the given algorithm asynchronously. * @param algorithm :: The algorithm to execute. */ void CatalogHelper::executeAsynchronously( const Mantid::API::IAlgorithm_sptr &algorithm) { Poco::ActiveResult<bool> result(algorithm->executeAsync()); while (!result.available()) { QCoreApplication::processEvents(); } }
/** Upadates the non-default algorithm properties in the history. @param alg :: Pointer to the algorthm */ void InputHistoryImpl::updateAlgorithm(Mantid::API::IAlgorithm_sptr alg) { const std::vector< Property* >& props = alg->getProperties(); QList< PropertyData > prop_hist_list; for(std::vector< Property* >::const_iterator prop=props.begin();prop!=props.end();++prop) if (!(*prop)->isDefault()) { PropertyData prop_hist(QString::fromStdString((*prop)->name()),QString::fromStdString((*prop)->value())); prop_hist_list.push_back(prop_hist); } else { PropertyData prop_hist(QString::fromStdString((*prop)->name()),""); prop_hist_list.push_back(prop_hist); } m_history[QString::fromStdString(alg->name())] = prop_hist_list; }
void ConvFit::setupFit(Mantid::API::IAlgorithm_sptr fitAlgorithm) { if (boolSettingValue("UseTempCorrection")) m_convFittingModel->setTemperature(doubleSettingValue("TempCorrection")); else m_convFittingModel->setTemperature(boost::none); fitAlgorithm->setProperty("ExtractMembers", boolSettingValue("ExtractMembers")); IndirectFitAnalysisTab::setupFit(fitAlgorithm); }
/** * Create a list of file extensions from the given algorithm * @param algName :: The name of the algorithm * @param propName :: The name of the property * @returns A list of file extensions */ QStringList MWRunFiles::getFileExtensionsFromAlgorithm(const QString &algName, const QString &propName) { Mantid::API::IAlgorithm_sptr algorithm = Mantid::API::AlgorithmManager::Instance().createUnmanaged( algName.toStdString()); QStringList fileExts; if (!algorithm) return fileExts; algorithm->initialize(); Property *prop = algorithm->getProperty(propName.toStdString()); FileProperty *fileProp = dynamic_cast<FileProperty *>(prop); MultipleFileProperty *multiFileProp = dynamic_cast<MultipleFileProperty *>(prop); std::vector<std::string> allowed; QString preferredExt; if (fileProp) { allowed = fileProp->allowedValues(); preferredExt = QString::fromStdString(fileProp->getDefaultExt()); } else if (multiFileProp) { allowed = multiFileProp->allowedValues(); preferredExt = QString::fromStdString(multiFileProp->getDefaultExt()); } else { return fileExts; } std::vector<std::string>::const_iterator iend = allowed.end(); int index(0); for (std::vector<std::string>::const_iterator it = allowed.begin(); it != iend; ++it) { if (!it->empty()) { QString ext = QString::fromStdString(*it); fileExts.append(ext); if (ext == preferredExt) { fileExts.move(index, 0); } ++index; } } return fileExts; }
/** * Set the "search" properties to their related input fields. * @param catalogAlgorithm :: Algorithm to set the search properties for. * @param userInputFields :: The search properties to set against the algorithm. */ void CatalogHelper::setSearchProperties(const Mantid::API::IAlgorithm_sptr &catalogAlgorithm, const std::map<std::string, std::string> &userInputFields) { // This will be the workspace where the content of the search result is output to. catalogAlgorithm->setProperty("OutputWorkspace", "__searchResults"); // Iterate over the provided map of user input fields. For each field that isn't empty (e.g. a value was input by the user) // then we will set the algorithm property with the key and value of that specific value. for (auto it = userInputFields.begin(); it != userInputFields.end(); it++) { std::string value = it->second; // If the user has input any search terms. if (!value.empty()) { // Set the property that the search algorithm uses to: (key => FieldName, value => FieldValue) (e.g., (Keywords, bob)) catalogAlgorithm->setProperty(it->first, value); } } }
/** * Plus two workspaces together, "in place". * * @param ws1 :: The first workspace. * @param ws2 :: The second workspace. * * @returns a pointer to the result (the first workspace). */ API::Workspace_sptr Load::plusWs(Workspace_sptr ws1, Workspace_sptr ws2) { WorkspaceGroup_sptr group1 = boost::dynamic_pointer_cast<WorkspaceGroup>(ws1); WorkspaceGroup_sptr group2 = boost::dynamic_pointer_cast<WorkspaceGroup>(ws2); if (group1 && group2) { // If we're dealing with groups, then the child workspaces must be added // separately - setProperty // wont work otherwise. std::vector<std::string> group1ChildWsNames = group1->getNames(); std::vector<std::string> group2ChildWsNames = group2->getNames(); if (group1ChildWsNames.size() != group2ChildWsNames.size()) throw std::runtime_error("Unable to add group workspaces with different " "number of child workspaces."); auto group1ChildWsName = group1ChildWsNames.begin(); auto group2ChildWsName = group2ChildWsNames.begin(); for (; group1ChildWsName != group1ChildWsNames.end(); ++group1ChildWsName, ++group2ChildWsName) { Workspace_sptr group1ChildWs = group1->getItem(*group1ChildWsName); Workspace_sptr group2ChildWs = group2->getItem(*group2ChildWsName); Mantid::API::IAlgorithm_sptr plusAlg = createChildAlgorithm("Plus", 1); plusAlg->setProperty<Workspace_sptr>("LHSWorkspace", group1ChildWs); plusAlg->setProperty<Workspace_sptr>("RHSWorkspace", group2ChildWs); plusAlg->setProperty<Workspace_sptr>("OutputWorkspace", group1ChildWs); plusAlg->executeAsChildAlg(); } } else if (!group1 && !group2) { Mantid::API::IAlgorithm_sptr plusAlg = createChildAlgorithm("Plus", 1); plusAlg->setProperty<Workspace_sptr>("LHSWorkspace", ws1); plusAlg->setProperty<Workspace_sptr>("RHSWorkspace", ws2); plusAlg->setProperty<Workspace_sptr>("OutputWorkspace", ws1); plusAlg->executeAsChildAlg(); } else { throw std::runtime_error( "Unable to add a group workspace to a non-group workspace"); } return ws1; }
/** * Set the algorithm pointer * @param alg :: A pointer to the algorithm */ void AlgorithmDialog::setAlgorithm(Mantid::API::IAlgorithm_sptr alg) { m_algorithm = alg; m_algName = QString::fromStdString(alg->name()); m_algProperties.clear(); m_tied_properties.clear(); std::vector<Mantid::Kernel::Property *>::const_iterator iend = alg->getProperties().end(); for (std::vector<Mantid::Kernel::Property *>::const_iterator itr = alg->getProperties().begin(); itr != iend; ++itr) { Mantid::Kernel::Property *p = *itr; if (dynamic_cast<Mantid::API::IWorkspaceProperty *>(p) || p->direction() != Mantid::Kernel::Direction::Output) { m_algProperties.append(QString::fromStdString(p->name())); } } m_validators.clear(); m_noValidation.clear(); }
/** @param inname Name of workspace containing peaks @param params optimized cell parameters @param out residuals from optimization */ void OptimizeLatticeForCellType::optLattice(std::string inname, std::vector<double> ¶ms, double *out) { PeaksWorkspace_sptr ws = boost::dynamic_pointer_cast<PeaksWorkspace>( AnalysisDataService::Instance().retrieve(inname)); const std::vector<Peak> &peaks = ws->getPeaks(); size_t n_peaks = ws->getNumberPeaks(); std::vector<V3D> q_vector; std::vector<V3D> hkl_vector; for (size_t i = 0; i < params.size(); i++) params[i] = std::abs(params[i]); for (size_t i = 0; i < n_peaks; i++) { q_vector.push_back(peaks[i].getQSampleFrame()); hkl_vector.push_back(peaks[i].getHKL()); } Mantid::API::IAlgorithm_sptr alg = createChildAlgorithm("CalculateUMatrix"); alg->setPropertyValue("PeaksWorkspace", inname); alg->setProperty("a", params[0]); alg->setProperty("b", params[1]); alg->setProperty("c", params[2]); alg->setProperty("alpha", params[3]); alg->setProperty("beta", params[4]); alg->setProperty("gamma", params[5]); alg->executeAsChildAlg(); ws = alg->getProperty("PeaksWorkspace"); OrientedLattice latt = ws->mutableSample().getOrientedLattice(); DblMatrix UB = latt.getUB(); DblMatrix A = aMatrix(params); DblMatrix Bc = A; Bc.Invert(); DblMatrix U1_B1 = UB * A; OrientedLattice o_lattice; o_lattice.setUB(U1_B1); DblMatrix U1 = o_lattice.getU(); DblMatrix U1_Bc = U1 * Bc; for (size_t i = 0; i < hkl_vector.size(); i++) { V3D error = U1_Bc * hkl_vector[i] - q_vector[i] / (2.0 * M_PI); out[i] = error.norm2(); } return; }
bool ICatUtils::isSessionValid(const Mantid::API::IAlgorithm_sptr& alg) { try { return alg->getProperty("IsValid"); } catch (Mantid::Kernel::Exception::NotFoundError&) { throw; } }
/** * Loads a file into a *hidden* workspace. * * @param fileName :: file name to load. * @param wsName :: workspace name, which will be prefixed by a "__" * * @returns a pointer to the loaded workspace */ API::Workspace_sptr Load::loadFileToWs(const std::string &fileName, const std::string &wsName) { Mantid::API::IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 1); // Get the list properties for the concrete loader load algorithm const std::vector<Kernel::Property *> &props = getProperties(); // Loop through and set the properties on the Child Algorithm for (auto prop : props) { const std::string &propName = prop->name(); if (this->existsProperty(propName)) { if (propName == "Filename") { loadAlg->setPropertyValue("Filename", fileName); } else if (propName == "OutputWorkspace") { loadAlg->setPropertyValue("OutputWorkspace", wsName); } else { loadAlg->setPropertyValue(propName, getPropertyValue(propName)); } } } loadAlg->executeAsChildAlg(); Workspace_sptr ws = loadAlg->getProperty("OutputWorkspace"); // ws->setName(wsName); AnalysisDataService::Instance().addOrReplace(wsName, ws); return ws; }
/** * Runs an algorithm async * * @param algorithm :: The algorithm to be run */ void IndirectTab::runAlgorithm(const Mantid::API::IAlgorithm_sptr algorithm) { algorithm->setRethrows(true); // There should never really be unexecuted algorithms in the queue, but it is // worth warning in case of possible weirdness size_t batchQueueLength = m_batchAlgoRunner->queueLength(); if (batchQueueLength > 0) g_log.warning() << "Batch queue already contains " << batchQueueLength << " algorithms!\n"; m_batchAlgoRunner->addAlgorithm(algorithm); m_batchAlgoRunner->executeBatchAsync(); }
bool ICatUtils::login() { QString algName("CatalogLogin"); const int version =-1; Mantid::API::IAlgorithm_sptr alg; try { alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version); } catch(...) { throw std::runtime_error("Error when Populating the instrument list box"); } if(!m_applicationWindow) {return false;} MantidQt::API::InterfaceManager interfaceManager; MantidQt::API::AlgorithmDialog *dlg = interfaceManager.createDialog(alg.get(), m_applicationWindow); if(!dlg) return false; if(dlg->exec()==QDialog::Accepted) { delete dlg; Poco::ActiveResult<bool> result(alg->executeAsync()); while( !result.available() ) { QCoreApplication::processEvents(); } if(!alg->isExecuted()) { return false; } return true; } else { return false; } }
/** * Sorts the peak workspace by a specified column name in ascending or * descending order. * @param byColumnName The column by which the workspace is to be sorted. * @param ascending If the workspace is to be sorted in a ascending or * descending manner. */ void ConcretePeaksPresenterVsi::sortPeaksWorkspace( const std::string &byColumnName, const bool ascending) { Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>( this->m_peaksWorkspace); // Sort the Peaks in-place. Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("SortPeaksWorkspace"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("InputWorkspace", peaksWS); alg->setPropertyValue("OutputWorkspace", "SortedPeaksWorkspace"); alg->setProperty("OutputWorkspace", peaksWS); alg->setProperty("SortAscending", ascending); alg->setPropertyValue("ColumnNameToSortBy", byColumnName); alg->execute(); }
void WorkspacePresenter::groupWorkspaces() { auto view = lockView(); auto selected = view->getSelectedWorkspaceNames(); std::string groupName("NewGroup"); // get selected workspaces if (selected.size() < 2) { view->showCriticalUserMessage("Cannot Group Workspaces", "Select at least two workspaces to group "); return; } if (m_adapter->doesWorkspaceExist(groupName)) { if (!view->askUserYesNo("", "Workspace " + groupName + " already exists. Do you want to replace it?")) return; } try { std::string algName("GroupWorkspaces"); Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create(algName, -1); alg->initialize(); alg->setProperty("InputWorkspaces", selected); alg->setPropertyValue("OutputWorkspace", groupName); // execute the algorithm bool bStatus = alg->execute(); if (!bStatus) { view->showCriticalUserMessage("MantidPlot - Algorithm error", " Error in GroupWorkspaces algorithm"); } } catch (...) { view->showCriticalUserMessage("MantidPlot - Algorithm error", " Error in GroupWorkspaces algorithm"); } }
/** * Create a list of files from the given algorithm property. */ void FindFilesThread::getFilesFromAlgorithm() { Mantid::API::IAlgorithm_sptr algorithm = Mantid::API::AlgorithmManager::Instance().createUnmanaged( m_algorithm.toStdString()); if (!algorithm) throw std::invalid_argument("Cannot create algorithm " + m_algorithm.toStdString() + "."); algorithm->initialize(); const std::string propName = m_property.toStdString(); algorithm->setProperty(propName, m_text); Property *prop = algorithm->getProperty(propName); m_valueForProperty = QString::fromStdString(prop->value()); FileProperty *fileProp = dynamic_cast<FileProperty *>(prop); MultipleFileProperty *multiFileProp = dynamic_cast<MultipleFileProperty *>(prop); if (fileProp) { m_filenames.push_back(fileProp->value()); } else if (multiFileProp) { // This flattens any summed files to a set of single files so that you lose // the information about // what was summed std::vector<std::vector<std::string>> filenames = algorithm->getProperty(propName); std::vector<std::string> flattenedNames = VectorHelper::flattenVector(filenames); for (auto filename = flattenedNames.begin(); filename != flattenedNames.end(); ++filename) { m_filenames.push_back(*filename); } } }
/** * Execute the underlying algorithm */ void AlgorithmDialog::executeAlgorithmAsync() { Mantid::API::IAlgorithm_sptr algToExec = m_algorithm; // Clear any previous trackers so we know what state we are in this->stopObserving(algToExec); try { // Add any custom AlgorithmObservers to the algorithm for (auto it = m_observers.begin(); it != m_observers.end(); ++it) { (*it)->observeAll(algToExec); } // Only need to observe finish events if we are staying open if (m_keepOpenCheckBox && m_keepOpenCheckBox->isChecked()) { this->observeFinish(algToExec); this->observeError(algToExec); m_statusTracked = true; // Disable close button for a short period. If it is clicked to soon then // Mantid crashes - https://github.com/mantidproject/mantid/issues/13836 if (m_exitButton) { m_exitButton->setEnabled(false); m_btnTimer.setInterval(1000); connect(&m_btnTimer, SIGNAL(timeout()), this, SLOT(enableExitButton())); } else { m_statusTracked = false; } } algToExec->executeAsync(); m_btnTimer.start(); if (m_okButton) { m_okButton->setEnabled(false); } } catch (Poco::NoThreadAvailableException &) { g_log.error() << "No thread was available to run the " << algToExec->name() << " algorithm in the background.\n"; } }
/** Make a (optionally) file backed MDEventWorkspace with nEvents fake data points * the points are randomly distributed within the box (nEvents>0) or homoheneously and regularly spread through the box (nEvents<0) * * @param wsName :: name of the workspace in ADS * @param fileBacked :: true for file-backed * @param numEvents :: number of events in the target workspace distributed randomly if numEvents>0 or regularly & homogeneously if numEvents<0 * @return MDEW sptr */ MDEventWorkspace3Lean::sptr makeFileBackedMDEW(std::string wsName, bool fileBacked,long numEvents) { // ---------- Make a file-backed MDEventWorkspace ----------------------- std::string snEvents = boost::lexical_cast<std::string>(numEvents); MDEventWorkspace3Lean::sptr ws1 = MDEventsTestHelper::makeMDEW<3>(10, 0.0, 10.0, 0); ws1->getBoxController()->setSplitThreshold(100); Mantid::API::AnalysisDataService::Instance().addOrReplace(wsName, boost::dynamic_pointer_cast< Mantid::API::IMDEventWorkspace>(ws1)); FrameworkManager::Instance().exec("FakeMDEventData", 6, "InputWorkspace", wsName.c_str(), "UniformParams", snEvents.c_str(), "RandomizeSignal", "1"); if (fileBacked) { std::string filename = wsName + ".nxs"; Mantid::API::IAlgorithm_sptr saver = FrameworkManager::Instance().exec("SaveMD", 4, "InputWorkspace", wsName.c_str(), "Filename", filename.c_str()); FrameworkManager::Instance().exec("LoadMD", 8, "OutputWorkspace", wsName.c_str(), "Filename", saver->getPropertyValue("Filename").c_str(), "FileBackEnd", "1", "Memory", "0"); } return boost::dynamic_pointer_cast<MDEventWorkspace3Lean>( Mantid::API::AnalysisDataService::Instance().retrieve(wsName) ); }
void ConcretePeaksPresenter::sortPeaksWorkspace(const std::string &byColumnName, const bool ascending) { Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(this->m_peaksWS); // Sort the Peaks in-place. Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("SortPeaksWorkspace"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("InputWorkspace", peaksWS); alg->setPropertyValue("OutputWorkspace", "SortedPeaksWorkspace"); alg->setProperty("OutputWorkspace", peaksWS); alg->setProperty("SortAscending", ascending); alg->setPropertyValue("ColumnNameToSortBy", byColumnName); alg->execute(); // Reproduce the views. this->produceViews(); // Give the new views the current slice point. m_viewPeaks->setSlicePoint(this->m_slicePoint.slicePoint(), m_viewablePeaks); }
Mantid::API::MatrixWorkspace_sptr SANSPlotSpecial::runIQTransform() { // Run the IQTransform algorithm for the current settings on the GUI Mantid::API::IAlgorithm_sptr iqt = Mantid::API::AlgorithmManager::Instance().create("IQTransform"); iqt->initialize(); try { iqt->setPropertyValue("InputWorkspace", m_uiForm.wsInput->currentText().toStdString()); } catch (std::invalid_argument &) { m_uiForm.lbPlotOptionsError->setText( "Selected input workspace is not appropriate for the IQTransform " "algorithm. Please refer to the documentation for guidelines."); return Mantid::API::MatrixWorkspace_sptr(); } iqt->setPropertyValue("OutputWorkspace", "__sans_isis_display_iqt"); iqt->setPropertyValue("TransformType", m_uiForm.cbPlotType->currentText().toStdString()); if (m_uiForm.cbBackground->currentText() == "Value") { iqt->setProperty<double>("BackgroundValue", m_uiForm.dsBackground->value()); } else { iqt->setPropertyValue("BackgroundWorkspace", m_uiForm.wsBackground->currentText().toStdString()); } if (m_uiForm.cbPlotType->currentText() == "General") { std::vector<double> constants = m_transforms["General"]->functionConstants(); iqt->setProperty("GeneralFunctionConstants", constants); } iqt->execute(); Mantid::API::MatrixWorkspace_sptr result = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>( Mantid::API::AnalysisDataService::Instance().retrieve( "__sans_isis_display_iqt")); return result; }
bool ConcretePeaksPresenter::deletePeaksIn(PeakBoundingBox box) { Left left(box.left()); Right right(box.right()); Bottom bottom(box.bottom()); Top top(box.top()); SlicePoint slicePoint(box.slicePoint()); if (slicePoint() < 0) { // indicates that it should not be used. slicePoint = SlicePoint(m_slicePoint.slicePoint()); } PeakBoundingBox accurateBox( left, right, top, bottom, slicePoint /*Use the current slice position, previously unknown.*/); // Tranform box from plot coordinates into orderd HKL, Qx,Qy,Qz etc, then find // the visible peaks. std::vector<size_t> deletionIndexList = findVisiblePeakIndexes(accurateBox); // If we have things to remove, do that in one-step. if (!deletionIndexList.empty()) { Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>( this->m_peaksWS); // Sort the Peaks in-place. Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("DeleteTableRows"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("TableWorkspace", peaksWS); alg->setProperty("Rows", deletionIndexList); alg->execute(); // Reproduce the views. Proxy representations recreated for all peaks. this->produceViews(); // Refind visible peaks and Set the proxy representations to be visible or // not. doFindPeaksInRegion(); // Upstream controls need to be regenerated. this->informOwnerUpdate(); } return !deletionIndexList.empty(); }
bool ConcretePeaksPresenter::addPeakAt(double plotCoordsPointX, double plotCoordsPointY) { V3D plotCoordsPoint(plotCoordsPointX, plotCoordsPointY, m_slicePoint.slicePoint()); V3D hkl = m_transform->transformBack(plotCoordsPoint); Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(this->m_peaksWS); Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("AddPeakHKL"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("Workspace", peaksWS); alg->setProperty("HKL", std::vector<double>(hkl)); // Execute the algorithm try { alg->execute(); } catch (...) { g_log.warning("ConcretePeaksPresenter: Could not add the peak. Make sure " "that it is added within a valid workspace region"); } // Reproduce the views. Proxy representations recreated for all peaks. this->produceViews(); // Refind visible peaks and Set the proxy representations to be visible or // not. doFindPeaksInRegion(); // Upstream controls need to be regenerated. this->informOwnerUpdate(); return alg->isExecuted(); }
/** * Groups the workspace according to grouping provided. * * @param ws :: Workspace to group * @param g :: The grouping information * @return Sptr to created grouped workspace */ MatrixWorkspace_sptr groupWorkspace(MatrixWorkspace_const_sptr ws, const Grouping& g) { // As I couldn't specify multiple groups for GroupDetectors, I am going down quite a complicated // route - for every group distinct grouped workspace is created using GroupDetectors. These // workspaces are then merged into the output workspace. // Create output workspace MatrixWorkspace_sptr outWs = WorkspaceFactory::Instance().create(ws, g.groups.size(), ws->readX(0).size(), ws->blocksize()); for(size_t gi = 0; gi < g.groups.size(); gi++) { Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("GroupDetectors"); alg->setChild(true); // So Output workspace is not added to the ADS alg->initialize(); alg->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(ws)); alg->setPropertyValue("SpectraList", g.groups[gi]); alg->setPropertyValue("OutputWorkspace", "grouped"); // Is not actually used, just to make validators happy alg->execute(); MatrixWorkspace_sptr grouped = alg->getProperty("OutputWorkspace"); // Copy the spectrum *(outWs->getSpectrum(gi)) = *(grouped->getSpectrum(0)); // Update spectrum number outWs->getSpectrum(gi)->setSpectrumNo(static_cast<specid_t>(gi)); // Copy to the output workspace outWs->dataY(gi) = grouped->readY(0); outWs->dataX(gi) = grouped->readX(0); outWs->dataE(gi) = grouped->readE(0); } return outWs; }
/** * Move the user selected spectra in the input workspace into groups in the output workspace * @param inputWS :: user selected input workspace for the algorithm * @param outputWS :: user selected output workspace for the algorithm * @param prog4Copy :: the amount of algorithm progress to attribute to moving a single spectra * @return number of new grouped spectra */ size_t GroupDetectors2::formGroupsEvent( DataObjects::EventWorkspace_const_sptr inputWS, DataObjects::EventWorkspace_sptr outputWS, const double prog4Copy) { // get "Behaviour" string const std::string behaviour = getProperty("Behaviour"); int bhv = 0; if ( behaviour == "Average" ) bhv = 1; API::MatrixWorkspace_sptr beh = API::WorkspaceFactory::Instance().create( "Workspace2D", static_cast<int>(m_GroupSpecInds.size()), 1, 1); g_log.debug() << name() << ": Preparing to group spectra into " << m_GroupSpecInds.size() << " groups\n"; // where we are copying spectra to, we start copying to the start of the output workspace size_t outIndex = 0; // Only used for averaging behaviour. We may have a 1:1 map where a Divide would be waste as it would be just dividing by 1 bool requireDivide(false); for ( storage_map::const_iterator it = m_GroupSpecInds.begin(); it != m_GroupSpecInds.end() ; ++it ) { // This is the grouped spectrum EventList & outEL = outputWS->getEventList(outIndex); // The spectrum number of the group is the key outEL.setSpectrumNo(it->first); // Start fresh with no detector IDs outEL.clearDetectorIDs(); // the Y values and errors from spectra being grouped are combined in the output spectrum // Keep track of number of detectors required for masking size_t nonMaskedSpectra(0); beh->dataX(outIndex)[0] = 0.0; beh->dataE(outIndex)[0] = 0.0; for( std::vector<size_t>::const_iterator wsIter = it->second.begin(); wsIter != it->second.end(); ++wsIter) { const size_t originalWI = *wsIter; const EventList & fromEL=inputWS->getEventList(originalWI); //Add the event lists with the operator outEL += fromEL; // detectors to add to the output spectrum outEL.addDetectorIDs(fromEL.getDetectorIDs() ); try { Geometry::IDetector_const_sptr det = inputWS->getDetector(originalWI); if( !det->isMasked() ) ++nonMaskedSpectra; } catch(Exception::NotFoundError&) { // If a detector cannot be found, it cannot be masked ++nonMaskedSpectra; } } if( nonMaskedSpectra == 0 ) ++nonMaskedSpectra; // Avoid possible divide by zero if(!requireDivide) requireDivide = (nonMaskedSpectra > 1); beh->dataY(outIndex)[0] = static_cast<double>(nonMaskedSpectra); // make regular progress reports and check for cancelling the algorithm if ( outIndex % INTERVAL == 0 ) { m_FracCompl += INTERVAL*prog4Copy; if ( m_FracCompl > 1.0 ) m_FracCompl = 1.0; progress(m_FracCompl); interruption_point(); } outIndex ++; } // Refresh the spectraDetectorMap outputWS->doneAddingEventLists(); if ( bhv == 1 && requireDivide ) { g_log.debug() << "Running Divide algorithm to perform averaging.\n"; Mantid::API::IAlgorithm_sptr divide = createChildAlgorithm("Divide"); divide->initialize(); divide->setProperty<API::MatrixWorkspace_sptr>("LHSWorkspace", outputWS); divide->setProperty<API::MatrixWorkspace_sptr>("RHSWorkspace", beh); divide->setProperty<API::MatrixWorkspace_sptr>("OutputWorkspace", outputWS); divide->execute(); } g_log.debug() << name() << " created " << outIndex << " new grouped spectra\n"; return outIndex; }
/** * Move the user selected spectra in the input workspace into groups in the output workspace * @param inputWS :: user selected input workspace for the algorithm * @param outputWS :: user selected output workspace for the algorithm * @param prog4Copy :: the amount of algorithm progress to attribute to moving a single spectra * @return number of new grouped spectra */ size_t GroupDetectors2::formGroups( API::MatrixWorkspace_const_sptr inputWS, API::MatrixWorkspace_sptr outputWS, const double prog4Copy) { // get "Behaviour" string const std::string behaviour = getProperty("Behaviour"); int bhv = 0; if ( behaviour == "Average" ) bhv = 1; API::MatrixWorkspace_sptr beh = API::WorkspaceFactory::Instance().create( "Workspace2D", static_cast<int>(m_GroupSpecInds.size()), 1, 1); g_log.debug() << name() << ": Preparing to group spectra into " << m_GroupSpecInds.size() << " groups\n"; // where we are copying spectra to, we start copying to the start of the output workspace size_t outIndex = 0; // Only used for averaging behaviour. We may have a 1:1 map where a Divide would be waste as it would be just dividing by 1 bool requireDivide(false); for ( storage_map::const_iterator it = m_GroupSpecInds.begin(); it != m_GroupSpecInds.end() ; ++it ) { // This is the grouped spectrum ISpectrum * outSpec = outputWS->getSpectrum(outIndex); // The spectrum number of the group is the key outSpec->setSpectrumNo(it->first); // Start fresh with no detector IDs outSpec->clearDetectorIDs(); // Copy over X data from first spectrum, the bin boundaries for all spectra are assumed to be the same here outSpec->dataX() = inputWS->readX(0); // the Y values and errors from spectra being grouped are combined in the output spectrum // Keep track of number of detectors required for masking size_t nonMaskedSpectra(0); beh->dataX(outIndex)[0] = 0.0; beh->dataE(outIndex)[0] = 0.0; for( std::vector<size_t>::const_iterator wsIter = it->second.begin(); wsIter != it->second.end(); ++wsIter) { const size_t originalWI = *wsIter; // detectors to add to firstSpecNum const ISpectrum * fromSpectrum = inputWS->getSpectrum(originalWI); // Add up all the Y spectra and store the result in the first one // Need to keep the next 3 lines inside loop for now until ManagedWorkspace mru-list works properly MantidVec &firstY = outSpec->dataY(); MantidVec::iterator fYit; MantidVec::iterator fEit = outSpec->dataE().begin(); MantidVec::const_iterator Yit = fromSpectrum->dataY().begin(); MantidVec::const_iterator Eit = fromSpectrum->dataE().begin(); for (fYit = firstY.begin(); fYit != firstY.end(); ++fYit, ++fEit, ++Yit, ++Eit) { *fYit += *Yit; // Assume 'normal' (i.e. Gaussian) combination of errors *fEit = std::sqrt( (*fEit)*(*fEit) + (*Eit)*(*Eit) ); } // detectors to add to the output spectrum outSpec->addDetectorIDs(fromSpectrum->getDetectorIDs() ); try { Geometry::IDetector_const_sptr det = inputWS->getDetector(originalWI); if( !det->isMasked() ) ++nonMaskedSpectra; } catch(Exception::NotFoundError&) { // If a detector cannot be found, it cannot be masked ++nonMaskedSpectra; } } if( nonMaskedSpectra == 0 ) ++nonMaskedSpectra; // Avoid possible divide by zero if(!requireDivide) requireDivide = (nonMaskedSpectra > 1); beh->dataY(outIndex)[0] = static_cast<double>(nonMaskedSpectra); // make regular progress reports and check for cancelling the algorithm if ( outIndex % INTERVAL == 0 ) { m_FracCompl += INTERVAL*prog4Copy; if ( m_FracCompl > 1.0 ) m_FracCompl = 1.0; progress(m_FracCompl); interruption_point(); } outIndex ++; } // Refresh the spectraDetectorMap outputWS->generateSpectraMap(); if ( bhv == 1 && requireDivide ) { g_log.debug() << "Running Divide algorithm to perform averaging.\n"; Mantid::API::IAlgorithm_sptr divide = createChildAlgorithm("Divide"); divide->initialize(); divide->setProperty<API::MatrixWorkspace_sptr>("LHSWorkspace", outputWS); divide->setProperty<API::MatrixWorkspace_sptr>("RHSWorkspace", beh); divide->setProperty<API::MatrixWorkspace_sptr>("OutputWorkspace", outputWS); divide->execute(); } g_log.debug() << name() << " created " << outIndex << " new grouped spectra\n"; return outIndex; }