Exemple #1
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;
}
Exemple #2
0
/**
 * Handles the plotting of workspace post algorithm completion
 */
void Stretch::plotWorkspaces() {

  WorkspaceGroup_sptr fitWorkspace;
  fitWorkspace = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
      m_fitWorkspaceName);

  auto sigma = QString::fromStdString(fitWorkspace->getItem(0)->getName());
  auto beta = QString::fromStdString(fitWorkspace->getItem(1)->getName());
  // Check Sigma and Beta workspaces exist
  if (sigma.right(5).compare("Sigma") == 0) {
    if (beta.right(4).compare("Beta") == 0) {

      // Plot Beta workspace
      QString pyInput = "from mantidplot import plot2D\n";
      if (m_plotType.compare("All") == 0 || m_plotType.compare("Beta") == 0) {
        pyInput += "importMatrixWorkspace('";
        pyInput += beta;
        pyInput += "').plotGraph2D()\n";
      }
      // Plot Sigma workspace
      if (m_plotType.compare("All") == 0 || m_plotType.compare("Sigma") == 0) {
        pyInput += "importMatrixWorkspace('";
        pyInput += sigma;
        pyInput += "').plotGraph2D()\n";
      }
      m_pythonRunner.runPythonCode(pyInput);
    }
  } else {
    g_log.error(
        "Beta and Sigma workspace were not found and could not be plotted.");
  }
}
/** Process WorkspaceGroup inputs.
 *
 * Overriden from Algorithm base class.
 *
 * This should be called after checkGroups(), which sets up required members.
 * It goes through each member of the group(s), creates and sets an algorithm
 * for each and executes them one by one.
 *
 * If there are several group input workspaces, then the member of each group
 * is executed pair-wise.
 *
 * @param sourceAlg : Source algorithm
 * @param vecMultiPeriodGroups : Vector of pre-identified multiperiod groups.
 * @return true - if all the workspace members are executed.
 */
bool MultiPeriodGroupWorker::processGroups(
    Algorithm *const sourceAlg,
    const VecWSGroupType &vecMultiPeriodGroups) const {
  // If we are not processing multiperiod groups, use the base behaviour.
  if (vecMultiPeriodGroups.empty()) {
    return false; // Indicates that this is not a multiperiod group workspace.
  }
  Property *outputWorkspaceProperty = sourceAlg->getProperty("OutputWorkspace");
  const std::string outName = outputWorkspaceProperty->value();

  const size_t nPeriods = vecMultiPeriodGroups[0]->size();
  WorkspaceGroup_sptr outputWS = boost::make_shared<WorkspaceGroup>();
  AnalysisDataService::Instance().addOrReplace(outName, outputWS);

  double progress_proportion = 1.0 / static_cast<double>(nPeriods);
  // Loop through all the periods. Create spawned algorithms of the same type as
  // this to process pairs from the input groups.
  for (size_t i = 0; i < nPeriods; ++i) {
    const int periodNumber = static_cast<int>(i + 1);
    // use create Child Algorithm that look like this one
    Algorithm_sptr alg = sourceAlg->createChildAlgorithm(
        sourceAlg->name(), progress_proportion * periodNumber,
        progress_proportion * (1 + periodNumber), sourceAlg->isLogging(),
        sourceAlg->version());
    if (!alg) {
      throw std::runtime_error("Algorithm creation failed.");
    }
    // Don't make the new algorithm a child so that it's workspaces are stored
    // correctly
    alg->setChild(false);
    alg->setRethrows(true);
    alg->initialize();
    // Copy properties that aren't workspaces properties.
    sourceAlg->copyNonWorkspaceProperties(alg.get(), periodNumber);

    if (this->useCustomWorkspaceProperty()) {
      const std::string inputWorkspaces =
          createFormattedInputWorkspaceNames(i, vecMultiPeriodGroups);
      // Set the input workspace property.
      alg->setPropertyValue(this->m_workspacePropertyName, inputWorkspaces);
    } else {
      // Configure input properties that are group workspaces.
      copyInputWorkspaceProperties(alg.get(), sourceAlg, periodNumber);
    }
    const std::string outName_i = outName + "_" + Strings::toString(i + 1);
    alg->setPropertyValue("OutputWorkspace", outName_i);
    // Run the spawned algorithm.
    if (!alg->execute()) {
      throw std::runtime_error("Execution of " + sourceAlg->name() +
                               " for group entry " + Strings::toString(i + 1) +
                               " failed.");
    }
    // Add the output workpace from the spawned algorithm to the group.
    outputWS->add(outName_i);
  }

  sourceAlg->setProperty("OutputWorkspace", outputWS);

  return true;
}
/**
 * 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 #5
0
/**
 * Handles the plotting of workspace post algorithm completion
 */
