コード例 #1
0
 /** Makes a workspace with the total solid angle all the detectors in each spectrum cover from the sample
  *  note returns an empty shared pointer on failure, uses the SolidAngle algorithm
  * @param firstSpec :: the index number of the first histogram to analyse
  * @param lastSpec :: the index number of the last histogram to analyse
  * @return A pointer to the workspace (or an empty pointer)
  */
 API::MatrixWorkspace_sptr MedianDetectorTest::getSolidAngles(int firstSpec, int lastSpec )
 {
   g_log.debug("Calculating solid angles");
   // get percentage completed estimates for now, t0 and when we've finished t1
   double t0 = m_fracDone, t1 = advanceProgress(RTGetSolidAngle);
   IAlgorithm_sptr childAlg = createChildAlgorithm("SolidAngle", t0, t1, true);
   childAlg->setProperty( "InputWorkspace", m_inputWS);
   childAlg->setProperty( "StartWorkspaceIndex", firstSpec );
   childAlg->setProperty( "EndWorkspaceIndex", lastSpec );
   try
   {
     // Execute the Child Algorithm, it could throw a runtime_error at this point which would abort execution
     childAlg->execute();
     if ( ! childAlg->isExecuted() )
     {
       throw std::runtime_error("Unexpected problem calculating solid angles");
     }
   }
   //catch all exceptions because the solid angle calculation is optional
   catch(std::exception&)
   {
     g_log.warning(
         "Precision warning:  Can't find detector geometry " + name() +
         " will continue with the solid angles of all spectra set to the same value" );
     failProgress(RTGetSolidAngle);
     //The return is an empty workspace pointer, which must be handled by the calling function
     MatrixWorkspace_sptr empty;
     //function returns normally
     return empty;
   }
   return childAlg->getProperty("OutputWorkspace");
 }
コード例 #2
0
void LoadNexus::runLoadTOFRawNexus() {
  IAlgorithm_sptr loadNexusPro =
      createChildAlgorithm("LoadTOFRawNexus", 0., 1.);
  // Pass through the same input filename
  loadNexusPro->setPropertyValue("Filename", m_filename);
  // Set the workspace property
  std::string outputWorkspace = "OutputWorkspace";
  loadNexusPro->setPropertyValue(outputWorkspace, m_workspace);
  // Get the array passed in the spectrum_list, if an empty array was passed use
  // the default
  std::vector<int> specList = getProperty("SpectrumList");
  if (!specList.empty())
    loadNexusPro->setPropertyValue("SpectrumList",
                                   getPropertyValue("SpectrumList"));
  //
  int specMax = getProperty("SpectrumMax");
  if (specMax != Mantid::EMPTY_INT()) {
    loadNexusPro->setPropertyValue("SpectrumMax",
                                   getPropertyValue("SpectrumMax"));
    loadNexusPro->setPropertyValue("SpectrumMin",
                                   getPropertyValue("SpectrumMin"));
  }

  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  try {
    loadNexusPro->execute();
  } catch (std::runtime_error &) {
    g_log.error("Unable to successfully run LoadTOFRawNexus Child Algorithm");
  }
  if (!loadNexusPro->isExecuted())
    g_log.error("Unable to successfully run LoadTOFRawNexus Child Algorithm");

  setOutputWorkspace(loadNexusPro);
}
コード例 #3
0
/** Set goniometer to matrix workspace and get its rotation matrix R (from
 * Q-sample to Q-lab
 * and output 1/R
 * @brief ConvertCWSDExpToMomentum::setupTransferMatrix
 * @param dataws :: matrix workspace containing sample rotation angles
 * @param rotationMatrix :: output as matrix 1/R to convert from Q-lab to
 * Q-sample
 */
