/// Fetch the properties and set the appropriate member variables
void AbsorptionCorrection::retrieveBaseProperties() {
  double sigma_atten = getProperty("AttenuationXSection"); // in barns
  double sigma_s = getProperty("ScatteringXSection");      // in barns
  double rho = getProperty("SampleNumberDensity");         // in Angstroms-3
  const Material &sampleMaterial = m_inputWS->sample().getShape().material();
  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(0, 0, 0.0, 0.0, sigma_s, 0.0, sigma_s, sigma_atten);

    auto shape = boost::shared_ptr<IObject>(
        m_inputWS->sample().getShape().cloneWithMaterial(
            Material("SetInAbsorptionCorrection", neutron, rho)));
    m_inputWS->mutableSample().setShape(shape);
  }
  rho *= 100; // Will give right units in going from
              // mu in cm^-1 to m^-1 for mu*total flight path( in m )

  // NOTE: the angstrom^-2 to barns and the angstrom^-1 to cm^-1
  // will cancel for mu to give units: cm^-1
  m_refAtten = -sigma_atten * rho / NeutronAtom::ReferenceLambda;
  m_scattering = -sigma_s * rho;

  n_lambda = getProperty("NumberOfWavelengthPoints");

  std::string exp_string = getProperty("ExpMethod");
  if (exp_string == "Normal") // Use the system exp function
    EXPONENTIAL = exp;
  else if (exp_string == "FastApprox") // Use the compact approximation
    EXPONENTIAL = fast_exp;

  // Get the energy mode
  const std::string emodeStr = getProperty("EMode");
  // Convert back to an integer representation
  m_emode = 0;
  if (emodeStr == "Direct")
    m_emode = 1;
  else if (emodeStr == "Indirect")
    m_emode = 2;
  // If inelastic, get the fixed energy and convert it to a wavelength
  if (m_emode) {
    const double efixed = getProperty("Efixed");
    Unit_const_sptr energy = UnitFactory::Instance().create("Energy");
    double factor, power;
    energy->quickConversion(*UnitFactory::Instance().create("Wavelength"),
                            factor, power);
    m_lambdaFixed = factor * std::pow(efixed, power);
  }

  // Call the virtual function for any further properties
  retrieveProperties();
}
/// Fetch the properties and set the appropriate member variables
void AnvredCorrection::retrieveBaseProperties() {
  m_smu = getProperty("LinearScatteringCoef"); // in 1/cm
  m_amu = getProperty("LinearAbsorptionCoef"); // in 1/cm
  m_radius = getProperty("Radius");            // in cm
  m_power_th = getProperty("PowerLambda");     // in cm
  const Material &sampleMaterial = m_inputWS->sample().getMaterial();
  if (sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) !=
      0.0) {
    double rho = sampleMaterial.numberDensity();
    if (m_smu == EMPTY_DBL())
      m_smu =
          sampleMaterial.totalScatterXSection(NeutronAtom::ReferenceLambda) *
          rho;
    if (m_amu == EMPTY_DBL())
      m_amu = sampleMaterial.absorbXSection(NeutronAtom::ReferenceLambda) * rho;
  } 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, m_smu, 0.0, m_smu,
                        m_amu);
    Object shape = m_inputWS->sample().getShape(); // copy
    shape.setMaterial(Material("SetInAnvredCorrection", neutron, 1.0));
    m_inputWS->mutableSample().setShape(shape);
  }
  if (m_smu != EMPTY_DBL() && m_amu != EMPTY_DBL())
    g_log.notice() << "LinearScatteringCoef = " << m_smu << " 1/cm\n"
                   << "LinearAbsorptionCoef = " << m_amu << " 1/cm\n"
                   << "Radius = " << m_radius << " cm\n"
                   << "Power Lorentz corrections = " << m_power_th << " \n";
  // Call the virtual function for any further properties
  retrieveProperties();
}
예제 #3
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");
}
예제 #4
0
/** Loads and checks the values passed to the algorithm
 *
 *  @throw invalid_argument if there is an incapatible property value so the algorithm can't continue
 */
void DetectorEfficiencyCorUser::retrieveProperties() {

	// Get the workspaces
	m_inputWS = this->getProperty("InputWorkspace");

	m_outputWS = this->getProperty("OutputWorkspace");

	// If input and output workspaces are not the same, create a new workspace for the output
	if (m_outputWS != this->m_inputWS) {
		m_outputWS = API::WorkspaceFactory::Instance().create(m_inputWS);
	}

	// these first three properties are fully checked by validators
	m_Ei = this->getProperty("IncidentEnergy");
	// If we're not given an Ei, see if one has been set.
	if (m_Ei == EMPTY_DBL()) {
		Mantid::Kernel::Property* prop = m_inputWS->run().getProperty("Ei");
		double val;
		if (!prop || !Strings::convert(prop->value(), val)) {
			throw std::invalid_argument(
					"No Ei value has been set or stored within the run information.");
		}
		m_Ei = val;
		g_log.debug() << "Using stored Ei value " << m_Ei << "\n";
	} else {
		g_log.debug() << "Using user input Ei value: " << m_Ei << "\n";
	}
}
예제 #5
0
/** Returns whether algorithm parameter was left as default EMPTY_INT,LONG,DBL
 *  @returns True if param was unset and value = EMPTY_XXX, else false
 */
bool PropertyHistory::isEmptyDefault() const {
  bool emptyDefault = false;

  // Static lists to be initialised on first call
  static std::vector<std::string> numberTypes, emptyValues;
  // Type strings corresponding to numbers
  if (numberTypes.empty()) {
    numberTypes.push_back(getUnmangledTypeName(typeid(int)));
    numberTypes.push_back(getUnmangledTypeName(typeid(int64_t)));
    numberTypes.push_back(getUnmangledTypeName(typeid(double)));
  }
  // Empty values
  if (emptyValues.empty()) {
    emptyValues.push_back(std::to_string(EMPTY_INT()));
    emptyValues.push_back(boost::lexical_cast<std::string>(EMPTY_DBL()));
    emptyValues.push_back(std::to_string(EMPTY_LONG()));
  }

  // If default, input, number type and matches empty value then return true
  if (m_isDefault && m_direction != Direction::Output) {
    if (std::find(numberTypes.begin(), numberTypes.end(), m_type) !=
        numberTypes.end()) {
      if (std::find(emptyValues.begin(), emptyValues.end(), m_value) !=
          emptyValues.end()) {
        emptyDefault = true;
      }
    }
  }
  return emptyDefault;
}
예제 #6
0
/** Initialize the algorithm's properties.
 */
