Ejemplo n.º 1
0
/**
* This function either shows or hides the given QCheckBox, based on the named property
* inside the instrument param file.  When hidden, the default state will be used to
* reset to the "unused" state of the checkbox.
*
* @param parameterName :: The name of the property to look for inside the current inst param file.
* @param checkBox :: The checkbox to set the state of, and to either hide or show based on the current inst.
* @param defaultState :: The state to which the checkbox will be set upon hiding it.
*/
void IndirectDataReduction::setInstSpecificWidget(const std::string & parameterName, QCheckBox * checkBox, QCheckBox::ToggleState defaultState)
{
  // Get access to instrument specific parameters via the loaded empty workspace.
  std::string instName = m_uiForm.cbInst->currentText().toStdString();
  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve("__empty_" + instName));
  if(input == NULL)
    return;

  Mantid::Geometry::Instrument_const_sptr instr = input->getInstrument();

  // See if the instrument params file requests that the checkbox be shown to the user.
  std::vector<std::string> showParams = instr->getStringParameter(parameterName);
  
  std::string show = "";
  if(!showParams.empty())
    show = showParams[0];
  
  if(show == "Show")
    checkBox->setHidden(false);
  else
  {
    checkBox->setHidden(true);
    checkBox->setState(defaultState);
  }
}
Ejemplo n.º 2
0
void set2DValues(Mantid::API::MatrixWorkspace_sptr ws) {
  const auto numberOfHistograms = ws->getNumberHistograms();

  for (size_t index = 0; index < numberOfHistograms; ++index) {
    auto &data = ws->dataY(index);
    data = Mantid::MantidVec(data.size(), static_cast<double>(index));
  }
}
Ejemplo n.º 3
0
  /**
   * Redraw the raw input plot
   */
  void IndirectDiagnostics::slicePlotRaw()
  {
    QString filename = m_uiForm.dsInputFiles->getFirstFilename();

    // Only update if we have a different file
    if(filename == m_lastDiagFilename)
      return;

    m_lastDiagFilename = filename;

    disconnect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updatePreviewPlot()));
    disconnect(m_blnManager, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(updatePreviewPlot()));

    setDefaultInstDetails();

    if ( m_uiForm.dsInputFiles->isValid() )
    {
      QFileInfo fi(filename);
      QString wsname = fi.baseName();

      int specMin = static_cast<int>(m_dblManager->value(m_properties["SpecMin"]));
      int specMax = static_cast<int>(m_dblManager->value(m_properties["SpecMax"]));

      if(!loadFile(filename, wsname, specMin, specMax))
      {
        emit showMessageBox("Unable to load file.\nCheck whether your file exists and matches the selected instrument in the EnergyTransfer tab.");
        return;
      }

      Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
          Mantid::API::AnalysisDataService::Instance().retrieve(wsname.toStdString()));

      const Mantid::MantidVec & dataX = input->readX(0);
      std::pair<double, double> range(dataX.front(), dataX.back());

      plotMiniPlot(input, 0, "SlicePlot");
      setXAxisToCurve("SlicePlot", "SlicePlot");

      setPlotRange("SlicePeak", m_properties["PeakStart"], m_properties["PeakEnd"], range);
      setPlotRange("SliceBackground", m_properties["BackgroundStart"], m_properties["BackgroundEnd"], range);

      replot("SlicePlot");
    }
    else
    {
      emit showMessageBox("Selected input files are invalid.");
    }

    connect(m_dblManager, SIGNAL(valueChanged(QtProperty*, double)), this, SLOT(updatePreviewPlot()));
    connect(m_blnManager, SIGNAL(valueChanged(QtProperty*, bool)), this, SLOT(updatePreviewPlot()));

    updatePreviewPlot();
  }
Ejemplo n.º 4
0
/*
 * Set the goniometer values for the workspace
 *
 * @param workspace :: the workspace to set the goniometer values in
 */
void CreateMD::setGoniometer(Mantid::API::MatrixWorkspace_sptr workspace) {
  Algorithm_sptr log_alg = createChildAlgorithm("SetGoniometer");
  if (!workspace->run().getProperty("gl")) {
    std::ostringstream temp_ss;
    temp_ss << "Value of gl in log is: "
            << workspace->run().getPropertyAsSingleValue("gl");
    throw std::invalid_argument(temp_ss.str());
  }
  log_alg->setProperty("Workspace", workspace);
  log_alg->setProperty("Axis0", "gl,0,0,1,1");
  log_alg->setProperty("Axis1", "gs,1,0,0,1");
  log_alg->setProperty("Axis2", "psi,0,1,0,1");

  log_alg->executeAsChildAlg();
}
Ejemplo n.º 5
0
/*
 * Add parameter logs and convert to MD for a single run
 *
 * @param input_workspace :: datasource workspace
 * @param emode :: analysis mode "Elastic", "Direct" or "Indirect"
 * @param efix :: datasource energy values in meV
 * @param psi :: goniometer rotation in degrees
 * @param gl :: goniometer rotation in degrees
 * @param gs :: goniometer rotation in degrees
 * @param in_place :: do merge step at the same time as converting to
 *MDWorkspace
 * @param alatt :: length of crystal lattice parameter in angstroms
 * @param angdeg :: lattice angle
 * @param u :: lattice vector parallel to incident neutron beam
 * @param v :: lattice vector perpendicular to u in the horizontal plane
 * @param out_mdws :output workspace to use if merge step is carried out
 */
