Пример #1
0
/**
 * Loads a file into a *hidden* workspace.
 *
 * @param fileName :: file name to load.
 * @param wsName   :: workspace name, which will be prefixed by a "__"
 *
 * @returns a pointer to the loaded workspace
 */
API::Workspace_sptr Load::loadFileToWs(const std::string &fileName,
                                       const std::string &wsName) {
  Mantid::API::IAlgorithm_sptr loadAlg = createChildAlgorithm("Load", 1);

  // Get the list properties for the concrete loader load algorithm
  const std::vector<Kernel::Property *> &props = getProperties();

  // Loop through and set the properties on the Child Algorithm
  for (auto prop : props) {
    const std::string &propName = prop->name();

    if (this->existsProperty(propName)) {
      if (propName == "Filename") {
        loadAlg->setPropertyValue("Filename", fileName);
      } else if (propName == "OutputWorkspace") {
        loadAlg->setPropertyValue("OutputWorkspace", wsName);
      } else {
        loadAlg->setPropertyValue(propName, getPropertyValue(propName));
      }
    }
  }

  loadAlg->executeAsChildAlg();

  Workspace_sptr ws = loadAlg->getProperty("OutputWorkspace");
  // ws->setName(wsName);
  AnalysisDataService::Instance().addOrReplace(wsName, ws);
  return ws;
}
Пример #2
0
/** Finds the largest peak by looping through the histogram and finding the
* maximum
*  value
* @param height :: its passed value ignored it is set to the peak height
* @param centreInd :: passed value is ignored it will be set to the bin index of
* the peak center
* @param background :: passed value ignored set mean number of counts per bin in
* the spectrum
* @throw invalid_argument if the peak is not clearly above the background
*/
void GetEi::getPeakEstimates(double &height, int64_t &centreInd,
                             double &background) const {
    // take note of the number of background counts as error checking, do we have
    // a peak or just a bump in the background
    background = 0;
    // start at the first Y value
    height = m_tempWS->readY(0)[0];
    centreInd = 0;
    // then loop through all the Y values and find the tallest peak
    for (MantidVec::size_type i = 1; i < m_tempWS->readY(0).size() - 1; ++i) {
        background += m_tempWS->readY(0)[i];
        if (m_tempWS->readY(0)[i] > height) {
            centreInd = i;
            height = m_tempWS->readY(0)[centreInd];
        }
    }

    background = background / static_cast<double>(m_tempWS->readY(0).size());
    if (height < PEAK_THRESH_H * background) {
        throw std::invalid_argument(
            "No peak was found or its height is less than the threshold of " +
            boost::lexical_cast<std::string>(PEAK_THRESH_H) +
            " times the mean background, was the energy estimate (" +
            getPropertyValue("EnergyEstimate") + " meV) close enough?");
    }

    g_log.debug() << "Peak position is the bin that has the maximum Y value in "
                  "the monitor spectrum, which is at TOF "
                  << (m_tempWS->readX(0)[centreInd] +
                      m_tempWS->readX(0)[centreInd + 1]) /
                  2 << " (peak height " << height
                  << " counts/microsecond)\n";
}
Пример #3
0
/** Make a (optionally) file backed MDEventWorkspace with nEvents fake data
 *points
 * the points are randomly distributed within the box (nEvents>0) or
 *homogeneously and regularly spread through the box (nEvents<0)
 *
 * @param wsName :: name of the workspace in ADS
 * @param fileBacked :: true for file-backed
 * @param frame:: the required frame
 * @param numEvents :: number of events in the target workspace distributed
 *randomly if numEvents>0 or regularly & homogeneously if numEvents<0
 * @param coord :: Required coordinate system
 * @return MDEW sptr
 */