void ReflectometrySumInQ::init() {
  auto inputWSValidator = boost::make_shared<Kernel::CompositeValidator>();
  inputWSValidator->add<API::WorkspaceUnitValidator>("Wavelength");
  inputWSValidator->add<API::InstrumentValidator>();
  auto mandatoryNonnegative = boost::make_shared<Kernel::CompositeValidator>();
  mandatoryNonnegative->add<Kernel::MandatoryValidator<double>>();
  auto nonnegative = boost::make_shared<Kernel::BoundedValidator<double>>();
  nonnegative->setLower(0.);
  mandatoryNonnegative->add(nonnegative);
  declareWorkspaceInputProperties<API::MatrixWorkspace,
                                  API::IndexType::SpectrumNum |
                                      API::IndexType::WorkspaceIndex>(
      Prop::INPUT_WS, "A workspace in X units of wavelength to be summed.",
      inputWSValidator);
  declareProperty(
      Kernel::make_unique<API::WorkspaceProperty<API::MatrixWorkspace>>(
          Prop::OUTPUT_WS, "", Kernel::Direction::Output),
      "A single histogram workspace containing the result of summation in Q.");
  declareProperty(
      Prop::BEAM_CENTRE, EMPTY_DBL(), mandatoryNonnegative,
      "Fractional workspace index of the specular reflection centre.");
  declareProperty(Prop::IS_FLAT_SAMPLE, true,
                  "If true, the summation is handled as the standard divergent "
                  "beam case, otherwise as the non-flat sample case.");
  declareProperty(Prop::PARTIAL_BINS, false,
                  "If true, use the full projected wavelength range possibly "
                  "including partially filled bins.");
}
예제 #7
0
/** Loads and checks the values passed to the algorithm
*
*  @throw invalid_argument if there is an incapatible property value so the algorithm can't continue
*/
void DetectorEfficiencyCor::retrieveProperties()
{
  // these first three properties are fully checked by validators
  m_inputWS = getProperty("InputWorkspace");
  m_paraMap = &(m_inputWS->instrumentParameters());

  m_Ei = getProperty("IncidentEnergy");
  // If we're not given an Ei, see if one has been set.
  if( m_Ei == EMPTY_DBL() )
  {
    if( m_inputWS->run().hasProperty("Ei") )
    {
      Kernel::Property* eiprop = m_inputWS->run().getProperty("Ei");
      m_Ei = boost::lexical_cast<double>(eiprop->value());
      g_log.debug() << "Using stored Ei value " << m_Ei << "\n";
    }
    else
    {
      throw std::invalid_argument("No Ei value has been set or stored within the run information.");
    }
  }

  m_outputWS = getProperty("OutputWorkspace");
  // If input and output workspaces are not the same, create a new workspace for the output
  if (m_outputWS != m_inputWS )
  {
    m_outputWS = WorkspaceFactory::Instance().create(m_inputWS);
  }
}
예제 #8
0
/**
 * Applies offset, crops and rebin the workspace according to specified params.
 * @param ws :: Workspace to correct
 * @param loadedTimeZero :: Time zero of the data, so we can calculate the
 * offset
 * @return Corrected workspace
 */
MatrixWorkspace_sptr MuonLoad::correctWorkspace(MatrixWorkspace_sptr ws,
                                                double loadedTimeZero) {
  // Offset workspace, if need to
  double timeZero = getProperty("TimeZero");
  if (timeZero != EMPTY_DBL()) {
    double offset = loadedTimeZero - timeZero;

    IAlgorithm_sptr changeOffset = createChildAlgorithm("ChangeBinOffset");
    changeOffset->setProperty("InputWorkspace", ws);
    changeOffset->setProperty("Offset", offset);
    changeOffset->execute();

    ws = changeOffset->getProperty("OutputWorkspace");
  }

  // Crop workspace, if need to
  double Xmin = getProperty("Xmin");
  double Xmax = getProperty("Xmax");
  if (Xmin != EMPTY_DBL() || Xmax != EMPTY_DBL()) {
    IAlgorithm_sptr crop = createChildAlgorithm("CropWorkspace");
    crop->setProperty("InputWorkspace", ws);

    if (Xmin != EMPTY_DBL())
      crop->setProperty("Xmin", Xmin);

    if (Xmax != EMPTY_DBL())
      crop->setProperty("Xmax", Xmax);

    crop->execute();

    ws = crop->getProperty("OutputWorkspace");
  }

  // Rebin workspace if need to
  std::vector<double> rebinParams = getProperty("RebinParams");
  if (!rebinParams.empty()) {
    IAlgorithm_sptr rebin = createChildAlgorithm("Rebin");
    rebin->setProperty("InputWorkspace", ws);
    rebin->setProperty("Params", rebinParams);
    rebin->setProperty("FullBinsOnly", true);
    rebin->execute();

    ws = rebin->getProperty("OutputWorkspace");
  }

  return ws;
}
/**
 * Get end time for fit
 * If it's not there, use the last available time in the workspace.
 * @return :: End time for fit
 */
double CalMuonDetectorPhases::getEndTime() const {
  double endTime = getProperty("LastGoodData");
  if (endTime == EMPTY_DBL()) {
    // Last available time
    endTime = m_inputWS->readX(0).back();
  }
  return endTime;
}
예제 #10
0
파일: Fit1D.cpp 프로젝트: spaceyatom/mantid
/** Initialisation method
 */
void Fit1D::init() {
  declareProperty(new WorkspaceProperty<MatrixWorkspace>("InputWorkspace", "",
                                                         Direction::Input),
                  "Name of the input Workspace");

  auto mustBePositive = boost::make_shared<BoundedValidator<int>>();
  mustBePositive->setLower(0);
  declareProperty("WorkspaceIndex", 0, mustBePositive,
                  "The Workspace to fit, uses the workspace numbering of the "
                  "spectra (default 0)");
  declareProperty("StartX", EMPTY_DBL(), "A value of x in, or on the low x "
                                         "boundary of, the first bin to "
                                         "include in\n"
                                         "the fit (default lowest value of x)");
  declareProperty("EndX", EMPTY_DBL(), "A value in, or on the high x boundary "
                                       "of, the last bin the fitting range\n"
                                       "(default the highest value of x)");

  size_t i0 = getProperties().size();

  // declare parameters specific to a given fitting function
  declareParameters();

  // load the name of these specific parameter into a vector for later use
  const std::vector<Property *> props = getProperties();
  for (size_t i = i0; i < props.size(); i++) {
    m_parameterNames.push_back(props[i]->name());
  }

  declareProperty("Fix", "", "A list of comma separated parameter names which "
                             "should be fixed in the fit");
  declareProperty(
      "MaxIterations", 500, mustBePositive,
      "Stop after this number of iterations if a good fit is not found");
  declareProperty("OutputStatus", "", Direction::Output);
  declareProperty("OutputChi2overDoF", 0.0, Direction::Output);

  // Disable default gsl error handler (which is to call abort!)
  gsl_set_error_handler_off();

  declareAdditionalProperties();

  declareProperty("Output", "", "If not empty OutputParameters TableWorksace "
                                "and OutputWorkspace will be created.");
}
예제 #11
0
/**
 * @brief Calculate function values on an energy domain
 * @param out array to store function values
 * @param xValues energy domain where function is evaluated
 * @param nData size of the energy domain
 * @exception No Q values can be found in associated attributes
 */
