WSL/SLF GitLab Repository

libsmet.cc 49.5 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/***********************************************************************************/
/*  Copyright 2009 WSL Institute for Snow and Avalanche Research    SLF-DAVOS      */
/***********************************************************************************/
/* This file is part of MeteoIO.
    MeteoIO is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    MeteoIO is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with MeteoIO.  If not, see <http://www.gnu.org/licenses/>.
*/
18
#include <meteoio/plugins/libsmet.h>
19
20
#include <errno.h>
#include <string.h>
21
#include <limits>
22
23
24
25
26
27
28
#include <cmath>
#include <cstdlib>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
29

30
31
32
33
34
35
#if defined _WIN32 || defined __MINGW32__
	#include <windows.h>
#else
	#include <sys/stat.h>
#endif

36
37
38
39
using namespace std;

namespace smet {

Mathias Bavay's avatar
Mathias Bavay committed
40
const char* SMETCommon::smet_version = "1.1";
41
42
43
44
set<string> SMETCommon::all_mandatory_header_keys = set<std::string>();
set<string> SMETCommon::all_optional_header_keys  = set<std::string>();
set<string> SMETCommon::all_decimal_header_values = set<std::string>();

Mathias Bavay's avatar
Mathias Bavay committed
45
46
SMETException::SMETException(const std::string& message, const std::string& position)
              : msg( (position.empty())? "At unknown position: " + message : position + ": " + message) {}
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88

SMETException::~SMETException() throw() {}

const char* SMETException::what() const throw()
{
	return msg.c_str();
}

const bool SMETCommon::__init = SMETCommon::initStaticData();
bool SMETCommon::initStaticData()
{
	all_mandatory_header_keys.insert("station_id");
	all_mandatory_header_keys.insert("nodata");
	all_mandatory_header_keys.insert("fields");

	all_optional_header_keys.insert("latitude");
	all_optional_header_keys.insert("longitude");
	all_optional_header_keys.insert("altitude");
	all_optional_header_keys.insert("easting");
	all_optional_header_keys.insert("northing");
	all_optional_header_keys.insert("epsg");

	all_optional_header_keys.insert("station_name");
	all_optional_header_keys.insert("tz");
	all_optional_header_keys.insert("creation");
	all_optional_header_keys.insert("source");
	all_optional_header_keys.insert("units_offset");
	all_optional_header_keys.insert("units_multiplier");
	all_optional_header_keys.insert("comment");

	all_decimal_header_values.insert("nodata");
	all_decimal_header_values.insert("latitude");
	all_decimal_header_values.insert("longitude");
	all_decimal_header_values.insert("altitude");
	all_decimal_header_values.insert("easting");
	all_decimal_header_values.insert("northing");
	all_decimal_header_values.insert("epsg");
	all_decimal_header_values.insert("tz");

	return true;
}

89
#if defined _WIN32 || defined __MINGW32__
90
bool SMETCommon::fileExists(const std::string& filename)
91
92
{
	const DWORD attributes = GetFileAttributes( filename.c_str() );
93
94

	if (attributes==INVALID_FILE_ATTRIBUTES || attributes==FILE_ATTRIBUTE_VIRTUAL
95
96
	     || attributes==FILE_ATTRIBUTE_DIRECTORY || attributes==FILE_ATTRIBUTE_DEVICE)
		return false;
97

98
99
100
	return true;
}
#else
101
bool SMETCommon::fileExists(const std::string& filename)
102
103
104
105
106
107
{
	struct stat buffer ;

	if ((stat( filename.c_str(), &buffer))!=0) {//File exists if stat returns 0
		return false;
	}
108

109
110
111
112
113
114
115
	if (S_ISREG(buffer.st_mode) || S_ISFIFO(buffer.st_mode) || S_ISLNK(buffer.st_mode))
		return true;
	else
		return false; //exclude char device, block device, sockets, etc
}
#endif

116
117
118
119
120
121
122
123
124
bool SMETCommon::validFileAndPath(const std::string& filename)
{
#if defined _WIN32 || defined __MINGW32__ || defined __CYGWIN__
	const size_t startpos = filename.find_first_not_of(" \t\n"); // Find the first character position after excluding leading blank spaces
	const size_t invalid_char = filename.find_first_of("\000*:<>?|"); //find possible invalid characters
#else
	const size_t startpos = filename.find_first_not_of(" \t\n"); // Find the first character position after excluding leading blank spaces
	const size_t invalid_char = filename.find_first_of("\000"); //find possible invalid characters
#endif
Mathias Bavay's avatar
Mathias Bavay committed
125

126
127
128
129
130
131
	if ((startpos!=0) || (invalid_char!=std::string::npos) || (filename==".") || (filename=="..")) {
		return false;
	}
	return true;
}

132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
void SMETCommon::copy_file(const std::string& src, const std::string& dest)
{
	if (src == dest) return; //copying to the same file doesn't make sense, but is no crime either

	if (!fileExists(src)) throw SMETException("File '"+src+"' does not exist", AT);
	std::ifstream fin(src.c_str(), std::ios::binary);
	if (fin.fail()) throw SMETException("Failed to open file '"+src+"'", AT);

	if (!validFileAndPath(dest)) throw SMETException("Destination file name '"+dest+"' is invalid", AT);
	std::ofstream fout(dest.c_str(), std::ios::binary);
	if (fout.fail()) {
		fin.close();
		throw SMETException("Failed to open destination file '"+dest+"'", AT);
	}

	fout << fin.rdbuf();

	fin.close();
	fout.close();
}

153
154
double SMETCommon::convert_to_double(const std::string& in_string)
{
155
156
	char* conversion_end = NULL;
	const double conversion_value = strtod(in_string.c_str(), &conversion_end);
157

158
159
	if (*conversion_end == '\0') {
		return conversion_value;
160
161
162
	} else {
		throw SMETException("Value \"" + in_string + "\" cannot be converted to double", SMET_AT);
	}
163
164
}

165
166
167
168
int SMETCommon::convert_to_int(const std::string& in_string)
{
	istringstream ss(in_string);
	int value;
169
	if (!(ss >> value)) throw SMETException("Value \"" + in_string + "\" cannot be converted to int", SMET_AT);
170
171
172
173

	return value;
}

174
175
176
177
178
179
180
void SMETCommon::trim(std::string& str)
{
	const std::string whitespaces(" \t\f\v\n\r");
	const size_t startpos = str.find_first_not_of(whitespaces); // Find the first character position after excluding leading blank spaces
	const size_t endpos = str.find_last_not_of(whitespaces); // Find the first character position from reverse af

	// if all spaces or empty return an empty string
181
	if (( std::string::npos == startpos ) || ( std::string::npos == endpos)) {
182
		str.clear();
183
	} else {
184
185
		str.erase(endpos+1); //right trim
		str.erase(0, startpos); //left trim
186
187
188
189
	}
}

bool SMETCommon::readKeyValuePair(const std::string& in_line, const std::string& delimiter,
190
                                  std::map<std::string,std::string>& out_map)
191
192
193
194
195
196
197
198
199
200
201
{
	//size_t pos = in_line.find(delimiter); //first occurence of '='

	size_t pos = std::string::npos;
	if ((delimiter==" ") || (delimiter=="\t")) {
		pos = in_line.find_first_of(" \t", 0);
	} else {
		pos = in_line.find(delimiter); //first occurence of '='
	}


202
	if (pos != std::string::npos) { //ignore in_lines that are empty or without '='
203
204
205
206
207
208
		std::string key = in_line.substr(0, pos);
		std::string value = in_line.substr(pos + 1);

		SMETCommon::trim(key);
		SMETCommon::trim(value);

209
		if (key.empty() || value.empty()) {
210
211
212
213
214
215
216
217
218
219
220
221
222
			return false;
		}

		out_map[key] = value;
	} else {
		return false;
	}

	return true;
}

void SMETCommon::stripComments(std::string& str)
{
223
	const size_t found = str.find_first_of("#;");
224
225
226
227
228
229
230
	if (found != std::string::npos){
		str.erase(found); //rest of line disregarded
	}
}

void SMETCommon::toUpper(std::string& str)
{
231
	std::transform(str.begin(), str.end(),str.begin(), ::toupper);
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
}

char SMETCommon::getEoln(std::istream& fin)
{
	std::streambuf* pbuf;
	char tmp = '0';
	int chars = 0;

	const std::streampos position = fin.tellg();

	do {
		fin.get(tmp);
		chars++;

		if ((tmp == '\r') || (tmp == '\n')) {
			char peekc = tmp;
			while ((!fin.eof() && ((peekc=='\r') || (peekc=='\n')))) {
				tmp = peekc;
				fin.get(peekc);
				chars++;
			}
			pbuf = fin.rdbuf();
			pbuf->pubseekpos(position); //rewind
			fin.clear(); //reset eof flag, etc
			return tmp;
		}
	} while ((chars < 3000) && (!fin.eof()));

	pbuf = fin.rdbuf();
	pbuf->pubseekpos(position); //rewind
	fin.clear(); //reset eof flag, etc

	return '\n';
}

bool SMETCommon::is_decimal(const std::string& value)
{
	istringstream ss(value);
	double doublevalue;
	if (!(ss >> doublevalue)) return false;

	return true;
}

size_t SMETCommon::readLineToVec(const std::string& line_in, std::vector<std::string>& vec_string)
{
	vec_string.clear();
	std::istringstream iss(line_in); //construct inputstream with the string line as input

	std::string tmp_string;
	while (!iss.eof()) {
		iss >> std::skipws >> tmp_string;

285
		if (!tmp_string.empty()) {
286
			vec_string.push_back( tmp_string );
287
		}
288
		tmp_string.clear();
289
290
291
292
293
	}

	return vec_string.size();
}

294
295
296

////////////////////////////////////////////////////////////
//// SMETWriter class
297
SMETWriter::SMETWriter(const std::string& in_filename, const SMETType& in_type)
298
           : other_header_keys(), ascii_precision(), ascii_width(), header(), mandatory_header_keys(),
299
             filename(in_filename), nodata_string(), smet_type(in_type), nodata_value(-999.), nr_of_fields(0),
300
             julian_field(0), timestamp_field(0), location_wgs84(0), location_epsg(0),
301
             location_in_header(false), location_in_data_wgs84(false), location_in_data_epsg(false),
302
             timestamp_present(false), julian_present(false), file_is_binary(false), append_mode(false), append_possible(false) {}
303
304
305
306
307
308
309
310
311
312
313
314

//what the caller MUST provide: 
//	* the fields header (for checks)
//	* the ascii width and precision
//	* nodata_value provided through set_header_value() calls
//HACK: the multipliers and offsets are not handled yet...
//for now, we do the most basic append: all the data after the first insertion point is deleted
SMETWriter::SMETWriter(const std::string& in_filename, const std::string& in_fields, const double& in_nodata)
           : other_header_keys(), ascii_precision(), ascii_width(), header(), mandatory_header_keys(),
             filename(in_filename), nodata_string(), smet_type(ASCII), nodata_value(in_nodata), nr_of_fields(0),
             julian_field(0), timestamp_field(0), location_wgs84(0), location_epsg(0),
             location_in_header(false), location_in_data_wgs84(false), location_in_data_epsg(false),
315
             timestamp_present(false), julian_present(false), file_is_binary(false), append_mode(true), append_possible(false)
316
317
318
319
320
321
{
	SMETReader reader(filename);
	smet_type = (reader.isAscii)? ASCII : BINARY;
	nodata_string = reader.get_header_value("nodata");
	//nodata_value = reader.nodata_value; //we trust the value provided to the constructor
	
322
	nr_of_fields = reader.nr_of_fields; //in SMETReader, this does NOT contain the timestamp
323
324
325
326
327
328
329
330
331
332
333
334
335
336
	julian_field = reader.julian_field;
	timestamp_field = reader.timestamp_field;
	timestamp_present = reader.timestamp_present;
	julian_present = reader.julian_present;
	
	location_wgs84 = reader.location_wgs84;
	location_epsg = reader.location_epsg;
	location_in_header = reader.location_in_header(WGS84) || reader.location_in_header(EPSG);
	location_in_data_wgs84 = reader.location_in_data(WGS84);
	location_in_data_epsg = reader.location_in_data(EPSG);
	
	//check that the fields match
	std::vector<std::string> vecFields;
	SMETCommon::readLineToVec(in_fields, vecFields);
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
	if (timestamp_present) {
		if (vecFields[timestamp_field]!="timestamp") {
			std::ostringstream ss;
			ss << "Timestamp should be in field at position " << timestamp_field << "when  appending data to file '" << filename << "' but instead '" << reader.get_field_name(timestamp_field) << "' was found";
			throw SMETException(ss.str(), AT);
		}
		vecFields.erase( vecFields.begin()+timestamp_field );
	}
	if (julian_present) {
		if (vecFields[julian_field]!="julian") {
			std::ostringstream ss;
			ss << "Julian should be in field at position " << julian_field << "when  appending data to file '" << filename << "' but instead '" << reader.get_field_name(julian_field) << "' was found";
			throw SMETException(ss.str(), AT);
		}
		vecFields.erase( vecFields.begin()+julian_field );
	}
	
354
355
	if (nr_of_fields!=vecFields.size()) {
		std::ostringstream ss;
356
		ss << "Trying to append " << vecFields.size() << " fields in existing file '" << filename << "' that has " << nr_of_fields << " fields";
357
358
359
360
361
		throw SMETException(ss.str(), AT);
	}
	for (size_t ii=0; ii<nr_of_fields; ii++) {
		if (vecFields[ii] != reader.get_field_name(ii)) {
			std::ostringstream ss;
362
			ss << "Trying to append field '" << vecFields[ii] << "' at position " << ii << " in existing file '" << filename << "' when it should be '" << reader.get_field_name(ii);
363
364
365
			throw SMETException(ss.str(), AT);
		}
	}
366
367
368
369
	
	//adjust the number of fields to reflect the potential presence of timestamp and julian
	if (timestamp_present) nr_of_fields++;
	if (julian_present) nr_of_fields++;
370
}
371

372
373
374
375
376
377
378
379
380
381
382
383
384
385
const std::string SMETWriter::toString() const {
	ostringstream os;
	os << "<SMETWriter>\n";
	os << "\tfilename: " << filename << "\n";
	os << "\ttype: " << ((smet_type==ASCII)? "Ascii" : "Binary") << " append_mode: " << std::boolalpha << append_mode << " append_possible: " << append_possible << "\n";
	os << "\ttimestamp_present: " << timestamp_present << " field: " << timestamp_field << " julian_present: " << julian_present << " field: " << julian_field << "\n";
	os << "\tlocation: in header? " << location_in_header << " in data_wgs84? " << location_in_data_wgs84 << " in data_epsg? " << location_in_data_epsg << "\n";
	os << "\tlocation_wgs84: " << location_wgs84 << " location_epsg: " << location_epsg << "\n";
	os << "\tnodata: " << nodata_value << " = \"" << nodata_string << "\"\n";
	os << "\tnr_of_fields: " << nr_of_fields << "\n";
	os << "</SMETWriter>\n";
	return os.str();
}

386
387
388
389
void SMETWriter::set_header_value(const std::string& key, const double& value)
{
	//check if key is decimal, transform to string and add to header
	if (SMETCommon::all_decimal_header_values.find(key) != SMETCommon::all_decimal_header_values.end()){
390
		ostringstream ss;
391
392
393
394
395
396
397
398
399
400
401
		if ((key == "latitude") || (key == "longitude") || (key == "easting") || (key == "northing")){
			ss << fixed << setprecision(6) << value;
		} else if (key == "altitude"){
			ss << fixed << setprecision(1) << value;
		} else if ((key == "epsg") || (key == "tz")){
			ss << fixed << setprecision(0) << value;
		} else {
			ss << value; //for nodata
		}

		set_header_value(key, ss.str());
402
	} else { //It's a non-standard header value
403
		ostringstream ss;
404
405
		ss << value; //for nodata
		set_header_value(key, ss.str());
406
407
408
409
410
411
412
	}
}

void SMETWriter::set_header_value(const std::string& key, const std::string& value)
{
	//check if header key/value pair is valid
	if (valid_header_pair(key, value)){
413
		header[key] = value;
414
415
416
417

		if ((SMETCommon::all_optional_header_keys.find(key) == SMETCommon::all_optional_header_keys.end())
		    && (SMETCommon::all_mandatory_header_keys.find(key) == SMETCommon::all_mandatory_header_keys.end()))
			other_header_keys.push_back(key);
418
419
420
421
422
423
424
	} else {
		throw SMETException("Invalid, inconsistent or unknown key/value pair: " + key + " = " + value, SMET_AT);
	}
}

bool SMETWriter::valid_header_pair(const std::string& key, const std::string& value)
{
425
	bool key_ok = true;
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454

	if (SMETCommon::all_mandatory_header_keys.find(key) != SMETCommon::all_mandatory_header_keys.end()){
		mandatory_header_keys.insert(key);
		key_ok = true;
	}

	//nodata value needs extra treatment
	if (key == "nodata"){
		istringstream ss(value);
		if (!(ss >> nodata_value)) return false;
		nodata_string = value;
	}

	//Using WGS_84 coordinate system
	if (key == "latitude")  location_wgs84 |= 1;
	else if (key == "longitude") location_wgs84 |= 2;
	else if (key == "altitude")  location_wgs84 |= 4;

	//Using an EPSG coordinate system
	if (key == "easting")  location_epsg |= 1;
	else if (key == "northing") location_epsg |= 2;
	else if (key == "altitude") location_epsg |= 4;
	else if (key == "epsg")     location_epsg |= 8;

	//Now do some value checks
	if (key == "epsg"){
		istringstream ss(value);
		int intvalue;
		if (!(ss >> intvalue)) return false;
455
	}
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474

	if (SMETCommon::all_decimal_header_values.find(key) != SMETCommon::all_decimal_header_values.end()){
		//check if value is a double value
		if (!SMETCommon::is_decimal(value)) return false;
	}

	if ((location_epsg == 15) || (location_wgs84 == 7))
		location_in_header = true;

	//Rudimentary check on keys: fields, units_offset, units_multiplier
	if ((key == "fields") || (key == "units_offset") || (key == "units_multiplier"))
		key_ok = check_fields(key, value);

	return key_ok;
}

bool SMETWriter::check_fields(const std::string& key, const std::string& value)
{
	vector<string> tmp_vec;
475
	const size_t counter = SMETCommon::readLineToVec(value, tmp_vec);
476
477
478
479
480
481
482

	//Firstly: Check if number of fields is consistent
	if (nr_of_fields != 0){
		if (counter != nr_of_fields) return false;
	} else {
		nr_of_fields = counter;
	}
483

484
	if (key == "fields"){
485
		size_t count_wgs84 = 0, count_epsg = 0;
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518

		//check if location is in data and if timestamp is present
		for (size_t ii = 0; ii<tmp_vec.size(); ii++){
			if (tmp_vec[ii] == "latitude") count_wgs84++;
			else if (tmp_vec[ii] == "longitude") count_wgs84++;
			else if (tmp_vec[ii] == "easting") count_epsg++;
			else if (tmp_vec[ii] == "northing") count_epsg++;

			if (tmp_vec[ii] == "altitude") {
				count_wgs84++;
				count_epsg++;
			}

			if (tmp_vec[ii] == "timestamp"){
				if (timestamp_present) return false; //no duplicate timestamp field allowed
				timestamp_present = true;
				timestamp_field = ii;
			}

			if (tmp_vec[ii] == "julian"){
				if (julian_present) return false; //no duplicate julian field allowed
				julian_present = true;
				julian_field = ii;
			}
		}

		if (count_wgs84 == 3)
			location_in_data_wgs84 = true;

		if (count_epsg == 3)
			location_in_data_epsg = true;
	} else {
		//every value in units_offset and units_multiplier must be a decimal
519
		for (vector<string>::const_iterator it = tmp_vec.begin(); it != tmp_vec.end(); ++it)
520
521
522
523
524
525
526
527
528
529
530
531
			if (!SMETCommon::is_decimal(*it)) return false;
	}

	return true;
}

bool SMETWriter::valid_header()
{
	if (mandatory_header_keys.size() != 3)
		return false;

	if (location_in_data_epsg){ //EPSG code must be in the header anyway
532
		const map<string,string>::const_iterator it = header.find("epsg");
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
		if (it == header.end()){
			return false;
		} else {
			return true;
		}
	}

	if (location_in_header || location_in_data_wgs84)
		return true;

	return false;
}

void SMETWriter::write(const std::vector<std::string>& vec_timestamp, const std::vector<double>& data)
{
548
549
	if (!SMETCommon::validFileAndPath(filename)) throw SMETException("Invalid file name \""+filename+"\"", AT);
	errno = 0;
550
	
551
	ofstream fout;
552
553
554
555
556
557
558
559
560
	if (append_mode) {
		if (!append_possible) {
			//check where to insert the new data
			SMETReader reader(filename);
			const std::string last_timestamp = reader.getLastTimestamp();
			if (last_timestamp.empty() || last_timestamp>=vec_timestamp[0])
				reader.truncate_file(vec_timestamp[0]);
			append_possible = true;
		}
561
		fout.open(filename.c_str(), ios::binary | ofstream::app);
562
563
		if (fout.fail())
			throw SMETException("Error opening file \"" + filename + "\" for writing, possible reason: " + std::string(strerror(errno)), SMET_AT);
564
	} else { //normal mode
565
566
		if (!append_possible) { //first write -> overwrite potential previous content
			fout.open(filename.c_str(), ios::binary);
567
568
569
570
571
			if (fout.fail())
				throw SMETException("Error opening file \"" + filename + "\" for writing, possible reason: " + std::string(strerror(errno)), SMET_AT);
			write_header(fout); //Write the header info, always in ASCII format
			append_possible = true; //now all other calls to "open" will be in append mode
		} else { //after the first write: append
572
			fout.open(filename.c_str(), ios::binary | ofstream::app);
573
574
575
			if (fout.fail())
				throw SMETException("Error opening file \"" + filename + "\" for writing, possible reason: " + std::string(strerror(errno)), SMET_AT);
		}
576
	}
577
	
578
	if (vec_timestamp.empty() || data.empty() || nr_of_fields == 0) {//the header has been written, nothing to add
579
		fout.close();
580
581
582
		return;
	}

583
584
	if (!timestamp_present) {
		fout.close();
585
		throw SMETException("No timestamp present when writing file \""+filename+"\", use write(const vector<double>& data)", SMET_AT);
586
	}
587
588

	const size_t nr_of_data_fields = nr_of_fields - 1;
589
	if (nr_of_fields<=1) { //avoid division by zero in the next block
590
		cerr << "[W] Attempting to write a dataset that contains no fields to file \"" + filename + "\"!\n";
591
		fout.close();
592
		return;
593
	}
594

595
	const size_t nr_of_lines = data.size() / (nr_of_fields-1);
596
597
	if ((nr_of_lines != vec_timestamp.size()) || ((data.size() % (nr_of_fields-1)) != 0)) {
		fout.close();
598
		ostringstream os;
599
		os << "Inconsistency between the number of timestamp (" << vec_timestamp.size() << ")  and number of data points (" << data.size() << " for " << nr_of_fields-1 << " fields) detected for file \""+filename+"\", recheck your data";
600
		throw SMETException(os.str(), SMET_AT);
601
	}
602

603
	std::vector<double> current_data(nr_of_fields-1);
604
605
	check_formatting();

606
607
	if (smet_type == ASCII) {
		for (size_t ii=0; ii<nr_of_lines; ii++) {
608
			const size_t offset = ii*(nr_of_fields-1);
609
			if (!data.empty())
610
				copy(data.begin()+offset, data.begin()+offset+nr_of_data_fields, current_data.begin());
611
			write_data_line_ascii(vec_timestamp[ii], current_data, fout);
612
613
		}
	} else {
614
		fout.close();
615
		throw SMETException("Cannot write binary file \""+filename+"\" with a timestamp, use julian instead", SMET_AT);
616
617
	}

618
	fout.close();
619
620
621
622
}

void SMETWriter::write(const std::vector<double>& data)
{
623
624
	if (!SMETCommon::validFileAndPath(filename)) throw SMETException("Invalid file name \""+filename+"\"", AT);
	errno = 0;
625
	std::ofstream fout;
626
	fout.open(filename.c_str(), ios::binary);
627
	if (fout.fail()) {
628
		ostringstream ss;
629
		ss << "Error opening file \"" << filename << "\" for writing, possible reason: " << strerror(errno);
630
631
		throw SMETException(ss.str(), SMET_AT);
	}
632

633
	write_header(fout); //Write the header info, always in ASCII format
634
635

	if (nr_of_fields == 0){
636
		fout.close();
637
638
639
		return;
	}

640
	const size_t nr_of_lines = data.size() / nr_of_fields;
641
642
	if ((data.size() % nr_of_fields) != 0) {
		fout.close();
643
		throw SMETException("Inconsistency between data and header fields detected in file \""+filename+"\", recheck your data", SMET_AT);
644
	}
645

646
	std::vector<double> current_data(nr_of_fields);
647
648
649
650
	check_formatting();

	if (smet_type == ASCII){
		for (size_t ii=0; ii<nr_of_lines; ii++){
651
			if (!data.empty())
652
				copy(data.begin()+ii*nr_of_fields, data.begin()+ii*nr_of_fields+nr_of_fields, current_data.begin());
653
			write_data_line_ascii("0000-01-01T00:00", current_data, fout); //dummy time
654
655
656
		}
	} else {
		for (size_t ii=0; ii<nr_of_lines; ii++){
657
			if (!data.empty())
658
				copy(data.begin()+ii*nr_of_fields, data.begin()+ii*nr_of_fields+nr_of_fields, current_data.begin());
659
			write_data_line_binary(current_data, fout);
660
		}
661

662
663
664
		file_is_binary = false;
	}

665
	fout.close();
666
667
}

668
669
670
671
672
673
674
void SMETWriter::print_if_exists(const std::string& header_field, std::ofstream& fout) const
{
	const std::map<string,string>::const_iterator it = header.find(header_field);
	if (it != header.end())
		fout << std::left << std::setw(16) << header_field << " = " << it->second << "\n";
}

675
void SMETWriter::write_header(std::ofstream& fout)
676
{
677
678
	if (!valid_header()) {
		fout.close();
679
		throw SMETException("The header data you supplied is not valid, file \""+filename+"\" cannot be written", SMET_AT);
680
	}
681

682
683
684
685
	//write signature
	fout << "SMET " << SMETCommon::smet_version << " ";
	if (smet_type == ASCII) fout << "ASCII" << "\n";
	else fout << "BINARY" << "\n";
686

687
	fout << "[HEADER]" << "\n";
688
689
	print_if_exists("station_id", fout);
	print_if_exists("station_name", fout);
690
691
692

	if (location_in_header){
		if (location_wgs84 == 7){
693
694
695
			print_if_exists("latitude", fout);
			print_if_exists("longitude", fout);
			print_if_exists("altitude", fout);
696
697
698
		}

		if (location_epsg == 15){
699
700
			print_if_exists("easting", fout);
			print_if_exists("northing", fout);
701
			if (location_wgs84 != 7)
702
703
				print_if_exists("altitude", fout);
			print_if_exists("epsg", fout);
704
705
706
		}
	} else {
		if (location_in_data_epsg)
707
			print_if_exists("epsg", fout);
708
709
	}

710
	print_if_exists("nodata", fout);
711

712
713
714
715
716
717
	print_if_exists("tz", fout);
	print_if_exists("creation", fout);
	print_if_exists("source", fout);
	print_if_exists("units_offset", fout);
	print_if_exists("units_multiplier", fout);
	print_if_exists("comment", fout);
718

719
	for (size_t ii=0; ii<other_header_keys.size(); ii++){
720
		fout << std::left << std::setw(16) << other_header_keys[ii] << " = " << header[other_header_keys[ii]] << "\n";
721
722
	}

723
	print_if_exists("fields", fout);
724
725
726
	fout << "[DATA]" << endl;
}

727
void SMETWriter::write_data_line_binary(const std::vector<double>& data, std::ofstream& fout)
728
729
730
731
732
{
	const char eoln = '\n';

	if (!file_is_binary){ //open it as binary file
		fout.close();
733
		errno = 0;
734
		fout.open(filename.c_str(), ios::out | ios::app | ios::binary); //reopen as binary file
735
		if (fout.fail()) {
736
			ostringstream ss;
737
738
739
			ss << "Error writing to file \"" << filename << "\", possible reason: " << strerror(errno);
			throw SMETException(ss.str(), SMET_AT);
		}
740
741
742
743
744
745

		file_is_binary = true;
	}

	for (size_t ii = 0; ii < data.size(); ii++){
		if (julian_present && (julian_field == ii)){
746
			const double julian = data[ii];
747
748
			fout.write((char*)&julian, sizeof(double)); //the julian date is written in 64bit IEEE754 precision
		} else {
749
			const float val = (float)data[ii];
750
751
752
753
754
755
756
			fout.write((char*)&val, sizeof(float)); //normal data fields are written in 32bit IEEE754 precision
		}
	}

	fout.write((char*)&eoln, sizeof(char));
}

757
void SMETWriter::write_data_line_ascii(const std::string& timestamp, const std::vector<double>& data, std::ofstream& fout)
758
759
760
761
762
{
	fout.fill(' ');
	fout << right;
	fout << fixed;

763
	if ((data.empty()) && timestamp_present) fout << timestamp;
764
765
766
767
768
769
770
771
772

	for (size_t ii = 0; ii < data.size(); ii++){
		if (ii > 0) fout << " ";
		if (timestamp_present && (timestamp_field == ii))	fout << timestamp << " ";

		fout << setw(ascii_width[ii]) << setprecision(ascii_precision[ii]);
		if (data[ii] == nodata_value) fout << nodata_string; //to have a nicer representation
		else fout << data[ii];
	}
773
	fout << "\n";
774
775
776
777
}

void SMETWriter::check_formatting()
{
778
	const size_t nr_of_data_fields = (timestamp_present)? nr_of_fields-1 : nr_of_fields;
779
780
781
782
783
784
785
786
787
788
789
790

	if ((ascii_precision.size() != nr_of_data_fields) || (ascii_width.size() != nr_of_data_fields)){
		ascii_precision.resize(nr_of_data_fields, 3);
		ascii_width.resize(nr_of_data_fields, 8);
	}

	if (julian_present){
		ascii_precision[julian_field] = 8;
		ascii_width[julian_field] = 16;
	}
}

791
void SMETWriter::set_width(const std::vector<int>& vec_width)
792
793
794
795
{
	ascii_width = vec_width;
}

796
void SMETWriter::set_precision(const std::vector<int>& vec_precision)
797
798
799
800
{
	ascii_precision = vec_precision;
}

801
802
803

////////////////////////////////////////////////////////////
//// SMETReader class
804
805
const size_t SMETReader::streampos_every_n_lines = 2000; //save streampos every 2000 lines of data

806
807
808
809
810
811
812
813
814
815
816
SMETReader::SMETReader(const std::string& in_fname)
            : data_start_fpointer(), vec_offset(), vec_multiplier(), vec_fieldnames(),
              header(), indexer(),
              filename(in_fname), timestamp_start("-4714-11-24T00:00"),
              timestamp_end("9999-12-31T00:00"), nodata_value(-999.),
              julian_start(0.), julian_end(5373483.5),
              nr_of_fields(0), timestamp_field(0), julian_field(0),
              location_wgs84(0), location_epsg(0), location_data_wgs84(0), location_data_epsg(0),
              eoln('\n'),
              timestamp_present(false), julian_present(false), isAscii(true), mksa(true),
              timestamp_interval(false), julian_interval(false)
817
818
{
	std::ifstream fin; //Input file streams
819
	if (!SMETCommon::fileExists(filename)) throw SMETException("File '"+filename+"' does not exists", AT); //prevent invalid filenames
820
	errno = 0;
821
	fin.open (filename.c_str(), ios::in|ios::binary); //ascii does end of line translation, which messes up the pointer code
822
	if (fin.fail()) {
823
		ostringstream ss;
824
		ss << "Error opening file \"" << filename << "\" for reading, possible reason: " << strerror(errno);
825
826
827
		ss << " Please check file existence and permissions!";
		throw SMETException(ss.str(), SMET_AT);
	}
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853

	try {
		eoln = SMETCommon::getEoln(fin); //get the end of line character for the file
		read_header(fin);
		process_header();
	} catch(...){
		cleanup(fin); //closes file
		throw;
	}
	cleanup(fin); //closes file
}

void SMETReader::cleanup(std::ifstream& fin) throw()
{
	if (fin.is_open()) //close fin if open
		fin.close();
}

void SMETReader::convert_to_MKSA(const bool& in_mksa)
{
	mksa = in_mksa;
}

std::string SMETReader::get_field_name(const size_t& nr_of_field)
{
	if (nr_of_field < nr_of_fields){
854
		return vec_fieldnames[nr_of_field];
855
	} else {
856
		ostringstream ss;
857
858
859
		ss << "Trying to access field #" << nr_of_field << " (starting from 0) of " << nr_of_fields << " fields in file \"" << filename << "\". ";
		ss << "This is out of bounds!";
		throw SMETException(ss.str(), SMET_AT);
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
	}
}

size_t SMETReader::get_nr_of_fields() const
{
	return nr_of_fields;
}

void SMETReader::get_units_conversion(std::vector<double>& offset, std::vector<double>& multiplier) const
{
	multiplier = vec_multiplier;
	offset = vec_offset;
}

bool SMETReader::location_in_header(const LocationType& type) const
{
	if ((location_epsg == 15) && (type == EPSG)){
		return true;
	} else if ((location_wgs84 == 7) && (type == WGS84)){
		return true;
	}

	return false;
}

bool SMETReader::location_in_data(const LocationType& type) const
{
	if ((location_epsg == 8) && (location_data_epsg == 7) && (type == EPSG)){
		return true;
	} else if ((location_data_wgs84 == 7) && (type == WGS84)){
		return true;
	}

	return false;
}

void SMETReader::process_header()
{
	vector<string> tmp_vec;
	set<string> obligatory_keys;
900
	for (map<string,string>::iterator it = header.begin(); it != header.end(); ++it){
901
902
		if (SMETCommon::all_mandatory_header_keys.find(it->first) != SMETCommon::all_mandatory_header_keys.end())
			obligatory_keys.insert(it->first);
903

904
905
		if (it->first == "fields"){
			SMETCommon::readLineToVec(it->second, tmp_vec);
906
			string newfields;
907
			if (!tmp_vec.empty()){
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
				for (size_t ii=0; ii<tmp_vec.size(); ii++){
					if (tmp_vec[ii] == "timestamp"){
						timestamp_present = true;
						timestamp_field = ii;
					} else {
						if (nr_of_fields > 0) newfields += " ";
						vec_fieldnames.push_back(tmp_vec[ii]);
						newfields += tmp_vec[ii];
						nr_of_fields++;
					}

					if (tmp_vec[ii] == "julian"){
						julian_present = true;
						julian_field = ii;
					}
923

924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
					//Using WGS_84 coordinate system
					if (tmp_vec[ii] == "latitude")  location_data_wgs84 |= 1;
					else if (tmp_vec[ii] == "longitude") location_data_wgs84 |= 2;
					else if (tmp_vec[ii] == "altitude")  location_data_wgs84 |= 4;

					//Using an EPSG coordinate system
					if (tmp_vec[ii] == "easting")  location_data_epsg |= 1;
					else if (tmp_vec[ii] == "northing") location_data_epsg |= 2;
					else if (tmp_vec[ii] == "altitude") location_data_epsg |= 4;
				}
				it->second = newfields;
			}
		}

		if (it->first == "nodata")
			nodata_value = SMETCommon::convert_to_double(it->second);

		//Using WGS_84 coordinate system
		if (it->first == "latitude")  location_wgs84 |= 1;
		else if (it->first == "longitude") location_wgs84 |= 2;
		else if (it->first == "altitude")  location_wgs84 |= 4;

		//Using an EPSG coordinate system
		if (it->first == "easting")  location_epsg |= 1;
		else if (it->first == "northing") location_epsg |= 2;
		else if (it->first == "altitude") location_epsg |= 4;
		else if (it->first == "epsg")     location_epsg |= 8;

952
953
954
		//Now do a value check on EPSG
		if (it->first == "epsg")
			SMETCommon::convert_to_int(it->second);
955
956
957
958
	}

	if (get_header_value("units_offset") != ""){
		vector<string> tmp_offset;
959
		string offsetstring;
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
		SMETCommon::readLineToVec(get_header_value("units_offset"), tmp_offset);

		for (size_t ii=0; ii<tmp_offset.size(); ii++){
			if (!timestamp_present || (ii != timestamp_field)){
				if (ii>0) offsetstring += " ";
				offsetstring += tmp_offset[ii];
				vec_offset.push_back(SMETCommon::convert_to_double(tmp_offset[ii]));
			}
		}
		header["units_offset"] = offsetstring;
	} else {
		vec_offset.resize(nr_of_fields, 0.0);
	}

	if (get_header_value("units_multiplier") != ""){
		vector<string> tmp_multiplier;
976
		string multiplierstring;
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
		SMETCommon::readLineToVec(get_header_value("units_multiplier"), tmp_multiplier);

		for (size_t ii=0; ii<tmp_multiplier.size(); ii++){
			if (!timestamp_present || (ii != timestamp_field)){
				if (ii>0) multiplierstring += " ";
				multiplierstring += tmp_multiplier[ii];
				vec_multiplier.push_back(SMETCommon::convert_to_double(tmp_multiplier[ii]));
			}
		}
		header["units_multiplier"] = multiplierstring;
	} else {
		vec_multiplier.resize(nr_of_fields, 1.0);
	}

	if (obligatory_keys.size() != SMETCommon::all_mandatory_header_keys.size())
992
		throw SMETException("\""+filename+"\" is not a valid SMET file, mandatory information in header is missing", SMET_AT);
993

994
995
996
997
998
999
1000
	const bool location_meta_present = (location_wgs84 == 7) || (location_epsg == 15) || (location_data_wgs84 == 7)
	    || ((location_epsg == 8) && (location_data_epsg == 7));
	if (!location_meta_present) {
		ostringstream ss;
		ss << "Mandatory location data is missing in file '" << filename << "'";
		std::string missing;
		if ((location_epsg>0 && !(location_epsg & 4)) || (location_wgs84>0 && !(location_wgs84 & 4))) //altitude meta is missing
For faster browsing, not all history is shown. View entire blame