WSL/SLF GitLab Repository

libsmet.cc 35 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
/***********************************************************************************/
/*  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/>.
*/
#include <meteoio/libsmet.h>
19
20
#include <errno.h>
#include <string.h>
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
89

using namespace std;

namespace smet {

const std::string SMETCommon::smet_version = "1.1";
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>();

SMETException::SMETException(const std::string& message, const std::string& position)
{
	if (position=="") {
		msg = "At unknown position: " + message;
	} else {
		msg = position + ": " + message;
	}
}

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;
}

double SMETCommon::convert_to_double(const std::string& in_string)
{
	istringstream ss(in_string);
	double value;
	if (!(ss >> value)) throw SMETException("Value '" + in_string + "' cannot be converted to double", SMET_AT);

	return value;
}

90
91
92
93
94
95
96
97
98
int SMETCommon::convert_to_int(const std::string& in_string)
{
	istringstream ss(in_string);
	int value;
	if (!(ss >> value)) throw SMETException("Value '" + in_string + "' cannot be converted to int", SMET_AT);

	return value;
}

99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
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
	if(( std::string::npos == startpos ) || ( std::string::npos == endpos)) {
		str = "";
	} else {
		str = str.substr( startpos, endpos-startpos+1 );
	}
}

bool SMETCommon::readKeyValuePair(const std::string& in_line, const std::string& delimiter,
114
                                  std::map<std::string,std::string>& out_map)
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
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
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
{
	//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 '='
	}


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

		SMETCommon::trim(key);
		SMETCommon::trim(value);
		//cerr << "key:" << key << " val:" << value << endl;

		if ((key == "") || (value=="")) {
			return false;
		}

		out_map[key] = value;
	} else {
		return false;
		//cerr << "line:" << in_line << "delimiter" << endl;
	}

	return true;
}

void SMETCommon::stripComments(std::string& str)
{
	size_t found = str.find_first_of("#;");
	if (found != std::string::npos){
		str.erase(found); //rest of line disregarded
	}
}

void SMETCommon::toUpper(std::string& str)
{
	for(size_t t=0; t<str.length(); t++) {
		str[t] = (char)toupper(str[t]);
	}
}

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;
			//cout << (int)tmp << endl;
			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;

		if (tmp_string != "") {
			vec_string.push_back(tmp_string);
		}
		tmp_string="";
	}

	return vec_string.size();
}

223
SMETWriter::SMETWriter(const std::string& in_filename, const SMETType& in_type, const bool& in_gzip)
224
225
226
227
228
           : filename(in_filename), smet_type(in_type), gzip(in_gzip), nr_of_fields(0),
             julian_field(0), timestamp_field(0), nodata_value(-999.), nodata_string(""),
             location_in_header(false), location_in_data_wgs84(false), location_in_data_epsg(false),
             timestamp_present(false), julian_present(false), file_is_binary(false),
             location_wgs84(0), location_epsg(0)
229
230
231
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
{

}

SMETWriter::~SMETWriter()
{
	cleanup();
}

void SMETWriter::cleanup() throw()
{
	//clear ios flags
	fout << resetiosflags(ios_base::fixed | ios_base::left);

	if (fout.is_open()) //close fout if open
		fout.close();
}

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()){
		stringstream ss;
		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());
	} else {
264
265
266
267
		//It's a non-standard header value
		stringstream ss;
		ss << value; //for nodata
		set_header_value(key, ss.str());
268
269
270
271
272
273
274
	}
}

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)){
275
		header[key] = value;
276
277
278
279

		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);
280
281
282
283
284
285
286
	} 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)
{
287
	bool key_ok = true;
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

	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;
317
	}
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336

	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;
337

338
339
340
341
342
343
344
345
	size_t counter = SMETCommon::readLineToVec(value, tmp_vec);

	//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;
	}
346

347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
	size_t count_wgs84 = 0, count_epsg = 0;
	if (key == "fields"){
		//set<string> fieldnames; //this will help us locate duplicate fields

		//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
		vector<string>::iterator it;
		for (it = tmp_vec.begin(); it != tmp_vec.end(); it++)
			if (!SMETCommon::is_decimal(*it)) return false;
	}

	return true;
}