DataObjects::MDEventWorkspace3Lean::sptr
makeFileBackedMDEWwithMDFrame(const std::string &wsName, bool fileBacked,
                              const Mantid::Geometry::MDFrame &frame,
                              long numEvents,
                              Kernel::SpecialCoordinateSystem coord) {
  // ---------- Make a file-backed MDEventWorkspace -----------------------
  std::string snEvents = boost::lexical_cast<std::string>(numEvents);
  MDEventWorkspace3Lean::sptr ws1 =
      MDEventsTestHelper::makeAnyMDEWWithFrames<MDLeanEvent<3>, 3>(
          10, 0.0, 10.0, frame, 0);
  ws1->getBoxController()->setSplitThreshold(100);
  ws1->setCoordinateSystem(coord);
  Mantid::API::AnalysisDataService::Instance().addOrReplace(
      wsName, boost::dynamic_pointer_cast<Mantid::API::IMDEventWorkspace>(ws1));
  FrameworkManager::Instance().exec("FakeMDEventData", 6, "InputWorkspace",
                                    wsName.c_str(), "UniformParams",
                                    snEvents.c_str(), "RandomizeSignal", "1");
  if (fileBacked) {
    std::string filename = wsName + ".nxs";
    auto saver = FrameworkManager::Instance().exec(
        "SaveMD", 4, "InputWorkspace", wsName.c_str(), "Filename",
        filename.c_str());
    FrameworkManager::Instance().exec(
        "LoadMD", 8, "OutputWorkspace", wsName.c_str(), "Filename",
        saver->getPropertyValue("Filename").c_str(), "FileBackEnd", "1",
        "Memory", "0");
  }
  return boost::dynamic_pointer_cast<MDEventWorkspace3Lean>(
      Mantid::API::AnalysisDataService::Instance().retrieve(wsName));
}
Пример #4
0
/**
 * Publish the history of a given workspace.
 * @param catalogInfoService :: The catalog to use to publish the file.
 * @param workspace :: The workspace to obtain the history from.
 */
void CatalogPublish::publishWorkspaceHistory(
    Mantid::API::ICatalogInfoService_sptr &catalogInfoService,
    Mantid::API::Workspace_sptr &workspace) {
  std::stringstream ss;
  // Obtain the workspace history as a string.
  ss << generateWorkspaceHistory(workspace);
  // Use the name the use wants to save the file to the server as and append .py
  std::string fileName =
      Poco::Path(Poco::Path(getPropertyValue("NameInCatalog")).getFileName())
          .getBaseName() +
      ".py";
  // Publish the workspace history to the server.
  publish(ss, catalogInfoService->getUploadURL(
                  getPropertyValue("InvestigationNumber"), fileName,
                  getPropertyValue("DataFileDescription")));
}
Пример #5
0
/** Execute the algorithm.
 */
void FakeMDEventData::exec() {
  IMDEventWorkspace_sptr in_ws = getProperty("InputWorkspace");

  if (getPropertyValue("UniformParams") == "" &&
      getPropertyValue("PeakParams") == "")
    throw std::invalid_argument(
        "You must specify at least one of PeakParams or UniformParams.");

  setupDetectorCache(*in_ws);

  CALL_MDEVENT_FUNCTION(this->addFakePeak, in_ws)
  CALL_MDEVENT_FUNCTION(this->addFakeUniformData, in_ws)

  // Mark that events were added, so the file back end (if any) needs updating
  in_ws->setFileNeedsUpdating(true);
}
Пример #6
0
    /// execute the algorithm
    void CatalogLogout::exec()
    {
      std::string logoutSession = getPropertyValue("Session");

      // Destroy all sessions if no session provided.
      if (logoutSession.empty()) API::CatalogManager::Instance().destroyCatalog("");

      auto keepAliveInstances = API::AlgorithmManager::Instance().runningInstancesOf("CatalogKeepAlive");

      for (unsigned i = 0; i < keepAliveInstances.size(); ++i)
      {
        auto keepAliveInstance = API::AlgorithmManager::Instance().getAlgorithm(keepAliveInstances.at(i)->getAlgorithmID());

        if (logoutSession == keepAliveInstances.at(i)->getPropertyValue("Session"))
        {
          keepAliveInstance->cancel();
          API::CatalogManager::Instance().destroyCatalog(logoutSession);
          break;
        }
        else if (logoutSession.empty())
        {
          keepAliveInstance->cancel();
        }
      }
    }
Пример #7
0
/**
 * Formats the minimizer string for a given spectrum from a given workspace.
 *
 * @param wsName Name of workspace being fitted
 * @param wsIndex Index of spectrum being fitted
 * @return Formatted minimizer string
 */
