当前位置: 首页>>代码示例>>C++>>正文


C++ IAlgorithm_sptr::initialize方法代码示例

本文整理汇总了C++中api::IAlgorithm_sptr::initialize方法的典型用法代码示例。如果您正苦于以下问题:C++ IAlgorithm_sptr::initialize方法的具体用法?C++ IAlgorithm_sptr::initialize怎么用?C++ IAlgorithm_sptr::initialize使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在api::IAlgorithm_sptr的用法示例。


在下文中一共展示了IAlgorithm_sptr::initialize方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C++代码示例。

示例1: doFitGaussianPeak

/**
 * Fit peak without background i.e, with background removed
 *  inspired from FitPowderDiffPeaks.cpp
 *  copied from PoldiPeakDetection2.cpp
 *
 @param workspaceindex :: indice of the row to use
 @param center :: gaussian parameter - center
 @param sigma :: gaussian parameter - width
 @param height :: gaussian parameter - height
 @param startX :: fit range - start X value
 @param endX :: fit range - end X value
 @returns A boolean status flag, true for fit success, false else
 */
bool ConvertEmptyToTof::doFitGaussianPeak(int workspaceindex, double &center,
                                          double &sigma, double &height,
                                          double startX, double endX) {

  g_log.debug("Calling doFitGaussianPeak...");

  // 1. Estimate
  sigma = sigma * 0.5;

  // 2. Use factory to generate Gaussian
  auto temppeak = API::FunctionFactory::Instance().createFunction("Gaussian");
  auto gaussianpeak = boost::dynamic_pointer_cast<API::IPeakFunction>(temppeak);
  gaussianpeak->setHeight(height);
  gaussianpeak->setCentre(center);
  gaussianpeak->setFwhm(sigma);

  // 3. Constraint
  double centerleftend = center - sigma * 0.5;
  double centerrightend = center + sigma * 0.5;
  std::ostringstream os;
  os << centerleftend << " < PeakCentre < " << centerrightend;
  auto *centerbound = API::ConstraintFactory::Instance().createInitialized(
      gaussianpeak.get(), os.str(), false);
  gaussianpeak->addConstraint(centerbound);

  g_log.debug("Calling createChildAlgorithm : Fit...");
  // 4. Fit
  API::IAlgorithm_sptr fitalg = createChildAlgorithm("Fit", -1, -1, true);
  fitalg->initialize();

  fitalg->setProperty(
      "Function", boost::dynamic_pointer_cast<API::IFunction>(gaussianpeak));
  fitalg->setProperty("InputWorkspace", m_inputWS);
  fitalg->setProperty("WorkspaceIndex", workspaceindex);
  fitalg->setProperty("Minimizer", "Levenberg-MarquardtMD");
  fitalg->setProperty("CostFunction", "Least squares");
  fitalg->setProperty("MaxIterations", 1000);
  fitalg->setProperty("Output", "FitGaussianPeak");
  fitalg->setProperty("StartX", startX);
  fitalg->setProperty("EndX", endX);

  // 5.  Result
  bool successfulfit = fitalg->execute();
  if (!fitalg->isExecuted() || !successfulfit) {
    // Early return due to bad fit
    g_log.warning() << "Fitting Gaussian peak for peak around "
                    << gaussianpeak->centre() << '\n';
    return false;
  }

  // 6. Get result
  center = gaussianpeak->centre();
  height = gaussianpeak->height();
  double fwhm = gaussianpeak->fwhm();

  return fwhm > 0.0;
}
开发者ID:liyulun,项目名称:mantid,代码行数:70,代码来源:ConvertEmptyToTof.cpp

