/**
 * 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);
  }
}
/** 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);
      }
    }
  }
Exemple #3
0
/** 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);
}
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;
}
Exemple #5
0
/**
 * 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.");
}
/**
 * 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;
}
    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;
    }
/**
 * 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.");
  }
}
Exemple #9
0
/// 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;
}
/** 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);
}
Exemple #11
0
/**
 * 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)));
}
  /**
   * 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
    }
  }
Exemple #13
0
/**
 * 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;
}
/**
 * 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> &paramsByLabel,
    const QStringList &paramsToDisplay) 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 &paramName : paramsToDisplay) {
      row << paramsList[paramName];
    }
  }
}
/// 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);
}
/** Constructor
@param tableWorkspace : The table workspace to wrap
@param whitelist : A DataProcessorWhiteList containing the columns
*/
QDataProcessorOneLevelTreeModel::QDataProcessorOneLevelTreeModel(
    ITableWorkspace_sptr tableWorkspace,
    const DataProcessorWhiteList &whitelist)
    : m_tWS(tableWorkspace), m_whitelist(whitelist) {

  if (tableWorkspace->columnCount() != m_whitelist.size())
    throw std::invalid_argument(
        "Invalid table workspace. Table workspace must "
        "have the same number of columns as the white list");
}
int PoldiFitPeaks1D2::getBestChebyshevPolynomialDegree(
    const Workspace2D_sptr &dataWorkspace, const RefinedRange_sptr &range) {
  double chiSquareMin = 1e10;
  int nMin = -1;

  try {
    int n = 0;

    while ((n < 3)) {
      IAlgorithm_sptr fit = getFitAlgorithm(dataWorkspace, range, n);
      bool fitSuccess = fit->execute();

      if (fitSuccess) {
        ITableWorkspace_sptr fitCharacteristics =
            fit->getProperty("OutputParameters");
        TableRow row =
            fitCharacteristics->getRow(fitCharacteristics->rowCount() - 1);

        double chiSquare = row.Double(1);

        if (fabs(chiSquare - 1) < fabs(chiSquareMin - 1)) {
          chiSquareMin = chiSquare;
          nMin = n;
        }
      }

      ++n;
    }
  } catch (std::runtime_error) {
    nMin = -1;
  }

  if (nMin == -1) {
    g_log.information() << "Range [" << range->getXStart() << " - "
                        << range->getXEnd() << "] is excluded.";
  } else {
    g_log.information() << "Chi^2 for range [" << range->getXStart() << " - "
                        << range->getXEnd() << "] is minimal at n = " << nMin
                        << " with Chi^2 = " << chiSquareMin << std::endl;
  }

  return nMin;
}
/** Constructor
@param tableWorkspace : The table workspace to wrap
@param whitelist : A DataProcessorWhiteList containing information about the
columns, their indices and descriptions
*/
QDataProcessorTreeModel::QDataProcessorTreeModel(
    ITableWorkspace_sptr tableWorkspace,
    const DataProcessorWhiteList &whitelist)
    : m_tWS(tableWorkspace), m_whitelist(whitelist) {

  if (tableWorkspace->columnCount() != m_whitelist.size() + 1)
    throw std::invalid_argument("Invalid table workspace. Table workspace must "
                                "have one extra column accounting for groups");

  setupModelData(tableWorkspace);
}
std::vector<size_t>
ConcretePeaksPresenter::findVisiblePeakIndexes(const PeakBoundingBox &box) {
  std::vector<size_t> indexes;
  // Don't bother to find peaks in the region if there are no peaks to find.
  if (this->m_peaksWS->getNumberPeaks() >= 1) {

    double radius =
        m_viewPeaks
            ->getRadius(); // Effective radius of each peak representation.

    Mantid::API::IPeaksWorkspace_sptr peaksWS =
        boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(
            this->m_peaksWS);

    PeakBoundingBox transformedViewableRegion = box.makeSliceBox(radius);

    transformedViewableRegion.transformBox(m_transform);

    Mantid::API::IAlgorithm_sptr alg =
        AlgorithmManager::Instance().create("PeaksInRegion");
    alg->setChild(true);
    alg->setRethrows(true);
    alg->initialize();
    alg->setProperty("InputWorkspace", peaksWS);
    alg->setProperty("OutputWorkspace", peaksWS->name() + "_peaks_in_region");
    alg->setProperty("Extents", transformedViewableRegion.toExtents());
    alg->setProperty("CheckPeakExtents", false); // consider all peaks as points
    alg->setProperty("PeakRadius", radius);
    alg->setPropertyValue("CoordinateFrame", m_transform->getFriendlyName());
    alg->execute();
    ITableWorkspace_sptr outTable = alg->getProperty("OutputWorkspace");

    for (size_t i = 0; i < outTable->rowCount(); ++i) {
      const bool insideRegion = outTable->cell<Boolean>(i, 1);
      if (insideRegion) {
        indexes.push_back(i);
      }
    }
  }
  return indexes;
}
void ConvertTableToMatrixWorkspace::exec()
{
  ITableWorkspace_sptr inputWorkspace = getProperty("InputWorkspace");
  std::string columnX = getProperty("ColumnX");
  std::string columnY = getProperty("ColumnY");
  std::string columnE = getProperty("ColumnE");

  size_t nrows = inputWorkspace->rowCount();
  std::vector<double> X(nrows);
  std::vector<double> Y(nrows);
  std::vector<double> E(nrows);

  inputWorkspace->getColumn(columnX)->numeric_fill(X);
  inputWorkspace->getColumn(columnY)->numeric_fill(Y);

  if (!columnE.empty())
  {
    inputWorkspace->getColumn(columnE)->numeric_fill(E);
  }
  else
  {
    E.assign(X.size(),1.0);
  }

  MatrixWorkspace_sptr outputWorkspace = WorkspaceFactory::Instance().create("Workspace2D",1,X.size(),X.size());
  outputWorkspace->dataX(0).assign(X.begin(),X.end());
  outputWorkspace->dataY(0).assign(Y.begin(),Y.end());
  outputWorkspace->dataE(0).assign(E.begin(),E.end());

  outputWorkspace->generateSpectraMap();
  boost::shared_ptr<Kernel::Units::Label> labelX = boost::dynamic_pointer_cast<Kernel::Units::Label>(
    Kernel::UnitFactory::Instance().create("Label")
    );
  labelX->setLabel(columnX);
  outputWorkspace->getAxis(0)->unit() = labelX;

  outputWorkspace->setYUnitLabel(columnY);

  setProperty("OutputWorkspace", outputWorkspace);

}
ITableWorkspace_sptr ALCBaselineModellingModel::exportSections() {
  if (!m_sections.empty()) {

    ITableWorkspace_sptr table =
        WorkspaceFactory::Instance().createTable("TableWorkspace");

    table->addColumn("double", "Start X");
    table->addColumn("double", "End X");

    for (auto it = m_sections.begin(); it != m_sections.end(); ++it) {
      TableRow newRow = table->appendRow();
      newRow << it->first << it->second;
    }

    return table;

  } else {

    return ITableWorkspace_sptr();
  }
}
Exemple #22
0
/**
 * Sets a new preview spectrum for the mini plot.
 *
 * @param value workspace index
 */