std::string PlotPeakByLogValue::getMinimizerString(const std::string &wsName,
                                                   const std::string &wsIndex) {
  std::string format = getPropertyValue("Minimizer");
  std::string wsBaseName = wsName + "_" + wsIndex;
  boost::replace_all(format, "$wsname", wsName);
  boost::replace_all(format, "$wsindex", wsIndex);
  boost::replace_all(format, "$basename", wsBaseName);
  boost::replace_all(format, "$outputname", m_baseName);

  auto minimizer = FuncMinimizerFactory::Instance().createMinimizer(format);
  auto minimizerProps = minimizer->getProperties();
  for (auto &minimizerProp : minimizerProps) {
    Mantid::API::WorkspaceProperty<> *wsProp =
        dynamic_cast<Mantid::API::WorkspaceProperty<> *>(minimizerProp);
    if (wsProp) {
      std::string wsPropValue = minimizerProp->value();
      if (wsPropValue != "") {
        std::string wsPropName = minimizerProp->name();
        m_minimizerWorkspaces[wsPropName].push_back(wsPropValue);
      }
    }
  }

  return format;
}
/**
 * Synchronize properties with scatterer members
 *
 * This method synchronizes the properties of CompositeBraggScatterer with the
 * properties of the contained BraggScatterer instances. It adds new properties
 * if required and removed properties that are no longer used (for example
 * because the member that introduced the property has been removed).
 */
void CompositeBraggScatterer::redeclareProperties() {
  std::map<std::string, size_t> propertyUseCount = getPropertyCountMap();

  for (auto &scatterer : m_scatterers) {
    // Check if any of the declared properties is in this scatterer (and set
    // value if that's the case)
    for (auto &prop : propertyUseCount) {
      if (scatterer->existsProperty(prop.first)) {
        prop.second += 1;

        propagatePropertyToScatterer(scatterer, prop.first,
                                     getPropertyValue(prop.first));
      }
    }

    // Use the properties of this scatterer which have been marked as exposed to
    // composite
    std::vector<Property *> properties =
        scatterer->getPropertiesInGroup(getPropagatingGroupName());
    for (auto &property : properties) {
      const std::string &propertyName = property->name();
      if (!existsProperty(propertyName)) {
        declareProperty(std::unique_ptr<Property>(property->clone()));
      }
    }
  }

  // Remove unused properties
  for (auto &property : propertyUseCount) {
    if (property.second == 0) {
      removeProperty(property.first);
    }
  }
}
Пример #9
0
/**
 * Load metadata file witch to date is just a line of of double values
 * Parses this file and put it into a vector
 * @return vector with the file contents
 */
std::vector<double> LoadSwans::loadMetaData() {
  std::vector<double> metadata;
  std::string filename = getPropertyValue("FilenameMetaData");
  std::ifstream infile(filename);
  if (infile.fail()) {
    g_log.error("Error reading file " + filename);
    throw Exception::FileError("Unable to read data in File:", filename);
  }
  std::string line;
  while (getline(infile, line)) {
    // line with data, need to be parsed by white spaces
    if (!line.empty() && line[0] != '#') {
      g_log.debug() << "Metadata parsed line: " << line << '\n';
      auto tokenizer = Mantid::Kernel::StringTokenizer(
          line, "\t ",
          Mantid::Kernel::StringTokenizer::TOK_TRIM |
              Mantid::Kernel::StringTokenizer::TOK_IGNORE_EMPTY);
      for (const auto &token : tokenizer) {
        metadata.push_back(boost::lexical_cast<double>(token));
      }
    }
  }
  if (metadata.size() < 6) {
    g_log.error("Expecting length >=6 for metadata arguments!");
    throw Exception::NotFoundError(
        "Number of arguments for metadata must be at least 6. Found: ",
        metadata.size());
  }
  return metadata;
}
Пример #10
0
void LoadMappingTable::exec()
{
  //Get the raw file name
  m_filename = getPropertyValue("Filename");
  // Get the input workspace
  const MatrixWorkspace_sptr localWorkspace = getProperty("Workspace");
        
  /// ISISRAW class instance which does raw file reading. Shared pointer to prevent memory leak when an exception is thrown.
  boost::scoped_ptr<ISISRAW2> iraw(new ISISRAW2);

  if (iraw->readFromFile(m_filename.c_str(),0) != 0) // ReadFrom File with no data
  {
    g_log.error("Unable to open file " + m_filename);
    throw Kernel::Exception::FileError("Unable to open File:" , m_filename);
  }
  progress(0.5);
  const int number_spectra=iraw->i_det; // Number of entries in the spectra/udet table
  if ( number_spectra == 0 )
  {
    g_log.warning("The spectra to detector mapping table is empty");
  }
  // Fill in the mapping in the workspace's ISpectrum objects
  localWorkspace->updateSpectraUsing(SpectrumDetectorMapping(iraw->spec,iraw->udet,number_spectra));
  progress(1);

  return;
}
Пример #11
0
/**
 * Load the data into a map. The map is indexed by pixel id (0 to 128*128-1 =
 * m_detector_size)
 * The map values are the events TOF
 * @returns the map of events indexed by pixel index
 */