Mantid::API::IMDEventWorkspace_sptr CreateMD::single_run(
    Mantid::API::MatrixWorkspace_sptr input_workspace, const std::string &emode,
    double efix, double psi, double gl, double gs, bool in_place,
    const std::vector<double> &alatt, const std::vector<double> &angdeg,
    const std::vector<double> &u, const std::vector<double> &v,
    const std::string &filebackend_filename, const bool filebackend,
    Mantid::API::IMDEventWorkspace_sptr out_mdws) {

  std::vector<std::vector<double>> ub_params{alatt, angdeg, u, v};

  if (any_given(ub_params) && !all_given(ub_params)) {
    throw std::invalid_argument(
        "Either specify all of alatt, angledeg, u, v or none of them");
  } else {
    if (input_workspace->sample().hasOrientedLattice()) {
      g_log.warning() << "Sample already has a UB. This will not be "
                         "overwritten. Use ClearUB and re-run.\n";
    } else {
      setUB(input_workspace, alatt[0], alatt[1], alatt[2], angdeg[0], angdeg[1],
            angdeg[2], u, v);
    }

    if (efix > 0.0) {
      addSampleLog(input_workspace, "Ei", efix);
    }

    addSampleLog(input_workspace, "gl", gl);
    addSampleLog(input_workspace, "gs", gs);
    addSampleLog(input_workspace, "psi", psi);
    setGoniometer(input_workspace);

    return convertToMD(input_workspace, emode, in_place, filebackend_filename,
                       filebackend, out_mdws);
  }
}
Ejemplo n.º 6
0
/// calculate distance from source to sample or detector
double ModeratorTzero::CalculateL1(Mantid::API::MatrixWorkspace_sptr inputWS, size_t i){
  double L1(0);
  // Get detector position
  IDetector_const_sptr det;
  try
  {
    det = inputWS->getDetector(i);
  }
  catch (Exception::NotFoundError&)
  {
    return 0;
  }

  if( det->isMonitor() )
  {
    L1=m_instrument->getSource()->getDistance(*det);
  }
  else
  {
    IComponent_const_sptr sample = m_instrument->getSample();
    try
    {
      L1 = m_instrument->getSource()->getDistance(*sample);
    }
    catch (Exception::NotFoundError &)
    {
      g_log.error("Unable to calculate source-sample distance");
      throw Exception::InstrumentDefinitionError("Unable to calculate source-sample distance", inputWS->getTitle());
    }
  }
  return L1;
}
/**
 * Provide the collimation length which is associated with the instrument
 * @param workspace: the input workspace
 * @returns the collimation length
 */
