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"); } }
/** 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; }
/** * Get the viewable peaks. Essentially copied from the slice viewer. * @returns A vector indicating which of the peaks are viewable. */ std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const { // Need to apply a transform. // Don't bother to find peaks in the region if there are no peaks to find. Mantid::API::ITableWorkspace_sptr outTable; if (this->m_peaksWorkspace->getNumberPeaks() >= 1) { double effectiveRadius = 1e-2; std::string viewable = m_viewableRegion->toExtentsAsString(); Mantid::API::IPeaksWorkspace_sptr peaksWS = m_peaksWorkspace; Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmManager::Instance().create("PeaksInRegion"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("InputWorkspace", peaksWS); alg->setProperty("OutputWorkspace", peaksWS->name() + "_peaks_in_region"); alg->setProperty("Extents", viewable); alg->setProperty("CheckPeakExtents", true); alg->setProperty("PeakRadius", effectiveRadius); alg->setPropertyValue("CoordinateFrame", m_frame); alg->execute(); outTable = alg->getProperty("OutputWorkspace"); std::vector<bool> viewablePeaks(outTable->rowCount()); for (size_t i = 0; i < outTable->rowCount(); ++i) { viewablePeaks[i] = outTable->cell<Mantid::API::Boolean>(i, 1); } m_viewablePeaks = viewablePeaks; } else { // No peaks will be viewable m_viewablePeaks = std::vector<bool>(); } return m_viewablePeaks; }
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(); }
/** * 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(); }
std::vector<size_t> ConcretePeaksPresenter::findVisiblePeakIndexes(const PeakBoundingBox &box) { std::vector<size_t> indexes; // Don't bother to find peaks in the region if there are no peaks to find. if (this->m_peaksWS->getNumberPeaks() >= 1) { double radius = m_viewPeaks ->getRadius(); // Effective radius of each peak representation. Mantid::API::IPeaksWorkspace_sptr peaksWS = boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>( this->m_peaksWS); PeakBoundingBox transformedViewableRegion = box.makeSliceBox(radius); transformedViewableRegion.transformBox(m_transform); Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("PeaksInRegion"); alg->setChild(true); alg->setRethrows(true); alg->initialize(); alg->setProperty("InputWorkspace", peaksWS); alg->setProperty("OutputWorkspace", peaksWS->name() + "_peaks_in_region"); alg->setProperty("Extents", transformedViewableRegion.toExtents()); alg->setProperty("CheckPeakExtents", false); // consider all peaks as points alg->setProperty("PeakRadius", radius); alg->setPropertyValue("CoordinateFrame", m_transform->getFriendlyName()); alg->execute(); ITableWorkspace_sptr outTable = alg->getProperty("OutputWorkspace"); for (size_t i = 0; i < outTable->rowCount(); ++i) { const bool insideRegion = outTable->cell<Boolean>(i, 1); if (insideRegion) { indexes.push_back(i); } } } return indexes; }
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; }
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"); } }
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(); }
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); }
/** * 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; }
/** * Fill m_uiForm.logBox with names of the log values read from one of the input files */ void PlotAsymmetryByLogValueDialog::fillLogBox(const QString&) { QString nexusFileName = m_uiForm.firstRunBox->text(); QFileInfo file(nexusFileName); if (!file.exists()) { return; } m_uiForm.logBox->clear(); Mantid::API::IAlgorithm_sptr alg = Mantid::API::AlgorithmFactory::Instance().create("LoadNexus",-1); alg->initialize(); try { alg->setPropertyValue("Filename",nexusFileName.toStdString()); alg->setPropertyValue("OutputWorkspace","PlotAsymmetryByLogValueDialog_tmp"); alg->setPropertyValue("SpectrumMin","0"); alg->setPropertyValue("SpectrumMax","0"); alg->execute(); if (alg->isExecuted()) { std::string wsName = alg->getPropertyValue("OutputWorkspace"); Mantid::API::Workspace_sptr ws = Mantid::API::AnalysisDataService::Instance().retrieve(wsName); if ( !ws ) { return; } Mantid::API::MatrixWorkspace_sptr mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws); Mantid::API::WorkspaceGroup_sptr gws = boost::dynamic_pointer_cast<Mantid::API::WorkspaceGroup>(ws); if (gws) { if (gws->getNumberOfEntries() < 2) return; mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>( Mantid::API::AnalysisDataService::Instance().retrieve(gws->getNames()[1]) ); } const std::vector< Mantid::Kernel::Property* >& props = mws->run().getLogData(); if (gws) { std::vector<std::string> wsNames = gws->getNames(); for(std::vector<std::string>::iterator it=wsNames.begin();it!=wsNames.end();++it) { Mantid::API::AnalysisDataService::Instance().remove(*it); } } else { Mantid::API::AnalysisDataService::Instance().remove("PlotAsymmetryByLogValueDialog_tmp"); } for(size_t i=0;i<props.size();i++) { m_uiForm.logBox->addItem(QString::fromStdString(props[i]->name())); } // Display the appropriate value QString displayed(""); if( !isForScript() ) { displayed = MantidQt::API::AlgorithmInputHistory::Instance().previousInput("PlotAsymmetryByLogValue", "LogValue"); } if( !displayed.isEmpty() ) { int index = m_uiForm.logBox->findText(displayed); if( index >= 0 ) { m_uiForm.logBox->setCurrentIndex(index); } } } } catch(std::exception& ) { } }