Ejemplo n.º 1
0
/**
 * Load a single entry into a workspace
 * @param root :: The opened root node
 * @param entry_name :: The entry name
 * @param progressStart :: The percentage value to start the progress reporting for this entry
 * @param progressRange :: The percentage range that the progress reporting should cover
 * @returns A 2D workspace containing the loaded data
 */
API::Workspace_sptr LoadNexusProcessed::loadEntry(NXRoot & root, const std::string & entry_name,
    const double& progressStart, const double& progressRange)
{
  progress(progressStart,"Opening entry " + entry_name + "...");

  NXEntry mtd_entry = root.openEntry(entry_name);

  if (mtd_entry.containsGroup("table_workspace"))
  {
    return loadTableEntry(mtd_entry);
  }  

  bool isEvent = false;
  std::string group_name = "workspace";
  if (mtd_entry.containsGroup("event_workspace"))
  {
    isEvent = true;
    group_name = "event_workspace";
  }

  // Get workspace characteristics
  NXData wksp_cls = mtd_entry.openNXData(group_name);

  // Axis information
  // "X" axis
  NXDouble xbins = wksp_cls.openNXDouble("axis1");
  xbins.load();
  std::string unit1 = xbins.attributes("units");
  // Non-uniform x bins get saved as a 2D 'axis1' dataset
  int xlength(-1);
  if( xbins.rank() == 2 )
  {
    xlength = xbins.dim1();
    m_shared_bins = false;
  }
  else if( xbins.rank() == 1 )
  {
    xlength = xbins.dim0();
    m_shared_bins = true;
    xbins.load();
    m_xbins.access().assign(xbins(), xbins() + xlength);
  }
  else
  {
    throw std::runtime_error("Unknown axis1 dimension encountered.");
  }

  // MatrixWorkspace axis 1
  NXDouble axis2 = wksp_cls.openNXDouble("axis2");
  std::string unit2 = axis2.attributes("units");

  // The workspace being worked on
  API::MatrixWorkspace_sptr local_workspace;
  size_t nspectra;
  int64_t nchannels;

  // -------- Process as event ? --------------------
  if (isEvent)
  {
    local_workspace = loadEventEntry(wksp_cls, xbins, progressStart, progressRange);
    nspectra = local_workspace->getNumberHistograms();
    nchannels = local_workspace->blocksize();
  }
  else
  {
    NXDataSetTyped<double> data = wksp_cls.openDoubleData();
    nspectra = data.dim0();
    nchannels = data.dim1();
    //// validate the optional spectrum parameters, if set
    checkOptionalProperties(nspectra);
    // Actual number of spectra in output workspace (if only a range was going to be loaded)
    int total_specs=calculateWorkspacesize(nspectra);

    //// Create the 2D workspace for the output
    local_workspace = boost::dynamic_pointer_cast<API::MatrixWorkspace>
    (WorkspaceFactory::Instance().create("Workspace2D", total_specs, xlength, nchannels));
    try
    {
      local_workspace->setTitle(mtd_entry.getString("title"));
    }
    catch (std::runtime_error&)
    {
      g_log.debug() << "No title was found in the input file, " << getPropertyValue("Filename") << std::endl;
    }

    // Set the YUnit label
    local_workspace->setYUnit(data.attributes("units"));
    std::string unitLabel = data.attributes("unit_label");
    if (unitLabel.empty()) unitLabel = data.attributes("units");
    local_workspace->setYUnitLabel(unitLabel);
    
    readBinMasking(wksp_cls, local_workspace);
    NXDataSetTyped<double> errors = wksp_cls.openNXDouble("errors");

    int64_t blocksize(8);
    //const int fullblocks = nspectra / blocksize;
    //size of the workspace
    int64_t fullblocks = total_specs / blocksize;
    int64_t read_stop = (fullblocks * blocksize);
    const double progressBegin = progressStart+0.25*progressRange;
    const double progressScaler = 0.75*progressRange;
    int64_t hist_index = 0;
    int64_t wsIndex=0;
    if( m_shared_bins )
    {
      //if spectrum min,max,list properties are set
      if(m_interval||m_list)
      {
        //if spectrum max,min properties are set read the data as a block(multiple of 8) and
        //then read the remaining data as finalblock
        if(m_interval)
        {
          //specs at the min-max interval
          int interval_specs=static_cast<int>(m_spec_max-m_spec_min);
          fullblocks=(interval_specs)/blocksize;
          read_stop = (fullblocks * blocksize)+m_spec_min-1;

          if(interval_specs<blocksize)
          {
            blocksize=total_specs;
            read_stop=m_spec_max-1;
          }
          hist_index=m_spec_min-1;

          for( ; hist_index < read_stop; )
          {
            progress(progressBegin+progressScaler*static_cast<double>(hist_index)/static_cast<double>(read_stop),"Reading workspace data...");
            loadBlock(data, errors, blocksize, nchannels, hist_index,wsIndex, local_workspace);
          }
          int64_t finalblock = m_spec_max-1 - read_stop;
          if( finalblock > 0 )
          {
            loadBlock(data, errors, finalblock, nchannels, hist_index,wsIndex,local_workspace);
          }
        }
        // if spectrum list property is set read each spectrum separately by setting blocksize=1
        if(m_list)
        {
          std::vector<int64_t>::iterator itr=m_spec_list.begin();
          for(;itr!=m_spec_list.end();++itr)
          {
            int64_t specIndex=(*itr)-1;
            progress(progressBegin+progressScaler*static_cast<double>(specIndex)/static_cast<double>(m_spec_list.size()),"Reading workspace data...");
            loadBlock(data, errors, static_cast<int64_t>(1), nchannels, specIndex,wsIndex, local_workspace);
          }

        }
      }
      else
      {
        for( ; hist_index < read_stop; )
        {
          progress(progressBegin+progressScaler*static_cast<double>(hist_index)/static_cast<double>(read_stop),"Reading workspace data...");
          loadBlock(data, errors, blocksize, nchannels, hist_index,wsIndex, local_workspace);
        }
        int64_t finalblock = total_specs - read_stop;
        if( finalblock > 0 )
        {
          loadBlock(data, errors, finalblock, nchannels, hist_index,wsIndex,local_workspace);
        }
      }

    }
    else
    {
      if(m_interval||m_list)
      {
        if(m_interval)
        {
          int64_t interval_specs=m_spec_max-m_spec_min;
          fullblocks=(interval_specs)/blocksize;
          read_stop = (fullblocks * blocksize)+m_spec_min-1;

          if(interval_specs<blocksize)
          {
            blocksize=interval_specs;
            read_stop=m_spec_max-1;
          }
          hist_index=m_spec_min-1;

          for( ; hist_index < read_stop; )
          {
            progress(progressBegin+progressScaler*static_cast<double>(hist_index)/static_cast<double>(read_stop),"Reading workspace data...");
            loadBlock(data, errors, xbins, blocksize, nchannels, hist_index,wsIndex,local_workspace);
          }
          int64_t finalblock = m_spec_max-1 - read_stop;
          if( finalblock > 0 )
          {
            loadBlock(data, errors, xbins, finalblock, nchannels, hist_index,wsIndex, local_workspace);
          }
        }
        //
        if(m_list)
        {
          std::vector<int64_t>::iterator itr=m_spec_list.begin();
          for(;itr!=m_spec_list.end();++itr)
          {
            int64_t specIndex=(*itr)-1;
            progress(progressBegin+progressScaler*static_cast<double>(specIndex)/static_cast<double>(read_stop),"Reading workspace data...");
            loadBlock(data, errors, xbins, 1, nchannels, specIndex,wsIndex,local_workspace);
          }

        }
      }
      else
      {
        for( ; hist_index < read_stop; )
        {
          progress(progressBegin+progressScaler*static_cast<double>(hist_index)/static_cast<double>(read_stop),"Reading workspace data...");
          loadBlock(data, errors, xbins, blocksize, nchannels, hist_index,wsIndex,local_workspace);
        }
        int64_t finalblock = total_specs - read_stop;
        if( finalblock > 0 )
        {
          loadBlock(data, errors, xbins, finalblock, nchannels, hist_index,wsIndex, local_workspace);
        }
      }
    }
  } //end of NOT an event -------------------------------



  //Units
  try
  {
    local_workspace->getAxis(0)->unit() = UnitFactory::Instance().create(unit1);
    //If this doesn't throw then it is a numeric access so grab the data so we can set it later
    axis2.load();
    m_axis1vals = MantidVec(axis2(), axis2() + axis2.dim0());
  }
  catch( std::runtime_error & )
  {
    g_log.information() << "Axis 0 set to unitless quantity \"" << unit1 << "\"\n";
  }

  // Setting a unit onto a SpectraAxis makes no sense.
  if ( unit2 == "TextAxis" )
  {
    Mantid::API::TextAxis* newAxis = new Mantid::API::TextAxis(nspectra);
    local_workspace->replaceAxis(1, newAxis);
  }
  else if ( unit2 != "spectraNumber" )
  {
    try
    {
      Mantid::API::NumericAxis* newAxis = new Mantid::API::NumericAxis(nspectra);
      local_workspace->replaceAxis(1, newAxis);
      newAxis->unit() = UnitFactory::Instance().create(unit2);
    }
    catch( std::runtime_error & )
    {
      g_log.information() << "Axis 1 set to unitless quantity \"" << unit2 << "\"\n";
    }
  }


  //Are we a distribution
  std::string dist = xbins.attributes("distribution");
  if( dist == "1" )
  {
    local_workspace->isDistribution(true);
  }
  else
  {
    local_workspace->isDistribution(false);
  }

  //Get information from all but data group
  std::string parameterStr;

  progress(progressStart+0.05*progressRange,"Reading the sample details...");

  // Hop to the right point
  cppFile->openPath(mtd_entry.path());
  try
  {
    // This loads logs, sample, and instrument.
    local_workspace->loadExperimentInfoNexus(cppFile, parameterStr);
  }
  catch (std::exception & e)
  {
    g_log.information("Error loading Instrument section of nxs file");
    g_log.information(e.what());
  }

  // Now assign the spectra-detector map
  readInstrumentGroup(mtd_entry, local_workspace);

  // Parameter map parsing
  progress(progressStart+0.11*progressRange,"Reading the parameter maps...");
  local_workspace->readParameterMap(parameterStr);


  if ( ! local_workspace->getAxis(1)->isSpectra() )
  { // If not a spectra axis, load the axis data into the workspace. (MW 25/11/10)
    loadNonSpectraAxis(local_workspace, wksp_cls);
  }

  progress(progressStart+0.15*progressRange,"Reading the workspace history...");
  try
  {
    readAlgorithmHistory(mtd_entry, local_workspace);
  }
  catch (std::out_of_range&)
  {
    g_log.warning() << "Error in the workspaces algorithm list, its processing history is incomplete\n";
  }

  progress(progressStart+0.2*progressRange,"Reading the workspace history...");

  return boost::static_pointer_cast<API::Workspace>(local_workspace);
}
Ejemplo n.º 2
0
    /** Executes the algorithm. Reading in the file and creating and populating
     *  the output workspace
     *
     *  @throw Exception::FileError If the RAW file cannot be found/opened
     *  @throw std::invalid_argument If the optional properties are set to invalid values
     */
    void LoadRaw::exec()
    {
      // Retrieve the filename from the properties
      m_filename = getPropertyValue("Filename");

      LoadRawHelper *helper = new LoadRawHelper;
      FILE* file = helper->openRawFile(m_filename);
      ISISRAW iraw;
      iraw.ioRAW(file, true);

      std::string title(iraw.r_title, 80);
      g_log.information("**** Run title: "+title+ "***");
      
      // Read in the number of spectra in the RAW file
      m_numberOfSpectra = iraw.t_nsp1;
      // Read the number of periods in this file
      m_numberOfPeriods = iraw.t_nper;
      // Need to extract the user-defined output workspace name
      Property *ws = getProperty("OutputWorkspace");
      std::string localWSName = ws->value();

      // Call private method to validate the optional parameters, if set
      checkOptionalProperties();

      // Read the number of time channels (i.e. bins) from the RAW file
      const int channelsPerSpectrum = iraw.t_ntc1;
      // Read in the time bin boundaries
      const int lengthIn = channelsPerSpectrum + 1;
      float* timeChannels = new float[lengthIn];
      iraw.getTimeChannels(timeChannels, lengthIn);
      // Put the read in array into a vector (inside a shared pointer)
      boost::shared_ptr<MantidVec> timeChannelsVec
                          (new MantidVec(timeChannels, timeChannels + lengthIn));
      // Create an array to hold the read-in data
      int* spectrum = new int[lengthIn];

      // Calculate the size of a workspace, given its number of periods & spectra to read
      specid_t total_specs;
      if( m_interval || m_list)
      {
        total_specs = static_cast<specid_t>(m_spec_list.size());
        if (m_interval)
        {
          total_specs += (m_spec_max-m_spec_min+1);
          m_spec_max += 1;
        }
      }
      else
      {
        total_specs = m_numberOfSpectra;
        // In this case want all the spectra, but zeroth spectrum is garbage so go from 1 to NSP1
        m_spec_min = 1;
        m_spec_max = m_numberOfSpectra + 1;
      }

      double histTotal = static_cast<double>(total_specs * m_numberOfPeriods);
      int32_t histCurrent = -1;

      // Create the 2D workspace for the output
      DataObjects::Workspace2D_sptr localWorkspace = boost::dynamic_pointer_cast<DataObjects::Workspace2D>
               (WorkspaceFactory::Instance().create("Workspace2D",total_specs,lengthIn,lengthIn-1));
      localWorkspace->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
      localWorkspace->setTitle(title);
      // Run parameters
      helper->loadRunParameters(localWorkspace, &iraw);
      delete helper;
      helper = NULL;


      // Loop over the number of periods in the raw file, putting each period in a separate workspace
      for (int period = 0; period < m_numberOfPeriods; ++period) {

        if ( period > 0 ) localWorkspace =  boost::dynamic_pointer_cast<DataObjects::Workspace2D>
                                              (WorkspaceFactory::Instance().create(localWorkspace));

        specid_t counter = 0;
        for (specid_t i = m_spec_min; i < m_spec_max; ++i)
        {
          // Shift the histogram to read if we're not in the first period
          int32_t histToRead = i + period*total_specs;
          loadData(timeChannelsVec,counter,histToRead,iraw,lengthIn,spectrum,localWorkspace );
          counter++;
          if (++histCurrent % 100 == 0) progress(static_cast<double>(histCurrent)/histTotal);
          interruption_point();
        }
        // Read in the spectra in the optional list parameter, if set
        if (m_list)
        {
          for(size_t i=0; i < m_spec_list.size(); ++i)
          {
            loadData(timeChannelsVec,counter,m_spec_list[i],iraw,lengthIn,spectrum, localWorkspace );
            counter++;
            if (++histCurrent % 100 == 0) progress(static_cast<double>(histCurrent)/histTotal);
            interruption_point();
          }
        }
        // Just a sanity check
        assert(counter == total_specs);

        std::string outputWorkspace = "OutputWorkspace";
        if (period == 0)
        {
          // Only run the Child Algorithms once
          runLoadInstrument(localWorkspace );
          runLoadMappingTable(localWorkspace );
          runLoadLog(localWorkspace );
          const int period_number = 1;
          Property* log=createPeriodLog(period_number);
          if(log)
          {
            localWorkspace->mutableRun().addLogData(log);
            localWorkspace->mutableRun().addLogData(createCurrentPeriodLog(period_number));
          }
          // Set the total proton charge for this run
          // (not sure how this works for multi_period files)
          localWorkspace->mutableRun().setProtonCharge(iraw.rpb.r_gd_prtn_chrg);
        }
        else   // We are working on a higher period of a multiperiod raw file
        {
          // Create a WorkspaceProperty for the new workspace of a higher period
          // The workspace name given in the OutputWorkspace property has _periodNumber appended to it
          //                (for all but the first period, which has no suffix)
          std::stringstream suffix;
          suffix << (period+1);
          outputWorkspace += suffix.str();
          std::string WSName = localWSName + "_" + suffix.str();
          declareProperty(new WorkspaceProperty<DataObjects::Workspace2D>(outputWorkspace,WSName,Direction::Output));
          g_log.information() << "Workspace " << WSName << " created. \n";
        }

        if (localWorkspace)
          localWorkspace->updateSpectraUsingMap();

        // Assign the result to the output workspace property
        setProperty(outputWorkspace,localWorkspace);

      } // loop over periods

      // Clean up
      delete[] timeChannels;
      delete[] spectrum;
    }