void ConvertCWSDExpToMomentum::setupTransferMatrix(
    API::MatrixWorkspace_sptr dataws, Kernel::DblMatrix &rotationMatrix) {
  // Check sample logs
  if (!dataws->run().hasProperty("_omega") ||
      !dataws->run().hasProperty("_chi") || !dataws->run().hasProperty("_phi"))
    throw std::runtime_error(
        "Data workspace does not have sample log _phi, _chi or _omega. "
        "Unable to set goniometer and calcualte roation matrix R.");

  // Call algorithm SetGoniometer
  IAlgorithm_sptr setalg = createChildAlgorithm("SetGoniometer");
  setalg->initialize();
  setalg->setProperty("Workspace", dataws);
  setalg->setProperty("Axis0", "_omega,0,1,0,-1");
  setalg->setProperty("Axis1", "_chi,0,0,1,-1");
  setalg->setProperty("Axis2", "_phi,0,1,0,-1");
  setalg->execute();

  if (setalg->isExecuted()) {
    rotationMatrix = dataws->run().getGoniometer().getR();
    g_log.debug() << "Ratation matrix: " << rotationMatrix.str() << "\n";
    rotationMatrix.Invert();
    g_log.debug() << "Ratation matrix: " << rotationMatrix.str() << "\n";
  } else
    throw std::runtime_error("Unable to set Goniometer.");

  return;
}
コード例 #4
0
  /**
   * 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();
  }
コード例 #5
0
ファイル: SaveNexus.cpp プロジェクト: mducle/mantid
void SaveNexus::runSaveNexusProcessed() {
  IAlgorithm_sptr saveNexusPro =
      createChildAlgorithm("SaveNexusProcessed", 0.0, 1.0, true);
  // Pass through the same output filename
  saveNexusPro->setPropertyValue("Filename", m_filename);
  // Set the workspace property
  std::string inputWorkspace = "InputWorkspace";
  saveNexusPro->setProperty(inputWorkspace, m_inputWorkspace);
  //
  std::vector<int> specList = getProperty("WorkspaceIndexList");
  if (!specList.empty())
    saveNexusPro->setPropertyValue("WorkspaceIndexList",
                                   getPropertyValue("WorkspaceIndexList"));
  //
  int specMax = getProperty("WorkspaceIndexMax");
  if (specMax != Mantid::EMPTY_INT()) {
    saveNexusPro->setPropertyValue("WorkspaceIndexMax",
                                   getPropertyValue("WorkspaceIndexMax"));
    saveNexusPro->setPropertyValue("WorkspaceIndexMin",
                                   getPropertyValue("WorkspaceIndexMin"));
  }
  std::string title = getProperty("Title");
  if (!title.empty())
    saveNexusPro->setPropertyValue("Title", getPropertyValue("Title"));

  // Pass through the append property
  saveNexusPro->setProperty<bool>("Append", getProperty("Append"));

  // If we're tracking history, add the entry before we save it to file
  if (trackingHistory()) {
    m_history->fillAlgorithmHistory(
        this, Mantid::Kernel::DateAndTime::getCurrentTime(), 0,
        Algorithm::g_execCount);
    if (!isChild()) {
      m_inputWorkspace->history().addHistory(m_history);
    }
    // this is a child algorithm, but we still want to keep the history.
    else if (isRecordingHistoryForChild() && m_parentHistory) {
      m_parentHistory->addChildHistory(m_history);
    }
  }
  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  try {
    saveNexusPro->execute();
  } catch (std::runtime_error &) {
    g_log.error(
        "Unable to successfully run SaveNexusprocessed Child Algorithm");
  }
  if (!saveNexusPro->isExecuted())
    g_log.error(
        "Unable to successfully run SaveNexusProcessed Child Algorithm");
  //
  progress(1);
}
コード例 #6
0
/** Set up grouping workspace
  */
