Esempio n. 1
0
/**
 * 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;
}
  /** 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;
  }
Esempio n. 3
0
    /** 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
        {
          for(size_t i=0;i<axis->length();++i)
          {
            int j = axis->spectraNo(i);
            if (j == out.spec)
            {
              out.i = static_cast<int>(i);
              break;
            }
          }
        }
        if (out.i < 0 && out.indx.empty())
        {
          return data;
        }
      }
      else
      {// numeric axis
        out.spec = -1;
        if (out.i >= 0)
        {
          out.indx.clear();
        }
        else
        {
          if (out.i < -1)
          {
            out.start = (*axis)(0);
            out.end = (*axis)(axis->length()-1);
          }
          for(size_t i=0;i<axis->length();++i)
          {
            double s = (*axis)(i);
            if (s >= out.start && s <= out.end)
            {
              out.indx.push_back(static_cast<int>(i));
            }
          }
        }
      }

      return out;
    }