std::map<uint32_t, std::vector<uint32_t>> LoadSwans::loadData() {

  std::string filename = getPropertyValue("FilenameData");
  std::ifstream input(filename, std::ifstream::binary | std::ios::ate);
  input.seekg(0);

  m_ws->initialize(m_detector_size, 1, 1);

  std::map<uint32_t, std::vector<uint32_t>> eventMap;

  while (input.is_open()) {
    if (input.eof())
      break;
    uint32_t tof = 0;
    input.read(reinterpret_cast<char *>(&tof), sizeof(tof));
    tof -= static_cast<uint32_t>(1e9);
    tof = static_cast<uint32_t>(tof * 0.1);

    uint32_t pos = 0;
    input.read(reinterpret_cast<char *>(&pos), sizeof(pos));
    if (pos < 400000) {
      g_log.warning() << "Detector index invalid: " << pos << '\n';
      continue;
    }
    pos -= 400000;
    eventMap[pos].push_back(tof);
  }
  return eventMap;
}
Пример #12
0
String CSSStyleDeclaration::getPropertyValue(const String &propertyName)
{
    int propID = cssPropertyID(propertyName);
    if (!propID)
        return String();
    return getPropertyValue(propID);
}
Пример #13
0
void DataBus::AbstractClient::processGetClientPropertyValueRequestPacket(const Packet &packet)
{
    // Check if registered
    if (m_registered == false)
    {
        // Error, can't send a response if not registered
        return;
    }

    // Check destination
    if (packet.getDestination() != m_clientId)
    {
        // Error, invalid destination
        return;
    }

    // Get Property ID
    quint8 propertyId;

    if (GetClientPropertyValueRequestPacket::parse(packet,
                                                   &propertyId) == false)
    {
        // Error, failed to parse packet
        return;
    }

    // Get Property Value
    Value propertyValue;

    if (getPropertyValue(propertyId, &propertyValue) == false)
    {
        // Error, failed to get property value
        return;
    }

    // Create response
    Packet responsePacket;

    if (GetClientPropertyValueResponsePacket::create(m_clientId,
                                                     packet.getSource(),
                                                     packet.getPacketId(),
                                                     propertyId,
                                                     propertyValue,
                                                     &responsePacket) == false)
    {
        // Error, failed to create packet
        return;
    }

    // Send Response
    if (sendPacket(responsePacket) == false)
    {
        // Error, failed to create packet
        return;
    }

    // Success
    return;
}
Пример #14
0
String CIMHelper::getPropertyAsString(const CIMInstance &instanceObject, String name)
{
    CIMValue value = getPropertyValue(instanceObject, name);
    if (value.isNull()) return String("");
    String result;
    value.get(result);
    return result;
}
Пример #15
0
    const CheckerboardDetector::Checkerboard &
    CheckerboardDetector::detect(const Img8u &image){
      const Img8u *useImage = &image;
      if(image.getFormat() != formatGray && image.getChannels() != 1){
        m_data->grayBuf.setFormat(formatGray);
        m_data->grayBuf.setSize(image.getSize());

        cc(&image, &m_data->grayBuf);

        useImage = &m_data->grayBuf;
      }
      img_to_ipl(useImage, &m_data->ipl);
      std::vector<CvPoint2D32f> corners(m_data->cb.size.getDim());

      CvSize s = {m_data->cb.size.width, m_data->cb.size.height };

      int n = corners.size();
      m_data->cb.found = cv::cvFindChessboardCorners(
          m_data->ipl, s, corners.data(), &n,
          cv::CALIB_CB_ADAPTIVE_THRESH | cv::CALIB_CB_FILTER_QUADS);

      bool optSubPix = getPropertyValue("subpixel opt.enabled");
      int radius = getPropertyValue("subpixel opt.radius");
      int innerR = getPropertyValue("subpixel opt.inner radius");
      if(innerR >= radius) innerR = radius -1;
      if(innerR == 0) innerR = -1;
      int maxIter = getPropertyValue("subpixel opt.max iterations");
      float minErr = getPropertyValue("subpixel opt.min error");

      if(m_data->cb.found && optSubPix){
        cvFindCornerSubPix(m_data->ipl, corners.data(), corners.size(), cvSize(radius,radius),
                           cvSize(innerR, innerR),
                           cvTermCriteria(CV_TERMCRIT_EPS+CV_TERMCRIT_ITER, maxIter, minErr));
      }

      if(m_data->cb.found){
        m_data->cb.corners.resize(corners.size());
        for(size_t i=0;i<corners.size();++i){
          m_data->cb.corners[i] = Point32f(corners[i].x, corners[i].y);
        }
      }else{
        m_data->cb.corners.clear();
      }

      return m_data->cb;
    }