void LoadVulcanCalFile::setupGroupingWorkspace() {
  // Get the right group option for CreateGroupingWorkspace
  string groupdetby = "";
  switch (m_groupingType) {
  case VULCAN_OFFSET_BANK:
    groupdetby = "bank";
    break;

  case VULCAN_OFFSET_MODULE:
    groupdetby = "Group";
    break;

  case VULCAN_OFFSET_STACK:
    groupdetby = "All";
    break;

  default:
    throw runtime_error("Grouping type is not supported. ");
    break;
  }

  // Calling algorithm CreateGroupingWorkspace
  IAlgorithm_sptr creategroupws =
      createChildAlgorithm("CreateGroupingWorkspace", -1, -1, true);
  creategroupws->initialize();

  creategroupws->setProperty("InstrumentName", "VULCAN");
  creategroupws->setProperty("GroupDetectorsBy", groupdetby);

  creategroupws->execute();
  if (!creategroupws->isExecuted())
    throw runtime_error("Unable to create grouping workspace.");

  m_groupWS = creategroupws->getProperty("OutputWorkspace");

  // Set title
  m_groupWS->setTitle(groupdetby);

  // Output
  string WorkspaceName = getPropertyValue("WorkspaceName");
  declareProperty(new WorkspaceProperty<GroupingWorkspace>(
                      "OutputGroupingWorkspace", WorkspaceName + "_group",
                      Direction::Output),
                  "Set the output GroupingWorkspace. ");
  m_groupWS->mutableRun().addProperty("Filename", m_offsetFilename);
  setProperty("OutputGroupingWorkspace", m_groupWS);

  return;
}
コード例 #7
0
void LoadNexus::runLoadNexusProcessed() {
  IAlgorithm_sptr loadNexusPro =
      createChildAlgorithm("LoadNexusProcessed", 0., 1.);
  // Pass through the same input filename
  loadNexusPro->setPropertyValue("Filename", m_filename);
  // Set the workspace property
  loadNexusPro->setPropertyValue("OutputWorkspace", m_workspace);

  loadNexusPro->setPropertyValue("SpectrumMin",
                                 getPropertyValue("SpectrumMin"));
  loadNexusPro->setPropertyValue("SpectrumMax",
                                 getPropertyValue("SpectrumMax"));
  loadNexusPro->setPropertyValue("SpectrumList",
                                 getPropertyValue("SpectrumList"));

  /* !!! The spectrum min/max/list properties are currently missing from
     LoadNexus
         so don't pass them through here, just print a warning !!! */

  // Get the array passed in the spectrum_list, if an empty array was passed use
  // the default
  // std::vector<int> specList = getProperty("SpectrumList");
  // if ( !specList.empty() )
  //{
  //  g_log.warning("SpectrumList property ignored - it is not implemented in
  //  LoadNexusProcessed.");
  //  //loadNexusPro->setProperty("SpectrumList",specList);
  //}
  // int specMin = getProperty("SpectrumMin");
  // int specMax = getProperty("SpectrumMax");
  // if ( specMax != Mantid::EMPTY_INT() || specMin != 0 )
  //{
  //  g_log.warning("SpectrumMin/Max properties ignored - they are not
  //  implemented in LoadNexusProcessed.");
  //  //loadNexusPro->setProperty("SpectrumMax",specMin);
  //  //loadNexusPro->setProperty("SpectrumMin",specMax);
  //}

  loadNexusPro->setPropertyValue("EntryNumber",
                                 getPropertyValue("EntryNumber"));
  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  loadNexusPro->execute();
  if (!loadNexusPro->isExecuted())
    g_log.error(
        "Unable to successfully run LoadNexusProcessed Child Algorithm");

  setOutputWorkspace(loadNexusPro);
}
コード例 #8
0
ファイル: LoadMuonNexus1.cpp プロジェクト: mducle/mantid
/// Run the LoadLog Child Algorithm
void LoadMuonNexus1::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) {
  IAlgorithm_sptr loadLog = createChildAlgorithm("LoadMuonLog");
  // Pass through the same input filename
  loadLog->setPropertyValue("Filename", m_filename);
  // Set the workspace property to be the same one filled above
  loadLog->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace);

  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  try {
    loadLog->execute();
  } catch (std::runtime_error &) {
    g_log.error("Unable to successfully run LoadMuonLog Child Algorithm");
  } catch (std::logic_error &) {
    g_log.error("Unable to successfully run LoadMuonLog Child Algorithm");
  }

  if (!loadLog->isExecuted())
    g_log.error("Unable to successfully run LoadMuonLog Child Algorithm");

  NXRoot root(m_filename);

  // Get main field direction
  std::string mainFieldDirection = "Longitudinal"; // default
  try {
    NXChar orientation = root.openNXChar("run/instrument/detector/orientation");
    // some files have no data there
    orientation.load();

    if (orientation[0] == 't') {
      auto p =
          Kernel::make_unique<Kernel::TimeSeriesProperty<double>>("fromNexus");
      std::string start_time = root.getString("run/start_time");
      p->addValue(start_time, -90.0);
      localWorkspace->mutableRun().addLogData(std::move(p));
      mainFieldDirection = "Transverse";
    }
  } catch (...) {
    // no data - assume main field was longitudinal
  }

  // set output property and add to workspace logs
  auto &run = localWorkspace->mutableRun();
  setProperty("MainFieldDirection", mainFieldDirection);
  run.addProperty("main_field_direction", mainFieldDirection);

  ISISRunLogs runLogs(run);
  runLogs.addStatusLog(run);
}
コード例 #9
0
    /**
    Process a row
    @param rowNo : The row in the model to process
    @throws std::runtime_error if processing fails
    */
    void ReflMainViewPresenter::processRow(size_t rowNo)
    {
      const std::string         run = m_model->String(rowNo, COL_RUNS);
      const std::string    transStr = m_model->String(rowNo, COL_TRANSMISSION);
      const std::string transWSName = makeTransWSName(transStr);

      double theta = 0;

      const bool thetaGiven = !m_model->String(rowNo, COL_ANGLE).empty();

      if(thetaGiven)
        Mantid::Kernel::Strings::convert<double>(m_model->String(rowNo, COL_ANGLE), theta);

      Workspace_sptr runWS = fetchRun(run, m_view->getProcessInstrument());

      //If the transmission workspace already exists, re-use it.
      MatrixWorkspace_sptr transWS;
      if(AnalysisDataService::Instance().doesExist(transWSName))
        transWS = AnalysisDataService::Instance().retrieveWS<MatrixWorkspace>(transWSName);
      else
        transWS = makeTransWS(transStr);

      IAlgorithm_sptr algReflOne = AlgorithmManager::Instance().create("ReflectometryReductionOneAuto");
      algReflOne->initialize();
      algReflOne->setChild(true);
      algReflOne->setProperty("InputWorkspace", runWS);
      algReflOne->setProperty("FirstTransmissionRun", transWS);
      algReflOne->setProperty("OutputWorkspace", run + "_IvsQ");
      algReflOne->setProperty("OutputWorkspaceWaveLength", run + "_IvsLam");
      algReflOne->setProperty("ThetaIn", theta);
      algReflOne->execute();

      if(!algReflOne->isExecuted())
        throw std::runtime_error("Failed to run ReflectometryReductionOneAuto.");

      MatrixWorkspace_sptr runWSQ = algReflOne->getProperty("OutputWorkspace");
      MatrixWorkspace_sptr runWSLam = algReflOne->getProperty("OutputWorkspaceWaveLength");

      //Finally, place the resulting workspaces into the ADS.
      AnalysisDataService::Instance().addOrReplace(run + "_TOF", runWS);

      AnalysisDataService::Instance().addOrReplace(run + "_IvsQ", runWSQ);
      AnalysisDataService::Instance().addOrReplace(run + "_IvsLam", runWSLam);

      AnalysisDataService::Instance().addOrReplace(transWSName, transWS);
    }
