コード例 #1
0
    /**
     * Integrate each spectra to get the number of counts
     * @param inputWS :: The workspace to integrate
     * @param indexMin :: The lower bound of the spectra to integrate
     * @param indexMax :: The upper bound of the spectra to integrate
     * @param lower :: The lower bound
     * @param upper :: The upper bound
     * @param outputWorkspace2D :: set to true to output a workspace 2D even if the input is an EventWorkspace
     * @returns A workspace containing the integrated counts
     */
    MatrixWorkspace_sptr 
    DetectorDiagnostic::integrateSpectra(MatrixWorkspace_sptr inputWS, 
        const int indexMin, const int indexMax, const double lower, const double upper,
        const bool outputWorkspace2D)
    {
      g_log.debug() << "Integrating input spectra.\n";
      // If the input spectra only has one bin, assume it has been integrated already
      // but we need to pass it to the algorithm so that a copy of the input workspace is
      // actually created to use for further calculations
      // get percentage completed estimates for now, t0 and when we've finished t1
      double t0 = m_fracDone, t1 = advanceProgress(RTGetTotalCounts);
      IAlgorithm_sptr childAlg = createChildAlgorithm("Integration", t0, t1 );
      childAlg->setProperty( "InputWorkspace", inputWS );
      childAlg->setProperty( "StartWorkspaceIndex", indexMin );
      childAlg->setProperty( "EndWorkspaceIndex", indexMax );
      // pass inputed values straight to this integration trusting the checking done there
      childAlg->setProperty("RangeLower",  lower );
      childAlg->setProperty("RangeUpper", upper);
      childAlg->setPropertyValue("IncludePartialBins", "1");
      childAlg->executeAsChildAlg();

      // Convert to 2D if desired, and if the input was an EventWorkspace.
      MatrixWorkspace_sptr outputW = childAlg->getProperty("OutputWorkspace");
      MatrixWorkspace_sptr finalOutputW = outputW;
      if (outputWorkspace2D && boost::dynamic_pointer_cast<EventWorkspace>(outputW))
      {
        g_log.debug() << "Converting output Event Workspace into a Workspace2D." << std::endl;
        childAlg = createChildAlgorithm("ConvertToMatrixWorkspace", t0, t1 );
        childAlg->setProperty("InputWorkspace", outputW);
        childAlg->executeAsChildAlg();
        finalOutputW = childAlg->getProperty("OutputWorkspace");
      }

      return finalOutputW;
    }
コード例 #2
0
/** Carries out a normalisation based on the integrated count of the monitor over a range
 *  @param inputWorkspace The input workspace
 *  @param outputWorkspace The result workspace
 */
void NormaliseToMonitor::normaliseByIntegratedCount(API::MatrixWorkspace_sptr inputWorkspace,
                                                    API::MatrixWorkspace_sptr& outputWorkspace)
{
  // Add up all the bins so it's just effectively a single value with an error
  IAlgorithm_sptr integrate = createChildAlgorithm("Integration");
  integrate->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_monitor);
  integrate->setProperty("RangeLower",m_integrationMin);
  integrate->setProperty("RangeUpper",m_integrationMax);
  integrate->setProperty<bool>("IncludePartialBins",getProperty("IncludePartialBins"));

  integrate->executeAsChildAlg();

  // Get back the result
  m_monitor = integrate->getProperty("OutputWorkspace");

  // Run the divide algorithm explicitly to enable progress reporting
  IAlgorithm_sptr divide = createChildAlgorithm("Divide",0.0,1.0);
  divide->setProperty<MatrixWorkspace_sptr>("LHSWorkspace", inputWorkspace);
  divide->setProperty<MatrixWorkspace_sptr>("RHSWorkspace", m_monitor);
  divide->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", outputWorkspace);

  divide->executeAsChildAlg();

  // Get back the result
  outputWorkspace = divide->getProperty("OutputWorkspace");
}
コード例 #3
0
/** Runs MaskDetectors as a child algorithm on the input workspace.
 *  @param inputWS The input workspace
 *  @param maskWS  A masking workspace
 */
void StepScan::runMaskDetectors(MatrixWorkspace_sptr inputWS,
                                MatrixWorkspace_sptr maskWS) {
  IAlgorithm_sptr maskingAlg = createChildAlgorithm("MaskDetectors");
  maskingAlg->setProperty<MatrixWorkspace_sptr>("Workspace", inputWS);
  maskingAlg->setProperty<MatrixWorkspace_sptr>("MaskedWorkspace", maskWS);
  maskingAlg->executeAsChildAlg();
}
コード例 #4
0
/**
 * It's assumed that both the flux reference files are simple Nexus
 * files since they have to produced by hand by the instrument
 * scientists. A simple Load algorithm should suffice.
 */
MatrixWorkspace_sptr SANSBeamFluxCorrection::loadReference() {
  const std::string referenceFluxFile =
      getPropertyValue("ReferenceFluxFilename");
  Poco::Path path(referenceFluxFile);
  const std::string entryName = "SANSBeamFluxCorrection_" + path.getBaseName();
  std::string fluxRefWSName = "__beam_flux_reference_" + path.getBaseName();

  // Load reference flux as needed
  MatrixWorkspace_sptr fluxRefWS;
  if (m_reductionManager->existsProperty(entryName)) {
    fluxRefWS = m_reductionManager->getProperty(entryName);
    fluxRefWSName = m_reductionManager->getPropertyValue(entryName);
    m_output_message += "   | Using flux reference " + referenceFluxFile + "\n";
  } else {
    IAlgorithm_sptr loadAlg = createChildAlgorithm("Load");
    loadAlg->setProperty("Filename", referenceFluxFile);
    loadAlg->executeAsChildAlg();
    Workspace_sptr tmpWS = loadAlg->getProperty("OutputWorkspace");
    fluxRefWS = boost::dynamic_pointer_cast<MatrixWorkspace>(tmpWS);
    m_output_message +=
        "   | Loaded flux reference " + referenceFluxFile + "\n";

    // Keep the reference data for later use
    AnalysisDataService::Instance().addOrReplace(fluxRefWSName, fluxRefWS);
    m_reductionManager->declareProperty(
        new WorkspaceProperty<>(entryName, fluxRefWSName, Direction::InOut));
    m_reductionManager->setPropertyValue(entryName, fluxRefWSName);
    m_reductionManager->setProperty(entryName, fluxRefWS);
  }

  return fluxRefWS;
}
コード例 #5
0
/** Uses Polynomial as a ChildAlgorithm to fit the log of the exponential curve
 * expected for the transmission.
 * @param[in] WS The single-spectrum workspace to fit
 * @param[in] order The order of the polynomial from 2 to 6
 * @param[out] coeficients of the polynomial. c[0] + c[1]x + c[2]x^2 + ...
 */