void InelasticDiffSphere::function1D(double *out, const double *xValues,
                                     const size_t nData) const {
  auto I = this->getParameter("Intensity");
  auto R = this->getParameter("Radius");
  auto D = this->getParameter("Diffusion");
  auto S = this->getParameter("Shift");

  double Q;
  if (this->getAttribute("Q").asDouble() == EMPTY_DBL()) {
    if (m_qValueCache.empty()) {
      throw std::runtime_error(
          "No Q attribute provided and cannot retrieve from worksapce.");
    }

    auto specIdx = this->getAttribute("WorkspaceIndex").asInt();
    Q = m_qValueCache[specIdx];

    g_log.debug() << "Get Q value for workspace index " << specIdx << ": " << Q
                  << '\n';
  } else {
    Q = this->getAttribute("Q").asDouble();

    g_log.debug() << "Using Q attribute: " << Q << '\n';
  }

  // // Penalize negative parameters
  if (I < std::numeric_limits<double>::epsilon() ||
      R < std::numeric_limits<double>::epsilon() ||
      D < std::numeric_limits<double>::epsilon()) {
    for (size_t i = 0; i < nData; i++) {
      out[i] = std::numeric_limits<double>::infinity();
    }
    return;
  }

  // List of Lorentzian HWHM
  std::vector<double> HWHM;
  size_t ncoeff = m_xnl.size();
  for (size_t n = 0; n < ncoeff; n++) {
    auto x = m_xnl[n].x; // eigenvalue
    HWHM.push_back(m_hbar * x * x * D / (R * R));
  }

  std::vector<double> YJ;
  YJ = this->LorentzianCoefficients(Q * R); // The (2l+1)*A_{n,l}
  for (size_t i = 0; i < nData; i++) {
    double energy = xValues[i] - S; // from meV to THz (or from micro-eV to PHz)
    out[i] = 0.0;
    for (size_t n = 0; n < ncoeff; n++) {
      double L = (1.0 / M_PI) * HWHM[n] /
                 (HWHM[n] * HWHM[n] + energy * energy); // Lorentzian
      out[i] += I * YJ[n] * L;
    }
  }
}
예제 #12
0
/*
 * Get instrument property as double
 * @s - input property name
 *
 */
double
LoadHelper::getInstrumentProperty(const API::MatrixWorkspace_sptr &workspace,
                                  std::string s) {
    std::vector<std::string> prop =
        workspace->getInstrument()->getStringParameter(s);
    if (prop.empty()) {
        g_log.debug("Property <" + s + "> doesn't exist!");
        return EMPTY_DBL();
    } else {
        g_log.debug() << "Property <" + s + "> = " << prop[0] << '\n';
        return boost::lexical_cast<double>(prop[0]);
    }
}
예제 #13
0
double
ConvertSpectrumAxis::getEfixed(const Mantid::Geometry::IDetector &detector,
                               MatrixWorkspace_const_sptr inputWS,
                               int emode) const {
  double efixed(0);
  double efixedProp = getProperty("Efixed");
  if (efixedProp != EMPTY_DBL()) {
    efixed = efixedProp;
    g_log.debug() << "Detector: " << detector.getID() << " Efixed: " << efixed
                  << "\n";
  } else {
    if (emode == 1) {
      if (inputWS->run().hasProperty("Ei")) {
        Kernel::Property *p = inputWS->run().getProperty("Ei");
        Kernel::PropertyWithValue<double> *doublep =
            dynamic_cast<Kernel::PropertyWithValue<double> *>(p);
        if (doublep) {
          efixed = (*doublep)();
        } else {
          efixed = 0.0;
          g_log.warning() << "Efixed could not be found for detector "
                          << detector.getID() << ", set to 0.0\n";
        }
      } else {
        efixed = 0.0;
        g_log.warning() << "Efixed could not be found for detector "
                        << detector.getID() << ", set to 0.0\n";
      }
    } else if (emode == 2) {
      std::vector<double> efixedVec = detector.getNumberParameter("Efixed");
      if (efixedVec.empty()) {
        int detid = detector.getID();
        IDetector_const_sptr detectorSingle =
            inputWS->getInstrument()->getDetector(detid);
        efixedVec = detectorSingle->getNumberParameter("Efixed");
      }
      if (!efixedVec.empty()) {
        efixed = efixedVec.at(0);
        g_log.debug() << "Detector: " << detector.getID()
                      << " EFixed: " << efixed << "\n";
      } else {
        efixed = 0.0;
        g_log.warning() << "Efixed could not be found for detector "
                        << detector.getID() << ", set to 0.0\n";
      }
    }
  }
  return efixed;
}
예제 #14
0
/**
 * Get start time for fit
 * If not provided as input, try to read from workspace logs.
 * If it's not there either, set to 0 and warn user.
 * @return :: Start time for fit
 */
double CalMuonDetectorPhases::getStartTime() const {
  double startTime = getProperty("FirstGoodData");
  if (startTime == EMPTY_DBL()) {
    try {
      // Read FirstGoodData from workspace logs if possible
      double firstGoodData =
          m_inputWS->run().getLogAsSingleValue("FirstGoodData");
      startTime = firstGoodData;
    } catch (...) {
      g_log.warning("Couldn't read FirstGoodData, setting to 0");
      startTime = 0.;
    }
  }
  return startTime;
}
예제 #15
0
/**
 * @brief Learn the Q values from the workspace, if possible, and update
 * attribute Q accordingly.
 * @param workspace Matrix workspace
 * @param wi selected spectrum to initialize attributes
 * @param startX unused
 * @param endX unused
 */