コード例 #10
0
ファイル: LoadMuonNexus1.cpp プロジェクト: nimgould/mantid
/// Run the LoadLog Child Algorithm
void LoadMuonNexus1::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace) {
  IAlgorithm_sptr loadLog = createChildAlgorithm("LoadMuonLog");
  // Pass through the same input filename
  loadLog->setPropertyValue("Filename", m_filename);
  // Set the workspace property to be the same one filled above
  loadLog->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace);

  // Now execute the Child Algorithm. Catch and log any error, but don't stop.
  try {
    loadLog->execute();
  } catch (std::runtime_error &) {
    g_log.error("Unable to successfully run LoadLog Child Algorithm");
  } catch (std::logic_error &) {
    g_log.error("Unable to successfully run LoadLog Child Algorithm");
  }

  if (!loadLog->isExecuted())
    g_log.error("Unable to successfully run LoadLog Child Algorithm");

  NXRoot root(m_filename);

  try {
    NXChar orientation = root.openNXChar("run/instrument/detector/orientation");
    // some files have no data there
    orientation.load();

    if (orientation[0] == 't') {
      Kernel::TimeSeriesProperty<double> *p =
          new Kernel::TimeSeriesProperty<double>("fromNexus");
      std::string start_time = root.getString("run/start_time");
      p->addValue(start_time, -90.0);
      localWorkspace->mutableRun().addLogData(p);
      setProperty("MainFieldDirection", "Transverse");
    } else {
      setProperty("MainFieldDirection", "Longitudinal");
    }
  } catch (...) {
    setProperty("MainFieldDirection", "Longitudinal");
  }

  auto &run = localWorkspace->mutableRun();
  int n = static_cast<int>(m_numberOfPeriods);
  ISISRunLogs runLogs(run, n);
  runLogs.addStatusLog(run);
}
コード例 #11
0
ファイル: LoadRaw.cpp プロジェクト: trnielsen/mantid
    /// Run LoadInstrumentFromRaw as a Child Algorithm (only if loading from instrument definition file fails)
    void LoadRaw::runLoadInstrumentFromRaw(DataObjects::Workspace2D_sptr localWorkspace)
    {
      IAlgorithm_sptr loadInst = createChildAlgorithm("LoadInstrumentFromRaw");
      loadInst->setPropertyValue("Filename", m_filename);
      // Set the workspace property to be the same one filled above
      loadInst->setProperty<MatrixWorkspace_sptr>("Workspace",localWorkspace);

      // Now execute the Child Algorithm. Catch and log any error, but don't stop.
      try
      {
        loadInst->execute();
      }
      catch (std::runtime_error&)
      {
        g_log.error("Unable to successfully run LoadInstrumentFromRaw Child Algorithm");
      }

      if ( ! loadInst->isExecuted() ) g_log.error("No instrument definition loaded");
    }