/// Propagates the given property to all contained scatterers that have this
/// property.
void CompositeBraggScatterer::propagateProperty(
    const std::string &propertyName) {
  std::string propertyValue = getPropertyValue(propertyName);

  for (auto &scatterer : m_scatterers) {
    propagatePropertyToScatterer(scatterer, propertyName, propertyValue);
  }
}
Пример #17
0
Array<String> CIMHelper::getPropertyAsStringArray(const CIMInstance &instanceObject, String name)
{
    CIMValue value = getPropertyValue(instanceObject, name);
    if (value.isNull()) return Array<String>();
    Array<String> result;
    value.get(result);
    return result;
}
Пример #18
0
/// Propagates the given property to all contained scatterers that have this
/// property.
void
CompositeBraggScatterer::propagateProperty(const std::string &propertyName) {
  std::string propertyValue = getPropertyValue(propertyName);

  for (auto it = m_scatterers.begin(); it != m_scatterers.end(); ++it) {
    propagatePropertyToScatterer(*it, propertyName, propertyValue);
  }
}
Пример #19
0
Uint64 CIMHelper::getPropertyAsUint64(const CIMInstance &instanceObject, String name)
{
    CIMValue value = getPropertyValue(instanceObject, name);
    if (value.isNull()) return PEG_NOT_FOUND;
    Uint64 result;
    value.get(result);
    return result;
}
Пример #20
0
/**
 * Generate the history of a given workspace.
 * @param workspace :: The workspace to obtain the history from.
 * @return The history of a given workspace.
 */
const std::string CatalogPublish::generateWorkspaceHistory(
    Mantid::API::Workspace_sptr &workspace) {
  auto wsHistory = Mantid::API::AlgorithmManager::Instance().createUnmanaged(
      "GeneratePythonScript");
  wsHistory->initialize();
  wsHistory->setProperty("InputWorkspace", workspace->name());
  wsHistory->execute();
  return wsHistory->getPropertyValue("ScriptText");
}
Пример #21
0
/** Executes the algorithm
*  @throw invalid_argument if the detection delay time is different for different monitors
*  @throw FileError if there was a problem opening the file or its format
*  @throw MisMatch<int> if not very spectra is associated with exaltly one detector
*  @throw IndexError if there is a problem converting spectra indexes to spectra numbers, which would imply there is a problem with the workspace
*  @throw runtime_error if the SpectraDetectorMap had not been filled
*/
void LoadDetectorInfo::exec()
{
  // get the infomation that will be need from the user selected workspace, assume it exsists because of the validator in init()
  m_workspace = getProperty("Workspace");
  m_numHists = static_cast<int>(m_workspace->getNumberHistograms());
  // when we change the X-values will care take to maintain sharing. I have only implemented maintaining sharing where _all_ the arrays are initiall common
  m_commonXs = WorkspaceHelpers::sharedXData(m_workspace);
  // set the other member variables to their defaults
  m_FracCompl = 0.0;
  m_monitors.clear();
  m_monitOffset = UNSETOFFSET;
  m_error = false;
  m_moveDets = getProperty("RelocateDets");
  if( m_moveDets )
  {
    Geometry::IObjComponent_const_sptr sample = m_workspace->getInstrument()->getSample();
    if( sample ) m_samplePos = sample->getPos();
  }

  // get the user selected filename
  std::string filename = getPropertyValue("DataFilename");
  // load the data from the file using the correct algorithm depending on the assumed type of file
  if ( filename.find(".dat") == filename.size()-4 ||
    filename.find(".DAT") == filename.size()-4 )
  {
    readDAT(filename);
  }
  if ( filename.find(".sca") == filename.size()-4 ||
    filename.find(".SCA") == filename.size()-4 )
  {
    readDAT(filename);
  }
  
  if ( filename.find(".raw") == filename.size()-4 ||
    filename.find(".RAW") == filename.size()-4)
  {
    readRAW(filename);
  }

  if (m_error)
  {
    g_log.warning() << "Note workspace " << getPropertyValue("Workspace") << " has been changed so if you intend to fix detector mismatch problems by running " << name() << " on this workspace again is likely to corrupt it" << std::endl;
  }
}
Пример #22
0
/**
 * Loads the mapping between index -> set of detector IDs
 *
 * If "detector_index", "detector_count" and "detector_list" are all present,
 * use these to get the mapping, otherwise spectrum number = detector ID
 * (one-to-one)
 *
 * The spectrum spectrum_index[i] maps to detector_count[i] detectors, whose
 * detector IDs are in detector_list starting at the index detector_index[i]
 *
 * @returns :: map of index -> detector IDs
 * @throws std::runtime_error if fails to read data from file
 */