void Stretch::plotWorkspaces() {
  setPlotResultIsPlotting(true);
  WorkspaceGroup_sptr fitWorkspace;
  fitWorkspace = getADSWorkspaceGroup(m_fitWorkspaceName);

  auto sigma = QString::fromStdString(fitWorkspace->getItem(0)->getName());
  auto beta = QString::fromStdString(fitWorkspace->getItem(1)->getName());
  // Check Sigma and Beta workspaces exist
  if (sigma.right(5).compare("Sigma") == 0 &&
      beta.right(4).compare("Beta") == 0) {
    QString pyInput = "from mantidplot import plot2D\n";

    std::string const plotType = m_uiForm.cbPlot->currentText().toStdString();
    if (plotType == "All" || plotType == "Beta") {
      pyInput += "importMatrixWorkspace('";
      pyInput += beta;
      pyInput += "').plotGraph2D()\n";
    }
    if (plotType == "All" || plotType == "Sigma") {
      pyInput += "importMatrixWorkspace('";
      pyInput += sigma;
      pyInput += "').plotGraph2D()\n";
    }

    m_pythonRunner.runPythonCode(pyInput);
  } else {
    g_log.error(
        "Beta and Sigma workspace were not found and could not be plotted.");
  }
  setPlotResultIsPlotting(false);
}
/**
 * Handles completion of the algorithm.
 *
 * @param error If the algorithm failed
 */
void ISISDiagnostics::algorithmComplete(bool error) {
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(algorithmComplete(bool)));

  if (error)
    return;

  WorkspaceGroup_sptr sliceOutputGroup =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
          "IndirectDiagnostics_Workspaces");
  if (sliceOutputGroup->size() == 0) {
    g_log.warning("No result workspaces, cannot plot preview.");
    return;
  }

  for (size_t i = 0; i < sliceOutputGroup->size(); i++) {
    QString wsName =
        QString::fromStdString(sliceOutputGroup->getItem(i)->name());
  }
  // Enable plot and save buttons
  m_uiForm.pbSave->setEnabled(true);
  m_uiForm.pbPlot->setEnabled(true);

  // Update the preview plots
  sliceAlgDone(false);

  m_batchAlgoRunner->executeBatchAsync();
}
WorkspaceGroup_sptr PolarizationCorrection::execPNR(WorkspaceGroup_sptr inWS) {
    size_t itemIndex = 0;
    MatrixWorkspace_sptr Ip =
        boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++));
    MatrixWorkspace_sptr Ia =
        boost::dynamic_pointer_cast<MatrixWorkspace>(inWS->getItem(itemIndex++));

    MatrixWorkspace_sptr ones = copyShapeAndFill(Ip, 1.0);

    const VecDouble c_rho = getProperty(crhoLabel());
    const VecDouble c_pp = getProperty(cppLabel());

    const auto rho = this->execPolynomialCorrection(
                         ones, c_rho); // Execute polynomial expression
    const auto pp = this->execPolynomialCorrection(
                        ones, c_pp); // Execute polynomial expression

    const auto D = pp * (rho + 1);

    const auto nIp = (Ip * (rho * pp + 1.0) + Ia * (pp - 1.0)) / D;
    const auto nIa = (Ip * (rho * pp - 1.0) + Ia * (pp + 1.0)) / D;

    // Preserve the history of the inside workspaces
    nIp->history().addHistory(Ip->getHistory());
    nIa->history().addHistory(Ia->getHistory());

    WorkspaceGroup_sptr dataOut = boost::make_shared<WorkspaceGroup>();
    dataOut->addWorkspace(nIp);
    dataOut->addWorkspace(nIa);

    return dataOut;
}
Exemple #8
0
/**
 * Handle completion of the algorithm.
 *
 * @param error If the algorithm failed
 */
