Example #1
0
/**
 * Execute the algorithm
 */
void LoadRKH::exec() {
  using namespace Mantid::Kernel;
  using namespace Mantid::API;

  // Retrieve filename and try to open the file
  std::string filename = getPropertyValue("Filename");

  m_fileIn.open(filename.c_str());
  if (!m_fileIn) {
    g_log.error("Unable to open file " + filename);
    throw Exception::FileError("Unable to open File: ", filename);
  }
  g_log.information() << "Opened file \"" << filename << "\" for reading\n";

  std::string line;
  // The first line contains human readable information about the original
  // workspace that we don't need
  getline(m_fileIn, line);
  getline(m_fileIn, line);

  // Use one line of the file to diagnose if it is 1D or 2D, this line contains
  // some data required by the 2D data reader
  MatrixWorkspace_sptr result = is2D(line) ? read2D(line) : read1D();

  // all RKH files contain distribution data
  result->setDistribution(true);
  // Set the output workspace
  setProperty("OutputWorkspace", result);
}
Example #2
0
/**
 * 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;
}
Example #3
0
/**
 * Creates the output workspace for this algorithm
 * @param inputWorkspace A parent workspace to initialize from.
 * @return A pointer to the output workspace.
 */
API::MatrixWorkspace_sptr Transpose::createOutputWorkspace(
    API::MatrixWorkspace_const_sptr inputWorkspace) {
  Mantid::API::Axis *yAxis = getVerticalAxis(inputWorkspace);
  const size_t oldNhist = inputWorkspace->getNumberHistograms();
  const auto &inX = inputWorkspace->x(0);
  const size_t oldYlength = inputWorkspace->blocksize();
  const size_t oldVerticalAxislength = yAxis->length();

  // The input Y axis may be binned so the new X data should be too
  size_t newNhist(oldYlength), newXsize(oldVerticalAxislength),
      newYsize(oldNhist);
  MatrixWorkspace_sptr outputWorkspace = inputWorkspace->cloneEmpty();
  outputWorkspace->initialize(newNhist, newXsize, newYsize);
  outputWorkspace->setTitle(inputWorkspace->getTitle());
  outputWorkspace->setComment(inputWorkspace->getComment());
  outputWorkspace->copyExperimentInfoFrom(inputWorkspace.get());
  outputWorkspace->setYUnit(inputWorkspace->YUnit());
  outputWorkspace->setYUnitLabel(inputWorkspace->YUnitLabel());
  outputWorkspace->setDistribution(inputWorkspace->isDistribution());

  // Create a new numeric axis for Y the same length as the old X array
  // Values come from input X
  API::NumericAxis *newYAxis(nullptr);
  if (inputWorkspace->isHistogramData()) {
    newYAxis = new API::BinEdgeAxis(inX.rawData());
  } else {
    newYAxis = new API::NumericAxis(inX.rawData());
  }

  newYAxis->unit() = inputWorkspace->getAxis(0)->unit();
  outputWorkspace->getAxis(0)->unit() = inputWorkspace->getAxis(1)->unit();
  outputWorkspace->replaceAxis(1, newYAxis);
  setProperty("OutputWorkspace", outputWorkspace);
  return outputWorkspace;
}
Example #4
0
MatrixWorkspace_sptr MonteCarloAbsorption::createOutputWorkspace(
    const MatrixWorkspace &inputWS) const {
  MatrixWorkspace_sptr outputWS = inputWS.clone();
  // The algorithm computes the signal values at bin centres so they should
  // be treated as a distribution
  outputWS->setDistribution(true);
  outputWS->setYUnit("");
  outputWS->setYUnitLabel("Attenuation factor");
  return outputWS;
}
MatrixWorkspace_sptr CalculateCarpenterSampleCorrection::createOutputWorkspace(
    const MatrixWorkspace_sptr &inputWksp, const std::string ylabel) const {
  MatrixWorkspace_sptr outputWS = create<HistoWorkspace>(*inputWksp);
  // The algorithm computes the signal values at bin centres so they should
  // be treated as a distribution
  outputWS->setDistribution(true);
  outputWS->setYUnit("");
  outputWS->setYUnitLabel(ylabel);
  return outputWS;
}
Example #6
0
/** Initialize a workspace from its parent
 * This sets values such as title, instrument, units, sample, spectramap.
 * This does NOT copy any data.
 *
 * @param parent :: the parent workspace
 * @param child :: the child workspace
 * @param differentSize :: A flag to indicate if the two workspace will be
 *different sizes
 */