API::MatrixWorkspace_sptr
CalculateTransmission::fitPolynomial(API::MatrixWorkspace_sptr WS, int order,
                                     std::vector<double> &coeficients) {
  g_log.notice("Fitting the experimental transmission curve fitpolyno");
  double start = m_done;
  IAlgorithm_sptr childAlg = createChildAlgorithm("Fit", start, m_done = 0.9);
  auto polyfit = API::FunctionFactory::Instance().createFunction("Polynomial");
  polyfit->setAttributeValue("n", order);
  polyfit->initialize();
  childAlg->setProperty("Function", polyfit);
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS);
  childAlg->setProperty("Minimizer", "Levenberg-MarquardtMD");
  childAlg->setProperty("CreateOutput", true);
  childAlg->setProperty("IgnoreInvalidData", true);
  childAlg->executeAsChildAlg();
  std::string fitStatus = childAlg->getProperty("OutputStatus");
  if (fitStatus != "success") {
    g_log.error("Unable to successfully fit the data: " + fitStatus);
    throw std::runtime_error("Unable to successfully fit the data");
  }

  // Only get to here if successful
  coeficients.resize(order + 1);
  for (int i = 0; i <= order; i++) {
    coeficients[i] = polyfit->getParameter(i);
  }
  return this->extractSpectra(childAlg->getProperty("OutputWorkspace"),
                              std::vector<size_t>(1, 1));
}
コード例 #6
0
ファイル: Integration.cpp プロジェクト: mducle/mantid
/**
 * This function gets the input workspace. In the case for a RebinnedOutput
 * workspace, it must be cleaned before proceeding. Other workspaces are
 * untouched.
 * @return the input workspace, cleaned if necessary
 */
MatrixWorkspace_sptr Integration::getInputWorkspace() {
  MatrixWorkspace_sptr temp = getProperty("InputWorkspace");

  if (temp->id() == "RebinnedOutput") {
    // Clean the input workspace in the RebinnedOutput case for nan's and
    // inf's in order to treat the data correctly later.
    IAlgorithm_sptr alg = this->createChildAlgorithm("ReplaceSpecialValues");
    alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", temp);
    std::string outName = "_" + temp->getName() + "_clean";
    alg->setProperty("OutputWorkspace", outName);
    alg->setProperty("NaNValue", 0.0);
    alg->setProperty("NaNError", 0.0);
    alg->setProperty("InfinityValue", 0.0);
    alg->setProperty("InfinityError", 0.0);
    alg->executeAsChildAlg();
    temp = alg->getProperty("OutputWorkspace");
  }

  // To integrate point data it will be converted to histograms
  if (!temp->isHistogramData()) {
    auto alg = this->createChildAlgorithm("ConvertToHistogram");
    alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", temp);
    std::string outName = "_" + temp->getName() + "_histogram";
    alg->setProperty("OutputWorkspace", outName);
    alg->executeAsChildAlg();
    temp = alg->getProperty("OutputWorkspace");
    temp->setDistribution(true);
  }

  return temp;
}
コード例 #7
0
ファイル: ConvertDiffCal.cpp プロジェクト: spaceyatom/mantid
/** Execute the algorithm.
 */
void ConvertDiffCal::exec() {
  OffsetsWorkspace_const_sptr offsetsWS = getProperty("OffsetsWorkspace");

  // initial setup of new style config
  ITableWorkspace_sptr configWksp = boost::make_shared<TableWorkspace>();
  configWksp->addColumn("int", "detid");
  configWksp->addColumn("double", "difc");
  configWksp->addColumn("double", "difa");
  configWksp->addColumn("double", "tzero");

  // create values in the table
  const size_t numberOfSpectra = offsetsWS->getNumberHistograms();
  Progress progress(this, 0.0, 1.0, numberOfSpectra);

  for (size_t i = 0; i < numberOfSpectra; ++i) {
    API::TableRow newrow = configWksp->appendRow();
    newrow << static_cast<int>(getDetID(offsetsWS, i));
    newrow << calculateDIFC(offsetsWS, i);
    newrow << 0.; // difa
    newrow << 0.; // tzero

    progress.report();
  }

  // sort the results
  IAlgorithm_sptr sortTable = createChildAlgorithm("SortTableWorkspace");
  sortTable->setProperty("InputWorkspace", configWksp);
  sortTable->setProperty("OutputWorkspace", configWksp);
  sortTable->setPropertyValue("Columns", "detid");
  sortTable->executeAsChildAlg();

  // copy over the results
  configWksp = sortTable->getProperty("OutputWorkspace");
  setProperty("OutputWorkspace", configWksp);
}
コード例 #8
0
/** Executes the algorithm
   *
   *  @throw Exception::FileError If the grouping file cannot be opened or read
  *successfully
   */