void ResNorm::handleAlgorithmComplete(bool error) {
  if (error)
    return;

  QString outputBase = (m_uiForm.dsResolution->getCurrentDataName()).toLower();
  const int indexCut = outputBase.lastIndexOf("_");
  outputBase = outputBase.left(indexCut);
  outputBase += "_ResNorm";

  std::string outputBaseStr = outputBase.toStdString();

  WorkspaceGroup_sptr fitWorkspaces =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
          outputBaseStr + "_Fit_Workspaces");
  QString fitWsName("");
  if (fitWorkspaces)
    fitWsName =
        QString::fromStdString(fitWorkspaces->getItem(m_previewSpec)->name());

  // MantidPlot plotting
  QString plotOptions(m_uiForm.cbPlot->currentText());
  if (plotOptions == "Intensity" || plotOptions == "All")
    plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Intensity");
  if (plotOptions == "Stretch" || plotOptions == "All")
    plotSpectrum(QString::fromStdString(m_pythonExportWsName) + "_Stretch");
  if (plotOptions == "Fit" || plotOptions == "All")
    plotSpectrum(fitWsName, 0, 1);

  loadFile(m_uiForm.dsResolution->getFullFilePath(),
           m_uiForm.dsResolution->getCurrentDataName());

  // Update preview plot
  previewSpecChanged(m_previewSpec);
}
  /**
   * Replots the energy mini plot
   */
  void ISISCalibration::calPlotEnergy()
  {
    if ( ! m_uiForm.leRunNo->isValid() )
    {
      emit showMessageBox("Run number not valid.");
      return;
    }

    QString files = m_uiForm.leRunNo->getFilenames().join(",");

    QFileInfo fi(m_uiForm.leRunNo->getFirstFilename());

    QString detRange = QString::number(m_dblManager->value(m_properties["ResSpecMin"])) + ","
                     + QString::number(m_dblManager->value(m_properties["ResSpecMax"]));

    IAlgorithm_sptr reductionAlg = AlgorithmManager::Instance().create("ISISIndirectEnergyTransfer");
    reductionAlg->initialize();
    reductionAlg->setProperty("Instrument", getInstrumentConfiguration()->getInstrumentName().toStdString());
    reductionAlg->setProperty("Analyser", getInstrumentConfiguration()->getAnalyserName().toStdString());
    reductionAlg->setProperty("Reflection", getInstrumentConfiguration()->getReflectionName().toStdString());
    reductionAlg->setProperty("InputFiles", files.toStdString());
    reductionAlg->setProperty("OutputWorkspace", "__IndirectCalibration_reduction");
    reductionAlg->setProperty("SpectraRange", detRange.toStdString());
    reductionAlg->execute();

    if(!reductionAlg->isExecuted())
    {
      g_log.warning("Could not generate energy preview plot.");
      return;
    }

    WorkspaceGroup_sptr reductionOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("__IndirectCalibration_reduction");
    if(reductionOutputGroup->size() == 0)
    {
      g_log.warning("No result workspaces, cannot plot energy preview.");
      return;
	}

    MatrixWorkspace_sptr energyWs = boost::dynamic_pointer_cast<MatrixWorkspace>(reductionOutputGroup->getItem(0));
    if(!energyWs)
    {
      g_log.warning("No result workspaces, cannot plot energy preview.");
      return;
    }

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

    auto resBackground = m_uiForm.ppResolution->getRangeSelector("ResBackground");
    setPlotPropertyRange(resBackground, m_properties["ResStart"], m_properties["ResEnd"], range);

    m_uiForm.ppResolution->clear();
    m_uiForm.ppResolution->addSpectrum("Energy", energyWs, 0);
    m_uiForm.ppResolution->resizeX();

    calSetDefaultResolution(energyWs);

    m_uiForm.ppResolution->replot();
  }
Exemple #10
0
/**
 * Sort members by Workspace name. The group must be in the ADS.
 * @param groupName :: A group name.
 */
void AnalysisDataServiceImpl::sortGroupByName(const std::string &groupName) {
  WorkspaceGroup_sptr group = retrieveWS<WorkspaceGroup>(groupName);
  if (!group) {
    throw std::runtime_error("Workspace " + groupName +
                             " is not a workspace group.");
  }
  group->sortMembersByName();
  notificationCenter.postNotification(new GroupUpdatedNotification(groupName));
}
/** Execute the algorithm.
 */