std::map<int, std::set<int>>
LoadMuonNexus2::loadDetectorMapping(const Mantid::NeXus::NXInt &spectrumIndex) {
  std::map<int, std::set<int>> mapping;
  const int nSpectra = spectrumIndex.dim0();

  // Find and open the data group
  NXRoot root(getPropertyValue("Filename"));
  NXEntry entry = root.openEntry(m_entry_name);
  const std::string detectorName = [&entry]() {
    // Only the first NXdata found
    for (auto &group : entry.groups()) {
      std::string className = group.nxclass;
      if (className == "NXdata") {
        return group.nxname;
      }
    }
    throw std::runtime_error("No NXdata found in file");
  }();
  NXData dataGroup = entry.openNXData(detectorName);

  // Usually for muon data, detector id = spectrum number
  // If not, the optional groups "detector_index", "detector_list" and
  // "detector_count" will be present to map one to the other
  const bool hasDetectorMapping = dataGroup.containsDataSet("detector_index") &&
                                  dataGroup.containsDataSet("detector_list") &&
                                  dataGroup.containsDataSet("detector_count");
  if (hasDetectorMapping) {
    // Read detector IDs
    try {
      const auto detIndex = dataGroup.openNXInt("detector_index");
      const auto detCount = dataGroup.openNXInt("detector_count");
      const auto detList = dataGroup.openNXInt("detector_list");
      const int nSpectra = detIndex.dim0();
      for (int i = 0; i < nSpectra; ++i) {
        const int start = detIndex[i];
        const int nDetectors = detCount[i];
        std::set<int> detIDs;
        for (int jDet = 0; jDet < nDetectors; ++jDet) {
          detIDs.insert(detList[start + jDet]);
        }
        mapping[i] = detIDs;
      }
    } catch (const ::NeXus::Exception &err) {
      // Throw a more user-friendly message
      std::ostringstream message;
      message << "Failed to read detector mapping: " << err.what();
      throw std::runtime_error(message.str());
    }
  } else {
    for (int i = 0; i < nSpectra; ++i) {
      mapping[i] = std::set<int>{spectrumIndex[i]};
    }
  }

  return mapping;
}
	/**
	 *
	 * \param nValue 
	 * \param area 
	 */
	void			EditorTerrainPage::alterEnd(int nValue)
	{
		switch( nValue )
		{
		case 0:
			{
				uint32 nSize = m_AlterRect.width() * m_AlterRect.height();
				if(nSize && m_pSaveHeight)
				{
					float*	pData	= new float[nSize];
					int		nPos	= 0;	
					int		nRowSize= m_pTerrain->getSize();

					for(int y=m_AlterRect.top; y<m_AlterRect.bottom; y++)
					{
						for(int x=m_AlterRect.left; x<m_AlterRect.right; x++)
						{
							pData[nPos] = m_pSaveHeight[y * nRowSize + x];

							++ nPos;
						}
					}

					String name;
					getPropertyValue(terrainPageName[TERRAINPAGE_PLUGIN_NAME], name);
					int nPageX;
					getPropertyValue(terrainPageName[TERRAINPAGE_PAGEX], nPageX);
					int nPageY;
					getPropertyValue(terrainPageName[TERRAINPAGE_PAGEY], nPageY);

					EditorActionManager::getSingleton().addRedo( 
						new EditorHeightAction(name, nPageX, nPageY, pData, m_AlterRect));
					
					delete [] pData;
					delete [] m_pSaveHeight;
					m_pSaveHeight = NULL;
					
					m_AlterRect = Rect(0, 0, 0, 0);
				}
			}
			break;
		}
	}
