/**
 * Overridden remove member to delete its name held by the workspace itself.
 * It is important to do if the workspace isn't deleted after removal.
 * @param name The name of a workspace to remove.
 */
void AnalysisDataServiceImpl::remove(const std::string &name) {
  Workspace_sptr ws;
  try {
    ws = retrieve(name);
  } catch (Kernel::Exception::NotFoundError) {
    // do nothing - remove will do what's needed
  }
  Kernel::DataService<API::Workspace>::remove(name);
  if (ws) {
    ws->setName("");
  }
}
  /**
   * Make ADS entry to point to the given workspace.
   */
  void ScopedWorkspace::set(Workspace_sptr newWS)
  {
    AnalysisDataServiceImpl& ads = AnalysisDataService::Instance();

    if ( ! newWS->name().empty() && ads.doesExist( newWS->name() ) )
      throw std::invalid_argument( "Workspace is already in the ADS under the name " + newWS->name() );

    // Remove previous workspace entry
    remove();

    ads.add(m_name, newWS); 
  }
Exemple #3
0
    /** Execute the algorithm.
     */
    void DgsReduction::exec()
    {
      // Reduction property manager
      const std::string reductionManagerName = this->getProperty("ReductionProperties");
      if (reductionManagerName.empty())
      {
        g_log.error() << "ERROR: Reduction Property Manager name is empty" << std::endl;
        return;
      }
      this->reductionManager = boost::make_shared<PropertyManager>();
      PropertyManagerDataService::Instance().addOrReplace(reductionManagerName,
          this->reductionManager);

      // Put all properties except input files/workspaces into property manager.
      const std::vector<Property *> props = this->getProperties();
      std::vector<Property *>::const_iterator iter = props.begin();
      for (; iter != props.end(); ++iter)
      {
        if (!boost::contains((*iter)->name(), "Input"))
        {
          this->reductionManager->declareProperty((*iter)->clone());
        }
      }
      // Determine the default facility
      const FacilityInfo defaultFacility = ConfigService::Instance().getFacility();

      // Need to load data to get certain bits of information.
      Workspace_sptr sampleWS = this->loadInputData("Sample");
      MatrixWorkspace_sptr WS = boost::dynamic_pointer_cast<MatrixWorkspace>(sampleWS);
      this->reductionManager->declareProperty(new PropertyWithValue<std::string>(
          "InstrumentName", WS->getInstrument()->getName()));

      // Check the facility for the loaded file and make sure it's the
      // same as the default.
      const InstrumentInfo info = ConfigService::Instance().getInstrument(WS->getInstrument()->getName());
      if (defaultFacility.name() != info.facility().name())
      {
        std::ostringstream mess;
        mess << "Default facility must be set to " << info.facility().name();
        mess << " in order for reduction to work!";
        throw std::runtime_error(mess.str());
      }

      MatrixWorkspace_sptr sampleMonWS = this->getProperty("SampleInputMonitorWorkspace");

      const bool showIntermedWS = this->getProperty("ShowIntermediateWorkspaces");

      // Get output workspace pointer and name
      MatrixWorkspace_sptr outputWS = this->getProperty("OutputWorkspace");
      std::string outputWsName = this->getPropertyValue("OutputWorkspace");
      if (boost::ends_with(outputWsName, "_spe"))
      {
        boost::erase_all(outputWsName, "_spe");
      }

      // Load the hard mask if available
      MatrixWorkspace_sptr hardMaskWS = this->loadHardMask();
      if (hardMaskWS && showIntermedWS)
      {
        std::string hardMaskName = outputWsName + "_hardmask";
        this->declareProperty(new WorkspaceProperty<>("ReductionHardMask",
            hardMaskName, Direction::Output));
        this->setProperty("ReductionHardMask", hardMaskWS);
      }
      // Load the grouping file if available
      MatrixWorkspace_sptr groupingWS = this->loadGroupingFile("");
      if (groupingWS && showIntermedWS)
      {
        std::string groupName = outputWsName + "_grouping";
        this->declareProperty(new WorkspaceProperty<>("ReductionGrouping",
            groupName, Direction::Output));
        this->setProperty("ReductionGrouping", groupingWS);
      }

      // This will be diagnostic mask if DgsDiagnose is run and hard mask if not.
      MatrixWorkspace_sptr maskWS;

      // Process the sample detector vanadium if present
      Workspace_sptr detVanWS = this->loadInputData("DetectorVanadium", false);
      MatrixWorkspace_sptr detVanMonWS = this->getProperty("DetectorVanadiumInputMonitorWorkspace");
      bool isProcessedDetVan = this->getProperty("UseProcessedDetVan");
      // Process a comparison detector vanadium if present
      Workspace_sptr detVan2WS = this->loadInputData("DetectorVanadium2", false);
      MatrixWorkspace_sptr detVan2MonWS = this->getProperty("DetectorVanadium2InputMonitorWorkspace");
      IAlgorithm_sptr detVan;
      Workspace_sptr idetVanWS;
      if (detVanWS && !isProcessedDetVan)
      {
        std::string detVanMaskName = outputWsName + "_diagmask";

        IAlgorithm_sptr diag = this->createChildAlgorithm("DgsDiagnose");
        diag->setProperty("DetVanWorkspace", detVanWS);
        diag->setProperty("DetVanMonitorWorkspace", detVanMonWS);
        diag->setProperty("DetVanCompWorkspace", detVan2WS);
        diag->setProperty("DetVanCompMonitorWorkspace", detVan2MonWS);
        diag->setProperty("SampleWorkspace", sampleWS);
        diag->setProperty("SampleMonitorWorkspace", sampleMonWS);
        diag->setProperty("HardMaskWorkspace", hardMaskWS);
        diag->setProperty("ReductionProperties", reductionManagerName);
        diag->executeAsChildAlg();
        maskWS = diag->getProperty("OutputWorkspace");

        if (showIntermedWS)
        {
          this->declareProperty(new WorkspaceProperty<>("SampleDetVanDiagMask",
              detVanMaskName, Direction::Output));
          this->setProperty("SampleDetVanDiagMask", maskWS);
        }

        detVan = this->createChildAlgorithm("DgsProcessDetectorVanadium");
        detVan->setProperty("InputWorkspace", detVanWS);
        detVan->setProperty("InputMonitorWorkspace", detVanMonWS);
        detVan->setProperty("MaskWorkspace", maskWS);
        std::string idetVanName = outputWsName + "_idetvan";
        detVan->setProperty("ReductionProperties", reductionManagerName);
        detVan->executeAsChildAlg();
        MatrixWorkspace_sptr oWS = detVan->getProperty("OutputWorkspace");
        idetVanWS = boost::dynamic_pointer_cast<Workspace>(oWS);

        if (showIntermedWS)
        {
          this->declareProperty(new WorkspaceProperty<>("IntegratedNormWorkspace",
              idetVanName, Direction::Output));
          this->setProperty("IntegratedNormWorkspace", idetVanWS);
        }
      }
      else
      {
        idetVanWS = detVanWS;
        maskWS = boost::dynamic_pointer_cast<MatrixWorkspace>(idetVanWS);
        detVanWS.reset();
      }

      IAlgorithm_sptr etConv = this->createChildAlgorithm("DgsConvertToEnergyTransfer");
      etConv->setProperty("InputWorkspace", sampleWS);
      etConv->setProperty("InputMonitorWorkspace", sampleMonWS);
      etConv->setProperty("IntegratedDetectorVanadium", idetVanWS);
      const double ei = this->getProperty("IncidentEnergyGuess");
      etConv->setProperty("IncidentEnergyGuess", ei);
      if (!maskWS && hardMaskWS)
      {
        maskWS = hardMaskWS;
      }
      etConv->setProperty("MaskWorkspace", maskWS);
      if (groupingWS)
      {
        etConv->setProperty("GroupingWorkspace", groupingWS);
      }
      etConv->setProperty("ReductionProperties", reductionManagerName);
      std::string tibWsName = this->getPropertyValue("OutputWorkspace") + "_tib";
      etConv->executeAsChildAlg();
      outputWS = etConv->getProperty("OutputWorkspace");
      MatrixWorkspace_sptr tibWS = etConv->getProperty("OutputTibWorkspace");

      if (tibWS && showIntermedWS)
      {
        this->declareProperty(new WorkspaceProperty<>("SampleTibWorkspace",
            tibWsName, Direction::Output));
        this->setProperty("SampleTibWorkspace", tibWS);
      }

      Workspace_sptr absSampleWS = this->loadInputData("AbsUnitsSample", false);

      // Perform absolute normalisation if necessary
      if (absSampleWS)
      {
        std::string absWsName = outputWsName + "_absunits";

        // Collect the other workspaces first.
        MatrixWorkspace_sptr absSampleMonWS = this->getProperty("AbsUnitsSampleInputMonitorWorkspace");
        Workspace_sptr absDetVanWS = this->loadInputData("AbsUnitsDetectorVanadium", false);
        MatrixWorkspace_sptr absDetVanMonWS = this->getProperty("AbsUnitsDetectorVanadiumInputMonitorWorkspace");
        MatrixWorkspace_sptr absGroupingWS = this->loadGroupingFile("AbsUnits");

        // Run the absolute normalisation reduction
        IAlgorithm_sptr absUnitsRed = this->createChildAlgorithm("DgsAbsoluteUnitsReduction");
        absUnitsRed->setProperty("InputWorkspace", absSampleWS);
        absUnitsRed->setProperty("InputMonitorWorkspace", absSampleMonWS);
        absUnitsRed->setProperty("DetectorVanadiumWorkspace", absDetVanWS);
        absUnitsRed->setProperty("DetectorVanadiumMonitorWorkspace",
            absDetVanMonWS);
        absUnitsRed->setProperty("GroupingWorkspace", absGroupingWS);
        absUnitsRed->setProperty("MaskWorkspace", maskWS);
        absUnitsRed->setProperty("ReductionProperties", reductionManagerName);
        absUnitsRed->executeAsChildAlg();
        MatrixWorkspace_sptr absUnitsWS = absUnitsRed->getProperty("OutputWorkspace");
//!!! There is Property outputMaskWorkspace to get masks? It looks like one is using wrong property for masks
        MatrixWorkspace_sptr absMaskWS = absUnitsRed->getProperty("OutputWorkspace");

        IAlgorithm_sptr mask = this->createChildAlgorithm("MaskDetectors");
        mask->setProperty("Workspace", outputWS);
        mask->setProperty("MaskedWorkspace", absMaskWS);
        mask->executeAsChildAlg();
        outputWS = mask->getProperty("Workspace");

        // Do absolute normalisation
        outputWS = divide(outputWS, absUnitsWS);

        if (showIntermedWS)
        {
          this->declareProperty(new WorkspaceProperty<>("AbsUnitsWorkspace",
              absWsName, Direction::Output));
          this->setProperty("AbsUnitsWorkspace", absUnitsWS);
          this->declareProperty(new WorkspaceProperty<>("AbsUnitsDiagMask",
              outputWsName+"_absunits_diagmask", Direction::Output));
          this->setProperty("AbsUnitsDiagMask", absMaskWS);
        }
      }

      // Convert from DeltaE to powder S(Q,W)
      const bool doPowderConvert = this->getProperty("DoPowderDataConversion");
      if (doPowderConvert)
      {
        g_log.notice() << "Converting to powder S(Q,W)" << std::endl;
        // Collect information
        std::string sqwWsName = outputWsName + "_pd_sqw";
        std::vector<double> qBinning = this->getProperty("PowderMomTransferRange");
        const double initialEnergy = boost::lexical_cast<double>(outputWS->run().getProperty("Ei")->value());

        IAlgorithm_sptr sofqw = this->createChildAlgorithm("SofQW3");
        sofqw->setProperty("InputWorkspace", outputWS);
        sofqw->setProperty("QAxisBinning", qBinning);
        sofqw->setProperty("EMode", "Direct");
        sofqw->setProperty("EFixed", initialEnergy);
        sofqw->executeAsChildAlg();
        MatrixWorkspace_sptr sqwWS = sofqw->getProperty("OutputWorkspace");
        this->declareProperty(new WorkspaceProperty<>("PowderSqwWorkspace",
            sqwWsName, Direction::Output));
        this->setProperty("PowderSqwWorkspace", sqwWS);

        const bool saveProcNexus = this->getProperty("SavePowderNexusFile");
        if (saveProcNexus)
        {
          std::string saveProcNexusFilename = this->getProperty("SavePowderNexusFilename");
          if (saveProcNexusFilename.empty())
          {
            saveProcNexusFilename = sqwWsName + ".nxs";
          }
          IAlgorithm_sptr saveNxs = this->createChildAlgorithm("SaveNexus");
          saveNxs->setProperty("InputWorkspace", sqwWS);
          saveNxs->setProperty("Filename", saveProcNexusFilename);
          saveNxs->executeAsChildAlg();
        }
      }

      this->setProperty("OutputWorkspace", outputWS);
    }