void SMETWriter::write_signature()
{
	fout << "SMET " << SMETCommon::smet_version << " ";
	if (smet_type == ASCII)
395
		fout << "ASCII" << "\n";
396
	else
397
		fout << "BINARY" << "\n";
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
}

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
		map<string,string>::iterator it = header.find("epsg");
		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)
{
	fout.open(filename.c_str());
423
424
425
426
427
	if (fout.fail()) {
		stringstream ss;
		ss << "Error openning file \"" << filename << "\" for writing, possible reason: " << strerror(errno);
		throw SMETException(ss.str(), SMET_AT);
	}
428
429
430
431
432
433
434
435

	write_header(); //Write the header info, always in ASCII format

	if (nr_of_fields == 0){
		cleanup();
		return;
	}

436
	if (!timestamp_present)
437
		throw SMETException("No timestamp present when writing file \""+filename+"\", use write(const vector<double>& data)", SMET_AT);
438
439
440
441
442

	const size_t nr_of_data_fields = nr_of_fields - 1;

	size_t nr_of_lines = data.size() / (nr_of_fields-1);
	if ((nr_of_lines != vec_timestamp.size()) || ((data.size() % (nr_of_fields-1)) != 0))
443
		throw SMETException("Inconsistency between vec_timestamp and data detected for file \""+filename+"\", recheck your data", SMET_AT);
444
445

	std::vector<double> current_data;
446
447
448
449
	if(nr_of_fields<1) {
		throw SMETException("Attempting to write a dataset that contains no fields to file \"" + filename + "\"!", SMET_AT);
	}
	current_data.resize(nr_of_fields-1);
450
451
452
453
454
455
456
	check_formatting();

	if (smet_type == ASCII){
		for (size_t ii=0; ii<nr_of_lines; ii++){
			const size_t offset = ii*(nr_of_fields-1);
			if (data.size() != 0)
				copy(data.begin()+offset, data.begin()+offset+nr_of_data_fields, current_data.begin());
457
			write_data_line_ascii(vec_timestamp[ii], current_data);
458
459
		}
	} else {
460
		throw SMETException("Cannot write binary file \""+filename+"\" with a timestamp, use julian instead", SMET_AT);
461
462
463
464
465
466
467
468
	}

	cleanup();
}

void SMETWriter::write(const std::vector<double>& data)
{
	fout.open(filename.c_str());
469
470
471
472
473
	if (fout.fail()) {
		stringstream ss;
		ss << "Error openning file \"" << filename << "\" for writing, possible reason: " << strerror(errno);
		throw SMETException(ss.str(), SMET_AT);
	}
474
475
476
477
478
479
480
481
482
483

	write_header(); //Write the header info, always in ASCII format

	if (nr_of_fields == 0){
		cleanup();
		return;
	}

	size_t nr_of_lines = data.size() / nr_of_fields;
	if ((data.size() % nr_of_fields) != 0)
484
		throw SMETException("Inconsistency between data and header fields detected in file \""+filename+"\", recheck your data", SMET_AT);
485
486

	std::vector<double> current_data;
487
	current_data.resize(nr_of_fields);
488
489
490
491
492
493
494
495
496
497
498
499
500
501
	check_formatting();

	if (smet_type == ASCII){
		for (size_t ii=0; ii<nr_of_lines; ii++){
			if (data.size() != 0)
				copy(data.begin()+ii*nr_of_fields, data.begin()+ii*nr_of_fields+nr_of_fields, current_data.begin());
			write_data_line_ascii("0000-01-01T00:00", current_data); //dummy time
		}
	} else {
		for (size_t ii=0; ii<nr_of_lines; ii++){
			if (data.size() != 0)
				copy(data.begin()+ii*nr_of_fields, data.begin()+ii*nr_of_fields+nr_of_fields, current_data.begin());
			write_data_line_binary(current_data);
		}
502

503
504
505
506
507
508
509
510
511
512
513
		file_is_binary = false;
	}

	cleanup();
}

