Newer
Older
Janik Zikovsky
committed
/*WIKI*
The LoadAscii algorithm reads in spectra data from a text file and stores it in a [[Workspace2D]] as data points. The data in the file must be organized in columns separated by commas, tabs, spaces, colons or semicolons. Only one separator type can be used throughout the file; use the "Separator" property to tell the algorithm which to use.
By default the algorithm attempts to guess which lines are header lines by trying to see where a contiguous block of numbers starts. This can be turned off by specifying the "SkipNumLines" property, which will then tell the algorithm to simply use that as the the number of header lines.
The format can be one of:
* Two columns: 1st column=X, 2nd column=Y, E=0
* For a workspace of ''n'' spectra, 2''n''+1 columns: 1''st'' column=X, 2i''th'' column=Y, 2i+1''th'' column =E
The number of bins is defined by the number of rows.
The resulting workspace will have common X binning for all spectra.
*WIKI*/
//----------------------------------------------------------------------
// Includes
//----------------------------------------------------------------------
#include "MantidDataHandling/LoadAscii.h"
#include "MantidDataObjects/Workspace2D.h"
#include "MantidKernel/UnitFactory.h"
Gigg, Martyn Anthony
committed
#include "MantidAPI/FileProperty.h"
Sofia Antony
committed
#include "MantidAPI/LoadAlgorithmFactory.h"
#include "MantidKernel/BoundedValidator.h"
#include "MantidKernel/ListValidator.h"
Gigg, Martyn Anthony
committed
Gigg, Martyn Anthony
committed
#include <Poco/StringTokenizer.h>
// String utilities
#include <boost/algorithm/string.hpp>
namespace Mantid
{
namespace DataHandling
{
// Register the algorithm into the algorithm factory
DECLARE_ALGORITHM(LoadAscii)
Sofia Antony
committed
//register the algorithm into loadalgorithm factory
DECLARE_LOADALGORITHM(LoadAscii)
Janik Zikovsky
committed
/// Sets documentation strings for this algorithm
void LoadAscii::initDocs()
{
this->setWikiSummary("Loads data from a text file and stores it in a 2D [[workspace]] ([[Workspace2D]] class). ");
this->setOptionalMessage("Loads data from a text file and stores it in a 2D workspace (Workspace2D class).");
}
using namespace Kernel;
using namespace API;
Russell Taylor
committed
/// Empty constructor
Gigg, Martyn Anthony
committed
LoadAscii::LoadAscii() : m_columnSep(), m_separatorIndex()
Gigg, Martyn Anthony
committed
/** This method does a quick file check by checking the no.of bytes read nread params and header buffer
Gigg, Martyn Anthony
committed
* @param filePath :: path of the file including name.
* @param nread :: no.of bytes read
* @param header :: The first 100 bytes of the file as a union
* @return true if the given file is of type which can be loaded by this algorithm
*/
Gigg, Martyn Anthony
committed
bool LoadAscii::quickFileCheck(const std::string& filePath,size_t nread,const file_header& header)
Sofia Antony
committed
{
std::string extn=extension(filePath);
Robert Whitley
committed
if (!extn.compare("dat")||!extn.compare("csv")|| !extn.compare("txt")|| !extn.compare("")) //If the file is of type ascii then have a go
Sofia Antony
committed
{
Robert Whitley
committed
return true;
}
else //See if file looks like Ascii and have a go at doing something about it
{
bool is_ascii (true);
if( filePath.compare(filePath.size()-12,12,"_runinfo.xml") == 0)
is_ascii =false;
Robert Whitley
committed
for(size_t i=0; i<nread; i++)
{
if (!isascii(header.full_hdr[i]))
is_ascii =false;
}
return (is_ascii);
Sofia Antony
committed
}
}
Gigg, Martyn Anthony
committed
/**
Gigg, Martyn Anthony
committed
* Checks the file by opening it and reading few lines
* @param filePath name of the file including its path
* @return an integer value how much this algorithm can load the file
*/
Sofia Antony
committed
int LoadAscii::fileCheck(const std::string& filePath)
{
Robert Whitley
committed
FILE* file = fopen(filePath.c_str(), "rb");
Sofia Antony
committed
if (!file)
{
g_log.error("Unable to open file: " + filePath);
throw Exception::FileError("Unable to open file: " , filePath);
}
Robert Whitley
committed
Gigg, Martyn Anthony
committed
int confidence(0);
if( filePath.compare(filePath.size()-12,12,"_runinfo.xml") == 0)
{
fclose(file);
return confidence;
}
Robert Whitley
committed
if (isAscii(file))
{
confidence = 10; //Lower because should load other files first
Sofia Antony
committed
}
Robert Whitley
committed
return confidence;
}
Sofia Antony
committed
Robert Whitley
committed
/**
* Check if a file is a text file
* @param file :: The file pointer
* @returns true if the file an ascii text file, false otherwise
*/
bool LoadAscii::isAscii(FILE *file)
{
char data[256];
char *pend = &data[fread(data, 1, sizeof(data), file)];
fseek(file,0,SEEK_SET);
/*
* Call it a binary file if we find a non-ascii character in the
* first 256 bytes of the file.
*/
for( char *p = data; p < pend; ++p )
{
unsigned long ch = (unsigned long)*p;
if( !(ch <= 0x7F) )
Sofia Antony
committed
{
Robert Whitley
committed
return false;
Sofia Antony
committed
}
Gigg, Martyn Anthony
committed
Sofia Antony
committed
}
Robert Whitley
committed
return true;
Gigg, Martyn Anthony
committed
}
//--------------------------------------------------------------------------
// Protected methods
//--------------------------------------------------------------------------
/**
Gigg, Martyn Anthony
committed
* Process the header information. This implementation just skips it entirely.
* @param file :: A reference to the file stream
*/
Gigg, Martyn Anthony
committed
void LoadAscii::processHeader(std::ifstream & file) const
{
Gigg, Martyn Anthony
committed
Gigg, Martyn Anthony
committed
// Most files will have some sort of header. If we've haven't been told how many lines to
// skip then try and guess
int numToSkip = getProperty("SkipNumLines");
if( numToSkip == EMPTY_INT() )
Gigg, Martyn Anthony
committed
const int rowsToMatch(5);
// Have a guess where the data starts. Basically say, when we have say "rowsToMatch" lines of pure numbers
// in a row then the line that started block is the top of the data
int numCols(-1), matchingRows(0), row(0);
std::string line;
std::vector<double> values;
while( getline(file,line) )
{
++row;
Gigg, Martyn Anthony
committed
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
boost::trim(line);
if( this->skipLine(line) )
{
continue;
}
std::list<std::string> columns;
int lineCols = this->splitIntoColumns(columns, line);
try
{
fillInputValues(values, columns);
}
catch(boost::bad_lexical_cast&)
{
continue;
}
if( numCols < 0 ) numCols = lineCols;
if( lineCols == numCols )
{
++matchingRows;
if( matchingRows == rowsToMatch ) break;
}
else
{
numCols = lineCols;
matchingRows = 1;
}
}
// if the file does not have more than rowsToMatch + skipped lines, it will stop
// and raise the EndOfFile, this may cause problems for small workspaces.
// In this case clear the flag
if (file.eof()){
file.clear(file.eofbit);
}
Gigg, Martyn Anthony
committed
// Seek the file pointer back to the start.
// NOTE: Originally had this as finding the stream position of the data and then moving the file pointer
// back to the start of the data. This worked when a file was read on the same platform it was written
// but failed when read on a different one due to underlying differences in the stream translation.
file.seekg(0,std::ios::beg);
// We've read the header plus the number of rowsToMatch
numToSkip = row - rowsToMatch;
Gigg, Martyn Anthony
committed
int i(0);
std::string line;
while( i < numToSkip && getline(file, line) )
Sofia Antony
committed
{
Gigg, Martyn Anthony
committed
++i;
Gigg, Martyn Anthony
committed
}
g_log.information() << "Skipped " << numToSkip << " line(s) of header information()\n";
Sofia Antony
committed
}
Gigg, Martyn Anthony
committed
/**
Gigg, Martyn Anthony
committed
* Reads the data from the file. It is assumed that the provided file stream has its position
* set such that the first call to getline will be give the first line of data
* @param file :: A reference to a file stream
* @returns A pointer to a new workspace
*/
Gigg, Martyn Anthony
committed
API::Workspace_sptr LoadAscii::readData(std::ifstream & file) const
{
// Get the first line and find the number of spectra from the number of columns
std::string line;
Gigg, Martyn Anthony
committed
getline(file,line);
boost::trim(line);
Gigg, Martyn Anthony
committed
std::list<std::string> columns;
const int numCols = splitIntoColumns(columns, line);
if( numCols < 2 )
{
Gigg, Martyn Anthony
committed
g_log.error() << "Invalid data format found in file \"" << getPropertyValue("Filename") << "\"\n";
throw std::runtime_error("Invalid data format. Fewer than 2 columns found.");
Gigg, Martyn Anthony
committed
}
Gigg, Martyn Anthony
committed
bool haveErrors(false);
bool haveXErrors(false);
Gigg, Martyn Anthony
committed
// Assume single data set with no errors
if( numCols == 2 )
{
Gigg, Martyn Anthony
committed
numSpectra = numCols/2;
Gigg, Martyn Anthony
committed
}
// Data with errors
else if( (numCols-1) % 2 == 0 )
{
Gigg, Martyn Anthony
committed
numSpectra = (numCols - 1)/2;
haveErrors = true;
Gigg, Martyn Anthony
committed
}
// Data with errors on both X and Y (4-column file)
else if( numCols == 4 )
{
numSpectra = 1;
haveErrors = true;
haveXErrors = true;
}
Gigg, Martyn Anthony
committed
else
{
Gigg, Martyn Anthony
committed
g_log.error() << "Invalid data format found in file \"" << getPropertyValue("Filename") << "\"\n";
g_log.error() << "LoadAscii requires the number of columns to be an even multiple of either 2 or 3.";
throw std::runtime_error("Invalid data format.");
Gigg, Martyn Anthony
committed
}
Gigg, Martyn Anthony
committed
Gigg, Martyn Anthony
committed
// A quick check at the number of lines won't be accurate enough as potentially there
// could be blank lines and comment lines
int numBins(0), lineNo(0);
std::vector<DataObjects::Histogram1D> spectra(numSpectra);
std::vector<double> values(numCols, 0.);
Gigg, Martyn Anthony
committed
do
Gigg, Martyn Anthony
committed
{
Gigg, Martyn Anthony
committed
++lineNo;
boost::trim(line);
if( this->skipLine(line) ) continue;
columns.clear();
int lineCols = this->splitIntoColumns(columns, line);
if( lineCols != numCols )
{
std::ostringstream ostr;
Gigg, Martyn Anthony
committed
ostr << "Number of columns changed at line " << lineNo;
Gigg, Martyn Anthony
committed
throw std::runtime_error(ostr.str());
}
Gigg, Martyn Anthony
committed
Gigg, Martyn Anthony
committed
try
{
Robert Whitley
committed
fillInputValues(values, columns); //ignores nans and replaces them with 0
Gigg, Martyn Anthony
committed
}
catch(boost::bad_lexical_cast&)
{
g_log.error() << "Invalid value on line " << lineNo << " of \""
<< getPropertyValue("Filename") << "\"\n";
throw std::runtime_error("Invalid value encountered.");
}
Gigg, Martyn Anthony
committed
for (size_t i = 0; i < numSpectra; ++i)
Gigg, Martyn Anthony
committed
{
spectra[i].dataX().push_back(values[0]);
spectra[i].dataY().push_back(values[i*2+1]);
Gigg, Martyn Anthony
committed
if( haveErrors )
{
spectra[i].dataE().push_back(values[i*2+2]);
}
if( haveXErrors )
{
// Note: we only have X errors with 4-column files.
// We are only here when i=0.
spectra[i].dataDx().push_back(values[3]);
}
Gigg, Martyn Anthony
committed
}
++numBins;
}
Gigg, Martyn Anthony
committed
while(getline(file,line));
Gigg, Martyn Anthony
committed
MatrixWorkspace_sptr localWorkspace = boost::dynamic_pointer_cast<MatrixWorkspace>
(WorkspaceFactory::Instance().create("Workspace2D",numSpectra,numBins,numBins));
try
{
localWorkspace->getAxis(0)->unit() = UnitFactory::Instance().create(getProperty("Unit"));
}
catch (Exception::NotFoundError&)
{
// Asked for dimensionless workspace (obviously not in unit factory)
}
for (size_t i = 0; i < numSpectra; ++i)
Gigg, Martyn Anthony
committed
{
localWorkspace->dataX(i) = spectra[i].dataX();
localWorkspace->dataY(i) = spectra[i].dataY();
/* If Y or E errors are not there, DON'T copy across as the 'spectra' vectors
have not been filled above. The workspace will by default have vectors of
the right length filled with zeroes. */
if ( haveErrors ) localWorkspace->dataE(i) = spectra[i].dataE();
if ( haveXErrors ) localWorkspace->dataDx(i) = spectra[i].dataDx();
Gigg, Martyn Anthony
committed
// Just have spectrum number start at 1 and count up
localWorkspace->getAxis(1)->spectraNo(i) = static_cast<specid_t>(i+1);
Gigg, Martyn Anthony
committed
}
return localWorkspace;
}
/**
Gigg, Martyn Anthony
committed
* Peek at a line without extracting it from the stream
*/
Gigg, Martyn Anthony
committed
void LoadAscii::peekLine(std::ifstream & is, std::string & str) const
{
getline(is, str);
Gigg, Martyn Anthony
committed
is.seekg(-(int)str.length(),std::ios::cur);
Gigg, Martyn Anthony
committed
boost::trim(str);
}
Gigg, Martyn Anthony
committed
Gigg, Martyn Anthony
committed
/**
Gigg, Martyn Anthony
committed
* Return true if the line is to be skipped.
* @param line :: The line to be checked
Gigg, Martyn Anthony
committed
*/
Gigg, Martyn Anthony
committed
bool LoadAscii::skipLine(const std::string & line) const
{
// Empty or comment
return ( line.empty() || boost::starts_with(line, "#") );
}
/**
Gigg, Martyn Anthony
committed
* Split the data into columns based on the input separator
* @param[out] columns :: A reference to a list to store the column data
* @param[in] str :: The input string
* @returns The number of columns
*/
Gigg, Martyn Anthony
committed
int LoadAscii::splitIntoColumns(std::list<std::string> & columns, const std::string & str) const
{
boost::split(columns, str, boost::is_any_of(m_columnSep), boost::token_compress_on);
return static_cast<int>(columns.size());
Gigg, Martyn Anthony
committed
}
/**
Gigg, Martyn Anthony
committed
* Fill the given vector with the data values. Its size is assumed to be correct
* @param[out] values :: The data vector fill
* @param columns :: The list of strings denoting columns
*/
Gigg, Martyn Anthony
committed
void LoadAscii::fillInputValues(std::vector<double> &values,
Gigg, Martyn Anthony
committed
const std::list<std::string>& columns) const
Gigg, Martyn Anthony
committed
{
values.resize(columns.size());
std::list<std::string>::const_iterator iend = columns.end();
int i = 0;
for( std::list<std::string>::const_iterator itr = columns.begin();
Gigg, Martyn Anthony
committed
itr != iend; ++itr )
Gigg, Martyn Anthony
committed
{
Gigg, Martyn Anthony
committed
std::string value = *itr;
boost::trim(value);
Robert Whitley
committed
boost::to_lower(value);
Robert Whitley
committed
if (value == "nan"|| value == "1.#qnan") //ignores nans (not a number) and replaces them with a nan
Robert Whitley
committed
{
double nan = std::numeric_limits<double>::quiet_NaN();//(0.0/0.0);
values[i] = nan;
}
else
{
values[i] = boost::lexical_cast<double>(value);
}
Gigg, Martyn Anthony
committed
++i;
Gigg, Martyn Anthony
committed
}
}
//--------------------------------------------------------------------------
// Private methods
//--------------------------------------------------------------------------
/// Initialisation method.
void LoadAscii::init()
{
std::vector<std::string> exts;
exts.push_back(".dat");
exts.push_back(".txt");
exts.push_back(".csv");
exts.push_back("");
Gigg, Martyn Anthony
committed
declareProperty(new FileProperty("Filename", "", FileProperty::Load, exts),
"A comma separated Ascii file");
declareProperty(new WorkspaceProperty<Workspace>("OutputWorkspace",
"",Direction::Output), "The name of the workspace that will be created.");
std::string spacers[6][6] = { {"Automatic", ",\t:; "}, {"CSV", ","},
{"Tab", "\t"}, {"Space", " "}, {"Colon", ":"}, {"SemiColon", ";"} };
Gigg, Martyn Anthony
committed
// For the ListValidator
std::vector<std::string> sepOptions;
for( size_t i = 0; i < 5; ++i )
{
Gigg, Martyn Anthony
committed
std::string option = spacers[i][0];
m_separatorIndex.insert(std::pair<std::string,std::string>(option, spacers[i][1]));
sepOptions.push_back(option);
Gigg, Martyn Anthony
committed
}
declareProperty("Separator", "Automatic", boost::make_shared<StringListValidator>(sepOptions),
"The column separator character (default: Automatic selection)");
Gigg, Martyn Anthony
committed
std::vector<std::string> units = UnitFactory::Instance().getKeys();
units.insert(units.begin(),"Dimensionless");
declareProperty("Unit","Energy", boost::make_shared<StringListValidator>(units),
Gigg, Martyn Anthony
committed
"The unit to assign to the X axis (default: Energy)");
auto mustBePosInt = boost::make_shared<BoundedValidator<int> >();
Gigg, Martyn Anthony
committed
mustBePosInt->setLower(0);
declareProperty("SkipNumLines", EMPTY_INT(), mustBePosInt,
Gigg, Martyn Anthony
committed
"If set, this number of lines from the top of the file are ignored.");
Gigg, Martyn Anthony
committed
}
/**
Gigg, Martyn Anthony
committed
* Executes the algorithm.
*/
Gigg, Martyn Anthony
committed
void LoadAscii::exec()
{
std::string filename = getProperty("Filename");
Gigg, Martyn Anthony
committed
std::ifstream file(filename.c_str());
Gigg, Martyn Anthony
committed
if (!file)
{
g_log.error("Unable to open file: " + filename);
throw Exception::FileError("Unable to open file: " , filename);
}
std::string sepOption = getProperty("Separator");
m_columnSep = m_separatorIndex[sepOption];
// Process the header information.
processHeader(file);
// Read the data
MatrixWorkspace_sptr outputWS = boost::dynamic_pointer_cast<MatrixWorkspace>(readData(file));
outputWS->mutableRun().addProperty("Filename",filename);
Gigg, Martyn Anthony
committed
setProperty("OutputWorkspace", outputWS);
}
Gigg, Martyn Anthony
committed
} // namespace DataHandling
} // namespace Mantid