Exemple #1
0
  /** Execute the algorithm.
   */
  void OneStepMDEW::exec()
  {
    std::string tempWsName = getPropertyValue("OutputWorkspace") + "_nxs";

    Algorithm_sptr childAlg;

    // -------- First we load the event nexus file -------------
    childAlg = AlgorithmFactory::Instance().create("LoadEventNexus", 1); // new Mantid::NeXus::LoadEventNexus();
    childAlg->initialize();
    childAlg->setPropertyValue("Filename", getPropertyValue("Filename"));
    childAlg->setPropertyValue("OutputWorkspace", tempWsName);
    childAlg->executeAsSubAlg();

//    Workspace_sptr tempWS = childAlg->getProperty<Workspace>("OutputWorkspace");
//    IEventWorkspace_sptr tempEventWS = boost::dynamic_pointer_cast<IEventWorkspace>(AnalysisDataService::Instance().retrieve(tempWsName));
    //    IEventWorkspace_sptr tempEventWS = boost::dynamic_pointer_cast<IEventWorkspace>(AnalysisDataService::Instance().retrieve(tempWsName));


    // --------- Now Convert -------------------------------
    //childAlg = createSubAlgorithm("ConvertToDiffractionMDWorkspace");
    childAlg = AlgorithmFactory::Instance().create("ConvertToDiffractionMDWorkspace", 1);  // new ConvertToDiffractionMDWorkspace();
    childAlg->initialize();
    childAlg->setPropertyValue("InputWorkspace", tempWsName);
    childAlg->setProperty<bool>("ClearInputWorkspace", false);
    childAlg->setProperty<bool>("LorentzCorrection", true);
    childAlg->setPropertyValue("OutputWorkspace", getPropertyValue("OutputWorkspace"));
    childAlg->executeAsSubAlg();

//    Workspace_sptr tempWS = childAlg->getProperty("OutputWorkspace");
//    IMDEventWorkspace_sptr outWS = boost::dynamic_pointer_cast<IMDEventWorkspace>(tempWS);
    IMDEventWorkspace_sptr outWS = boost::dynamic_pointer_cast<IMDEventWorkspace>(
        AnalysisDataService::Instance().retrieve(getPropertyValue("OutputWorkspace")));

    setProperty<Workspace_sptr>("OutputWorkspace", outWS);
  }
/** 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;
}
/** Add workspace2 to workspace1 by adding spectrum.
  */
MatrixWorkspace_sptr
AlignAndFocusPowder::conjoinWorkspaces(API::MatrixWorkspace_sptr ws1,
                                       API::MatrixWorkspace_sptr ws2,
                                       size_t offset) {
  // Get information from ws1: maximum spectrum number, and store original
  // spectrum Nos
  size_t nspec1 = ws1->getNumberHistograms();
  specnum_t maxspecNo1 = 0;
  std::vector<specnum_t> origspecNos;
  for (size_t i = 0; i < nspec1; ++i) {
    specnum_t tmpspecNo = ws1->getSpectrum(i).getSpectrumNo();
    origspecNos.push_back(tmpspecNo);
    if (tmpspecNo > maxspecNo1)
      maxspecNo1 = tmpspecNo;
  }

  g_log.information() << "[DBx536] Max spectrum number of ws1 = " << maxspecNo1
                      << ", Offset = " << offset << ".\n";

  size_t nspec2 = ws2->getNumberHistograms();

  // Conjoin 2 workspaces
  Algorithm_sptr alg = this->createChildAlgorithm("AppendSpectra");
  alg->initialize();
  ;

  alg->setProperty("InputWorkspace1", ws1);
  alg->setProperty("InputWorkspace2", ws2);
  alg->setProperty("OutputWorkspace", ws1);
  alg->setProperty("ValidateInputs", false);

  alg->executeAsChildAlg();

  API::MatrixWorkspace_sptr outws = alg->getProperty("OutputWorkspace");

  // FIXED : Restore the original spectrum Nos to spectra from ws1
  for (size_t i = 0; i < nspec1; ++i) {
    specnum_t tmpspecNo = outws->getSpectrum(i).getSpectrumNo();
    outws->getSpectrum(i).setSpectrumNo(origspecNos[i]);

    g_log.information() << "[DBx540] Conjoined spectrum " << i
                        << ": restore spectrum number to "
                        << outws->getSpectrum(i).getSpectrumNo()
                        << " from spectrum number = " << tmpspecNo << ".\n";
  }

  // Rename spectrum number
  if (offset >= 1) {
    for (size_t i = 0; i < nspec2; ++i) {
      specnum_t newspecid = maxspecNo1 + static_cast<specnum_t>((i) + offset);
      outws->getSpectrum(nspec1 + i).setSpectrumNo(newspecid);
      // ISpectrum* spec = outws->getSpectrum(nspec1+i);
      // if (spec)
      // spec->setSpectrumNo(3);
    }
  }

  return outws;
}
  void EstimatePDDetectorResolution::retrieveInstrumentParameters()
  {
#if 0
    // Call SolidAngle to get solid angles for all detectors
    Algorithm_sptr calsolidangle = createChildAlgorithm("SolidAngle", -1, -1, true);
    calsolidangle->initialize();

    calsolidangle->setProperty("InputWorkspace", m_inputWS);

    calsolidangle->execute();
    if (!calsolidangle->isExecuted())
      throw runtime_error("Unable to run solid angle. ");

    m_solidangleWS = calsolidangle->getProperty("OutputWorkspace");
    if (!m_solidangleWS)
      throw runtime_error("Unable to get solid angle workspace from SolidAngle(). ");


    size_t numspec = m_solidangleWS->getNumberHistograms();
    for (size_t i = 0; i < numspec; ++i)
      g_log.debug() << "[DB]: " << m_solidangleWS->readY(i)[0] << "\n";
#endif

    // Calculate centre neutron velocity
    Property* cwlproperty = m_inputWS->run().getProperty("LambdaRequest");
    if (!cwlproperty)
      throw runtime_error("Unable to locate property LambdaRequest as central wavelength. ");
    TimeSeriesProperty<double>* cwltimeseries = dynamic_cast<TimeSeriesProperty<double>* >(cwlproperty);
    if (!cwltimeseries)
      throw runtime_error("LambdaReqeust is not a TimeSeriesProperty in double. ");
    if (cwltimeseries->size() != 1)
      throw runtime_error("LambdaRequest should contain 1 and only 1 entry. ");

    double centrewavelength = cwltimeseries->nthValue(0);
    string unit = cwltimeseries->units();
    if (unit.compare("Angstrom") == 0)
      centrewavelength *= 1.0E-10;
    else
      throw runtime_error("Unit is not recognized");

    m_centreVelocity = PhysicalConstants::h/PhysicalConstants::NeutronMass/centrewavelength;
    g_log.notice() << "Centre wavelength = " << centrewavelength << ", Centre neutron velocity = " << m_centreVelocity << "\n";

    // Calcualte L1 sample to source
    Instrument_const_sptr instrument = m_inputWS->getInstrument();
    V3D samplepos = instrument->getSample()->getPos();
    V3D sourcepos = instrument->getSource()->getPos();
    m_L1 = samplepos.distance(sourcepos);
    g_log.notice() << "L1 = " << m_L1 << "\n";

    return;
  }
