/**
 * Looks at each of the parameters, to see if they are default, and if they are,
 * over-writes them
 * with the values set in the instrument parameters (if they exist).
 * @param instrument : Instrument on input workspace.
 * @param ndims : Number of dimensions in output workspace.
 */
void BoxControllerSettingsAlgorithm::takeDefaultsFromInstrument(
    Mantid::Geometry::Instrument_const_sptr instrument, const size_t ndims) {
  const std::string splitThresholdName = "SplitThreshold";
  const std::string splitIntoName = "SplitInto";
  const std::string maxRecursionDepthName = "MaxRecursionDepth";
  Property *p = getProperty(splitThresholdName);
  if (p->isDefault()) {
    std::vector<double> instrumentSplitThresholds =
        instrument->getNumberParameter(splitThresholdName, true);
    if (!instrumentSplitThresholds.empty()) {
      setProperty(splitThresholdName,
                  static_cast<int>(instrumentSplitThresholds.front()));
    }
  }
  p = getProperty(splitIntoName);
  if (p->isDefault()) {
    std::vector<double> instrumentSplitInto =
        instrument->getNumberParameter(splitIntoName, true);
    if (!instrumentSplitInto.empty()) {
      const int splitInto = static_cast<int>(instrumentSplitInto.front());
      std::vector<int> newSplitInto(ndims, splitInto);
      setProperty(splitIntoName, newSplitInto);
    }
  }
  p = getProperty(maxRecursionDepthName);
  if (p->isDefault()) {
    std::vector<double> instrumentMaxRecursionDepth =
        instrument->getNumberParameter(maxRecursionDepthName, true);
    if (!instrumentMaxRecursionDepth.empty()) {
      setProperty(maxRecursionDepthName,
                  static_cast<int>(instrumentMaxRecursionDepth.front()));
    }
  }
}
Esempio n. 2
0
/**
* This function either shows or hides the given QCheckBox, based on the named property
* inside the instrument param file.  When hidden, the default state will be used to
* reset to the "unused" state of the checkbox.
*
* @param parameterName :: The name of the property to look for inside the current inst param file.
* @param checkBox :: The checkbox to set the state of, and to either hide or show based on the current inst.
* @param defaultState :: The state to which the checkbox will be set upon hiding it.
*/
void IndirectDataReduction::setInstSpecificWidget(const std::string & parameterName, QCheckBox * checkBox, QCheckBox::ToggleState defaultState)
{
  // Get access to instrument specific parameters via the loaded empty workspace.
  std::string instName = m_uiForm.cbInst->currentText().toStdString();
  Mantid::API::MatrixWorkspace_sptr input = boost::dynamic_pointer_cast<Mantid::API::MatrixWorkspace>(Mantid::API::AnalysisDataService::Instance().retrieve("__empty_" + instName));
  if(input == NULL)
    return;

  Mantid::Geometry::Instrument_const_sptr instr = input->getInstrument();

  // See if the instrument params file requests that the checkbox be shown to the user.
  std::vector<std::string> showParams = instr->getStringParameter(parameterName);
  
  std::string show = "";
  if(!showParams.empty())
    show = showParams[0];
  
  if(show == "Show")
    checkBox->setHidden(false);
  else
  {
    checkBox->setHidden(true);
    checkBox->setState(defaultState);
  }
}
Esempio n. 3
0
/**
 * Attempt to extract an instrument double parameter from a specified
 * instrument.
 *
 * @param instrument    The instrument to extract the parameter from.
 * @param parameterName The name of the parameter to extract.
 *
 * @return              The extracted parameter if it is found, else
 *                      boost::none.
 */
boost::optional<double> CalculatePaalmanPings::getInstrumentParameter(
    Mantid::Geometry::Instrument_const_sptr instrument,
    const std::string &parameterName) {

  if (instrument->hasParameter(parameterName)) {
    const auto parameterValue = QString::fromStdString(
        instrument->getStringParameter(parameterName)[0]);
    return parameterValue.toDouble();
  }
  return boost::none;
}
/**
 * Get the detector component. Use the name provided as a property as the basis
 *for the lookup as a priority.
 *
 * Throws if the name is invalid.
 * @param workspace : Workspace from instrument with detectors
 * @param isPointDetector : True if this is a point detector. Used to guess a
 *name.
 * @return The component : The component object found.
 */
