/**
 * Handles completion of the algorithm.
 *
 * Sets result workspace for Python export and ungroups result WorkspaceGroup.
 *
 * @param error True if the algorithm was stopped due to error, false otherwise
 */
void ISISEnergyTransfer::algorithmComplete(bool error) {
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(algorithmComplete(bool)));

  if (error)
    return;

  WorkspaceGroup_sptr energyTransferOutputGroup =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
          "IndirectEnergyTransfer_Workspaces");
  if (energyTransferOutputGroup->size() == 0)
    return;

  // Set workspace for Python export as the first result workspace
  m_pythonExportWsName = energyTransferOutputGroup->getNames()[0];
  m_outputWorkspaces = energyTransferOutputGroup->getNames();
  // Ungroup the output workspace
  energyTransferOutputGroup->removeAll();
  AnalysisDataService::Instance().remove("IndirectEnergyTransfer_Workspaces");

  // Enable plotting and saving
  m_uiForm.pbPlot->setEnabled(true);
  m_uiForm.cbPlotType->setEnabled(true);
  m_uiForm.pbSave->setEnabled(true);
  m_uiForm.ckSaveAclimax->setEnabled(true);
  m_uiForm.ckSaveASCII->setEnabled(true);
  m_uiForm.ckSaveDaveGrp->setEnabled(true);
  m_uiForm.ckSaveNexus->setEnabled(true);
  m_uiForm.ckSaveNXSPE->setEnabled(true);
  m_uiForm.ckSaveSPE->setEnabled(true);
}
/**
 * Returns a list of sequentially fitted workspaces names.
 * @param label :: Label to return sequential fits for
 * @return List of workspace base names
 */
QStringList MuonAnalysisResultTableTab::getSequentialFitWorkspaces(const QString& label)
{
  const AnalysisDataServiceImpl& ads = AnalysisDataService::Instance();

  std::string groupName = MuonSequentialFitDialog::SEQUENTIAL_PREFIX + label.toStdString();

  WorkspaceGroup_sptr group;

  // Might have been accidentally deleted by user
  if ( ! ads.doesExist(groupName) || ! ( group = ads.retrieveWS<WorkspaceGroup>(groupName) ) )
  {
    QMessageBox::critical(this, "Group not found", 
      "Group with fitting results of the specified label was not found.");
    return QStringList();
  }

  std::vector<std::string> wsNames = group->getNames(); 

  QStringList workspaces;

  for (auto it = wsNames.begin(); it != wsNames.end(); it++)
  {
    if( ! isFittedWs(*it) )
      continue; // Doesn't pass basic checks

    workspaces << QString::fromStdString( wsBaseName(*it) );
  }

  return workspaces;
}
/**
 * Handles completion of algorithm
 *
 * @param error True if the chain was stopped due to error
 */
void IndirectDiffractionReduction::algorithmComplete(bool error) {
  // Handles completion of the diffraction algorithm chain
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(algorithmComplete(bool)));

  if (error) {
    showInformationBox(
        "Error running diffraction reduction.\nSee Results Log for details.");
    return;
  }
  // Ungroup the output workspace if generic reducer was used
  if (AnalysisDataService::Instance().doesExist(
          "IndirectDiffraction_Workspaces")) {
    WorkspaceGroup_sptr diffResultsGroup =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            "IndirectDiffraction_Workspaces");

    m_plotWorkspaces.clear();
    m_plotWorkspaces = diffResultsGroup->getNames();

    diffResultsGroup->removeAll();
    AnalysisDataService::Instance().remove("IndirectDiffraction_Workspaces");
  }
  // Enable plotting
  m_uiForm.pbPlot->setEnabled(true);
  m_uiForm.cbPlotType->setEnabled(true);
  // Enable saving
  m_uiForm.ckAscii->setEnabled(true);
  m_uiForm.ckGSS->setEnabled(true);
  m_uiForm.ckNexus->setEnabled(true);
  m_uiForm.pbSave->setEnabled(true);
}
Exemple #4
0
/**
 * Groups together a vector of workspaces.  This is done "manually", since the
 * workspaces being passed will be outside of the ADS and so the GroupWorkspaces
 * alg is not an option here.
 *
 * @param wsList :: the list of workspaces to group
 */
