本文整理汇总了C++中ITableWorkspace_sptr类的典型用法代码示例。如果您正苦于以下问题:C++ ITableWorkspace_sptr类的具体用法?C++ ITableWorkspace_sptr怎么用?C++ ITableWorkspace_sptr使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了ITableWorkspace_sptr类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。
示例1: removeFixedParameterErrors
/**
* Removes error columns from the table if all errors are zero,
* as these columns correspond to fixed parameters.
* @param table :: [input, output] Pointer to TableWorkspace to edit
*/
void MuonAnalysisResultTableCreator::removeFixedParameterErrors(
const ITableWorkspace_sptr table) const {
assert(table);
const size_t nRows = table->rowCount();
const auto colNames = table->getColumnNames();
std::vector<std::string> zeroErrorColumns;
for (const auto &name : colNames) {
// if name does not end with "Error", continue
const size_t nameLength = name.length();
if (nameLength < ERROR_LENGTH ||
name.compare(nameLength - ERROR_LENGTH, ERROR_LENGTH, ERROR_STRING)) {
continue;
}
auto col = table->getColumn(name);
bool allZeros = true;
// Check if all values in the column are zero
for (size_t iRow = 0; iRow < nRows; ++iRow) {
const double val = col->toDouble(iRow);
if (std::abs(val) > std::numeric_limits<double>::epsilon()) {
allZeros = false;
break;
}
}
if (allZeros) {
zeroErrorColumns.push_back(name);
}
}
for (const auto &name : zeroErrorColumns) {
table->removeColumn(name);
}
}
示例2: parseProfileTableWorkspace
/** Parse profile table workspace to a map (the new ...
*/
void SaveGSASInstrumentFile::parseProfileTableWorkspace(
ITableWorkspace_sptr ws,
map<unsigned int, map<string, double>> &profilemap) {
size_t numbanks = ws->columnCount() - 1;
size_t numparams = ws->rowCount();
vector<map<string, double>> vec_maptemp(numbanks);
vector<unsigned int> vecbankindex(numbanks);
// Check
vector<string> colnames = ws->getColumnNames();
if (colnames[0].compare("Name"))
throw runtime_error("The first column must be Name");
// Parse
for (size_t irow = 0; irow < numparams; ++irow) {
TableRow tmprow = ws->getRow(irow);
string parname;
tmprow >> parname;
if (parname.compare("BANK")) {
for (size_t icol = 0; icol < numbanks; ++icol) {
double tmpdbl;
tmprow >> tmpdbl;
vec_maptemp[icol].insert(make_pair(parname, tmpdbl));
}
} else {
for (size_t icol = 0; icol < numbanks; ++icol) {
double tmpint;
tmprow >> tmpint;
vecbankindex[icol] = static_cast<unsigned int>(tmpint);
}
}
}
示例3: getProperty
/** 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);
}
示例4: search
ITableWorkspace_sptr ReflCatalogSearcher::search(const std::string &text) {
auto sessions = CatalogManager::Instance().getActiveSessions();
if (sessions.empty())
throw std::runtime_error("You are not logged into any catalogs.");
const std::string sessionId = sessions.front()->getSessionId();
auto algSearch = AlgorithmManager::Instance().create("CatalogGetDataFiles");
algSearch->initialize();
algSearch->setChild(true);
algSearch->setLogging(false);
algSearch->setProperty("Session", sessionId);
algSearch->setProperty("InvestigationId", text);
algSearch->setProperty("OutputWorkspace", "_ReflSearchResults");
algSearch->execute();
ITableWorkspace_sptr results = algSearch->getProperty("OutputWorkspace");
// Now, tidy up the data
std::set<size_t> toRemove;
for (size_t i = 0; i < results->rowCount(); ++i) {
std::string &run = results->String(i, 0);
// Too short to be more than ".raw or .nxs"
if (run.size() < 5) {
toRemove.insert(i);
}
}
// Sets are sorted so if we go from back to front we won't trip over ourselves
for (auto row = toRemove.rbegin(); row != toRemove.rend(); ++row)
results->removeRow(*row);
return results;
}
示例5: disconnect
/**
* Calculates binning parameters.
*/
void Iqt::calculateBinning() {
using namespace Mantid::API;
disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
SLOT(updatePropertyValues(QtProperty *, double)));
QString wsName = m_uiForm.dsInput->getCurrentDataName();
QString resName = m_uiForm.dsResolution->getCurrentDataName();
if (wsName.isEmpty() || resName.isEmpty())
return;
double energyMin = m_dblManager->value(m_properties["ELow"]);
double energyMax = m_dblManager->value(m_properties["EHigh"]);
double numBins = m_dblManager->value(m_properties["SampleBinning"]);
if (numBins == 0)
return;
IAlgorithm_sptr furyAlg =
AlgorithmManager::Instance().create("TransformToIqt");
furyAlg->initialize();
furyAlg->setProperty("SampleWorkspace", wsName.toStdString());
furyAlg->setProperty("ResolutionWorkspace", resName.toStdString());
furyAlg->setProperty("ParameterWorkspace", "__FuryProperties_temp");
furyAlg->setProperty("EnergyMin", energyMin);
furyAlg->setProperty("EnergyMax", energyMax);
furyAlg->setProperty("BinReductionFactor", numBins);
furyAlg->setProperty("DryRun", true);
furyAlg->execute();
// Get property table from algorithm
ITableWorkspace_sptr propsTable =
AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(
"__FuryProperties_temp");
// Get data from property table
double energyWidth = propsTable->getColumn("EnergyWidth")->cell<float>(0);
int sampleBins = propsTable->getColumn("SampleOutputBins")->cell<int>(0);
int resolutionBins = propsTable->getColumn("ResolutionBins")->cell<int>(0);
// Update data in property editor
m_dblManager->setValue(m_properties["EWidth"], energyWidth);
m_dblManager->setValue(m_properties["ResolutionBins"], resolutionBins);
m_dblManager->setValue(m_properties["SampleBins"], sampleBins);
connect(m_dblManager, SIGNAL(valueChanged(QtProperty *, double)), this,
SLOT(updatePropertyValues(QtProperty *, double)));
// Warn for low number of resolution bins
int numResolutionBins =
static_cast<int>(m_dblManager->value(m_properties["ResolutionBins"]));
if (numResolutionBins < 5)
showMessageBox("Number of resolution bins is less than 5.\nResults may be "
"inaccurate.");
}
示例6: getProperty
/**
* Run new CompareWorkspaces algorithm as a child algorithm.
*
* Result string formatted the same way as before; "Success!" when workspaces
* match or a newline separated list of mismatch messages.
*
* @param group_compare Should output be formatted like group comparison?
* @return A string containing either successString() or mismatch messages
*/
std::string CheckWorkspacesMatch::runCompareWorkspaces(bool group_compare) {
// This algorithm produces a single result string
std::string result;
// Use new CompareWorkspaces algorithm to perform comparison
Algorithm_sptr compare = this->createChildAlgorithm("CompareWorkspaces");
compare->setRethrows(true);
compare->setLogging(false);
// Forward workspace properties
Workspace_sptr ws1 = getProperty("Workspace1");
Workspace_sptr ws2 = getProperty("Workspace2");
compare->setProperty("Workspace1", ws1);
compare->setProperty("Workspace2", ws2);
// Copy any other non-default properties
const std::vector<Property *> &allProps = this->getProperties();
auto propCount = allProps.size();
for (size_t i = 0; i < propCount; ++i) {
Property *prop = allProps[i];
const std::string &pname = prop->name();
if (!prop->isDefault() && pname != "Workspace1" && pname != "Workspace2" &&
pname != "Result")
compare->setPropertyValue(pname, prop->value());
}
// Execute comparison
compare->execute();
// Generate result string
if (!compare->getProperty("Result")) {
ITableWorkspace_sptr table = compare->getProperty("Messages");
auto rowcount = table->rowCount();
for (size_t i = 0; i < rowcount; ++i) {
result += table->cell<std::string>(i, 0);
// Emulate special case output format when comparing groups
if (group_compare &&
table->cell<std::string>(i, 0) !=
"Type mismatch. One workspace is a group, the other is not." &&
table->cell<std::string>(i, 0) != "GroupWorkspaces size mismatch.") {
result += ". Inputs=[" + table->cell<std::string>(i, 1) + "," +
table->cell<std::string>(i, 2) + "]";
}
if (i < (rowcount - 1))
result += "\n";
}
} else {
result = successString();
}
return result;
}
示例7: search
ITableWorkspace_sptr ReflCatalogSearcher::search(const std::string& text, const std::string& instrument)
{
auto sessions = CatalogManager::Instance().getActiveSessions();
if(sessions.empty())
throw std::runtime_error("You are not logged into any catalogs.");
const std::string sessionId = sessions.front()->getSessionId();
auto algSearch = AlgorithmManager::Instance().create("CatalogGetDataFiles");
algSearch->initialize();
algSearch->setChild(true);
algSearch->setLogging(false);
algSearch->setProperty("Session", sessionId);
algSearch->setProperty("InvestigationId", text);
algSearch->setProperty("OutputWorkspace", "_ReflSearchResults");
algSearch->execute();
ITableWorkspace_sptr results = algSearch->getProperty("OutputWorkspace");
//Now, tidy up the data
std::set<size_t> toRemove;
for(size_t i = 0; i < results->rowCount(); ++i)
{
std::string& run = results->String(i,0);
//Too short to be more than ".raw"
if(run.size() < 5)
{
toRemove.insert(i);
}
//If this isn't the right instrument, remove it
else if(run.substr(0, instrument.size()) != instrument)
{
toRemove.insert(i);
}
//If it's not a raw file, remove it
else if(run.substr(run.size() - 4, 4) != ".raw")
{
toRemove.insert(i);
}
//It's a valid run, so let's trim the instrument prefix and ".raw" suffix
run = run.substr(instrument.size(), run.size() - (instrument.size() + 4));
//Let's also get rid of any leading zeros
size_t numZeros = 0;
while(run[numZeros] == '0')
numZeros++;
run = run.substr(numZeros, run.size() - numZeros);
}
//Sets are sorted so if we go from back to front we won't trip over ourselves
for(auto row = toRemove.rbegin(); row != toRemove.rend(); ++row)
results->removeRow(*row);
return results;
}
示例8: createDomainFromPeakTable
/**
* Creates a domain from an ITableWorkspace
*
* This method creates a LatticeDomain from a table workspace that contains two
* columns, HKL and d. HKL can either be a V3D-column or a string column,
* containing three integers separated by space, comma, semi-colon and
* optionally surrounded by []. The d-column can be double or a string that can
* be parsed as a double number.
*
* @param workspace :: ITableWorkspace with format specified above.
* @param domain :: Pointer to outgoing FunctionDomain instance.
* @param values :: Pointer to outgoing FunctionValues object.
* @param i0 :: Size offset for values object if it already contains data.
*/
void LatticeDomainCreator::createDomainFromPeakTable(
const ITableWorkspace_sptr &workspace,
boost::shared_ptr<FunctionDomain> &domain,
boost::shared_ptr<FunctionValues> &values, size_t i0) {
size_t peakCount = workspace->rowCount();
if (peakCount < 1) {
throw std::range_error("Cannot create a domain for 0 peaks.");
}
try {
Column_const_sptr hklColumn = workspace->getColumn("HKL");
Column_const_sptr dColumn = workspace->getColumn("d");
std::vector<V3D> hkls;
hkls.reserve(peakCount);
std::vector<double> dSpacings;
dSpacings.reserve(peakCount);
V3DFromHKLColumnExtractor extractor;
for (size_t i = 0; i < peakCount; ++i) {
try {
V3D hkl = extractor(hklColumn, i);
if (hkl != V3D(0, 0, 0)) {
hkls.push_back(hkl);
double d = (*dColumn)[i];
dSpacings.push_back(d);
}
} catch (const std::bad_alloc &) {
// do nothing.
}
}
domain = boost::make_shared<LatticeDomain>(hkls);
if (!values) {
values = boost::make_shared<FunctionValues>(*domain);
} else {
values->expand(i0 + domain->size());
}
values->setFitData(dSpacings);
values->setFitWeights(1.0);
} catch (const std::runtime_error &) {
// Column does not exist
throw std::runtime_error("Can not process table, the following columns are "
"required: HKL, d.");
}
}
示例9: invalid_argument
/// Returns a TableWorkspace with refined cell parameters and error.
ITableWorkspace_sptr PoldiFitPeaks2D::getRefinedCellParameters(
const IFunction_sptr &fitFunction) const {
Poldi2DFunction_sptr poldi2DFunction =
boost::dynamic_pointer_cast<Poldi2DFunction>(fitFunction);
if (!poldi2DFunction || poldi2DFunction->nFunctions() < 1) {
throw std::invalid_argument(
"Cannot process function that is not a Poldi2DFunction.");
}
// Create a new table for lattice parameters
ITableWorkspace_sptr latticeParameterTable =
WorkspaceFactory::Instance().createTable();
latticeParameterTable->addColumn("str", "Parameter");
latticeParameterTable->addColumn("double", "Value");
latticeParameterTable->addColumn("double", "Error");
// The first function should be PoldiSpectrumPawleyFunction
boost::shared_ptr<PoldiSpectrumPawleyFunction> poldiPawleyFunction =
boost::dynamic_pointer_cast<PoldiSpectrumPawleyFunction>(
poldi2DFunction->getFunction(0));
if (!poldiPawleyFunction) {
throw std::invalid_argument("First function in Poldi2DFunction is not "
"PoldiSpectrumPawleyFunction.");
}
// Get the actual PawleyFunction to extract parameters.
IPawleyFunction_sptr pawleyFunction =
boost::dynamic_pointer_cast<IPawleyFunction>(
poldiPawleyFunction->getDecoratedFunction());
if (pawleyFunction) {
CompositeFunction_sptr pawleyParts =
boost::dynamic_pointer_cast<CompositeFunction>(
pawleyFunction->getDecoratedFunction());
// The first function in PawleyFunction contains the parameters
IFunction_sptr pawleyParameters = pawleyParts->getFunction(0);
for (size_t i = 0; i < pawleyParameters->nParams(); ++i) {
TableRow newRow = latticeParameterTable->appendRow();
newRow << pawleyParameters->parameterName(i)
<< pawleyParameters->getParameter(i)
<< pawleyParameters->getError(i);
}
}
return latticeParameterTable;
}
示例10:
/** Creates grouping table from supplied forward and backward spectra
* @param fwd :: [Input] Forward spectra
* @param bwd :: [Input] Backward spectra
* @return :: Workspace containing custom grouping
*/
Workspace_sptr
PlotAsymmetryByLogValue::createCustomGrouping(const std::vector<int> &fwd,
const std::vector<int> &bwd) {
ITableWorkspace_sptr group =
WorkspaceFactory::Instance().createTable("TableWorkspace");
group->addColumn("vector_int", "group");
TableRow row = group->appendRow();
row << fwd;
row = group->appendRow();
row << bwd;
return boost::dynamic_pointer_cast<Workspace>(group);
}
示例11: previewAlgDone
/**
* Handles completion of the preview algorithm.
*
* @param error If the algorithm failed
*/
void IndirectSymmetrise::previewAlgDone(bool error) {
if (error)
return;
QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
int spectrumNumber =
static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));
MatrixWorkspace_sptr sampleWS =
AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
workspaceName.toStdString());
ITableWorkspace_sptr propsTable =
AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(
"__SymmetriseProps_temp");
MatrixWorkspace_sptr symmWS =
AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
"__Symmetrise_temp");
// Get the index of XCut on each side of zero
int negativeIndex = propsTable->getColumn("NegativeXMinIndex")->cell<int>(0);
int positiveIndex = propsTable->getColumn("PositiveXMinIndex")->cell<int>(0);
// Get the Y values for each XCut and the difference between them
double negativeY = sampleWS->dataY(0)[negativeIndex];
double positiveY = sampleWS->dataY(0)[positiveIndex];
double deltaY = fabs(negativeY - positiveY);
// Show values in property tree
m_dblManager->setValue(m_properties["NegativeYValue"], negativeY);
m_dblManager->setValue(m_properties["PositiveYValue"], positiveY);
m_dblManager->setValue(m_properties["DeltaY"], deltaY);
// Set indicator positions
m_uiForm.ppRawPlot->getRangeSelector("NegativeEMinYPos")
->setMinimum(negativeY);
m_uiForm.ppRawPlot->getRangeSelector("PositiveEMinYPos")
->setMinimum(positiveY);
// Plot preview plot
size_t spectrumIndex = symmWS->getIndexFromSpectrumNumber(spectrumNumber);
m_uiForm.ppPreviewPlot->clear();
m_uiForm.ppPreviewPlot->addSpectrum("Symmetrised", "__Symmetrise_temp",
spectrumIndex);
// Don't want this to trigger when the algorithm is run for all spectra
disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
SLOT(previewAlgDone(bool)));
}
示例12: readCharInfo
/**
* Parse the stream for the characterization file information.
*
* @param file The stream to parse.
* @param wksp The table workspace to fill in.
*/
void PDLoadCharacterizations::readCharInfo(std::ifstream &file, ITableWorkspace_sptr &wksp)
{
// end early if already at the end of the file
if (file.eof()) return;
// parse the file
for (std::string line = Strings::getLine(file); !file.eof(); line = Strings::getLine(file))
{
line = Strings::strip(line);
// skip empty lines and "comments"
if (line.empty()) continue;
if (line.substr(0,1) == "#") continue;
// parse the line
std::vector<std::string> splitted;
boost::split(splitted, line, boost::is_any_of("\t "), boost::token_compress_on);
while (splitted.size() < 10)
splitted.push_back(ZERO); // extra values default to zero
// add the row
API::TableRow row = wksp->appendRow();
row << boost::lexical_cast<double>(splitted[0]); // frequency
row << boost::lexical_cast<double>(splitted[1]); // wavelength
row << boost::lexical_cast<int32_t>(splitted[2]); // bank
row << boost::lexical_cast<int32_t>(splitted[3]); // vanadium
row << boost::lexical_cast<int32_t>(splitted[4]); // container
row << boost::lexical_cast<int32_t>(splitted[5]); // empty
row << splitted[6]; // d_min
row << splitted[7]; // d_max
row << boost::lexical_cast<double>(splitted[8]); // tof_min
row << boost::lexical_cast<double>(splitted[9]); // tof_max
}
}
示例13: tableToGrouping
/**
* Convert a grouping table to a grouping struct.
* @param table :: A table to convert
* @return Grouping info
*/
boost::shared_ptr<Grouping> tableToGrouping(ITableWorkspace_sptr table)
{
auto grouping = boost::make_shared<Grouping>();
for ( size_t row = 0; row < table->rowCount(); ++row )
{
std::vector<int> detectors = table->cell< std::vector<int> >(row,0);
// toString() expects the sequence to be sorted
std::sort( detectors.begin(), detectors.end() );
// Convert to a range string, i.e. 1-5,6-8,9
std::string detectorRange = Strings::toString(detectors);
grouping->groupNames.push_back(boost::lexical_cast<std::string>(row + 1));
grouping->groups.push_back(detectorRange);
}
// If we have 2 groups only - create a longitudinal pair
if ( grouping->groups.size() == 2 )
{
grouping->pairNames.push_back("long");
grouping->pairAlphas.push_back(1.0);
grouping->pairs.push_back(std::make_pair(0,1));
}
return grouping;
}
示例14: writeDataForSingleFit
/**
* Write log and parameter values to the table for the case of a single fit.
* @param table :: [input, output] Table to write to
* @param paramsByLabel :: [input] Map of <label name, <workspace name,
* <parameter, value>>>
* @param paramsToDisplay :: [input] List of parameters to display in table
*/
void MuonAnalysisResultTableCreator::writeDataForSingleFit(
ITableWorkspace_sptr &table,
const QMap<QString, WSParameterList> ¶msByLabel,
const QStringList ¶msToDisplay) const {
assert(!m_multiple);
assert(m_logValues);
for (const auto &wsName : m_items) {
Mantid::API::TableRow row = table->appendRow();
row << wsName.toStdString();
// Get log values for this row
const auto &logValues = m_logValues->value(wsName);
// Write log values in each column
for (int i = 0; i < m_logs.size(); ++i) {
Mantid::API::Column_sptr col = table->getColumn(i);
const auto &log = m_logs[i];
const QVariant &val = logValues[log];
QString valueToWrite;
// Special case: if log is time in sec, subtract the first start time
if (log.endsWith(" (s)")) {
auto seconds =
val.toDouble() - static_cast<double>(m_firstStart_ns) * 1.e-9;
valueToWrite = QString::number(seconds);
} else if (MuonAnalysisHelper::isNumber(val.toString()) &&
!log.endsWith(" (text)")) {
valueToWrite = QString::number(val.toDouble());
} else {
valueToWrite = val.toString();
}
if (MuonAnalysisHelper::isNumber(val.toString()) &&
!log.endsWith(" (text)")) {
row << valueToWrite.toDouble();
} else {
row << valueToWrite.toStdString();
}
}
// Add param values (params same for all workspaces)
QMap<QString, double> paramsList = paramsByLabel.begin()->value(wsName);
for (const auto ¶mName : paramsToDisplay) {
row << paramsList[paramName];
}
}
}
示例15: getProperty
/// Execute
void EstimatePeakErrors::exec() {
IFunction_sptr function = getProperty("Function");
ITableWorkspace_sptr results =
WorkspaceFactory::Instance().createTable("TableWorkspace");
results->addColumn("str", "Parameter");
results->addColumn("double", "Value");
results->addColumn("double", "Error");
auto matrix = function->getCovarianceMatrix();
if (!matrix) {
g_log.warning() << "Function doesn't have covariance matrix.\n";
setProperty("OutputWorkspace", results);
return;
}
IPeakFunction *peak = dynamic_cast<IPeakFunction *>(function.get());
if (peak) {
GSLMatrix covariance(*matrix);
calculatePeakValues(*peak, *results, covariance, "");
} else {
CompositeFunction *cf = dynamic_cast<CompositeFunction *>(function.get());
if (cf) {
size_t ip = 0;
for (size_t i = 0; i < cf->nFunctions(); ++i) {
IFunction *fun = cf->getFunction(i).get();
size_t np = fun->nParams();
peak = dynamic_cast<IPeakFunction *>(fun);
if (peak) {
std::string prefix = "f" + std::to_string(i) + ".";
GSLMatrix covariance(*matrix, ip, ip, np, np);
calculatePeakValues(*peak, *results, covariance, prefix);
}
ip += np;
}
} else {
g_log.warning() << "Function has no peaks.\n";
}
}
setProperty("OutputWorkspace", results);
}