boost::shared_ptr<const Mantid::Geometry::IComponent>
SpecularReflectionAlgorithm::getDetectorComponent(
    MatrixWorkspace_sptr workspace, const bool isPointDetector) const {
  boost::shared_ptr<const IComponent> searchResult;
  if (!isPropertyDefault("SpectrumNumbersOfDetectors")) {
    const std::vector<int> spectrumNumbers =
        this->getProperty("SpectrumNumbersOfDetectors");
    const bool strictSpectrumChecking =
        this->getProperty("StrictSpectrumChecking");
    checkSpectrumNumbers(spectrumNumbers, strictSpectrumChecking, g_log);
    auto specToWorkspaceIndex = workspace->getSpectrumToWorkspaceIndexMap();
    DetectorGroup_sptr allDetectors = boost::make_shared<DetectorGroup>();
    const auto &spectrumInfo = workspace->spectrumInfo();
    for (auto index : spectrumNumbers) {
      const size_t spectrumNumber{static_cast<size_t>(index)};
      auto it = specToWorkspaceIndex.find(index);
      if (it == specToWorkspaceIndex.end()) {
        std::stringstream message;
        message << "Spectrum number " << spectrumNumber
                << " does not exist in the InputWorkspace";
        throw std::invalid_argument(message.str());
      }
      const size_t workspaceIndex = it->second;
      auto detector = workspace->getDetector(workspaceIndex);
      if (spectrumInfo.isMasked(workspaceIndex))
        g_log.warning() << "Adding a detector (ID:" << detector->getID()
                        << ") that is flagged as masked.\n";
      allDetectors->addDetector(detector);
    }
    searchResult = allDetectors;
  } else {
    Mantid::Geometry::Instrument_const_sptr inst = workspace->getInstrument();
    std::string componentToCorrect =
        isPointDetector ? "point-detector" : "linedetector";

    if (!isPropertyDefault("DetectorComponentName")) {
      componentToCorrect = this->getPropertyValue("DetectorComponentName");
    }
    searchResult = inst->getComponentByName(componentToCorrect);
    if (searchResult == nullptr) {
      throw std::invalid_argument(componentToCorrect +
                                  " does not exist. Check input properties.");
    }
  }

  return searchResult;
}
/**
 * Get the sample component. Use the name provided as a property as the basis
 *for the lookup as a priority.
 *
 * Throws if the name is invalid.
 * @param inst : Instrument to search through
 * @return : The component : The component object found.
 */
Mantid::Geometry::IComponent_const_sptr
SpecularReflectionAlgorithm::getSurfaceSampleComponent(
    Mantid::Geometry::Instrument_const_sptr inst) const {
  std::string sampleComponent = "some-surface-holder";
  if (!isPropertyDefault("SampleComponentName")) {
    sampleComponent = this->getPropertyValue("SampleComponentName");
  }
  auto searchResult = inst->getComponentByName(sampleComponent);
  if (searchResult == nullptr) {
    throw std::invalid_argument(sampleComponent +
                                " does not exist. Check input properties.");
  }
  return searchResult;
}
double ReflectometryReductionOneAuto::checkForDefault(
    std::string propName, Mantid::Geometry::Instrument_const_sptr instrument,
    std::string idf_name) const {
    auto algProperty = this->getPointerToProperty(propName);
    if (algProperty->isDefault()) {
        auto defaults = instrument->getNumberParameter(idf_name);
        if (defaults.size() == 0) {
            throw std::runtime_error("No data could be retrieved from the parameters "
                                     "and argument wasn't provided: " +
                                     propName);
        }
        return defaults[0];
    } else {
        return boost::lexical_cast<double, std::string>(algProperty->value());
    }
}
Esempio n. 7
0
/**
  @param  inst         Instrument
  @param  bankName     Name of detector bank
  @param  col          Column number containing peak
  @param  row          Row number containing peak
  @param  Edge         Number of edge points for each bank
  @return True if peak is on edge
*/
bool edgePixel(Mantid::Geometry::Instrument_const_sptr inst,
               std::string bankName, int col, int row, int Edge) {
  if (bankName == "None")
    return false;
  boost::shared_ptr<const Geometry::IComponent> parent =
      inst->getComponentByName(bankName);
  if (parent->type() == "RectangularDetector") {
    boost::shared_ptr<const Geometry::RectangularDetector> RDet =
        boost::dynamic_pointer_cast<const Geometry::RectangularDetector>(
            parent);

    return col < Edge || col >= (RDet->xpixels() - Edge) || row < Edge ||
           row >= (RDet->ypixels() - Edge);
  } else {
    std::vector<Geometry::IComponent_const_sptr> children;
    boost::shared_ptr<const Geometry::ICompAssembly> asmb =
        boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
    asmb->getChildren(children, false);
    int startI = 1;
    if (children[0]->getName() == "sixteenpack") {
      startI = 0;
      parent = children[0];
      children.clear();
      boost::shared_ptr<const Geometry::ICompAssembly> asmb =
          boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(parent);
      asmb->getChildren(children, false);
    }
    boost::shared_ptr<const Geometry::ICompAssembly> asmb2 =
        boost::dynamic_pointer_cast<const Geometry::ICompAssembly>(children[0]);
    std::vector<Geometry::IComponent_const_sptr> grandchildren;
    asmb2->getChildren(grandchildren, false);
    int NROWS = static_cast<int>(grandchildren.size());
    int NCOLS = static_cast<int>(children.size());
    // Wish pixels and tubes start at 1 not 0
    return col - startI < Edge || col - startI >= (NCOLS - Edge) ||
           row - startI < Edge || row - startI >= (NROWS - Edge);
  }
  return false;
}
Esempio n. 8
0
/**
 * Gets the eFixed value from the workspace using the instrument parameters.
 *
 * @param ws Pointer to the workspace
 * @return eFixed value
 */