void PolarizationCorrection::exec() {
    WorkspaceGroup_sptr inWS = getProperty("InputWorkspace");
    const std::string analysisMode = getProperty("PolarizationAnalysis");
    const size_t nWorkspaces = inWS->size();

    validateInputWorkspace(inWS);

    Instrument_const_sptr instrument = fetchInstrument(inWS.get());

    // Check if we need to fetch polarization parameters from the instrument's
    // parameters
    std::map<std::string, std::string> loadableProperties;
    loadableProperties[crhoLabel()] = "crho";
    loadableProperties[cppLabel()] = "cPp";

    // In PA mode, we also require cap and calpha
    if (analysisMode == pALabel()) {
        loadableProperties[cApLabel()] = "cAp";
        loadableProperties[cAlphaLabel()] = "calpha";
    }

    for (auto propName = loadableProperties.begin();
            propName != loadableProperties.end(); ++propName) {
        Property *prop = getProperty(propName->first);

        if (!prop)
            continue;

        if (prop->isDefault()) {
            auto vals = instrument->getStringParameter(propName->second);
            if (vals.empty())
                throw std::runtime_error(
                    "Cannot find value for " + propName->first +
                    " in parameter file. Please specify this property manually.");
            prop->setValue(vals[0]);
        }
    }

    WorkspaceGroup_sptr outWS;
    if (analysisMode == pALabel()) {
        if (nWorkspaces != 4) {
            throw std::invalid_argument(
                "For PA analysis, input group must have 4 periods.");
        }
        g_log.notice("PA polarization correction");
        outWS = execPA(inWS);
    } else if (analysisMode == pNRLabel()) {
        if (nWorkspaces != 2) {
            throw std::invalid_argument(
                "For PNR analysis, input group must have 2 periods.");
        }
        outWS = execPNR(inWS);
        g_log.notice("PNR polarization correction");
    }
    this->setProperty("OutputWorkspace", outWS);
}
Exemple #12
0
/**
 * Add a workspace to a group. The group and the workspace must be in the ADS.
 * @param groupName :: A group name.
 * @param wsName :: Name of a workspace to add to the group.
 */
void AnalysisDataServiceImpl::addToGroup(const std::string &groupName,
                                         const std::string &wsName) {
  WorkspaceGroup_sptr group = retrieveWS<WorkspaceGroup>(groupName);
  if (!group) {
    throw std::runtime_error("Workspace " + groupName +
                             " is not a workspace group.");
  }
  auto ws = retrieve(wsName);
  group->addWorkspace(ws);
  notificationCenter.postNotification(new GroupUpdatedNotification(groupName));
}
/**
 * Try to add the input workspace to the multiperiod input group list.
 * @param ws: candidate workspace
 * @param vecMultiPeriodWorkspaceGroups: Vector of multi period workspace
 * groups.
 * @param vecWorkspaceGroups: Vector of non-multi period workspace groups.
 */
void MultiPeriodGroupWorker::tryAddInputWorkspaceToInputGroups(
    Workspace_sptr ws,
    MultiPeriodGroupWorker::VecWSGroupType &vecMultiPeriodWorkspaceGroups,
    MultiPeriodGroupWorker::VecWSGroupType &vecWorkspaceGroups) const {
  WorkspaceGroup_sptr inputGroup =
      boost::dynamic_pointer_cast<WorkspaceGroup>(ws);
  if (inputGroup) {
    if (inputGroup->isMultiperiod()) {
      vecMultiPeriodWorkspaceGroups.push_back(inputGroup);
    } else {
      vecWorkspaceGroups.push_back(inputGroup);
    }
  }
}
Exemple #14
0
/**
 * Remove a workspace from a group but not from the ADS.
 *
 * @param groupName :: Name of a workspace group.
 * @param wsName :: Name of a workspace to remove.
 */