void FunctionQDepends::setMatrixWorkspace(
    boost::shared_ptr<const Mantid::API::MatrixWorkspace> workspace, size_t wi,
    double startX, double endX) {
  UNUSED_ARG(startX);
  UNUSED_ARG(endX);
  // reset attributes if new workspace is passed
  if (!m_vQ.empty()) {
    Mantid::API::IFunction::setAttribute("WorkspaceIndex", Attr(EMPTY_INT()));
    Mantid::API::IFunction::setAttribute("Q", Attr(EMPTY_DBL()));
  }
  // Obtain Q values from the passed workspace, if possible. m_vQ will be
  // cleared if unsuccessful.
  if (workspace) {
    m_vQ = this->extractQValues(*workspace);
  }
  if (!m_vQ.empty()) {
    this->setAttribute("WorkspaceIndex", Attr(static_cast<int>(wi)));
  }
}
예제 #16
0
/** Compute the detector rotation angle around origin and optionally set the
 *  OutputBeamPosition property.
 *  @return a rotation angle
 */
double LoadILLReflectometry::detectorRotation() {
  ITableWorkspace_const_sptr posTable = getProperty("DirectBeamPosition");
  const double peakCentre = reflectometryPeak();
  g_log.debug() << "Using detector angle (degrees): " << m_detectorAngle
                << '\n';
  const double deflection = collimationAngle();
  if (!isDefault("OutputBeamPosition")) {
    PeakInfo p;
    p.detectorAngle = m_detectorAngle;
    p.detectorDistance = m_detectorDistance;
    p.peakCentre = peakCentre;
    setProperty("OutputBeamPosition", createPeakPositionTable(p));
  }
  const double userAngle = getProperty("BraggAngle");
  const double offset =
      offsetAngle(peakCentre, PIXEL_CENTER, m_detectorDistance);
  m_log.debug() << "Beam offset angle: " << offset << '\n';
  if (userAngle != EMPTY_DBL()) {
    if (posTable) {
      g_log.notice()
          << "Ignoring DirectBeamPosition, using BraggAngle instead.";
    }
    return 2 * userAngle - offset;
  }
  if (!posTable) {
    if (deflection != 0) {
      g_log.debug() << "Using incident deflection angle (degrees): "
                    << deflection << '\n';
    }
    return m_detectorAngle + deflection;
  }
  const auto dbPeak = parseBeamPositionTable(*posTable);
  const double dbOffset =
      offsetAngle(dbPeak.peakCentre, PIXEL_CENTER, dbPeak.detectorDistance);
  m_log.debug() << "Direct beam offset angle: " << dbOffset << '\n';
  const double detectorAngle =
      m_detectorAngle - dbPeak.detectorAngle - dbOffset;
  m_log.debug() << "Direct beam calibrated detector angle: " << detectorAngle
                << '\n';
  return detectorAngle;
}
예제 #17
0
/**
 * Returns the frequency hint to use as a starting point for finding the
 * frequency.
 *
 * If user has provided a frequency (MHz) as input, use that converted to
 * Mrad/s.
 * Otherwise, use 2*pi*g_mu*(sample_magn_field).
 * (2*pi to convert MHz to Mrad/s)
 *
 * @return :: Frequency hint to use in Mrad/s
 */
double CalMuonDetectorPhases::getFrequencyHint() const {
  double freq = getProperty("Frequency");

  if (freq == EMPTY_DBL()) {
    try {
      // Read sample_magn_field from workspace logs
      freq = m_inputWS->run().getLogAsSingleValue("sample_magn_field");
      // Multiply by muon gyromagnetic ratio: 0.01355 MHz/G
      freq *= PhysicalConstants::MuonGyromagneticRatio;
    } catch (...) {
      throw std::runtime_error(
          "Couldn't read sample_magn_field. Please provide a value for "
          "the frequency");
    }
  }

  // Convert from MHz to Mrad/s
  freq *= 2 * M_PI;

  return freq;
}
예제 #18
0
double ConvertSpectrumAxis2::getEfixed(IDetector_const_sptr detector,
                                       MatrixWorkspace_const_sptr inputWS,
                                       int emode) const {
  double efixed(0);
  double efixedProp = getProperty("Efixed");
  if (efixedProp != EMPTY_DBL()) {
    efixed = efixedProp;
    g_log.debug() << "Detector: " << detector->getID() << " Efixed: " << efixed
                  << "\n";
  } else {
    if (emode == 1) {
      if (inputWS->run().hasProperty("Ei")) {
        efixed = inputWS->run().getLogAsSingleValue("Ei");
      } else {
        throw std::invalid_argument("Could not retrieve Efixed from the "
                                    "workspace. Please provide a value.");
      }
    } else if (emode == 2) {
      std::vector<double> efixedVec = detector->getNumberParameter("Efixed");
      if (efixedVec.empty()) {
        int detid = detector->getID();
        IDetector_const_sptr detectorSingle =
            inputWS->getInstrument()->getDetector(detid);
        efixedVec = detectorSingle->getNumberParameter("Efixed");
      }
      if (!efixedVec.empty()) {
        efixed = efixedVec.at(0);
        g_log.debug() << "Detector: " << detector->getID()
                      << " EFixed: " << efixed << "\n";
      } else {
        g_log.warning() << "Efixed could not be found for detector "
                        << detector->getID() << ", please provide a value\n";
        throw std::invalid_argument("Could not retrieve Efixed from the "
                                    "detector. Please provide a value.");
      }
    }
  }
  return efixed;
}
예제 #19
0
/** Executes the algorithm
 *
 *  @throw runtime_error Thrown if algorithm cannot execute
 */
