Example #1
0
/**
 * This function: 1. loads the instrument and gets the value of deltaE-mode parameter
 *				 2. Based on this value, makes the necessary changes to the form setup (direct or indirect).
 * @param name :: name of the instrument from the QComboBox
 */
void IndirectDataReduction::instrumentSelectChanged(const QString& name)
{
  QString defFile = (Mantid::API::ExperimentInfo::getInstrumentFilename(name.toStdString())).c_str();
  if((defFile == "") || !m_uiForm.cbInst->isVisible())
  {
    g_log.error("Instument loading failed!");
    m_uiForm.cbInst->setEnabled(true);
    m_uiForm.pbRun->setEnabled(true);
    return;
  }

  QString outWS = "__empty_" + m_uiForm.cbInst->currentText();

  m_curInterfaceSetup = name;

  //Load the empty instrument into the workspace __empty_[name]
  //This used to be done in Python
  Mantid::API::IAlgorithm_sptr instLoader = Mantid::API::AlgorithmManager::Instance().create("LoadEmptyInstrument", -1);
  instLoader->initialize();
  instLoader->setProperty("Filename", defFile.toStdString());
  instLoader->setProperty("OutputWorkspace", outWS.toStdString());

  //Ensure no other algorithm is running
  m_algRunner->cancelRunningAlgorithm();
  m_algRunner->startAlgorithm(instLoader);
}
/**
 * Get the viewable peaks. Essentially copied from the slice viewer.
 * @returns A vector indicating which of the peaks are viewable.
 */
std::vector<bool> ConcretePeaksPresenterVsi::getViewablePeaks() const {
  // Need to apply a transform.
  // Don't bother to find peaks in the region if there are no peaks to find.
  Mantid::API::ITableWorkspace_sptr outTable;

  if (this->m_peaksWorkspace->getNumberPeaks() >= 1) {
    double effectiveRadius = 1e-2;
    std::string viewable = m_viewableRegion->toExtentsAsString();
    Mantid::API::IPeaksWorkspace_sptr peaksWS = m_peaksWorkspace;

    Mantid::API::IAlgorithm_sptr alg =
        Mantid::API::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", viewable);
    alg->setProperty("CheckPeakExtents", true);
    alg->setProperty("PeakRadius", effectiveRadius);
    alg->setPropertyValue("CoordinateFrame", m_frame);
    alg->execute();
    outTable = alg->getProperty("OutputWorkspace");
    std::vector<bool> viewablePeaks(outTable->rowCount());
    for (size_t i = 0; i < outTable->rowCount(); ++i) {
      viewablePeaks[i] = outTable->cell<Mantid::API::Boolean>(i, 1);
    }
    m_viewablePeaks = viewablePeaks;
  } else {
    // No peaks will be viewable
    m_viewablePeaks = std::vector<bool>();
  }

  return m_viewablePeaks;
}
Example #3
0
    /// execute getdatafIles algorithm
    ITableWorkspace_sptr ICatInvestigation::executeGetdataFiles()
    {
      QString algName("CatalogGetDataFiles");
      const int version=1;
      Mantid::API::ITableWorkspace_sptr  ws_sptr;
      Mantid::API::IAlgorithm_sptr alg;
      try
      {
        alg = Mantid::API::AlgorithmManager::Instance().create(algName.toStdString(),version);
      }
      catch(...)
      {
        throw std::runtime_error("Error when loading the data files associated to the selected investigation ");
      }
      try
      {
        alg->setProperty("InvestigationId",m_invstId);
        alg->setProperty("FilterLogFiles",isDataFilesChecked());
        alg->setPropertyValue("OutputWorkspace","datafiles");
      }
      catch(std::invalid_argument& e)
      {
        emit error(e.what());
        return ws_sptr;
      }
      catch (Mantid::Kernel::Exception::NotFoundError& e)
      {
        emit error(e.what());
        return ws_sptr;
      }

      try
      {
        Poco::ActiveResult<bool> result(alg->executeAsync());
        while( !result.available() )
        {
          QCoreApplication::processEvents();
        }
      }
      catch(...)
      {
        return ws_sptr;
      }
      if(AnalysisDataService::Instance().doesExist("datafiles"))
      {
        ws_sptr = boost::dynamic_pointer_cast<Mantid::API::ITableWorkspace>
        (AnalysisDataService::Instance().retrieve("datafiles"));
      }
      return ws_sptr;

    }