コード例 #12
0
ファイル: LoadRaw.cpp プロジェクト: trnielsen/mantid
    /// Run the LoadLog Child Algorithm
    void LoadRaw::runLoadLog(DataObjects::Workspace2D_sptr localWorkspace)
    {
      IAlgorithm_sptr loadLog = createChildAlgorithm("LoadLog");
      // Pass through the same input filename
      loadLog->setPropertyValue("Filename",m_filename);
      // Set the workspace property to be the same one filled above
      loadLog->setProperty<MatrixWorkspace_sptr>("Workspace",localWorkspace);

      // Now execute the Child Algorithm. Catch and log any error, but don't stop.
      try
      {
        loadLog->execute();
      }
      catch (std::runtime_error&)
      {
        g_log.error("Unable to successfully run LoadLog Child Algorithm");
      }

      if ( ! loadLog->isExecuted() ) g_log.error("Unable to successfully run LoadLog Child Algorithm");
    }
コード例 #13
0
ファイル: LoadLiveData.cpp プロジェクト: dezed/mantid
/**
 * Add a matrix workspace to the accumulation workspace.
 *
 * @param algoName :: Name of algorithm which will be adding the workspaces.
 * @param accumWS :: accumulation matrix workspace
 * @param chunkWS :: processed live data chunk matrix workspace
 */
void LoadLiveData::addMatrixWSChunk(const std::string &algoName,
                                    Workspace_sptr accumWS,
                                    Workspace_sptr chunkWS) {
  // Handle the addition of the internal monitor workspace, if present
  auto accumMW = boost::dynamic_pointer_cast<MatrixWorkspace>(accumWS);
  auto chunkMW = boost::dynamic_pointer_cast<MatrixWorkspace>(chunkWS);
  if (accumMW && chunkMW) {
    auto accumMon = accumMW->monitorWorkspace();
    auto chunkMon = chunkMW->monitorWorkspace();

    if (accumMon && chunkMon)
      accumMon += chunkMon;
  }

  // Now do the main workspace
  IAlgorithm_sptr alg = this->createChildAlgorithm(algoName);
  alg->setProperty("LHSWorkspace", accumWS);
  alg->setProperty("RHSWorkspace", chunkWS);
  alg->setProperty("OutputWorkspace", accumWS);
  alg->execute();
  if (!alg->isExecuted()) {
    throw std::runtime_error("Error when calling " + alg->name() +
                             " to add the chunk of live data. See log.");
  } else {
    // Get the output as the generic Workspace type
    // This step is necessary for when we are operating on MD workspaces
    // (PlusMD)
    Property *prop = alg->getProperty("OutputWorkspace");
    IWorkspaceProperty *wsProp = dynamic_cast<IWorkspaceProperty *>(prop);
    if (!wsProp)
      throw std::runtime_error(
          "The " + alg->name() +
          " Algorithm's OutputWorkspace property is not a WorkspaceProperty!");
    Workspace_sptr temp = wsProp->getWorkspace();
    accumWS = temp;
    // And sort the events, if any
    doSortEvents(accumWS);
  }
}
コード例 #14
0
    /**
    Create a transmission workspace
    @param transString : the numbers of the transmission runs to use
    */
    MatrixWorkspace_sptr ReflMainViewPresenter::makeTransWS(const std::string& transString)
    {
      const size_t maxTransWS = 2;

      std::vector<std::string> transVec;
      std::vector<Workspace_sptr> transWSVec;

      //Take the first two run numbers
      boost::split(transVec, transString, boost::is_any_of(","));
      if(transVec.size() > maxTransWS)
        transVec.resize(maxTransWS);

      if(transVec.size() == 0)
        throw std::runtime_error("Failed to parse the transmission run list.");

      for(auto it = transVec.begin(); it != transVec.end(); ++it)
        transWSVec.push_back(fetchRun(*it, m_view->getProcessInstrument()));

      //We have the runs, so we can create a TransWS
      IAlgorithm_sptr algCreateTrans = AlgorithmManager::Instance().create("CreateTransmissionWorkspaceAuto");
      algCreateTrans->initialize();
      algCreateTrans->setChild(true);
      algCreateTrans->setProperty("FirstTransmissionRun", boost::dynamic_pointer_cast<MatrixWorkspace>(transWSVec[0]));
      if(transWSVec.size() > 1)
        algCreateTrans->setProperty("SecondTransmissionRun", boost::dynamic_pointer_cast<MatrixWorkspace>(transWSVec[1]));

      algCreateTrans->setProperty("OutputWorkspace", makeTransWSName(transString));

      if(!algCreateTrans->isInitialized())
        throw std::runtime_error("Could not initialize CreateTransmissionWorkspaceAuto");

      algCreateTrans->execute();

      if(!algCreateTrans->isExecuted())
        throw std::runtime_error("CreateTransmissionWorkspaceAuto failed to execute");

      return algCreateTrans->getProperty("OutputWorkspace");
    }
