void StepScan::generateCurve( const QString & var ) { // Create a matrix workspace out of the variable that's asked for IAlgorithm_sptr alg = AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace"); alg->setLogging(false); // Don't log this algorithm alg->setPropertyValue("InputWorkspace", m_tableWSName); m_plotWSName = "__plot_" + m_tableWSName; alg->setPropertyValue("OutputWorkspace", m_plotWSName); alg->setPropertyValue("ColumnX", var.toStdString() ); alg->setPropertyValue("ColumnY", "Counts" ); alg->execute(); // Now create one for the normalisation, if required if ( m_uiForm.normalization->currentIndex() != 0 ) { IAlgorithm_sptr norm = AlgorithmManager::Instance().create("ConvertTableToMatrixWorkspace"); norm->setChild(true); norm->setLogging(false); // Don't log this algorithm norm->setPropertyValue("InputWorkspace", m_tableWSName); norm->setPropertyValue("OutputWorkspace", "dummyName"); norm->setPropertyValue("ColumnX", var.toStdString() ); // TODO: Protect against column being missing (e.g. if monitor not found in data) norm->setPropertyValue("ColumnY", m_uiForm.normalization->currentText().toStdString() ); norm->execute(); MatrixWorkspace_sptr top = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(m_plotWSName); MatrixWorkspace_sptr bottom = norm->getProperty("OutputWorkspace"); top /= bottom; } plotCurve(); }
void ApplyPaalmanPings::updateContainer() { const auto canName = m_uiForm.dsContainer->getCurrentDataName(); const auto canValid = m_uiForm.dsContainer->isValid(); const auto useCan = m_uiForm.ckUseCan->isChecked(); if (canValid && useCan) { auto shift = m_uiForm.spCanShift->value(); if (!m_uiForm.ckShiftCan->isChecked()) shift = 0.0; auto scale = m_uiForm.spCanScale->value(); if (!m_uiForm.ckScaleCan->isChecked()) scale = 1.0; IAlgorithm_sptr scaleXAlg = AlgorithmManager::Instance().create("ScaleX"); scaleXAlg->initialize(); scaleXAlg->setLogging(false); scaleXAlg->setProperty("InputWorkspace", canName.toStdString()); scaleXAlg->setProperty("OutputWorkspace", m_containerWorkspaceName); scaleXAlg->setProperty("Factor", shift); scaleXAlg->setProperty("Operation", "Add"); scaleXAlg->execute(); IAlgorithm_sptr scaleAlg = AlgorithmManager::Instance().create("Scale"); scaleAlg->initialize(); scaleAlg->setLogging(false); scaleAlg->setProperty("InputWorkspace", m_containerWorkspaceName); scaleAlg->setProperty("OutputWorkspace", m_containerWorkspaceName); scaleAlg->setProperty("Factor", scale); scaleAlg->setProperty("Operation", "Multiply"); scaleAlg->execute(); const auto sampleValid = m_uiForm.dsSample->isValid(); if (sampleValid) { IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("RebinToWorkspace"); rebin->initialize(); rebin->setLogging(false); rebin->setProperty("WorkspaceToRebin", m_containerWorkspaceName); rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName); rebin->setProperty("OutputWorkspace", m_containerWorkspaceName); rebin->execute(); } else { // Sample was not valid so do not rebin m_uiForm.ppPreview->removeSpectrum("Container"); return; } } else { // Can was not valid so do not replot m_uiForm.ppPreview->removeSpectrum("Container"); return; } plotPreview(m_uiForm.spPreviewSpec->value()); }
/** Rebins the distributions and sets error values. */ MatrixWorkspace_sptr VesuvioL1ThetaResolution::processDistribution(MatrixWorkspace_sptr ws, const double binWidth) { const size_t numHist = ws->getNumberHistograms(); double xMin(DBL_MAX); double xMax(DBL_MIN); for (size_t i = 0; i < numHist; i++) { auto &x = ws->x(i); xMin = std::min(xMin, x.front()); xMax = std::max(xMax, x.back()); } std::stringstream binParams; binParams << xMin << "," << binWidth << "," << xMax; IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("Rebin"); rebin->initialize(); rebin->setChild(true); rebin->setLogging(false); rebin->setProperty("InputWorkspace", ws); rebin->setProperty("OutputWorkspace", "__rebin"); rebin->setProperty("Params", binParams.str()); rebin->execute(); ws = rebin->getProperty("OutputWorkspace"); for (size_t i = 0; i < numHist; i++) { auto &y = ws->y(i); auto &e = ws->mutableE(i); std::transform(y.begin(), y.end(), e.begin(), [](double x) { return sqrt(x); }); } return ws; }
Workspace_sptr GenericDataProcessorAlgorithm<Base>::assemble(const std::string &partialWSName, const std::string &outputWSName) { #ifdef MPI_BUILD std::string threadOutput = partialWSName; Workspace_sptr partialWS = AnalysisDataService::Instance().retrieve(partialWSName); IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); gatherAlg->setProperty("PreserveEvents", true); gatherAlg->setPropertyValue("OutputWorkspace", outputWSName); gatherAlg->execute(); if (isMainThread()) threadOutput = outputWSName; #else UNUSED_ARG(outputWSName) const std::string &threadOutput = partialWSName; #endif Workspace_sptr outputWS = AnalysisDataService::Instance().retrieve(threadOutput); return outputWS; }
/** Using the [Post]ProcessingAlgorithm and [Post]ProcessingProperties *properties, * create and initialize an algorithm for processing. * * @param postProcessing :: true to create the PostProcessingAlgorithm. * false to create the ProcessingAlgorithm * @return shared pointer to the algorithm, ready for execution. * Returns a NULL pointer if no algorithm was chosen. */ IAlgorithm_sptr LiveDataAlgorithm::makeAlgorithm(bool postProcessing) { std::string prefix; if (postProcessing) prefix = "Post"; // Get the name of the algorithm to run std::string algoName = this->getPropertyValue(prefix + "ProcessingAlgorithm"); algoName = Strings::strip(algoName); // Get the script to run. Ignored if algo is specified std::string script = this->getPropertyValue(prefix + "ProcessingScript"); script = Strings::strip(script); std::string scriptfile = this->getPropertyValue(prefix + "ProcessingScriptFilename"); if (!algoName.empty()) { g_log.information() << "Creating algorithm from name \'" << algoName << "\'\n"; // Properties to pass to algo std::string props = this->getPropertyValue(prefix + "ProcessingProperties"); // Create the UNMANAGED algorithm IAlgorithm_sptr alg = this->createChildAlgorithm(algoName); // Skip some of the properties when setting std::unordered_set<std::string> ignoreProps; ignoreProps.insert("InputWorkspace"); ignoreProps.insert("OutputWorkspace"); // ...and pass it the properties alg->setPropertiesWithString(props, ignoreProps); // Warn if someone put both values. if (!script.empty()) g_log.warning() << "Running algorithm " << algoName << " and ignoring the script code in " << prefix + "ProcessingScript\n"; return alg; } else if (!script.empty() || !scriptfile.empty()) { // Run a snippet of python IAlgorithm_sptr alg = this->createChildAlgorithm("RunPythonScript"); alg->setLogging(false); if (scriptfile.empty()) { g_log.information("Creating python algorithm from string"); alg->setPropertyValue("Code", script); } else { g_log.information() << "Creating python algorithm from file \'" << scriptfile << "\'\n"; alg->setPropertyValue("Filename", scriptfile); } g_log.information(" stack traces will be off by 5" " lines because of boiler-plate"); return alg; } else { return IAlgorithm_sptr(); } }
/** * Loads an empty instrument into a workspace and returns a pointer to it. * * If an analyser and reflection are supplied then the corresponding IPF is also *loaded. * The workspace is not stored in ADS. * * @param instrumentName Name of the instrument to load * @param analyser Analyser being used (optional) * @param reflection Relection being used (optional) * @returns Pointer to instrument workspace */ Mantid::API::MatrixWorkspace_sptr IndirectDataReduction::loadInstrumentIfNotExist(std::string instrumentName, std::string analyser, std::string reflection) { std::string idfDirectory = Mantid::Kernel::ConfigService::Instance().getString( "instrumentDefinition.directory"); try { std::string parameterFilename = idfDirectory + instrumentName + "_Definition.xml"; IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument"); loadAlg->setChild(true); loadAlg->setLogging(false); loadAlg->initialize(); loadAlg->setProperty("Filename", parameterFilename); loadAlg->setProperty("OutputWorkspace", "__IDR_Inst"); loadAlg->execute(); MatrixWorkspace_sptr instWorkspace = loadAlg->getProperty("OutputWorkspace"); // Load the IPF if given an analyser and reflection if (!analyser.empty() && !reflection.empty()) { std::string ipfFilename = idfDirectory + instrumentName + "_" + analyser + "_" + reflection + "_Parameters.xml"; IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile"); loadParamAlg->setChild(true); loadParamAlg->setLogging(false); loadParamAlg->initialize(); loadParamAlg->setProperty("Filename", ipfFilename); loadParamAlg->setProperty("Workspace", instWorkspace); loadParamAlg->execute(); } return instWorkspace; } catch (std::exception &ex) { g_log.warning() << "Failed to load instrument with error: " << ex.what() << ". The current facility may not be fully " "supported.\n"; return MatrixWorkspace_sptr(); } }
/** Load dead-time corrections from specified file * @param deadTimeFile :: [input] File to read corrections from * @return :: Deadtime corrections loaded from file */ Workspace_sptr PlotAsymmetryByLogValue::loadCorrectionsFromFile( const std::string &deadTimeFile) { IAlgorithm_sptr alg = createChildAlgorithm("LoadNexusProcessed"); alg->setPropertyValue("Filename", deadTimeFile); alg->setLogging(false); alg->execute(); Workspace_sptr deadTimes = alg->getProperty("OutputWorkspace"); return deadTimes; }
void IqtFit::plotGuess(QtProperty *) { // Do nothing if there is no sample data curve if (!m_uiForm.ppPlot->hasCurve("Sample")) return; CompositeFunction_sptr function = createFunction(true); // Create the double* array from the input workspace const size_t binIndxLow = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_properties["StartX"])); const size_t binIndxHigh = m_ffInputWS->binIndexOf(m_ffRangeManager->value(m_properties["EndX"])); const size_t nData = binIndxHigh - binIndxLow; std::vector<double> inputXData(nData); const Mantid::MantidVec &XValues = m_ffInputWS->readX(0); const bool isHistogram = m_ffInputWS->isHistogramData(); for (size_t i = 0; i < nData; i++) { if (isHistogram) inputXData[i] = 0.5 * (XValues[binIndxLow + i] + XValues[binIndxLow + i + 1]); else inputXData[i] = XValues[binIndxLow + i]; } FunctionDomain1DVector domain(inputXData); FunctionValues outputData(domain); function->function(domain, outputData); QVector<double> dataX; QVector<double> dataY; for (size_t i = 0; i < nData; i++) { dataX.append(inputXData[i]); dataY.append(outputData.getCalculated(i)); } IAlgorithm_sptr createWsAlg = AlgorithmManager::Instance().create("CreateWorkspace"); createWsAlg->initialize(); createWsAlg->setChild(true); createWsAlg->setLogging(false); createWsAlg->setProperty("OutputWorkspace", "__GuessAnon"); createWsAlg->setProperty("NSpec", 1); createWsAlg->setProperty("DataX", dataX.toStdVector()); createWsAlg->setProperty("DataY", dataY.toStdVector()); createWsAlg->execute(); MatrixWorkspace_sptr guessWs = createWsAlg->getProperty("OutputWorkspace"); m_uiForm.ppPlot->addSpectrum("Guess", guessWs, 0, Qt::green); }
/** Calculate the integral asymmetry for a workspace. * The calculation is done by AsymmetryCalc and Integration algorithms. * @param ws :: The workspace * @param Y :: Reference to a variable receiving the value of asymmetry * @param E :: Reference to a variable receiving the value of the error */ void PlotAsymmetryByLogValue::calcIntAsymmetry(MatrixWorkspace_sptr ws, double &Y, double &E) { if (!m_int) { // "Differential asymmetry" IAlgorithm_sptr asym = createChildAlgorithm("AsymmetryCalc"); asym->setLogging(false); asym->setProperty("InputWorkspace", ws); asym->execute(); MatrixWorkspace_sptr asymWS = asym->getProperty("OutputWorkspace"); IAlgorithm_sptr integr = createChildAlgorithm("Integration"); integr->setLogging(false); integr->setProperty("InputWorkspace", asymWS); integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); MatrixWorkspace_sptr out = integr->getProperty("OutputWorkspace"); Y = out->readY(0)[0]; E = out->readE(0)[0]; } else { // "Integral asymmetry" IAlgorithm_sptr integr = createChildAlgorithm("Integration"); integr->setLogging(false); integr->setProperty("InputWorkspace", ws); integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); MatrixWorkspace_sptr intWS = integr->getProperty("OutputWorkspace"); IAlgorithm_sptr asym = createChildAlgorithm("AsymmetryCalc"); asym->setLogging(false); asym->setProperty("InputWorkspace", intWS); asym->execute(); MatrixWorkspace_sptr out = asym->getProperty("OutputWorkspace"); Y = out->readY(0)[0]; E = out->readE(0)[0]; } }
/** Group detectors from table * @param loadedWs :: [input/output] Workspace to apply grouping to * @param grouping :: [input] Workspace containing grouping to apply */ void PlotAsymmetryByLogValue::groupDetectors(Workspace_sptr &loadedWs, Workspace_sptr grouping) { // Could be groups of workspaces, so need to work with ADS ScopedWorkspace inWS(loadedWs); ScopedWorkspace grWS(grouping); ScopedWorkspace outWS; IAlgorithm_sptr alg = AlgorithmManager::Instance().create("MuonGroupDetectors"); alg->setLogging(false); alg->setPropertyValue("InputWorkspace", inWS.name()); alg->setPropertyValue("DetectorGroupingTable", grWS.name()); alg->setPropertyValue("OutputWorkspace", outWS.name()); alg->execute(); loadedWs = outWS.retrieve(); }
/** Apply dead-time corrections. The calculation is done by ApplyDeadTimeCorr * algorithm * @param loadedWs :: [input/output] Workspace to apply corrections to * @param deadTimes :: [input] Corrections to apply */ void PlotAsymmetryByLogValue::applyDeadtimeCorr(Workspace_sptr &loadedWs, Workspace_sptr deadTimes) { ScopedWorkspace ws(loadedWs); ScopedWorkspace dt(deadTimes); IAlgorithm_sptr applyCorr = AlgorithmManager::Instance().create("ApplyDeadTimeCorr"); applyCorr->setLogging(false); applyCorr->setRethrows(true); applyCorr->setPropertyValue("InputWorkspace", ws.name()); applyCorr->setPropertyValue("OutputWorkspace", ws.name()); applyCorr->setProperty("DeadTimeTable", dt.name()); applyCorr->execute(); // Workspace should've been replaced in the ADS by ApplyDeadTimeCorr, so // need to // re-assign it loadedWs = ws.retrieve(); }
/** Using the [Post]ProcessingAlgorithm and [Post]ProcessingProperties *properties, * create and initialize an algorithm for processing. * * @param postProcessing :: true to create the PostProcessingAlgorithm. * false to create the ProcessingAlgorithm * @return shared pointer to the algorithm, ready for execution. * Returns a NULL pointer if no algorithm was chosen. */ IAlgorithm_sptr LiveDataAlgorithm::makeAlgorithm(bool postProcessing) { std::string prefix = ""; if (postProcessing) prefix = "Post"; // Get the name of the algorithm to run std::string algoName = this->getPropertyValue(prefix + "ProcessingAlgorithm"); algoName = Strings::strip(algoName); // Get the script to run. Ignored if algo is specified std::string script = this->getPropertyValue(prefix + "ProcessingScript"); script = Strings::strip(script); if (!algoName.empty()) { // Properties to pass to algo std::string props = this->getPropertyValue(prefix + "ProcessingProperties"); // Create the UNMANAGED algorithm IAlgorithm_sptr alg = this->createChildAlgorithm(algoName); // Skip some of the properties when setting std::set<std::string> ignoreProps; ignoreProps.insert("InputWorkspace"); ignoreProps.insert("OutputWorkspace"); // ...and pass it the properties alg->setPropertiesWithSimpleString(props, ignoreProps); // Warn if someone put both values. if (!script.empty()) g_log.warning() << "Running algorithm " << algoName << " and ignoring the script code in " << prefix + "ProcessingScript" << std::endl; return alg; } else if (!script.empty()) { // Run a snippet of python IAlgorithm_sptr alg = this->createChildAlgorithm("RunPythonScript"); alg->setLogging(false); alg->setPropertyValue("Code", script); return alg; } else return IAlgorithm_sptr(); }
Workspace_sptr GenericDataProcessorAlgorithm<Base>::assemble(Workspace_sptr partialWS) { Workspace_sptr outputWS = partialWS; #ifdef MPI_BUILD IAlgorithm_sptr gatherAlg = createChildAlgorithm("GatherWorkspaces"); gatherAlg->setLogging(true); gatherAlg->setAlwaysStoreInADS(true); gatherAlg->setProperty("InputWorkspace", partialWS); gatherAlg->setProperty("PreserveEvents", true); gatherAlg->setPropertyValue("OutputWorkspace", "_total"); gatherAlg->execute(); if (isMainThread()) { outputWS = AnalysisDataService::Instance().retrieve("_total"); } #endif return outputWS; }
/** * Updates the analyser and reflection names in the UI when an instrument is selected. * * @param instrumentName Nmae of instrument */ void IndirectInstrumentConfig::updateInstrumentConfigurations(const QString & instrumentName) { if(instrumentName.isEmpty()) return; g_log.debug() << "Loading configuration for instrument: " << instrumentName.toStdString() << std::endl; bool analyserPreviousBlocking = m_uiForm.cbAnalyser->signalsBlocked(); m_uiForm.cbAnalyser->blockSignals(true); m_uiForm.cbAnalyser->clear(); // Try to load the instrument into an empty workspace MatrixWorkspace_sptr instWorkspace; try { IAlgorithm_sptr loadInstAlg = AlgorithmManager::Instance().create("CreateSimulationWorkspace"); loadInstAlg->initialize(); loadInstAlg->setChild(true); loadInstAlg->setLogging(false); loadInstAlg->setProperty("Instrument", instrumentName.toStdString()); loadInstAlg->setProperty("BinParams", "0,0.5,1"); loadInstAlg->setProperty("OutputWorkspace", "__empty_instrument_workspace"); loadInstAlg->execute(); instWorkspace = loadInstAlg->getProperty("OutputWorkspace"); } catch(...) { } // Try to update the list of analysers bool valid = updateAnalysersList(instWorkspace); m_uiForm.cbAnalyser->setEnabled(valid); if(!valid) m_uiForm.cbAnalyser->addItem("No Valid Analysers"); // Update the list of reflections int index = m_uiForm.cbAnalyser->currentIndex(); updateReflectionsList(index); m_uiForm.cbAnalyser->blockSignals(analyserPreviousBlocking); }
/** * Loads dead time table (group of tables) from the file. * @param filename :: File to load dead times from * @return Table (group of tables) with dead times */ Workspace_sptr MuonAnalysisDataLoader::loadDeadTimesFromFile( const std::string &filename) const { try { IAlgorithm_sptr loadDeadTimes = AlgorithmManager::Instance().create("LoadNexusProcessed"); loadDeadTimes->setChild(true); loadDeadTimes->setLogging(false); // We'll take care of logging ourself loadDeadTimes->setPropertyValue( "Filename", filename.empty() ? m_deadTimesFile : filename); loadDeadTimes->setPropertyValue("OutputWorkspace", "__NotUsed"); loadDeadTimes->execute(); return loadDeadTimes->getProperty("OutputWorkspace"); } catch (std::exception &e) { std::ostringstream errorMsg; errorMsg << "Unable to load dead times from the specified file: " << e.what(); throw std::runtime_error(errorMsg.str()); } }
/** Loads the instrument into a workspace. */ void VesuvioL1ThetaResolution::loadInstrument() { // Get the filename for the VESUVIO IDF MatrixWorkspace_sptr tempWS = WorkspaceFactory::Instance().create("Workspace2D", 1, 1, 1); const std::string vesuvioIPF = tempWS->getInstrumentFilename("VESUVIO"); // Load an empty VESUVIO instrument workspace IAlgorithm_sptr loadInst = AlgorithmManager::Instance().create("LoadEmptyInstrument"); loadInst->initialize(); loadInst->setChild(true); loadInst->setLogging(false); loadInst->setProperty("OutputWorkspace", "__evs"); loadInst->setProperty("Filename", vesuvioIPF); loadInst->execute(); m_instWorkspace = loadInst->getProperty("OutputWorkspace"); // Load the PAR file if provided const std::string parFilename = getPropertyValue("PARFile"); if (!parFilename.empty()) { g_log.information() << "Loading PAR file: " << parFilename << '\n'; // Get header format std::map<size_t, std::string> headerFormats; headerFormats[5] = "spectrum,theta,t0,-,R"; headerFormats[6] = "spectrum,-,theta,t0,-,R"; std::ifstream parFile(parFilename); if (!parFile) { throw std::runtime_error("Cannot open PAR file"); } std::string header; getline(parFile, header); g_log.debug() << "PAR file header: " << header << '\n'; boost::trim(header); std::vector<std::string> headers; boost::split(headers, header, boost::is_any_of("\t "), boost::token_compress_on); size_t numCols = headers.size(); g_log.debug() << "PAR file columns: " << numCols << '\n'; std::string headerFormat = headerFormats[numCols]; if (headerFormat.empty()) { std::stringstream error; error << "Unrecognised PAR file header. Number of colums: " << numCols << " (expected either 5 or 6."; throw std::runtime_error(error.str()); } g_log.debug() << "PAR file header format: " << headerFormat << '\n'; // Update instrument IAlgorithm_sptr updateInst = AlgorithmManager::Instance().create("UpdateInstrumentFromFile"); updateInst->initialize(); updateInst->setChild(true); updateInst->setLogging(false); updateInst->setProperty("Workspace", m_instWorkspace); updateInst->setProperty("Filename", parFilename); updateInst->setProperty("MoveMonitors", false); updateInst->setProperty("IgnorePhi", true); updateInst->setProperty("AsciiHeader", headerFormat); updateInst->execute(); m_instWorkspace = updateInst->getProperty("Workspace"); } const int specIdxMin = static_cast<int>( m_instWorkspace->getIndexFromSpectrumNumber(getProperty("SpectrumMin"))); const int specIdxMax = static_cast<int>( m_instWorkspace->getIndexFromSpectrumNumber(getProperty("SpectrumMax"))); // Crop the workspace to just the detectors we are interested in IAlgorithm_sptr crop = AlgorithmManager::Instance().create("CropWorkspace"); crop->initialize(); crop->setChild(true); crop->setLogging(false); crop->setProperty("InputWorkspace", m_instWorkspace); crop->setProperty("OutputWorkspace", "__evs"); crop->setProperty("StartWorkspaceIndex", specIdxMin); crop->setProperty("EndWorkspaceIndex", specIdxMax); crop->execute(); m_instWorkspace = crop->getProperty("OutputWorkspace"); m_sample = m_instWorkspace->getInstrument()->getSample(); }
/** Using the [Post]ProcessingAlgorithm and [Post]ProcessingProperties properties, * create and initialize an algorithm for processing. * * @param postProcessing :: true to create the PostProcessingAlgorithm. * false to create the ProcessingAlgorithm * @return shared pointer to the algorithm, ready for execution. * Returns a NULL pointer if no algorithm was chosen. */ IAlgorithm_sptr LiveDataAlgorithm::makeAlgorithm(bool postProcessing) { std::string prefix = ""; if (postProcessing) prefix = "Post"; // Get the name of the algorithm to run std::string algoName = this->getPropertyValue(prefix+"ProcessingAlgorithm"); algoName = Strings::strip(algoName); // Get the script to run. Ignored if algo is specified std::string script = this->getPropertyValue(prefix+"ProcessingScript"); script = Strings::strip(script); if (!algoName.empty()) { // Properties to pass to algo std::string props = this->getPropertyValue(prefix+"ProcessingProperties"); // Create the UNMANAGED algorithm IAlgorithm_sptr alg = this->createChildAlgorithm(algoName); // ...and pass it the properties boost::char_separator<char> sep(";"); typedef boost::tokenizer<boost::char_separator<char> > tokenizer; tokenizer propPairs(props, sep); // Iterate over the properties for (tokenizer::iterator it = propPairs.begin(); it != propPairs.end(); ++it) { // Pair of the type " std::string pair = *it; size_t n = pair.find('='); if (n == std::string::npos) { // Do nothing } else { // Normal "PropertyName=value" string. std::string propName = ""; std::string value = ""; // Extract the value string if (n < pair.size()-1) { propName = pair.substr(0, n); value = pair.substr(n+1, pair.size()-n-1); } else { // String is "PropertyName=" propName = pair.substr(0, n); value = ""; } // Skip some of the properties when setting if ((propName != "InputWorkspace") && (propName != "OutputWorkspace")) alg->setPropertyValue(propName,value); } } // Warn if someone put both values. if (!script.empty()) g_log.warning() << "Running algorithm " << algoName << " and ignoring the script code in " << prefix+"ProcessingScript" << std::endl; return alg; } else if (!script.empty()) { // Run a snippet of python IAlgorithm_sptr alg = this->createChildAlgorithm("RunPythonScript"); alg->setLogging(false); alg->setPropertyValue("Code", script); return alg; } else return IAlgorithm_sptr(); }
void ApplyPaalmanPings::run() { // Create / Initialize algorithm API::BatchAlgorithmRunner::AlgorithmRuntimeProps absCorProps; IAlgorithm_sptr applyCorrAlg = AlgorithmManager::Instance().create("ApplyPaalmanPingsCorrection"); applyCorrAlg->initialize(); // get Sample Workspace MatrixWorkspace_sptr sampleWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>( m_sampleWorkspaceName); m_originalSampleUnits = sampleWs->getAxis(0)->unit()->unitID(); // If not in wavelength then do conversion if (m_originalSampleUnits != "Wavelength") { g_log.information( "Sample workspace not in wavelength, need to convert to continue."); absCorProps["SampleWorkspace"] = addConvertUnitsStep(sampleWs, "Wavelength"); } else { absCorProps["SampleWorkspace"] = m_sampleWorkspaceName; } const bool useCan = m_uiForm.ckUseCan->isChecked(); const bool useCorrections = m_uiForm.ckUseCorrections->isChecked(); // Get Can and Clone MatrixWorkspace_sptr canClone; if (useCan) { const auto canName = m_uiForm.dsContainer->getCurrentDataName().toStdString(); const auto cloneName = "__algorithm_can"; IAlgorithm_sptr clone = AlgorithmManager::Instance().create("CloneWorkspace"); clone->initialize(); clone->setProperty("InputWorkspace", canName); clone->setProperty("Outputworkspace", cloneName); clone->execute(); const bool useShift = m_uiForm.ckShiftCan->isChecked(); if (useShift) { IAlgorithm_sptr scaleX = AlgorithmManager::Instance().create("ScaleX"); scaleX->initialize(); scaleX->setLogging(false); scaleX->setProperty("InputWorkspace", cloneName); scaleX->setProperty("OutputWorkspace", cloneName); scaleX->setProperty("Factor", m_uiForm.spCanShift->value()); scaleX->setProperty("Operation", "Add"); scaleX->execute(); IAlgorithm_sptr rebin = AlgorithmManager::Instance().create("RebinToWorkspace"); rebin->initialize(); rebin->setLogging(false); rebin->setProperty("WorkspaceToRebin", cloneName); rebin->setProperty("WorkspaceToMatch", m_sampleWorkspaceName); rebin->setProperty("OutputWorkspace", cloneName); rebin->execute(); } canClone = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(cloneName); // Check for same binning across sample and container if (!checkWorkspaceBinningMatches(sampleWs, canClone)) { const char *text = "Binning on sample and container does not match." "Would you like to rebin the container to match the sample?"; int result = QMessageBox::question(NULL, tr("Rebin sample?"), tr(text), QMessageBox::Yes, QMessageBox::No, QMessageBox::NoButton); if (result == QMessageBox::Yes) { addRebinStep(QString::fromStdString(canName), QString::fromStdString(m_sampleWorkspaceName)); } else { m_batchAlgoRunner->clearQueue(); g_log.error("Cannot apply absorption corrections " "using a sample and " "container with different binning."); return; } } // If not in wavelength then do conversion std::string originalCanUnits = canClone->getAxis(0)->unit()->unitID(); if (originalCanUnits != "Wavelength") { g_log.information("Container workspace not in wavelength, need to " "convert to continue."); absCorProps["CanWorkspace"] = addConvertUnitsStep(canClone, "Wavelength"); } else { absCorProps["CanWorkspace"] = cloneName; } const bool useCanScale = m_uiForm.ckScaleCan->isChecked(); if (useCanScale) { const double canScaleFactor = m_uiForm.spCanScale->value(); applyCorrAlg->setProperty("CanScaleFactor", canScaleFactor); } } if (useCorrections) { QString correctionsWsName = m_uiForm.dsCorrections->getCurrentDataName(); WorkspaceGroup_sptr corrections = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( correctionsWsName.toStdString()); bool interpolateAll = false; for (size_t i = 0; i < corrections->size(); i++) { MatrixWorkspace_sptr factorWs = boost::dynamic_pointer_cast<MatrixWorkspace>(corrections->getItem(i)); // Check for matching binning if (sampleWs && (sampleWs->blocksize() != factorWs->blocksize())) { int result; if (interpolateAll) { result = QMessageBox::Yes; } else { std::string text = "Number of bins on sample and " + factorWs->name() + " workspace does not match.\n" + "Would you like to interpolate this workspace to " "match the sample?"; result = QMessageBox::question( NULL, tr("Interpolate corrections?"), tr(text.c_str()), QMessageBox::YesToAll, QMessageBox::Yes, QMessageBox::No); } switch (result) { case QMessageBox::YesToAll: interpolateAll = true; // fall through case QMessageBox::Yes: addInterpolationStep(factorWs, absCorProps["SampleWorkspace"]); break; default: m_batchAlgoRunner->clearQueue(); g_log.error("ApplyPaalmanPings cannot run with corrections that do " "not match sample binning."); return; } } } applyCorrAlg->setProperty("CorrectionsWorkspace", correctionsWsName.toStdString()); } // Generate output workspace name auto QStrSampleWsName = QString::fromStdString(m_sampleWorkspaceName); int nameCutIndex = QStrSampleWsName.lastIndexOf("_"); if (nameCutIndex == -1) nameCutIndex = QStrSampleWsName.length(); QString correctionType; switch (m_uiForm.cbGeometry->currentIndex()) { case 0: correctionType = "flt"; break; case 1: correctionType = "cyl"; break; case 2: correctionType = "anl"; break; } QString outputWsName = QStrSampleWsName.left(nameCutIndex); // Using corrections if (m_uiForm.ckUseCorrections->isChecked()) { outputWsName += "_" + correctionType + "_Corrected"; } else { outputWsName += "_Subtracted"; } // Using container if (m_uiForm.ckUseCan->isChecked()) { const auto canName = m_uiForm.dsContainer->getCurrentDataName().toStdString(); MatrixWorkspace_sptr containerWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(canName); auto run = containerWs->run(); if (run.hasProperty("run_number")) { outputWsName += "_" + QString::fromStdString(run.getProperty("run_number")->value()); } else { auto canCutIndex = QString::fromStdString(canName).indexOf("_"); outputWsName += "_" + QString::fromStdString(canName).left(canCutIndex); } } outputWsName += "_red"; applyCorrAlg->setProperty("OutputWorkspace", outputWsName.toStdString()); // Add corrections algorithm to queue m_batchAlgoRunner->addAlgorithm(applyCorrAlg, absCorProps); // Run algorithm queue connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(absCorComplete(bool))); m_batchAlgoRunner->executeBatchAsync(); // Set the result workspace for Python script export m_pythonExportWsName = outputWsName.toStdString(); // m_containerWorkspaceName = m_uiForm.dsContainer->getCurrentDataName(); // updateContainer(); }