void GetDetOffsetsMultiPeaks::exec() {
  // Process input information
  processProperties();

  // Create information workspaces
  createInformationWorkspaces();

  // Calculate offset of each detector
  calculateDetectorsOffsets();

  // Return the output
  setProperty("OutputWorkspace", m_outputW);
  setProperty("NumberPeaksWorkspace", m_outputNP);
  setProperty("MaskWorkspace", m_maskWS);
  setProperty("FittedResolutionWorkspace", m_resolutionWS);
  setProperty("SpectraFitInfoTableWorkspace", m_infoTableWS);
  setProperty("PeaksOffsetTableWorkspace", m_peakOffsetTableWS);

  // Also save to .cal file, if requested
  std::string filename = getProperty("GroupingFileName");
  if (!filename.empty()) {
    progress(0.9, "Saving .cal file");
    IAlgorithm_sptr childAlg = createChildAlgorithm("SaveCalFile");
    childAlg->setProperty("OffsetsWorkspace", m_outputW);
    childAlg->setProperty("MaskWorkspace", m_maskWS);
    childAlg->setPropertyValue("Filename", filename);
    childAlg->executeAsChildAlg();
  }

  // Make summary
  progress(0.92, "Making summary");
  makeFitSummary();

  return;
}
コード例 #9
0
/** Pulls the monitor spectrum out of a larger workspace
 *  @param WS :: The workspace containing the spectrum to extract
 *  @param index :: The index of the spectrum to extract
 *  @returns A workspace containing the single spectrum requested
 */
API::MatrixWorkspace_sptr NormaliseToMonitor::extractMonitorSpectrum(API::MatrixWorkspace_sptr WS, const std::size_t index)
{
  IAlgorithm_sptr childAlg = createChildAlgorithm("ExtractSingleSpectrum");
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS);
  childAlg->setProperty<int>("WorkspaceIndex", static_cast<int>(index));
  childAlg->executeAsChildAlg();
  MatrixWorkspace_sptr outWS = childAlg->getProperty("OutputWorkspace");

  IAlgorithm_sptr alg = createChildAlgorithm("ConvertToMatrixWorkspace");
  alg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", outWS);
  alg->executeAsChildAlg();
  outWS = alg->getProperty("OutputWorkspace");

  // Only get to here if successful
  return outWS;
}
コード例 #10
0
/** Load the logs from the input NeXus file.
 *
 * @param nexusFileName :: Name of the NeXus file to load logs from.
 * @param localWorkspace :: MatrixWorkspace in which to put the logs.
 * @param alg :: Handle of an algorithm for logging access.
 * @return true if successful.
 */
bool AppendGeometryToSNSNexus::runLoadNexusLogs(
    const std::string &nexusFileName, API::MatrixWorkspace_sptr localWorkspace,
    Algorithm *alg) {
  IAlgorithm_sptr loadLogs =
      alg->createChildAlgorithm("LoadNexusLogs", 0, 1, true);

  // Execute the Child Algorithm, catching errors without stopping.
  bool executionSuccessful(true);
  try {
    alg->getLogger().information() << "Loading logs from the NeXus file..."
                                   << std::endl;
    loadLogs->setPropertyValue("Filename", nexusFileName);
    loadLogs->setProperty<MatrixWorkspace_sptr>("Workspace", localWorkspace);
    loadLogs->executeAsChildAlg();
  } catch (std::invalid_argument &e) {
    alg->getLogger().information(
        "Invalid argument to LoadNexusLogs Child Algorithm");
    alg->getLogger().information(e.what());
    executionSuccessful = false;
  } catch (std::runtime_error &) {
    alg->getLogger().information(
        "Unable to successfully run runLoadNexusLogs Child Algorithm./n");
    executionSuccessful = false;
  }

  return executionSuccessful;
}
コード例 #11
0
/** Uses 'Linear' as a ChildAlgorithm to fit the log of the exponential curve
 * expected for the transmission.
 *  @param[in] WS The single-spectrum workspace to fit
 *  @param[out] grad The single-spectrum workspace to fit
 *  @param[out] offset The single-spectrum workspace to fit
 *  @return A workspace containing the fit
 *  @throw runtime_error if the Linear algorithm fails during execution
 */
API::MatrixWorkspace_sptr
CalculateTransmission::fitData(API::MatrixWorkspace_sptr WS, double &grad,
                               double &offset) {
  g_log.information("Fitting the experimental transmission curve");
  double start = m_done;
  IAlgorithm_sptr childAlg = createChildAlgorithm("Fit", start, m_done = 0.9);
  auto linearBack =
      API::FunctionFactory::Instance().createFunction("LinearBackground");
  childAlg->setProperty("Function", linearBack);
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS);
  childAlg->setProperty("Minimizer", "Levenberg-MarquardtMD");
  childAlg->setProperty("CreateOutput", true);
  childAlg->setProperty("IgnoreInvalidData", true);
  childAlg->executeAsChildAlg();

  std::string fitStatus = childAlg->getProperty("OutputStatus");
  if (fitStatus != "success") {
    g_log.error("Unable to successfully fit the data: " + fitStatus);
    throw std::runtime_error("Unable to successfully fit the data");
  }

  // Only get to here if successful
  offset = linearBack->getParameter(0);
  grad = linearBack->getParameter(1);
  return this->extractSpectra(childAlg->getProperty("OutputWorkspace"),
                              std::vector<size_t>(1, 1));
}
コード例 #12
0
/**
 * Extracts multiple spectra from a Workspace2D into a new workspaces, using
 *SumSpectra.
 *
 * @param ws      :: The workspace containing the spectrum to extract
 * @param indices :: The workspace index of the spectrum to extract
 *
 * @returns a Workspace2D containing the extracted spectrum
 * @throws runtime_error if the ExtractSingleSpectrum algorithm fails during
 *execution
 */