Пример #24
0
/// Appends the removal of the empty group after execution to the PairedGroupAlgorithm::processGroups method
bool ConjoinWorkspaces::processGroups(API::WorkspaceGroup_sptr wsPt, const std::vector<Kernel::Property*>& prop)
{
  // Call the base class method for most of the functionality
  const bool retval = PairedGroupAlgorithm::processGroups(wsPt,prop);

  // If that was successful, remove the now empty group in the second input workspace property
  if (retval) AnalysisDataService::Instance().remove(getPropertyValue("InputWorkspace2"));

  return retval;
}
Пример #25
0
  /**
   * Execute the algorithm
   */
  void LoadLOQDistancesFromRaw::exec()
  {
    std::string filename = getPropertyValue("Filename");
    FILE* file = fopen(filename.c_str(), "rb");
    if (file == NULL)
    {
      g_log.error("Unable to open file " + filename);
      throw Exception::FileError("Unable to open File:", filename);
    }

    ISISRAW2 *isis_raw = new ISISRAW2;
    isis_raw->ioRAW(file, true);

    MatrixWorkspace_sptr data_ws = getProperty("InputWorkspace");
    // Specific LOQ distances
    // Moderator to sample distance (primary flight path)
    double i_l1 = static_cast<double>(isis_raw->ivpb.i_l1);
    // Sample-det distance (secondary flight path)
    double sddist = static_cast<double>(isis_raw->ivpb.i_sddist);
    g_log.debug() << "Flight paths: moderator-sample: " << i_l1 << "m,  sample-detector: " << sddist << "m." << std::endl;

    // Get current sample position
    std::string compname = "some-sample-holder";
    Geometry::IComponent_const_sptr sample_holder = data_ws->getInstrument()->getComponentByName(compname);
    if( sample_holder.get() )
    {
      double curr_zpos = sample_holder->getPos().Z();
      double rel_shift = i_l1 - curr_zpos;
      if( std::abs(rel_shift) / curr_zpos > 1e-08 )
      {
        g_log.debug("Running MoveInstrumentComponent as a sub algorithm for the sample holder.");
        // This performs a relative shift in the component along the Z axis
        performMoveComponent(compname, rel_shift, 0.0, 0.5);
      }
    }
    //Now the secondary flight path relative the the sample
    // Redo the get so that it retrieves an up-to-date parameterized component if a move occurred
    sample_holder = data_ws->getInstrument()->getComponentByName(compname);
    //Get the main detector component
    compname = "main-detector-bank";
    Geometry::IComponent_const_sptr main_det = data_ws->getInstrument()->getComponentByName(compname);
    if( main_det.get() && sample_holder.get() )
    {
      double curr_zpos = main_det->getPos().Z();
      double rel_shift = i_l1 + sddist - curr_zpos;
      if( std::abs(rel_shift) / curr_zpos > 1e-08 )
      {
        g_log.debug("Running MoveInstrumentComponent as a sub algorithm for the main-detector-bank");
        // This performs a relative shift in the component along the Z axis
        performMoveComponent(compname, rel_shift, 0.5, 1.0);
      }
    }
    // Free the used memory
    delete isis_raw;
  }
/** Execute the algorithm.
 */