void SMETWriter::write_header()
{
	map<string,string>::iterator it;

	if (!valid_header())
514
		throw SMETException("The header data you supplied is not valid, file \""+filename+"\" cannot be written", SMET_AT);
515
516
517

	write_signature();

518
519
	fout << "[HEADER]" << "\n";
	fout << "station_id       = " << header["station_id"] << "\n";
520

521
	it = header.find("station_name");
522
	if (it != header.end())
523
		fout << "station_name     = " << it->second << "\n";
524
525
526

	if (location_in_header){
		if (location_wgs84 == 7){
527
528
529
			fout << "latitude         = " << header["latitude"]  << "\n";
			fout << "longitude        = " << header["longitude"] << "\n";
			fout << "altitude         = " << header["altitude"]  << "\n";
530
531
532
		}

		if (location_epsg == 15){
533
534
			fout << "easting          = " << header["easting"]   << "\n";
			fout << "northing         = " << header["northing"]  << "\n";
535
			if (location_wgs84 != 7)
536
537
				fout << "altitude         = " << header["altitude"]  << "\n";
			fout << "epsg             = " << header["epsg"]  << "\n";
538
539
540
		}
	} else {
		if (location_in_data_epsg)
541
			fout << "epsg             = " << header["epsg"]      << "\n";
542
543
	}

544
	fout << "nodata           = " << header["nodata"] << "\n";
545
546
547

	//Optional header keys:
	it = header.find("tz");
548
	if (it != header.end())
549
		fout << "tz               = " << it->second << "\n";
550
551

	it = header.find("creation");
552
	if (it != header.end())
553
		fout << "creation         = " << it->second << "\n";
554
555

	it = header.find("source");
556
	if (it != header.end())
557
		fout << "source           = " << it->second << "\n";
558
559

	it = header.find("units_offset");
560
	if (it != header.end())
561
		fout << "units_offset     = " << it->second << "\n";
562
563

	it = header.find("units_multiplier");
564
	if (it != header.end())
565
		fout << "units_multiplier = " << it->second << "\n";
566
567

	it = header.find("comment");
568
	if (it != header.end())
569
		fout << "comment          = " << it->second << "\n";
570

571
	for (size_t ii=0; ii<other_header_keys.size(); ii++){
572
		fout << other_header_keys[ii] << " = " << header[other_header_keys[ii]] << "\n";
573
574
	}

575
	fout << "fields           = " << header["fields"] << "\n";
576
577
578
579
580
581
582
583
584
585
	fout << "[DATA]" << endl;
}

void SMETWriter::write_data_line_binary(const std::vector<double>& data)
{
	const char eoln = '\n';

	if (!file_is_binary){ //open it as binary file
		fout.close();
		fout.open(filename.c_str(), ios::out | ios::app | ios::binary); //reopen as binary file
586
587
588
589
590
		if (fout.fail()) {
			stringstream ss;
			ss << "Error writing to file \"" << filename << "\", possible reason: " << strerror(errno);
			throw SMETException(ss.str(), SMET_AT);
		}
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624

		file_is_binary = true;
	}

	float val = 0;
	for (size_t ii = 0; ii < data.size(); ii++){
		if (julian_present && (julian_field == ii)){
			double julian = data[ii];
			fout.write((char*)&julian, sizeof(double)); //the julian date is written in 64bit IEEE754 precision
		} else {
			val = (float)data[ii];
			fout.write((char*)&val, sizeof(float)); //normal data fields are written in 32bit IEEE754 precision
		}
	}

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

void SMETWriter::write_data_line_ascii(const std::string& timestamp, const std::vector<double>& data)
{
	fout.fill(' ');
	fout << right;
	fout << fixed;

	if ((data.size() == 0) && timestamp_present) fout << timestamp;

	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];
	}
625
	fout << "\n";
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
}

void SMETWriter::check_formatting()
{
	size_t nr_of_data_fields = nr_of_fields;
	if (timestamp_present) nr_of_data_fields--;

	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;
	}
}

644
void SMETWriter::set_width(const std::vector<int>& vec_width)
645
646
647
648
{
	ascii_width = vec_width;
}

649
void SMETWriter::set_precision(const std::vector<int>& vec_precision)
650
651
652
653
654
{
	ascii_precision = vec_precision;
}