void WorkspacePresenter::ungroupWorkspaces() {
  auto view = lockView();
  auto selected = view->getSelectedWorkspaceNames();

  if (selected.size() == 0) {
    view->showCriticalUserMessage("Error Ungrouping Workspaces",
                                  "Select a group workspace to Ungroup.");
    return;
  }

  try {
    // workspace name
    auto wsname = selected[0];

    std::string algName("UnGroupWorkspace");
    Mantid::API::IAlgorithm_sptr alg =
        Mantid::API::AlgorithmManager::Instance().create(algName, -1);
    alg->initialize();
    alg->setProperty("InputWorkspace", wsname);

    // execute the algorithm
    bool bStatus = alg->execute();
    if (!bStatus) {
      view->showCriticalUserMessage("MantidPlot - Algorithm error",
                                    " Error in UnGroupWorkspace algorithm");
    }
  } catch (...) {
    view->showCriticalUserMessage("MantidPlot - Algorithm error",
                                  " Error in UnGroupWorkspace algorithm");
  }
}
/**
  @param  inname       Name of workspace containing peaks
  @param  params       optimized cell parameters
  @param  out          residuals from optimization
*/
void OptimizeLatticeForCellType::optLattice(std::string inname,
                                            std::vector<double> &params,
                                            double *out) {
  PeaksWorkspace_sptr ws = boost::dynamic_pointer_cast<PeaksWorkspace>(
      AnalysisDataService::Instance().retrieve(inname));
  const std::vector<Peak> &peaks = ws->getPeaks();
  size_t n_peaks = ws->getNumberPeaks();
  std::vector<V3D> q_vector;
  std::vector<V3D> hkl_vector;

  for (size_t i = 0; i < params.size(); i++)
    params[i] = std::abs(params[i]);
  for (size_t i = 0; i < n_peaks; i++) {
    q_vector.push_back(peaks[i].getQSampleFrame());
    hkl_vector.push_back(peaks[i].getHKL());
  }

  Mantid::API::IAlgorithm_sptr alg = createChildAlgorithm("CalculateUMatrix");
  alg->setPropertyValue("PeaksWorkspace", inname);
  alg->setProperty("a", params[0]);
  alg->setProperty("b", params[1]);
  alg->setProperty("c", params[2]);
  alg->setProperty("alpha", params[3]);
  alg->setProperty("beta", params[4]);
  alg->setProperty("gamma", params[5]);
  alg->executeAsChildAlg();

  ws = alg->getProperty("PeaksWorkspace");
  OrientedLattice latt = ws->mutableSample().getOrientedLattice();
  DblMatrix UB = latt.getUB();
  DblMatrix A = aMatrix(params);
  DblMatrix Bc = A;
  Bc.Invert();
  DblMatrix U1_B1 = UB * A;
  OrientedLattice o_lattice;
  o_lattice.setUB(U1_B1);
  DblMatrix U1 = o_lattice.getU();
  DblMatrix U1_Bc = U1 * Bc;

  for (size_t i = 0; i < hkl_vector.size(); i++) {
    V3D error = U1_Bc * hkl_vector[i] - q_vector[i] / (2.0 * M_PI);
    out[i] = error.norm2();
  }

  return;
}
Example #6
0
void ConvFit::setupFit(Mantid::API::IAlgorithm_sptr fitAlgorithm) {
  if (boolSettingValue("UseTempCorrection"))
    m_convFittingModel->setTemperature(doubleSettingValue("TempCorrection"));
  else
    m_convFittingModel->setTemperature(boost::none);
  fitAlgorithm->setProperty("ExtractMembers",
                            boolSettingValue("ExtractMembers"));
  IndirectFitAnalysisTab::setupFit(fitAlgorithm);
}
    /**
     * Set the "search" properties to their related input fields.
     * @param catalogAlgorithm :: Algorithm to set the search properties for.
     * @param userInputFields  :: The search properties to set against the algorithm.
     */
    void CatalogHelper::setSearchProperties(const Mantid::API::IAlgorithm_sptr &catalogAlgorithm,
        const std::map<std::string, std::string> &userInputFields)
    {
      // This will be the workspace where the content of the search result is output to.
      catalogAlgorithm->setProperty("OutputWorkspace", "__searchResults");

      // Iterate over the provided map of user input fields. For each field that isn't empty (e.g. a value was input by the user)
      // then we will set the algorithm property with the key and value of that specific value.
      for (auto it = userInputFields.begin(); it != userInputFields.end(); it++)
      {
        std::string value = it->second;
        // If the user has input any search terms.
        if (!value.empty())
        {
          // Set the property that the search algorithm uses to: (key => FieldName, value => FieldValue) (e.g., (Keywords, bob))
          catalogAlgorithm->setProperty(it->first, value);
        }
      }
    }