示例2: createChildAlgorithm

  /** Fit function
    * Minimizer: "Levenberg-MarquardtMD"/"Simplex"
   */
  bool RefinePowderInstrumentParameters2::doFitFunction(IFunction_sptr function, Workspace2D_sptr dataws, int wsindex,
                                                        string minimizer, int numiters, double& chi2, string& fitstatus)
  {
    // 0. Debug output
    stringstream outss;
    outss << "Fit function: " << m_positionFunc->asString() << endl << "Data To Fit: \n";
    for (size_t i = 0; i < dataws->readX(0).size(); ++i)
      outss << dataws->readX(wsindex)[i] << "\t\t" << dataws->readY(wsindex)[i] << "\t\t"
            << dataws->readE(wsindex)[i] << "\n";
    g_log.information() << outss.str();

    // 1. Create and setup fit algorithm
    API::IAlgorithm_sptr fitalg = createChildAlgorithm("Fit", 0.0, 0.2, true);
    fitalg->initialize();

    fitalg->setProperty("Function", function);
    fitalg->setProperty("InputWorkspace", dataws);
    fitalg->setProperty("WorkspaceIndex", wsindex);
    fitalg->setProperty("Minimizer", minimizer);
    fitalg->setProperty("CostFunction", "Least squares");
    fitalg->setProperty("MaxIterations", numiters);
    fitalg->setProperty("CalcErrors", true);

    // 2. Fit
    bool successfulfit = fitalg->execute();
    if (!fitalg->isExecuted() || ! successfulfit)
    {
      // Early return due to bad fit
      g_log.warning("Fitting to instrument geometry function failed. ");
      chi2 = DBL_MAX;
      fitstatus = "Minimizer throws exception.";
      return false;
    }

    // 3. Understand solution
    chi2 = fitalg->getProperty("OutputChi2overDoF");
    string tempfitstatus = fitalg->getProperty("OutputStatus");
    fitstatus = tempfitstatus;

    bool goodfit = fitstatus.compare("success") == 0;

    stringstream dbss;
    dbss << "Fit Result (GSL):  Chi^2 = " << chi2
         << "; Fit Status = " << fitstatus << ", Return Bool = " << goodfit << std::endl;
    vector<string> funcparnames = function->getParameterNames();
    for (size_t i = 0; i < funcparnames.size(); ++i)
      dbss << funcparnames[i] << " = " << setw(20) << function->getParameter(funcparnames[i])
           << " +/- " << function->getError(i) << "\n";
    g_log.debug() << dbss.str();

    return goodfit;
  }
开发者ID:trnielsen,项目名称:mantid,代码行数:55,代码来源:RefinePowderInstrumentParameters2.cpp

示例3: createAlgorithmDocs

std::string FrameworkManagerProxy::createAlgorithmDocs(const std::string& algName, const int version)
{
  const std::string EOL="\n";
  API::IAlgorithm_sptr algm = API::AlgorithmManager::Instance().createUnmanaged(algName, version);
  algm->initialize();

  // Put in the quick overview message
  std::stringstream buffer;
  std::string temp = algm->getOptionalMessage();
  if (temp.size() > 0)
    buffer << temp << EOL << EOL;

  // get a sorted copy of the properties
  PropertyVector properties(algm->getProperties());
  std::sort(properties.begin(), properties.end(), PropertyOrdering());

  // generate the sanitized names
  StringVector names(properties.size());
  size_t numProps = properties.size();
  for ( size_t i = 0; i < numProps; ++i) 
  {
    names[i] = removeCharacters(properties[i]->name(), "");
  }

  buffer << "Property descriptions: " << EOL << EOL;
  // write the actual property descriptions
  Mantid::Kernel::Property *prop;
  for ( size_t i = 0; i < numProps; ++i) 
  {
    prop = properties[i];
    buffer << names[i] << "("
           << Mantid::Kernel::Direction::asText(prop->direction());
    if (!prop->isValid().empty())
      buffer << ":req";
    buffer << ") *" << prop->type() << "* ";
    std::set<std::string> allowed = prop->allowedValues();
    if (!prop->documentation().empty() || !allowed.empty())
    {
      buffer << "      " << prop->documentation();
      if (!allowed.empty())
      {
        buffer << " [" << Kernel::Strings::join(allowed.begin(), allowed.end(), ", ");
        buffer << "]";
      }
      buffer << EOL;
      if( i < numProps - 1 ) buffer << EOL;
    }
  }

  return buffer.str();
}
开发者ID:trnielsen,项目名称:mantid,代码行数:51,代码来源:FrameworkManagerProxy.cpp

示例4: createLoader