void AnalysisDataServiceImpl::removeFromGroup(const std::string &groupName,
                                              const std::string &wsName) {
  WorkspaceGroup_sptr group = retrieveWS<WorkspaceGroup>(groupName);
  if (!group) {
    throw std::runtime_error("Workspace " + groupName +
                             " is not a workspace group.");
  }
  if (!group->contains(wsName)) {
    throw std::runtime_error("WorkspaceGroup " + groupName +
                             " does not containt workspace " + wsName);
  }
  group->removeByADS(wsName);
  notificationCenter.postNotification(new GroupUpdatedNotification(groupName));
}
Exemple #15
0
void IqtFit::updatePlot() {
  if (!m_ffInputWS) {
    g_log.error("No workspace loaded, cannot create preview plot.");
    return;
  }

  int specNo = m_uiForm.spPlotSpectrum->value();

  m_uiForm.ppPlot->clear();
  m_uiForm.ppPlot->addSpectrum("Sample", m_ffInputWS, specNo);

  try {
    const QPair<double, double> curveRange =
        m_uiForm.ppPlot->getCurveRange("Sample");
    const std::pair<double, double> range(curveRange.first, curveRange.second);
    m_uiForm.ppPlot->getRangeSelector("FuryFitRange")
        ->setRange(range.first, range.second);
    m_ffRangeManager->setRange(m_properties["StartX"], range.first,
                               range.second);
    m_ffRangeManager->setRange(m_properties["EndX"], range.first, range.second);

    setDefaultParameters("Exponential1");
    setDefaultParameters("Exponential2");
    setDefaultParameters("StretchedExp");

    m_uiForm.ppPlot->resizeX();
    m_uiForm.ppPlot->setAxisRange(qMakePair(0.0, 1.0), QwtPlot::yLeft);
  } catch (std::invalid_argument &exc) {
    showMessageBox(exc.what());
  }

  // If there is a result plot then plot it
  if (AnalysisDataService::Instance().doesExist(m_pythonExportWsName)) {
    WorkspaceGroup_sptr outputGroup =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            m_pythonExportWsName);
    if (specNo >= static_cast<int>(outputGroup->size()))
      return;
    MatrixWorkspace_sptr ws = boost::dynamic_pointer_cast<MatrixWorkspace>(
        outputGroup->getItem(specNo));
    if (ws) {
      if (m_uiForm.ckPlotGuess->isChecked()) {
        m_uiForm.ppPlot->removeSpectrum("Guess");
      }
      m_uiForm.ppPlot->addSpectrum("Fit", ws, 1, Qt::red);
      m_uiForm.ppPlot->addSpectrum("Diff", ws, 2, Qt::blue);
    }
  }
}
/**
 * Handles completion of the correction algorithm.
 *
 * @param error True of the algorithm failed
 */
void CalculatePaalmanPings::absCorComplete(bool error) {
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(absCorComplete(bool)));

  if (error) {
    emit showMessageBox("Absorption correction calculation failed.\nSee "
                        "Results Log for more details.");
    return;
  }

  // Convert the spectrum axis of correction factors to Q
  const auto sampleWsName =
      m_uiForm.dsSample->getCurrentDataName().toStdString();
  MatrixWorkspace_sptr sampleWs =
      AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(sampleWsName);
  WorkspaceGroup_sptr corrections =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
          m_pythonExportWsName);
  for (size_t i = 0; i < corrections->size(); i++) {
    MatrixWorkspace_sptr factorWs =
        boost::dynamic_pointer_cast<MatrixWorkspace>(corrections->getItem(i));
    if (!factorWs || !sampleWs)
      continue;

    if (getEMode(sampleWs) == "Indirect") {
      API::BatchAlgorithmRunner::AlgorithmRuntimeProps convertSpecProps;
      IAlgorithm_sptr convertSpecAlgo =
          AlgorithmManager::Instance().create("ConvertSpectrumAxis");
      convertSpecAlgo->initialize();
      convertSpecAlgo->setProperty("InputWorkspace", factorWs);
      convertSpecAlgo->setProperty("OutputWorkspace", factorWs->getName());
      convertSpecAlgo->setProperty("Target", "ElasticQ");
      convertSpecAlgo->setProperty("EMode", "Indirect");

      try {
        convertSpecAlgo->setProperty("EFixed", getEFixed(factorWs));
      } catch (std::runtime_error &) {
      }

      m_batchAlgoRunner->addAlgorithm(convertSpecAlgo);
    }
  }

  // Run algorithm queue
  connect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
          SLOT(postProcessComplete(bool)));
  m_batchAlgoRunner->executeBatchAsync();
}
/**
 * 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 #19
0
/**
 * Returns a workspace for the first period as specified using FirstPeriod
 * property.
 * @param group :: Loaded group of workspaces to use
 * @return Workspace for the period
 */