/**
 * Sorts the peak workspace by a specified column name in ascending or
 * descending order.
 * @param byColumnName The column by which the workspace is to be sorted.
 * @param ascending If the workspace is to be sorted in a ascending or
 * descending manner.
 */
void ConcretePeaksPresenterVsi::sortPeaksWorkspace(
    const std::string &byColumnName, const bool ascending) {
  Mantid::API::IPeaksWorkspace_sptr peaksWS =
      boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(
          this->m_peaksWorkspace);

  // Sort the Peaks in-place.
  Mantid::API::IAlgorithm_sptr alg =
      Mantid::API::AlgorithmManager::Instance().create("SortPeaksWorkspace");
  alg->setChild(true);
  alg->setRethrows(true);
  alg->initialize();
  alg->setProperty("InputWorkspace", peaksWS);
  alg->setPropertyValue("OutputWorkspace", "SortedPeaksWorkspace");
  alg->setProperty("OutputWorkspace", peaksWS);
  alg->setProperty("SortAscending", ascending);
  alg->setPropertyValue("ColumnNameToSortBy", byColumnName);
  alg->execute();
}
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;
}
Example #10
0
bool ConcretePeaksPresenter::addPeakAt(double plotCoordsPointX,
                                       double plotCoordsPointY) {
  V3D plotCoordsPoint(plotCoordsPointX, plotCoordsPointY,
                      m_slicePoint.slicePoint());
  V3D hkl = m_transform->transformBack(plotCoordsPoint);

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

  Mantid::API::IAlgorithm_sptr alg =
      AlgorithmManager::Instance().create("AddPeakHKL");
  alg->setChild(true);
  alg->setRethrows(true);
  alg->initialize();
  alg->setProperty("Workspace", peaksWS);
  alg->setProperty("HKL", std::vector<double>(hkl));

  // Execute the algorithm
  try {
    alg->execute();
  } catch (...) {
    g_log.warning("ConcretePeaksPresenter: Could not add the peak. Make sure "
                  "that it is added within a valid workspace region");
  }

  // Reproduce the views. Proxy representations recreated for all peaks.
  this->produceViews();

  // Refind visible peaks and Set the proxy representations to be visible or
  // not.
  doFindPeaksInRegion();

  // Upstream controls need to be regenerated.
  this->informOwnerUpdate();

  return alg->isExecuted();
}
Example #11
0
void ConcretePeaksPresenter::sortPeaksWorkspace(const std::string &byColumnName,
                                                const bool ascending) {
  Mantid::API::IPeaksWorkspace_sptr peaksWS =
      boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(this->m_peaksWS);

  // Sort the Peaks in-place.
  Mantid::API::IAlgorithm_sptr alg =
      AlgorithmManager::Instance().create("SortPeaksWorkspace");
  alg->setChild(true);
  alg->setRethrows(true);
  alg->initialize();
  alg->setProperty("InputWorkspace", peaksWS);
  alg->setPropertyValue("OutputWorkspace", "SortedPeaksWorkspace");
  alg->setProperty("OutputWorkspace", peaksWS);
  alg->setProperty("SortAscending", ascending);
  alg->setPropertyValue("ColumnNameToSortBy", byColumnName);
  alg->execute();

  // Reproduce the views.
  this->produceViews();

  // Give the new views the current slice point.
  m_viewPeaks->setSlicePoint(this->m_slicePoint.slicePoint(), m_viewablePeaks);
}
Example #12
0
bool ConcretePeaksPresenter::deletePeaksIn(PeakBoundingBox box) {

  Left left(box.left());
  Right right(box.right());
  Bottom bottom(box.bottom());
  Top top(box.top());
  SlicePoint slicePoint(box.slicePoint());
  if (slicePoint() < 0) { // indicates that it should not be used.
    slicePoint = SlicePoint(m_slicePoint.slicePoint());
  }

  PeakBoundingBox accurateBox(
      left, right, top, bottom,
      slicePoint /*Use the current slice position, previously unknown.*/);

  // Tranform box from plot coordinates into orderd HKL, Qx,Qy,Qz etc, then find
  // the visible peaks.
  std::vector<size_t> deletionIndexList = findVisiblePeakIndexes(accurateBox);

  // If we have things to remove, do that in one-step.
  if (!deletionIndexList.empty()) {

    Mantid::API::IPeaksWorkspace_sptr peaksWS =
        boost::const_pointer_cast<Mantid::API::IPeaksWorkspace>(
            this->m_peaksWS);
    // Sort the Peaks in-place.
    Mantid::API::IAlgorithm_sptr alg =
        AlgorithmManager::Instance().create("DeleteTableRows");
    alg->setChild(true);
    alg->setRethrows(true);
    alg->initialize();
    alg->setProperty("TableWorkspace", peaksWS);
    alg->setProperty("Rows", deletionIndexList);
    alg->execute();

    // Reproduce the views. Proxy representations recreated for all peaks.
    this->produceViews();

    // Refind visible peaks and Set the proxy representations to be visible or
    // not.
    doFindPeaksInRegion();

    // Upstream controls need to be regenerated.
    this->informOwnerUpdate();
  }
  return !deletionIndexList.empty();
}
Mantid::API::MatrixWorkspace_sptr SANSPlotSpecial::runIQTransform() {
  // Run the IQTransform algorithm for the current settings on the GUI
  Mantid::API::IAlgorithm_sptr iqt =
      Mantid::API::AlgorithmManager::Instance().create("IQTransform");
  iqt->initialize();
  try {
    iqt->setPropertyValue("InputWorkspace",
                          m_uiForm.wsInput->currentText().toStdString());
  } catch (std::invalid_argument &) {
    m_uiForm.lbPlotOptionsError->setText(
        "Selected input workspace is not appropriate for the IQTransform "
        "algorithm. Please refer to the documentation for guidelines.");
    return Mantid::API::MatrixWorkspace_sptr();
  }
  iqt->setPropertyValue("OutputWorkspace", "__sans_isis_display_iqt");
  iqt->setPropertyValue("TransformType",
                        m_uiForm.cbPlotType->currentText().toStdString());

  if (m_uiForm.cbBackground->currentText() == "Value") {
    iqt->setProperty<double>("BackgroundValue", m_uiForm.dsBackground->value());
  } else {
    iqt->setPropertyValue("BackgroundWorkspace",
                          m_uiForm.wsBackground->currentText().toStdString());
  }

  if (m_uiForm.cbPlotType->currentText() == "General") {
    std::vector<double> constants =
        m_transforms["General"]->functionConstants();
    iqt->setProperty("GeneralFunctionConstants", constants);
  }

  iqt->execute();

  Mantid::API::MatrixWorkspace_sptr result =
      boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(
          Mantid::API::AnalysisDataService::Instance().retrieve(
              "__sans_isis_display_iqt"));
  return result;
}
void WorkspacePresenter::groupWorkspaces() {
  auto view = lockView();
  auto selected = view->getSelectedWorkspaceNames();

  std::string groupName("NewGroup");
  // get selected workspaces
  if (selected.size() < 2) {
    view->showCriticalUserMessage("Cannot Group Workspaces",
                                  "Select at least two workspaces to group ");
    return;
  }

  if (m_adapter->doesWorkspaceExist(groupName)) {
    if (!view->askUserYesNo("",
                            "Workspace " + groupName +
                                " already exists. Do you want to replace it?"))
      return;
  }

  try {
    std::string algName("GroupWorkspaces");
    Mantid::API::IAlgorithm_sptr alg =
        Mantid::API::AlgorithmManager::Instance().create(algName, -1);
    alg->initialize();
    alg->setProperty("InputWorkspaces", selected);
    alg->setPropertyValue("OutputWorkspace", groupName);
    // execute the algorithm
    bool bStatus = alg->execute();
    if (!bStatus) {
      view->showCriticalUserMessage("MantidPlot - Algorithm error",
                                    " Error in GroupWorkspaces algorithm");
    }
  } catch (...) {
    view->showCriticalUserMessage("MantidPlot - Algorithm error",
                                  " Error in GroupWorkspaces algorithm");
  }
}
Example #15
0
/**
 * Create a list of files from the given algorithm property.
 */