API::MatrixWorkspace_sptr
CalculateTransmission::extractSpectra(API::MatrixWorkspace_sptr ws,
                                      const std::vector<size_t> &indices) {
  // Compile a comma separated list of indices that we can pass to SumSpectra.
  std::vector<std::string> indexStrings(indices.size());
  // A bug in boost 1.53: https://svn.boost.org/trac/boost/ticket/7421
  // means that lexical_cast cannot be used directly as the call is ambiguous
  // so we need to define a function pointer that can resolve the overloaded
  // lexical_cast function
  typedef std::string (*from_size_t)(const size_t &);

  std::transform(indices.begin(), indices.end(), indexStrings.begin(),
                 (from_size_t)boost::lexical_cast<std::string, size_t>);
  const std::string commaIndexList = boost::algorithm::join(indexStrings, ",");

  double start = m_done;
  IAlgorithm_sptr childAlg =
      createChildAlgorithm("SumSpectra", start, m_done += 0.1);
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", ws);
  childAlg->setPropertyValue("ListOfWorkspaceIndices", commaIndexList);
  childAlg->executeAsChildAlg();

  // Only get to here if successful
  return childAlg->getProperty("OutputWorkspace");
}
コード例 #13
0
ファイル: TransformMD.cpp プロジェクト: mkoennecke/mantid
/** Execute the algorithm.
 */
void TransformMD::exec() {
  Mantid::API::IMDWorkspace_sptr inWS;
  Mantid::API::IMDWorkspace_sptr outWS;

  inWS = getProperty("InputWorkspace");
  outWS = getProperty("OutputWorkspace");

  if (boost::dynamic_pointer_cast<MatrixWorkspace>(inWS))
    throw std::runtime_error("TransformMD can only transform a "
                             "MDHistoWorkspace or a MDEventWorkspace.");

  if (outWS != inWS) {
    // NOT in-place. So first we clone inWS into outWS
    IAlgorithm_sptr clone =
        this->createChildAlgorithm("CloneMDWorkspace", 0.0, 0.5, true);
    clone->setProperty("InputWorkspace", inWS);
    clone->executeAsChildAlg();
    outWS = clone->getProperty("OutputWorkspace");
  }

  if (!outWS)
    throw std::runtime_error("Invalid output workspace.");

  size_t nd = outWS->getNumDims();
  m_scaling = getProperty("Scaling");
  m_offset = getProperty("Offset");

  // Replicate single values
  if (m_scaling.size() == 1)
    m_scaling = std::vector<double>(nd, m_scaling[0]);
  if (m_offset.size() == 1)
    m_offset = std::vector<double>(nd, m_offset[0]);

  // Check the size
  if (m_scaling.size() != nd)
    throw std::invalid_argument("Scaling argument must be either length 1 or "
                                "match the number of dimensions.");
  if (m_offset.size() != nd)
    throw std::invalid_argument("Offset argument must be either length 1 or "
                                "match the number of dimensions.");

  // Transform the dimensions
  outWS->transformDimensions(m_scaling, m_offset);

  MDHistoWorkspace_sptr histo =
      boost::dynamic_pointer_cast<MDHistoWorkspace>(outWS);
  IMDEventWorkspace_sptr event =
      boost::dynamic_pointer_cast<IMDEventWorkspace>(outWS);

  if (histo) {
    // Recalculate all the values since the dimensions changed.
    histo->cacheValues();
  } else if (event) {
    // Call the method for this type of MDEventWorkspace.
    CALL_MDEVENT_FUNCTION(this->doTransform, outWS);
  }

  this->setProperty("OutputWorkspace", outWS);
}
コード例 #14
0
  void StripVanadiumPeaks2::exec(){

    // 1. Process input/output
    API::MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
    std::string outputWSName = getPropertyValue("OutputWorkspace");
    int singleIndex = getProperty("WorkspaceIndex");
    int param_fwhm = getProperty("FWHM");
    int param_tolerance = getProperty("Tolerance");

    bool singleSpectrum = !isEmpty(singleIndex);

    // 2. Call StripPeaks
    std::string peakpositions;
    std::string unit = inputWS->getAxis(0)->unit()->unitID();
    if (unit == "dSpacing")
    {
      peakpositions = "0.5044,0.5191,0.5350,0.5526,0.5936,0.6178,0.6453,0.6768,0.7134,0.7566,0.8089,0.8737,0.9571,1.0701,1.2356,1.5133,2.1401";
    }
    else if (unit == "MomentumTransfer")
    {
      g_log.error() << "Unit MomentumTransfer (Q-space) is NOT supported by StripVanadiumPeaks now.\n";
      throw std::invalid_argument("Q-space is not supported");
      // Comment out next line as it won't be reached.
      //peakpositions = "2.9359, 4.1520, 5.0851, 5.8716, 6.5648, 7.1915, 7.7676, 8.3045, 8.8074, 9.2837, 9.7368, 10.1703, 10.5849, 11.3702, 11.7443, 12.1040, 12.4568";

    } else {
      g_log.error() << "Unit " << unit << " Is NOT supported by StripVanadiumPeaks, which only supports d-spacing" << std::endl;
      throw std::invalid_argument("Not supported unit");
    }

    // Call StripPeak
    double pro0 = 0.0;
    double prof = 1.0;
    bool sublog = true;
    IAlgorithm_sptr stripPeaks = createChildAlgorithm("StripPeaks", pro0, prof, sublog);
    stripPeaks->setProperty("InputWorkspace", inputWS);
    stripPeaks->setPropertyValue("OutputWorkspace", outputWSName);
    stripPeaks->setProperty("FWHM", param_fwhm);
    stripPeaks->setProperty("Tolerance", param_tolerance);
    stripPeaks->setPropertyValue("PeakPositions", peakpositions);
    stripPeaks->setProperty<std::string>("BackgroundType", getProperty("BackgroundType"));
    stripPeaks->setProperty<bool>("HighBackground", getProperty("HighBackground"));
    if (singleSpectrum){
      stripPeaks->setProperty("WorkspaceIndex", singleIndex);
    }
    stripPeaks->setProperty<double>("PeakPositionTolerance", getProperty("PeakPositionTolerance"));

    stripPeaks->executeAsChildAlg();

    // 3. Get and set output workspace
    // API::MatrixWorkspace_sptr outputWS = AnalysisDataService::Instance().retrieveWS<API::MatrixWorkspace_sptr>(outputWSName);
    // boost::shared_ptr<API::Workspace> outputWS = AnalysisDataService::Instance().retrieve(outputWSName);
    API::MatrixWorkspace_sptr outputWS = stripPeaks->getProperty("OutputWorkspace");

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

    return;
  }