API::WorkspaceGroup_sptr
Load::groupWsList(const std::vector<API::Workspace_sptr> &wsList) {
  auto group = boost::make_shared<WorkspaceGroup>();

  for (const auto &ws : wsList) {
    WorkspaceGroup_sptr isGroup =
        boost::dynamic_pointer_cast<WorkspaceGroup>(ws);
    // If the ws to add is already a group, then add its children individually.
    if (isGroup) {
      std::vector<std::string> childrenNames = isGroup->getNames();
      size_t count = 1;
      for (auto childName = childrenNames.begin();
           childName != childrenNames.end(); ++childName, ++count) {
        Workspace_sptr childWs = isGroup->getItem(*childName);
        isGroup->remove(*childName);
        // childWs->setName(isGroup->getName() + "_" +
        // boost::lexical_cast<std::string>(count));
        group->addWorkspace(childWs);
      }

      // Remove the old group from the ADS
      AnalysisDataService::Instance().remove(isGroup->getName());
    } else {
      group->addWorkspace(ws);
    }
  }

  return group;
}
/**
 * Handles plotting result spectra from algorithm chains.
 *
 * @param error True if the chain was stopped due to error
 */
void IndirectDiffractionReduction::plotResults(bool error) {
  // Handles completion of the diffraction algorithm chain
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(plotResults(bool)));

  // Nothing can be plotted
  if (error) {
    showInformationBox(
        "Error running diffraction reduction.\nSee Results Log for details.");
    return;
  }

  // Ungroup the output workspace if generic reducer was used
  if (AnalysisDataService::Instance().doesExist(
          "IndirectDiffraction_Workspaces")) {
    WorkspaceGroup_sptr diffResultsGroup =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            "IndirectDiffraction_Workspaces");

    m_plotWorkspaces.clear();
    m_plotWorkspaces = diffResultsGroup->getNames();

    diffResultsGroup->removeAll();
    AnalysisDataService::Instance().remove("IndirectDiffraction_Workspaces");

    saveGenericReductions();
  }

  QString instName = m_uiForm.iicInstrumentConfiguration->getInstrumentName();
  QString mode = m_uiForm.iicInstrumentConfiguration->getReflectionName();

  QString plotType = m_uiForm.cbPlotType->currentText();

  QString pyInput = "from mantidplot import plotSpectrum, plot2D\n";

  if (plotType == "Spectra" || plotType == "Both") {
    for (auto it = m_plotWorkspaces.begin(); it != m_plotWorkspaces.end(); ++it)
      pyInput += "plotSpectrum('" + QString::fromStdString(*it) + "', 0)\n";
  }

  if (plotType == "Contour" || plotType == "Both") {
    for (auto it = m_plotWorkspaces.begin(); it != m_plotWorkspaces.end(); ++it)
      pyInput += "plot2D('" + QString::fromStdString(*it) + "')\n";
  }

  runPythonCode(pyInput);
}
  /**
   * Handles completion of the algorithm.
   *
   * Sets result workspace for Python export and ungroups result WorkspaceGroup.
   *
   * @param error True if the algorithm was stopped due to error, false otherwise
   */
  void IndirectConvertToEnergy::algorithmComplete(bool error)
  {
    disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this, SLOT(algorithmComplete(bool)));

    if(error)
      return;

    WorkspaceGroup_sptr energyTransferOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("IndirectEnergyTransfer_Workspaces");
    if(energyTransferOutputGroup->size() == 0)
      return;

    // Set workspace for Python export as the first result workspace
    m_pythonExportWsName = energyTransferOutputGroup->getNames()[0];

    // Ungroup the output workspace
    energyTransferOutputGroup->removeAll();
    AnalysisDataService::Instance().remove("IndirectEnergyTransfer_Workspaces");
  }
Exemple #7
0
/**
 * Handles plotting the preview plot when the algorithm finishes.
 *
 * @param error True if the algorithm exited due to error, false otherwise
 */