Exemple #5
0
/// Constructor
AlgorithmProxy::AlgorithmProxy(Algorithm_sptr alg)
    : PropertyManagerOwner(),
      m_executeAsync(new Poco::ActiveMethod<bool, Poco::Void, AlgorithmProxy>(
                         this, &AlgorithmProxy::executeAsyncImpl)),
      m_name(alg->name()), m_category(alg->category()),
      m_categorySeparator(alg->categorySeparator()), m_alias(alg->alias()),
      m_summary(alg->summary()), m_version(alg->version()), m_alg(alg),
      m_isExecuted(), m_isLoggingEnabled(true), m_loggingOffset(0),
      m_isAlgStartupLoggingEnabled(true), m_rethrow(false), m_isChild(false) {
    if (!alg) {
        throw std::logic_error("Unable to create a proxy algorithm.");
    }
    alg->initialize();
    copyPropertiesFrom(*alg);
}
/*
 Executes the underlying algorithm to create the MVP model.
 @param factory : visualisation factory to use.
 @param loadingProgressUpdate : Handler for GUI updates while algorithm
 progresses.
 @param drawingProgressUpdate : Handler for GUI updates while
 vtkDataSetFactory::create occurs.
 */
vtkSmartPointer<vtkDataSet>
EventNexusLoadingPresenter::execute(vtkDataSetFactory *factory,
                                    ProgressAction &loadingProgressUpdate,
                                    ProgressAction &drawingProgressUpdate) {
  using namespace Mantid::API;
  using namespace Mantid::Geometry;

  this->m_view->getLoadInMemory(); // TODO, nexus reader algorithm currently has
                                   // no use of this.

  if (this->shouldLoad()) {
    Poco::NObserver<ProgressAction,
                    Mantid::API::Algorithm::ProgressNotification>
        observer(loadingProgressUpdate, &ProgressAction::handler);
    AnalysisDataService::Instance().remove("MD_EVENT_WS_ID");

    Algorithm_sptr loadAlg =
        AlgorithmManager::Instance().createUnmanaged("LoadEventNexus");
    loadAlg->initialize();
    loadAlg->setChild(true);
    loadAlg->setPropertyValue("Filename", this->m_filename);
    loadAlg->setPropertyValue("OutputWorkspace", "temp_ws");
    loadAlg->addObserver(observer);
    loadAlg->executeAsChildAlg();
    loadAlg->removeObserver(observer);

    Workspace_sptr temp = loadAlg->getProperty("OutputWorkspace");
    IEventWorkspace_sptr tempWS =
        boost::dynamic_pointer_cast<IEventWorkspace>(temp);

    Algorithm_sptr convertAlg = AlgorithmManager::Instance().createUnmanaged(
        "ConvertToDiffractionMDWorkspace", 1);
    convertAlg->initialize();
    convertAlg->setChild(true);
    convertAlg->setProperty("InputWorkspace", tempWS);
    convertAlg->setProperty<bool>("ClearInputWorkspace", false);
    convertAlg->setProperty<bool>("LorentzCorrection", true);
    convertAlg->setPropertyValue("OutputWorkspace", "converted_ws");
    convertAlg->addObserver(observer);
    convertAlg->executeAsChildAlg();
    convertAlg->removeObserver(observer);

    IMDEventWorkspace_sptr outWS = convertAlg->getProperty("OutputWorkspace");
    AnalysisDataService::Instance().addOrReplace("MD_EVENT_WS_ID", outWS);
  }

  Workspace_sptr result =
      AnalysisDataService::Instance().retrieve("MD_EVENT_WS_ID");
  Mantid::API::IMDEventWorkspace_sptr eventWs =
      boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(result);
  m_wsTypeName = eventWs->id();

  factory->setRecursionDepth(this->m_view->getRecursionDepth());
  auto visualDataSet = factory->oneStepCreate(
      eventWs, drawingProgressUpdate); // HACK: progressUpdate should be
                                       // argument for drawing!

  this->extractMetadata(*eventWs);
  this->appendMetadata(visualDataSet, eventWs->getName());

  return visualDataSet;
}
Exemple #7
0
void Load::loadMultipleFiles() {
  // allFilenames contains "rows" of filenames. If the row has more than 1 file
  // in it
  // then that row is to be summed across each file in the row
  const std::vector<std::vector<std::string>> allFilenames =
      getProperty("Filename");
  std::string outputWsName = getProperty("OutputWorkspace");

  std::vector<std::string> wsNames(allFilenames.size());
  std::transform(allFilenames.begin(), allFilenames.end(), wsNames.begin(),
                 generateWsNameFromFileNames);

  auto wsName = wsNames.cbegin();
  assert(allFilenames.size() == wsNames.size());

  std::vector<API::Workspace_sptr> loadedWsList;
  loadedWsList.reserve(allFilenames.size());

  Workspace_sptr tempWs;

  // Cycle through the filenames and wsNames.
  for (auto filenames = allFilenames.cbegin(); filenames != allFilenames.cend();
       ++filenames, ++wsName) {
    auto filename = filenames->cbegin();
    Workspace_sptr sumWS = loadFileToWs(*filename, *wsName);

    ++filename;
    for (; filename != filenames->cend(); ++filename) {
      tempWs = loadFileToWs(*filename, "__@loadsum_temp@");
      sumWS = plusWs(sumWS, tempWs);
    }

    API::WorkspaceGroup_sptr group =
        boost::dynamic_pointer_cast<WorkspaceGroup>(sumWS);
    if (group) {
      std::vector<std::string> childWsNames = group->getNames();
      auto childWsName = childWsNames.begin();
      size_t count = 1;
      for (; childWsName != childWsNames.end(); ++childWsName, ++count) {
        Workspace_sptr childWs = group->getItem(*childWsName);
        const std::string childName =
            group->getName() + "_" + std::to_string(count);
        API::AnalysisDataService::Instance().addOrReplace(childName, childWs);
        // childWs->setName(group->getName() + "_" +
        // boost::lexical_cast<std::string>(count));
      }
    }
    // Add the sum to the list of loaded workspace names.
    loadedWsList.push_back(sumWS);
  }

  // If we only have one loaded ws, set it as the output.
  if (loadedWsList.size() == 1) {
    setProperty("OutputWorkspace", loadedWsList[0]);
    AnalysisDataService::Instance().rename(loadedWsList[0]->getName(),
                                           outputWsName);
  }
  // Else we have multiple loaded workspaces - group them and set the group as
  // output.
  else {
    API::WorkspaceGroup_sptr group = groupWsList(loadedWsList);
    setProperty("OutputWorkspace", group);

    std::vector<std::string> childWsNames = group->getNames();
    size_t count = 1;
    for (auto &childWsName : childWsNames) {
      if (childWsName == outputWsName) {
        Mantid::API::Workspace_sptr child = group->getItem(childWsName);
        // child->setName(child->getName() + "_" +
        // boost::lexical_cast<std::string>(count));
        const std::string childName =
            child->getName() + "_" + std::to_string(count);
        API::AnalysisDataService::Instance().addOrReplace(childName, child);
        count++;
      }
    }

    childWsNames = group->getNames();
    count = 1;
    for (auto &childWsName : childWsNames) {
      Workspace_sptr childWs = group->getItem(childWsName);
      std::string outWsPropName = "OutputWorkspace_" + std::to_string(count);
      ++count;
      declareProperty(Kernel::make_unique<WorkspaceProperty<Workspace>>(
          outWsPropName, childWsName, Direction::Output));
      setProperty(outWsPropName, childWs);
    }
  }

  // Clean up.
  if (tempWs) {
    Algorithm_sptr alg =
        AlgorithmManager::Instance().createUnmanaged("DeleteWorkspace");
    alg->initialize();
    alg->setChild(true);
    alg->setProperty("Workspace", tempWs);
    alg->execute();
  }
}