void LoadILLReflectometry::exec() {
  // Retrieve filename
  std::string filenameData = getPropertyValue("Filename");

  // open the root node
  NeXus::NXRoot dataRoot(filenameData);
  NXEntry firstEntry = dataRoot.openFirstEntry();

  // Load Monitor details: n. monitors x monitor contents
  std::vector<std::vector<int>> monitorsData = loadMonitors(firstEntry);

  // Load Data details (number of tubes, channels, etc)
  loadDataDetails(firstEntry);

  std::string instrumentPath = m_loader.findInstrumentNexusPath(firstEntry);
  setInstrumentName(firstEntry, instrumentPath);

  initWorkSpace(firstEntry, monitorsData);

  g_log.debug("Building properties...");
  loadNexusEntriesIntoProperties(filenameData);

  g_log.debug("Loading data...");
  loadDataIntoTheWorkSpace(firstEntry, monitorsData);

  // load the instrument from the IDF if it exists
  g_log.debug("Loading instrument definition...");
  runLoadInstrument();

  // 1) Move

  // Get distance and tilt angle stored in nexus file
  // Mantid way
  ////	auto angleProp =
  /// dynamic_cast<PropertyWithValue<double>*>(m_localWorkspace->run().getProperty("dan.value"));
  // Nexus way
  double angle =
      firstEntry.getFloat("instrument/dan/value"); // detector angle in degrees
  double distance = firstEntry.getFloat(
      "instrument/det/value"); // detector distance in millimeter

  distance /= 1000.0; // convert to meter
  g_log.debug() << "Moving detector at angle " << angle << " and distance "
                << distance << std::endl;
  placeDetector(distance, angle);

  // Set the channel width property
  auto channel_width = dynamic_cast<PropertyWithValue<double> *>(
      m_localWorkspace->run().getProperty("monitor1.time_of_flight_0"));
  m_localWorkspace->mutableRun().addProperty<double>(
      "channel_width", *channel_width, true); // overwrite

  // Set the output workspace property
  setProperty("OutputWorkspace", m_localWorkspace);
}
Пример #27
0
void NormaliseByCurrent::exec()
{
  // Get the input workspace
  MatrixWorkspace_sptr inputWS = getProperty("InputWorkspace");
  MatrixWorkspace_sptr outputWS = getProperty("OutputWorkspace");

  // Get the good proton charge and check it's valid
  double charge(-1.0);
  try
  {
    charge = inputWS->run().getProtonCharge();
  }
  catch(Exception::NotFoundError &)
  {
    g_log.error() << "The proton charge is not set for the run attached to this workspace\n";
    throw;
  }

  if (charge == 0)
  {
    throw std::domain_error("The proton charge is zero");
  }

  g_log.information() << "Normalisation current: " << charge << " uamps" <<  std::endl;

  charge=1.0/charge; // Inverse of the charge to be multiplied by

  // The operator overloads properly take into account of both EventWorkspaces and doing it in place or not.

  if (getPropertyValue("InputWorkspace") != getPropertyValue("OutputWorkspace"))
  {
    outputWS = inputWS*charge;
    setProperty("OutputWorkspace", outputWS);
  }
  else
  {
    inputWS *= charge;
    setProperty("OutputWorkspace", inputWS);
  }

  outputWS->setYUnitLabel("Counts per microAmp.hour");
}
Пример #28
0
bool getPropertyValue(CComPtr<IDispatchEx> object, CStringW propertyName, VARIANT& result)
{
	DISPID dispId;
	BSTR name = SysAllocString(propertyName);
	HRESULT hr = object->GetIDsOfNames(IID_NULL, &name, 1, LOCALE_SYSTEM_DEFAULT, &dispId);
	SysFreeString(name);
	if (FAILED(hr))
		return false;

	return getPropertyValue(object, dispId, result);
}
Пример #29
0
/**
 * Use the LoadHelper utility to load most of the nexus entries into workspace
 * sample log properties
 */
void LoadILLReflectometry::loadNexusEntriesIntoProperties() {
  g_log.debug("Building properties...");
  // Open NeXus file
  const std::string filename{getPropertyValue("Filename")};
  NXhandle nxfileID;
  NXstatus stat = NXopen(filename.c_str(), NXACC_READ, &nxfileID);
  if (stat == NX_ERROR)
    throw Kernel::Exception::FileError("Unable to open File:", filename);
  m_loader.addNexusFieldsToWsRun(nxfileID, m_localWorkspace->mutableRun());
  stat = NXclose(&nxfileID);
}
Пример #30
0
/// Appends the removal of the empty group after execution to the
/// Algorithm::processGroups() method
bool ConjoinWorkspaces::processGroups() {
  // Call the base class method for most of the functionality
  const bool retval = Algorithm::processGroups();

  // If that was successful, remove the now empty group in the second input
  // workspace property
  if (retval)
    AnalysisDataService::Instance().remove(getPropertyValue("InputWorkspace2"));

  return retval;
}