Esempio n. 1
0
/** Load PhaseTable file to a vector of HistData.
* @param phaseTable :: [input] phase table containing detector info
* @param deadTimeTable :: [output] phase table containing dead times
*/
void PhaseQuadMuon::loadPhaseTable(API::ITableWorkspace_sptr phaseTable, API::ITableWorkspace_sptr deadTimeTable)
{
  if ( phaseTable->rowCount() )
  {
    if ( phaseTable->columnCount()<4 )
    {
      throw std::invalid_argument("PhaseQuad: PhaseTable must contain at least four columns");
    }

    // Check number of histograms in inputWs match number of detectors in phase table
    if (m_nHist != static_cast<int>(phaseTable->rowCount()))
    {
      throw std::runtime_error("PhaseQuad: Number of histograms in phase table does not match number of spectra in workspace");
    }

    for (size_t i=0; i<phaseTable->rowCount(); ++i)
    {
      API::TableRow phaseRow = phaseTable->getRow(i);

      // The first three columns go to m_histData
      HistData tempHist;
      tempHist.detOK = phaseRow.Bool(0);
      tempHist.alpha = phaseRow.Double(1);
      tempHist.phi   = phaseRow.Double(2);
      m_histData.push_back(tempHist);

      // The last column goes to deadTimeTable
      API::TableRow deadRow = deadTimeTable->appendRow();
      deadRow << static_cast<int>(i)+1 << phaseRow.Double(3);
    }

  }
  else
  {
    throw std::invalid_argument("PhaseQuad: PhaseTable is empty");
  }

}
Esempio n. 2
0
void EnggDiffFittingModel::mergeTables(
    const API::ITableWorkspace_sptr tableToCopy,
    API::ITableWorkspace_sptr targetTable) const {
  for (size_t i = 0; i < tableToCopy->rowCount(); ++i) {
    API::TableRow rowToCopy = tableToCopy->getRow(i);
    API::TableRow newRow = targetTable->appendRow();

    for (size_t j = 0; j < tableToCopy->columnCount(); ++j) {
      double valueToCopy;
      rowToCopy >> valueToCopy;
      newRow << valueToCopy;
    }
  }
}
/* This function fills in a list of the row numbers starting 0 of the parameters
   in the table workspace, so one can find the position in a column of
   the value of the given parameter.
*/
void LoadFullprofResolution::getTableRowNumbers(
    const API::ITableWorkspace_sptr &tablews,
    std::map<std::string, size_t> &parammap) {
  parammap.clear();

  size_t numrows = tablews->rowCount();
  for (size_t i = 0; i < numrows; ++i) {
    TableRow row = tablews->getRow(i);
    std::string name;
    row >> name;
    parammap.emplace(name, i);
  }

  return;
}
Esempio n. 4
0
size_t LatticeDomainCreator::getDomainSize() const {
  API::IPeaksWorkspace_sptr peaksWorkspace =
      boost::dynamic_pointer_cast<IPeaksWorkspace>(m_workspace);
  if (peaksWorkspace) {
    return peaksWorkspace->getNumberPeaks();
  }

  API::ITableWorkspace_sptr tableWorkspace =
      boost::dynamic_pointer_cast<ITableWorkspace>(m_workspace);
  if (tableWorkspace) {
    return tableWorkspace->rowCount();
  }

  return 0;
}
void SaveDiffFittingAscii::writeData(const API::ITableWorkspace_sptr workspace,
                                     std::ofstream &file,
                                     const size_t columnSize) {

  for (size_t rowIndex = 0; rowIndex < workspace->rowCount(); ++rowIndex) {
    TableRow row = workspace->getRow(rowIndex);
    for (size_t columnIndex = 0; columnIndex < columnSize; columnIndex++) {

      const auto row_str =
          boost::lexical_cast<std::string>(row.Double(columnIndex));
      g_log.debug() << row_str << std::endl;

      if (columnIndex == columnSize - 1)
        writeVal(row_str, file, true);
      else
        writeVal(row_str, file, false);
    }
  }
}
/**
 * Fit the asymmetry and return the frequency found.
 * Starting value for the frequency is taken from the hint.
 * If the fit fails, return the initial hint.
 * @param wsAsym :: [input] Workspace with asymmetry to fit
 * @return :: Frequency found from fit
 */