double SANSCollimationLengthEstimator::provideCollimationLength(
    Mantid::API::MatrixWorkspace_sptr workspace) {
  // If the instrument does not have a correction specified then set the length
  // to 4
  const double defaultLColim = 4.0;
  auto collimationLengthID = "collimation-length-correction";

  if (!workspace->getInstrument()->hasParameter(collimationLengthID)) {
    g_log.error("Error in SANSCollimtionLengthEstimator: The instrument "
                "parameter file does not contain a collimation length "
                "correction,"
                "a default of 4 is provided. Please update the instrument "
                "parameter file.");
    return defaultLColim;
  }

  // Get the L1 length
  const V3D samplePos = workspace->getInstrument()->getSample()->getPos();
  const V3D sourcePos = workspace->getInstrument()->getSource()->getPos();
  const V3D SSD = samplePos - sourcePos;
  const double L1 = SSD.norm();

  auto collimationLengthCorrection =
      workspace->getInstrument()->getNumberParameter(collimationLengthID);

  if (workspace->getInstrument()->hasParameter(
          "special-default-collimation-length-method")) {
    auto specialCollimationMethod =
        workspace->getInstrument()->getStringParameter(
            "special-default-collimation-length-method");
    if (specialCollimationMethod[0] == "guide") {
      try {
        return getCollimationLengthWithGuides(workspace, L1,
                                              collimationLengthCorrection[0]);
      } catch (std::invalid_argument &ex) {
        g_log.notice() << ex.what();
        g_log.notice()
            << "SANSCollimationLengthEstimator: Not using any guides";
        return L1 - collimationLengthCorrection[0];
      }
    } else {
      throw std::invalid_argument("Error in SANSCollimationLengthEstimator: "
                                  "Unknown special collimation method.");
    }
  }
  return L1 - collimationLengthCorrection[0];
}
void EnggDiffMultiRunFittingWidgetPresenter::addFocusedRun(
    const Mantid::API::MatrixWorkspace_sptr ws) {
  const auto runNumber = ws->getRunNumber();
  const auto bankID = guessBankID(ws);

  m_model->addFocusedRun(RunLabel(runNumber, bankID), ws);
  m_view->updateRunList(m_model->getAllWorkspaceLabels());
}
Ejemplo n.º 9
0
/// Constructor.
/// @param wsName :: Name of a MatrixWorkspace with the data for fitting.
/// @param wsIndex :: Workspace index of a spectrum in wsName to plot.
/// @param outputWSName :: Name of the Fit's output workspace containing at
/// least 3 spectra:
///    #0 - original data (the same as in wsName[wsIndex]), #1 - calculated
///    data, #3 - difference.
///    If empty - ignore this workspace.
DatasetPlotData::DatasetPlotData(const QString &wsName, int wsIndex,
                                 const QString &outputWSName)
    : m_dataCurve(new QwtPlotCurve(wsName + QString(" (%1)").arg(wsIndex))),
      m_dataErrorCurve(NULL), m_calcCurve(NULL), m_diffCurve(NULL),
      m_showDataErrorBars(false) {
  // get the data workspace
  auto ws = Mantid::API::AnalysisDataService::Instance()
                .retrieveWS<Mantid::API::MatrixWorkspace>(wsName.toStdString());
  if (!ws) {
    QString mess =
        QString("Workspace %1 either doesn't exist or isn't a MatrixWorkspace")
            .arg(wsName);
    throw std::runtime_error(mess.toStdString());
  }
  // check that the index is in range
  if (static_cast<size_t>(wsIndex) >= ws->getNumberHistograms()) {
    QString mess = QString("Spectrum %1 doesn't exist in workspace %2")
                       .arg(wsIndex)
                       .arg(wsName);
    throw std::runtime_error(mess.toStdString());
  }

  // get the data workspace
  Mantid::API::MatrixWorkspace_sptr outputWS;
  if (!outputWSName.isEmpty()) {
    std::string stdOutputWSName = outputWSName.toStdString();
    if (Mantid::API::AnalysisDataService::Instance().doesExist(
            stdOutputWSName)) {
      try {
        outputWS =
            Mantid::API::AnalysisDataService::Instance()
                .retrieveWS<Mantid::API::MatrixWorkspace>(stdOutputWSName);
      } catch (Mantid::Kernel::Exception::NotFoundError &) {
        QString mess =
            QString(
                "Workspace %1 either doesn't exist or isn't a MatrixWorkspace")
                .arg(outputWSName);
        throw std::runtime_error(mess.toStdString());
      }
    }
  }

  // create the curves
  setData(ws.get(), wsIndex, outputWS.get());
}
Ejemplo n.º 10
0
/**
 * Shift the time in a time series. This is similar to the implementation in
 * @param ws :: a matrix workspace
 * @param prop :: a time series log
 * @param timeShift :: the time shift in seconds
 */
void ChangeTimeZero::shiftTimeInLogForTimeSeries(
    Mantid::API::MatrixWorkspace_sptr ws, Mantid::Kernel::Property *prop,
    double timeShift) const {
  if (auto timeSeries =
          dynamic_cast<Mantid::Kernel::ITimeSeriesProperty *>(prop)) {
    auto newlog = timeSeries->cloneWithTimeShift(timeShift);
    ws->mutableRun().addProperty(newlog, true);
  }
}
Ejemplo n.º 11
0
/**
 * @brief Gets the X range of the first curve whose data is stored in the query
 * workspace.
 * @param workspace pointer to query workspace
 * @return the range of the first curve associated to the workspace
 * @exception std::runtime_error no stored curves are associated to the query
 * workspace
 */
QPair<double, double> DisplayCurveFit::getCurveRange(
    const Mantid::API::MatrixWorkspace_sptr workspace) {
  curveTypes typesFound = this->getCurvesForWorkspace(workspace);
  if (typesFound.size() == 0) {
    throw std::runtime_error("No fitting curves associated to workspace" +
                             workspace->name());
  }
  return getCurveRange(typesFound[0]);
}
Ejemplo n.º 12
0
void EnggDiffFittingModel::convertFromDistribution(
    Mantid::API::MatrixWorkspace_sptr inputWS) {
  const auto name = inputWS->getName();
  auto convertFromDistAlg = Mantid::API::AlgorithmManager::Instance().create(
      "ConvertFromDistribution");
  convertFromDistAlg->initialize();
  convertFromDistAlg->setProperty("Workspace", inputWS);
  convertFromDistAlg->execute();
}
Ejemplo n.º 13
0
/**
 * Check the input workspace
 * @param inWS: the input workspace
 */