void FindFilesThread::getFilesFromAlgorithm() {
  Mantid::API::IAlgorithm_sptr algorithm =
      Mantid::API::AlgorithmManager::Instance().createUnmanaged(
          m_algorithm.toStdString());

  if (!algorithm)
    throw std::invalid_argument("Cannot create algorithm " +
                                m_algorithm.toStdString() + ".");

  algorithm->initialize();
  const std::string propName = m_property.toStdString();
  algorithm->setProperty(propName, m_text);

  Property *prop = algorithm->getProperty(propName);
  m_valueForProperty = QString::fromStdString(prop->value());

  FileProperty *fileProp = dynamic_cast<FileProperty *>(prop);
  MultipleFileProperty *multiFileProp =
      dynamic_cast<MultipleFileProperty *>(prop);

  if (fileProp) {
    m_filenames.push_back(fileProp->value());
  } else if (multiFileProp) {
    // This flattens any summed files to a set of single files so that you lose
    // the information about
    // what was summed
    std::vector<std::vector<std::string>> filenames =
        algorithm->getProperty(propName);
    std::vector<std::string> flattenedNames =
        VectorHelper::flattenVector(filenames);

    for (auto filename = flattenedNames.begin();
         filename != flattenedNames.end(); ++filename) {
      m_filenames.push_back(*filename);
    }
  }
}
Example #16
0
/**
 * Groups the workspace according to grouping provided.
 *
 * @param ws :: Workspace to group
 * @param  g :: The grouping information
 * @return Sptr to created grouped workspace
 */