void ResNorm::previewSpecChanged(int value) {
  m_previewSpec = value;

  // Update vanadium plot
  if (m_uiForm.dsVanadium->isValid())
    m_uiForm.ppPlot->addSpectrum(
        "Vanadium", m_uiForm.dsVanadium->getCurrentDataName(), m_previewSpec);

  // Update fit plot
  std::string fitWsGroupName(m_pythonExportWsName + "_Fit_Workspaces");
  std::string fitParamsName(m_pythonExportWsName + "_Fit");
  if (AnalysisDataService::Instance().doesExist(fitWsGroupName)) {
    WorkspaceGroup_sptr fitWorkspaces =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            fitWsGroupName);
    ITableWorkspace_sptr fitParams =
        AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(
            fitParamsName);
    if (fitWorkspaces && fitParams) {
      Column_const_sptr scaleFactors = fitParams->getColumn("Scaling");
      std::string fitWsName(fitWorkspaces->getItem(m_previewSpec)->name());
      MatrixWorkspace_const_sptr fitWs =
          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
              fitWsName);

      MatrixWorkspace_sptr fit = WorkspaceFactory::Instance().create(fitWs, 1);
      fit->setX(0, fitWs->readX(1));
      fit->getSpectrum(0)->setData(fitWs->readY(1), fitWs->readE(1));

      for (size_t i = 0; i < fit->blocksize(); i++)
        fit->dataY(0)[i] /= scaleFactors->cell<double>(m_previewSpec);

      m_uiForm.ppPlot->addSpectrum("Fit", fit, 0, Qt::red);
    }
  }
}
Exemple #23
0
void LoadDNSSCD::loadHuber(ITableWorkspace_sptr tws) {
  ColumnVector<double> huber = tws->getVector("Huber(degrees)");
  // set huber[0] for each run in m_data
  for (auto &ds : m_data) {
    ds.huber = huber[0];
  }
  // dublicate runs for each huber in the table
  std::vector<ExpData> old(m_data);
  for (size_t i = 1; i < huber.size(); ++i) {
    for (auto &ds : old) {
      ds.huber = huber[i];
      m_data.push_back(ds);
    }
  }
}
/**
 * Creates an output workspace from calculated and observed values
 *
 * This method creates a table workspace for an ILatticeFunction, containing
 * observed and calculated d-values for each HKL, as well as the difference
 * between those two values.
 *
 * @param baseName :: Basename for output workspace.
 * @param function :: An ILatticeFunction
 * @param domain :: Pointer to LatticeDomain instance.
 * @param values :: Pointer to FunctionValues instance.
 * @param outputWorkspacePropertyName :: Name of output workspace property.
 * @return TableWorkspace with calculated and observed d-values.
 */