コード例 #15
0
ファイル: MergeRuns.cpp プロジェクト: mducle/mantid
/** Calls the Rebin algorithm as a ChildAlgorithm.
 *  @param  workspace The workspace to use as input to the Rebin algorithms
 *  @param  params    The rebin parameters
 *  @return A shared pointer to the output (rebinned) workspace
 *  @throw  std::runtime_error If the Rebin algorithm fails
 */
API::MatrixWorkspace_sptr
MergeRuns::rebinInput(const API::MatrixWorkspace_sptr &workspace,
                      const std::vector<double> &params) {
    // Create a Rebin child algorithm
    IAlgorithm_sptr rebin = createChildAlgorithm("Rebin");
    rebin->setProperty("InputWorkspace", workspace);
    rebin->setProperty("Params", params);
    rebin->executeAsChildAlg();
    return rebin->getProperty("OutputWorkspace");
}
コード例 #16
0
ファイル: NormaliseToMonitor.cpp プロジェクト: mganeva/mantid
/**
 * Pulls the monitor spectra out of a larger workspace
 * @param ws
 * @param workspaceIndexes The indexes of the spectra to extract
 * @return A workspace containing the spectra requested
 */
MatrixWorkspace_sptr NormaliseToMonitor::extractMonitorSpectra(
    const MatrixWorkspace_sptr &ws,
    const std::vector<std::size_t> &workspaceIndexes) {
  IAlgorithm_sptr childAlg = createChildAlgorithm("ExtractSpectra");
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", ws);
  childAlg->setProperty("WorkspaceIndexList", workspaceIndexes);
  childAlg->executeAsChildAlg();
  MatrixWorkspace_sptr outWS = childAlg->getProperty("OutputWorkspace");
  return outWS;
}
コード例 #17
0
 /**
  * Function to apply a given mask to a workspace.
  * @param inputWS : the workspace to mask
  * @param maskWS : the workspace containing the masking information
  */
 void DetectorDiagnostic::applyMask(API::MatrixWorkspace_sptr inputWS,
     API::MatrixWorkspace_sptr maskWS)
 {
   IAlgorithm_sptr maskAlg = createChildAlgorithm("MaskDetectors"); // should set progress bar
   maskAlg->setProperty("Workspace", inputWS);
   maskAlg->setProperty("MaskedWorkspace", maskWS);
   maskAlg->setProperty("StartWorkspaceIndex", m_minIndex);
   maskAlg->setProperty("EndWorkspaceIndex", m_maxIndex);
   maskAlg->executeAsChildAlg();
 }
コード例 #18
0
/** Runs FilterByXValue as a child algorithm on the given workspace
 *  @param inputWS The input workspace
 *  @param xmin    The minimum value of the filter
 *  @param xmax    The maximum value of the filter
 */
void StepScan::runFilterByXValue(MatrixWorkspace_sptr inputWS,
                                 const double xmin, const double xmax) {
  std::string rangeUnit = getProperty("RangeUnit");
  // Run ConvertUnits on the input workspace if xmin/max were given in a
  // different unit
  if (rangeUnit != "TOF") {
    IAlgorithm_sptr convertUnits = createChildAlgorithm("ConvertUnits");
    convertUnits->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputWS);
    convertUnits->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", inputWS);
    convertUnits->setProperty("Target", rangeUnit);
    // TODO: Emode/efixed?
    convertUnits->executeAsChildAlg();
  }

  IAlgorithm_sptr filter = createChildAlgorithm("FilterByXValue");
  filter->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputWS);
  filter->setProperty<MatrixWorkspace_sptr>("OutputWorkspace", inputWS);
  filter->setProperty("XMin", xmin);
  filter->setProperty("XMax", xmax);
  filter->executeAsChildAlg();
}
コード例 #19
0
ファイル: SumRowColumn.cpp プロジェクト: AlistairMills/mantid
/** Call Integration as a Child Algorithm
 *  @return The integrated workspace
 */