double CalMuonDetectorPhases::fitFrequencyFromAsymmetry(
    const API::MatrixWorkspace_sptr &wsAsym) {
  // Starting value for frequency is hint
  double hint = getFrequencyHint();
  std::string funcStr = createFittingFunction(hint, false);
  double frequency = hint;

  std::string fitStatus = "success";
  try {
    auto func = API::FunctionFactory::Instance().createInitialized(funcStr);
    auto fit = createChildAlgorithm("Fit");
    fit->setProperty("Function", func);
    fit->setProperty("InputWorkspace", wsAsym);
    fit->setProperty("WorkspaceIndex", 0);
    fit->setProperty("CreateOutput", true);
    fit->setProperty("OutputParametersOnly", true);
    fit->setProperty("Output", "__Invisible");
    fit->executeAsChildAlg();
    fitStatus = fit->getPropertyValue("OutputStatus");
    if (fitStatus == "success") {
      API::ITableWorkspace_sptr params = fit->getProperty("OutputParameters");
      const size_t rows = params->rowCount();
      static size_t colName(0), colValue(1);
      for (size_t iRow = 0; iRow < rows; iRow++) {
        if (params->cell<std::string>(iRow, colName) == "w") {
          frequency = params->cell<double>(iRow, colValue);
          break;
        }
      }
    }
  } catch (const std::exception &e) {
    // Report fit failure to user
    fitStatus = e.what();
  }
  if (fitStatus != "success") { // Either failed, or threw an exception
    std::ostringstream message;
    message << "Fit failed (" << fitStatus << "), using omega hint = " << hint;
    g_log.error(message.str());
  }
  return frequency;
}
/**
 * Parse the (optional) exp.ini file found on NOMAD
 * @param filename full path to a exp.ini file
 * @param wksp The table workspace to modify.
 */
void PDLoadCharacterizations::readExpIni(const std::string &filename,
                                         API::ITableWorkspace_sptr &wksp) {
  if (wksp->rowCount() == 0)
    throw std::runtime_error("Characterizations file does not have any "
                             "characterizations information");

  std::ifstream file(filename.c_str());
  if (!file) {
    throw Exception::FileError("Unable to open file", filename);
  }

  // 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;

    // split the line and see if it has something meaningful
    std::vector<std::string> splitted;
    boost::split(splitted, line, boost::is_any_of("\t "),
                 boost::token_compress_on);
    if (splitted.size() < 2)
      continue;

    // update the various charaterization runs
    if (splitted[0] == EXP_INI_VAN_KEY) {
      wksp->getRef<std::string>("vanadium", 0) = splitted[1];
    } else if (splitted[0] == EXP_INI_EMPTY_KEY) {
      wksp->getRef<std::string>("container", 0) = splitted[1];
    } else if (splitted[0] == EXP_INI_CAN_KEY) {
      wksp->getRef<std::string>("empty", 0) = splitted[1];
    }
  }
}
Esempio n. 8
0
    /** Executes the algorithm. Moving detectors of input workspace to positions indicated in table workspace
    *
    *  @throw FileError Thrown if unable to get instrument from workspace, 
    *                   table workspace is incompatible with instrument
    */
    void ApplyCalibration::exec()
    {
      // Get pointers to the workspace, parameter map and table
      API::MatrixWorkspace_sptr inputWS = getProperty("Workspace");
      m_pmap = &(inputWS->instrumentParameters()); // Avoids a copy if you get the reference before the instrument

      API::ITableWorkspace_sptr PosTable = getProperty("PositionTable");
      Geometry::Instrument_const_sptr instrument = inputWS->getInstrument();
      if(!instrument)
      {
        throw std::runtime_error("Workspace to apply calibration to has no defined instrument");
      }

      size_t numDetector = PosTable->rowCount();
      ColumnVector<int> detID = PosTable->getVector("Detector ID");
      ColumnVector<V3D> detPos = PosTable->getVector("Detector Position");
      // numDetector needs to be got as the number of rows in the table and the detID got from the (i)th row of table.
      for (size_t i = 0; i < numDetector; ++i)
      {
        setDetectorPosition(instrument, detID[i], detPos[i], false );
      }
      // Ensure pointer is only valid for execution
      m_pmap = NULL;
    }
/** Generate a list of peaks that meets= all the requirements for fitting offset
  * @param peakslist :: table workspace as the output of FindPeaks
  * @param wi :: workspace index of the spectrum
  * @param peakPositionRef :: reference peaks positions
  * @param peakPosToFit :: output of reference centres of the peaks used to fit
 * offset
  * @param peakPosFitted :: output of fitted centres of the peaks used to fit
 * offset
  * @param peakHeightFitted :: heights of the peaks used to fit offset
  * @param chisq :: chi squares of the peaks used to fit offset
  * @param useFitWindows :: boolean whether FitWindows is used
  * @param fitWindowsToUse :: fit windows
  * @param minD :: minimum d-spacing of the spectrum
  * @param maxD :: minimum d-spacing of the spectrum
  * @param deltaDovD :: delta(d)/d of the peak for fitting
  * @param dev_deltaDovD :: standard deviation of delta(d)/d of all the peaks in
 * the spectrum
  */