655
SMETReader::SMETReader(const std::string& in_fname) : filename(in_fname), nr_of_fields(0), timestamp_present(false),
656
657
658
659
660
661
                                                      julian_present(false), timestamp_field(0), julian_field(0),
                                                      isAscii(true), location_wgs84(0), location_epsg(0),
                                                      location_data_wgs84(0), location_data_epsg(0), nodata_value(-999.), mksa(true),
                                                      timestamp_interval(false), julian_interval(false),
                                                      timestamp_start("-4714-11-24T00:00"),
                                                      timestamp_end("9999-12-31T00:00")
662
663
664
665
{
	std::ifstream fin; //Input file streams
	fin.clear();
	fin.open (filename.c_str(), ios::in);
666
667
668
669
670
671
	if (fin.fail()) {
		stringstream ss;
		ss << "Error openning file \"" << filename << "\" for reading, possible reason: " << strerror(errno);
		ss << " Please check file existence and permissions!";
		throw SMETException(ss.str(), SMET_AT);
	}
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705

	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
}

SMETReader::~SMETReader()
{

}

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){
		return vec_fieldnames[nr_of_fields];
	} else {
706
707
708
709
		stringstream ss;
		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);
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
	}
}

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;
	map<string,string>::iterator it;
	set<string> obligatory_keys;
	for (it = header.begin(); it != header.end(); it++){
		if (SMETCommon::all_mandatory_header_keys.find(it->first) != SMETCommon::all_mandatory_header_keys.end())
			obligatory_keys.insert(it->first);
754

755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
		if (it->first == "fields"){
			SMETCommon::readLineToVec(it->second, tmp_vec);
			string newfields = "";
			if (tmp_vec.size() > 0){
				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;
					}
774

775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
					//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;

803
804
805
		//Now do a value check on EPSG
		if (it->first == "epsg")
			SMETCommon::convert_to_int(it->second);
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
	}

	if (get_header_value("units_offset") != ""){
		vector<string> tmp_offset;
		string offsetstring = "";
		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;
		string multiplierstring = "";
		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())
843
		throw SMETException("'"+filename+"' is not a valid SMET file, mandatory information in header is missing", SMET_AT);
844

845
	if ((location_wgs84 == 7) || (location_epsg == 15) || (location_data_wgs84 == 7)
846
847
848
	    || ((location_epsg == 8) && (location_data_epsg == 7))){
		//location info present somewhere
	} else {
849
		throw SMETException("'"+filename+"' is not a valid SMET file, mandatory location info is missing (header and data)", SMET_AT);
850
	}
851
852
853
854
855
856
857
858
859
860

	const size_t nr_offset = vec_offset.size();
	const size_t nr_multiplier = vec_multiplier.size();
	if ((nr_offset>0 && nr_offset!=nr_of_fields) || (nr_multiplier>0 && nr_multiplier!=nr_of_fields)) {
		std::stringstream ss;
		ss << "File \'" << filename << "\' has " << nr_of_fields << " data fields, but specifies ";
		ss << nr_offset << " offsets and " << nr_multiplier << " multipliers. ";
		ss << "The number of offsets and multipliers MUST fit the number of fields, including the (optional) timestamp column.";
		throw SMETException(ss.str(), SMET_AT);
	}
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
}

void SMETReader::read_header(std::ifstream& fin)
{
	//1. Read signature
	std::string line = "";
	vector<string> tmpvec;
	getline(fin, line, eoln); //read complete signature line
	SMETCommon::stripComments(line);
	SMETCommon::readLineToVec(line, tmpvec);
	checkSignature(tmpvec, isAscii);

	//2. Read Header
	while (!fin.eof() && (fin.peek() != '[')) //skip lines until '[' is found
		getline(fin, line, eoln);

	getline(fin, line, eoln);
	SMETCommon::stripComments(line);
	SMETCommon::trim(line);
	SMETCommon::toUpper(line);

	if (line != "[HEADER]")
		throw;// InvalidFormatException("Section " + line + " in "+ filename + " invalid", AT);

	while (!fin.eof() && (fin.peek() != '[')){ //Read until next section
		getline(fin, line, eoln);

		SMETCommon::stripComments(line);
		SMETCommon::trim(line);

		if (line != "") {
			if (!SMETCommon::readKeyValuePair(line, "=", header))
893
				throw SMETException("Invalid key value pair in file '"+filename+"', in [Header] section: " + line, SMET_AT);
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
		}

	}

	//Read [DATA] section tag
	getline(fin, line, eoln);
	SMETCommon::stripComments(line);
	SMETCommon::trim(line);
	SMETCommon::toUpper(line);

	if (line != "[DATA]")
		throw SMETException("Section " + line + " in "+ filename + " invalid, expected [DATA]", SMET_AT);

	data_start_fpointer = fin.tellg();
}