void MaxMin::exec()
{
  // Try and retrieve the optional properties
  m_MinRange = getProperty("RangeLower");
  m_MaxRange = getProperty("RangeUpper");
  m_MinSpec = getProperty("StartWorkspaceIndex");
  m_MaxSpec = getProperty("EndWorkspaceIndex");
  showMin = getProperty("ShowMin");

  // Get the input workspace
  MatrixWorkspace_const_sptr localworkspace = getProperty("InputWorkspace");

  const int numberOfSpectra = static_cast<int>(localworkspace->getNumberHistograms());

  // Check 'StartSpectrum' is in range 0-numberOfSpectra
  if ( m_MinSpec > numberOfSpectra )
  {
    g_log.warning("StartSpectrum out of range! Set to 0.");
    m_MinSpec = 0;
  }
  if ( isEmpty(m_MaxSpec) ) m_MaxSpec = numberOfSpectra-1;
  if ( m_MaxSpec > numberOfSpectra-1 || m_MaxSpec < m_MinSpec )
  {
    g_log.warning("EndSpectrum out of range! Set to max detector number");
    m_MaxSpec = numberOfSpectra;
  }
  if ( m_MinRange > m_MaxRange )
  {
    g_log.warning("Range_upper is less than Range_lower. Will integrate up to frame maximum.");
    m_MaxRange = 0.0;
  }

  // Create the 1D workspace for the output
  MatrixWorkspace_sptr outputWorkspace = API::WorkspaceFactory::Instance().create(localworkspace,m_MaxSpec-m_MinSpec+1,2,1);


  Progress progress(this,0,1,(m_MaxSpec-m_MinSpec+1));
  PARALLEL_FOR2(localworkspace,outputWorkspace)
  // Loop over spectra
  for (int i = m_MinSpec; i <= m_MaxSpec; ++i)
  {
    PARALLEL_START_INTERUPT_REGION
    int newindex=i-m_MinSpec;
    // Copy over spectrum and detector number info
    outputWorkspace->getSpectrum(newindex)->copyInfoFrom(*localworkspace->getSpectrum(i));

    // Retrieve the spectrum into a vector
    const MantidVec& X = localworkspace->readX(i);
    const MantidVec& Y = localworkspace->readY(i);

    // Find the range [min,max]
    MantidVec::const_iterator lowit, highit;
    if (m_MinRange == EMPTY_DBL()) lowit=X.begin();
    else lowit=std::lower_bound(X.begin(),X.end(),m_MinRange);

    if (m_MaxRange == EMPTY_DBL()) highit=X.end();
    else highit=std::find_if(lowit,X.end(),std::bind2nd(std::greater<double>(),m_MaxRange));

    // If range specified doesn't overlap with this spectrum then bail out
    if ( lowit == X.end() || highit == X.begin() ) continue;

    --highit; // Upper limit is the bin before, i.e. the last value smaller than MaxRange

    MantidVec::difference_type distmin=std::distance(X.begin(),lowit);
    MantidVec::difference_type distmax=std::distance(X.begin(),highit);

    MantidVec::const_iterator maxY;
    // Find the max/min element
    if (showMin==true)
    {
      maxY=std::min_element(Y.begin()+distmin,Y.begin()+distmax);
    }
    else
    {
      maxY=std::max_element(Y.begin()+distmin,Y.begin()+distmax);
    }
    MantidVec::difference_type d=std::distance(Y.begin(),maxY);
    // X boundaries for the max/min element
    outputWorkspace->dataX(newindex)[0]=*(X.begin()+d);
    outputWorkspace->dataX(newindex)[1]=*(X.begin()+d+1); //This is safe since X is of dimension Y+1
    outputWorkspace->dataY(newindex)[0]=*maxY;
    progress.report();
    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION

  // Assign it to the output workspace property
  setProperty("OutputWorkspace",outputWorkspace);

  return;
}
예제 #20
0
파일: LoadBBY.cpp 프로젝트: dezed/mantid
/**
 * Initialise the algorithm. Declare properties which can be set before
 * execution (input) or
 * read from after the execution (output).
 */
void LoadBBY::init() {
  // Specify file extensions which can be associated with a specific file.
  std::vector<std::string> exts;

  // Declare the Filename algorithm property. Mandatory. Sets the path to the
  // file to load.
  exts.clear();
  exts.emplace_back(".tar");
  declareProperty(Kernel::make_unique<API::FileProperty>(
                      FilenameStr, "", API::FileProperty::Load, exts),
                  "The input filename of the stored data");

  // mask
  exts.clear();
  exts.emplace_back(".xml");
  declareProperty(Kernel::make_unique<API::FileProperty>(
                      MaskStr, "", API::FileProperty::OptionalLoad, exts),
                  "The input filename of the mask data");

  // OutputWorkspace
  declareProperty(
      Kernel::make_unique<API::WorkspaceProperty<API::IEventWorkspace>>(
          "OutputWorkspace", "", Kernel::Direction::Output));

  // FilterByTofMin
  declareProperty(Kernel::make_unique<Kernel::PropertyWithValue<double>>(
                      FilterByTofMinStr, 0, Kernel::Direction::Input),
                  "Optional: To exclude events that do not fall within a range "
                  "of times-of-flight. "
                  "This is the minimum accepted value in microseconds. Keep "
                  "blank to load all events.");

  // FilterByTofMax
  declareProperty(Kernel::make_unique<Kernel::PropertyWithValue<double>>(
                      FilterByTofMaxStr, EMPTY_DBL(), Kernel::Direction::Input),
                  "Optional: To exclude events that do not fall within a range "
                  "of times-of-flight. "
                  "This is the maximum accepted value in microseconds. Keep "
                  "blank to load all events.");

  // FilterByTimeStart
  declareProperty(
      Kernel::make_unique<Kernel::PropertyWithValue<double>>(
          FilterByTimeStartStr, 0.0, Kernel::Direction::Input),
      "Optional: To only include events after the provided start time, in "
      "seconds (relative to the start of the run).");

  // FilterByTimeStop
  declareProperty(
      Kernel::make_unique<Kernel::PropertyWithValue<double>>(
          FilterByTimeStopStr, EMPTY_DBL(), Kernel::Direction::Input),
      "Optional: To only include events before the provided stop time, in "
      "seconds (relative to the start of the run).");

  // period and phase
  declareProperty(Kernel::make_unique<Kernel::PropertyWithValue<double>>(
                      PeriodMasterStr, EMPTY_DBL(), Kernel::Direction::Input),
                  "Optional");
  declareProperty(Kernel::make_unique<Kernel::PropertyWithValue<double>>(
                      PeriodSlaveStr, EMPTY_DBL(), Kernel::Direction::Input),
                  "Optional");
  declareProperty(Kernel::make_unique<Kernel::PropertyWithValue<double>>(
                      PhaseSlaveStr, EMPTY_DBL(), Kernel::Direction::Input),
                  "Optional");

  std::string grpOptional = "Filters";
  setPropertyGroup(FilterByTofMinStr, grpOptional);
  setPropertyGroup(FilterByTofMaxStr, grpOptional);
  setPropertyGroup(FilterByTimeStartStr, grpOptional);
  setPropertyGroup(FilterByTimeStopStr, grpOptional);

  std::string grpPhaseCorrection = "Phase Correction";
  setPropertyGroup(PeriodMasterStr, grpPhaseCorrection);
  setPropertyGroup(PeriodSlaveStr, grpPhaseCorrection);
  setPropertyGroup(PhaseSlaveStr, grpPhaseCorrection);
}
예제 #21
0
void CorrectKiKf::exec()
{
  // Get the workspaces
  this->inputWS = this->getProperty("InputWorkspace");
  this->outputWS = this->getProperty("OutputWorkspace");

  // If input and output workspaces are not the same, create a new workspace for the output
  if (this->outputWS != this->inputWS)
  {
    this->outputWS = API::WorkspaceFactory::Instance().create(this->inputWS);
  }

  //Check if it is an event workspace
  EventWorkspace_const_sptr eventW = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);
  if (eventW != NULL)
  {
    this->execEvent();
    return;
  }  
  

  const size_t size = this->inputWS->blocksize();
  // Calculate the number of spectra in this workspace
  const int numberOfSpectra = static_cast<int>(this->inputWS->size() / size);
  API::Progress prog(this,0.0,1.0,numberOfSpectra);
  const bool histogram = this->inputWS->isHistogramData();
  bool negativeEnergyWarning = false;
    
  const std::string emodeStr = getProperty("EMode");
  double efixedProp = getProperty("EFixed");

  if( efixedProp == EMPTY_DBL() )
  {
    if (emodeStr == "Direct")
    {
      // Check if it has been store on the run object for this workspace
      if( this->inputWS->run().hasProperty("Ei"))
      {
        Kernel::Property* eiprop = this->inputWS->run().getProperty("Ei");
        efixedProp = boost::lexical_cast<double>(eiprop->value());
        g_log.debug() << "Using stored Ei value " << efixedProp << "\n";
      }
      else
      {
        throw std::invalid_argument("No Ei value has been set or stored within the run information.");
      }
    }
    else
    {
      // If not specified, will try to get Ef from the parameter file for indirect geometry, 
      // but it will be done for each spectrum separately, in case of different analyzer crystals
    }
  }


  PARALLEL_FOR2(inputWS,outputWS)
  for (int64_t i = 0; i < int64_t(numberOfSpectra); ++i)
  {
    PARALLEL_START_INTERUPT_REGION 
    double Efi = 0;
    // Now get the detector object for this histogram to check if monitor
    // or to get Ef for indirect geometry
    if (emodeStr == "Indirect") 
    {
      if ( efixedProp != EMPTY_DBL()) Efi = efixedProp;
      else try 
      {
        IDetector_const_sptr det = inputWS->getDetector(i);
        if (!det->isMonitor())
        {
          std::vector< double >  wsProp=det->getNumberParameter("Efixed");
          if ( wsProp.size() > 0 )
          {
            Efi=wsProp.at(0);
            g_log.debug() << i << " Ef: "<< Efi<<" (from parameter file)\n";     
          }
          else
          { 
            g_log.information() <<"Ef not found for spectrum "<< i << std::endl;
            throw std::invalid_argument("No Ef value has been set or found.");
          }
        }

      }
      catch(std::runtime_error&) { g_log.information() << "Spectrum " << i << ": cannot find detector" << "\n"; }
    }

    MantidVec& yOut = outputWS->dataY(i);
    MantidVec& eOut = outputWS->dataE(i);
    const MantidVec& xIn = inputWS->readX(i);
    const MantidVec& yIn = inputWS->readY(i);
    const MantidVec& eIn = inputWS->readE(i);
    //Copy the energy transfer axis
    outputWS->setX( i, inputWS->refX(i) );
    for (unsigned int j = 0; j < size; ++j)
    {
      const double deltaE = histogram ? 0.5*(xIn[j]+xIn[j+1]) : xIn[j];
      double Ei=0.;
      double Ef=0.;
      double kioverkf = 1.;
      if (emodeStr == "Direct")  //Ei=Efixed
      {
        Ei = efixedProp;
        Ef = Ei - deltaE;
      } else                     //Ef=Efixed
      { 
        Ef = Efi;
        Ei = Efi + deltaE;
      }
      // if Ei or Ef is negative, it should be a warning
      // however, if the intensity is 0 (histogram goes to energy transfer higher than Ei) it is still ok, so no warning.
      if ((Ei <= 0)||(Ef <= 0))
      {
        kioverkf=0.;
        if (yIn[j]!=0) negativeEnergyWarning=true;
      } 
      else kioverkf = std::sqrt( Ei / Ef );

      yOut[j] = yIn[j]*kioverkf;
      eOut[j] = eIn[j]*kioverkf;
    }
    prog.report();
    PARALLEL_END_INTERUPT_REGION
  }//end for i 
  PARALLEL_CHECK_INTERUPT_REGION

  if (negativeEnergyWarning) g_log.information() <<"Ef <= 0 or Ei <= 0 in at least one spectrum!!!!"<<std::endl;
  if ((negativeEnergyWarning) && ( efixedProp == EMPTY_DBL())) g_log.information()<<"Try to set fixed energy"<<std::endl ;
  this->setProperty("OutputWorkspace",this->outputWS);
  return;
}
예제 #22
0
  /** Executes the algorithm
  *
  *  @throw runtime_error Thrown if algorithm cannot execute
  */
  void Fit::exec()
  {
    API::MatrixWorkspace_sptr ws = getProperty("InputWorkspace");
    std::string input = "WorkspaceIndex=" + getPropertyValue("WorkspaceIndex");
    double startX = getProperty("StartX");
    if (startX != EMPTY_DBL())
    {
      input += ",StartX=" + getPropertyValue("StartX");
    }
    double endX = getProperty("EndX");
    if (endX != EMPTY_DBL())
    {
      input += ",EndX=" + getPropertyValue("EndX");
    }

    // Process the Function property and create the function using FunctionFactory
    // fills in m_function_input
    processParameters();

    boost::shared_ptr<GenericFit> fit = boost::dynamic_pointer_cast<GenericFit>(createSubAlgorithm("GenericFit"));
    fit->setChild(false);
    fit->setLogging(false); // No logging of time to run GenericFit
    fit->initialize();
    fit->setProperty("InputWorkspace",boost::dynamic_pointer_cast<API::Workspace>(ws));
    fit->setProperty("Input",input);
    fit->setProperty("Function",m_function_input);
    fit->setProperty("Output",getPropertyValue("Output"));
    fit->setPropertyValue("MaxIterations",getPropertyValue("MaxIterations"));
    fit->setPropertyValue("Minimizer",getPropertyValue("Minimizer"));
    fit->setPropertyValue("CostFunction",getPropertyValue("CostFunction"));
    fit->execute();

    m_function_input = fit->getPropertyValue("Function");
    setProperty("Function",m_function_input);

    // also output summary to properties
    setProperty("OutputStatus", fit->getPropertyValue("OutputStatus"));
    double finalCostFuncVal = fit->getProperty("OutputChi2overDoF");
    setProperty("OutputChi2overDoF", finalCostFuncVal);
    setProperty("Minimizer", fit->getPropertyValue("Minimizer"));

    std::vector<double> errors;
    if (fit->existsProperty("Parameters"))
    {
      // Add Parameters, Errors and ParameterNames properties to output so they can be queried on the algorithm.
      declareProperty(new ArrayProperty<double> ("Parameters",new NullValidator<std::vector<double> >,Direction::Output));
      declareProperty(new ArrayProperty<double> ("Errors",new NullValidator<std::vector<double> >,Direction::Output));
      declareProperty(new ArrayProperty<std::string> ("ParameterNames",new NullValidator<std::vector<std::string> >,Direction::Output));
      std::vector<double> params = fit->getProperty("Parameters");
      errors = fit->getProperty("Errors");
      std::vector<std::string> parNames = fit->getProperty("ParameterNames");

      setProperty("Parameters",params);
      setProperty("Errors",errors);
      setProperty("ParameterNames",parNames);
    }
    
    std::string output = getProperty("Output");
    if (!output.empty())
    {
      // create output parameter table workspace to store final fit parameters 
      // including error estimates if derivative of fitting function defined

      boost::shared_ptr<API::IFunctionMW> funmw = boost::dynamic_pointer_cast<API::IFunctionMW>(fit->getFunction());
      if (funmw)
      {
        declareProperty(new WorkspaceProperty<>("OutputWorkspace","",Direction::Output),
          "Name of the output Workspace holding resulting simlated spectrum");

        setPropertyValue("OutputWorkspace",output+"_Workspace");

        // Save the fitted and simulated spectra in the output workspace
        int workspaceIndex  = getProperty("WorkspaceIndex");
        if (workspaceIndex < 0) throw std::invalid_argument("WorkspaceIndex must be >= 0");
        funmw->setWorkspace(ws,input);
        API::MatrixWorkspace_sptr outws = funmw->createCalculatedWorkspace(ws,workspaceIndex,errors);

        setProperty("OutputWorkspace",outws);
      }
    }

  }