Ejemplo n.º 3
0
/** Executes the algorithm. Reading in the file and creating and populating
 *  the output workspace
 *
 *  @throw Exception::FileError If the RAW file cannot be found/opened
 *  @throw std::invalid_argument If the optional properties are set to invalid values
 */
void LoadRawBin0::exec()
{
	// Retrieve the filename from the properties
	m_filename = getPropertyValue("Filename");

	bool bLoadlogFiles = getProperty("LoadLogFiles");

	//open the raw file
	FILE* file=openRawFile(m_filename);

	// Need to check that the file is not a text file as the ISISRAW routines don't deal with these very well, i.e 
	// reading continues until a bad_alloc is encountered.
	if( isAscii(file) )
	{
		g_log.error() << "File \"" << m_filename << "\" is not a valid RAW file.\n";
		throw std::invalid_argument("Incorrect file type encountered.");
	}
	std::string title;
	readTitle(file,title);

	readworkspaceParameters(m_numberOfSpectra,m_numberOfPeriods,m_lengthIn,m_noTimeRegimes);

	///
	setOptionalProperties();

	// to validate the optional parameters, if set
	checkOptionalProperties();

    // Calculate the size of a workspace, given its number of periods & spectra to read
     m_total_specs = calculateWorkspaceSize();

 //no real X values for bin 0,so initialize this to zero
  boost::shared_ptr<MantidVec> channelsVec(new MantidVec(1,0));
  m_timeChannelsVec.push_back(channelsVec);

  double histTotal = static_cast<double>(m_total_specs * m_numberOfPeriods);
  int64_t histCurrent = -1;
 
  // Create the 2D workspace for the output xlength and ylength is one 
  DataObjects::Workspace2D_sptr localWorkspace = createWorkspace(m_total_specs, 1,1,title);
  Run& run = localWorkspace->mutableRun();
  if (bLoadlogFiles)
  {
    runLoadLog(m_filename,localWorkspace, 0.0, 0.0);
    const int period_number = 1;
    createPeriodLogs(period_number, localWorkspace);
  }
  // Set the total proton charge for this run
  setProtonCharge(run);

  WorkspaceGroup_sptr ws_grp = createGroupWorkspace();
  setWorkspaceProperty("OutputWorkspace", title, ws_grp, localWorkspace,m_numberOfPeriods, false);
    
  // Loop over the number of periods in the raw file, putting each period in a separate workspace
  for (int period = 0; period < m_numberOfPeriods; ++period)
  {
    if (period > 0)
    {
      localWorkspace=createWorkspace(localWorkspace);

      if (bLoadlogFiles)
      {
        //remove previous period data
        std::stringstream prevPeriod;
        prevPeriod << "PERIOD " << (period);
        Run& runObj = localWorkspace->mutableRun();
        runObj.removeLogData(prevPeriod.str());
        runObj.removeLogData("current_period");
        //add current period data
        const int period_number = period + 1;
        createPeriodLogs(period_number, localWorkspace);
      }

    }
    skipData(file, period * (m_numberOfSpectra + 1));
    int64_t wsIndex = 0;
    for (specid_t i = 1; i <= m_numberOfSpectra; ++i)
    {
      int64_t histToRead = i + period * (m_numberOfSpectra + 1);
      if ((i >= m_spec_min && i < m_spec_max) || (m_list && find(m_spec_list.begin(), m_spec_list.end(),
          i) != m_spec_list.end()))
      {
        progress(m_prog, "Reading raw file data...");
        //readData(file, histToRead);
		  //read spectrum 
		  if (!readData(file, histToRead))
		  {
			  throw std::runtime_error("Error reading raw file");
		  }
		  int64_t binStart=0;
		  setWorkspaceData(localWorkspace, m_timeChannelsVec, wsIndex, i, m_noTimeRegimes,1,binStart);
		  ++wsIndex;

      if (m_numberOfPeriods == 1)
      {
        if (++histCurrent % 100 == 0)
        {
          m_prog = double(histCurrent) / histTotal;
        }
        interruption_point();
      }

    }
	  else
	  {
		  skipData(file, histToRead);
	  }
    
    }
	
	if(m_numberOfPeriods>1)
	{
		setWorkspaceProperty(localWorkspace, ws_grp, period, false);
		// progress for workspace groups 
		m_prog = static_cast<double>(period) / static_cast<double>(m_numberOfPeriods - 1);
	}
  
  } // loop over periods
  // Clean up
  isisRaw.reset();
  fclose(file);
}
Ejemplo n.º 4
0
    /**
    * Executes the algorithm.
    * Saves the workspace specified by the user to the VTK XML format
    */
    void SaveVTK::exec()
    {
      std::string filename = getProperty("Filename");
      g_log.debug() << "Parameters: Filename='" << filename << "'" << std::endl;
      //add extension
      filename += ".vtu";

      MatrixWorkspace_sptr inputWorkspace = getProperty("InputWorkspace");
      if( !inputWorkspace )
      {
        g_log.error("Failed to retrieve inputWorkspace.");
        throw Exception::NullPointerException("SaveVTK::exec()", "inputWorkspace");
      }

      checkOptionalProperties();

      //Open file for writing
      std::ofstream outVTP(filename.c_str());
      if( !outVTP )
      {
        g_log.error("Failed to open file: " + filename);
        throw Exception::FileError("Failed to open file ", filename);
      }

      // First write document level XML header
      outVTP << "<?xml version=\"1.0\"?>\n"
        "<VTKFile type=\"UnstructuredGrid\" version=\"0.1\" byte_order=\"LittleEndian\">\n"
        "<UnstructuredGrid>\n";

      const std::string workspaceID = inputWorkspace->id();    
      if( workspaceID.find("Workspace2D") != std::string::npos )
      {
        const Workspace2D_sptr localWorkspace = 
          boost::dynamic_pointer_cast<Workspace2D>(inputWorkspace);
        //      const size_t numberOfHist = localWorkspace->getNumberHistograms();

        //Write out whole range
        bool xMin(m_Xmin > 0.0), xMax(m_Xmax > 0.0);
        Progress prog(this,0.0,1.0,97);
        if( !xMin && !xMax )
        {
          for( int hNum = 2; hNum < 100; ++hNum )
          {
            writeVTKPiece(outVTP, localWorkspace->dataX(hNum), localWorkspace->dataY(hNum), 
              localWorkspace->dataE(hNum), hNum);
            prog.report();
          }
        }
        else
        {
          for( int hNum = 2; hNum < 100; ++hNum )
          {
            std::vector<double> xValue, yValue, errors;
            std::vector<double>::size_type nVals(localWorkspace->dataY(hNum).size());
            for( int i = 0; i < (int)nVals; ++i )
            {
              if( xMin && localWorkspace->dataX(hNum)[i] < m_Xmin ) continue;
              if( xMax && localWorkspace->dataX(hNum)[i+1] > m_Xmax)
              {
                xValue.push_back(localWorkspace->dataX(hNum)[i]);
                break;
              }
              xValue.push_back(localWorkspace->dataX(hNum)[i]);
              if( i == (int)nVals - 1 )
              {
                xValue.push_back(localWorkspace->dataX(hNum)[i+1]);
              } 	    
              yValue.push_back(localWorkspace->dataY(hNum)[i]);
              errors.push_back(localWorkspace->dataE(hNum)[i]);
            }
            //sanity check
            assert( (int)xValue.size() == (int)yValue.size() + 1 );

            writeVTKPiece(outVTP, xValue, yValue, errors, hNum);
            prog.report();
          }
        }
      }
      else
      {
        outVTP.close();
        Poco::File(filename).remove();
        throw Exception::NotImplementedError("SaveVTK only implemented for Workspace2D\n");
      }

      // Final XML end block tags
      outVTP << "</UnstructuredGrid>\n</VTKFile>\n";
      outVTP.close();
    }