void SMETReader::checkSignature(const std::vector<std::string>& vecSignature, bool& isAscii)
{
	if ((vecSignature.size() != 3) || (vecSignature[0] != "SMET"))
913
		throw SMETException("The signature of file " + filename + " is invalid. Is it really a SMET file?", SMET_AT);
914
915

	std::string version = vecSignature[1];
916
	if ((version != "0.9") && (version != "0.95") && (version != "0.99")
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
	    && (version != "1.0") && (version != SMETCommon::smet_version))
		throw SMETException("Unsupported file format version for file " + filename, SMET_AT);

	if(version=="0.9" || version=="0.95" || version=="0.99" || version=="1.0") {
		cout << "[W] SMET specification 1.1 changes the priorities of units_multiplier and units_offset. "
			<< "Please check/update your files and bring them to 1.1!!" << endl;
	}

	const std::string type = vecSignature[2];
	if (type == "ASCII")
		isAscii = true;
	else if (type == "BINARY")
		isAscii = false;
	else
		throw SMETException("The 3rd column of file " + filename + " must be either ASCII or BINARY", SMET_AT);
}

934
void SMETReader::read(const std::string& i_timestamp_start, const std::string& i_timestamp_end,
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
                      std::vector<std::string>& vec_timestamp, std::vector<double>& vec_data)
{
	if (!timestamp_present){
		read(vec_timestamp, vec_data);
	} else {
		timestamp_interval = true;
		timestamp_start = i_timestamp_start;
		timestamp_end = i_timestamp_end;

		read(vec_timestamp, vec_data);

		timestamp_interval = false;
	}
}

void SMETReader::read(const double& i_julian_start, const double& i_julian_end, std::vector<double>& vec_data)
{
	if (!julian_present){
		read(vec_data);
	} else {
		julian_interval = true;
		julian_start = i_julian_start;
		julian_end = i_julian_end;

		read(vec_data);

		julian_interval = false;
	}
}

void SMETReader::read(std::vector<std::string>& vec_timestamp, std::vector<double>& vec_data)
{
967
	if (!timestamp_present)
968
		throw SMETException("Requesting to read timestamp when there is none present in '"+filename+"'", SMET_AT);
969
970
971
972

	ifstream fin;
	fin.clear();
	fin.open (filename.c_str(), ios::in);
973
974
975
976
977
	if (fin.fail()) {
		stringstream ss;
		ss << "Error openning file \"" << filename << "\" for reading, possible reason: " << strerror(errno);
		throw SMETException(ss.str(), SMET_AT);
	}
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992

	try {
		fin.seekg(data_start_fpointer); //jump to data start position in the file
		if (timestamp_interval && timestamp_present){
			map<string, streampos>::const_iterator it = map_timestamp_streampos.find(timestamp_start);
			if ( it != map_timestamp_streampos.end())
				fin.seekg(it->second);
		} else if (julian_interval && julian_present){
			map<double, streampos>::const_iterator it = map_julian_streampos.find(julian_start);
			if ( it != map_julian_streampos.end())
				fin.seekg(it->second);
		}

		if (fin.fail() || fin.bad())
			fin.seekg(data_start_fpointer);
993

994
995
996
		if (isAscii)
			read_data_ascii(fin, vec_timestamp, vec_data);
		else
997
			throw SMETException("Binary SMET file '"+filename+"' has no field timestamp, only julian date", SMET_AT);
998
999
	} catch(...) {
		cleanup(fin);
1000
		throw;
For faster browsing, not all history is shown. View entire blame