예제 #23
0
bool ReadMaterial::isEmpty(const double toCheck) {
  return std::abs((toCheck - EMPTY_DBL()) / (EMPTY_DBL())) < 1e-8;
}
예제 #24
0
/** Executes the algorithm
 *
 */
void CalculateEfficiency::exec()
{

  // Minimum efficiency. Pixels with lower efficiency will be masked
  double min_eff = getProperty("MinEfficiency");
  // Maximum efficiency. Pixels with higher efficiency will be masked
  double max_eff = getProperty("MaxEfficiency");

  // Get the input workspace
  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
  MatrixWorkspace_sptr rebinnedWS;// = inputWS;

  // Now create the output workspace
  MatrixWorkspace_sptr outputWS;// = getProperty("OutputWorkspace");

 // DataObjects::EventWorkspace_const_sptr inputEventWS = boost::dynamic_pointer_cast<const EventWorkspace>(inputWS);

  // Sum up all the wavelength bins
  IAlgorithm_sptr childAlg = createChildAlgorithm("Integration", 0.0, 0.2);
  childAlg->setProperty<MatrixWorkspace_sptr>("InputWorkspace", inputWS);
  childAlg->executeAsChildAlg();
  rebinnedWS = childAlg->getProperty("OutputWorkspace");

  outputWS = WorkspaceFactory::Instance().create(rebinnedWS);
  WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, false);
  for (int i=0; i<(int)rebinnedWS->getNumberHistograms(); i++)
  {
    outputWS->dataX(i) = rebinnedWS->readX(i);
  }
  setProperty("OutputWorkspace",outputWS);

  double sum = 0.0;
  double err = 0.0;
  int npixels = 0;

  // Loop over spectra and sum all the counts to get normalization
  // Skip monitors and masked detectors
  sumUnmaskedDetectors(rebinnedWS, sum, err, npixels);

  // Normalize each detector pixel by the sum we just found to get the
  // relative efficiency. If the minimum and maximum efficiencies are
  // provided, the pixels falling outside this range will be marked
  // as 'masked' in both the input and output workspace.
  // We mask detectors in the input workspace so that we can resum the
  // counts to find a new normalization factor that takes into account
  // the newly masked detectors.
  normalizeDetectors(rebinnedWS, outputWS, sum, err, npixels, min_eff, max_eff);

  if ( !isEmpty(min_eff) || !isEmpty(max_eff) )
  {
    // Recompute the normalization, excluding the pixels that were outside
    // the acceptable efficiency range.
    sumUnmaskedDetectors(rebinnedWS, sum, err, npixels);

    // Now that we have a normalization factor that excludes bad pixels,
    // recompute the relative efficiency.
    // We pass EMPTY_DBL() to avoid masking pixels that might end up high or low
    // after the new normalization.
    normalizeDetectors(rebinnedWS, outputWS, sum, err, npixels, EMPTY_DBL(), EMPTY_DBL());
  }

  return;
}
예제 #25
0
/** Process and check input properties
 */