void IndirectMoments::momentsAlgComplete(bool error)
{
    if(error)
        return;

    QString workspaceName = m_uiForm.dsInput->getCurrentDataName();
    QString outputName = workspaceName.left(workspaceName.length() - 4);
    std::string outputWorkspaceName = outputName.toStdString() + "_Moments";

    WorkspaceGroup_sptr resultWsGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(outputWorkspaceName);
    std::vector<std::string> resultWsNames = resultWsGroup->getNames();

    if(resultWsNames.size() < 4)
        return;

    // Plot each spectrum
    m_uiForm.ppMomentsPreview->clear();
    m_uiForm.ppMomentsPreview->addSpectrum("M0", QString::fromStdString(resultWsNames[0]), 0, Qt::green);
    m_uiForm.ppMomentsPreview->addSpectrum("M1", QString::fromStdString(resultWsNames[2]), 0, Qt::black);
    m_uiForm.ppMomentsPreview->addSpectrum("M2", QString::fromStdString(resultWsNames[3]), 0, Qt::red);
    m_uiForm.ppMomentsPreview->resizeX();
}
/**
 * Handle plotting of mantid workspace
 */
void IndirectMolDyn::plotClicked() {

  QString filename = m_uiForm.mwRun->getFirstFilename();
  QFileInfo fi(filename);
  QString baseName = fi.baseName();

  if (checkADSForPlotSaveWorkspace(baseName.toStdString(), true)) {

    WorkspaceGroup_sptr diffResultsGroup =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            baseName.toStdString());

    auto names = diffResultsGroup->getNames();
    auto plotType = m_uiForm.cbPlot->currentText();

    for (const auto wsName : names) {
      if (plotType == "Spectra" || plotType == "Both")
        plotSpectrum(QString::fromStdString(wsName));

      if (plotType == "Contour" || plotType == "Both")
        plot2D(QString::fromStdString(wsName));
    }
  }
}
/** Flattens the list of group workspaces (if any) into list of workspaces
 * @param inputs : input workspaces vector [including] group workspaces (all
 * must be on ADS)
 * @return : the flat vector of the input workspaces
 * @throw : std::runtime_error if the input workspaces are neither groups nor
 * MatrixWorkspaces
 */
std::vector<std::string>
RunCombinationHelper::unWrapGroups(const std::vector<std::string> &inputs) {
  std::vector<std::string> outputs;
  for (const auto &input : inputs) {
    WorkspaceGroup_sptr wsgroup =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(input);
    if (wsgroup) {
      // workspace group
      std::vector<std::string> group = wsgroup->getNames();
      outputs.insert(outputs.end(), group.begin(), group.end());
    } else {
      // MatrixWorkspace
      MatrixWorkspace_sptr matrixws =
          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(input);
      if (matrixws)
        outputs.push_back(matrixws->getName());
      else
        throw(std::runtime_error(
            "The input " + input +
            " is neither a WorkspaceGroup nor a MatrixWorkspace"));
    }
  }
  return outputs;
}
Exemple #10
0
/**
 * Create FITS file information for each file selected. Loads headers
 * and data from the files and creates and fills the output
 * workspace(s).
 *
 * @param paths File names as given in the algorithm input property
 *
 * @param outWSName name of the output (group) workspace to create
 *
 * @param loadAsRectImg Load files with 1 spectrum per row and 1 bin
 * per column, so a color fill plot displays the image
 *
 * @param binSize size to rebin (1 == no re-bin == default)
 *
 * @param noiseThresh threshold for noise filtering
 *
 * @throw std::runtime_error when load fails (for example a memory
 * allocation issue, wrong rebin requested, etc.)
 */