void TOFSANSResolutionByPixel::checkInput(
    Mantid::API::MatrixWorkspace_sptr inWS) {
  // Make sure that input workspace has an instrument as we rely heavily on
  // thisa
  auto inst = inWS->getInstrument();
  if (inst->getName().empty()) {
    throw std::invalid_argument("TOFSANSResolutionByPixel: The input workspace "
                                "does not contain an instrument");
  }
}
Ejemplo n.º 14
0
void setXValuesOn1DWorkspaceWithPointData(
    Mantid::API::MatrixWorkspace_sptr workspace, double xmin, double xmax) {
  auto &xValues = workspace->dataX(0);
  auto size = xValues.size();
  double binWidth = (xmax - xmin) / static_cast<double>(size - 1);
  for (size_t index = 0; index < size; ++index) {
    xValues[index] = xmin;
    xmin += binWidth;
  }
}
void IndirectFitAnalysisTab::plotAll(
    Mantid::API::MatrixWorkspace_sptr workspace) {
  auto const numberOfDataPoints = workspace->blocksize();
  if (numberOfDataPoints > 1)
    plotSpectrum(workspace);
  else
    showMessageBox(
        "The plotting of data in one of the result workspaces failed:\n\n "
        "Workspace has only one data point");
}
Ejemplo n.º 16
0
void ISISDiagnostics::handleNewFile() {
  if (!m_uiForm.dsInputFiles->isValid())
    return;

  QString filename = m_uiForm.dsInputFiles->getFirstFilename();

  QFileInfo fi(filename);
  QString wsname = fi.baseName();

  int specMin = static_cast<int>(m_dblManager->value(m_properties["SpecMin"]));
  int specMax = static_cast<int>(m_dblManager->value(m_properties["SpecMax"]));

  if (!loadFile(filename, wsname, specMin, specMax)) {
    emit showMessageBox("Unable to load file.\nCheck whether your file exists "
                        "and matches the selected instrument in the "
                        "EnergyTransfer tab.");
    return;
  }

  Mantid::API::MatrixWorkspace_sptr input =
      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
          Mantid::API::AnalysisDataService::Instance().retrieve(
              wsname.toStdString()));

  const Mantid::MantidVec &dataX = input->readX(0);
  QPair<double, double> range(dataX.front(), dataX.back());
  int previewSpec =
      static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"])) -
      specMin;

  m_uiForm.ppRawPlot->clear();
  m_uiForm.ppRawPlot->addSpectrum("Raw", input, previewSpec);

  setPlotPropertyRange(m_uiForm.ppRawPlot->getRangeSelector("SlicePeak"),
                       m_properties["PeakStart"], m_properties["PeakEnd"],
                       range);
  setPlotPropertyRange(m_uiForm.ppRawPlot->getRangeSelector("SliceBackground"),
                       m_properties["BackgroundStart"],
                       m_properties["BackgroundEnd"], range);

  m_uiForm.ppRawPlot->resizeX();
}
Ejemplo n.º 17
0
/**
 * Gets the energy mode from a workspace based on the X unit.
 *
 * Units of dSpacing typically denote diffraction, hence Elastic.
 * All other units default to spectroscopy, therefore Indirect.
 *
 * @param ws Pointer to the workspace
 * @return Energy mode
 */
std::string IndirectTab::getEMode(Mantid::API::MatrixWorkspace_sptr ws) {
  Mantid::Kernel::Unit_sptr xUnit = ws->getAxis(0)->unit();
  std::string xUnitName = xUnit->caption();

  g_log.debug() << "X unit name is: " << xUnitName << '\n';

  if (boost::algorithm::find_first(xUnitName, "d-Spacing"))
    return "Elastic";

  return "Indirect";
}
void IndirectFitAnalysisTab::plotSpectrum(
    Mantid::API::MatrixWorkspace_sptr workspace,
    const std::string &parameterToPlot) {
  const auto name = QString::fromStdString(workspace->getName());
  const auto labels = IndirectTab::extractAxisLabels(workspace, 1);
  for (const auto &parameter : m_fittingModel->getFitParameterNames()) {
    if (boost::contains(parameter, parameterToPlot)) {
      auto it = labels.find(parameter);
      if (it != labels.end())
        IndirectTab::plotSpectrum(name, static_cast<int>(it->second));
    }
  }
}
Ejemplo n.º 19
0
/**
Check for a set of synthetic logs associated with multi-period log data. Raise
warnings where necessary.
*/
void
LoadISISNexus2::validateMultiPeriodLogs(Mantid::API::MatrixWorkspace_sptr ws) {
  const Run &run = ws->run();
  if (!run.hasProperty("current_period")) {
    g_log.warning("Workspace has no current_period log.");
  }
  if (!run.hasProperty("nperiods")) {
    g_log.warning("Workspace has no nperiods log");
  }
  if (!run.hasProperty("proton_charge_by_period")) {
    g_log.warning("Workspace has not proton_charge_by_period log");
  }
}
Ejemplo n.º 20
0
/**
 * Updates the mini plots.
 */