コード例 #15
0
ファイル: LoadLiveData.cpp プロジェクト: rosswhitfield/mantid
/** Accumulate the data by appending the spectra into the
 * the output workspace.
 * Calls AppendSpectra algorithm.
 *
 * @param accumWS :: accumulation matrix workspace
 * @param chunkWS :: processed live data chunk matrix workspace
 */
Workspace_sptr LoadLiveData::appendMatrixWSChunk(Workspace_sptr accumWS,
                                                 Workspace_sptr chunkWS) {
  IAlgorithm_sptr alg;
  ReadLock _lock1(*accumWS);
  ReadLock _lock2(*chunkWS);

  alg = this->createChildAlgorithm("AppendSpectra");
  alg->setProperty("InputWorkspace1", accumWS);
  alg->setProperty("InputWorkspace2", chunkWS);
  alg->setProperty("ValidateInputs", false);
  alg->setProperty("MergeLogs", true);
  alg->execute();
  if (!alg->isExecuted()) {
    throw std::runtime_error("Error when calling AppendSpectra to append the "
                             "spectra of the chunk of live data. See log.");
  }

  MatrixWorkspace_sptr temp = alg->getProperty("OutputWorkspace");
  accumWS = temp;
  // And sort the events, if any
  doSortEvents(accumWS);
  return accumWS;
}
コード例 #16
0
    /**
    Fetches a run from disk or the AnalysisDataService
    @param run : The name of the run
    @param instrument : The instrument the run belongs to
    @throws std::runtime_error if the run cannot be found
    @returns a shared pointer to the workspace
    */
    Workspace_sptr ReflMainViewPresenter::fetchRun(const std::string& run, const std::string& instrument = "")
    {
      const std::string wsName = run + "_TOF";

      //First, let's see if the run given is the name of a workspace in the ADS
      if(AnalysisDataService::Instance().doesExist(wsName))
        return AnalysisDataService::Instance().retrieveWS<Workspace>(wsName);

      const std::string filename = instrument + run;

      //We'll just have to load it ourselves
      IAlgorithm_sptr algLoadRun = AlgorithmManager::Instance().create("Load");
      algLoadRun->initialize();
      algLoadRun->setChild(true);
      algLoadRun->setProperty("Filename", filename);
      algLoadRun->setProperty("OutputWorkspace", wsName);
      algLoadRun->execute();

      if(!algLoadRun->isExecuted())
        throw std::runtime_error("Could not open " + filename);

      return algLoadRun->getProperty("OutputWorkspace");
    }
コード例 #17
0
int main( int argc, char** argv )
{
    std::cout << "Start of ImageViewNxEventFile..." << std::endl;
    if ( argc < 2 )
    {
        std::cout << "Please enter a NeXus event file name on the command line!"
                  << std::endl;
        return 0;
    }
    std::string file_name(argv[1]);

    QApplication a( argc, argv );

    Mantid::API::FrameworkManager::Instance();
    IAlgorithm_sptr ld = AlgorithmManager::Instance().createUnmanaged("LoadEventNexus");
    ld->initialize();

    ld->setPropertyValue("Filename", file_name );
    std::string outws_name = "EventWS";
    ld->setPropertyValue("OutputWorkspace",outws_name);
    ld->setPropertyValue("Precount", "0");

    std::cout << "Loading file: " << file_name << std::endl;
    ld->execute();
    ld->isExecuted();

    std::cout << "File Loaded, getting workspace. " << std::endl;

    IEventWorkspace_sptr WS;
    WS = AnalysisDataService::Instance().retrieveWS<IEventWorkspace>(outws_name);

    std::cout << "Got EventWorkspace, making EventWSDataSource..." << std::endl;

    MantidQt::ImageView::MatrixWSImageView image_view( WS );

    return a.exec();
}
コード例 #18
0
/**
 * Determine the instrument from the various input parameters.
 *
 * @return The correct instrument.
 */