MatrixWorkspace_sptr SumRowColumn::integrateWorkspace()
{
  g_log.debug() << "Integrating input workspace\n";

  IAlgorithm_sptr childAlg = createChildAlgorithm("Integration");
  //pass inputed values straight to this Child Algorithm, checking must be done there
  childAlg->setProperty<MatrixWorkspace_sptr>( "InputWorkspace", getProperty("InputWorkspace") );
  childAlg->setProperty<double>( "RangeLower",  getProperty("XMin") );
  childAlg->setProperty<double>( "RangeUpper", getProperty("XMax") );
  childAlg->executeAsChildAlg();
  return childAlg->getProperty("OutputWorkspace");
}
コード例 #20
0
/** Calls rebin as Child Algorithm
*  @param binParams this string is passed to rebin as the "Params" property
*  @param ws the workspace to rebin
*  @return the resultant rebinned workspace
*  @throw runtime_error if the rebin algorithm fails during execution
*/
API::MatrixWorkspace_sptr
CalculateTransmission::rebin(std::vector<double> &binParams,
                             API::MatrixWorkspace_sptr ws) {
  double start = m_done;
  IAlgorithm_sptr childAlg =
      createChildAlgorithm("Rebin", start, m_done += 0.05);
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", ws);
  childAlg->setProperty<std::vector<double>>("Params", binParams);
  childAlg->executeAsChildAlg();

  // Only get to here if successful
  return childAlg->getProperty("OutputWorkspace");
}
コード例 #21
0
ファイル: EQSANSLoad.cpp プロジェクト: liyulun/mantid
/// Move the detector according to the beam center
void EQSANSLoad::moveToBeamCenter() {
  // Check that we have a beam center defined, otherwise set the
  // default beam center
  if (isEmpty(m_center_x) || isEmpty(m_center_y)) {
    EQSANSInstrument::getDefaultBeamCenter(dataWS, m_center_x, m_center_y);
    g_log.information() << "Setting beam center to [" << m_center_x << ", "
                        << m_center_y << "]\n";
    return;
  }

  // Check that the center of the detector really is at (0,0)
  int nx_pixels = static_cast<int>(
      dataWS->getInstrument()->getNumberParameter("number-of-x-pixels")[0]);
  int ny_pixels = static_cast<int>(
      dataWS->getInstrument()->getNumberParameter("number-of-y-pixels")[0]);
  V3D pixel_first = dataWS->getInstrument()->getDetector(0)->getPos();
  int detIDx = EQSANSInstrument::getDetectorFromPixel(nx_pixels - 1, 0, dataWS);
  int detIDy = EQSANSInstrument::getDetectorFromPixel(0, ny_pixels - 1, dataWS);

  V3D pixel_last_x = dataWS->getInstrument()->getDetector(detIDx)->getPos();
  V3D pixel_last_y = dataWS->getInstrument()->getDetector(detIDy)->getPos();
  double x_offset = (pixel_first.X() + pixel_last_x.X()) / 2.0;
  double y_offset = (pixel_first.Y() + pixel_last_y.Y()) / 2.0;
  double beam_ctr_x = 0.0;
  double beam_ctr_y = 0.0;
  EQSANSInstrument::getCoordinateFromPixel(m_center_x, m_center_y, dataWS,
                                           beam_ctr_x, beam_ctr_y);

  IAlgorithm_sptr mvAlg =
      createChildAlgorithm("MoveInstrumentComponent", 0.5, 0.50);
  mvAlg->setProperty<MatrixWorkspace_sptr>("Workspace", dataWS);
  mvAlg->setProperty("ComponentName", "detector1");
  mvAlg->setProperty("X", -x_offset - beam_ctr_x);
  mvAlg->setProperty("Y", -y_offset - beam_ctr_y);
  mvAlg->setProperty("RelativePosition", true);
  mvAlg->executeAsChildAlg();
  m_output_message += "   Beam center offset: " +
                      Poco::NumberFormatter::format(x_offset) + ", " +
                      Poco::NumberFormatter::format(y_offset) + " m\n";
  // m_output_message += "   Beam center in real-space: " +
  // Poco::NumberFormatter::format(-x_offset-beam_ctr_x)
  //    + ", " + Poco::NumberFormatter::format(-y_offset-beam_ctr_y) + " m\n";
  g_log.information() << "Moving beam center to " << m_center_x << " "
                      << m_center_y << '\n';

  dataWS->mutableRun().addProperty("beam_center_x", m_center_x, "pixel", true);
  dataWS->mutableRun().addProperty("beam_center_y", m_center_y, "pixel", true);
  m_output_message += "   Beam center: " +
                      Poco::NumberFormatter::format(m_center_x) + ", " +
                      Poco::NumberFormatter::format(m_center_y) + "\n";
}
コード例 #22
0
/** Execute the algorithm.
 */
void MergeMDFiles::exec() {
  // clear disk buffer which can remain from previous runs
  // the existence/ usage of the buffer indicates if the algorithm works with
  // file based or memory based target workspaces;
  // pDiskBuffer = NULL;
  MultipleFileProperty *multiFileProp =
      dynamic_cast<MultipleFileProperty *>(getPointerToProperty("Filenames"));
  if (!multiFileProp) {
    throw std::logic_error(
        "Filenames property must have MultipleFileProperty type.");
  }
  m_Filenames =
      MultipleFileProperty::flattenFileNames(multiFileProp->operator()());
  if (m_Filenames.size() == 0)
    throw std::invalid_argument("Must specify at least one filename.");
  std::string firstFile = m_Filenames[0];

  std::string outputFile = getProperty("OutputFilename");
  m_fileBasedTargetWS = false;
  if (!outputFile.empty()) {
    m_fileBasedTargetWS = true;
    if (Poco::File(outputFile).exists())
      throw std::invalid_argument(
          " File " + outputFile + " already exists. Can not use existing file "
                                  "as the target to MergeMD files.\n" +
          " Use it as one of source files if you want to add MD data to it");
  }

  // Start by loading the first file but just the box structure, no events, and
  // not file-backed
  // m_BoxStruct.loadBoxStructure(firstFile,
  IAlgorithm_sptr loader = createChildAlgorithm("LoadMD", 0.0, 0.05, false);
  loader->setPropertyValue("Filename", firstFile);
  loader->setProperty("MetadataOnly", false);
  loader->setProperty("BoxStructureOnly", true);
  loader->setProperty("FileBackEnd", false);
  loader->executeAsChildAlg();
  IMDWorkspace_sptr result = (loader->getProperty("OutputWorkspace"));

  auto firstWS = boost::dynamic_pointer_cast<API::IMDEventWorkspace>(result);
  if (!firstWS)
    throw std::runtime_error(
        "Can not load MDEventWorkspace from initial file " + firstFile);

  // do the job
  this->doExecByCloning(firstWS, outputFile);

  m_OutIWS->setFileNeedsUpdating(false);

  setProperty("OutputWorkspace", m_OutIWS);
}
コード例 #23
0
ファイル: NormaliseToMonitor.cpp プロジェクト: mganeva/mantid
/** Carries out a normalization based on the integrated count of the monitor
 * over a range
 * @param inputWorkspace The input workspace
 * @param outputWorkspace The result workspace
 * @param isSingleCountWorkspace Whether or not the input workspace is point
 *data with single counts per spectrum
 */