Exemple #4
0
  /** Executes the algorithm.
   *
   *  @throw runtime_error Thrown if algorithm cannot execute
   */
  void SaveNexusProcessed::exec()
  {
    //TODO: Remove?
    NXMEnableErrorReporting();

    Workspace_sptr inputWorkspace = getProperty("InputWorkspace");
    boost::shared_ptr<WorkspaceGroup> wsGrpSptr =
                  boost::dynamic_pointer_cast<WorkspaceGroup>(inputWorkspace);
    if(wsGrpSptr)
    {
      processGroups(wsGrpSptr, this->getProperties());
      return;
    }

    Progress prog_init(this, 0.0, 0.3, 5);

    // Retrieve the filename from the properties
    m_filename = getPropertyValue("Filename");
    //m_entryname = getPropertyValue("EntryName");
    m_title = getPropertyValue("Title");
    // Do we prserve events?
    bool PreserveEvents = getProperty("PreserveEvents");

    MatrixWorkspace_const_sptr matrixWorkspace = boost::dynamic_pointer_cast<const MatrixWorkspace>(inputWorkspace);
    ITableWorkspace_const_sptr tableWorkspace = boost::dynamic_pointer_cast<const ITableWorkspace>(inputWorkspace);
    // check if inputWorkspace is something we know how to save
    if (!matrixWorkspace && !tableWorkspace) 
      return;
    m_eventWorkspace = boost::dynamic_pointer_cast<const EventWorkspace>(matrixWorkspace);

    // If no title's been given, use the workspace title field
    if (m_title.empty()) 
      m_title = inputWorkspace->getTitle();

    // If we don't want to append then remove the file if it already exists
    bool append_to_file = getProperty("Append");
    if( !append_to_file )
    {
      Poco::File file(m_filename);
      if( file.exists() )
        file.remove();
    }


    const std::string workspaceID = inputWorkspace->id();
    if ((workspaceID.find("Workspace2D") == std::string::npos) &&
        !m_eventWorkspace && !tableWorkspace)
      throw Exception::NotImplementedError("SaveNexusProcessed passed invalid workspaces. Must be Workspace2D, EventWorkspace or ITableWorkspace.");


    Mantid::NeXus::NexusFileIO *nexusFile= new Mantid::NeXus::NexusFileIO();

    if( nexusFile->openNexusWrite( m_filename ) != 0 )
      throw Exception::FileError("Failed to open file", m_filename);

    // Equivalent C++ API handle
    ::NeXus::File * cppFile = new ::NeXus::File(nexusFile->fileID);

    prog_init.reportIncrement(1, "Opening file");
    if( nexusFile->writeNexusProcessedHeader( m_title ) != 0 )
      throw Exception::FileError("Failed to write to file", m_filename);

    prog_init.reportIncrement(1, "Writing header");

    // write instrument data, if present and writer enabled
    if (matrixWorkspace) 
    { 
      // Save the instrument names, ParameterMap, sample, run
      matrixWorkspace->saveExperimentInfoNexus(cppFile);
      prog_init.reportIncrement(1, "Writing sample and instrument");

      // check if all X() are in fact the same array
      const bool uniformSpectra = API::WorkspaceHelpers::commonBoundaries(matrixWorkspace);

      // Retrieve the workspace indices (from params)
      std::vector<int> spec;
      this->getSpectrumList(spec, matrixWorkspace);

      // Write out the data (2D or event)
      if (m_eventWorkspace && PreserveEvents)
      {
        this->execEvent(nexusFile,uniformSpectra,spec);
      }
      else
      {
        nexusFile->writeNexusProcessedData2D(matrixWorkspace,uniformSpectra,spec, "workspace", true);
      }

      // MW 27/10/10 - don't try and save the spectra-detector map if there isn't one
      if ( matrixWorkspace->getAxis(1)->isSpectra() )
      {
        cppFile->openGroup("instrument", "NXinstrument");
        matrixWorkspace->saveSpectraMapNexus(cppFile, spec, ::NeXus::LZW);
        cppFile->closeGroup();
      }

    }  // finish matrix workspace specifics 
    
    if (tableWorkspace)
    {
      nexusFile->writeNexusTableWorkspace(tableWorkspace,"table_workspace");
    }
 
    nexusFile->writeNexusProcessedProcess(inputWorkspace);
    nexusFile->closeNexusFile();

    delete nexusFile;

    return;
  }