MatrixWorkspace_sptr MuonLoad::getFirstPeriodWS(WorkspaceGroup_sptr group) {
  int firstPeriod = getProperty("FirstPeriod");

  MatrixWorkspace_sptr resultWS;

  if (firstPeriod < 0 || firstPeriod >= static_cast<int>(group->size()))
    throw std::invalid_argument(
        "Workspace doesn't contain specified first period");

  resultWS =
      boost::dynamic_pointer_cast<MatrixWorkspace>(group->getItem(firstPeriod));

  if (!resultWS)
    throw std::invalid_argument(
        "First period workspace is not a MatrixWorkspace");

  return resultWS;
}
Exemple #20
0
/**
* Run instead of exec when operating on groups
*/
bool SaveNXTomo::processGroups() {
  try {
    std::string name = getPropertyValue("InputWorkspaces");
    WorkspaceGroup_sptr groupWS =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(name);

    for (int i = 0; i < groupWS->getNumberOfEntries(); ++i) {
      m_workspaces.push_back(
          boost::dynamic_pointer_cast<Workspace2D>(groupWS->getItem(i)));
    }
  } catch (...) {
  }

  if (m_workspaces.size() != 0)
    processAll();

  return true;
}
/** Extract a spectrum from the Efficiencies workspace as a 1D workspace.
 * @param label :: A label of the spectrum to extract.
 * @return :: A workspace with a single spectrum.
 */
boost::shared_ptr<Mantid::API::MatrixWorkspace>
PolarizationCorrectionFredrikze::getEfficiencyWorkspace(
    const std::string &label) {
  MatrixWorkspace_sptr efficiencies = getProperty(efficienciesLabel);
  auto const &axis = dynamic_cast<TextAxis &>(*efficiencies->getAxis(1));
  size_t index = axis.length();
  for (size_t i = 0; i < axis.length(); ++i) {
    if (axis.label(i) == label) {
      index = i;
      break;
    }
  }

  if (index == axis.length()) {
    // Check if we need to fetch polarization parameters from the instrument's
    // parameters
    static std::map<std::string, std::string> loadableProperties{
        {crhoLabel, "crho"},
        {cppLabel, "cPp"},
        {cApLabel, "cAp"},
        {cAlphaLabel, "calpha"}};
    WorkspaceGroup_sptr inWS = getProperty("InputWorkspace");
    Instrument_const_sptr instrument = fetchInstrument(inWS.get());
    auto vals = instrument->getStringParameter(loadableProperties[label]);
    if (vals.empty()) {
      throw std::invalid_argument("Efficiencey property not found: " + label);
    }
    auto extract = createChildAlgorithm("CreatePolarizationEfficiencies");
    extract->initialize();
    extract->setProperty("InputWorkspace", efficiencies);
    extract->setProperty(label, vals.front());
    extract->execute();
    MatrixWorkspace_sptr outWS = extract->getProperty("OutputWorkspace");
    return outWS;
  } else {
    auto extract = createChildAlgorithm("ExtractSingleSpectrum");
    extract->initialize();
    extract->setProperty("InputWorkspace", efficiencies);
    extract->setProperty("WorkspaceIndex", static_cast<int>(index));
    extract->execute();
    MatrixWorkspace_sptr outWS = extract->getProperty("OutputWorkspace");
    return outWS;
  }
}
MatrixWorkspace_sptr MuonPairingAsymmetry::execGroupWorkspaceInput() {

  // Get the input workspace into a useful form
  Workspace_sptr tmpWS1 = getProperty("InputWorkspace1");
  Workspace_sptr tmpWS2 = getProperty("InputWorkspace2");
  WorkspaceGroup_sptr ws1 = workspaceToWorkspaceGroup(tmpWS1);
  WorkspaceGroup_sptr ws2 = workspaceToWorkspaceGroup(tmpWS2);
  WorkspaceGroup_sptr groupedPeriods = boost::make_shared<WorkspaceGroup>();
  for (int i = 0; i < countPeriods(ws1); i++) {
    groupedPeriods->addWorkspace(
        appendSpectra(getWorkspace(ws1, i), getWorkspace(ws2, i)));
  }

  // Do the asymmetry calculation
  const double alpha = static_cast<double>(getProperty("Alpha"));
  std::vector<int> summedPeriods = getProperty("SummedPeriods");
  std::vector<int> subtractedPeriods = getProperty("SubtractedPeriods");
  return calcPairAsymmetryWithSummedAndSubtractedPeriods(
      summedPeriods, subtractedPeriods, groupedPeriods, alpha);
}
Exemple #23
0
/**
 * Returns a workspace for the second period as specified using SecondPeriod
 * property.
 * @param group :: Loaded group of workspaces to use
 * @return Workspace for the period
 */