void IndirectSymmetrise::updateMiniPlots() {
  if (!m_uiForm.dsInput->isValid())
    return;

  QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
  int spectrumNumber =
      static_cast<int>(m_dblManager->value(m_properties["PreviewSpec"]));

  Mantid::API::MatrixWorkspace_sptr input =
      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
          Mantid::API::AnalysisDataService::Instance().retrieve(
              workspaceName.toStdString()));

  // Plot the spectrum chosen by the user
  size_t spectrumIndex = input->getIndexFromSpectrumNumber(spectrumNumber);
  m_uiForm.ppRawPlot->clear();
  m_uiForm.ppRawPlot->addSpectrum("Raw", input, spectrumIndex);

  // Match X axis range on preview plot
  m_uiForm.ppPreviewPlot->setAxisRange(m_uiForm.ppRawPlot->getCurveRange("Raw"),
                                       QwtPlot::xBottom);
  m_uiForm.ppPreviewPlot->replot();
}
Ejemplo n.º 21
0
/** Executes the algorithm
 *
 */
void SumNeighbours::exec()
{
  // Try and retrieve the optional properties
  SumX = getProperty("SumX");
  SumY = getProperty("SumY");


  // Get the input workspace
  Mantid::API::MatrixWorkspace_sptr inWS = getProperty("InputWorkspace");
  Mantid::Geometry::IDetector_const_sptr det = inWS->getDetector(0);
  // Check if grandparent is rectangular detector
  boost::shared_ptr<const Geometry::IComponent> parent = det->getParent()->getParent();
  boost::shared_ptr<const RectangularDetector> rect = boost::dynamic_pointer_cast<const RectangularDetector>(parent);
  
  Mantid::API::MatrixWorkspace_sptr outWS;

  IAlgorithm_sptr smooth = createChildAlgorithm("SmoothNeighbours");
  smooth->setProperty("InputWorkspace", inWS);
  if (rect)
  {
    smooth->setProperty("SumPixelsX",SumX);
    smooth->setProperty("SumPixelsY",SumY);
  }
  else
  {
    smooth->setProperty<std::string>("RadiusUnits","NumberOfPixels");
    smooth->setProperty("Radius",static_cast<double>(SumX*SumY*SumX*SumY));
    smooth->setProperty("NumberOfNeighbours",SumX*SumY*SumX*SumY*4);
    smooth->setProperty("SumNumberOfNeighbours",SumX*SumY);
  }
  smooth->executeAsChildAlg();
  // Get back the result
  outWS = smooth->getProperty("OutputWorkspace");
  //Cast to the matrixOutputWS and save it
  this->setProperty("OutputWorkspace", outWS);

}
Ejemplo n.º 22
0
Mantid::API::MatrixWorkspace_sptr
provide1DWorkspace(NXcanSASTestParameters &parameters) {
  Mantid::API::MatrixWorkspace_sptr ws;
  if (parameters.hasDx) {
    ws = WorkspaceCreationHelper::create1DWorkspaceConstantWithXerror(
        parameters.size, parameters.value, parameters.error, parameters.xerror);
  } else {
    ws = WorkspaceCreationHelper::create1DWorkspaceConstant(
        parameters.size, parameters.value, parameters.error);
  }

  ws->setTitle(parameters.workspaceTitle);
  ws->getAxis(0)->unit() =
      Mantid::Kernel::UnitFactory::Instance().create("MomentumTransfer");

  // Add sample logs
  set_logs(ws, parameters.runNumber, parameters.userFile);

  // Set instrument
  set_instrument(ws, parameters.instrumentName);

  // Set to point data or histogram data
  if (parameters.isHistogram) {
    const std::string outName = "convert_to_histo_out_name";
    auto toHistAlg = Mantid::API::AlgorithmManager::Instance().createUnmanaged(
        "ConvertToHistogram");
    toHistAlg->initialize();
    toHistAlg->setChild(true);
    toHistAlg->setProperty("InputWorkspace", ws);
    toHistAlg->setProperty("OutputWorkspace", outName);
    toHistAlg->execute();
    ws = toHistAlg->getProperty("OutputWorkspace");
  }

  return ws;
}
Ejemplo n.º 23
0
/**
 * Create the vector of rebin parameters
 * @param toMatch :: A shared pointer to the workspace with the desired binning 
 * @param rb_params :: A vector to hold the rebin parameters once they have been calculated
 */