Ejemplo n.º 5
0
    /** Executes the algorithm. Reading in the file and creating and populating
     *  the output workspace
     *
     *  @throw Exception::FileError If the RAW file cannot be found/opened
     *  @throw std::invalid_argument If the optional properties are set to invalid values
     */
    void LoadRaw2::exec()
    {
      // Retrieve the filename from the properties
      m_filename = getPropertyValue("Filename");
      LoadRawHelper *helper = new LoadRawHelper;
      FILE* file = helper->openRawFile(m_filename);
      isisRaw->ioRAW(file, true);
      
      std::string title(isisRaw->r_title, 80);
      g_log.information("**** Run title: "+ title + "***");

      // Read in the number of spectra in the RAW file
      m_numberOfSpectra = isisRaw->t_nsp1;
      // Read the number of periods in this file
      m_numberOfPeriods = isisRaw->t_nper;
      // Read the number of time channels (i.e. bins) from the RAW file
      const int channelsPerSpectrum = isisRaw->t_ntc1;
      // Read in the time bin boundaries
      const int lengthIn = channelsPerSpectrum + 1;

      // Call private method to validate the optional parameters, if set
      checkOptionalProperties();

      // Calculate the size of a workspace, given its number of periods & spectra to read
      specid_t total_specs;
      if( m_interval || m_list)
      {
        if (m_interval)
        {
          total_specs = (m_spec_max-m_spec_min+1);
          m_spec_max += 1;
        }
        else
            total_specs = 0;

        if (m_list)
        {
            if (m_interval)
            {
                for(std::vector<specid_t>::iterator it=m_spec_list.begin();it!=m_spec_list.end();)
                    if (*it >= m_spec_min && *it <m_spec_max)
                    {
                        it = m_spec_list.erase(it);
                    }
                    else
                        ++it;

            }
            if (m_spec_list.size() == 0) m_list = false;
            total_specs += static_cast<specid_t>(m_spec_list.size());
        }
      }
      else
      {
        total_specs = m_numberOfSpectra;
        // In this case want all the spectra, but zeroth spectrum is garbage so go from 1 to NSP1
        m_spec_min = 1;
        m_spec_max = m_numberOfSpectra + 1;
      }

      // If there is not enough memory use ManagedRawFileWorkspace2D.
      if ( ConfigService::Instance().getString("ManagedRawFileWorkspace.DoNotUse") != "1" &&
           m_numberOfPeriods == 1 && MemoryManager::Instance().goForManagedWorkspace(total_specs,lengthIn,channelsPerSpectrum) &&
          total_specs == m_numberOfSpectra)
      {
        const std::string cache_option = getPropertyValue("Cache");
        size_t option = find(m_cache_options.begin(),m_cache_options.end(),cache_option) - m_cache_options.begin();
        DataObjects::Workspace2D_sptr localWorkspace =
          DataObjects::Workspace2D_sptr(
          new ManagedRawFileWorkspace2D(m_filename, static_cast<int>(option)));
        progress(0.,"Reading raw file...");
        helper->loadRunParameters(localWorkspace, isisRaw.get());
        runLoadInstrument(localWorkspace );
        runLoadMappingTable(localWorkspace );
        runLoadLog(localWorkspace );
        const int period_number = 1;
        Property* log=createPeriodLog(period_number);
        if(log)
        {
          localWorkspace->mutableRun().addLogData(log);
          localWorkspace->mutableRun().addLogData(createCurrentPeriodLog(period_number));
        }
              localWorkspace->mutableRun().setProtonCharge(isisRaw->rpb.r_gd_prtn_chrg);
        for (int i = 0; i < m_numberOfSpectra; ++i)
          localWorkspace->getAxis(1)->setValue(i, i+1);
        localWorkspace->populateInstrumentParameters();
        setProperty("OutputWorkspace",localWorkspace);
        return;
      }

      float* timeChannels = new float[lengthIn];
      isisRaw->getTimeChannels(timeChannels, lengthIn);
      // Put the read in array into a vector (inside a shared pointer)
      boost::shared_ptr<MantidVec> timeChannelsVec
                          (new MantidVec(timeChannels, timeChannels + lengthIn));

      // Need to extract the user-defined output workspace name
      Property *ws = getProperty("OutputWorkspace");
      std::string localWSName = ws->value();

      Progress pr(this,0.,1.,total_specs * m_numberOfPeriods);

      // Create the 2D workspace for the output
      DataObjects::Workspace2D_sptr localWorkspace = boost::dynamic_pointer_cast<DataObjects::Workspace2D>
               (WorkspaceFactory::Instance().create("Workspace2D",total_specs,lengthIn,lengthIn-1));
      localWorkspace->setTitle(title);
      localWorkspace->getAxis(0)->unit() = UnitFactory::Instance().create("TOF");
      // Run parameters
      helper->loadRunParameters(localWorkspace, isisRaw.get());
      delete helper;
      helper = NULL;

      // Loop over the number of periods in the raw file, putting each period in a separate workspace
      for (int period = 0; period < m_numberOfPeriods; ++period) {

        if ( period > 0 )
        {
            localWorkspace =  boost::dynamic_pointer_cast<DataObjects::Workspace2D>
                (WorkspaceFactory::Instance().create(localWorkspace));
        }

        isisRaw->skipData(file,period*(m_numberOfSpectra+1));
        int counter = 0;
        for (int i = 1; i <= m_numberOfSpectra; ++i)
        {
            int histToRead = i + period*(m_numberOfSpectra+1);
            if ((i >= m_spec_min && i < m_spec_max) ||
                (m_list && find(m_spec_list.begin(),m_spec_list.end(),i) != m_spec_list.end()))
            {
                isisRaw->readData(file,histToRead);
                // Copy the data into the workspace vector, discarding the 1st entry, which is rubbish
                // But note that the last (overflow) bin is kept
                MantidVec& Y = localWorkspace->dataY(counter);
                Y.assign(isisRaw->dat1 + 1, isisRaw->dat1 + lengthIn);
                // Fill the vector for the errors, containing sqrt(count)
                MantidVec& E = localWorkspace->dataE(counter);
                std::transform(Y.begin(), Y.end(), E.begin(), dblSqrt);
                // Set the X vector pointer and spectrum number
                localWorkspace->setX(counter, timeChannelsVec);
                localWorkspace->getAxis(1)->setValue(counter, i);
                // NOTE: Raw numbers go straight into the workspace
                //     - no account taken of bin widths/units etc.
                ++counter;
                pr.report();
            }
            else
            {
                isisRaw->skipData(file,histToRead);
            }
        }

        // Just a sanity check
        assert(counter == total_specs);

        std::string outputWorkspace = "OutputWorkspace";
        if (period == 0)
        {
          // Only run the Child Algorithms once
          runLoadInstrument(localWorkspace );
          runLoadMappingTable(localWorkspace );
          runLoadLog(localWorkspace );
          const int period_number = period + 1;
          Property* log=createPeriodLog(period_number);
          if(log)
          {
            localWorkspace->mutableRun().addLogData(log);
            localWorkspace->mutableRun().addLogData(createCurrentPeriodLog(period_number));
          }
          // Set the total proton charge for this run
          // (not sure how this works for multi_period files)
          localWorkspace->mutableRun().setProtonCharge(isisRaw->rpb.r_gd_prtn_chrg);
        }
        else   // We are working on a higher period of a multiperiod raw file
        {
          // Create a WorkspaceProperty for the new workspace of a higher period
          // The workspace name given in the OutputWorkspace property has _periodNumber appended to it
          //                (for all but the first period, which has no suffix)
          std::stringstream suffix;
          suffix << (period+1);
          outputWorkspace += suffix.str();
          std::string WSName = localWSName + "_" + suffix.str();
          declareProperty(new WorkspaceProperty<DataObjects::Workspace2D>(outputWorkspace,WSName,Direction::Output));
          g_log.information() << "Workspace " << WSName << " created. \n";
                         
          //remove previous period data
          std::stringstream index;
          index << (period);
          std::string prevPeriod="PERIOD "+index.str();
          localWorkspace->mutableRun().removeLogData(prevPeriod);
          localWorkspace->mutableRun().removeLogData("current_period");
          //add current period data
          const int period_number = period + 1;
          Property* log=createPeriodLog(period_number);
          if(log)
          {
            localWorkspace->mutableRun().addLogData(log);
            localWorkspace->mutableRun().addLogData(createCurrentPeriodLog(period_number));
          }
        }

        // check if values stored in logfiles should be used to define parameters of the instrument
        localWorkspace->populateInstrumentParameters();

        // Assign the result to the output workspace property
        setProperty(outputWorkspace,localWorkspace);

      } // loop over periods

      // Clean up
      delete[] timeChannels;
      //delete[] spectrum;
      fclose(file);
    }