MatrixWorkspace_sptr MuonLoad::getSecondPeriodWS(WorkspaceGroup_sptr group) {
  int secondPeriod = getProperty("SecondPeriod");

  MatrixWorkspace_sptr resultWS;

  if (secondPeriod != EMPTY_INT()) {
    if (secondPeriod < 0 || secondPeriod >= static_cast<int>(group->size()))
      throw std::invalid_argument(
          "Workspace doesn't contain specified second period");

    resultWS = boost::dynamic_pointer_cast<MatrixWorkspace>(
        group->getItem(secondPeriod));

    if (!resultWS)
      throw std::invalid_argument(
          "Second period workspace is not a MatrixWorkspace");
  }

  return resultWS;
}
Exemple #24
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();
}
void SmoothNeighboursDialog::inputWorkspaceChanged(const QString& pName)
{
  UNUSED_ARG(pName);

  m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(false);
  m_propertiesWidget->m_groupWidgets[NON_UNIFORM_GROUP]->setVisible(false);

  std::string inWsName = INPUT_WORKSPACE.toStdString();

  // Workspace should have been set by PropertyWidget before emitting valueChanged
  MatrixWorkspace_sptr inWs = this->getAlgorithm()->getProperty(inWsName);

  if(!inWs)
  {
    // Workspace groups are NOT returned by IWP->getWorkspace(), as they are not MatrixWorkspace,
    // so check the ADS for the GroupWorkspace with the same name
    std::string inWsValue = this->getAlgorithm()->getPointerToProperty(inWsName)->value();

    // If it really doesn't exist, don't do anything
    if(!AnalysisDataService::Instance().doesExist(inWsValue))
      return;

    WorkspaceGroup_sptr inGroupWs = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(inWsValue);

    if(inGroupWs)
      // If is a group workspace, use the first workspace to determine the instrument type,
      // as most of the times it will be the same for all the workspaces
      inWs = boost::dynamic_pointer_cast<MatrixWorkspace>(inGroupWs->getItem(0));
    else
      // If is not a GroupWorkspace as well, do nothing
      return;
  }
  Instrument::ContainsState containsRectDetectors = inWs->getInstrument()->containsRectDetectors();

  if(containsRectDetectors == Instrument::ContainsState::Full)
    m_propertiesWidget->m_groupWidgets[RECTANGULAR_GROUP]->setVisible(true);
  else
    m_propertiesWidget->m_groupWidgets[NON_UNIFORM_GROUP]->setVisible(true);
}
Exemple #26
0
/**
 * Updates the preview plot when the algorithm is complete.
 *
 * @param error True if the algorithm was stopped due to error, false otherwise
 */
void ISISDiagnostics::sliceAlgDone(bool error) {
  disconnect(m_batchAlgoRunner, SIGNAL(batchComplete(bool)), this,
             SLOT(sliceAlgDone(bool)));

  if (error)
    return;

  QStringList filenames = m_uiForm.dsInputFiles->getFilenames();
  if (filenames.size() < 1)
    return;

  WorkspaceGroup_sptr sliceOutputGroup =
      AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
          "IndirectDiagnostics_Workspaces");
  if (sliceOutputGroup->size() == 0) {
    g_log.warning("No result workspaces, cannot plot preview.");
    return;
  }

  MatrixWorkspace_sptr sliceWs = boost::dynamic_pointer_cast<MatrixWorkspace>(
      sliceOutputGroup->getItem(0));
  if (!sliceWs) {
    g_log.warning("No result workspaces, cannot plot preview.");
    return;
  }

  // Set workspace for Python export as the first result workspace
  m_pythonExportWsName = sliceWs->getName();

  // Plot result spectrum
  m_uiForm.ppSlicePreview->clear();
  m_uiForm.ppSlicePreview->addSpectrum("Slice", sliceWs, 0);
  m_uiForm.ppSlicePreview->resizeX();

  // Ungroup the output workspace
  sliceOutputGroup->removeAll();
  AnalysisDataService::Instance().remove("IndirectDiagnostics_Workspaces");
}
  /**
   * Updates the preview plot when the algorithm is complete.
   *
   * @param error True if the algorithm was stopped due to error, false otherwise
   */
  void IndirectDiagnostics::sliceAlgDone(bool error)
  {
    if(error)
      return;

    QStringList filenames = m_uiForm.dsInputFiles->getFilenames();
    if(filenames.size() < 1)
      return;

    WorkspaceGroup_sptr sliceOutputGroup = AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>("IndirectDiagnostics_Workspaces");
    if(sliceOutputGroup->size() == 0)
    {
      g_log.warning("No result workspaces, cannot plot preview.");
      return;
    }

    MatrixWorkspace_sptr sliceWs = boost::dynamic_pointer_cast<MatrixWorkspace>(sliceOutputGroup->getItem(0));
    if(!sliceWs)
    {
      g_log.warning("No result workspaces, cannot plot preview.");
      return;
    }

    // Set workspace for Python export as the first result workspace
    m_pythonExportWsName = sliceWs->getName();

    // Plot result spectrum
    plotMiniPlot(sliceWs, 0, "SlicePreviewPlot", "SlicePreviewCurve");

    // Set X range to data range
    setXAxisToCurve("SlicePreviewPlot", "SlicePreviewCurve");
    m_plots["SlicePreviewPlot"]->replot();

    // Ungroup the output workspace
    sliceOutputGroup->removeAll();
    AnalysisDataService::Instance().remove("IndirectDiagnostics_Workspaces");
  }