double IndirectTab::getEFixed(Mantid::API::MatrixWorkspace_sptr ws) {
  Mantid::Geometry::Instrument_const_sptr inst = ws->getInstrument();
  if (!inst)
    throw std::runtime_error("No instrument on workspace");

  // Try to get the parameter form the base instrument
  if (inst->hasParameter("Efixed"))
    return inst->getNumberParameter("Efixed")[0];

  // Try to get it form the analyser component
  if (inst->hasParameter("analyser")) {
    std::string analyserName = inst->getStringParameter("analyser")[0];
    auto analyserComp = inst->getComponentByName(analyserName);

    if (analyserComp && analyserComp->hasParameter("Efixed"))
      return analyserComp->getNumberParameter("Efixed")[0];
  }

  throw std::runtime_error("Instrument has no efixed parameter");
}
    /**
     * @return List of columns to hide by default.
     */
    std::vector<int> QPeaksTableModel::defaultHideCols()
    {
      std::vector<int> result;

      // figure out if there are any rectangular detectors
      Mantid::Geometry::Instrument_const_sptr instr = m_peaksWS->getInstrument();
      { // shrink variable scope
        std::vector<Mantid::detid_t> ids = instr->getDetectorIDs(true);
        size_t numToCheck(ids.size());
        if (numToCheck > 20) // arbitrary cutoff
          numToCheck = 20;
        const std::string RECT_DET("RectangularDetector");
        for (size_t i = 0; i < numToCheck; ++i)
        {
          boost::shared_ptr<const Mantid::Geometry::IComponent> component = instr->getDetector(ids[i]);
          if (component->type().compare(RECT_DET) == 0)
          {
            break;
          }
          else
          {
            component = component->getParent();
            if (component->type().compare(RECT_DET) == 0)
            {
              break;
            }
          }
        }
      }

      // only show bank name for SNS instruments
      std::string instrName = instr->getName();
      try
      {
        Mantid::Kernel::InstrumentInfo instrInfo =
            Mantid::Kernel::ConfigService::Instance().getInstrument(instrName);
        if (instrInfo.facility().name() != "SNS")
          result.push_back(COL_BANKNAME);

        // hide some columns based on the techniques
        { // shrink variable scope
          std::set<std::string> techniques = instrInfo.techniques();
          // required for showing final and delta energy
          const std::string IGS("TOF Indirect Geometry Spectroscopy");
          // required for showing initial and delta energy
          const std::string DGS("TOF Direct Geometry Spectroscopy");
          bool showEnergy(false);
          if (techniques.find(DGS) == techniques.end())
            result.push_back(COL_FINAL_ENERGY);
          else
            showEnergy = true;
          if (techniques.find(IGS) == techniques.end())
            result.push_back(COL_INITIAL_ENERGY);
          else
            showEnergy = true;
          if (!showEnergy)
            result.push_back(COL_ENERGY);
        }
      } catch (Mantid::Kernel::Exception::NotFoundError&)
      {
        // Unable to fetch instrument info, so continue without it.
      }

      return result;
    }