Workspace_sptr LatticeDomainCreator::createOutputWorkspace(
    const std::string &baseName, IFunction_sptr function,
    boost::shared_ptr<FunctionDomain> domain,
    boost::shared_ptr<FunctionValues> values,
    const std::string &outputWorkspacePropertyName) {

  boost::shared_ptr<LatticeDomain> latticeDomain =
      boost::dynamic_pointer_cast<LatticeDomain>(domain);
  if (!latticeDomain) {
    throw std::invalid_argument("LatticeDomain is required.");
  }

  ILatticeFunction_sptr latticeFunction =
      boost::dynamic_pointer_cast<ILatticeFunction>(function);
  if (!latticeFunction) {
    throw std::invalid_argument(
        "LatticeDomainCreator can only process ILatticeFunction.");
  }

  // Calculate function values again.
  latticeFunction->functionLattice(*latticeDomain, *values);

  ITableWorkspace_sptr tableWorkspace =
      WorkspaceFactory::Instance().createTable();

  if (tableWorkspace) {
    tableWorkspace->addColumn("V3D", "HKL");
    tableWorkspace->addColumn("double", "d(obs)");
    tableWorkspace->addColumn("double", "d(calc)");
    tableWorkspace->addColumn("double", "d(obs) - d(calc)");

    for (size_t i = 0; i < values->size(); ++i) {
      double dObs = values->getFitData(i);
      double dCalc = values->getCalculated(i);

      TableRow newRow = tableWorkspace->appendRow();
      newRow << (*latticeDomain)[i] << dObs << dCalc << dObs - dCalc;
    }
  }

  if (m_manager && !outputWorkspacePropertyName.empty()) {
    declareProperty(
        new WorkspaceProperty<ITableWorkspace>(outputWorkspacePropertyName, "",
                                               Kernel::Direction::Output),
        "Result workspace");

    m_manager->setPropertyValue(outputWorkspacePropertyName,
                                baseName + "Workspace");
    m_manager->setProperty(outputWorkspacePropertyName, tableWorkspace);
  }

  return tableWorkspace;
}
/** Setup the data, initialize member variables using a table workspace and
* whitelist
* @param table : A table workspace containing the data
*/
void QDataProcessorTreeModel::setupModelData(ITableWorkspace_sptr table) {

  int nrows = static_cast<int>(table->rowCount());

  int lastIndex = 0;
  std::map<std::string, int> groupIndex;

  for (int r = 0; r < nrows; r++) {

    const std::string &groupName = m_tWS->String(r, 0);

    if (groupIndex.count(groupName) == 0) {
      groupIndex[groupName] = lastIndex++;

      m_groupName.push_back(groupName);
      m_rowsOfGroup.push_back(std::vector<int>());
    }

    m_rowsOfGroup[groupIndex[groupName]].push_back(r);
  }
}
Exemple #26
0
/**
 * Construct a Grouping from a table
 * @param table :: [input] Table to construct from
 */