Exemple #5
0
/** Execute the algorithm.
 */
void ClearUB::exec() {
  Workspace_sptr ws = getProperty("Workspace");
  bool doesClear = doExecute(ws.get(), false /* Not a dry run*/);
  this->setProperty("DoesClear", doesClear);
}
Exemple #6
0
void LoadFlexiNexus::addMetaData(NeXus::File *fin, Workspace_sptr ws,
                                 ExperimentInfo_sptr info) {
  std::map<std::string, std::string>::const_iterator it;

  // assign a title
  if ((it = dictionary.find("title")) == dictionary.end()) {
    const std::string title("No title found");
    ws->setTitle(title);
  } else {
    if (it->second.find('/') == it->second.npos) {
      const std::string title(it->second);
      ws->setTitle(title);
    } else {
      if (safeOpenpath(fin, it->second)) {
        const std::string title = fin->getStrData();
        ws->setTitle(title);
      }
    }
  }

  // assign a sample name
  std::string sample;
  if ((it = dictionary.find("sample")) == dictionary.end()) {
    sample = "No sample found";
  } else {
    if (it->second.find('/') == it->second.npos) {
      sample = it->second;
    } else {
      if (safeOpenpath(fin, it->second)) {
        sample = fin->getStrData();
      } else {
        sample = "Sampe plath not found";
      }
    }
  }
  info->mutableSample().setName(sample);

  /**
  * load all the extras into the Run information
  */
  Run &r = info->mutableRun();
  std::set<std::string> specialMap = populateSpecialMap();
  for (it = dictionary.begin(); it != dictionary.end(); ++it) {
    if (specialMap.find(it->first) == specialMap.end()) {
      // not in specials!
      if (it->second.find('/') == it->second.npos) {
        r.addProperty(it->first, it->second, true);
      } else {
        if (safeOpenpath(fin, it->second)) {
          NeXus::Info inf = fin->getInfo();
          if (inf.type == ::NeXus::CHAR) {
            std::string data = fin->getStrData();
            r.addProperty(it->first, data, true);
          } else if (inf.type == ::NeXus::FLOAT32 ||
                     inf.type == ::NeXus::FLOAT64) {
            std::vector<double> data;
            fin->getDataCoerce(data);
            r.addProperty(it->first, data, true);
          } else {
            std::vector<int> data;
            fin->getDataCoerce(data);
            r.addProperty(it->first, data, true);
          }
        }
      }
    }
  }
}
  /** Executes the algorithm.
   *
   *  @throw runtime_error Thrown if algorithm cannot execute
   */
  void SaveNexusProcessed::exec()
  {
    //TODO: Remove?
    NXMEnableErrorReporting();

    Workspace_sptr inputWorkspace = getProperty("InputWorkspace");

    // Retrieve the filename from the properties
    m_filename = getPropertyValue("Filename");
    //m_entryname = getPropertyValue("EntryName");
    m_title = getPropertyValue("Title");
    // Do we prserve events?
    bool PreserveEvents = getProperty("PreserveEvents");

    MatrixWorkspace_const_sptr matrixWorkspace = boost::dynamic_pointer_cast<const MatrixWorkspace>(inputWorkspace);
    ITableWorkspace_const_sptr tableWorkspace = boost::dynamic_pointer_cast<const ITableWorkspace>(inputWorkspace);
    PeaksWorkspace_const_sptr peaksWorkspace = boost::dynamic_pointer_cast<const PeaksWorkspace>(inputWorkspace);
    OffsetsWorkspace_const_sptr offsetsWorkspace = boost::dynamic_pointer_cast<const OffsetsWorkspace>(inputWorkspace);
    if(peaksWorkspace) g_log.debug("We have a peaks workspace");
    // check if inputWorkspace is something we know how to save
    if (!matrixWorkspace && !tableWorkspace) {
      g_log.debug() << "Workspace "  << m_title << " not saved because it is not of a type we can presently save.\n";
      return;
    }
    m_eventWorkspace = boost::dynamic_pointer_cast<const EventWorkspace>(matrixWorkspace);
    const std::string workspaceID = inputWorkspace->id();
    if ((workspaceID.find("Workspace2D") == std::string::npos) &&
      (workspaceID.find("RebinnedOutput") == std::string::npos) &&
      !m_eventWorkspace && !tableWorkspace && !offsetsWorkspace)
      throw Exception::NotImplementedError("SaveNexusProcessed passed invalid workspaces. Must be Workspace2D, EventWorkspace, ITableWorkspace, or OffsetsWorkspace.");

    // Create progress object for initial part - depends on whether events are processed
    if( PreserveEvents && m_eventWorkspace)
    {
       m_timeProgInit = 0.07; // Events processed 0.05 to 1.0
    }
    else
    {
      m_timeProgInit = 1.0; // All work is done in the initial part
    }
    Progress prog_init(this, 0.0, m_timeProgInit, 7);

    // If no title's been given, use the workspace title field
    if (m_title.empty()) 
      m_title = inputWorkspace->getTitle();

    // If we don't want to append then remove the file if it already exists
    bool append_to_file = getProperty("Append");
    if( !append_to_file )
    {
      Poco::File file(m_filename);
      if( file.exists() )
        file.remove();
    }
	// Then immediately open the file
    Mantid::NeXus::NexusFileIO *nexusFile= new Mantid::NeXus::NexusFileIO( &prog_init );

    nexusFile->openNexusWrite( m_filename );

    // Equivalent C++ API handle
    ::NeXus::File * cppFile = new ::NeXus::File(nexusFile->fileID);

    prog_init.reportIncrement(1, "Opening file");
    if( nexusFile->writeNexusProcessedHeader( m_title ) != 0 )
      throw Exception::FileError("Failed to write to file", m_filename);

    prog_init.reportIncrement(1, "Writing header");

    // write instrument data, if present and writer enabled
    if (matrixWorkspace) 
    { 
      // Save the instrument names, ParameterMap, sample, run
      matrixWorkspace->saveExperimentInfoNexus(cppFile);
      prog_init.reportIncrement(1, "Writing sample and instrument");

      // check if all X() are in fact the same array
      const bool uniformSpectra = API::WorkspaceHelpers::commonBoundaries(matrixWorkspace);

      // Retrieve the workspace indices (from params)
      std::vector<int> spec;
      this->getSpectrumList(spec, matrixWorkspace);

      prog_init.reportIncrement(1, "Writing data");
      // Write out the data (2D or event)
      if (m_eventWorkspace && PreserveEvents)
      {
        this->execEvent(nexusFile,uniformSpectra,spec);
      }
      else if (offsetsWorkspace)
      {
        g_log.warning() << "Writing SpecialWorkspace2D ID=" << workspaceID << "\n";
        nexusFile->writeNexusProcessedData2D(matrixWorkspace,uniformSpectra,spec, "offsets_workspace", true);
      }
      else
      {
        nexusFile->writeNexusProcessedData2D(matrixWorkspace,uniformSpectra,spec, "workspace", true);
      }

      // MW 27/10/10 - don't try and save the spectra-detector map if there isn't one
      if ( matrixWorkspace->getAxis(1)->isSpectra() )
      {
        cppFile->openGroup("instrument", "NXinstrument");
        matrixWorkspace->saveSpectraMapNexus(cppFile, spec, ::NeXus::LZW);
        cppFile->closeGroup();
      }

    }  // finish matrix workspace specifics 



    if (peaksWorkspace) 
    {
      // Save the instrument names, ParameterMap, sample, run
      peaksWorkspace->saveExperimentInfoNexus(cppFile);
      prog_init.reportIncrement(1, "Writing sample and instrument");
    }


    // peaks workspace specifics
    if (peaksWorkspace)
    {
      //	g_log.information("Peaks Workspace saving to Nexus would be done");
      //	int pNum = peaksWorkspace->getNumberPeaks();
      peaksWorkspace->saveNexus( cppFile );



    } // finish peaks workspace specifics
    else if (tableWorkspace) // Table workspace specifics 
    {
      nexusFile->writeNexusTableWorkspace(tableWorkspace,"table_workspace");
    }  // finish table workspace specifics

    // Switch to the Cpp API for the algorithm history
	  inputWorkspace->getHistory().saveNexus(cppFile);

    nexusFile->closeNexusFile();

    delete nexusFile;

    return;
  }