void RebinToWorkspace::createRebinParameters(Mantid::API::MatrixWorkspace_sptr toMatch, std::vector<double> & rb_params)
{
  using namespace Mantid::API;

  const MantidVec & matchXdata = toMatch->readX(0);
  //params vector should have the form [x_1, delta_1,x_2, ... ,x_n-1,delta_n-1,x_n), see Rebin.cpp
  rb_params.clear();
  int xsize = (int)matchXdata.size();
  rb_params.reserve(xsize*2);
  for( int i = 0; i < xsize; ++i )
  {
    //bin bound
    rb_params.push_back(matchXdata[i]);
    //Bin width
    if( i < xsize - 1) rb_params.push_back(matchXdata[i + 1] - matchXdata[i]);
  }
}
Ejemplo n.º 24
0
void EnggDiffFittingModel::alignDetectors(
    Mantid::API::MatrixWorkspace_sptr inputWS,
    const std::string &outputWSName) {
  const auto calibrationParamsTable = createCalibrationParamsTable(inputWS);

  if (inputWS->isDistribution()) {
    convertFromDistribution(inputWS);
  }

  auto alignDetAlg =
      Mantid::API::AlgorithmManager::Instance().create("AlignDetectors");
  alignDetAlg->initialize();
  alignDetAlg->setProperty("InputWorkspace", inputWS);
  alignDetAlg->setProperty("OutputWorkspace", outputWSName);
  alignDetAlg->setProperty("CalibrationWorkspace", calibrationParamsTable);
  alignDetAlg->execute();
}
Ejemplo n.º 25
0
/**
 * Create the vector of rebin parameters
 * @param toMatch :: A shared pointer to the workspace with the desired binning
 * @returns :: A vector to hold the rebin parameters once they have been
 * calculated
 */
std::vector<double> RebinToWorkspace::createRebinParameters(
    Mantid::API::MatrixWorkspace_sptr toMatch) {
  using namespace Mantid::API;

  const MantidVec &matchXdata = toMatch->readX(0);
  // params vector should have the form [x_1, delta_1,x_2, ...
  // ,x_n-1,delta_n-1,x_n), see Rebin.cpp
  std::vector<double> rb_params;
  int xsize = static_cast<int>(matchXdata.size());
  rb_params.reserve(xsize * 2);
  for (int i = 0; i < xsize; ++i) {
    // bin bound
    rb_params.push_back(matchXdata[i]);
    // Bin width
    if (i < xsize - 1)
      rb_params.push_back(matchXdata[i + 1] - matchXdata[i]);
  }
  return rb_params;
}
Ejemplo n.º 26
0
/**
 * Gets the eFixed value from the workspace using the instrument parameters.
 *
 * @param ws Pointer to the workspace
 * @return eFixed value
 */
double IndirectTab::getEFixed(Mantid::API::MatrixWorkspace_sptr ws) {
  Mantid::Geometry::Instrument_const_sptr inst = ws->getInstrument();
  if (!inst)
    throw std::runtime_error("No instrument on workspace");

  // Try to get the parameter form the base instrument
  if (inst->hasParameter("Efixed"))
    return inst->getNumberParameter("Efixed")[0];

  // Try to get it form the analyser component
  if (inst->hasParameter("analyser")) {
    std::string analyserName = inst->getStringParameter("analyser")[0];
    auto analyserComp = inst->getComponentByName(analyserName);

    if (analyserComp && analyserComp->hasParameter("Efixed"))
      return analyserComp->getNumberParameter("Efixed")[0];
  }

  throw std::runtime_error("Instrument has no efixed parameter");
}
Ejemplo n.º 27
0
/**
 * Change the time of the logs.
 * @param ws :: a workspace
 * @param timeShift :: the time shift that is applied to the log files
 * @param startProgress :: start point of the progress
 * @param stopProgress :: end point of the progress
 */