Instrument_const_sptr CreateChunkingFromInstrument::getInstrument() {
  // try the input workspace
  MatrixWorkspace_sptr inWS = getProperty(PARAM_IN_WKSP);
  if (inWS) {
    return inWS->getInstrument();
  }

  // temporary workspace to hang everything else off of
  MatrixWorkspace_sptr tempWS(new Workspace2D());
  // name of the instrument
  string instName = getPropertyValue(PARAM_INST_NAME);

  // see if there is an input file
  string filename = getPropertyValue(PARAM_IN_FILE);
  if (!filename.empty()) {
    string top_entry_name("entry"); // TODO make more flexible

    // get the instrument name from the filename
    size_t n = filename.rfind('/');
    if (n != std::string::npos) {
      std::string temp = filename.substr(n + 1, filename.size() - n - 1);
      n = temp.find('_');
      if (n != std::string::npos && n > 0) {
        instName = temp.substr(0, n);
      }
    }

    // read information from the nexus file itself
    try {
      NeXus::File nxsfile(filename);

      // get the run start time
      string start_time;
      nxsfile.openGroup(top_entry_name, "NXentry");
      nxsfile.readData("start_time", start_time);
      tempWS->mutableRun().addProperty(
          "run_start", DateAndTime(start_time).toISO8601String(), true);

      // get the instrument name
      nxsfile.openGroup("instrument", "NXinstrument");
      nxsfile.readData("name", instName);
      nxsfile.closeGroup();

      // Test if IDF exists in file, move on quickly if not
      nxsfile.openPath("instrument/instrument_xml");
      nxsfile.close();
      IAlgorithm_sptr loadInst =
          createChildAlgorithm("LoadIDFFromNexus", 0.0, 0.2);
      // Now execute the Child Algorithm. Catch and log any error, but don't
      // stop.
      try {
        loadInst->setPropertyValue("Filename", filename);
        loadInst->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
        loadInst->setPropertyValue("InstrumentParentPath", top_entry_name);
        loadInst->execute();
      } catch (std::invalid_argument &) {
        g_log.error("Invalid argument to LoadIDFFromNexus Child Algorithm ");
      } catch (std::runtime_error &) {
        g_log.debug("No instrument definition found in " + filename + " at " +
                    top_entry_name + "/instrument");
      }

      if (loadInst->isExecuted())
        return tempWS->getInstrument();
      else
        g_log.information("No IDF loaded from Nexus file.");

    } catch (::NeXus::Exception &) {
      g_log.information("No instrument definition found in " + filename +
                        " at " + top_entry_name + "/instrument");
    }
  }

  // run LoadInstrument if other methods have not run
  string instFilename = getPropertyValue(PARAM_INST_FILE);

  Algorithm_sptr childAlg = createChildAlgorithm("LoadInstrument", 0.0, 0.2);
  childAlg->setProperty<MatrixWorkspace_sptr>("Workspace", tempWS);
  childAlg->setPropertyValue("Filename", instFilename);
  childAlg->setPropertyValue("InstrumentName", instName);
  childAlg->executeAsChildAlg();
  return tempWS->getInstrument();
}
コード例 #19
0
/** Rebin and scale a workspace in Q.
*
* @param inputWS :: the workspace in Q
* @param theta :: the angle of this run
* @param params :: [output] rebin parameters
* @return :: the output workspace
*/
MatrixWorkspace_sptr
ReflectometryReductionOneAuto2::rebinAndScale(MatrixWorkspace_sptr inputWS,
                                              const double theta,
                                              std::vector<double> &params) {

  Property *qStepProp = getProperty("MomentumTransferStep");
  double qstep;
  if (!qStepProp->isDefault()) {
    qstep = getProperty("MomentumTransferStep");
    qstep = -qstep;
  } else {
    if (theta == 0.0) {
      throw std::runtime_error(
          "Theta determined from the detector positions is "
          "0.0. Please provide a value for theta manually "
          "or correct the detector position before running "
          "this algorithm.");
    }

    IAlgorithm_sptr calcRes = createChildAlgorithm("NRCalculateSlitResolution");
    calcRes->setProperty("Workspace", inputWS);
    calcRes->setProperty("TwoTheta", 2 * theta);
    calcRes->execute();

    if (!calcRes->isExecuted()) {
      g_log.error(
          "NRCalculateSlitResolution failed. Workspace in Q will not be "
          "rebinned. Please provide dQ/Q.");
      return inputWS;
    }
    qstep = calcRes->getProperty("Resolution");
    qstep = -qstep;
  }

  Property *qMin = getProperty("MomentumTransferMin");
  Property *qMax = getProperty("MomentumTransferMax");
  if (!qMin->isDefault() && !qMax->isDefault()) {
    double qmin = getProperty("MomentumTransferMin");
    double qmax = getProperty("MomentumTransferMax");
    params.push_back(qmin);
    params.push_back(qstep);
    params.push_back(qmax);
  } else {
    params.push_back(qstep);
  }

  // Rebin
  IAlgorithm_sptr algRebin = createChildAlgorithm("Rebin");
  algRebin->initialize();
  algRebin->setProperty("InputWorkspace", inputWS);
  algRebin->setProperty("OutputWorkspace", inputWS);
  algRebin->setProperty("Params", params);
  algRebin->execute();
  MatrixWorkspace_sptr IvsQ = algRebin->getProperty("OutputWorkspace");

  // Scale (optional)
  Property *scaleProp = getProperty("ScaleFactor");
  if (!scaleProp->isDefault()) {
    double scaleFactor = getProperty("ScaleFactor");
    IAlgorithm_sptr algScale = createChildAlgorithm("Scale");
    algScale->initialize();
    algScale->setProperty("InputWorkspace", IvsQ);
    algScale->setProperty("OutputWorkspace", IvsQ);
    algScale->setProperty("Factor", 1.0 / scaleFactor);
    algScale->execute();
    IvsQ = algScale->getProperty("OutputWorkspace");
  }

  return IvsQ;
}
コード例 #20
0
    /**
    Stitches the workspaces created by the given rows together.
    @param rows : the list of rows
    */
    void ReflMainViewPresenter::stitchRows(std::vector<size_t> rows)
    {
      //If we can get away with doing nothing, do.
      if(rows.size() < 2)
        return;

      //Ensure the rows are in order.
      std::sort(rows.begin(), rows.end());

      //Properties for Stitch1DMany
      std::vector<std::string> wsNames;
      std::vector<std::string> runs;

      std::vector<double> params;
      std::vector<double> startOverlaps;
      std::vector<double> endOverlaps;

      //Go through each row and prepare the properties
      for(auto rowIt = rows.begin(); rowIt != rows.end(); ++rowIt)
      {
        const std::string  runStr = m_model->String(*rowIt, COL_RUNS);
        const std::string qMinStr = m_model->String(*rowIt, COL_QMIN);
        const std::string qMaxStr = m_model->String(*rowIt, COL_QMAX);

        double qmin, qmax;
        Mantid::Kernel::Strings::convert<double>(qMinStr, qmin);
        Mantid::Kernel::Strings::convert<double>(qMaxStr, qmax);

        runs.push_back(runStr);
        wsNames.push_back(runStr + "_IvsQ");
        startOverlaps.push_back(qmin);
        endOverlaps.push_back(qmax);
      }

      double dqq;
      std::string dqqStr = m_model->String(rows.front(), COL_DQQ);
      Mantid::Kernel::Strings::convert<double>(dqqStr, dqq);

      //params are qmin, -dqq, qmax for the final output
      params.push_back(*std::min_element(startOverlaps.begin(), startOverlaps.end()));
      params.push_back(-dqq);
      params.push_back(*std::max_element(endOverlaps.begin(), endOverlaps.end()));

      //startOverlaps and endOverlaps need to be slightly offset from each other
      //See usage examples of Stitch1DMany to see why we discard first qmin and last qmax
      startOverlaps.erase(startOverlaps.begin());
      endOverlaps.pop_back();

      std::string outputWSName = boost::algorithm::join(runs, "_") + "_IvsQ";

      IAlgorithm_sptr algStitch = AlgorithmManager::Instance().create("Stitch1DMany");
      algStitch->initialize();
      algStitch->setChild(true);
      algStitch->setProperty("InputWorkspaces", boost::algorithm::join(wsNames, ","));
      algStitch->setProperty("OutputWorkspace", outputWSName);
      algStitch->setProperty("Params", params);
      algStitch->setProperty("StartOverlaps", startOverlaps);
      algStitch->setProperty("EndOverlaps", endOverlaps);

      algStitch->execute();

      if(!algStitch->isExecuted())
        throw std::runtime_error("Failed to run Stitch1DMany on IvsQ workspaces.");

      Workspace_sptr stitchedWS = algStitch->getProperty("OutputWorkspace");

      //Insert the final stitched row into the ADS
      AnalysisDataService::Instance().addOrReplace(outputWSName, stitchedWS);
    }