Exemple #8
0
void SaveNexusProcessed::doExec(Workspace_sptr inputWorkspace,
                                Mantid::NeXus::NexusFileIO_sptr &nexusFile,
                                const bool keepFile,
                                optional_size_t entryNumber) {
  // TODO: Remove?
  NXMEnableErrorReporting();

  // Retrieve the filename from the properties
  m_filename = getPropertyValue("Filename");
  // m_entryname = getPropertyValue("EntryName");
  m_title = getPropertyValue("Title");
  // Do we prserve events?
  bool PreserveEvents = getProperty("PreserveEvents");

  MatrixWorkspace_const_sptr matrixWorkspace =
      boost::dynamic_pointer_cast<const MatrixWorkspace>(inputWorkspace);
  ITableWorkspace_const_sptr tableWorkspace =
      boost::dynamic_pointer_cast<const ITableWorkspace>(inputWorkspace);
  PeaksWorkspace_const_sptr peaksWorkspace =
      boost::dynamic_pointer_cast<const PeaksWorkspace>(inputWorkspace);
  OffsetsWorkspace_const_sptr offsetsWorkspace =
      boost::dynamic_pointer_cast<const OffsetsWorkspace>(inputWorkspace);
  if (peaksWorkspace)
    g_log.debug("We have a peaks workspace");
  // check if inputWorkspace is something we know how to save
  if (!matrixWorkspace && !tableWorkspace) {
    // get the workspace name for the error message
    std::string name = getProperty("InputWorkspace");

    // md workspaces should be saved using SaveMD
    if (bool(boost::dynamic_pointer_cast<const IMDEventWorkspace>(
            inputWorkspace)) ||
        bool(boost::dynamic_pointer_cast<const IMDHistoWorkspace>(
            inputWorkspace)))
      g_log.warning() << name << " can be saved using SaveMD\n";

    // standard error message
    std::stringstream msg;
    msg << "Workspace \"" << name
        << "\" not saved because it is not of a type we can presently save.";

    throw std::runtime_error(msg.str());
  }
  m_eventWorkspace =
      boost::dynamic_pointer_cast<const EventWorkspace>(matrixWorkspace);
  const std::string workspaceID = inputWorkspace->id();
  if ((workspaceID.find("Workspace2D") == std::string::npos) &&
      (workspaceID.find("RebinnedOutput") == std::string::npos) &&
      !m_eventWorkspace && !tableWorkspace && !offsetsWorkspace)
    throw Exception::NotImplementedError(
        "SaveNexusProcessed passed invalid workspaces. Must be Workspace2D, "
        "EventWorkspace, ITableWorkspace, or OffsetsWorkspace.");

  // Create progress object for initial part - depends on whether events are
  // processed
  if (PreserveEvents && m_eventWorkspace) {
    m_timeProgInit = 0.07; // Events processed 0.05 to 1.0
  } else {
    m_timeProgInit = 1.0; // All work is done in the initial part
  }
  Progress prog_init(this, 0.0, m_timeProgInit, 7);

  // If no title's been given, use the workspace title field
  if (m_title.empty())
    m_title = inputWorkspace->getTitle();

  // get the workspace name to write to file
  std::string wsName = inputWorkspace->getName();

  // If we don't want to append then remove the file if it already exists
  bool append_to_file = getProperty("Append");
  if (!append_to_file && !keepFile) {
    Poco::File file(m_filename);
    if (file.exists())
      file.remove();
  }

  nexusFile->resetProgress(&prog_init);
  nexusFile->openNexusWrite(m_filename, entryNumber);

  // Equivalent C++ API handle
  auto cppFile = new ::NeXus::File(nexusFile->fileID);

  prog_init.reportIncrement(1, "Opening file");
  if (nexusFile->writeNexusProcessedHeader(m_title, wsName) != 0)
    throw Exception::FileError("Failed to write to file", m_filename);

  prog_init.reportIncrement(1, "Writing header");

  // write instrument data, if present and writer enabled
  if (matrixWorkspace) {
    // Save the instrument names, ParameterMap, sample, run
    matrixWorkspace->saveExperimentInfoNexus(cppFile);
    prog_init.reportIncrement(1, "Writing sample and instrument");

    // check if all X() are in fact the same array
    const bool uniformSpectra =
        API::WorkspaceHelpers::commonBoundaries(*matrixWorkspace);

    // Retrieve the workspace indices (from params)
    std::vector<int> spec;
    this->getSpectrumList(spec, matrixWorkspace);

    prog_init.reportIncrement(1, "Writing data");
    // Write out the data (2D or event)
    if (m_eventWorkspace && PreserveEvents) {
      this->execEvent(nexusFile.get(), uniformSpectra, spec);
    } else if (offsetsWorkspace) {
      g_log.warning() << "Writing SpecialWorkspace2D ID=" << workspaceID
                      << "\n";
      nexusFile->writeNexusProcessedData2D(matrixWorkspace, uniformSpectra,
                                           spec, "offsets_workspace", true);
    } else {
      nexusFile->writeNexusProcessedData2D(matrixWorkspace, uniformSpectra,
                                           spec, "workspace", true);
    }

    cppFile->openGroup("instrument", "NXinstrument");
    matrixWorkspace->saveSpectraMapNexus(cppFile, spec, ::NeXus::LZW);
    cppFile->closeGroup();

  } // finish matrix workspace specifics

  if (peaksWorkspace) {
    // Save the instrument names, ParameterMap, sample, run
    peaksWorkspace->saveExperimentInfoNexus(cppFile);
    prog_init.reportIncrement(1, "Writing sample and instrument");
  }

  // peaks workspace specifics
  if (peaksWorkspace) {
    //  g_log.information("Peaks Workspace saving to Nexus would be done");
    //  int pNum = peaksWorkspace->getNumberPeaks();
    peaksWorkspace->saveNexus(cppFile);

  }                        // finish peaks workspace specifics
  else if (tableWorkspace) // Table workspace specifics
  {
    nexusFile->writeNexusTableWorkspace(tableWorkspace, "table_workspace");
  } // finish table workspace specifics

  // Switch to the Cpp API for the algorithm history
  if (trackingHistory()) {
    m_history->fillAlgorithmHistory(
        this, Mantid::Kernel::DateAndTime::getCurrentTime(), 0,
        Algorithm::g_execCount);
    if (!isChild()) {
      inputWorkspace->history().addHistory(m_history);
    }
    // this is a child algorithm, but we still want to keep the history.
    else if (isRecordingHistoryForChild() && m_parentHistory) {
      m_parentHistory->addChildHistory(m_history);
    }
  }

  inputWorkspace->history().saveNexus(cppFile);
  nexusFile->closeGroup();
}