void WorkspaceFactoryImpl::initializeFromParent(
    const MatrixWorkspace_const_sptr parent, const MatrixWorkspace_sptr child,
    const bool differentSize) const {
  child->setTitle(parent->getTitle());
  child->setComment(parent->getComment());
  child->setInstrument(parent->getInstrument()); // This call also copies the
                                                 // SHARED POINTER to the
                                                 // parameter map
  // This call will (should) perform a COPY of the parameter map.
  child->instrumentParameters();
  child->m_sample = parent->m_sample;
  child->m_run = parent->m_run;
  child->setYUnit(parent->m_YUnit);
  child->setYUnitLabel(parent->m_YUnitLabel);
  child->setDistribution(parent->isDistribution());

  // Only copy the axes over if new sizes are not given
  if (!differentSize) {
    // Only copy mask map if same size for now. Later will need to check
    // continued validity.
    child->m_masks = parent->m_masks;
  }

  // Same number of histograms = copy over the spectra data
  if (parent->getNumberHistograms() == child->getNumberHistograms()) {
    for (size_t wi = 0; wi < parent->getNumberHistograms(); wi++) {
      auto &childSpec = child->getSpectrum(wi);
      const auto &parentSpec = parent->getSpectrum(wi);
      // Copy spectrum number and detector IDs
      childSpec.copyInfoFrom(parentSpec);
    }
  }

  // deal with axis
  for (size_t i = 0; i < parent->m_axes.size(); ++i) {
    const size_t newAxisLength = child->getAxis(i)->length();
    const size_t oldAxisLength = parent->getAxis(i)->length();

    if (!differentSize || newAxisLength == oldAxisLength) {
      // Need to delete the existing axis created in init above
      delete child->m_axes[i];
      // Now set to a copy of the parent workspace's axis
      child->m_axes[i] = parent->m_axes[i]->clone(child.get());
    } else {
      if (!parent->getAxis(i)->isSpectra()) // WHY???
      {
        delete child->m_axes[i];
        // Call the 'different length' clone variant
        child->m_axes[i] = parent->m_axes[i]->clone(newAxisLength, child.get());
      }
    }
  }

  return;
}
MatrixWorkspace_sptr
JoinISISPolarizationEfficiencies::interpolateHistogramWorkspace(
    MatrixWorkspace_sptr ws, size_t const maxSize) {
  ws->setDistribution(true);
  auto const &x = ws->x(0);
  auto const dX = (x.back() - x.front()) / double(maxSize);
  std::vector<double> params(2 * maxSize + 1);
  for (size_t i = 0; i < maxSize; ++i) {
    params[2 * i] = x.front() + dX * double(i);
    params[2 * i + 1] = dX;
  }
  params.back() = x.back();
  auto alg = createChildAlgorithm("InterpolatingRebin");
  alg->setProperty("InputWorkspace", ws);
  alg->setProperty("Params", params);
  alg->setProperty("OutputWorkspace", "dummy");
  alg->execute();
  MatrixWorkspace_sptr interpolatedWS = alg->getProperty("OutputWorkspace");
  assert(interpolatedWS->y(0).size() == maxSize);
  assert(interpolatedWS->x(0).size() == maxSize + 1);
  return interpolatedWS;
}
Example #8
0
/** Creates the output workspace, its size, units, etc.
*  @param binParams the bin boundary specification using the same same syntax as
* param the Rebin algorithm
*  @return A pointer to the newly-created workspace
*/
API::MatrixWorkspace_sptr
Q1D2::setUpOutputWorkspace(const std::vector<double> &binParams) const {
  // Calculate the output binning
  HistogramData::BinEdges XOut(0);
  size_t sizeOut = static_cast<size_t>(VectorHelper::createAxisFromRebinParams(
      binParams, XOut.mutableRawData()));

  // Now create the output workspace
  MatrixWorkspace_sptr outputWS =
      WorkspaceFactory::Instance().create(m_dataWS, 1, sizeOut, sizeOut - 1);
  outputWS->getAxis(0)->unit() =
      UnitFactory::Instance().create("MomentumTransfer");
  outputWS->setYUnitLabel("1/cm");

  // Set the X vector for the output workspace
  outputWS->setBinEdges(0, XOut);
  outputWS->setDistribution(true);

  outputWS->getSpectrum(0).clearDetectorIDs();
  outputWS->getSpectrum(0).setSpectrumNo(1);

  return outputWS;
}
void SANSSolidAngleCorrection::exec() {
  // Reduction property manager
  const std::string reductionManagerName = getProperty("ReductionProperties");
  boost::shared_ptr<PropertyManager> reductionManager;
  if (PropertyManagerDataService::Instance().doesExist(reductionManagerName)) {
    reductionManager =
        PropertyManagerDataService::Instance().retrieve(reductionManagerName);
  } else {
    reductionManager = boost::make_shared<PropertyManager>();
    PropertyManagerDataService::Instance().addOrReplace(reductionManagerName,
                                                        reductionManager);
  }

  // If the solid angle algorithm isn't in the reduction properties, add it
  if (!reductionManager->existsProperty("SolidAngleAlgorithm")) {
    auto algProp = make_unique<AlgorithmProperty>("SolidAngleAlgorithm");
    algProp->setValue(toString());
    reductionManager->declareProperty(std::move(algProp));
  }

  MatrixWorkspace_const_sptr inputWS = getProperty("InputWorkspace");
  DataObjects::EventWorkspace_const_sptr inputEventWS =
      boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
  if (inputEventWS)
    return execEvent();

  // Now create the output workspace
  MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");
  if (outputWS != inputWS) {
    outputWS = WorkspaceFactory::Instance().create(inputWS);
    outputWS->setDistribution(true);
    outputWS->setYUnit("");
    outputWS->setYUnitLabel("Steradian");
    setProperty("OutputWorkspace", outputWS);
  }

  const int numHists = static_cast<int>(inputWS->getNumberHistograms());
  Progress progress(this, 0.0, 1.0, numHists);

  // Number of X bins
  const int xLength = static_cast<int>(inputWS->readY(0).size());

  PARALLEL_FOR2(outputWS, inputWS)
  for (int i = 0; i < numHists; ++i) {
    PARALLEL_START_INTERUPT_REGION
    outputWS->dataX(i) = inputWS->readX(i);

    IDetector_const_sptr det;
    try {
      det = inputWS->getDetector(i);
    } catch (Exception::NotFoundError &) {
      g_log.warning() << "Workspace index " << i
                      << " has no detector assigned to it - discarding\n";
      // Catch if no detector. Next line tests whether this happened - test
      // placed
      // outside here because Mac Intel compiler doesn't like 'continue' in a
      // catch
      // in an openmp block.
    }
    // If no detector found, skip onto the next spectrum
    if (!det)
      continue;

    // Skip if we have a monitor or if the detector is masked.
    if (det->isMonitor() || det->isMasked())
      continue;

    const MantidVec &YIn = inputWS->readY(i);
    const MantidVec &EIn = inputWS->readE(i);

    MantidVec &YOut = outputWS->dataY(i);
    MantidVec &EOut = outputWS->dataE(i);

    // Compute solid angle correction factor
    const bool is_tube = getProperty("DetectorTubes");
    const bool is_wing = getProperty("DetectorWing");

    const double tanTheta = tan(inputWS->detectorTwoTheta(*det));
    const double theta_term = sqrt(tanTheta * tanTheta + 1.0);
    double corr;
    if (is_tube || is_wing) {
      const double tanAlpha = tan(getYTubeAngle(det, inputWS));
      const double alpha_term = sqrt(tanAlpha * tanAlpha + 1.0);
      if (is_tube)
        corr = alpha_term * theta_term * theta_term;
      else // if (is_wing) {
        corr = alpha_term;
    } else {
      corr = theta_term * theta_term * theta_term;
    }

    // Correct data for all X bins
    for (int j = 0; j < xLength; j++) {
      YOut[j] = YIn[j] * corr;
      EOut[j] = fabs(EIn[j] * corr);
    }
    progress.report("Solid Angle Correction");
    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION
  setProperty("OutputMessage", "Solid angle correction applied");
}
Example #10
0
Workspace_sptr SeqDomainSpectrumCreator::createOutputWorkspace(
    const std::string &baseName, IFunction_sptr function,
    boost::shared_ptr<FunctionDomain> domain,
    boost::shared_ptr<FunctionValues> values,
    const std::string &outputWorkspacePropertyName) {
  // don't need values, since the values need to be calculated spectrum by
  // spectrum (see loop below).
  UNUSED_ARG(values);

  boost::shared_ptr<SeqDomain> seqDomain =
      boost::dynamic_pointer_cast<SeqDomain>(domain);

  if (!seqDomain) {
    throw std::invalid_argument("CreateOutputWorkspace requires SeqDomain.");
  }

  if (!m_matrixWorkspace) {
    throw std::invalid_argument("No MatrixWorkspace assigned. Cannot construct "
                                "proper output workspace.");
  }

  MatrixWorkspace_sptr outputWs = boost::dynamic_pointer_cast<MatrixWorkspace>(
      WorkspaceFactory::Instance().create(m_matrixWorkspace));

  // Assign y-values, taking into account masked detectors
  for (size_t i = 0; i < seqDomain->getNDomains(); ++i) {
    FunctionDomain_sptr localDomain;
    FunctionValues_sptr localValues;

    seqDomain->getDomainAndValues(i, localDomain, localValues);
    function->function(*localDomain, *localValues);

    boost::shared_ptr<FunctionDomain1DSpectrum> spectrumDomain =
        boost::dynamic_pointer_cast<FunctionDomain1DSpectrum>(localDomain);

    if (spectrumDomain) {
      size_t wsIndex = spectrumDomain->getWorkspaceIndex();

      auto &yValues = outputWs->mutableY(wsIndex);
      for (size_t j = 0; j < yValues.size(); ++j) {
        yValues[j] = localValues->getCalculated(j);
      }
    }
  }

  // Assign x-values on all histograms
  for (size_t i = 0; i < m_matrixWorkspace->getNumberHistograms(); ++i) {
    outputWs->setSharedX(i, m_matrixWorkspace->sharedX(i));
  }

  if (m_manager && !outputWorkspacePropertyName.empty()) {
    declareProperty(
        new WorkspaceProperty<MatrixWorkspace>(outputWorkspacePropertyName, "",
                                               Kernel::Direction::Output),
        "Result workspace");

    m_manager->setPropertyValue(outputWorkspacePropertyName,
                                baseName + "Workspace");
    m_manager->setProperty(outputWorkspacePropertyName, outputWs);
  }

  // If the input is a not an EventWorkspace and is a distrubution, then convert
  // the output also to a distribution
  if (!boost::dynamic_pointer_cast<Mantid::API::IEventWorkspace>(
          m_matrixWorkspace)) {
    if (m_matrixWorkspace->isDistribution()) {
      outputWs->setDistribution(true);
    }
  }

  return outputWs;
}