MatrixWorkspace_sptr groupWorkspace(MatrixWorkspace_const_sptr ws, const Grouping& g)
{
  // As I couldn't specify multiple groups for GroupDetectors, I am going down quite a complicated
  // route - for every group distinct grouped workspace is created using GroupDetectors. These
  // workspaces are then merged into the output workspace.

  // Create output workspace
  MatrixWorkspace_sptr outWs =
    WorkspaceFactory::Instance().create(ws, g.groups.size(), ws->readX(0).size(), ws->blocksize());

  for(size_t gi = 0; gi < g.groups.size(); gi++)
  {
    Mantid::API::IAlgorithm_sptr alg = AlgorithmManager::Instance().create("GroupDetectors");
    alg->setChild(true); // So Output workspace is not added to the ADS
    alg->initialize();
    alg->setProperty("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(ws));
    alg->setPropertyValue("SpectraList", g.groups[gi]);
    alg->setPropertyValue("OutputWorkspace", "grouped"); // Is not actually used, just to make validators happy
    alg->execute();

    MatrixWorkspace_sptr grouped = alg->getProperty("OutputWorkspace");

    // Copy the spectrum
    *(outWs->getSpectrum(gi)) = *(grouped->getSpectrum(0));

    // Update spectrum number
    outWs->getSpectrum(gi)->setSpectrumNo(static_cast<specid_t>(gi));

    // Copy to the output workspace
    outWs->dataY(gi) = grouped->readY(0);
    outWs->dataX(gi) = grouped->readX(0);
    outWs->dataE(gi) = grouped->readE(0);
  }

  return outWs;
}