/** Uses Polynomial as a ChildAlgorithm to fit the log of the exponential curve * expected for the transmission. * @param[in] WS The single-spectrum workspace to fit * @param[in] order The order of the polynomial from 2 to 6 * @param[out] coeficients of the polynomial. c[0] + c[1]x + c[2]x^2 + ... */ API::MatrixWorkspace_sptr CalculateTransmission::fitPolynomial(API::MatrixWorkspace_sptr WS, int order, std::vector<double> &coeficients) { g_log.notice("Fitting the experimental transmission curve fitpolyno"); double start = m_done; IAlgorithm_sptr childAlg = createChildAlgorithm("Fit", start, m_done = 0.9); auto polyfit = API::FunctionFactory::Instance().createFunction("Polynomial"); polyfit->setAttributeValue("n", order); polyfit->initialize(); childAlg->setProperty("Function", polyfit); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS); childAlg->setProperty("Minimizer", "Levenberg-MarquardtMD"); childAlg->setProperty("CreateOutput", true); childAlg->setProperty("IgnoreInvalidData", true); childAlg->executeAsChildAlg(); std::string fitStatus = childAlg->getProperty("OutputStatus"); if (fitStatus != "success") { g_log.error("Unable to successfully fit the data: " + fitStatus); throw std::runtime_error("Unable to successfully fit the data"); } // Only get to here if successful coeficients.resize(order + 1); for (int i = 0; i <= order; i++) { coeficients[i] = polyfit->getParameter(i); } return this->extractSpectra(childAlg->getProperty("OutputWorkspace"), std::vector<size_t>(1, 1)); }
MatrixWorkspace_sptr DgsReduction::loadHardMask() { const std::string hardMask = this->getProperty("HardMaskFile"); if (hardMask.empty()) { return boost::shared_ptr<MatrixWorkspace>(); } else { IAlgorithm_sptr loadMask; bool castWorkspace = false; if (boost::ends_with(hardMask, ".nxs")) { loadMask = this->createChildAlgorithm("Load"); loadMask->setProperty("Filename", hardMask); } else { const std::string instName = this->reductionManager->getProperty("InstrumentName"); loadMask = this->createChildAlgorithm("LoadMask"); loadMask->setProperty("Instrument", instName); loadMask->setProperty("InputFile", hardMask); castWorkspace = true; } loadMask->execute(); if (castWorkspace) { MaskWorkspace_sptr tmp = loadMask->getProperty("OutputWorkspace"); return boost::dynamic_pointer_cast<MatrixWorkspace>(tmp); } return loadMask->getProperty("OutputWorkspace"); } }
/** Uses 'Linear' as a ChildAlgorithm to fit the log of the exponential curve * expected for the transmission. * @param[in] WS The single-spectrum workspace to fit * @param[out] grad The single-spectrum workspace to fit * @param[out] offset The single-spectrum workspace to fit * @return A workspace containing the fit * @throw runtime_error if the Linear algorithm fails during execution */ API::MatrixWorkspace_sptr CalculateTransmission::fitData(API::MatrixWorkspace_sptr WS, double &grad, double &offset) { g_log.information("Fitting the experimental transmission curve"); double start = m_done; IAlgorithm_sptr childAlg = createChildAlgorithm("Fit", start, m_done = 0.9); auto linearBack = API::FunctionFactory::Instance().createFunction("LinearBackground"); childAlg->setProperty("Function", linearBack); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS); childAlg->setProperty("Minimizer", "Levenberg-MarquardtMD"); childAlg->setProperty("CreateOutput", true); childAlg->setProperty("IgnoreInvalidData", true); childAlg->executeAsChildAlg(); std::string fitStatus = childAlg->getProperty("OutputStatus"); if (fitStatus != "success") { g_log.error("Unable to successfully fit the data: " + fitStatus); throw std::runtime_error("Unable to successfully fit the data"); } // Only get to here if successful offset = linearBack->getParameter(0); grad = linearBack->getParameter(1); return this->extractSpectra(childAlg->getProperty("OutputWorkspace"), std::vector<size_t>(1, 1)); }
/** * Creates a single-spectrum workspace filled with function values for given X values * @param func :: Function to calculate values * @param xValues :: X values to use * @return Single-spectrum workspace with calculated function values */ MatrixWorkspace_sptr createWsFromFunction(IFunction_const_sptr func, const std::vector<double>& xValues) { auto inputWs = boost::dynamic_pointer_cast<MatrixWorkspace>( WorkspaceFactory::Instance().create("Workspace2D", 1, xValues.size(), xValues.size())); inputWs->dataX(0) = xValues; IAlgorithm_sptr fit = AlgorithmManager::Instance().create("Fit"); fit->setChild(true); // Don't want workspace in the ADS fit->setProperty("Function", func->asString()); fit->setProperty("InputWorkspace", inputWs); fit->setProperty("MaxIterations", 0); // Don't want to fit, just calculate output workspace fit->setProperty("CreateOutput", true); fit->execute(); MatrixWorkspace_sptr fitOutput = fit->getProperty("OutputWorkspace"); IAlgorithm_sptr extract = AlgorithmManager::Instance().create("ExtractSingleSpectrum"); extract->setChild(true); // Don't want workspace in the ADS extract->setProperty("InputWorkspace", fitOutput); extract->setProperty("WorkspaceIndex", 1); // "Calc" extract->setPropertyValue("OutputWorkspace", "__NotUsed"); extract->execute(); return extract->getProperty("OutputWorkspace"); }
/** * Integrate each spectra to get the number of counts * @param inputWS :: The workspace to integrate * @param indexMin :: The lower bound of the spectra to integrate * @param indexMax :: The upper bound of the spectra to integrate * @param lower :: The lower bound * @param upper :: The upper bound * @param outputWorkspace2D :: set to true to output a workspace 2D even if the input is an EventWorkspace * @returns A workspace containing the integrated counts */ MatrixWorkspace_sptr DetectorDiagnostic::integrateSpectra(MatrixWorkspace_sptr inputWS, const int indexMin, const int indexMax, const double lower, const double upper, const bool outputWorkspace2D) { g_log.debug() << "Integrating input spectra.\n"; // If the input spectra only has one bin, assume it has been integrated already // but we need to pass it to the algorithm so that a copy of the input workspace is // actually created to use for further calculations // get percentage completed estimates for now, t0 and when we've finished t1 double t0 = m_fracDone, t1 = advanceProgress(RTGetTotalCounts); IAlgorithm_sptr childAlg = createChildAlgorithm("Integration", t0, t1 ); childAlg->setProperty( "InputWorkspace", inputWS ); childAlg->setProperty( "StartWorkspaceIndex", indexMin ); childAlg->setProperty( "EndWorkspaceIndex", indexMax ); // pass inputed values straight to this integration trusting the checking done there childAlg->setProperty("RangeLower", lower ); childAlg->setProperty("RangeUpper", upper); childAlg->setPropertyValue("IncludePartialBins", "1"); childAlg->executeAsChildAlg(); // Convert to 2D if desired, and if the input was an EventWorkspace. MatrixWorkspace_sptr outputW = childAlg->getProperty("OutputWorkspace"); MatrixWorkspace_sptr finalOutputW = outputW; if (outputWorkspace2D && boost::dynamic_pointer_cast<EventWorkspace>(outputW)) { g_log.debug() << "Converting output Event Workspace into a Workspace2D." << std::endl; childAlg = createChildAlgorithm("ConvertToMatrixWorkspace", t0, t1 ); childAlg->setProperty("InputWorkspace", outputW); childAlg->executeAsChildAlg(); finalOutputW = childAlg->getProperty("OutputWorkspace"); } return finalOutputW; }
/** 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"); }
/** Calculate the integral asymmetry for a pair of workspaces (red & green). * @param ws_red :: The red workspace * @param ws_green :: The green 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_red, MatrixWorkspace_sptr ws_green, double &Y, double &E) { if (!m_int) { // "Differential asymmetry" MatrixWorkspace_sptr tmpWS = WorkspaceFactory::Instance().create( ws_red, 1, ws_red->readX(0).size(), ws_red->readY(0).size()); for (size_t i = 0; i < tmpWS->dataY(0).size(); i++) { double FNORM = ws_green->readY(0)[i] + ws_red->readY(0)[i]; FNORM = FNORM != 0.0 ? 1.0 / FNORM : 1.0; double BNORM = ws_green->readY(1)[i] + ws_red->readY(1)[i]; BNORM = BNORM != 0.0 ? 1.0 / BNORM : 1.0; double ZF = (ws_green->readY(0)[i] - ws_red->readY(0)[i]) * FNORM; double ZB = (ws_green->readY(1)[i] - ws_red->readY(1)[i]) * BNORM; tmpWS->dataY(0)[i] = ZB - ZF; tmpWS->dataE(0)[i] = (1.0 + ZF * ZF) * FNORM + (1.0 + ZB * ZB) * BNORM; } IAlgorithm_sptr integr = createChildAlgorithm("Integration"); integr->setProperty("InputWorkspace", tmpWS); integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); MatrixWorkspace_sptr out = integr->getProperty("OutputWorkspace"); Y = out->readY(0)[0] / static_cast<double>(tmpWS->dataY(0).size()); E = out->readE(0)[0] / static_cast<double>(tmpWS->dataY(0).size()); } else { // "Integral asymmetry" IAlgorithm_sptr integr = createChildAlgorithm("Integration"); integr->setProperty("InputWorkspace", ws_red); integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); MatrixWorkspace_sptr intWS_red = integr->getProperty("OutputWorkspace"); integr = createChildAlgorithm("Integration"); integr->setProperty("InputWorkspace", ws_green); integr->setProperty("RangeLower", m_minTime); integr->setProperty("RangeUpper", m_maxTime); integr->execute(); MatrixWorkspace_sptr intWS_green = integr->getProperty("OutputWorkspace"); double YIF = (intWS_green->readY(0)[0] - intWS_red->readY(0)[0]) / (intWS_green->readY(0)[0] + intWS_red->readY(0)[0]); double YIB = (intWS_green->readY(1)[0] - intWS_red->readY(1)[0]) / (intWS_green->readY(1)[0] + intWS_red->readY(1)[0]); Y = YIB - YIF; double VARIF = (1.0 + YIF * YIF) / (intWS_green->readY(0)[0] + intWS_red->readY(0)[0]); double VARIB = (1.0 + YIB * YIB) / (intWS_green->readY(1)[0] + intWS_red->readY(1)[0]); E = sqrt(VARIF + VARIB); } }
void ALCDataLoadingPresenter::updateAvailableInfo() { Workspace_sptr loadedWs; double firstGoodData = 0, timeZero = 0; try //... to load the first run { IAlgorithm_sptr load = AlgorithmManager::Instance().create("LoadMuonNexus"); load->setChild(true); // Don't want workspaces in the ADS load->setProperty("Filename", m_view->firstRun()); // We need logs only but we have to use LoadMuonNexus // (can't use LoadMuonLogs as not all the logs would be // loaded), so we load the minimum amount of data, i.e., one spectrum load->setPropertyValue("SpectrumMin", "1"); load->setPropertyValue("SpectrumMax", "1"); load->setPropertyValue("OutputWorkspace", "__NotUsed"); load->execute(); loadedWs = load->getProperty("OutputWorkspace"); firstGoodData = load->getProperty("FirstGoodData"); timeZero = load->getProperty("TimeZero"); } catch (...) { m_view->setAvailableLogs(std::vector<std::string>()); // Empty logs list m_view->setAvailablePeriods( std::vector<std::string>()); // Empty period list m_view->setTimeLimits(0, 0); // "Empty" time limits return; } // Set logs MatrixWorkspace_const_sptr ws = MuonAnalysisHelper::firstPeriod(loadedWs); std::vector<std::string> logs; const auto &properties = ws->run().getProperties(); for (auto it = properties.begin(); it != properties.end(); ++it) { logs.push_back((*it)->name()); } m_view->setAvailableLogs(logs); // Set periods size_t numPeriods = MuonAnalysisHelper::numPeriods(loadedWs); std::vector<std::string> periods; for (size_t i = 0; i < numPeriods; i++) { std::stringstream buffer; buffer << i + 1; periods.push_back(buffer.str()); } m_view->setAvailablePeriods(periods); // Set time limits if this is the first data loaded (will both be zero) if (auto timeLimits = m_view->timeRange()) { if (std::abs(timeLimits->first) < 0.0001 && std::abs(timeLimits->second) < 0.0001) { m_view->setTimeLimits(firstGoodData - timeZero, ws->readX(0).back()); } } // Update number of detectors for this new first run m_numDetectors = ws->getInstrument()->getNumberDetectors(); }
/** Loads one run and applies dead-time corrections and detector grouping if * required * @param runNumber :: [input] Run number specifying run to load * @return :: Loaded workspace */ Workspace_sptr PlotAsymmetryByLogValue::doLoad(size_t runNumber) { // Get complete run name std::ostringstream fn, fnn; fnn << std::setw(m_filenameZeros) << std::setfill('0') << runNumber; fn << m_filenameBase << fnn.str() << m_filenameExt; // Check if file exists if (!Poco::File(fn.str()).exists()) { m_log.warning() << "File " << fn.str() << " not found" << std::endl; return Workspace_sptr(); } // Load run IAlgorithm_sptr load = createChildAlgorithm("LoadMuonNexus"); load->setPropertyValue("Filename", fn.str()); load->execute(); Workspace_sptr loadedWs = load->getProperty("OutputWorkspace"); // Check if dead-time corrections have to be applied if (m_dtcType != "None") { Workspace_sptr deadTimes; if (m_dtcType == "FromSpecifiedFile") { // Load corrections from file deadTimes = loadCorrectionsFromFile(m_dtcFile); } else { // Load corrections from run deadTimes = load->getProperty("DeadTimeTable"); } if (!deadTimes) { throw std::runtime_error("Couldn't load dead times"); } applyDeadtimeCorr(loadedWs, deadTimes); } // Group detectors Workspace_sptr grouping; if (m_forward_list.empty() && m_backward_list.empty()) { // Auto group grouping = load->getProperty("DetectorGroupingTable"); } else { // Custom grouping grouping = createCustomGrouping(m_forward_list, m_backward_list); } if (!grouping) throw std::runtime_error("Couldn't load detector grouping"); // Apply grouping groupDetectors(loadedWs, grouping); return loadedWs; }
/** * Uses linear algorithm to do the fitting. * @param histogram the histogram to fit * @param background an output variable for the calculated background * @param variance an output variable for background's variance, currently always * zero. * @param startX an X value in the first bin to be included in the fit * @param endX an X value in the last bin to be included in the fit */ void CalculateFlatBackground::LinearFit( const HistogramData::Histogram &histogram, double &background, double &variance, const double startX, const double endX) { MatrixWorkspace_sptr WS = WorkspaceFactory::Instance().create( "Workspace2D", 1, histogram.x().size(), histogram.y().size()); WS->setHistogram(0, histogram); IAlgorithm_sptr childAlg = createChildAlgorithm("Fit"); IFunction_sptr func = API::FunctionFactory::Instance().createFunction("LinearBackground"); childAlg->setProperty<IFunction_sptr>("Function", func); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS); childAlg->setProperty<bool>("CreateOutput", true); childAlg->setProperty<int>("WorkspaceIndex", 0); childAlg->setProperty<double>("StartX", startX); childAlg->setProperty<double>("EndX", endX); // Default minimizer doesn't work properly even on the easiest cases, // so Levenberg-MarquardtMD is used instead childAlg->setProperty<std::string>("Minimizer", "Levenberg-MarquardtMD"); childAlg->executeAsChildAlg(); std::string outputStatus = childAlg->getProperty("OutputStatus"); if (outputStatus != "success") { g_log.warning("Unable to successfully fit the data: " + outputStatus); background = -1; return; } Mantid::API::ITableWorkspace_sptr output = childAlg->getProperty("OutputParameters"); // Find rows with parameters we are after size_t rowA0, rowA1; output->find(static_cast<std::string>("A0"), rowA0, 0); output->find(static_cast<std::string>("A1"), rowA1, 0); // Linear function is defined as A0 + A1*x const double intercept = output->cell<double>(rowA0, 1); const double slope = output->cell<double>(rowA1, 1); const double centre = (startX + endX) / 2.0; // Calculate the value of the flat background by taking the value at the // centre point of the fit background = slope * centre + intercept; // ATM we don't calculate the error here. variance = 0; }
/** * Loads an empty instrument and returns a pointer to the workspace. * * Optionally loads an IPF if a reflection was provided. * * @param instrumentName Name of an inelastic indiretc instrument (IRIS, OSIRIN, *TOSCA, VESUVIO) * @param reflection Reflection mode to load parameters for (diffspec or *diffonly) */ MatrixWorkspace_sptr IndirectDiffractionReduction::loadInstrument(std::string instrumentName, std::string reflection) { std::string idfPath = Mantid::Kernel::ConfigService::Instance().getString( "instrumentDefinition.directory"); std::string parameterFilename = idfPath + instrumentName + "_Definition.xml"; IAlgorithm_sptr loadAlg = AlgorithmManager::Instance().create("LoadEmptyInstrument"); loadAlg->setChild(true); loadAlg->initialize(); loadAlg->setProperty("Filename", parameterFilename); loadAlg->setProperty("OutputWorkspace", "__InDiff_Inst"); loadAlg->execute(); MatrixWorkspace_sptr instWorkspace = loadAlg->getProperty("OutputWorkspace"); // Load parameter file if a reflection was given if (!reflection.empty()) { std::string ipfFilename = idfPath + instrumentName + "_diffraction_" + reflection + "_Parameters.xml"; IAlgorithm_sptr loadParamAlg = AlgorithmManager::Instance().create("LoadParameterFile"); loadParamAlg->setChild(true); loadParamAlg->initialize(); loadParamAlg->setProperty("Filename", ipfFilename); loadParamAlg->setProperty("Workspace", instWorkspace); loadParamAlg->execute(); } return instWorkspace; }
/** Execute the algorithm. */ void ConvertDiffCal::exec() { OffsetsWorkspace_const_sptr offsetsWS = getProperty("OffsetsWorkspace"); // initial setup of new style config ITableWorkspace_sptr configWksp = boost::make_shared<TableWorkspace>(); configWksp->addColumn("int", "detid"); configWksp->addColumn("double", "difc"); configWksp->addColumn("double", "difa"); configWksp->addColumn("double", "tzero"); // create values in the table const size_t numberOfSpectra = offsetsWS->getNumberHistograms(); Progress progress(this, 0.0, 1.0, numberOfSpectra); for (size_t i = 0; i < numberOfSpectra; ++i) { API::TableRow newrow = configWksp->appendRow(); newrow << static_cast<int>(getDetID(offsetsWS, i)); newrow << calculateDIFC(offsetsWS, i); newrow << 0.; // difa newrow << 0.; // tzero progress.report(); } // sort the results IAlgorithm_sptr sortTable = createChildAlgorithm("SortTableWorkspace"); sortTable->setProperty("InputWorkspace", configWksp); sortTable->setProperty("OutputWorkspace", configWksp); sortTable->setPropertyValue("Columns", "detid"); sortTable->executeAsChildAlg(); // copy over the results configWksp = sortTable->getProperty("OutputWorkspace"); setProperty("OutputWorkspace", configWksp); }
/** * This function gets the input workspace. In the case for a RebinnedOutput * workspace, it must be cleaned before proceeding. Other workspaces are * untouched. * @return the input workspace, cleaned if necessary */ MatrixWorkspace_sptr Integration::getInputWorkspace() { MatrixWorkspace_sptr temp = getProperty("InputWorkspace"); if (temp->id() == "RebinnedOutput") { // Clean the input workspace in the RebinnedOutput case for nan's and // inf's in order to treat the data correctly later. IAlgorithm_sptr alg = this->createChildAlgorithm("ReplaceSpecialValues"); alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", temp); std::string outName = "_" + temp->getName() + "_clean"; alg->setProperty("OutputWorkspace", outName); alg->setProperty("NaNValue", 0.0); alg->setProperty("NaNError", 0.0); alg->setProperty("InfinityValue", 0.0); alg->setProperty("InfinityError", 0.0); alg->executeAsChildAlg(); temp = alg->getProperty("OutputWorkspace"); } // To integrate point data it will be converted to histograms if (!temp->isHistogramData()) { auto alg = this->createChildAlgorithm("ConvertToHistogram"); alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", temp); std::string outName = "_" + temp->getName() + "_histogram"; alg->setProperty("OutputWorkspace", outName); alg->executeAsChildAlg(); temp = alg->getProperty("OutputWorkspace"); temp->setDistribution(true); } return temp; }
/** Correct an instrument component by shifting it vertically or * rotating it around the sample. * * @param instructions :: processing instructions defining the detectors of * interest * @param inputWS :: the input workspace * @param twoTheta :: the angle to move detectors to * @return :: the corrected workspace */ MatrixWorkspace_sptr ReflectometryReductionOneAuto2::correctDetectorPositions( const std::string &instructions, MatrixWorkspace_sptr inputWS, const double twoTheta) { auto detectorsOfInterest = getDetectorNames(instructions, inputWS); // Detectors of interest may be empty. This happens for instance when we input // a workspace that was previously reduced using this algorithm. In this case, // we shouldn't correct the detector positions if (detectorsOfInterest.empty()) return inputWS; const std::set<std::string> detectorSet(detectorsOfInterest.begin(), detectorsOfInterest.end()); const std::string correctionType = getProperty("DetectorCorrectionType"); MatrixWorkspace_sptr corrected = inputWS; for (const auto &detector : detectorSet) { IAlgorithm_sptr alg = createChildAlgorithm("SpecularReflectionPositionCorrect"); alg->setProperty("InputWorkspace", corrected); alg->setProperty("TwoTheta", twoTheta); alg->setProperty("DetectorCorrectionType", correctionType); alg->setProperty("DetectorComponentName", detector); alg->execute(); corrected = alg->getProperty("OutputWorkspace"); } return corrected; }
/** * It's assumed that both the flux reference files are simple Nexus * files since they have to produced by hand by the instrument * scientists. A simple Load algorithm should suffice. */ MatrixWorkspace_sptr SANSBeamFluxCorrection::loadReference() { const std::string referenceFluxFile = getPropertyValue("ReferenceFluxFilename"); Poco::Path path(referenceFluxFile); const std::string entryName = "SANSBeamFluxCorrection_" + path.getBaseName(); std::string fluxRefWSName = "__beam_flux_reference_" + path.getBaseName(); // Load reference flux as needed MatrixWorkspace_sptr fluxRefWS; if (m_reductionManager->existsProperty(entryName)) { fluxRefWS = m_reductionManager->getProperty(entryName); fluxRefWSName = m_reductionManager->getPropertyValue(entryName); m_output_message += " | Using flux reference " + referenceFluxFile + "\n"; } else { IAlgorithm_sptr loadAlg = createChildAlgorithm("Load"); loadAlg->setProperty("Filename", referenceFluxFile); loadAlg->executeAsChildAlg(); Workspace_sptr tmpWS = loadAlg->getProperty("OutputWorkspace"); fluxRefWS = boost::dynamic_pointer_cast<MatrixWorkspace>(tmpWS); m_output_message += " | Loaded flux reference " + referenceFluxFile + "\n"; // Keep the reference data for later use AnalysisDataService::Instance().addOrReplace(fluxRefWSName, fluxRefWS); m_reductionManager->declareProperty( new WorkspaceProperty<>(entryName, fluxRefWSName, Direction::InOut)); m_reductionManager->setPropertyValue(entryName, fluxRefWSName); m_reductionManager->setProperty(entryName, fluxRefWS); } return fluxRefWS; }
/** Makes a workspace with the total solid angle all the detectors in each spectrum cover from the sample * note returns an empty shared pointer on failure, uses the SolidAngle algorithm * @param firstSpec :: the index number of the first histogram to analyse * @param lastSpec :: the index number of the last histogram to analyse * @return A pointer to the workspace (or an empty pointer) */ API::MatrixWorkspace_sptr MedianDetectorTest::getSolidAngles(int firstSpec, int lastSpec ) { g_log.debug("Calculating solid angles"); // get percentage completed estimates for now, t0 and when we've finished t1 double t0 = m_fracDone, t1 = advanceProgress(RTGetSolidAngle); IAlgorithm_sptr childAlg = createChildAlgorithm("SolidAngle", t0, t1, true); childAlg->setProperty( "InputWorkspace", m_inputWS); childAlg->setProperty( "StartWorkspaceIndex", firstSpec ); childAlg->setProperty( "EndWorkspaceIndex", lastSpec ); try { // Execute the Child Algorithm, it could throw a runtime_error at this point which would abort execution childAlg->execute(); if ( ! childAlg->isExecuted() ) { throw std::runtime_error("Unexpected problem calculating solid angles"); } } //catch all exceptions because the solid angle calculation is optional catch(std::exception&) { g_log.warning( "Precision warning: Can't find detector geometry " + name() + " will continue with the solid angles of all spectra set to the same value" ); failProgress(RTGetSolidAngle); //The return is an empty workspace pointer, which must be handled by the calling function MatrixWorkspace_sptr empty; //function returns normally return empty; } return childAlg->getProperty("OutputWorkspace"); }
void SphericalAbsorption::exec() { // Retrieve the input workspace m_inputWS = getProperty("InputWorkspace"); // Get the input parameters retrieveBaseProperties(); // Create the output workspace MatrixWorkspace_sptr correctionFactors = WorkspaceFactory::Instance().create(m_inputWS); correctionFactors->isDistribution(true); // The output of this is a distribution correctionFactors->setYUnit(""); // Need to explicitly set YUnit to nothing correctionFactors->setYUnitLabel("Attenuation factor"); double m_sphRadius = getProperty("SphericalSampleRadius"); // in cm IAlgorithm_sptr anvred = createSubAlgorithm("AnvredCorrection"); anvred->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_inputWS); anvred->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", correctionFactors); anvred->setProperty("PreserveEvents", true); anvred->setProperty("ReturnTransmissionOnly", true); anvred->setProperty("LinearScatteringCoef", m_refAtten); anvred->setProperty("LinearAbsorptionCoef", m_scattering); anvred->setProperty("Radius", m_sphRadius); anvred->executeAsSubAlg(); // Get back the result correctionFactors = anvred->getProperty("OutputWorkspace"); setProperty("OutputWorkspace", correctionFactors); }
void ALCDataLoadingPresenter::updateAvailableLogs() { Workspace_sptr loadedWs; try //... to load the first run { IAlgorithm_sptr load = AlgorithmManager::Instance().create("LoadMuonNexus"); load->setChild(true); // Don't want workspaces in the ADS load->setProperty("Filename", m_view->firstRun()); // Don't load any data - we need logs only load->setPropertyValue("SpectrumMin","0"); load->setPropertyValue("SpectrumMax","0"); load->setPropertyValue("OutputWorkspace", "__NotUsed"); load->execute(); loadedWs = load->getProperty("OutputWorkspace"); } catch(...) { m_view->setAvailableLogs(std::vector<std::string>()); // Empty logs list return; } MatrixWorkspace_const_sptr ws = MuonAnalysisHelper::firstPeriod(loadedWs); std::vector<std::string> logs; const auto& properties = ws->run().getProperties(); for(auto it = properties.begin(); it != properties.end(); ++it) { logs.push_back((*it)->name()); } m_view->setAvailableLogs(logs); }
/** Executes the algorithm * @throw Exception::FileError If the calibration file cannot be opened and read successfully * @throw Exception::InstrumentDefinitionError If unable to obtain the source-sample distance */ void CaltoDspacemap::exec() { MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace"); const std::string DFileName = getProperty("DspacemapFile"); const std::string calFileName = getProperty("CalibrationFile"); progress(0.0,"Reading calibration file"); IAlgorithm_sptr alg = createSubAlgorithm("LoadCalFile", 0.0, 0.5, true); alg->setProperty("InputWorkspace", inputWS); alg->setPropertyValue("CalFilename", calFileName); alg->setProperty<bool>("MakeGroupingWorkspace", false); alg->setProperty<bool>("MakeOffsetsWorkspace", true); alg->setProperty<bool>("MakeMaskWorkspace", false); alg->setPropertyValue("WorkspaceName", "temp"); alg->executeAsSubAlg(); OffsetsWorkspace_sptr offsetsWS; offsetsWS = alg->getProperty("OutputOffsetsWorkspace"); progress(0.5,"Saving dspacemap file"); alg = createSubAlgorithm("SaveDspacemap", 0.5, 1.0, true); alg->setPropertyValue("DspacemapFile", DFileName); alg->setProperty<int>("PadDetID", getProperty("PadDetID")); alg->setProperty("InputWorkspace", offsetsWS); alg->executeAsSubAlg(); }
/** Multiply or divide the input workspace as specified by the user * @param[in] lhs the first input workspace * @param[in] rhs the last input workspace * @param[in] algName the name of the algorithm to use on the input files * @param[out] result the output workspace * @throw NotFoundError if requested algorithm requested doesn't exist * @throw runtime_error if algorithm encounters an error */ void CorrectToFile::doWkspAlgebra(API::MatrixWorkspace_sptr lhs, API::MatrixWorkspace_sptr rhs, const std::string &algName, API::MatrixWorkspace_sptr &result) { g_log.information() << "Initalising the algorithm " << algName << '\n'; progress(LOAD_TIME, "Applying correction"); IAlgorithm_sptr algebra = createChildAlgorithm(algName, LOAD_TIME, 1.0); algebra->setProperty("LHSWorkspace", lhs); algebra->setProperty("RHSWorkspace", rhs); algebra->setProperty("OutputWorkspace", result); try { algebra->execute(); } catch (std::runtime_error &) { g_log.warning() << "Error encountered while running algorithm " << algName << '\n'; g_log.error() << "Correction file " << getPropertyValue("Filename") + " can't be used to correct workspace " << getPropertyValue("WorkspaceToCorrect") << '\n'; g_log.error() << "Mismatched number of spectra?\n"; throw std::runtime_error("Correct to file failed, see log for details"); } result = algebra->getProperty("OutputWorkspace"); g_log.debug() << algName << " complete\n"; }
/** * Correct loaded data for dead times (if present) and group * @param loadedData :: [input] Load result * @param grouping :: [input] Grouping to use * @returns :: Workspace containing processed data */ Workspace_sptr MuonAnalysisDataLoader::correctAndGroup( const Muon::LoadResult &loadedData, const Mantid::API::Grouping &grouping) const { ITableWorkspace_sptr deadTimes; try { // to get the dead time correction deadTimes = getDeadTimesTable(loadedData); } catch (const std::exception &e) { // If dead correction wasn't applied we can still continue, though should // make user aware of that g_log.warning() << "No dead time correction applied: " << e.what() << "\n"; } // Now apply DTC, if used, and grouping Workspace_sptr correctedGroupedWS; IAlgorithm_sptr alg = AlgorithmManager::Instance().createUnmanaged("MuonProcess"); alg->initialize(); alg->setProperty("InputWorkspace", loadedData.loadedWorkspace); alg->setProperty("Mode", "CorrectAndGroup"); if (deadTimes) { alg->setProperty("ApplyDeadTimeCorrection", true); alg->setProperty("DeadTimeTable", deadTimes); } alg->setProperty("LoadedTimeZero", loadedData.timeZero); alg->setProperty("DetectorGroupingTable", grouping.toTable()); alg->setChild(true); alg->setPropertyValue("OutputWorkspace", "__NotUsed"); alg->execute(); correctedGroupedWS = alg->getProperty("OutputWorkspace"); return correctedGroupedWS; }
/** Call MaskBins * @param dataws :: MatrixWorkspace to mask bins for */ void MaskBinsFromTable::maskBins(API::MatrixWorkspace_sptr dataws) { bool firstloop = true; API::MatrixWorkspace_sptr outputws; size_t numcalls = m_xminVec.size(); g_log.debug() << "There will be " << numcalls << " calls to MaskBins" << "\n"; for (size_t ib = 0; ib < numcalls; ++ib) { // Construct algorithm IAlgorithm_sptr maskbins = this->createChildAlgorithm("MaskBins", 0, 0.3, true); maskbins->initialize(); // Set properties g_log.debug() << "Input to MaskBins: SpetraList = '" << m_spectraVec[ib] << "'; Xmin = " << m_xminVec[ib] << ", Xmax = " << m_xmaxVec[ib] << ".\n"; if (firstloop) { maskbins->setProperty("InputWorkspace", dataws); firstloop = false; } else { if (!outputws) throw runtime_error("Programming logic error."); maskbins->setProperty("InputWorkspace", outputws); } maskbins->setProperty("OutputWorkspace", this->getPropertyValue("OutputWorkspace")); maskbins->setPropertyValue("SpectraList", m_spectraVec[ib]); maskbins->setProperty("XMin", m_xminVec[ib]); maskbins->setProperty("XMax", m_xmaxVec[ib]); bool isexec = maskbins->execute(); if (!isexec) { stringstream errmsg; errmsg << "MaskBins() is not executed for row " << ib << "\n"; g_log.error(errmsg.str()); throw std::runtime_error(errmsg.str()); } else { g_log.debug("MaskBins() is executed successfully."); } outputws = maskbins->getProperty("OutputWorkspace"); if (!outputws) { stringstream errmsg; errmsg << "OutputWorkspace cannot be obtained from algorithm row " << ib << ". "; g_log.error(errmsg.str()); throw std::runtime_error(errmsg.str()); } } // g_log.debug() << "About to set to output." << "\n"; setProperty("OutputWorkspace", outputws); return; }
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>(); } } }
/** Load SPICE data to Matrix workspace * @brief ConvertCWSDExpToMomentum::loadSpiceData * @param filename * @param loaded * @param errmsg * @return */ API::MatrixWorkspace_sptr ConvertCWSDExpToMomentum::loadSpiceData(const std::string &filename, bool &loaded, std::string &errmsg) { // Init output API::MatrixWorkspace_sptr dataws; errmsg = ""; // Load SPICE file try { IAlgorithm_sptr loader = createChildAlgorithm("LoadSpiceXML2DDet"); loader->initialize(); loader->setProperty("Filename", filename); std::vector<size_t> sizelist(2); sizelist[0] = 256; sizelist[1] = 256; loader->setProperty("DetectorGeometry", sizelist); loader->setProperty("LoadInstrument", true); loader->execute(); dataws = loader->getProperty("OutputWorkspace"); loaded = static_cast<bool>(dataws); } catch (std::runtime_error &runerror) { loaded = false; errmsg = runerror.what(); } return dataws; }
/** * Extracts multiple spectra from a Workspace2D into a new workspaces, using *SumSpectra. * * @param ws :: The workspace containing the spectrum to extract * @param indices :: The workspace index of the spectrum to extract * * @returns a Workspace2D containing the extracted spectrum * @throws runtime_error if the ExtractSingleSpectrum algorithm fails during *execution */ API::MatrixWorkspace_sptr CalculateTransmission::extractSpectra(API::MatrixWorkspace_sptr ws, const std::vector<size_t> &indices) { // Compile a comma separated list of indices that we can pass to SumSpectra. std::vector<std::string> indexStrings(indices.size()); // A bug in boost 1.53: https://svn.boost.org/trac/boost/ticket/7421 // means that lexical_cast cannot be used directly as the call is ambiguous // so we need to define a function pointer that can resolve the overloaded // lexical_cast function typedef std::string (*from_size_t)(const size_t &); std::transform(indices.begin(), indices.end(), indexStrings.begin(), (from_size_t)boost::lexical_cast<std::string, size_t>); const std::string commaIndexList = boost::algorithm::join(indexStrings, ","); double start = m_done; IAlgorithm_sptr childAlg = createChildAlgorithm("SumSpectra", start, m_done += 0.1); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", ws); childAlg->setPropertyValue("ListOfWorkspaceIndices", commaIndexList); childAlg->executeAsChildAlg(); // Only get to here if successful return childAlg->getProperty("OutputWorkspace"); }
/** 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; }
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(); }
/** Pulls the monitor spectrum out of a larger workspace * @param WS :: The workspace containing the spectrum to extract * @param index :: The index of the spectrum to extract * @returns A workspace containing the single spectrum requested */ API::MatrixWorkspace_sptr NormaliseToMonitor::extractMonitorSpectrum(API::MatrixWorkspace_sptr WS, const std::size_t index) { IAlgorithm_sptr childAlg = createChildAlgorithm("ExtractSingleSpectrum"); childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS); childAlg->setProperty<int>("WorkspaceIndex", static_cast<int>(index)); childAlg->executeAsChildAlg(); MatrixWorkspace_sptr outWS = childAlg->getProperty("OutputWorkspace"); IAlgorithm_sptr alg = createChildAlgorithm("ConvertToMatrixWorkspace"); alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", outWS); alg->executeAsChildAlg(); outWS = alg->getProperty("OutputWorkspace"); // Only get to here if successful return outWS; }
/** * Applies offset, crops and rebin the workspace according to specified params. * @param ws :: Workspace to correct * @param loadedTimeZero :: Time zero of the data, so we can calculate the * offset * @return Corrected workspace */ MatrixWorkspace_sptr MuonLoad::correctWorkspace(MatrixWorkspace_sptr ws, double loadedTimeZero) { // Offset workspace, if need to double timeZero = getProperty("TimeZero"); if (timeZero != EMPTY_DBL()) { double offset = loadedTimeZero - timeZero; IAlgorithm_sptr changeOffset = createChildAlgorithm("ChangeBinOffset"); changeOffset->setProperty("InputWorkspace", ws); changeOffset->setProperty("Offset", offset); changeOffset->execute(); ws = changeOffset->getProperty("OutputWorkspace"); } // Crop workspace, if need to double Xmin = getProperty("Xmin"); double Xmax = getProperty("Xmax"); if (Xmin != EMPTY_DBL() || Xmax != EMPTY_DBL()) { IAlgorithm_sptr crop = createChildAlgorithm("CropWorkspace"); crop->setProperty("InputWorkspace", ws); if (Xmin != EMPTY_DBL()) crop->setProperty("Xmin", Xmin); if (Xmax != EMPTY_DBL()) crop->setProperty("Xmax", Xmax); crop->execute(); ws = crop->getProperty("OutputWorkspace"); } // Rebin workspace if need to std::vector<double> rebinParams = getProperty("RebinParams"); if (!rebinParams.empty()) { IAlgorithm_sptr rebin = createChildAlgorithm("Rebin"); rebin->setProperty("InputWorkspace", ws); rebin->setProperty("Params", rebinParams); rebin->setProperty("FullBinsOnly", true); rebin->execute(); ws = rebin->getProperty("OutputWorkspace"); } return ws; }
/** Execute the algorithm. */ void TransformMD::exec() { Mantid::API::IMDWorkspace_sptr inWS; Mantid::API::IMDWorkspace_sptr outWS; inWS = getProperty("InputWorkspace"); outWS = getProperty("OutputWorkspace"); if (boost::dynamic_pointer_cast<MatrixWorkspace>(inWS)) throw std::runtime_error("TransformMD can only transform a " "MDHistoWorkspace or a MDEventWorkspace."); if (outWS != inWS) { // NOT in-place. So first we clone inWS into outWS IAlgorithm_sptr clone = this->createChildAlgorithm("CloneMDWorkspace", 0.0, 0.5, true); clone->setProperty("InputWorkspace", inWS); clone->executeAsChildAlg(); outWS = clone->getProperty("OutputWorkspace"); } if (!outWS) throw std::runtime_error("Invalid output workspace."); size_t nd = outWS->getNumDims(); m_scaling = getProperty("Scaling"); m_offset = getProperty("Offset"); // Replicate single values if (m_scaling.size() == 1) m_scaling = std::vector<double>(nd, m_scaling[0]); if (m_offset.size() == 1) m_offset = std::vector<double>(nd, m_offset[0]); // Check the size if (m_scaling.size() != nd) throw std::invalid_argument("Scaling argument must be either length 1 or " "match the number of dimensions."); if (m_offset.size() != nd) throw std::invalid_argument("Offset argument must be either length 1 or " "match the number of dimensions."); // Transform the dimensions outWS->transformDimensions(m_scaling, m_offset); MDHistoWorkspace_sptr histo = boost::dynamic_pointer_cast<MDHistoWorkspace>(outWS); IMDEventWorkspace_sptr event = boost::dynamic_pointer_cast<IMDEventWorkspace>(outWS); if (histo) { // Recalculate all the values since the dimensions changed. histo->cacheValues(); } else if (event) { // Call the method for this type of MDEventWorkspace. CALL_MDEVENT_FUNCTION(this->doTransform, outWS); } this->setProperty("OutputWorkspace", outWS); }