void StripVanadiumPeaks2::exec(){ // 1. Process input/output API::MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace"); std::string outputWSName = getPropertyValue("OutputWorkspace"); int singleIndex = getProperty("WorkspaceIndex"); int param_fwhm = getProperty("FWHM"); int param_tolerance = getProperty("Tolerance"); bool singleSpectrum = !isEmpty(singleIndex); // 2. Call StripPeaks std::string peakpositions; std::string unit = inputWS->getAxis(0)->unit()->unitID(); if (unit == "dSpacing") { peakpositions = "0.5044,0.5191,0.5350,0.5526,0.5936,0.6178,0.6453,0.6768,0.7134,0.7566,0.8089,0.8737,0.9571,1.0701,1.2356,1.5133,2.1401"; } else if (unit == "MomentumTransfer") { g_log.error() << "Unit MomentumTransfer (Q-space) is NOT supported by StripVanadiumPeaks now.\n"; throw std::invalid_argument("Q-space is not supported"); // Comment out next line as it won't be reached. //peakpositions = "2.9359, 4.1520, 5.0851, 5.8716, 6.5648, 7.1915, 7.7676, 8.3045, 8.8074, 9.2837, 9.7368, 10.1703, 10.5849, 11.3702, 11.7443, 12.1040, 12.4568"; } else { g_log.error() << "Unit " << unit << " Is NOT supported by StripVanadiumPeaks, which only supports d-spacing" << std::endl; throw std::invalid_argument("Not supported unit"); } // Call StripPeak double pro0 = 0.0; double prof = 1.0; bool sublog = true; IAlgorithm_sptr stripPeaks = createChildAlgorithm("StripPeaks", pro0, prof, sublog); stripPeaks->setProperty("InputWorkspace", inputWS); stripPeaks->setPropertyValue("OutputWorkspace", outputWSName); stripPeaks->setProperty("FWHM", param_fwhm); stripPeaks->setProperty("Tolerance", param_tolerance); stripPeaks->setPropertyValue("PeakPositions", peakpositions); stripPeaks->setProperty<std::string>("BackgroundType", getProperty("BackgroundType")); stripPeaks->setProperty<bool>("HighBackground", getProperty("HighBackground")); if (singleSpectrum){ stripPeaks->setProperty("WorkspaceIndex", singleIndex); } stripPeaks->setProperty<double>("PeakPositionTolerance", getProperty("PeakPositionTolerance")); stripPeaks->executeAsChildAlg(); // 3. Get and set output workspace // API::MatrixWorkspace_sptr outputWS = AnalysisDataService::Instance().retrieveWS<API::MatrixWorkspace_sptr>(outputWSName); // boost::shared_ptr<API::Workspace> outputWS = AnalysisDataService::Instance().retrieve(outputWSName); API::MatrixWorkspace_sptr outputWS = stripPeaks->getProperty("OutputWorkspace"); this->setProperty("OutputWorkspace", outputWS); return; }
/** Executes the algorithm */ void FilterBadPulses::exec() { // the input workspace into the event workspace we already know it is EventWorkspace_sptr inputWS = this->getProperty("InputWorkspace"); // get the proton charge exists in the run object const API::Run& runlogs = inputWS->run(); if (!runlogs.hasProperty("proton_charge")) { throw std::runtime_error("Failed to find \"proton_charge\" in sample logs"); } Kernel::TimeSeriesProperty<double> * pcharge_log = dynamic_cast<Kernel::TimeSeriesProperty<double> *>( runlogs.getLogData("proton_charge") ); Kernel::TimeSeriesPropertyStatistics stats = pcharge_log->getStatistics(); // set the range double min_percent = this->getProperty("LowerCutoff"); min_percent *= .01; // convert it to a percentage (0<x<1) double min_pcharge = stats.mean * min_percent; double max_pcharge = stats.maximum * 1.1; // make sure everything high is in if (min_pcharge >= max_pcharge) { throw std::runtime_error("proton_charge window filters out all of the data"); } this->g_log.information() << "Filtering pcharge outside of " << min_pcharge << " to " << max_pcharge << std::endl; size_t inputNumEvents = inputWS->getNumberEvents(); // sub-algorithme does all of the actual work - do not set the output workspace IAlgorithm_sptr filterAlgo = createSubAlgorithm("FilterByLogValue", 0., 1.); filterAlgo->setProperty("InputWorkspace", inputWS); filterAlgo->setProperty("LogName", "proton_charge"); filterAlgo->setProperty("MinimumValue", min_pcharge); filterAlgo->setProperty("MaximumValue", max_pcharge); filterAlgo->execute(); // just grab the child's output workspace EventWorkspace_sptr outputWS = filterAlgo->getProperty("OutputWorkspace"); size_t outputNumEvents = outputWS->getNumberEvents(); this->setProperty("OutputWorkspace", outputWS); // log the number of events deleted double percent = static_cast<double>(inputNumEvents - outputNumEvents) / static_cast<double>(inputNumEvents); percent *= 100.; if (percent > 10.) { this->g_log.warning() << "Deleted " << (inputNumEvents - outputNumEvents) << " of " << inputNumEvents << " events (" << static_cast<int>(percent) << "%)\n"; } else { this->g_log.information() << "Deleted " << (inputNumEvents - outputNumEvents) << " of " << inputNumEvents << " events (" << static_cast<int>(percent) << "%)\n"; } }
MatrixWorkspace_sptr CalculateIqt::integration(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr integrationAlgorithm = this->createChildAlgorithm("Integration"); integrationAlgorithm->initialize(); integrationAlgorithm->setProperty("InputWorkspace", workspace); integrationAlgorithm->setProperty("OutputWorkspace", "_"); integrationAlgorithm->execute(); return integrationAlgorithm->getProperty("OutputWorkspace"); }
/** * Applies dead time correction to the workspace. * @param ws :: Workspace to apply correction * @param dt :: Dead time table to use * @return Corrected workspace */ MatrixWorkspace_sptr MuonLoad::applyDTC(MatrixWorkspace_sptr ws, TableWorkspace_sptr dt) { IAlgorithm_sptr dtc = createChildAlgorithm("ApplyDeadTimeCorr"); dtc->setProperty("InputWorkspace", ws); dtc->setProperty("DeadTimeTable", dt); dtc->execute(); return dtc->getProperty("OutputWorkspace"); }
/** * Groups specified workspace according to specified DetectorGroupingTable. * @param ws :: Workspace to group * @param grouping :: Detector grouping table to use * @return Grouped workspace */ MatrixWorkspace_sptr MuonLoad::groupWorkspace(MatrixWorkspace_sptr ws, TableWorkspace_sptr grouping) { IAlgorithm_sptr group = createChildAlgorithm("MuonGroupDetectors"); group->setProperty("InputWorkspace", ws); group->setProperty("DetectorGroupingTable", grouping); group->execute(); return group->getProperty("OutputWorkspace"); }
/** * Function to apply a given mask to a workspace. * @param inputWS : the workspace to mask * @param maskWS : the workspace containing the masking information */ void DetectorDiagnostic::applyMask(API::MatrixWorkspace_sptr inputWS, API::MatrixWorkspace_sptr maskWS) { IAlgorithm_sptr maskAlg = createChildAlgorithm("MaskDetectors"); // should set progress bar maskAlg->setProperty("Workspace", inputWS); maskAlg->setProperty("MaskedWorkspace", maskWS); maskAlg->setProperty("StartWorkspaceIndex", m_minIndex); maskAlg->setProperty("EndWorkspaceIndex", m_maxIndex); maskAlg->executeAsChildAlg(); }
MatrixWorkspace_sptr CalculateIqt::divide(MatrixWorkspace_sptr lhsWorkspace, MatrixWorkspace_sptr rhsWorkspace) { IAlgorithm_sptr divideAlgorithm = this->createChildAlgorithm("Divide"); divideAlgorithm->initialize(); divideAlgorithm->setProperty("LHSWorkspace", lhsWorkspace); divideAlgorithm->setProperty("RHSWorkspace", rhsWorkspace); divideAlgorithm->setProperty("OutputWorkspace", "_"); divideAlgorithm->execute(); return divideAlgorithm->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::convertToPointData(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr pointDataAlgorithm = this->createChildAlgorithm("ConvertToPointData"); pointDataAlgorithm->initialize(); pointDataAlgorithm->setProperty("InputWorkspace", workspace); pointDataAlgorithm->setProperty("OutputWorkspace", "_"); pointDataAlgorithm->execute(); return pointDataAlgorithm->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::rebin(MatrixWorkspace_sptr workspace, const std::string ¶ms) { IAlgorithm_sptr rebinAlgorithm = this->createChildAlgorithm("Rebin"); rebinAlgorithm->initialize(); rebinAlgorithm->setProperty("InputWorkspace", workspace); rebinAlgorithm->setProperty("OutputWorkspace", "_"); rebinAlgorithm->setProperty("Params", params); rebinAlgorithm->execute(); return rebinAlgorithm->getProperty("OutputWorkspace"); }
/** Calls the Rebin algorithm as a ChildAlgorithm. * @param workspace The workspace to use as input to the Rebin algorithms * @param params The rebin parameters * @return A shared pointer to the output (rebinned) workspace * @throw std::runtime_error If the Rebin algorithm fails */ API::MatrixWorkspace_sptr MergeRuns::rebinInput(const API::MatrixWorkspace_sptr &workspace, const std::vector<double> ¶ms) { // Create a Rebin child algorithm IAlgorithm_sptr rebin = createChildAlgorithm("Rebin"); rebin->setProperty("InputWorkspace", workspace); rebin->setProperty("Params", params); rebin->executeAsChildAlg(); return rebin->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr CalculateIqt::cropWorkspace(MatrixWorkspace_sptr workspace, const double xMax) { IAlgorithm_sptr cropAlgorithm = this->createChildAlgorithm("CropWorkspace"); cropAlgorithm->initialize(); cropAlgorithm->setProperty("InputWorkspace", workspace); cropAlgorithm->setProperty("OutputWorkspace", "_"); cropAlgorithm->setProperty("XMax", xMax); cropAlgorithm->execute(); return cropAlgorithm->getProperty("OutputWorkspace"); }
Workspace_sptr GenericDataProcessorAlgorithm<Base>::load(const std::string &inputData, const bool loadQuiet) { Workspace_sptr inputWS; // First, check whether we have the name of an existing workspace if (AnalysisDataService::Instance().doesExist(inputData)) { inputWS = AnalysisDataService::Instance().retrieve(inputData); } else { std::string foundFile = FileFinder::Instance().getFullPath(inputData); if (foundFile.empty()) { // Get facility extensions FacilityInfo facilityInfo = ConfigService::Instance().getFacility(); const std::vector<std::string> facilityExts = facilityInfo.extensions(); foundFile = FileFinder::Instance().findRun(inputData, facilityExts); } if (!foundFile.empty()) { Poco::Path p(foundFile); const std::string outputWSName = p.getBaseName(); IAlgorithm_sptr loadAlg = createChildAlgorithm(m_loadAlg); loadAlg->setProperty(m_loadAlgFileProp, foundFile); if (!loadQuiet) { loadAlg->setAlwaysStoreInADS(true); } // Set up MPI if available #ifdef MPI_BUILD // First, check whether the loader allows use to chunk the data if (loadAlg->existsProperty("ChunkNumber") && loadAlg->existsProperty("TotalChunks")) { m_useMPI = true; // The communicator containing all processes boost::mpi::communicator world; g_log.notice() << "Chunk/Total: " << world.rank() + 1 << "/" << world.size() << '\n'; loadAlg->setPropertyValue("OutputWorkspace", outputWSName); loadAlg->setProperty("ChunkNumber", world.rank() + 1); loadAlg->setProperty("TotalChunks", world.size()); } #endif loadAlg->execute(); if (loadQuiet) { inputWS = loadAlg->getProperty("OutputWorkspace"); } else { inputWS = AnalysisDataService::Instance().retrieve(outputWSName); } } else throw std::runtime_error( "DataProcessorAlgorithm::load could process any data"); } return inputWS; }
MatrixWorkspace_sptr CalculateIqt::extractFFTSpectrum(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr FFTAlgorithm = this->createChildAlgorithm("ExtractFFTSpectrum"); FFTAlgorithm->initialize(); FFTAlgorithm->setProperty("InputWorkspace", workspace); FFTAlgorithm->setProperty("OutputWorkspace", "_"); FFTAlgorithm->setProperty("FFTPart", 2); FFTAlgorithm->execute(); return FFTAlgorithm->getProperty("OutputWorkspace"); }
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); }
MatrixWorkspace_sptr MuonPairingAsymmetry::appendSpectra(MatrixWorkspace_sptr inputWS1, MatrixWorkspace_sptr inputWS2) { IAlgorithm_sptr alg = this->createChildAlgorithm("AppendSpectra"); alg->setProperty("InputWorkspace1", inputWS1); alg->setProperty("InputWorkspace2", inputWS2); alg->setProperty("ValidateInputs", true); alg->execute(); MatrixWorkspace_sptr ws = alg->getProperty("OutputWorkspace"); return ws; }
/// Run the Child Algorithm LoadInstrument (or LoadInstrumentFromNexus) void LoadISISNexus2::runLoadInstrument(DataObjects::Workspace2D_sptr localWorkspace) { IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument"); // Now execute the Child Algorithm. Catch and log any error, but don't stop. bool executionSuccessful(true); try { loadInst->setPropertyValue("InstrumentName", m_instrument_name); loadInst->setProperty<MatrixWorkspace_sptr> ("Workspace", localWorkspace); loadInst->setProperty("RewriteSpectraMap", false); loadInst->execute(); } catch( std::invalid_argument&) { g_log.information("Invalid argument to LoadInstrument Child Algorithm"); executionSuccessful = false; } catch (std::runtime_error&) { g_log.information("Unable to successfully run LoadInstrument Child Algorithm"); executionSuccessful = false; } if( executionSuccessful ) { // If requested update the instrument to positions in the data file const Geometry::ParameterMap & pmap = localWorkspace->instrumentParameters(); if( pmap.contains(localWorkspace->getInstrument()->getComponentID(),"det-pos-source") ) { boost::shared_ptr<Geometry::Parameter> updateDets = pmap.get(localWorkspace->getInstrument()->getComponentID(),"det-pos-source"); std::string value = updateDets->value<std::string>(); if(value.substr(0,8) == "datafile" ) { IAlgorithm_sptr updateInst = createChildAlgorithm("UpdateInstrumentFromFile"); updateInst->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace); updateInst->setPropertyValue("Filename", m_filename); if(value == "datafile-ignore-phi" ) { updateInst->setProperty("IgnorePhi", true); g_log.information("Detector positions in IDF updated with positions in the data file except for the phi values"); } else { g_log.information("Detector positions in IDF updated with positions in the data file"); } // We want this to throw if it fails to warn the user that the information is not correct. updateInst->execute(); } } } }
/** * Plots the loaded file to the miniplot and sets the guides * and the range * * @param filename :: The name of the workspace to plot */ void JumpFit::handleSampleInputReady(const QString& filename) { // Disable things that run the preview algorithm disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(runPreviewAlgorithm())); disconnect(m_uiForm.cbFunction, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(runPreviewAlgorithm())); disconnect(m_uiForm.cbWidth, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(runPreviewAlgorithm())); // Scale to convert to HWHM IAlgorithm_sptr scaleAlg = AlgorithmManager::Instance().create("Scale"); scaleAlg->initialize(); scaleAlg->setProperty("InputWorkspace", filename.toStdString()); scaleAlg->setProperty("OutputWorkspace", filename.toStdString()); scaleAlg->setProperty("Factor", 0.5); scaleAlg->execute(); auto ws = Mantid::API::AnalysisDataService::Instance().retrieve(filename.toStdString()); auto mws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(ws); findAllWidths(mws); if(m_spectraList.size() > 0) { m_uiForm.cbWidth->setEnabled(true); std::string currentWidth = m_uiForm.cbWidth->currentText().toStdString(); plotMiniPlot(filename, m_spectraList[currentWidth], "JumpFitPlot", "RawPlotCurve"); std::pair<double,double> res; std::pair<double,double> range = getCurveRange("RawPlotCurve"); // Use the values from the instrument parameter file if we can if(getInstrumentResolution(filename, res)) setMiniPlotGuides("JumpFitQ", m_properties["QMin"], m_properties["QMax"], res); else setMiniPlotGuides("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); setPlotRange("JumpFitQ", m_properties["QMin"], m_properties["QMax"], range); } else { m_uiForm.cbWidth->setEnabled(false); emit showMessageBox("Workspace doesn't appear to contain any width data"); } // Update preview plot runPreviewAlgorithm(); // Re-enable things that run the preview algorithm connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(runPreviewAlgorithm())); connect(m_uiForm.cbFunction, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(runPreviewAlgorithm())); connect(m_uiForm.cbWidth, SIGNAL(currentIndexChanged(const QString&)), this, SLOT(runPreviewAlgorithm())); }
/** * Adds a rebin to workspace step to the calculation for when using a sample and *container that * have different binning. * * @param toRebin * @param toMatch */ void ApplyPaalmanPings::addRebinStep(QString toRebin, QString toMatch) { API::BatchAlgorithmRunner::AlgorithmRuntimeProps rebinProps; rebinProps["WorkspaceToMatch"] = toMatch.toStdString(); IAlgorithm_sptr rebinAlg = AlgorithmManager::Instance().create("RebinToWorkspace"); rebinAlg->initialize(); rebinAlg->setProperty("WorkspaceToRebin", toRebin.toStdString()); rebinAlg->setProperty("OutputWorkspace", toRebin.toStdString()); m_batchAlgoRunner->addAlgorithm(rebinAlg, rebinProps); }
MatrixWorkspace_sptr CalculateIqt::replaceSpecialValues(MatrixWorkspace_sptr workspace) { IAlgorithm_sptr specialValuesAlgorithm = this->createChildAlgorithm("ReplaceSpecialValues"); specialValuesAlgorithm->initialize(); specialValuesAlgorithm->setProperty("InputWorkspace", workspace); specialValuesAlgorithm->setProperty("OutputWorkspace", "_"); specialValuesAlgorithm->setProperty("InfinityValue", 0.0); specialValuesAlgorithm->setProperty("BigNumberThreshold", 1.0001); specialValuesAlgorithm->setProperty("NaNValue", 0.0); specialValuesAlgorithm->execute(); return specialValuesAlgorithm->getProperty("OutputWorkspace"); }
/// Move the detector according to the beam center void EQSANSLoad::moveToBeamCenter() { // Check that we have a beam center defined, otherwise set the // default beam center if (isEmpty(m_center_x) || isEmpty(m_center_y)) { EQSANSInstrument::getDefaultBeamCenter(dataWS, m_center_x, m_center_y); g_log.information() << "Setting beam center to [" << m_center_x << ", " << m_center_y << "]\n"; return; } // Check that the center of the detector really is at (0,0) int nx_pixels = static_cast<int>( dataWS->getInstrument()->getNumberParameter("number-of-x-pixels")[0]); int ny_pixels = static_cast<int>( dataWS->getInstrument()->getNumberParameter("number-of-y-pixels")[0]); V3D pixel_first = dataWS->getInstrument()->getDetector(0)->getPos(); int detIDx = EQSANSInstrument::getDetectorFromPixel(nx_pixels - 1, 0, dataWS); int detIDy = EQSANSInstrument::getDetectorFromPixel(0, ny_pixels - 1, dataWS); V3D pixel_last_x = dataWS->getInstrument()->getDetector(detIDx)->getPos(); V3D pixel_last_y = dataWS->getInstrument()->getDetector(detIDy)->getPos(); double x_offset = (pixel_first.X() + pixel_last_x.X()) / 2.0; double y_offset = (pixel_first.Y() + pixel_last_y.Y()) / 2.0; double beam_ctr_x = 0.0; double beam_ctr_y = 0.0; EQSANSInstrument::getCoordinateFromPixel(m_center_x, m_center_y, dataWS, beam_ctr_x, beam_ctr_y); IAlgorithm_sptr mvAlg = createChildAlgorithm("MoveInstrumentComponent", 0.5, 0.50); mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS); mvAlg->setProperty("ComponentName", "detector1"); mvAlg->setProperty("X", -x_offset - beam_ctr_x); mvAlg->setProperty("Y", -y_offset - beam_ctr_y); mvAlg->setProperty("RelativePosition", true); mvAlg->executeAsChildAlg(); m_output_message += " Beam center offset: " + Poco::NumberFormatter::format(x_offset) + ", " + Poco::NumberFormatter::format(y_offset) + " m\n"; // m_output_message += " Beam center in real-space: " + // Poco::NumberFormatter::format(-x_offset-beam_ctr_x) // + ", " + Poco::NumberFormatter::format(-y_offset-beam_ctr_y) + " m\n"; g_log.information() << "Moving beam center to " << m_center_x << " " << m_center_y << '\n'; dataWS->mutableRun().addProperty("beam_center_x", m_center_x, "pixel", true); dataWS->mutableRun().addProperty("beam_center_y", m_center_y, "pixel", true); m_output_message += " Beam center: " + Poco::NumberFormatter::format(m_center_x) + ", " + Poco::NumberFormatter::format(m_center_y) + "\n"; }
/** Execute the algorithm. */ void MergeMDFiles::exec() { // clear disk buffer which can remain from previous runs // the existence/ usage of the buffer indicates if the algorithm works with // file based or memory based target workspaces; // pDiskBuffer = NULL; MultipleFileProperty *multiFileProp = dynamic_cast<MultipleFileProperty *>(getPointerToProperty("Filenames")); if (!multiFileProp) { throw std::logic_error( "Filenames property must have MultipleFileProperty type."); } m_Filenames = MultipleFileProperty::flattenFileNames(multiFileProp->operator()()); if (m_Filenames.size() == 0) throw std::invalid_argument("Must specify at least one filename."); std::string firstFile = m_Filenames[0]; std::string outputFile = getProperty("OutputFilename"); m_fileBasedTargetWS = false; if (!outputFile.empty()) { m_fileBasedTargetWS = true; if (Poco::File(outputFile).exists()) throw std::invalid_argument( " File " + outputFile + " already exists. Can not use existing file " "as the target to MergeMD files.\n" + " Use it as one of source files if you want to add MD data to it"); } // Start by loading the first file but just the box structure, no events, and // not file-backed // m_BoxStruct.loadBoxStructure(firstFile, IAlgorithm_sptr loader = createChildAlgorithm("LoadMD", 0.0, 0.05, false); loader->setPropertyValue("Filename", firstFile); loader->setProperty("MetadataOnly", false); loader->setProperty("BoxStructureOnly", true); loader->setProperty("FileBackEnd", false); loader->executeAsChildAlg(); IMDWorkspace_sptr result = (loader->getProperty("OutputWorkspace")); auto firstWS = boost::dynamic_pointer_cast<API::IMDEventWorkspace>(result); if (!firstWS) throw std::runtime_error( "Can not load MDEventWorkspace from initial file " + firstFile); // do the job this->doExecByCloning(firstWS, outputFile); m_OutIWS->setFileNeedsUpdating(false); setProperty("OutputWorkspace", m_OutIWS); }
/// Create workspace that contains the residuals. DataObjects::Workspace2D_sptr PoldiAnalyseResiduals::calculateResidualWorkspace( const DataObjects::Workspace2D_sptr &measured, const DataObjects::Workspace2D_sptr &calculated) { IAlgorithm_sptr minus = createChildAlgorithm("Minus"); minus->setProperty("LHSWorkspace", measured); minus->setProperty("RHSWorkspace", calculated); minus->execute(); MatrixWorkspace_sptr fg = minus->getProperty("OutputWorkspace"); DataObjects::Workspace2D_sptr residuals = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(fg); return residuals; }
/** Set up grouping workspace */ void LoadVulcanCalFile::setupGroupingWorkspace() { // Get the right group option for CreateGroupingWorkspace string groupdetby = ""; switch (m_groupingType) { case VULCAN_OFFSET_BANK: groupdetby = "bank"; break; case VULCAN_OFFSET_MODULE: groupdetby = "Group"; break; case VULCAN_OFFSET_STACK: groupdetby = "All"; break; default: throw runtime_error("Grouping type is not supported. "); break; } // Calling algorithm CreateGroupingWorkspace IAlgorithm_sptr creategroupws = createChildAlgorithm("CreateGroupingWorkspace", -1, -1, true); creategroupws->initialize(); creategroupws->setProperty("InstrumentName", "VULCAN"); creategroupws->setProperty("GroupDetectorsBy", groupdetby); creategroupws->execute(); if (!creategroupws->isExecuted()) throw runtime_error("Unable to create grouping workspace."); m_groupWS = creategroupws->getProperty("OutputWorkspace"); // Set title m_groupWS->setTitle(groupdetby); // Output string WorkspaceName = getPropertyValue("WorkspaceName"); declareProperty(new WorkspaceProperty<GroupingWorkspace>( "OutputGroupingWorkspace", WorkspaceName + "_group", Direction::Output), "Set the output GroupingWorkspace. "); m_groupWS->mutableRun().addProperty("Filename", m_offsetFilename); setProperty("OutputGroupingWorkspace", m_groupWS); return; }
MatrixWorkspace_const_sptr ALCBaselineModellingModel::correctedData() const { if (m_data && (m_data->getNumberHistograms()==3) ) { IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum"); extract->setChild(true); extract->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_data)); extract->setProperty("WorkspaceIndex", 2); extract->setProperty("OutputWorkspace", "__NotUsed__"); extract->execute(); MatrixWorkspace_const_sptr result = extract->getProperty("OutputWorkspace"); return result; } else { return MatrixWorkspace_const_sptr(); } }
/** * Adds a spline interpolation as a step in the calculation for using legacy *correction factor * workspaces. * * @param toInterpolate Pointer to the workspace to interpolate * @param toMatch Name of the workspace to match */ void ApplyPaalmanPings::addInterpolationStep(MatrixWorkspace_sptr toInterpolate, std::string toMatch) { API::BatchAlgorithmRunner::AlgorithmRuntimeProps interpolationProps; interpolationProps["WorkspaceToMatch"] = toMatch; IAlgorithm_sptr interpolationAlg = AlgorithmManager::Instance().create("SplineInterpolation"); interpolationAlg->initialize(); interpolationAlg->setProperty("WorkspaceToInterpolate", toInterpolate->name()); interpolationAlg->setProperty("OutputWorkspace", toInterpolate->name()); m_batchAlgoRunner->addAlgorithm(interpolationAlg, interpolationProps); }
/** * Handles completion of the correction algorithm. * * @param error True of the algorithm failed */ void CalculatePaalmanPings::absCorComplete(bool error) { disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(absCorComplete(bool))); if (error) { emit showMessageBox("Absorption correction calculation failed.\nSee " "Results Log for more details."); return; } // Convert the spectrum axis of correction factors to Q const auto sampleWsName = m_uiForm.dsSample->getCurrentDataName().toStdString(); MatrixWorkspace_sptr sampleWs = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(sampleWsName); WorkspaceGroup_sptr corrections = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>( m_pythonExportWsName); for (size_t i = 0; i < corrections->size(); i++) { MatrixWorkspace_sptr factorWs = boost::dynamic_pointer_cast<MatrixWorkspace>(corrections->getItem(i)); if (!factorWs || !sampleWs) continue; if (getEMode(sampleWs) == "Indirect") { API::BatchAlgorithmRunner::AlgorithmRuntimeProps convertSpecProps; IAlgorithm_sptr convertSpecAlgo = AlgorithmManager::Instance().create("ConvertSpectrumAxis"); convertSpecAlgo->initialize(); convertSpecAlgo->setProperty("InputWorkspace", factorWs); convertSpecAlgo->setProperty("OutputWorkspace", factorWs->getName()); convertSpecAlgo->setProperty("Target", "ElasticQ"); convertSpecAlgo->setProperty("EMode", "Indirect"); try { convertSpecAlgo->setProperty("EFixed", getEFixed(factorWs)); } catch (std::runtime_error &) { } m_batchAlgoRunner->addAlgorithm(convertSpecAlgo); } } // Run algorithm queue connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(postProcessComplete(bool))); m_batchAlgoRunner->executeBatchAsync(); }
/** * @brief MDHWInMemoryLoadingPresenter::transposeWs * * vtkDataSets are usually provided in 3D, trying to create these where one of *those dimensions * might be integrated out leads to empty datasets. To avoid this we reorder the *dimensions in our workspace * prior to visualisation by transposing if if needed. * * @param inHistoWs : An input workspace that may integrated dimensions *anywhere. * @param outCachedHistoWs : Cached histo workspace. To write to if needed. * @return A workspace that can be directly rendered from. Integrated dimensions *are always last. */ void MDHWLoadingPresenter::transposeWs( Mantid::API::IMDHistoWorkspace_sptr &inHistoWs, Mantid::API::IMDHistoWorkspace_sptr &outCachedHistoWs) { using namespace Mantid::API; if (!outCachedHistoWs) { /* Construct dimension indexes list for transpose. We do this by forcing integrated dimensions to be the last in the list. All other orderings are kept. */ std::vector<int> integratedDims; std::vector<int> nonIntegratedDims; for (int i = 0; i < int(inHistoWs->getNumDims()); ++i) { auto dim = inHistoWs->getDimension(i); if (dim->getIsIntegrated()) { integratedDims.push_back(i); } else { nonIntegratedDims.push_back(i); } } std::vector<int> orderedDims = nonIntegratedDims; orderedDims.insert(orderedDims.end(), integratedDims.begin(), integratedDims.end()); /* If there has been any reordering above, then the dimension indexes will no longer be sorted. We use that to determine if we can avoid transposing the workspace. */ if (!std::is_sorted(orderedDims.begin(), orderedDims.end())) { IAlgorithm_sptr alg = AlgorithmManager::Instance().create("TransposeMD"); alg->setChild(true); alg->initialize(); alg->setProperty("InputWorkspace", inHistoWs); alg->setPropertyValue("OutputWorkspace", "dummy"); alg->setProperty("Axes", orderedDims); alg->execute(); IMDHistoWorkspace_sptr visualHistoWs = alg->getProperty("OutputWorkspace"); outCachedHistoWs = visualHistoWs; } else { // No need to transpose anything. outCachedHistoWs = inHistoWs; } } }
API::MatrixWorkspace_sptr HRPDSlabCanAbsorption::runFlatPlateAbsorption() { MatrixWorkspace_sptr m_inputWS = getProperty("InputWorkspace"); double sigma_atten = getProperty("SampleAttenuationXSection"); // in barns double sigma_s = getProperty("SampleScatteringXSection"); // in barns double rho = getProperty("SampleNumberDensity"); // in Angstroms-3 const Material &sampleMaterial = m_inputWS->sample().getMaterial(); if (sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) != 0.0) { if (rho == EMPTY_DBL()) rho = sampleMaterial.numberDensity(); if (sigma_s == EMPTY_DBL()) sigma_s = sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda); if (sigma_atten == EMPTY_DBL()) sigma_atten = sampleMaterial.absorbXSection(NeutronAtom::ReferenceLambda); } else // Save input in Sample with wrong atomic number and name { NeutronAtom neutron(static_cast<uint16_t>(EMPTY_DBL()), static_cast<uint16_t>(0), 0.0, 0.0, sigma_s, 0.0, sigma_s, sigma_atten); Object shape = m_inputWS->sample().getShape(); // copy shape.setMaterial(Material("SetInSphericalAbsorption", neutron, rho)); m_inputWS->mutableSample().setShape(shape); } // Call FlatPlateAbsorption as a Child Algorithm IAlgorithm_sptr childAlg = createChildAlgorithm("FlatPlateAbsorption", 0.0, 0.9); // Pass through all the properties childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_inputWS); childAlg->setProperty<double>("AttenuationXSection", sigma_atten); childAlg->setProperty<double>("ScatteringXSection", sigma_s); childAlg->setProperty<double>("SampleNumberDensity", rho); childAlg->setProperty<int64_t>("NumberOfWavelengthPoints", getProperty("NumberOfWavelengthPoints")); childAlg->setProperty<std::string>("ExpMethod", getProperty("ExpMethod")); // The height and width of the sample holder are standard for HRPD const double HRPDCanHeight = 2.3; const double HRPDCanWidth = 1.8; childAlg->setProperty("SampleHeight", HRPDCanHeight); childAlg->setProperty("SampleWidth", HRPDCanWidth); // Valid values are 0.2,0.5,1.0 & 1.5 - would be nice to have a numeric list // validator const std::string thickness = getPropertyValue("Thickness"); childAlg->setPropertyValue("SampleThickness", thickness); childAlg->executeAsChildAlg(); return childAlg->getProperty("OutputWorkspace"); }
/** Carries out a normalisation based on the integrated count of the monitor over a range * @param inputWorkspace The input workspace * @param outputWorkspace The result workspace */ void NormaliseToMonitor::normaliseByIntegratedCount(API::MatrixWorkspace_sptr inputWorkspace, API::MatrixWorkspace_sptr& outputWorkspace) { // Add up all the bins so it's just effectively a single value with an error IAlgorithm_sptr integrate = createChildAlgorithm("Integration"); integrate->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_monitor); integrate->setProperty("RangeLower",m_integrationMin); integrate->setProperty("RangeUpper",m_integrationMax); integrate->setProperty<bool>("IncludePartialBins",getProperty("IncludePartialBins")); integrate->executeAsChildAlg(); // Get back the result m_monitor = integrate->getProperty("OutputWorkspace"); // Run the divide algorithm explicitly to enable progress reporting IAlgorithm_sptr divide = createChildAlgorithm("Divide",0.0,1.0); divide->setProperty<MatrixWorkspace_sptr>("LHSWorkspace", inputWorkspace); divide->setProperty<MatrixWorkspace_sptr>("RHSWorkspace", m_monitor); divide->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", outputWorkspace); divide->executeAsChildAlg(); // Get back the result outputWorkspace = divide->getProperty("OutputWorkspace"); }
MatrixWorkspace_sptr DgsReduction::loadGroupingFile(const std::string prop) { const std::string propName = prop + "GroupingFile"; const std::string groupFile = this->getProperty(propName); if (groupFile.empty()) { return boost::shared_ptr<MatrixWorkspace>(); } else { try { IAlgorithm_sptr loadGrpFile = this->createChildAlgorithm("LoadDetectorsGroupingFile"); loadGrpFile->setProperty("InputFile", groupFile); loadGrpFile->execute(); return loadGrpFile->getProperty("OutputWorkspace"); } catch (...) { // This must be an old format grouping file. // Set a property to use later. g_log.warning() << "Old format grouping file in use." << std::endl; this->reductionManager->declareProperty(new PropertyWithValue<std::string>( prop + "OldGroupingFilename", groupFile)); return boost::shared_ptr<MatrixWorkspace>(); } } }