Grouping::Grouping(ITableWorkspace_sptr table) {
  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 = Kernel::Strings::toString(detectors);

    this->groupNames.push_back(std::to_string(row + 1));
    this->groups.push_back(detectorRange);
  }

  // If we have 2 groups only - create a longitudinal pair
  if (this->groups.size() == 2) {
    this->pairNames.emplace_back("long");
    this->pairAlphas.push_back(1.0);
    this->pairs.emplace_back(0, 1);
  }
}
Exemple #27
0
/// Inserts statistics the supplied PeaksStatistics-objects into the supplied
/// TableWorkspace.
void SortHKL::insertStatisticsIntoTable(
    const ITableWorkspace_sptr &table,
    const PeaksStatistics &statistics) const {
  if (!table) {
    throw std::runtime_error("Can't store statistics into Null-table.");
  }

  std::string name = getProperty("RowName");
  double completeness = 0.0;
  if (name.substr(0, 4) != "bank") {
    completeness = static_cast<double>(statistics.m_completeness);
  }

  // append to the table workspace
  API::TableRow newrow = table->appendRow();

  newrow << name << statistics.m_uniqueReflections << statistics.m_dspacingMin
         << statistics.m_dspacingMax << statistics.m_redundancy
         << statistics.m_meanIOverSigma << 100.0 * statistics.m_rMerge
         << 100.0 * statistics.m_rPim << 100.0 * completeness;
}
/** Execute the algorithm.
 */