void IntegratePeaksCWSD::processInputs() {
  // Required input workspaces
  m_inputWS = getProperty("InputWorkspace");

  // Input peaks
  std::vector<double> peak_center = getProperty("PeakCentre");
  if (peak_center.size() > 0) {
    // assigned peak center
    if (peak_center.size() != 3)
      throw std::invalid_argument("PeakCentre must have 3 elements.");
    m_peakCenter.setX(peak_center[0]);
    m_peakCenter.setY(peak_center[1]);
    m_peakCenter.setZ(peak_center[2]);
    // no use input peak workspace
    m_haveInputPeakWS = false;
    m_useSinglePeakCenterFmUser = true;
  } else {
    // use input peak workspace
    std::string peakWSName = getPropertyValue("PeaksWorkspace");
    if (peakWSName.length() == 0)
      throw std::invalid_argument("It is not allowed that neither peak center "
                                  "nor PeaksWorkspace is specified.");
    m_peaksWS = getProperty("PeaksWorkspace");
    m_haveInputPeakWS = true;
    m_useSinglePeakCenterFmUser = false;
  }
  m_doMergePeak = getProperty("MergePeaks");
  if (m_haveInputPeakWS && m_peaksWS->getNumberPeaks() > 1 && m_doMergePeak) {
    throw std::invalid_argument(
        "It is not allowed to merge peaks when there are "
        "multiple peaks present in PeaksWorkspace.");
  }

  m_normalizeByMonitor = getProperty("NormalizeByMonitor");
  m_normalizeByTime = getProperty("NormalizeByTime");
  if (m_normalizeByMonitor && m_normalizeByTime)
    throw std::invalid_argument(
        "It is not allowed to select to be normalized both  "
        "by time and by monitor counts.");
  if (m_doMergePeak && !(m_normalizeByMonitor || m_normalizeByTime)) {
    throw std::invalid_argument(
        "Either being normalized by time or being normalized "
        "by monitor must be selected if merge-peak is selected.");
  }
  m_scaleFactor = getProperty("ScaleFactor");

  // monitor counts
  if (m_normalizeByMonitor)
    m_runNormMap = getMonitorCounts();
  else if (m_normalizeByTime)
    m_runNormMap = getMeasureTime();

  // go through peak
  if (m_haveInputPeakWS)
    getPeakInformation();
  if (m_runPeakCenterMap.size() > 1)
    m_haveMultipleRun = true;
  else
    m_haveMultipleRun = false;

  // peak related
  m_peakRadius = getProperty("PeakRadius");
  if (m_peakRadius == EMPTY_DBL()) {
    throw std::invalid_argument("Peak radius cannot be left empty.");
  }

  // optional mask workspace
  std::string maskwsname = getPropertyValue("MaskWorkspace");
  if (maskwsname.size() > 0) {
    // process mask workspace
    m_maskDets = true;
    m_maskWS = getProperty("MaskWorkspace");
    vecMaskedDetID = processMaskWorkspace(m_maskWS);
  } else {
    m_maskDets = false;
  }
}
예제 #26
0
/**
 * @brief declare commonattributes Q and WorkspaceIndex.
 * Subclasses containing additional attributes should override this method by
 * declaring the additional
 * attributes and then calling the parent (this) method to declare Q and
 * WorkspaceIndex.
 */