/**
* Sum transmission workspaces that belong to a workspace group
* @param transGroup : The transmission group containing the transmission runs
* @return :: A workspace pointer containing the sum of transmission workspaces
*/
MatrixWorkspace_sptr ReflectometryReductionOneAuto2::sumTransmissionWorkspaces(
    WorkspaceGroup_sptr &transGroup) {

  const std::string transSum = "trans_sum";
  Workspace_sptr sumWS = transGroup->getItem(0)->clone();

  /// For this step to appear in the history of the output workspaces I need to
  /// set child to false and work with the ADS
  auto plusAlg = createChildAlgorithm("Plus");
  plusAlg->setChild(false);
  plusAlg->initialize();

  for (size_t item = 1; item < transGroup->size(); item++) {
    plusAlg->setProperty("LHSWorkspace", sumWS);
    plusAlg->setProperty("RHSWorkspace", transGroup->getItem(item));
    plusAlg->setProperty("OutputWorkspace", transSum);
    plusAlg->execute();
    sumWS = AnalysisDataService::Instance().retrieve(transSum);
  }
  MatrixWorkspace_sptr result =
      boost::dynamic_pointer_cast<MatrixWorkspace>(sumWS);
  AnalysisDataService::Instance().remove(transSum);
  return result;
}
Exemple #29
0
/**
 * Sets a new preview spectrum for the mini plot.
 *
 * @param value workspace index
 */
void ResNorm::previewSpecChanged(int value) {
  m_previewSpec = value;

  // Update vanadium plot
  if (m_uiForm.dsVanadium->isValid())
    m_uiForm.ppPlot->addSpectrum(
        "Vanadium", m_uiForm.dsVanadium->getCurrentDataName(), m_previewSpec);

  // Update fit plot
  std::string fitWsGroupName(m_pythonExportWsName + "_Fit_Workspaces");
  std::string fitParamsName(m_pythonExportWsName + "_Fit");
  if (AnalysisDataService::Instance().doesExist(fitWsGroupName)) {
    WorkspaceGroup_sptr fitWorkspaces =
        AnalysisDataService::Instance().retrieveWS<WorkspaceGroup>(
            fitWsGroupName);
    ITableWorkspace_sptr fitParams =
        AnalysisDataService::Instance().retrieveWS<ITableWorkspace>(
            fitParamsName);
    if (fitWorkspaces && fitParams) {
      Column_const_sptr scaleFactors = fitParams->getColumn("Scaling");
      std::string fitWsName(fitWorkspaces->getItem(m_previewSpec)->name());
      MatrixWorkspace_const_sptr fitWs =
          AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(
              fitWsName);

      MatrixWorkspace_sptr fit = WorkspaceFactory::Instance().create(fitWs, 1);
      fit->setX(0, fitWs->readX(1));
      fit->getSpectrum(0)->setData(fitWs->readY(1), fitWs->readE(1));

      for (size_t i = 0; i < fit->blocksize(); i++)
        fit->dataY(0)[i] /= scaleFactors->cell<double>(m_previewSpec);

      m_uiForm.ppPlot->addSpectrum("Fit", fit, 0, Qt::red);
    }
  }
}
/**
 * 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));
    }
  }
}