void NormaliseToMonitor::normaliseByIntegratedCount(
    const MatrixWorkspace_sptr &inputWorkspace,
    MatrixWorkspace_sptr &outputWorkspace, const bool isSingleCountWorkspace) {
  m_monitor = extractMonitorSpectra(m_monitor, m_workspaceIndexes);

  // If single counting no need to integrate, monitor already guaranteed to be a
  // single count
  if (!isSingleCountWorkspace) {
    // Add up all the bins so it's just effectively a series of values with
    // errors
    IAlgorithm_sptr integrate = createChildAlgorithm("Integration");
    integrate->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_monitor);
    integrate->setProperty("RangeLower", m_integrationMin);
    integrate->setProperty("RangeUpper", m_integrationMax);
    integrate->setProperty<bool>("IncludePartialBins",
                                 getProperty("IncludePartialBins"));
    integrate->executeAsChildAlg();
    m_monitor = integrate->getProperty("OutputWorkspace");
  }

  EventWorkspace_sptr inputEvent =
      boost::dynamic_pointer_cast<EventWorkspace>(inputWorkspace);

  if (inputEvent) {
    // Run the divide algorithm explicitly to enable progress reporting
    IAlgorithm_sptr divide = createChildAlgorithm("Divide", 0.0, 1.0);
    divide->setProperty<MatrixWorkspace_sptr>("LHSWorkspace", inputWorkspace);
    divide->setProperty<MatrixWorkspace_sptr>("RHSWorkspace", m_monitor);
    divide->setProperty<MatrixWorkspace_sptr>("OutputWorkspace",
                                              outputWorkspace);
    divide->executeAsChildAlg();

    // Get back the result
    outputWorkspace = divide->getProperty("OutputWorkspace");
  } else {
    performHistogramDivision(inputWorkspace, outputWorkspace);
  }
}
コード例 #24
0
ファイル: RemoveBins.cpp プロジェクト: trnielsen/mantid
/// Calls CropWorkspace as a Child Algorithm to remove bins from the start or end of a square workspace
void RemoveBins::crop(const double& start, const double& end)
{
  IAlgorithm_sptr childAlg = createChildAlgorithm("CropWorkspace");
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", boost::const_pointer_cast<MatrixWorkspace>(m_inputWorkspace));
  childAlg->setProperty<double>("XMin", start);
  childAlg->setProperty<double>("XMax", end);
  childAlg->executeAsChildAlg();

  // Only get to here if successful
  // Assign the result to the output workspace property
  MatrixWorkspace_sptr outputWS = childAlg->getProperty("OutputWorkspace");
  setProperty("OutputWorkspace",outputWS);
  return;
}
コード例 #25
0
void AlignAndFocusPowder::convertOffsetsToCal(
    DataObjects::OffsetsWorkspace_sptr &offsetsWS) {
  if (!offsetsWS)
    return;

  IAlgorithm_sptr alg = createChildAlgorithm("ConvertDiffCal");
  alg->setProperty("OffsetsWorkspace", offsetsWS);
  alg->setPropertyValue("OutputWorkspace", m_instName + "_cal");
  alg->executeAsChildAlg();

  m_calibrationWS = alg->getProperty("OutputWorkspace");
  AnalysisDataService::Instance().addOrReplace(m_instName + "_cal",
                                               m_calibrationWS);
}
コード例 #26
0
/**
* Uses linear algorithm to do the fitting.
* @param histogram the histogram to fit
* @param background an output variable for the calculated background
* @param variance an output variable for background's variance, currently always
* zero.
* @param startX an X value in the first bin to be included in the fit
* @param endX an X value in the last bin to be included in the fit
*/
void CalculateFlatBackground::LinearFit(
    const HistogramData::Histogram &histogram, double &background,
    double &variance, const double startX, const double endX) {
  MatrixWorkspace_sptr WS = WorkspaceFactory::Instance().create(
      "Workspace2D", 1, histogram.x().size(), histogram.y().size());
  WS->setHistogram(0, histogram);
  IAlgorithm_sptr childAlg = createChildAlgorithm("Fit");

  IFunction_sptr func =
      API::FunctionFactory::Instance().createFunction("LinearBackground");
  childAlg->setProperty<IFunction_sptr>("Function", func);

  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", WS);
  childAlg->setProperty<bool>("CreateOutput", true);
  childAlg->setProperty<int>("WorkspaceIndex", 0);
  childAlg->setProperty<double>("StartX", startX);
  childAlg->setProperty<double>("EndX", endX);
  // Default minimizer doesn't work properly even on the easiest cases,
  // so Levenberg-MarquardtMD is used instead
  childAlg->setProperty<std::string>("Minimizer", "Levenberg-MarquardtMD");

  childAlg->executeAsChildAlg();

  std::string outputStatus = childAlg->getProperty("OutputStatus");
  if (outputStatus != "success") {
    g_log.warning("Unable to successfully fit the data: " + outputStatus);
    background = -1;
    return;
  }

  Mantid::API::ITableWorkspace_sptr output =
      childAlg->getProperty("OutputParameters");

  // Find rows with parameters we are after
  size_t rowA0, rowA1;
  output->find(static_cast<std::string>("A0"), rowA0, 0);
  output->find(static_cast<std::string>("A1"), rowA1, 0);

  // Linear function is defined as A0 + A1*x
  const double intercept = output->cell<double>(rowA0, 1);
  const double slope = output->cell<double>(rowA1, 1);

  const double centre = (startX + endX) / 2.0;

  // Calculate the value of the flat background by taking the value at the
  // centre point of the fit
  background = slope * centre + intercept;
  // ATM we don't calculate the error here.
  variance = 0;
}
コード例 #27
0
ファイル: Stitch1DMD.cpp プロジェクト: AlistairMills/mantid
 /**
 Creates a 1D MDHistoWorkspace from the inputs arrays. Runs the CreateMDHistoWorkspace algorithm as a ChildAlgorithm.
 @param signals: signal collection
 @param errors: error collection
 @param extents: extents collection
 @param vecNBins: number of bins collection
 @param names: names collection
 @param units: units collection
 */
 MDHistoWorkspace_sptr Stitch1DMD::create1DHistoWorkspace(const MantidVec& signals,const MantidVec& errors, const MantidVec& extents, const std::vector<int>& vecNBins, const std::vector<std::string> names, const std::vector<std::string>& units)
 {
   IAlgorithm_sptr createMDHistoWorkspace = this->createChildAlgorithm("CreateMDHistoWorkspace");
   createMDHistoWorkspace->initialize();
   createMDHistoWorkspace->setProperty("SignalInput", signals);
   createMDHistoWorkspace->setProperty("ErrorInput", errors);
   createMDHistoWorkspace->setProperty("Dimensionality", 1);
   createMDHistoWorkspace->setProperty("Extents", extents);
   createMDHistoWorkspace->setProperty("NumberOfBins", vecNBins);
   createMDHistoWorkspace->setProperty("Names", names);
   createMDHistoWorkspace->setProperty("Units", units);
   createMDHistoWorkspace->executeAsChildAlg();
   IMDHistoWorkspace_sptr outWS = createMDHistoWorkspace->getProperty("OutputWorkspace");
   return boost::dynamic_pointer_cast<MDHistoWorkspace>(outWS);
 }