void FunctionQDepends::declareAttributes() {
  this->declareAttribute("Q", Attr(EMPTY_DBL()));
  this->declareAttribute("WorkspaceIndex", Attr(EMPTY_INT()));
}
예제 #27
0
 //--------------------------------------------------------------------------
 // Public member functions
 //--------------------------------------------------------------------------
 DetectorDiagnostic::DetectorDiagnostic() : 
       API::Algorithm(), m_fracDone(0.0), m_TotalTime(RTTotal), m_parents(0),
       m_progStepWidth(0.0), m_minIndex(0), m_maxIndex(EMPTY_INT()),
       m_rangeLower(EMPTY_DBL()), m_rangeUpper(EMPTY_DBL())
 {
 }
예제 #28
0
void CorrectKiKf::execEvent()
{
  g_log.information("Processing event workspace");

  const MatrixWorkspace_const_sptr matrixInputWS = this->getProperty("InputWorkspace");
  EventWorkspace_const_sptr inputWS= boost::dynamic_pointer_cast<const EventWorkspace>(matrixInputWS);

  // generate the output workspace pointer
  API::MatrixWorkspace_sptr matrixOutputWS = this->getProperty("OutputWorkspace");
  EventWorkspace_sptr outputWS;
  if (matrixOutputWS == matrixInputWS)
    outputWS = boost::dynamic_pointer_cast<EventWorkspace>(matrixOutputWS);
  else
  {
    //Make a brand new EventWorkspace
    outputWS = boost::dynamic_pointer_cast<EventWorkspace>(
            API::WorkspaceFactory::Instance().create("EventWorkspace", inputWS->getNumberHistograms(), 2, 1));
    //Copy geometry over.
    API::WorkspaceFactory::Instance().initializeFromParent(inputWS, outputWS, false);
    //You need to copy over the data as well.
    outputWS->copyDataFrom( (*inputWS) );

    //Cast to the matrixOutputWS and save it
    matrixOutputWS = boost::dynamic_pointer_cast<MatrixWorkspace>(outputWS);
    this->setProperty("OutputWorkspace", matrixOutputWS);
  }

  const std::string emodeStr = getProperty("EMode");
  double efixedProp = getProperty("EFixed"),efixed;

  if( efixedProp == EMPTY_DBL() )
  {
    if (emodeStr == "Direct")
    {
      // Check if it has been store on the run object for this workspace
      if( this->inputWS->run().hasProperty("Ei"))
      {
        Kernel::Property* eiprop = this->inputWS->run().getProperty("Ei");
        efixedProp = boost::lexical_cast<double>(eiprop->value());
        g_log.debug() << "Using stored Ei value " << efixedProp << "\n";
      }
      else
      {
        throw std::invalid_argument("No Ei value has been set or stored within the run information.");
      }
    }
    else
    {
      // If not specified, will try to get Ef from the parameter file for indirect geometry, 
      // but it will be done for each spectrum separately, in case of different analyzer crystals
    }
  }

  // Get the parameter map
  const ParameterMap& pmap = outputWS->constInstrumentParameters();

  int64_t numHistograms = static_cast<int64_t>(inputWS->getNumberHistograms());
  API::Progress prog = API::Progress(this, 0.0, 1.0, numHistograms);
  PARALLEL_FOR1(outputWS)
  for (int64_t i=0; i < numHistograms; ++i)
  {
    PARALLEL_START_INTERUPT_REGION
    
    double Efi = 0;
    // Now get the detector object for this histogram to check if monitor
    // or to get Ef for indirect geometry
    if (emodeStr == "Indirect") 
    {
      if ( efixedProp != EMPTY_DBL()) Efi = efixedProp;
      else try 
      {
        IDetector_const_sptr det = inputWS->getDetector(i);
        if (!det->isMonitor())
        {
            try
            {
              Parameter_sptr par = pmap.getRecursive(det.get(),"Efixed");
              if (par)
              {
                Efi = par->value<double>();
                g_log.debug() << "Detector: " << det->getID() << " EFixed: " << Efi << "\n";
              }
            }
            catch (std::runtime_error&) { /* Throws if a DetectorGroup, use single provided value */ }
        }

      }
      catch(std::runtime_error&) { g_log.information() << "Workspace Index " << i << ": cannot find detector" << "\n"; }
    }

    if (emodeStr == "Indirect") efixed=Efi;
    else efixed=efixedProp;

    //Do the correction
		EventList *evlist=outputWS->getEventListPtr(i);
    switch (evlist->getEventType())
    {
      case TOF:
        //Switch to weights if needed.
        evlist->switchTo(WEIGHTED);
        /* no break */
        // Fall through
  
      case WEIGHTED:
        correctKiKfEventHelper(evlist->getWeightedEvents(), efixed,emodeStr);
        break;
  
      case WEIGHTED_NOTIME:
        correctKiKfEventHelper(evlist->getWeightedEventsNoTime(), efixed,emodeStr);
        break;
    }


    prog.report();
    PARALLEL_END_INTERUPT_REGION
  }
  PARALLEL_CHECK_INTERUPT_REGION

  outputWS->clearMRU();
  if (inputWS->getNumberEvents( ) != outputWS->getNumberEvents( ))
  {
    g_log.information() <<"Ef <= 0 or Ei <= 0 for "<<inputWS->getNumberEvents( )-outputWS->getNumberEvents( )<<" events, out of "<<inputWS->getNumberEvents( )<<std::endl;
    if ( efixedProp == EMPTY_DBL()) g_log.information()<<"Try to set fixed energy"<<std::endl ;
  }
}