Esempio n. 10
0
void InstrumentWidget::setSurfaceType(int type) {
  // we cannot do 3D without OpenGL
  if (type == FULL3D && !isGLEnabled()) {
    QMessageBox::warning(
        this, "Mantid - Warning",
        "OpenGL must be enabled to render the instrument in 3D.");
    return;
  }

  if (type < RENDERMODE_SIZE) {
    QApplication::setOverrideCursor(Qt::WaitCursor);
    SurfaceType surfaceType = SurfaceType(type);
    if (!m_instrumentActor)
      return;

    ProjectionSurface *surface = getSurface().get();
    int peakLabelPrecision = 6;
    bool showPeakRow = true;
    bool showPeakLabels = true;
    bool showPeakRelativeIntensity = true;
    if (surface) {
      peakLabelPrecision = surface->getPeakLabelPrecision();
      showPeakRow = surface->getShowPeakRowsFlag();
      showPeakLabels = surface->getShowPeakLabelsFlag();
    } else {
      QSettings settings;
      settings.beginGroup(InstrumentWidgetSettingsGroup);
      peakLabelPrecision = settings.value("PeakLabelPrecision", 2).toInt();
      showPeakRow = settings.value("ShowPeakRows", true).toBool();
      showPeakLabels = settings.value("ShowPeakLabels", true).toBool();

      // By default this is should be off for now.
      showPeakRelativeIntensity =
          settings.value("ShowPeakRelativeIntensities", false).toBool();
      settings.endGroup();
    }

    // Surface factory
    // If anything throws during surface creation, store error message here
    QString errorMessage;
    try {
      Mantid::Geometry::Instrument_const_sptr instr =
          m_instrumentActor->getInstrument();
      Mantid::Geometry::IComponent_const_sptr sample = instr->getSample();
      if (!sample) {
        throw InstrumentHasNoSampleError();
      }
      Mantid::Kernel::V3D sample_pos = sample->getPos();
      auto axis = getSurfaceAxis(surfaceType);

      // create the surface
      if (surfaceType == FULL3D) {
        surface = new Projection3D(m_instrumentActor.get(),
                                   getInstrumentDisplayWidth(),
                                   getInstrumentDisplayHeight());
      } else if (surfaceType <= CYLINDRICAL_Z) {
        surface =
            new UnwrappedCylinder(m_instrumentActor.get(), sample_pos, axis);
      } else if (surfaceType <= SPHERICAL_Z) {
        surface =
            new UnwrappedSphere(m_instrumentActor.get(), sample_pos, axis);
      } else // SIDE_BY_SIDE
      {
        surface = new PanelsSurface(m_instrumentActor.get(), sample_pos, axis);
      }
    } catch (InstrumentHasNoSampleError &) {
      QApplication::restoreOverrideCursor();
      throw;
    } catch (std::exception &e) {
      errorMessage = e.what();
    } catch (...) {
      errorMessage = "Unknown exception thrown.";
    }
    if (!errorMessage.isNull()) {
      // if exception was thrown roll back to the current surface type.
      QApplication::restoreOverrideCursor();
      QMessageBox::critical(
          this, "MantidPlot - Error",
          "Surface cannot be created because of an exception:\n\n  " +
              errorMessage + "\n\nPlease select a different surface type.");
      // if suface change was initialized by the GUI this should ensure its
      // consistency
      emit surfaceTypeChanged(m_surfaceType);
      return;
    }
    // end Surface factory

    m_surfaceType = surfaceType;
    surface->setPeakLabelPrecision(peakLabelPrecision);
    surface->setShowPeakRowsFlag(showPeakRow);
    surface->setShowPeakLabelsFlag(showPeakLabels);
    surface->setShowPeakRelativeIntensityFlag(showPeakRelativeIntensity);
    // set new surface
    setSurface(surface);

    // init tabs with new surface
    foreach (InstrumentWidgetTab *tab, m_tabs) { tab->initSurface(); }

    connect(surface, SIGNAL(executeAlgorithm(Mantid::API::IAlgorithm_sptr)),
            this, SLOT(executeAlgorithm(Mantid::API::IAlgorithm_sptr)));
    connect(surface, SIGNAL(updateInfoText()), this, SLOT(updateInfoText()),
            Qt::QueuedConnection);
    QApplication::restoreOverrideCursor();
  }