void GetDetOffsetsMultiPeaks::generatePeaksList(
    const API::ITableWorkspace_sptr &peakslist, int wi,
    const std::vector<double> &peakPositionRef,
    std::vector<double> &peakPosToFit, std::vector<double> &peakPosFitted,
    std::vector<double> &peakHeightFitted, std::vector<double> &chisq,
    bool useFitWindows, const std::vector<double> &fitWindowsToUse,
    const double minD, const double maxD, double &deltaDovD,
    double &dev_deltaDovD) {
  // FIXME - Need to make sure that the peakPositionRef and peakslist have the
  // same order of peaks

  // Check
  size_t numrows = peakslist->rowCount();
  if (numrows != peakPositionRef.size()) {
    std::stringstream msg;
    msg << "Number of peaks in PeaksList (from FindPeaks=" << numrows
        << ") is not same as number of "
        << "referenced peaks' positions (" << peakPositionRef.size() << ")";
    throw std::runtime_error(msg.str());
  }

  std::vector<double> vec_widthDivPos;
  std::vector<double> vec_offsets;

  for (size_t i = 0; i < peakslist->rowCount(); ++i) {
    // Get peak value
    double centre = peakslist->getRef<double>("centre", i);
    double width = peakslist->getRef<double>("width", i);
    double height = peakslist->getRef<double>("height", i);
    double chi2 = peakslist->getRef<double>("chi2", i);

    // Identify whether this peak would be accepted to optimize offset
    // - peak position within D-range
    if (centre <= minD || centre >= maxD) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre << " out of D-range ";
      g_log.debug(dbss.str());
      continue;
    }

    // - rule out of peak with wrong position
    if (useFitWindows) {
      // outside peak fit window o
      if (centre <= fitWindowsToUse[2 * i] ||
          centre >= fitWindowsToUse[2 * i + 1]) {
        std::stringstream dbss;
        dbss << " wi = " << wi << " c = " << centre << " out of fit window ";
        g_log.debug(dbss.str());
        continue;
      }
    }

    // - check chi-square
    if (chi2 > m_maxChiSq || chi2 < 0) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre << " chi2 = " << chi2
           << ": Too large";
      g_log.debug(dbss.str());
      continue;
    }

    // - check peak height
    if (height < m_minPeakHeight) {
      g_log.debug() << " wi = " << wi << " c = " << centre << " h = " << height
                    << ": Too low "
                    << "\n";
      continue;
    }

    // - check peak's resolution
    double widthdevpos = width / centre;
    if (m_hasInputResolution) {
      double recres = m_inputResolutionWS->readY(wi)[0];
      double resmax = recres * m_maxResFactor;
      double resmin = recres * m_minResFactor;
      if (widthdevpos < resmin || widthdevpos > resmax) {
        std::stringstream dbss;
        dbss << " wi = " << wi << " c = " << centre
             << " Delta(d)/d = " << widthdevpos
             << " too far away from suggested value " << recres;
        g_log.debug(dbss.str());
        continue;
      }
    }

    // background value
    double back_intercept = peakslist->getRef<double>("backgroundintercept", i);
    double back_slope = peakslist->getRef<double>("backgroundslope", i);
    double back_quad = peakslist->getRef<double>("A2", i);
    double background =
        back_intercept + back_slope * centre + back_quad * centre * centre;

    // Continue to identify whether this peak will be accepted
    // (e) peak signal/noise ratio
    if (height * FWHM_TO_SIGMA / width < 5.)
      continue;

    // (f) ban peaks that are not outside of error bars for the background
    if (height < 0.5 * std::sqrt(height + background))
      continue;

    // - calcualte offsets as to determine the (z-value)
    double offset = fabs(peakPositionRef[i] / centre - 1);
    if (offset > m_maxOffset) {
      std::stringstream dbss;
      dbss << " wi = " << wi << " c = " << centre
           << " exceeds maximum offset. ";
      g_log.debug(dbss.str());
      continue;
    } else
      vec_offsets.push_back(offset);

    // (g) calculate width/pos as to determine the (z-value) for constant
    // "width" - (delta d)/d
    // double widthdevpos = width/centre;
    vec_widthDivPos.push_back(widthdevpos);

    // g_log.debug() << " h:" << height << " c:" << centre << " w:" <<
    // (width/(2.*std::sqrt(2.*std::log(2.))))
    //               << " b:" << background << " chisq:" << chi2 << "\n";

    // Add peak to vectors
    double refcentre = peakPositionRef[i];
    peakPosFitted.push_back(centre);
    peakPosToFit.push_back(refcentre);
    peakHeightFitted.push_back(height);
    chisq.push_back(chi2);
  }

  // Remove by Z-score on delta d/d
  std::vector<size_t> banned;
  std::vector<double> Zscore = getZscore(vec_widthDivPos);
  std::vector<double> Z_offset = getZscore(vec_offsets);
  for (size_t i = 0; i < peakPosFitted.size(); ++i) {
    if (Zscore[i] > 2.0 || Z_offset[i] > 2.0) {
      g_log.debug() << "Banning peak at " << peakPosFitted[i]
                    << " in wkspindex = (no show)" // << wi
                    << " sigma/d = " << vec_widthDivPos[i] << "\n";
      banned.push_back(i);
      continue;
    }
  }

  // Delete banned peaks
  if (!banned.empty()) {
    g_log.debug() << "Deleting " << banned.size() << " of "
                  << peakPosFitted.size() << " peaks in wkspindex = ??? "
                  << "\n"; // << wi << "\n";

    deletePeaks(banned, peakPosToFit, peakPosFitted, peakHeightFitted, chisq,
                vec_widthDivPos);
  }

  Statistics widthDivPos = getStatistics(vec_widthDivPos);
  deltaDovD = widthDivPos.mean;
  dev_deltaDovD = widthDivPos.standard_deviation;

  return;
}