void LoadFITS::doLoadFiles(const std::vector<std::string> &paths,
                           const std::string &outWSName, bool loadAsRectImg,
                           int binSize, double noiseThresh) {
  std::vector<FITSInfo> headers;
  headers.resize(paths.size());

  loadHeader(paths[0], headers[0]);

  // No extension is set -> it's the standard format which we can parse.
  if (headers[0].numberOfAxis > 0)
    m_pixelCount += headers[0].axisPixelLengths[0];

  // Presumably 2 axis, but futureproofing.
  for (int i = 1; i < headers[0].numberOfAxis; ++i) {
    m_pixelCount *= headers[0].axisPixelLengths[i];
  }

  // Check consistency of binSize asap
  for (int i = 0; i < headers[0].numberOfAxis; ++i) {
    if (0 != (headers[0].axisPixelLengths[i] % binSize)) {
      throw std::runtime_error(
          "Cannot rebin this image in blocks of " + std::to_string(binSize) +
          " x " + std::to_string(binSize) +
          " pixels as requested because the size of dimension " +
          std::to_string(i + 1) + " (" +
          std::to_string(headers[0].axisPixelLengths[i]) +
          ") is not a multiple of the bin size.");
    }
  }

  MantidImage imageY(headers[0].axisPixelLengths[1],
                     std::vector<double>(headers[0].axisPixelLengths[0]));
  MantidImage imageE(headers[0].axisPixelLengths[1],
                     std::vector<double>(headers[0].axisPixelLengths[0]));

  size_t bytes = (headers[0].bitsPerPixel / 8) * m_pixelCount;
  std::vector<char> buffer;
  try {
    buffer.resize(bytes);
  } catch (std::exception &) {
    throw std::runtime_error(
        "Could not allocate enough memory to run when trying to allocate " +
        std::to_string(bytes) + " bytes.");
  }

  // Create a group for these new workspaces, if the group already exists, add
  // to it.
  size_t fileNumberInGroup = 0;
  WorkspaceGroup_sptr wsGroup;

  if (!AnalysisDataService::Instance().doesExist(outWSName)) {
    wsGroup = boost::make_shared<WorkspaceGroup>();
    wsGroup->setTitle(outWSName);
  } else {
    // Get the name of the latest file in group to start numbering from
    if (AnalysisDataService::Instance().doesExist(outWSName))
      wsGroup =
          AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(outWSName);

    std::string latestName = wsGroup->getNames().back();
    // Set next file number
    fileNumberInGroup = fetchNumber(latestName) + 1;
  }

  size_t totalWS = headers.size();
  // Create a progress reporting object
  API::Progress progress(this, 0, 1, totalWS + 1);
  progress.report(0, "Loading file(s) into workspace(s)");

  // Create first workspace (with instrument definition). This is also used as
  // a template for creating others
  Workspace2D_sptr imgWS;
  imgWS = makeWorkspace(headers[0], fileNumberInGroup, buffer, imageY, imageE,
                        imgWS, loadAsRectImg, binSize, noiseThresh);
  progress.report(1, "First file loaded.");

  wsGroup->addWorkspace(imgWS);

  if (isInstrOtherThanIMAT(headers[0])) {
    // For now we assume IMAT except when specific headers are found by
    // isInstrOtherThanIMAT()
    //
    // TODO: do this conditional on INSTR='IMAT' when we have proper IMAT .fits
    // files
    try {
      IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrument");
      std::string directoryName =
          Kernel::ConfigService::Instance().getInstrumentDirectory();
      directoryName = directoryName + "/IMAT_Definition.xml";
      loadInst->setPropertyValue("Filename", directoryName);
      loadInst->setProperty<MatrixWorkspace_sptr>(
          "Workspace", boost::dynamic_pointer_cast<MatrixWorkspace>(imgWS));
      loadInst->execute();
    } catch (std::exception &ex) {
      g_log.information("Cannot load the instrument definition. " +
                        std::string(ex.what()));
    }
  }

  // don't feel tempted to parallelize this loop as it is - it uses the same
  // imageY and imageE buffers for all the workspaces
  for (int64_t i = 1; i < static_cast<int64_t>(totalWS); ++i) {
    loadHeader(paths[i], headers[i]);
    // Check each header is valid/supported: standard (no extension to
    // FITS), has two axis, and it is consistent with the first header
    headerSanityCheck(headers[i], headers[0]);

    imgWS = makeWorkspace(headers[i], fileNumberInGroup, buffer, imageY, imageE,
                          imgWS, loadAsRectImg, binSize, noiseThresh);
    progress.report("Loaded file " + std::to_string(i + 1) + " of " +
                    std::to_string(totalWS));
    wsGroup->addWorkspace(imgWS);
  }

  setProperty("OutputWorkspace", wsGroup);
}