本文整理汇总了C++中IAlgorithm_sptr类的典型用法代码示例。如果您正苦于以下问题:C++ IAlgorithm_sptr类的具体用法?C++ IAlgorithm_sptr怎么用?C++ IAlgorithm_sptr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了IAlgorithm_sptr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: progress
void SANSSensitivityCorrection::exec() {
// Output log
m_output_message = "";
Progress progress(this, 0.0, 1.0, 10);
// Reduction property manager
const std::string reductionManagerName = getProperty("ReductionProperties");
boost::shared_ptr<PropertyManager> reductionManager;
if (PropertyManagerDataService::Instance().doesExist(reductionManagerName)) {
reductionManager =
PropertyManagerDataService::Instance().retrieve(reductionManagerName);
} else {
reductionManager = boost::make_shared<PropertyManager>();
PropertyManagerDataService::Instance().addOrReplace(reductionManagerName,
reductionManager);
}
if (!reductionManager->existsProperty("SensitivityAlgorithm")) {
auto algProp = make_unique<AlgorithmProperty>("SensitivityAlgorithm");
algProp->setValue(toString());
reductionManager->declareProperty(std::move(algProp));
}
progress.report("Loading sensitivity file");
const std::string fileName = getPropertyValue("Filename");
// Look for an entry for the dark current in the reduction table
Poco::Path path(fileName);
const std::string entryName = "Sensitivity" + path.getBaseName();
MatrixWorkspace_sptr floodWS;
std::string floodWSName = "__sensitivity_" + path.getBaseName();
if (reductionManager->existsProperty(entryName)) {
std::string wsName = reductionManager->getPropertyValue(entryName);
floodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(
AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(wsName));
m_output_message += " |Using " + wsName + "\n";
g_log.debug()
<< "SANSSensitivityCorrection :: Using sensitivity workspace: "
<< wsName << "\n";
} else {
// Load the flood field if we don't have it already
// First, try to determine whether we need to load data or a sensitivity
// workspace...
if (!floodWS && fileCheck(fileName)) {
g_log.debug() << "SANSSensitivityCorrection :: Loading sensitivity file: "
<< fileName << "\n";
IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 0.1, 0.3);
loadAlg->setProperty("Filename", fileName);
loadAlg->executeAsChildAlg();
Workspace_sptr floodWS_ws = loadAlg->getProperty("OutputWorkspace");
floodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(floodWS_ws);
// Check that it's really a sensitivity file
if (!floodWS->run().hasProperty("is_sensitivity")) {
// Reset pointer
floodWS.reset();
g_log.error() << "A processed Mantid workspace was loaded but it "
"wasn't a sensitivity file!\n";
}
}
// ... if we don't, just load the data and process it
if (!floodWS) {
// Read in default beam center
double center_x = getProperty("BeamCenterX");
double center_y = getProperty("BeamCenterY");
if (isEmpty(center_x) || isEmpty(center_y)) {
if (reductionManager->existsProperty("LatestBeamCenterX") &&
reductionManager->existsProperty("LatestBeamCenterY")) {
center_x = reductionManager->getProperty("LatestBeamCenterX");
center_y = reductionManager->getProperty("LatestBeamCenterY");
m_output_message +=
" |Setting beam center to [" +
Poco::NumberFormatter::format(center_x, 1) + ", " +
Poco::NumberFormatter::format(center_y, 1) + "]\n";
} else
m_output_message += " |No beam center provided: skipping!\n";
}
const std::string rawFloodWSName = "__flood_data_" + path.getBaseName();
MatrixWorkspace_sptr rawFloodWS;
if (!reductionManager->existsProperty("LoadAlgorithm")) {
IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 0.1, 0.3);
loadAlg->setProperty("Filename", fileName);
if (!isEmpty(center_x) && loadAlg->existsProperty("BeamCenterX"))
loadAlg->setProperty("BeamCenterX", center_x);
if (!isEmpty(center_y) && loadAlg->existsProperty("BeamCenterY"))
loadAlg->setProperty("BeamCenterY", center_y);
loadAlg->setPropertyValue("OutputWorkspace", rawFloodWSName);
loadAlg->executeAsChildAlg();
Workspace_sptr tmpWS = loadAlg->getProperty("OutputWorkspace");
rawFloodWS = boost::dynamic_pointer_cast<MatrixWorkspace>(tmpWS);
m_output_message += " | Loaded " + fileName + " (Load algorithm)\n";
} else {
// Get load algorithm as a string so that we can create a completely
// new proxy and ensure that we don't overwrite existing properties
IAlgorithm_sptr loadAlg0 =
reductionManager->getProperty("LoadAlgorithm");
//.........这里部分代码省略.........
示例2: saveReductions
/**
* Handles saving the reductions from the generic algorithm.
*/
void IndirectDiffractionReduction::saveReductions() {
for (const auto wsName : m_plotWorkspaces) {
const auto workspaceExists =
AnalysisDataService::Instance().doesExist(wsName);
if (workspaceExists) {
QString tofWsName = QString::fromStdString(wsName) + "_tof";
std::string instName =
(m_uiForm.iicInstrumentConfiguration->getInstrumentName())
.toStdString();
std::string mode =
(m_uiForm.iicInstrumentConfiguration->getReflectionName())
.toStdString();
BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromConvUnitsProps;
inputFromConvUnitsProps["InputWorkspace"] = tofWsName.toStdString();
BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromReductionProps;
inputFromReductionProps["InputWorkspace"] = (wsName + "_dRange");
if (m_uiForm.ckGSS->isChecked()) {
if (instName == "OSIRIS" && mode == "diffonly") {
QString gssFilename = tofWsName + ".gss";
IAlgorithm_sptr saveGSS =
AlgorithmManager::Instance().create("SaveGSS");
saveGSS->initialize();
saveGSS->setProperty("Filename", gssFilename.toStdString());
m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps);
} else {
// Convert to TOF for GSS
IAlgorithm_sptr convertUnits =
AlgorithmManager::Instance().create("ConvertUnits");
convertUnits->initialize();
convertUnits->setProperty("InputWorkspace", wsName);
convertUnits->setProperty("OutputWorkspace", tofWsName.toStdString());
convertUnits->setProperty("Target", "TOF");
m_batchAlgoRunner->addAlgorithm(convertUnits);
// Save GSS
std::string gssFilename = wsName + ".gss";
IAlgorithm_sptr saveGSS =
AlgorithmManager::Instance().create("SaveGSS");
saveGSS->initialize();
saveGSS->setProperty("Filename", gssFilename);
m_batchAlgoRunner->addAlgorithm(saveGSS, inputFromConvUnitsProps);
}
}
if (m_uiForm.ckNexus->isChecked()) {
// Save NEXus using SaveNexusProcessed
std::string nexusFilename = wsName + ".nxs";
IAlgorithm_sptr saveNexus =
AlgorithmManager::Instance().create("SaveNexusProcessed");
saveNexus->initialize();
saveNexus->setProperty("InputWorkspace", wsName);
saveNexus->setProperty("Filename", nexusFilename);
m_batchAlgoRunner->addAlgorithm(saveNexus);
}
if (m_uiForm.ckAscii->isChecked()) {
// Save ASCII using SaveAscii version 1
std::string asciiFilename = wsName + ".dat";
IAlgorithm_sptr saveASCII =
AlgorithmManager::Instance().create("SaveAscii", 1);
saveASCII->initialize();
saveASCII->setProperty("InputWorkspace", wsName);
saveASCII->setProperty("Filename", asciiFilename);
m_batchAlgoRunner->addAlgorithm(saveASCII);
}
} else
showInformationBox(QString::fromStdString(
"Workspace '" + wsName + "' not found\nUnable to plot workspace"));
}
m_batchAlgoRunner->executeBatchAsync();
}
示例3: catch
/**
* Runs a diffraction reduction for OSIRIS operating in diffonly mode using the
* OSIRISDiffractionReduction algorithm.
*/
void IndirectDiffractionReduction::runOSIRISdiffonlyReduction() {
// Get the files names from MWRunFiles widget, and convert them from Qt forms
// into stl equivalents.
QStringList fileNames = m_uiForm.rfSampleFiles->getFilenames();
std::vector<std::string> stlFileNames;
stlFileNames.reserve(fileNames.size());
std::transform(fileNames.begin(), fileNames.end(),
std::back_inserter(stlFileNames), toStdString);
// Use the file names to suggest a workspace name to use. Report to logger
// and stop if unable to parse correctly.
QString drangeWsName;
QString tofWsName;
try {
QString nameBase = QString::fromStdString(
Mantid::Kernel::MultiFileNameParsing::suggestWorkspaceName(
stlFileNames));
tofWsName = nameBase + "_tof";
drangeWsName = nameBase + "_dRange";
} catch (std::runtime_error &re) {
g_log.error(re.what());
return;
}
bool manualDRange(m_uiForm.ckManualDRange->isChecked());
IAlgorithm_sptr osirisDiffReduction =
AlgorithmManager::Instance().create("OSIRISDiffractionReduction");
osirisDiffReduction->initialize();
osirisDiffReduction->setProperty(
"Sample", m_uiForm.rfSampleFiles->getFilenames().join(",").toStdString());
osirisDiffReduction->setProperty(
"Vanadium",
m_uiForm.rfVanadiumFile->getFilenames().join(",").toStdString());
osirisDiffReduction->setProperty(
"CalFile", m_uiForm.rfCalFile->getFirstFilename().toStdString());
osirisDiffReduction->setProperty("LoadLogFiles",
m_uiForm.ckLoadLogs->isChecked());
osirisDiffReduction->setProperty("OutputWorkspace",
drangeWsName.toStdString());
auto specMin =
boost::lexical_cast<std::string, int>(m_uiForm.spSpecMin->value());
auto specMax =
boost::lexical_cast<std::string, int>(m_uiForm.spSpecMax->value());
osirisDiffReduction->setProperty("SpectraMin", specMin);
osirisDiffReduction->setProperty("SpectraMax", specMax);
osirisDiffReduction->setProperty("DetectDRange", !manualDRange);
if (manualDRange)
osirisDiffReduction->setProperty(
"DRange", static_cast<long>(m_uiForm.spDRange->value()));
if (m_uiForm.ckUseCan->isChecked()) {
osirisDiffReduction->setProperty(
"Container",
m_uiForm.rfCanFiles->getFilenames().join(",").toStdString());
if (m_uiForm.ckCanScale->isChecked())
osirisDiffReduction->setProperty("ContainerScaleFactor",
m_uiForm.spCanScale->value());
}
m_batchAlgoRunner->addAlgorithm(osirisDiffReduction);
BatchAlgorithmRunner::AlgorithmRuntimeProps inputFromReductionProps;
inputFromReductionProps["InputWorkspace"] = drangeWsName.toStdString();
IAlgorithm_sptr convertUnits =
AlgorithmManager::Instance().create("ConvertUnits");
convertUnits->initialize();
convertUnits->setProperty("OutputWorkspace", tofWsName.toStdString());
convertUnits->setProperty("Target", "TOF");
m_batchAlgoRunner->addAlgorithm(convertUnits, inputFromReductionProps);
m_plotWorkspaces.clear();
m_plotWorkspaces.push_back(tofWsName.toStdString());
m_plotWorkspaces.push_back(drangeWsName.toStdString());
// Handles completion of the diffraction algorithm chain
connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
SLOT(algorithmComplete(bool)));
m_batchAlgoRunner->executeBatchAsync();
}
示例4: getPropertyValue
/** Execute the algorithm.
*/
void CreateMDWorkspace::exec() {
// Get the properties and validate them
std::string eventType = getPropertyValue("EventType");
int ndims_prop = getProperty("Dimensions");
if (ndims_prop <= 0)
throw std::invalid_argument(
"You must specify a number of dimensions >= 1.");
int mind = this->getProperty("MinRecursionDepth");
int maxd = this->getProperty("MaxRecursionDepth");
if (mind > maxd)
throw std::invalid_argument(
"MinRecursionDepth must be <= MaxRecursionDepth.");
if (mind < 0 || maxd < 0)
throw std::invalid_argument(
"MinRecursionDepth and MaxRecursionDepth must be positive.");
size_t ndims = static_cast<size_t>(ndims_prop);
std::vector<double> extents = getProperty("Extents");
std::vector<std::string> names = getProperty("Names");
std::vector<std::string> units = getProperty("Units");
std::vector<std::string> frames = getProperty("Frames");
if (extents.size() != ndims * 2)
throw std::invalid_argument("You must specify twice as many extents "
"(min,max) as there are dimensions.");
if (names.size() != ndims)
throw std::invalid_argument(
"You must specify as many names as there are dimensions.");
if (units.size() != ndims)
throw std::invalid_argument(
"You must specify as many units as there are dimensions.");
// If no frames are specified we want to default to the General Frame,
// to ensure backward compatibility. But if they are only partly specified,
// then we want to throw an error. It should be either used correctly or not
// at all
if (!frames.empty() && frames.size() != ndims) {
throw std::invalid_argument(
"You must specify as many frames as there are dimensions.");
}
if (frames.empty()) {
frames.resize(ndims);
std::fill(frames.begin(), frames.end(), GeneralFrame::GeneralFrameName);
}
// Have the factory create it
IMDEventWorkspace_sptr out =
MDEventFactory::CreateMDWorkspace(ndims, eventType);
// Give all the dimensions
for (size_t d = 0; d < ndims; d++) {
auto frame = createMDFrame(frames[d], units[d]);
MDHistoDimension *dim = new MDHistoDimension(
names[d], names[d], *frame, static_cast<coord_t>(extents[d * 2]),
static_cast<coord_t>(extents[d * 2 + 1]), 1);
out->addDimension(MDHistoDimension_sptr(dim));
}
// Initialize it using the dimension
out->initialize();
// Call the templated function to finish ints
CALL_MDEVENT_FUNCTION(this->finish, out);
// --- File back end ? ----------------
std::string filename = getProperty("Filename");
if (!filename.empty()) {
// First save to the NXS file
g_log.notice() << "Running SaveMD" << std::endl;
IAlgorithm_sptr alg = createChildAlgorithm("SaveMD");
alg->setPropertyValue("Filename", filename);
alg->setProperty("InputWorkspace",
boost::dynamic_pointer_cast<IMDWorkspace>(out));
alg->executeAsChildAlg();
// And now re-load it with this file as the backing.
g_log.notice() << "Running LoadMD" << std::endl;
alg = createChildAlgorithm("LoadMD");
alg->setPropertyValue("Filename", filename);
alg->setProperty("FileBackEnd", true);
alg->setPropertyValue("Memory", getPropertyValue("Memory"));
alg->executeAsChildAlg();
// Replace the workspace with the loaded, file-backed one
IMDWorkspace_sptr temp;
temp = alg->getProperty("OutputWorkspace");
out = boost::dynamic_pointer_cast<IMDEventWorkspace>(temp);
}
// Save it on the output.
setProperty("OutputWorkspace", boost::dynamic_pointer_cast<Workspace>(out));
}
示例5: getPropertyValue
/** 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();
}
示例6: advanceProgress
/**
* 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.\n";
childAlg = createChildAlgorithm("ConvertToMatrixWorkspace", t0, t1);
childAlg->setProperty("InputWorkspace", outputW);
childAlg->executeAsChildAlg();
finalOutputW = childAlg->getProperty("OutputWorkspace");
}
return finalOutputW;
}
示例7: getProperty
/**
* Determine the instrument from the various input parameters.
*
* @return The correct instrument.
*/
Instrument_const_sptr CreateChunkingFromInstrument::getInstrument() {
// try the input workspace
MatrixWorkspace_sptr inWS = getProperty(PARAM_IN_WKSP);
if (inWS) {
return inWS->getInstrument();
}
// temporary workspace to hang everything else off of
MatrixWorkspace_sptr tempWS(new Workspace2D());
// name of the instrument
string instName = getPropertyValue(PARAM_INST_NAME);
// see if there is an input file
string filename = getPropertyValue(PARAM_IN_FILE);
if (!filename.empty()) {
string top_entry_name("entry"); // TODO make more flexible
// get the instrument name from the filename
size_t n = filename.rfind('/');
if (n != std::string::npos) {
std::string temp = filename.substr(n + 1, filename.size() - n - 1);
n = temp.find('_');
if (n != std::string::npos && n > 0) {
instName = temp.substr(0, n);
}
}
// read information from the nexus file itself
try {
NeXus::File nxsfile(filename);
// get the run start time
string start_time;
nxsfile.openGroup(top_entry_name, "NXentry");
nxsfile.readData("start_time", start_time);
tempWS->mutableRun().addProperty(
"run_start", DateAndTime(start_time).toISO8601String(), true);
// get the instrument name
nxsfile.openGroup("instrument", "NXinstrument");
nxsfile.readData("name", instName);
nxsfile.closeGroup();
// Test if IDF exists in file, move on quickly if not
nxsfile.openPath("instrument/instrument_xml");
nxsfile.close();
IAlgorithm_sptr loadInst =
createChildAlgorithm("LoadIDFFromNexus", 0.0, 0.2);
// Now execute the Child Algorithm. Catch and log any error, but don't
// stop.
try {
loadInst->setPropertyValue("Filename", filename);
loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
loadInst->setPropertyValue("InstrumentParentPath", top_entry_name);
loadInst->execute();
} catch (std::invalid_argument &) {
g_log.error("Invalid argument to LoadIDFFromNexus Child Algorithm ");
} catch (std::runtime_error &) {
g_log.debug("No instrument definition found in " + filename + " at " +
top_entry_name + "/instrument");
}
if (loadInst->isExecuted())
return tempWS->getInstrument();
else
g_log.information("No IDF loaded from Nexus file.");
} catch (::NeXus::Exception &) {
g_log.information("No instrument definition found in " + filename +
" at " + top_entry_name + "/instrument");
}
}
// run LoadInstrument if other methods have not run
string instFilename = getPropertyValue(PARAM_INST_FILE);
Algorithm_sptr childAlg = createChildAlgorithm("LoadInstrument", 0.0, 0.2);
childAlg->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
childAlg->setPropertyValue("Filename", instFilename);
childAlg->setPropertyValue("InstrumentName", instName);
childAlg->executeAsChildAlg();
return tempWS->getInstrument();
}
示例8: createChildAlgorithm
}
IAlgorithm_sptr algo = createChildAlgorithm("CreateWorkspace", 0.7, 1.0);
algo->setProperty< std::vector<double> >("DataX", std::vector<double>(2,0.0) );
algo->setProperty< std::vector<double> >("DataY", y_values );
algo->setProperty< std::vector<double> >("DataE", e_values );
algo->setProperty<int>("NSpec", numSpec );
algo->execute();
inputWS = algo->getProperty("OutputWorkspace");
WorkspaceFactory::Instance().initializeFromParent(inputWSWvl, inputWS, false);
}
else
{
// Sum up all the wavelength bins
IAlgorithm_sptr childAlg = createChildAlgorithm("Integration");
childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputWSWvl);
childAlg->executeAsChildAlg();
inputWS = childAlg->getProperty("OutputWorkspace");
}
// Define box around center of mass so that only pixels in an area
// _centered_ on the latest center position are considered. At each
// iteration we will recompute the bounding box, and we will make
// it as large as possible. The largest box is defined as:
double xmin0 = 0;
double xmax0 = 0;
double ymin0 = 0;
double ymax0 = 0;
// Starting values for the bounding box and the center
示例9: getProperty
/** Calculate the integral asymmetry for a workspace.
* The calculation is done by MuonAsymmetryCalc and SimpleIntegration 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(API::MatrixWorkspace_sptr ws, double& Y, double& E)
{
Property* startXprop = getProperty("TimeMin");
Property* endXprop = getProperty("TimeMax");
bool setX = !startXprop->isDefault() && !endXprop->isDefault();
double startX(0.0),endX(0.0);
if (setX)
{
startX = getProperty("TimeMin");
endX = getProperty("TimeMax");
}
if (!m_int)
{ // "Differential asymmetry"
IAlgorithm_sptr asym = createSubAlgorithm("AsymmetryCalc");
asym->initialize();
asym->setProperty("InputWorkspace",ws);
asym->setPropertyValue("OutputWorkspace","tmp");
if ( !m_autogroup )
{
asym->setProperty("ForwardSpectra",m_forward_list);
asym->setProperty("BackwardSpectra",m_backward_list);
}
asym->execute();
MatrixWorkspace_sptr asymWS = asym->getProperty("OutputWorkspace");
IAlgorithm_sptr integr = createSubAlgorithm("Integration");
integr->setProperty("InputWorkspace",asymWS);
integr->setPropertyValue("OutputWorkspace","tmp");
if (setX)
{
integr->setProperty("RangeLower",startX);
integr->setProperty("RangeUpper",endX);
}
integr->execute();
API::MatrixWorkspace_sptr out = integr->getProperty("OutputWorkspace");
Y = out->readY(0)[0];
E = out->readE(0)[0];
}
else
{
// "Integral asymmetry"
IAlgorithm_sptr integr = createSubAlgorithm("Integration");
integr->setProperty("InputWorkspace", ws);
integr->setPropertyValue("OutputWorkspace","tmp");
if (setX)
{
integr->setProperty("RangeLower",startX);
integr->setProperty("RangeUpper",endX);
}
integr->execute();
API::MatrixWorkspace_sptr intWS = integr->getProperty("OutputWorkspace");
IAlgorithm_sptr asym = createSubAlgorithm("AsymmetryCalc");
asym->initialize();
asym->setProperty("InputWorkspace",intWS);
asym->setPropertyValue("OutputWorkspace","tmp");
if ( !m_autogroup )
{
asym->setProperty("ForwardSpectra",m_forward_list);
asym->setProperty("BackwardSpectra",m_backward_list);
}
asym->execute();
MatrixWorkspace_sptr out = asym->getProperty("OutputWorkspace");
Y = out->readY(0)[0];
E = out->readE(0)[0];
}
}
示例10: QTreeWidget
void MonitorDlg::update() {
if (!m_tree) {
m_tree = new QTreeWidget(this);
m_tree->setColumnCount(3);
m_tree->setSelectionMode(QAbstractItemView::NoSelection);
// Make the algorithm name column wider
m_tree->setColumnWidth(0, 220);
QStringList hList;
hList << "Algorithm"
<< "Progress"
<< "";
m_tree->setHeaderLabels(hList);
QHeaderView *hHeader = (QHeaderView *)m_tree->header();
hHeader->setResizeMode(1, QHeaderView::Stretch);
hHeader->setResizeMode(2, QHeaderView::Fixed);
hHeader->setStretchLastSection(false);
} else
m_tree->clear();
if (!isVisible())
return;
m_algMonitor->lock();
QVector<Mantid::API::AlgorithmID>::const_iterator iend =
m_algMonitor->algorithms().end();
for (QVector<Mantid::API::AlgorithmID>::const_iterator itr =
m_algMonitor->algorithms().begin();
itr != iend; ++itr) {
IAlgorithm_sptr alg =
Mantid::API::AlgorithmManager::Instance().getAlgorithm(*itr);
// m_algorithms << alg;
QStringList iList;
iList << QString::fromStdString(alg->name());
QTreeWidgetItem *algItem = new QTreeWidgetItem(iList);
m_tree->addTopLevelItem(algItem);
QProgressBar *algProgress = new QProgressBar;
algProgress->setAlignment(Qt::AlignHCenter);
AlgButton *cancelButton = new AlgButton("Cancel", alg);
m_tree->setItemWidget(algItem, 1, algProgress);
m_tree->setItemWidget(algItem, 2, cancelButton);
const std::vector<Mantid::Kernel::Property *> &prop_list =
alg->getProperties();
for (std::vector<Mantid::Kernel::Property *>::const_iterator prop =
prop_list.begin();
prop != prop_list.end(); ++prop) {
QStringList lstr;
Mantid::Kernel::MaskedProperty<std::string> *maskedProp =
dynamic_cast<Mantid::Kernel::MaskedProperty<std::string> *>(*prop);
if (maskedProp) {
lstr << QString::fromStdString(maskedProp->name()) + ": "
<< QString::fromStdString(maskedProp->getMaskedValue());
} else {
lstr << QString::fromStdString((**prop).name()) + ": "
<< QString::fromStdString((**prop).value());
}
if ((**prop).isDefault())
lstr << " Default";
algItem->addChild(new QTreeWidgetItem(lstr));
}
connect(
cancelButton, SIGNAL(clicked(Mantid::API::AlgorithmID, QPushButton *)),
m_algMonitor, SLOT(cancel(Mantid::API::AlgorithmID, QPushButton *)));
}
m_algMonitor->unlock();
}
示例11: sqrt
/* Call Fit as child algorithm for each spectra
* @param index : the workspace index
*/
void FindEPP::fitGaussian(int64_t index) {
size_t spectrum = static_cast<size_t>(index);
m_outWS->cell<int>(spectrum, 0) = static_cast<int>(spectrum);
const auto &x = m_inWS->x(spectrum).rawData();
const auto &y = m_inWS->y(spectrum).rawData();
const auto &e = m_inWS->e(spectrum).rawData();
// Find the maximum value and it's index
const auto maxIt = std::max_element(y.begin(), y.end());
const double height = *maxIt;
size_t maxIndex = static_cast<size_t>(std::distance(y.begin(), maxIt));
if (height > 0) {
// Find how many bins are around maximum, that are above half-maximum
// Initialize the distances of the half-maxima bins from maximum
size_t leftHalf = maxIndex, rightHalf = x.size() - maxIndex - 1;
// Find the first bin on the right side of maximum, that drops below
// half-maximum
for (auto it = maxIt; it != y.end(); ++it) {
if (*it < 0.5 * height) {
rightHalf = it - maxIt - 1;
break;
}
}
// Find the first bin on the left side of maximum, that drops below
// half-maximum
for (auto it = maxIt; it != y.begin(); --it) {
if (*it < 0.5 * height) {
leftHalf = maxIt - it - 1;
break;
}
}
g_log.debug() << "Peak in spectrum #" << spectrum
<< " has last bins above 0.5*max at " << leftHalf << "\t"
<< rightHalf << "\n";
// We want to fit only if there are at least 3 bins (including the maximum
// itself) above half-maximum
if (rightHalf + leftHalf >= 2) {
// Prepare the initial parameters for the fit
double fwhm = x[maxIndex + rightHalf] - x[maxIndex - leftHalf];
double sigma = fwhm / (2. * sqrt(2. * log(2.)));
double center = x[maxIndex];
double start = center - 3. * fwhm;
double end = center + 3. * fwhm;
std::stringstream function;
function << "name=Gaussian,PeakCentre=";
function << center << ",Height=" << height << ",Sigma=" << sigma;
g_log.debug() << "Fitting spectrum #" << spectrum
<< " with: " << function.str() << "\n";
IAlgorithm_sptr fitAlg = createChildAlgorithm("Fit", 0., 0., false);
fitAlg->setProperty("Function", function.str());
fitAlg->setProperty("InputWorkspace", m_inWS);
fitAlg->setProperty("WorkspaceIndex", static_cast<int>(spectrum));
fitAlg->setProperty("StartX", start);
fitAlg->setProperty("EndX", end);
fitAlg->setProperty("CreateOutput", true);
fitAlg->setProperty("OutputParametersOnly", true);
fitAlg->executeAsChildAlg();
const std::string status = fitAlg->getProperty("OutputStatus");
ITableWorkspace_sptr fitResult = fitAlg->getProperty("OutputParameters");
if (status == "success") {
m_outWS->cell<double>(spectrum, 1) = fitResult->cell<double>(1, 1);
m_outWS->cell<double>(spectrum, 2) = fitResult->cell<double>(1, 2);
m_outWS->cell<double>(spectrum, 3) = fitResult->cell<double>(2, 1);
m_outWS->cell<double>(spectrum, 4) = fitResult->cell<double>(2, 2);
m_outWS->cell<double>(spectrum, 5) = fitResult->cell<double>(0, 1);
m_outWS->cell<double>(spectrum, 6) = fitResult->cell<double>(0, 2);
m_outWS->cell<double>(spectrum, 7) = fitResult->cell<double>(3, 1);
m_outWS->cell<std::string>(spectrum, 8) = status;
} else {
g_log.debug() << "Fit failed in spectrum #" << spectrum
<< ". \nReason :" << status
<< ". \nSetting the maximum.\n";
m_outWS->cell<std::string>(spectrum, 8) = "fitFailed";
m_outWS->cell<double>(spectrum, 1) = x[maxIndex];
m_outWS->cell<double>(spectrum, 2) = 0.;
m_outWS->cell<double>(spectrum, 5) = height;
m_outWS->cell<double>(spectrum, 6) = e[maxIndex];
}
} else {
g_log.information() << "Found <=3 bins above half maximum in spectrum #"
<< index << ". Not fitting.\n";
m_outWS->cell<std::string>(spectrum, 8) = "narrowPeak";
m_outWS->cell<double>(spectrum, 1) = x[maxIndex];
m_outWS->cell<double>(spectrum, 2) = 0.;
m_outWS->cell<double>(spectrum, 5) = height;
//.........这里部分代码省略.........
示例12: generateCurve
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();
}
示例13: getTofRange
/** Execute the algorithm.
*/
void RemovePromptPulse::exec() {
// verify there is a width parameter specified
double width = this->getProperty("Width");
if (this->isEmpty(width)) {
throw std::runtime_error("Failed to specify \'Width\' parameter");
}
// need the input workspace in general
API::MatrixWorkspace_const_sptr inputWS = this->getProperty("InputWorkspace");
// get the frequency
double frequency = this->getProperty("Frequency");
if (this->isEmpty(frequency)) // it wasn't specified so try divination
{
frequency = this->getFrequency(inputWS->run());
if (this->isEmpty(frequency)) {
throw std::runtime_error("Failed to determine the frequency");
}
}
g_log.information() << "Using frequency of " << frequency << "Hz\n";
double period = 1000000. / frequency; // period in microseconds
// determine the overall tof window for the data
double tmin;
double tmax;
getTofRange(inputWS, tmin, tmax);
g_log.information() << "Data tmin=" << tmin << ", tmax=" << tmax
<< ", period=" << period << " microseconds\n";
// calculate the times for the prompt pulse
std::vector<double> pulseTimes =
this->calculatePulseTimes(tmin, tmax, period);
if (pulseTimes.empty()) {
g_log.notice() << "Not applying filter since prompt pulse is not in data "
"range (period = " << period << ")\n";
setProperty("OutputWorkspace",
boost::const_pointer_cast<MatrixWorkspace>(inputWS));
return;
}
g_log.information() << "Calculated prompt pulses at ";
for (double pulseTime : pulseTimes)
g_log.information() << pulseTime << " ";
g_log.information() << " microseconds\n";
MatrixWorkspace_sptr outputWS;
for (double &pulseTime : pulseTimes) {
double right = pulseTime + width;
g_log.notice() << "Filtering tmin=" << pulseTime << ", tmax=" << right
<< " microseconds\n";
// run maskbins to do the work on the first prompt pulse
IAlgorithm_sptr algo = this->createChildAlgorithm("MaskBins");
if (outputWS) {
algo->setProperty<MatrixWorkspace_sptr>(
"InputWorkspace",
boost::const_pointer_cast<MatrixWorkspace>(outputWS));
} else { // should only be first time
algo->setProperty<MatrixWorkspace_sptr>(
"InputWorkspace",
boost::const_pointer_cast<MatrixWorkspace>(inputWS));
outputWS = this->getProperty("OutputWorkspace");
}
// always write to correct output workspace
algo->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", outputWS);
algo->setProperty<double>("XMin", pulseTime);
algo->setProperty<double>("XMax", right);
algo->executeAsChildAlg();
// copy over the output workspace
outputWS = algo->getProperty("OutputWorkspace");
}
setProperty("OutputWorkspace", outputWS);
}
示例14: retVal
/**
* Create histogram workspace
* @returns Created workspace
*/
MatrixWorkspace_sptr LoadFITS::initAndPopulateHistogramWorkspace()
{
MantidVecPtr x;
x.access().resize(m_allHeaderInfo.size() + 1);
// Init time bins
double binCount = 0;
for(size_t i=0;i<m_allHeaderInfo.size() + 1; ++i)
{
x.access()[i] = binCount;
if(i != m_allHeaderInfo.size()) binCount += m_allHeaderInfo[i].timeBin;
}
size_t spectraCount = 0;
if(m_allHeaderInfo[0].numberOfAxis > 0) spectraCount += m_allHeaderInfo[0].axisPixelLengths[0];
// Presumably 2 axis, but futureproofing.
for(int i=1;i<m_allHeaderInfo[0].numberOfAxis;++i)
{
spectraCount *= m_allHeaderInfo[0].axisPixelLengths[i];
}
MatrixWorkspace_sptr retVal(new DataObjects::Workspace2D);
retVal->initialize(spectraCount, m_allHeaderInfo.size()+1, m_allHeaderInfo.size());
IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
try
{
std::string directoryName = Kernel::ConfigService::Instance().getInstrumentDirectory();
directoryName = directoryName + "/IMAT_Definition.xml";
loadInst->setPropertyValue("Filename", directoryName);
loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", retVal);
loadInst->execute();
}
catch (std::exception & ex)
{
g_log.information("Cannot load the instrument definition. " + string(ex.what()) );
}
int bitsPerPixel = m_allHeaderInfo[0].bitsPerPixel; // assumes all files have the same, which they should.
vector<vector<double> > yVals(spectraCount, std::vector<double>(m_binChunkSize));
vector<vector<double> > eVals(spectraCount, std::vector<double>(m_binChunkSize));
// allocate memory to contain the data section of the file:
void * bufferAny = NULL;
bufferAny = malloc ((bitsPerPixel/8)*spectraCount);
if (bufferAny == NULL)
{
throw std::runtime_error("FITS loader couldn't allocate enough memory to run. Try a smaller chunk size.");
}
size_t steps = static_cast<size_t>(ceil(m_allHeaderInfo.size()/m_binChunkSize));
Progress prog(this,0.0,1.0,steps);
// Load a chunk of files at a time into workspace
try
{
for(size_t i=0; i<m_allHeaderInfo.size(); i+=m_binChunkSize)
{
loadChunkOfBinsFromFile(retVal, yVals, eVals, bufferAny, x, spectraCount, bitsPerPixel, i);
prog.report(name());
}
}
catch(...)
{
// Exceptions should be handled internally, but catch here to free any memory. Belt and braces.
free(bufferAny);
g_log.error("FITS Loader unable to correctly parse files.");
throw std::runtime_error("FITS loader unable to correctly parse files.");
}
// Memory no longer needed
free (bufferAny);
retVal->mutableRun().addProperty("Filename", m_allHeaderInfo[0].filePath);
// Set the Unit of the X Axis
try
{
retVal->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
}
catch ( Exception::NotFoundError & )
{
retVal->getAxis(0)->unit() = UnitFactory::Instance().create("Label");
Unit_sptr unit = retVal->getAxis(0)->unit();
boost::shared_ptr<Units::Label> label = boost::dynamic_pointer_cast<Units::Label>(unit);
label->setLabel("TOF", "TOF");
}
retVal->setYUnit("Counts");
retVal->setTitle("Test Workspace");
return retVal;
//.........这里部分代码省略.........
示例15: getPropertyValue
void EQSANSLoad::exec()
{
// Verify the validity of the inputs
//TODO: this should be done by the new data management algorithm used for
// live data reduction (when it's implemented...)
const std::string fileName = getPropertyValue("Filename");
EventWorkspace_sptr inputEventWS = getProperty("InputWorkspace");
if (fileName.size()==0 && !inputEventWS)
{
g_log.error() << "EQSANSLoad input error: Either a valid file path or an input workspace must be provided" << std::endl;
throw std::runtime_error("EQSANSLoad input error: Either a valid file path or an input workspace must be provided");
}
else if (fileName.size()>0 && inputEventWS)
{
g_log.error() << "EQSANSLoad input error: Either a valid file path or an input workspace must be provided, but not both" << std::endl;
throw std::runtime_error("EQSANSLoad input error: Either a valid file path or an input workspace must be provided, but not both");
}
// Read in default TOF cuts
const bool skipTOFCorrection = getProperty("SkipTOFCorrection");
m_low_TOF_cut = getProperty("LowTOFCut");
m_high_TOF_cut = getProperty("HighTOFCut");
// Read in default beam center
m_center_x = getProperty("BeamCenterX");
m_center_y = getProperty("BeamCenterY");
const bool noBeamCenter = getProperty("NoBeamCenter");
// Reduction property manager
const std::string reductionManagerName = getProperty("ReductionProperties");
boost::shared_ptr<PropertyManager> reductionManager;
if (PropertyManagerDataService::Instance().doesExist(reductionManagerName))
{
reductionManager = PropertyManagerDataService::Instance().retrieve(reductionManagerName);
}
else
{
reductionManager = boost::make_shared<PropertyManager>();
PropertyManagerDataService::Instance().addOrReplace(reductionManagerName, reductionManager);
}
if (!reductionManager->existsProperty("LoadAlgorithm"))
{
AlgorithmProperty *loadProp = new AlgorithmProperty("LoadAlgorithm");
setPropertyValue("InputWorkspace", "");
setProperty("NoBeamCenter", false);
loadProp->setValue(toString());
reductionManager->declareProperty(loadProp);
}
if (!reductionManager->existsProperty("InstrumentName"))
{
reductionManager->declareProperty(new PropertyWithValue<std::string>("InstrumentName", "EQSANS") );
}
// Output log
m_output_message = "";
// Check whether we need to load the data
if (!inputEventWS)
{
const bool loadMonitors = getProperty("LoadMonitors");
IAlgorithm_sptr loadAlg = createChildAlgorithm("LoadEventNexus", 0, 0.2);
loadAlg->setProperty("LoadMonitors", loadMonitors);
loadAlg->setProperty("MonitorsAsEvents", false);
loadAlg->setProperty("Filename", fileName);
if (skipTOFCorrection)
{
if (m_low_TOF_cut>0.0) loadAlg->setProperty("FilterByTofMin", m_low_TOF_cut);
if (m_high_TOF_cut>0.0) loadAlg->setProperty("FilterByTofMax", m_high_TOF_cut);
}
loadAlg->execute();
IEventWorkspace_sptr dataWS_asWks = loadAlg->getProperty("OutputWorkspace");
dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);
// Get monitor workspace as necessary
std::string mon_wsname = getPropertyValue("OutputWorkspace")+"_monitors";
if (loadMonitors && loadAlg->existsProperty("MonitorWorkspace"))
{
MatrixWorkspace_sptr monWS = loadAlg->getProperty("MonitorWorkspace");
declareProperty(new WorkspaceProperty<>("MonitorWorkspace",
mon_wsname, Direction::Output), "Monitors from the Event NeXus file");
setProperty("MonitorWorkspace", monWS);
}
} else {
MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
EventWorkspace_sptr outputEventWS = boost::dynamic_pointer_cast<EventWorkspace>(outputWS);
if (inputEventWS != outputEventWS)
{
IAlgorithm_sptr copyAlg = createChildAlgorithm("CloneWorkspace", 0, 0.2);
copyAlg->setProperty("InputWorkspace", inputEventWS);
copyAlg->executeAsChildAlg();
Workspace_sptr dataWS_asWks = copyAlg->getProperty("OutputWorkspace");
dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(dataWS_asWks);
} else {
dataWS = boost::dynamic_pointer_cast<MatrixWorkspace>(inputEventWS);
}
}
// Get the sample-detector distance
//.........这里部分代码省略.........