/**
 * Create the concrete instance use for the actual loading.
 * @param startProgress :: The percentage progress value of the overall
 * algorithm where this child algorithm starts
 * @param endProgress :: The percentage progress value of the overall
 * algorithm where this child algorithm ends
 * @param logging :: Set to false to disable logging from the child algorithm
 */
API::IAlgorithm_sptr Load::createLoader(const double startProgress,
                                        const double endProgress,
                                        const bool logging) const {
  std::string name = getPropertyValue("LoaderName");
  int version = getProperty("LoaderVersion");
  API::IAlgorithm_sptr loader =
      API::AlgorithmManager::Instance().createUnmanaged(name, version);
  loader->initialize();
  if (!loader) {
    throw std::runtime_error("Cannot create loader for \"" +
                             getPropertyValue("Filename") + "\"");
  }
  setUpLoader(loader, startProgress, endProgress, logging);
  return loader;
}
开发者ID:mantidproject,项目名称:mantid,代码行数:23,代码来源:Load.cpp

示例5: reflectometryPeak

/**
  * Gaussian fit to determine peak position if no user position given.
  *
  * @return :: detector position of the peak: Gaussian fit and position
  * of the maximum (serves as start value for the optimization)
  */
double LoadILLReflectometry::reflectometryPeak() {
  if (!isDefault("BeamCentre")) {
    return getProperty("BeamCentre");
  }
  size_t startIndex;
  size_t endIndex;
  std::tie(startIndex, endIndex) =
      fitIntegrationWSIndexRange(*m_localWorkspace);
  IAlgorithm_sptr integration = createChildAlgorithm("Integration");
  integration->initialize();
  integration->setProperty("InputWorkspace", m_localWorkspace);
  integration->setProperty("OutputWorkspace", "__unused_for_child");
  integration->setProperty("StartWorkspaceIndex", static_cast<int>(startIndex));
  integration->setProperty("EndWorkspaceIndex", static_cast<int>(endIndex));
  integration->execute();
  MatrixWorkspace_sptr integralWS = integration->getProperty("OutputWorkspace");
  IAlgorithm_sptr transpose = createChildAlgorithm("Transpose");
  transpose->initialize();
  transpose->setProperty("InputWorkspace", integralWS);
  transpose->setProperty("OutputWorkspace", "__unused_for_child");
  transpose->execute();
  integralWS = transpose->getProperty("OutputWorkspace");
  rebinIntegralWorkspace(*integralWS);
  // determine initial height: maximum value
  const auto maxValueIt =
      std::max_element(integralWS->y(0).cbegin(), integralWS->y(0).cend());
  const double height = *maxValueIt;
  // determine initial centre: index of the maximum value
  const size_t maxIndex = std::distance(integralWS->y(0).cbegin(), maxValueIt);
  const double centreByMax = static_cast<double>(maxIndex);
  g_log.debug() << "Peak maximum position: " << centreByMax << '\n';
  // determine sigma
  const auto &ys = integralWS->y(0);
  auto lessThanHalfMax = [height](const double x) { return x < 0.5 * height; };
  using IterType = HistogramData::HistogramY::const_iterator;
  std::reverse_iterator<IterType> revMaxValueIt{maxValueIt};
  auto revMinFwhmIt = std::find_if(revMaxValueIt, ys.crend(), lessThanHalfMax);
  auto maxFwhmIt = std::find_if(maxValueIt, ys.cend(), lessThanHalfMax);
  std::reverse_iterator<IterType> revMaxFwhmIt{maxFwhmIt};
  if (revMinFwhmIt == ys.crend() || maxFwhmIt == ys.cend()) {
    g_log.warning() << "Couldn't determine fwhm of beam, using position of max "
                       "value as beam center.\n";
    return centreByMax;
  }
  const double fwhm =
      static_cast<double>(std::distance(revMaxFwhmIt, revMinFwhmIt) + 1);
  g_log.debug() << "Initial fwhm (full width at half maximum): " << fwhm
                << '\n';
  // generate Gaussian
  auto func =
      API::FunctionFactory::Instance().createFunction("CompositeFunction");
  auto sum = boost::dynamic_pointer_cast<API::CompositeFunction>(func);
  func = API::FunctionFactory::Instance().createFunction("Gaussian");
  auto gaussian = boost::dynamic_pointer_cast<API::IPeakFunction>(func);
  gaussian->setHeight(height);
  gaussian->setCentre(centreByMax);
  gaussian->setFwhm(fwhm);
  sum->addFunction(gaussian);
  func = API::FunctionFactory::Instance().createFunction("LinearBackground");
  func->setParameter("A0", 0.);
  func->setParameter("A1", 0.);
  sum->addFunction(func);
  // call Fit child algorithm
  API::IAlgorithm_sptr fit = createChildAlgorithm("Fit");
  fit->initialize();
  fit->setProperty("Function",
                   boost::dynamic_pointer_cast<API::IFunction>(sum));
  fit->setProperty("InputWorkspace", integralWS);
  fit->setProperty("StartX", centreByMax - 3 * fwhm);
  fit->setProperty("EndX", centreByMax + 3 * fwhm);
  fit->execute();
  const std::string fitStatus = fit->getProperty("OutputStatus");
  if (fitStatus != "success") {
    g_log.warning("Fit not successful, using position of max value.\n");
    return centreByMax;
  }
  const auto centre = gaussian->centre();
  g_log.debug() << "Sigma: " << gaussian->fwhm() << '\n';
  g_log.debug() << "Estimated peak position: " << centre << '\n';
  return centre;
}
开发者ID:stuartcampbell,项目名称:mantid,代码行数:87,代码来源:LoadILLReflectometry.cpp