void ChangeTimeZero::shiftTimeOfLogs(Mantid::API::MatrixWorkspace_sptr ws,
                                     double timeShift, double startProgress,
                                     double stopProgress) {
  // We need to change the entries for each log which can be:
  // 1. any time series: here we change the time values
  // 2. string properties: here we change the values if they are ISO8601 times
  auto logs = ws->mutableRun().getLogData();
  Progress prog(this, startProgress, stopProgress, logs.size());
  for (auto iter = logs.begin(); iter != logs.end(); ++iter) {
    if (isTimeSeries(*iter)) {
      shiftTimeInLogForTimeSeries(ws, *iter, timeShift);

    } else if (auto stringProperty =
                   dynamic_cast<PropertyWithValue<std::string> *>(*iter)) {
      shiftTimeOfLogForStringProperty(stringProperty, timeShift);
    }

    prog.report(name());
  }
}
Ejemplo n.º 28
0
/**
 * Sum counts in detectors for purposes of rough plotting against the units on the x-axis.
 * Assumes that all spectra have different x vectors.
 *
 * @param dets :: A list of detector IDs to sum.
 * @param x :: (output) Time of flight values (or whatever values the x axis has) to plot against.
 * @param y :: (output) The sums of the counts for each bin.
 * @param size :: (input) Size of the output vectors.
 */