void CreateChunkingFromInstrument::exec() {
  // get the instrument
  Instrument_const_sptr inst = this->getInstrument();

  // setup the output workspace
  ITableWorkspace_sptr strategy =
      WorkspaceFactory::Instance().createTable("TableWorkspace");
  strategy->addColumn("str", "BankName");
  this->setProperty("OutputWorkspace", strategy);

  // get the correct level of grouping
  string groupLevel = this->getPropertyValue(PARAM_CHUNK_BY);
  vector<string> groupNames =
      getGroupNames(this->getPropertyValue(PARAM_CHUNK_NAMES));
  if (groupLevel.compare("All") == 0) {
    return; // nothing to do
  } else if (inst->getName().compare("SNAP") == 0 &&
             groupLevel.compare("Group") == 0) {
    groupNames.clear();
    groupNames.push_back("East");
    groupNames.push_back("West");
  }

  // set up a progress bar with the "correct" number of steps
  int maxBankNum = this->getProperty(PARAM_MAX_BANK_NUM);
  Progress progress(this, .2, 1., maxBankNum);

  // search the instrument for the bank names
  int maxRecurseDepth = this->getProperty(PARAM_MAX_RECURSE);
  map<string, vector<string>> grouping;
  // cppcheck-suppress syntaxError
    PRAGMA_OMP(parallel for schedule(dynamic, 1) )
    for (int num = 0; num < maxBankNum; ++num) {
      PARALLEL_START_INTERUPT_REGION
      ostringstream mess;
      mess << "bank" << num;
      IComponent_const_sptr comp =
          inst->getComponentByName(mess.str(), maxRecurseDepth);
      PARALLEL_CRITICAL(grouping)
      if (comp) {
        // get the name of the correct parent
        string parent;
        if (groupNames.empty()) {
          parent = parentName(comp, groupLevel);
        } else {
          parent = parentName(comp, groupNames);
        }

        // add it to the correct chunk
        if (!parent.empty()) {
          if (grouping.count(parent) == 0)
            grouping[parent] = vector<string>();

          grouping[parent].push_back(comp->getName());
        }
      }
      progress.report();
      PARALLEL_END_INTERUPT_REGION
    }
    PARALLEL_CHECK_INTERUPT_REGION

    // check to see that something happened
    if (grouping.empty())
      throw std::runtime_error("Failed to find any banks in the instrument");

    // fill in the table workspace
    for (auto group = grouping.begin(); group != grouping.end(); ++group) {
      stringstream banks;
      for (auto bank = group->second.begin(); bank != group->second.end();
           ++bank)
        banks << (*bank) << ",";

      // remove the trailing comma
      string banksStr = banks.str();
      banksStr = banksStr.substr(0, banksStr.size() - 1);

      // add it to the table
      TableRow row = strategy->appendRow();
      row << banksStr;
    }
}
Exemple #29
0
//----------------------------------------------------------------------------------------------
/// Run the algorithm
void QueryMDWorkspace::exec() {
    // Extract the required normalisation.
    std::string strNormalisation = getPropertyValue("Normalisation");
    MDNormalization requestedNormalisation = whichNormalisation(strNormalisation);

    IMDWorkspace_sptr input = getProperty("InputWorkspace");

    const bool transformCoordsToOriginal = getProperty("TransformCoordsToOriginal");

    // Define a table workspace with a specific column schema.
    ITableWorkspace_sptr output = WorkspaceFactory::Instance().createTable();
    const std::string signalColumnName = "Signal/" + strNormalisation;
    const std::string errorColumnName = "Error/" + strNormalisation;
    output->addColumn("double", signalColumnName);
    output->addColumn("double", errorColumnName);
    output->addColumn("int", "Number of Events");

    const size_t ndims = input->getNumDims();
    for (size_t index = 0; index < ndims; ++index) {
        Mantid::Geometry::IMDDimension_const_sptr dim = input->getDimension(index);
        std::string dimInUnit = dim->getName() + "/" + dim->getUnits().ascii();
        output->addColumn("double", dimInUnit);
        // Magic numbers required to configure the X axis.
        output->getColumn(dimInUnit)->setPlotType(1);
    }

    // Magic numbers required to configure the Y axis.
    output->getColumn(signalColumnName)->setPlotType(2);
    output->getColumn(errorColumnName)->setPlotType(5);

    IMDIterator *it = input->createIterator();
    it->setNormalization(requestedNormalisation);

    bool bLimitRows = getProperty("LimitRows");
    int maxRows = 0;
    if (bLimitRows) {
        maxRows = getProperty("MaximumRows");
    }

    // Use the iterator to loop through each MDBoxBase and create a row for each
    // entry.
    int rowCounter = 0;

    Progress progress(this, 0, 1, int64_t(input->getNPoints()));
    while (true) {
        size_t cellIndex = 0;
        output->appendRow();
        output->cell<double>(rowCounter, cellIndex++) = it->getNormalizedSignal();
        output->cell<double>(rowCounter, cellIndex++) = it->getNormalizedError();
        output->cell<int>(rowCounter, cellIndex++) = int(it->getNumEvents());
        VMD center = it->getCenter();
        const size_t numberOriginal = input->getNumberTransformsToOriginal();
        if (transformCoordsToOriginal && numberOriginal > 0) {
            const size_t index = numberOriginal - 1;
            CoordTransform const *transform = input->getTransformToOriginal(index);
            VMD temp = transform->applyVMD(center);
            center = temp;
        }

        for (size_t index = 0; index < ndims; ++index) {
            output->cell<double>(rowCounter, cellIndex++) = center[index];
        }

        progress.report();
        if (!it->next() || (bLimitRows && ((rowCounter + 1) >= maxRows))) {
            break;
        }
        rowCounter++;
    }
    setProperty("OutputWorkspace", output);
    delete it;

    //
    IMDEventWorkspace_sptr mdew;
    CALL_MDEVENT_FUNCTION(this->getBoxData, input);
}
Exemple #30
0
/**
*   Executes the algorithm.
*/
void LoadTBL::exec() {
  std::string filename = getProperty("Filename");
  std::ifstream file(filename.c_str());
  if (!file) {
    throw Exception::FileError("Unable to open file: ", filename);
  }
  std::string line;

  ITableWorkspace_sptr ws = WorkspaceFactory::Instance().createTable();

  std::vector<std::string> columnHeadings;

  Kernel::Strings::extractToEOL(file, line);
  // We want to check if the first line contains an empty string or series of
  // ",,,,,"
  // to see if we are loading a TBL file that actually contains data or not.
  boost::split(columnHeadings, line, boost::is_any_of(","),
               boost::token_compress_off);
  for (auto entry = columnHeadings.begin(); entry != columnHeadings.end();) {
    if (entry->empty()) {
      // erase the empty values
      entry = columnHeadings.erase(entry);
    } else {
      // keep any non-empty values
      ++entry;
    }
  }
  if (columnHeadings.empty()) {
    // we have an empty string or series of ",,,,,"
    throw std::runtime_error("The file you are trying to load is Empty. \n "
                             "Please load a non-empty TBL file");
  } else {
    // set columns back to empty ready to populated with columnHeadings.
    columnHeadings.clear();
  }
  // this will tell us if we need to just fill in the cell values
  // or whether we will have to create the column headings as well.
  bool isOld = getColumnHeadings(line, columnHeadings);

  std::vector<std::string> rowVec;
  if (isOld) {
    /**THIS IS ESSENTIALLY THE OLD LoadReflTBL CODE**/
    // create the column headings
    auto colStitch = ws->addColumn("str", "StitchGroup");
    auto colRuns = ws->addColumn("str", "Run(s)");
    auto colTheta = ws->addColumn("str", "ThetaIn");
    auto colTrans = ws->addColumn("str", "TransRun(s)");
    auto colQmin = ws->addColumn("str", "Qmin");
    auto colQmax = ws->addColumn("str", "Qmax");
    auto colDqq = ws->addColumn("str", "dq/q");
    auto colScale = ws->addColumn("str", "Scale");
    auto colOptions = ws->addColumn("str", "Options");
    auto colHiddenOptions = ws->addColumn("str", "HiddenOptions");

    for (size_t i = 0; i < ws->columnCount(); i++) {
      auto col = ws->getColumn(i);
      col->setPlotType(0);
    }

    // we are using the old ReflTBL format
    // where all of the entries are on one line
    // so we must reset the stream to reread the first line.
    std::ifstream file(filename.c_str());
    if (!file) {
      throw Exception::FileError("Unable to open file: ", filename);
    }
    std::string line;
    int stitchID = 1;
    while (Kernel::Strings::extractToEOL(file, line)) {
      if (line.empty() || line == ",,,,,,,,,,,,,,,,") {
        continue;
      }
      getCells(line, rowVec, 16, isOld);
      const std::string scaleStr = rowVec.at(16);
      const std::string stitchStr = boost::lexical_cast<std::string>(stitchID);

      // check if the first run in the row has any data associated with it
      // 0 = runs, 1 = theta, 2 = trans, 3 = qmin, 4 = qmax
      if (!rowVec[0].empty() || !rowVec[1].empty() || !rowVec[2].empty() ||
          !rowVec[3].empty() || !rowVec[4].empty()) {
        TableRow row = ws->appendRow();
        row << stitchStr;
        for (int i = 0; i < 5; ++i) {
          row << rowVec.at(i);
        }
        row << rowVec.at(15);
        row << scaleStr;
      }

      // check if the second run in the row has any data associated with it
      // 5 = runs, 6 = theta, 7 = trans, 8 = qmin, 9 = qmax
      if (!rowVec[5].empty() || !rowVec[6].empty() || !rowVec[7].empty() ||
          !rowVec[8].empty() || !rowVec[9].empty()) {
        TableRow row = ws->appendRow();
        row << stitchStr;
        for (int i = 5; i < 10; ++i) {
          row << rowVec.at(i);
        }
        row << rowVec.at(15);
        row << scaleStr;
      }

      // check if the third run in the row has any data associated with it
      // 10 = runs, 11 = theta, 12 = trans, 13 = qmin, 14 = qmax
      if (!rowVec[10].empty() || !rowVec[11].empty() || !rowVec[12].empty() ||
          !rowVec[13].empty() || !rowVec[14].empty()) {
        TableRow row = ws->appendRow();
        row << stitchStr;
        for (int i = 10; i < 17; ++i) {
          if (i == 16)
            row << scaleStr;
          else
            row << rowVec.at(i);
        }
      }
      ++stitchID;
      setProperty("OutputWorkspace", ws);
    }

  } else {
    // we have a TBL format that contains column headings
    // on the first row. These are now entries in the columns vector
    if (!columnHeadings.empty()) {
      // now we need to add the custom column headings from
      // the columns vector to the TableWorkspace
      for (auto heading = columnHeadings.begin();
           heading != columnHeadings.end();) {
        if (heading->empty()) {
          // there is no need to have empty column headings.
          heading = columnHeadings.erase(heading);
        } else {
          Mantid::API::Column_sptr col;
          col = ws->addColumn("str", *heading);
          col->setPlotType(0);
          heading++;
        }
      }
    }
    size_t expectedCommas = columnHeadings.size() - 1;
    while (Kernel::Strings::extractToEOL(file, line)) {
      if (line.empty() || line == ",,,,,,,,,,,,,,,,") {
        // skip over any empty lines
        continue;
      }
      getCells(line, rowVec, columnHeadings.size() - 1, isOld);
      // populate the columns with their values for this row.
      TableRow row = ws->appendRow();
      for (size_t i = 0; i < expectedCommas + 1; ++i) {
        row << rowVec.at(i);
      }
    }
    setProperty("OutputWorkspace", ws);
  }
}