示例6: createUnmanagedAlgorithm

/**
 * Creates a managed version of a specified algorithm.
 * @param algName :: The name of the algorithm to execute.
 * @param version :: The version number (default=-1=highest version).
 * @return Pointer to algorithm.
 **/
API::IAlgorithm_sptr FrameworkManagerProxy::createUnmanagedAlgorithm(const std::string& algName, const int version)
{
  API::IAlgorithm_sptr alg = API::AlgorithmManager::Instance().createUnmanaged(algName, version);
  alg->initialize();
  return alg;
}
开发者ID:trnielsen,项目名称:mantid,代码行数:12,代码来源:FrameworkManagerProxy.cpp

示例7: exec

void GoniometerAnglesFromPhiRotation::exec() {

  PeaksWorkspace_sptr PeaksRun1 = getProperty("PeaksWorkspace1");
  PeaksWorkspace_sptr PeaksRun2 = getProperty("PeaksWorkspace2");

  double Tolerance = getProperty("Tolerance");

  Kernel::Matrix<double> Gon1(3, 3);
  Kernel::Matrix<double> Gon2(3, 3);
  if (!CheckForOneRun(PeaksRun1, Gon1) || !CheckForOneRun(PeaksRun2, Gon2)) {
    g_log.error("Each peaks workspace MUST have only one run");
    throw std::invalid_argument("Each peaks workspace MUST have only one run");
  }

  Kernel::Matrix<double> UB1;

  bool Run1HasOrientedLattice = true;
  if (!PeaksRun1->sample().hasOrientedLattice()) {

    Run1HasOrientedLattice = false;

    const std::string fft("FindUBUsingFFT");
    API::IAlgorithm_sptr findUB = this->createChildAlgorithm(fft);
    findUB->initialize();
    findUB->setProperty<PeaksWorkspace_sptr>("PeaksWorkspace",
                                             getProperty("PeaksWorkspace1"));
    findUB->setProperty("MIND", static_cast<double>(getProperty("MIND")));
    findUB->setProperty("MAXD", static_cast<double>(getProperty("MAXD")));
    findUB->setProperty("Tolerance", Tolerance);

    findUB->executeAsChildAlg();

    if (!PeaksRun1->sample().hasOrientedLattice()) {
      g_log.notice(std::string("Could not find UB for ") +
                   std::string(PeaksRun1->getName()));
      throw std::invalid_argument(std::string("Could not find UB for ") +
                                  std::string(PeaksRun1->getName()));
    }
  }
  //-------------get UB raw :No goniometer----------------

  UB1 = PeaksRun1->sample().getOrientedLattice().getUB();

  UB1 = getUBRaw(UB1, Gon1);

  int N1;
  double avErrIndx, avErrAll;
  IndexRaw(PeaksRun1, UB1, N1, avErrIndx, avErrAll, Tolerance);

  if (N1 < .6 * PeaksRun1->getNumberPeaks()) {
    g_log.notice(std::string("UB did not index well for ") +
                 std::string(PeaksRun1->getName()));
    throw std::invalid_argument(std::string("UB did not index well for ") +
                                std::string(PeaksRun1->getName()));
  }

  //----------------------------------------------

  Geometry::OrientedLattice lat2 = PeaksRun1->sample().getOrientedLattice();

  lat2.setUB(UB1);
  PeaksRun2->mutableSample().setOrientedLattice(&lat2);

  if (!Run1HasOrientedLattice)
    PeaksRun1->mutableSample().setOrientedLattice(nullptr);

  double dphi = static_cast<double>(getProperty("Phi2")) -
                static_cast<double>(getProperty("Run1Phi"));
  Kernel::Matrix<double> Gon22(3, 3, true);

  for (int i = 0; i < PeaksRun2->getNumberPeaks(); i++) {
    PeaksRun2->getPeak(i).setGoniometerMatrix(Gon22);
  }

  int RunNum = PeaksRun2->getPeak(0).getRunNumber();
  std::string RunNumStr = std::to_string(RunNum);
  int Npeaks = PeaksRun2->getNumberPeaks();

  // n indexed, av err, phi, chi,omega
  std::array<double, 5> MinData = {{0., 0., 0., 0., 0.}};
  MinData[0] = 0.0;
  std::vector<V3D> directionList = IndexingUtils::MakeHemisphereDirections(50);

  API::FrameworkManager::Instance();

  for (auto dir : directionList)
    for (int sgn = 1; sgn > -2; sgn -= 2) {
      dir.normalize();
      Quat Q(sgn * dphi, dir);
      Q.normalize();
      Kernel::Matrix<double> Rot(Q.getRotation());

      int Nindexed;
      double dummyAvErrIndx, dummyAvErrAll;
      IndexRaw(PeaksRun2, Rot * UB1, Nindexed, dummyAvErrIndx, dummyAvErrAll,
               Tolerance);

      if (Nindexed > MinData[0]) {
        MinData[0] = Nindexed;
        MinData[1] = sgn;
//.........这里部分代码省略.........
开发者ID:mantidproject,项目名称:mantid,代码行数:101,代码来源:GoniometerAnglesFromPhiRotation.cpp

示例8: exec

    /** 
    *   Executes the algorithm
    */
    void PlotPeakByLogValue::exec()
    {

      // Create a list of the input workspace
      const std::vector<InputData> wsNames = makeNames();

      std::string fun = getPropertyValue("Function");
      //int wi = getProperty("WorkspaceIndex");
      std::string logName = getProperty("LogValue");
      bool sequential = getPropertyValue("FitType") == "Sequential";

      bool isDataName = false; // if true first output column is of type string and is the data source name
      ITableWorkspace_sptr result = WorkspaceFactory::Instance().createTable("TableWorkspace");
      if (logName == "SourceName")
      {
        result->addColumn("str","Source name");
        isDataName = true;
      }
      else if (logName.empty())
      {
        result->addColumn("double","axis-1");
      }
      else
      {
        result->addColumn("double",logName);
      }
      // Create an instance of the fitting function to obtain the names of fitting parameters
      IFitFunction* ifun = FunctionFactory::Instance().createInitialized(fun);
      if (!ifun)
      {
        throw std::invalid_argument("Fitting function failed to initialize");
      }
      for(size_t iPar=0;iPar<ifun->nParams();++iPar)
      {
        result->addColumn("double",ifun->parameterName(iPar));
        result->addColumn("double",ifun->parameterName(iPar)+"_Err");
      }
      result->addColumn("double","Chi_squared");
      delete ifun;
      setProperty("OutputWorkspace",result);

      double dProg = 1./static_cast<double>(wsNames.size());
      double Prog = 0.;
      for(int i=0;i<static_cast<int>(wsNames.size());++i)
      {
        InputData data = getWorkspace(wsNames[i]);

        if (!data.ws)
        {
          g_log.warning() << "Cannot access workspace " << wsNames[i].name << '\n';
          continue;
        }

        if (data.i < 0 && data.indx.empty())
        {
          g_log.warning() << "Zero spectra selected for fitting in workspace " << wsNames[i].name << '\n';
          continue;
        }

        int j,jend;
        if (data.i >= 0)
        {
          j = data.i;
          jend = j + 1;
        }
        else
        {// no need to check data.indx.empty()
          j = data.indx.front();
          jend = data.indx.back() + 1;
        }

        dProg /= abs(jend - j);
        for(;j < jend;++j)
        {

          // Find the log value: it is either a log-file value or simply the workspace number
          double logValue;
          if (logName.empty())
          {
            API::Axis* axis = data.ws->getAxis(1);
            logValue = (*axis)(j);
          }
          else if (logName != "SourceName")
          {
            Kernel::Property* prop = data.ws->run().getLogData(logName);
            if (!prop)
            {
              throw std::invalid_argument("Log value "+logName+" does not exist");
            }
            TimeSeriesProperty<double>* logp = 
              dynamic_cast<TimeSeriesProperty<double>*>(prop); 
            logValue = logp->lastValue();
          }

          std::string resFun = fun;
          std::vector<double> errors;
          double chi2;
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例9: getWorkspace

    /** Get a workspace identified by an InputData structure. 
      * @param data :: InputData with name and either spec or i fields defined. 
      * @return InputData structure with the ws field set if everything was OK.
      */
    PlotPeakByLogValue::InputData PlotPeakByLogValue::getWorkspace(const InputData& data)
    {
      InputData out(data);
      if (API::AnalysisDataService::Instance().doesExist(data.name))
      {
        DataObjects::Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(
          API::AnalysisDataService::Instance().retrieve(data.name));
        if (ws)
        {
          out.ws = ws;
        }
        else
        {
          return data;
        }
      }
      else
      {
        std::ifstream fil(data.name.c_str());
        if (!fil)
        {
          g_log.warning() << "File "<<data.name<<" does not exist\n";
          return data;
        }
        fil.close();
        std::string::size_type i = data.name.find_last_of('.');
        if (i == std::string::npos)
        {
          g_log.warning() << "Cannot open file "<<data.name<<"\n";
          return data;
        }
        std::string ext = data.name.substr(i);
        try
        {
          API::IAlgorithm_sptr load = createSubAlgorithm("Load");
          load->initialize();
          load->setPropertyValue("FileName",data.name);
          load->execute();
          if (load->isExecuted())
          {
            API::Workspace_sptr rws = load->getProperty("OutputWorkspace");
            if (rws)
            {
              DataObjects::Workspace2D_sptr ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(rws);
              if (ws) 
              {
                out.ws = ws;
              }
              else
              {
                API::WorkspaceGroup_sptr gws = boost::dynamic_pointer_cast<API::WorkspaceGroup>(rws);
                if (gws)
                {
                  std::vector<std::string> wsNames = gws->getNames();
                  std::string propName = "OUTPUTWORKSPACE_" + boost::lexical_cast<std::string>(data.period);
                  if (load->existsProperty(propName))
                  {
                    Workspace_sptr rws1 = load->getProperty(propName);
                    out.ws = boost::dynamic_pointer_cast<DataObjects::Workspace2D>(rws1);
                  }
                }
              }
            }
          }
        }
        catch(std::exception& e)
        {
          g_log.error(e.what());
          return data;
        }
      }

      if (!out.ws) return data;

      API::Axis* axis = out.ws->getAxis(1);
      if (axis->isSpectra())
      {// spectra axis
        if (out.spec < 0)
        {
          if (out.i >= 0)
          {
            out.spec = axis->spectraNo(out.i);
          }
          else
          {// i < 0 && spec < 0 => use start and end
            for(size_t i=0;i<axis->length();++i)
            {
              double s = double(axis->spectraNo(i));
              if (s >= out.start && s <= out.end)
              {
                out.indx.push_back(static_cast<int>(i));
              }
            }
          }
        }
        else
//.........这里部分代码省略.........
开发者ID:,项目名称:,代码行数:101,代码来源:

示例10: exec

  void MaskBinsFromTable::exec()
  {
    MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
    DataObjects::TableWorkspace_sptr paramWS = getProperty("MaskingInformation");

    // 1. Check input table workspace and column order
    g_log.debug() << "Lines of parameters workspace = " << paramWS->rowCount() << std::endl;

    bool colname_specx = false;
    if (!paramWS)
    {
      throw std::invalid_argument("Input table workspace is not accepted.");
    }
    else
    {
      std::vector<std::string> colnames = paramWS->getColumnNames();
      // check colum name order
      if (colnames.size() < 3)
      {
        g_log.error() << "Input MaskingInformation table workspace has fewer than 3 columns.  " << colnames.size()
                      << " columns indeed" << std::endl;
        throw std::invalid_argument("MaskingInformation (TableWorkspace) has too few columns.");
      }
      if (colnames[0].compare("XMin") == 0)
      {
          // 1. Style XMin, XMax, SpectraList. Check rest
          if (colnames[1].compare("XMax") != 0 || colnames[2].compare("SpectraList") != 0)
          {
              g_log.error() << "INput MaskingInformation table workspace has wrong column order. " << std::endl;
              throw std::invalid_argument("MaskingInformation (TableWorkspace) has too few columns.");
          }
      }
      else if (colnames[0].compare("SpectraList") == 0)
      {
          // 2. Style SpectraList, XMin, XMax
          colname_specx = true;
          if (colnames[1].compare("XMin") != 0 || colnames[2].compare("XMax") != 0)
          {
              g_log.error() << "INput MaskingInformation table workspace has wrong column order. " << std::endl;
              throw std::invalid_argument("MaskingInformation (TableWorkspace) has too few columns.");
          }
      }
      else
      {
          g_log.error() << "INput MaskingInformation table workspace has wrong column order. " << std::endl;
          throw std::invalid_argument("MaskingInformation (TableWorkspace) has too few columns.");
      }
    }

    // 2. Loop over all rows
    bool firstloop = true;
    API::MatrixWorkspace_sptr outputws = this->getProperty("OutputWorkspace");

    for (size_t ib = 0; ib < paramWS->rowCount(); ++ib)
    {
      API::TableRow therow = paramWS->getRow(ib);
      double xmin, xmax;
      std::string speclist;
      if (colname_specx)
      {
          therow >> speclist >> xmin >> xmax;
      }
      else
      {
          therow >> xmin >> xmax >> speclist;
      }

      g_log.debug() << "Row " << ib << " XMin = " << xmin << "  XMax = " << xmax << " SpectraList = " << speclist << std::endl;

      API::IAlgorithm_sptr maskbins = this->createChildAlgorithm("MaskBins", 0, 0.3, true);
      maskbins->initialize();
      if (firstloop)
      {
        maskbins->setProperty("InputWorkspace", inputWS);
        firstloop = false;
      }
      else
      {
        maskbins->setProperty("InputWorkspace", outputws);
      }
      maskbins->setProperty("OutputWorkspace", outputws);
      maskbins->setPropertyValue("SpectraList", speclist);
      maskbins->setProperty("XMin", xmin);
      maskbins->setProperty("XMax", xmax);

      bool isexec = maskbins->execute();
      if (!isexec)
      {
        g_log.error() << "MaskBins() is not executed for row " << ib << std::endl;
        throw std::runtime_error("MaskBins() is not executed");
      }

      outputws = maskbins->getProperty("OutputWorkspace");
      if (!outputws)
      {
        g_log.error() << "OutputWorkspace is not retrieved for row " << ib << ". " << std::endl;
        throw std::runtime_error("OutputWorkspace is not got from MaskBins");
      }
    }
开发者ID:trnielsen,项目名称:mantid,代码行数:99,代码来源:MaskBinsFromTable.cpp


注:本文中的api::IAlgorithm_sptr::initialize方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。