void InstrumentActor::sumDetectorsRagged(QList<int> &dets, std::vector<double> &x, std::vector<double> &y, size_t size) const
{
    if ( dets.isEmpty() || size == 0 )
    {
        x.clear();
        y.clear();
        return;
    }

    Mantid::API::MatrixWorkspace_const_sptr ws = getWorkspace();
    //  create a workspace to hold the data from the selected detectors
    Mantid::API::MatrixWorkspace_sptr dws = Mantid::API::WorkspaceFactory::Instance().create(ws,dets.size());

    // x-axis limits
    double xStart = maxBinValue();
    double xEnd = minBinValue();

    size_t nSpec = 0; // number of actual spectra to add
    // fill in the temp workspace with the data from the detectors
    foreach(int id, dets)
    {
        try {
            size_t index = getWorkspaceIndex( id );
            dws->dataX(nSpec) = ws->readX(index);
            dws->dataY(nSpec) = ws->readY(index);
            dws->dataE(nSpec) = ws->readE(index);
            double xmin = dws->readX(nSpec).front();
            double xmax = dws->readX(nSpec).back();
            if ( xmin < xStart )
            {
                xStart = xmin;
            }
            if ( xmax > xEnd )
            {
                xEnd = xmax;
            }
            ++nSpec;
        } catch (Mantid::Kernel::Exception::NotFoundError &) {
            continue; // Detector doesn't have a workspace index relating to it
        }
    }

    if ( nSpec == 0 )
    {
        x.clear();
        y.clear();
        return;
    }

    // limits should exceed the integration range
    if ( xStart < minBinValue() )
    {
        xStart = minBinValue();
    }

    if ( xEnd > maxBinValue() )
    {
        xEnd = maxBinValue();
    }

    double dx = (xEnd - xStart) / static_cast<double>(size - 1);
    std::string params = QString("%1,%2,%3").arg(xStart).arg(dx).arg(xEnd).toStdString();
    std::string outName = "_TMP_sumDetectorsRagged";

    try
    {
        // rebin all spectra to the same binning
        Mantid::API::IAlgorithm * alg = Mantid::API::FrameworkManager::Instance().createAlgorithm("Rebin",-1);
        alg->setProperty( "InputWorkspace", dws );
        alg->setPropertyValue( "OutputWorkspace", outName );
        alg->setPropertyValue( "Params", params );
        alg->execute();

        ws = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve(outName));
        Mantid::API::AnalysisDataService::Instance().remove( outName );

        x = ws->readX(0);
        y = ws->readY(0);
        // add the spectra
        for(size_t i = 0; i < nSpec; ++i)
        {
            const Mantid::MantidVec& Y = ws->readY(i);
            std::transform( y.begin(), y.end(), Y.begin(), y.begin(), std::plus<double>() );
        }
    }
    catch(std::invalid_argument&)
    {
        // wrong Params for any reason
        x.resize(size,(xEnd + xStart)/2);
        y.resize(size,0.0);
    }

}
Ejemplo n.º 29
0
    /** Method takes min-max values from algorithm parameters if they are present or calculates default min-max values if these values 
     *  were not supplied to the method or the supplied value is incorrect.
     *
    *@param inWS     -- the shared pointer to the source workspace
    *@param QMode    -- the string which defines algorithms Q-conversion mode
    *@param dEMode   -- the string describes the algorithms energy conversion mode
    *@param QFrame   -- in Q3D case this describes target coordinate system and is ignored in any other caste
    *@param ConvertTo -- The parameter describing Q-scaling transformations 
    *@param otherDim -- the vector of other dimension names (if any)
    *  Input-output values: 
    *@param minVal   -- the vector with min values for the algorithm
    *@param maxVal   -- the vector with max values for the algorithm
    *
    *
    */
    void ConvertToMD::findMinMax(const Mantid::API::MatrixWorkspace_sptr &inWS,const std::string &QMode, const std::string &dEMode,
      const std::string &QFrame,const std::string &ConvertTo,const std::vector<std::string> &otherDim,
      std::vector<double> &minVal,std::vector<double> &maxVal)
    {

      // get raw pointer to Q-transformation (do not delete this pointer, it hold by MDTransfFatctory!)
      MDTransfInterface* pQtransf =  MDTransfFactory::Instance().create(QMode).get();
      // get number of dimensions this Q transformation generates from the workspace. 
      auto iEmode = Kernel::DeltaEMode().fromString(dEMode);
      // get total number of dimensions the workspace would have.
      unsigned int nMatrixDim = pQtransf->getNMatrixDimensions(iEmode,inWS);
      // total number of dimensions
      size_t nDim =nMatrixDim+otherDim.size();

      // probably already have well defined min-max values, so no point of pre-calculating them
      bool wellDefined(true);
      if((nDim == minVal.size()) && (minVal.size()==maxVal.size()))
      {
        // are they indeed well defined?
        for(size_t i=0;i<minVal.size();i++)
        {
          if(minVal[i]>=maxVal[i]) // no it is ill defined
          {
            g_log.information()<<" Min Value: "<<minVal[i]<<" for dimension N: "<<i<<" equal or exceeds max value:"<<maxVal[i]<<std::endl;
            wellDefined = false;
            break;
          }
        }
        if (wellDefined)return;
      }

      // we need to identify min-max values by themselves

      Mantid::API::Algorithm_sptr childAlg = createChildAlgorithm("ConvertToMDMinMaxLocal");
      if(!childAlg)throw(std::runtime_error("Can not create child ChildAlgorithm to found min/max values"));

      childAlg->setPropertyValue("InputWorkspace", inWS->getName());
      childAlg->setPropertyValue("QDimensions",QMode);
      childAlg->setPropertyValue("dEAnalysisMode",dEMode);
      childAlg->setPropertyValue("Q3DFrames",QFrame);
      childAlg->setProperty("OtherDimensions",otherDim);
      childAlg->setProperty("QConversionScales",ConvertTo);
      childAlg->setProperty("PreprocDetectorsWS",std::string(getProperty("PreprocDetectorsWS")));
      childAlg->execute();
      if(!childAlg->isExecuted())throw(std::runtime_error("Can not properly execute child algorithm to find min/max workspace values"));

      minVal = childAlg->getProperty("MinValues");
      maxVal = childAlg->getProperty("MaxValues");

      // if some min-max values for dimensions produce ws with 0 width in this direction, change it to have some width;
      for(unsigned int i=0;i<nDim;i++)
      {
        if(minVal[i]>=maxVal[i])
        {
          g_log.debug()<<"identified min-max values for dimension N: "<<i<<" are equal. Modifying min-max value to produce dimension with 0.2*dimValue width\n";
          if(minVal[i]>0)
          {
            minVal[i]*=0.9;
            maxVal[i]*=1.1;
          }
          else if(minVal[i]==0)
          {
            minVal[i]=-0.1;
            maxVal[i]=0.1;
          }
          else
          {
            minVal[i]*=1.1;
            maxVal[i]*=0.9;

          }
        }
        else // expand min-max values a bit to avoid cutting data on the edges
        {
          if (std::fabs(minVal[i])>FLT_EPSILON)
            minVal[i]*=(1+2*FLT_EPSILON);
          else
            minVal[i]-=2*FLT_EPSILON;
          if (std::fabs(minVal[i])>FLT_EPSILON)
            maxVal[i]*=(1+2*FLT_EPSILON);
          else
            minVal[i]+=2*FLT_EPSILON;
        }
      }

      if(!wellDefined) return;

      // if only min or only max limits are defined and are well defined workspace, the algorithm will use these limits
      std::vector<double> minAlgValues = this->getProperty("MinValues");
      std::vector<double> maxAlgValues = this->getProperty("MaxValues");
      bool allMinDefined = (minAlgValues.size()==nDim);
      bool allMaxDefined = (maxAlgValues.size()==nDim);
      if(allMinDefined || allMaxDefined)
      {
        for(size_t i=0;i<nDim;i++)
        {
          if (allMinDefined)  minVal[i] = minAlgValues[i];
          if (allMaxDefined)  maxVal[i] = maxAlgValues[i];
        }

      }


    }
void IndirectFitAnalysisTab::plotSpectrum(
    Mantid::API::MatrixWorkspace_sptr workspace) {
  const auto name = QString::fromStdString(workspace->getName());
  for (auto i = 0u; i < workspace->getNumberHistograms(); ++i)
    IndirectTab::plotSpectrum(name, static_cast<int>(i));
}