コード例 #28
0
/** Load in the RKH file for that has the correction information
 *  @param corrFile :: the name of the correction to load
 *  @return workspace containing the loaded data
 *  @throw runtime_error if load algorithm fails
 */
MatrixWorkspace_sptr CorrectToFile::loadInFile(const std::string &corrFile) {
  g_log.information() << "Loading file " << corrFile << '\n';
  progress(0, "Loading file");
  IAlgorithm_sptr loadRKH =
      createChildAlgorithm("LoadRKH", 0, 1.0 /*LOAD_TIME*/);
  std::string rkhfile = getProperty("Filename");
  loadRKH->setPropertyValue("Filename", rkhfile);
  loadRKH->setPropertyValue("OutputWorkspace", "rkhout");
  std::string columnValue = getProperty("FirstColumnValue");
  loadRKH->setPropertyValue("FirstColumnValue", columnValue);
  loadRKH->executeAsChildAlg();

  g_log.debug() << corrFile << " loaded\n";
  return loadRKH->getProperty("OutputWorkspace");
}
コード例 #29
0
ファイル: MDNormDirectSC.cpp プロジェクト: nimgould/mantid
/**
 * Runs the BinMD algorithm on the input to provide the output workspace
 * All slicing algorithm properties are passed along
 * @return MDHistoWorkspace as a result of the binning
 */
MDHistoWorkspace_sptr MDNormDirectSC::binInputWS() {
  const auto &props = getProperties();
  IAlgorithm_sptr binMD = createChildAlgorithm("BinMD", 0.0, 0.3);
  binMD->setPropertyValue("AxisAligned", "1");
  for (auto it = props.begin(); it != props.end(); ++it) {
    const auto &propName = (*it)->name();
    if (propName != "SolidAngleWorkspace" &&
        propName != "OutputNormalizationWorkspace") {
      binMD->setPropertyValue(propName, (*it)->value());
    }
  }
  binMD->executeAsChildAlg();
  Workspace_sptr outputWS = binMD->getProperty("OutputWorkspace");
  return boost::dynamic_pointer_cast<MDHistoWorkspace>(outputWS);
}
コード例 #30
0
API::MatrixWorkspace_sptr HRPDSlabCanAbsorption::runFlatPlateAbsorption() {
  MatrixWorkspace_sptr m_inputWS = getProperty("InputWorkspace");
  double sigma_atten = getProperty("SampleAttenuationXSection"); // in barns
  double sigma_s = getProperty("SampleScatteringXSection");      // in barns
  double rho = getProperty("SampleNumberDensity"); // in Angstroms-3
  const Material &sampleMaterial = m_inputWS->sample().getMaterial();
  if (sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) !=
      0.0) {
    if (rho == EMPTY_DBL())
      rho = sampleMaterial.numberDensity();
    if (sigma_s == EMPTY_DBL())
      sigma_s =
          sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda);
    if (sigma_atten == EMPTY_DBL())
      sigma_atten = sampleMaterial.absorbXSection(NeutronAtom::ReferenceLambda);
  } else // Save input in Sample with wrong atomic number and name
  {
    NeutronAtom neutron(static_cast<uint16_t>(EMPTY_DBL()),
                        static_cast<uint16_t>(0), 0.0, 0.0, sigma_s, 0.0,
                        sigma_s, sigma_atten);
    Object shape = m_inputWS->sample().getShape(); // copy
    shape.setMaterial(Material("SetInSphericalAbsorption", neutron, rho));
    m_inputWS->mutableSample().setShape(shape);
  }

  // Call FlatPlateAbsorption as a Child Algorithm
  IAlgorithm_sptr childAlg =
      createChildAlgorithm("FlatPlateAbsorption", 0.0, 0.9);
  // Pass through all the properties
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", m_inputWS);
  childAlg->setProperty<double>("AttenuationXSection", sigma_atten);
  childAlg->setProperty<double>("ScatteringXSection", sigma_s);
  childAlg->setProperty<double>("SampleNumberDensity", rho);
  childAlg->setProperty<int64_t>("NumberOfWavelengthPoints",
                                 getProperty("NumberOfWavelengthPoints"));
  childAlg->setProperty<std::string>("ExpMethod", getProperty("ExpMethod"));
  // The height and width of the sample holder are standard for HRPD
  const double HRPDCanHeight = 2.3;
  const double HRPDCanWidth = 1.8;
  childAlg->setProperty("SampleHeight", HRPDCanHeight);
  childAlg->setProperty("SampleWidth", HRPDCanWidth);
  // Valid values are 0.2,0.5,1.0 & 1.5 - would be nice to have a numeric list
  // validator
  const std::string thickness = getPropertyValue("Thickness");
  childAlg->setPropertyValue("SampleThickness", thickness);
  childAlg->executeAsChildAlg();
  return childAlg->getProperty("OutputWorkspace");
}